python.js 1.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072
  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('ultralytics');
  177. this.register('__torch__');
  178. const sys = this.register('sys');
  179. sys.modules = this._modules;
  180. this.register('xgboost');
  181. this.registerType('ast.AST', class {});
  182. this.registerType('ast.mod', class extends ast.AST {});
  183. this.registerType('ast.expr', class extends ast.AST {});
  184. this.registerType('ast.unaryop', class extends ast.AST {});
  185. this.registerType('ast.binop', class extends ast.AST {});
  186. this.registerType('ast.operator', class extends ast.AST {});
  187. this.registerType('ast.boolop', class extends ast.AST {});
  188. this.registerType('ast.cmpop', class extends ast.AST {});
  189. this.registerType('ast.stmt', class extends ast.AST {});
  190. this.registerType('ast.excepthandler', class extends ast.AST {});
  191. this.registerType('ast.keyword', class extends ast.AST {
  192. constructor(arg, value) {
  193. super();
  194. this.arg = arg;
  195. this.value = value;
  196. }
  197. });
  198. this.registerType('ast.alias', class extends ast.AST {
  199. constructor(name, asname) {
  200. super();
  201. this.name = name;
  202. this.asname = asname;
  203. }
  204. });
  205. this.registerType('ast.Name', class extends ast.expr {
  206. constructor(id, ctx) {
  207. super();
  208. this.id = id;
  209. if (ctx) {
  210. this.ctx = ctx;
  211. }
  212. }
  213. });
  214. this.registerType('ast.Constant', class extends ast.expr {
  215. constructor(value, type) {
  216. super();
  217. this.value = value;
  218. this.type = type || null;
  219. }
  220. });
  221. this.registerType('ast.Ellipsis', class extends ast.Constant {
  222. constructor() {
  223. super(builtins.ellipsis);
  224. }
  225. });
  226. this.registerType('ast.Starred', class extends ast.expr {
  227. constructor(value, ctx) {
  228. super();
  229. this.value = value;
  230. if (ctx) {
  231. this.ctx = ctx;
  232. }
  233. }
  234. });
  235. this.registerType('ast.List', class extends ast.expr {
  236. constructor(elts, ctx) {
  237. super();
  238. this.elts = elts;
  239. if (ctx) {
  240. this.ctx = ctx;
  241. }
  242. }
  243. });
  244. this.registerType('ast.Set', class extends ast.expr {
  245. constructor(elts) {
  246. super();
  247. this.elts = elts;
  248. }
  249. });
  250. this.registerType('ast.Tuple', class extends ast.expr {
  251. constructor(elts, ctx) {
  252. super();
  253. this.elts = elts;
  254. if (ctx) {
  255. this.ctx = ctx;
  256. }
  257. }
  258. });
  259. this.registerType('ast.Dict', class extends ast.expr {
  260. constructor(keys, values) {
  261. super();
  262. this.keys = keys;
  263. this.values = values;
  264. }
  265. });
  266. this.registerType('ast.ListComp', class extends ast.expr {
  267. constructor(elt, generators) {
  268. super();
  269. this.elt = elt;
  270. this.generators = generators;
  271. }
  272. });
  273. this.registerType('ast.SetComp', class extends ast.expr {
  274. constructor(elt, generators) {
  275. super();
  276. this.elt = elt;
  277. this.generators = generators;
  278. }
  279. });
  280. this.registerType('ast.GeneratorExp', class extends ast.expr {
  281. constructor(elt, generators) {
  282. super();
  283. this.elt = elt;
  284. this.generators = generators;
  285. }
  286. });
  287. this.registerType('ast.DictComp', class extends ast.expr {
  288. constructor(key, value, generators) {
  289. super();
  290. this.key = key;
  291. this.value = value;
  292. this.generators = generators;
  293. }
  294. });
  295. this.registerType('ast.comprehension', class extends ast.AST {
  296. constructor(target, iter, ifs, is_async) {
  297. super();
  298. this.target = target;
  299. this.iter = iter;
  300. this.ifs = ifs;
  301. this.is_async = is_async;
  302. }
  303. });
  304. this.registerType('ast.Subscript', class extends ast.expr {
  305. constructor(value, slice, ctx) {
  306. super();
  307. this.value = value;
  308. this.slice = slice;
  309. if (ctx) {
  310. this.ctx = ctx;
  311. }
  312. }
  313. });
  314. this.registerType('ast.Slice', class extends ast.expr {
  315. constructor(lower, upper, step) {
  316. super();
  317. this.lower = lower;
  318. this.upper = upper;
  319. this.step = step;
  320. }
  321. });
  322. this.registerType('ast.UnaryOp', class extends ast.expr {
  323. constructor(op, operand) {
  324. super();
  325. this.op = op;
  326. this.operand = operand;
  327. }
  328. });
  329. this.registerType('ast.UAdd', class extends ast.unaryop {});
  330. this.registerType('ast.USub', class extends ast.unaryop {});
  331. this.registerType('ast.Not', class extends ast.unaryop {});
  332. this.registerType('ast.Invert', class extends ast.unaryop {});
  333. this.registerType('ast.BinOp', class extends ast.expr {
  334. constructor(left, op, right) {
  335. super();
  336. this.left = left;
  337. this.op = op;
  338. this.right = right;
  339. }
  340. });
  341. this.registerType('ast.Add', class extends ast.operator {});
  342. this.registerType('ast.Sub', class extends ast.operator {});
  343. this.registerType('ast.Mult', class extends ast.operator {});
  344. this.registerType('ast.Div', class extends ast.operator {});
  345. this.registerType('ast.FloorDiv', class extends ast.operator {});
  346. this.registerType('ast.Mod', class extends ast.operator {});
  347. this.registerType('ast.Pow', class extends ast.operator {});
  348. this.registerType('ast.LShift', class extends ast.operator {});
  349. this.registerType('ast.RShift', class extends ast.operator {});
  350. this.registerType('ast.BitOr', class extends ast.operator {});
  351. this.registerType('ast.BitXor', class extends ast.operator {});
  352. this.registerType('ast.BitAnd', class extends ast.operator {});
  353. this.registerType('ast.MatMult', class extends ast.operator {});
  354. this.registerType('ast.BoolOp', class extends ast.expr {
  355. constructor(op, values) {
  356. super();
  357. this.op = op;
  358. this.values = values;
  359. }
  360. });
  361. this.registerType('ast.And', class extends ast.boolop {});
  362. this.registerType('ast.Or', class extends ast.boolop {});
  363. this.registerType('ast.Compare', class extends ast.expr {
  364. constructor(left, ops, comparators) {
  365. super();
  366. this.left = left;
  367. this.ops = ops;
  368. this.comparators = comparators;
  369. }
  370. });
  371. this.registerType('ast.Eq', class extends ast.cmpop {});
  372. this.registerType('ast.NotEq', class extends ast.cmpop {});
  373. this.registerType('ast.Lt', class extends ast.cmpop {});
  374. this.registerType('ast.LtE', class extends ast.cmpop {});
  375. this.registerType('ast.Gt', class extends ast.cmpop {});
  376. this.registerType('ast.GtE', class extends ast.cmpop {});
  377. this.registerType('ast.Is', class extends ast.cmpop {});
  378. this.registerType('ast.IsNot', class extends ast.cmpop {});
  379. this.registerType('ast.In', class extends ast.cmpop {});
  380. this.registerType('ast.NotIn', class extends ast.cmpop {});
  381. this.registerType('ast.Call', class extends ast.expr {
  382. constructor(func, args, keywords) {
  383. super();
  384. this.func = func;
  385. this.args = args;
  386. this.keywords = keywords || [];
  387. }
  388. });
  389. this.registerType('ast.Attribute', class extends ast.expr {
  390. constructor(value, attr, ctx) {
  391. super();
  392. this.value = value;
  393. this.attr = attr;
  394. if (ctx) {
  395. this.ctx = ctx;
  396. }
  397. }
  398. });
  399. this.registerType('ast.Lambda', class extends ast.expr {
  400. constructor(args, body) {
  401. super();
  402. this.args = args;
  403. this.body = body;
  404. }
  405. });
  406. this.registerType('ast.IfExp', class extends ast.expr {
  407. constructor(test, body, orelse) {
  408. super();
  409. this.test = test;
  410. this.body = body;
  411. this.orelse = orelse;
  412. }
  413. });
  414. this.registerType('ast.NamedExpr', class extends ast.expr {
  415. constructor(target, value) {
  416. super();
  417. this.target = target;
  418. this.value = value;
  419. }
  420. });
  421. this.registerType('ast.Yield', class extends ast.expr {
  422. constructor(value) {
  423. super();
  424. this.value = value;
  425. }
  426. });
  427. this.registerType('ast.YieldFrom', class extends ast.expr {
  428. constructor(value) {
  429. super();
  430. this.value = value;
  431. }
  432. });
  433. this.registerType('ast.Expr', class extends ast.stmt {
  434. constructor(value) {
  435. super();
  436. this.value = value;
  437. }
  438. });
  439. this.registerType('ast.Assign', class extends ast.stmt {
  440. constructor(targets, value, ctx) {
  441. super();
  442. this.targets = targets;
  443. this.value = value;
  444. if (ctx) {
  445. this.ctx = ctx;
  446. }
  447. }
  448. });
  449. this.registerType('ast.AnnAssign', class extends ast.stmt {
  450. constructor(target, annotation, value, simple) {
  451. super();
  452. this.target = target;
  453. this.annotation = annotation;
  454. this.value = value;
  455. this.simple = simple;
  456. }
  457. });
  458. this.registerType('ast.AugAssign', class extends ast.stmt {
  459. constructor(target, op, value) {
  460. super();
  461. this.target = target;
  462. this.op = op;
  463. this.value = value;
  464. }
  465. });
  466. this.registerType('ast.If', class extends ast.stmt {
  467. constructor(test, body, orelse) {
  468. super();
  469. this.test = test;
  470. this.body = body;
  471. this.orelse = orelse;
  472. }
  473. });
  474. this.registerType('ast.For', class extends ast.stmt {
  475. constructor(target, iter, body, orelse /*, type_comment */) {
  476. super();
  477. this.target = target;
  478. this.iter = iter;
  479. this.body = body;
  480. this.orelse = orelse;
  481. }
  482. });
  483. this.registerType('ast.While', class extends ast.stmt {
  484. constructor(test, body, orelse /*, type_comment */) {
  485. super();
  486. this.test = test;
  487. this.body = body;
  488. this.orelse = orelse;
  489. }
  490. });
  491. this.registerType('ast.Del', class extends ast.stmt {
  492. constructor(targets) {
  493. super();
  494. this.targets = targets;
  495. }
  496. });
  497. this.registerType('ast.Return', class extends ast.stmt {
  498. constructor(value) {
  499. super();
  500. this.value = value;
  501. }
  502. });
  503. this.registerType('ast.Try', class extends ast.stmt {
  504. constructor(body, handlers, orelse, finalbody) {
  505. super();
  506. this.body = body;
  507. this.handlers = handlers;
  508. this.orelse = orelse;
  509. this.finalbody = finalbody;
  510. }
  511. });
  512. this.registerType('ast.ExceptHandler', class extends ast.excepthandler {
  513. constructor(type, name, body) {
  514. super();
  515. this.type_ = type;
  516. this.name = name;
  517. this.body = body;
  518. }
  519. });
  520. this.registerType('ast.ClassDef', class extends ast.stmt {
  521. constructor(name, bases, keywords, body, decorator_list, type_params) {
  522. super();
  523. this.name = name;
  524. this.bases = bases;
  525. this.keywords = keywords;
  526. this.body = body;
  527. this.decorator_list = decorator_list;
  528. this.type_params = type_params;
  529. }
  530. });
  531. this.registerType('ast.FunctionDef', class extends ast.stmt {
  532. constructor(name, args, body, decorator_list, returns, type_comment, type_params) {
  533. super();
  534. this.name = name;
  535. this.args = args;
  536. this.body = body;
  537. this.decorator_list = decorator_list;
  538. this.returns = returns;
  539. this.type_comment = type_comment;
  540. this.type_params = type_params;
  541. }
  542. });
  543. this.registerType('ast.arguments', class extends ast.AST {
  544. constructor(posonlyargs, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults) {
  545. super();
  546. this.posonlyargs = posonlyargs;
  547. this.args = args;
  548. this.vararg = vararg;
  549. this.kwonlyargs = kwonlyargs;
  550. this.kw_defaults = kw_defaults;
  551. this.kwarg = kwarg;
  552. this.defaults = defaults;
  553. }
  554. });
  555. this.registerType('ast.arg', class extends ast.AST {
  556. constructor(arg, annotation, type_comment) {
  557. super();
  558. this.arg = arg;
  559. this.annotation = annotation;
  560. this.type_comment = type_comment;
  561. }
  562. });
  563. this.registerType('ast.Import', class extends ast.stmt {
  564. constructor(names) {
  565. super();
  566. this.names = names;
  567. }
  568. });
  569. this.registerType('ast.ImportFrom', class extends ast.stmt {
  570. constructor(module, names, level) {
  571. super();
  572. this.module = module;
  573. this.names = names;
  574. this.level = level;
  575. }
  576. });
  577. this.registerType('ast.Assert', class extends ast.stmt {
  578. constructor(test, msg) {
  579. super();
  580. this.test = test;
  581. this.msg = msg;
  582. }
  583. });
  584. this.registerType('ast.Raise', class extends ast.stmt {
  585. constructor(exc, cause) {
  586. super();
  587. this.exc = exc;
  588. this.cause = cause;
  589. }
  590. });
  591. this.registerType('ast.With', class extends ast.stmt {
  592. constructor(items, body, type_comment) {
  593. super();
  594. this.items = items;
  595. this.body = body;
  596. this.type_comment = type_comment;
  597. }
  598. });
  599. this.registerType('ast.withitem', class extends ast.AST {
  600. constructor(context_expr, optional_vars) {
  601. super();
  602. this.context_expr = context_expr;
  603. this.optional_vars = optional_vars;
  604. }
  605. });
  606. this.registerType('ast.Global', class extends ast.stmt {
  607. constructor(names) {
  608. super();
  609. this.names = names;
  610. }
  611. });
  612. this.registerType('ast.Nonlocal', class extends ast.stmt {
  613. constructor(names) {
  614. super();
  615. this.names = names;
  616. }
  617. });
  618. this.registerType('ast.Continue', class extends ast.stmt {});
  619. this.registerType('ast.Break', class extends ast.stmt {});
  620. this.registerType('ast.Pass', class extends ast.stmt {});
  621. this.registerType('ast.Await', class extends ast.stmt {
  622. constructor(value) {
  623. super();
  624. this.value = value;
  625. }
  626. });
  627. this.registerType('ast.Module', class extends ast.mod {
  628. constructor(body, type_ignores) {
  629. super();
  630. this.body = body;
  631. this.type_ignores = type_ignores;
  632. }
  633. });
  634. this.registerFunction('ast.parse', (source, filename, mode, debug) => {
  635. const parser = new ast._Parser();
  636. const module = parser.parse(source, filename, debug, mode);
  637. return module;
  638. });
  639. this.registerFunction('ast._convert_literal', (node) => {
  640. if (node instanceof ast.Constant) {
  641. return node.value;
  642. }
  643. if (node instanceof ast.Dict && node.keys.length === node.values.length) {
  644. const keys = node.keys.map((k) => ast._convert_literal(k));
  645. const values = node.values.map((v) => ast._convert_literal(v));
  646. return Object.fromEntries(keys.map((k, i) => [k, values[i]]));
  647. }
  648. if (node instanceof ast.Tuple) {
  649. return new builtins.tuple(node.elts.map((e) => ast._convert_literal(e)));
  650. }
  651. if (node instanceof ast.List) {
  652. return new builtins.list(node.elts.map((e) => ast._convert_literal(e)));
  653. }
  654. throw new python.Error(`'${node.__class__.__name__}' not implemented.`);
  655. });
  656. this.registerFunction('ast.literal_eval', (node_or_string) => {
  657. if (typeof node_or_string === 'string') {
  658. node_or_string = ast.parse(node_or_string, '', 'eval').body;
  659. } else {
  660. throw new python.Error(`'ast.literal_eval' node eval not implemented.`);
  661. }
  662. return ast._convert_literal(node_or_string);
  663. });
  664. this.registerType('ast._Parser', class {
  665. constructor() {
  666. ast._Parser._precedence = ast._Parser._precedence || {
  667. 'or': 2, 'and': 3, 'not' : 4,
  668. 'in': 5, 'instanceof': 5, 'is': 5, '<': 5, '>': 5, '<=': 5, '>=': 5, '<>': 5, '==': 5, '!=': 5,
  669. '|': 6, '^' : 7, '&' : 8,
  670. '<<': 9, '>>': 9, '+': 10, '-': 10, '*': 11, '@': 11, '/': 11, '//': 11, '%': 11,
  671. // '+': 12, '-': 12,
  672. '~': 13, '**': 14
  673. };
  674. }
  675. parse(text, file, debug, mode) {
  676. this._tokenizer = new ast._Tokenizer(text, file);
  677. this._debug = debug;
  678. const position = this._position();
  679. let body = [];
  680. while (!this._tokenizer.match('eof')) {
  681. const statement = this._parseStatement();
  682. if (statement) {
  683. body.push(statement);
  684. continue;
  685. }
  686. if (this._tokenizer.accept('\n') || this._tokenizer.accept(';') || this._tokenizer.peek().type === 'eof') {
  687. continue;
  688. }
  689. if (this._tokenizer.accept('indent') && this._tokenizer.peek().type === 'eof') {
  690. continue;
  691. }
  692. throw new python.Error(`Unsupported statement ${this._location()}`);
  693. }
  694. if (mode === 'eval') {
  695. if (body.length !== 1 || body[0] instanceof ast.Expr === false) {
  696. throw new python.Error('Expected expression.');
  697. }
  698. body = body[0].value;
  699. }
  700. const module = new ast.Module(body);
  701. this._mark(module, position);
  702. return module;
  703. }
  704. _parseSuite() {
  705. const body = [];
  706. let statement = null;
  707. if (this._tokenizer.accept('\n')) {
  708. if (this._tokenizer.accept('indent')) {
  709. while (!this._tokenizer.accept('eof') && !this._tokenizer.accept('dedent')) {
  710. if (this._tokenizer.accept(';')) {
  711. continue;
  712. }
  713. statement = this._parseStatement();
  714. if (statement) {
  715. body.push(statement);
  716. continue;
  717. }
  718. if (this._tokenizer.accept('\n')) {
  719. continue;
  720. }
  721. if (this._tokenizer.match('dedent') || this._tokenizer.match('eof')) {
  722. continue;
  723. }
  724. throw new python.Error(`Empty statement ${this._location()}`);
  725. }
  726. }
  727. } else if (!this._tokenizer.accept('eof')) {
  728. while (!this._tokenizer.match('\n') && !this._tokenizer.match('eof') && !this._tokenizer.match('dedent')) {
  729. if (this._tokenizer.accept(';')) {
  730. continue;
  731. }
  732. statement = this._parseStatement();
  733. if (statement) {
  734. body.push(statement);
  735. continue;
  736. }
  737. throw new python.Error(`Empty statement ${this._location()}`);
  738. }
  739. this._tokenizer.accept('\n');
  740. }
  741. return body;
  742. }
  743. _parseStatement() {
  744. let node = null;
  745. let position = this._position();
  746. if (this._eat('id', 'break')) {
  747. const node = new ast.Break();
  748. return this._mark(node, position);
  749. }
  750. if (this._eat('id', 'continue')) {
  751. const node = new ast.Continue();
  752. return this._mark(node, position);
  753. }
  754. if (this._eat('id', 'return')) {
  755. const value = this._parseExpression(-1, [], true);
  756. const node = new ast.Return(value);
  757. return this._mark(node, position);
  758. }
  759. if (this._eat('id', 'raise')) {
  760. let exc = this._parseExpression(-1, ['from']);
  761. let cause = null;
  762. if (this._tokenizer.accept('id', 'from')) {
  763. cause = this._parseExpression();
  764. } else if (this._tokenizer.accept(',')) {
  765. exc = [exc];
  766. exc.push(this._parseExpression());
  767. if (this._tokenizer.accept(',')) {
  768. exc.push(this._parseExpression());
  769. }
  770. }
  771. node = new ast.Raise(exc, cause);
  772. return this._mark(node, position);
  773. }
  774. if (this._eat('id', 'assert')) {
  775. const test = this._parseExpression(-1, [',']);
  776. let msg = null;
  777. if (this._tokenizer.accept(',')) {
  778. msg = this._parseExpression();
  779. }
  780. node = new ast.Assert(test, msg);
  781. return this._mark(node, position);
  782. }
  783. if (this._eat('id', 'global')) {
  784. const names = [];
  785. do {
  786. const name = this._parseName(true);
  787. names.push(name.id);
  788. }
  789. while (this._tokenizer.accept(','));
  790. const node = new ast.Global(names);
  791. return this._mark(node, position);
  792. }
  793. if (this._eat('id', 'nonlocal')) {
  794. const names = [];
  795. do {
  796. const name = this._parseName(true);
  797. names.push(name.id);
  798. }
  799. while (this._tokenizer.accept(','));
  800. const node = new ast.Nonlocal(names);
  801. return this._mark(node, position);
  802. }
  803. if (this._eat('id', 'import')) {
  804. const names = [];
  805. do {
  806. const name = this._parseDottedName();
  807. let asname = null;
  808. if (this._tokenizer.accept('id', 'as')) {
  809. asname = this._parseName(true).id;
  810. }
  811. const node = new ast.alias(name, asname);
  812. names.push(node);
  813. }
  814. while (this._tokenizer.accept(','));
  815. const node = new ast.Import(names);
  816. return this._mark(node, position);
  817. }
  818. if (this._eat('id', 'from')) {
  819. let level = 0;
  820. const dots = this._tokenizer.peek();
  821. if (dots && Array.from(dots.type).every((c) => c === '.')) {
  822. this._eat(dots.type);
  823. level = Array.from(dots.type).length;
  824. }
  825. const module = this._parseDottedName();
  826. this._tokenizer.expect('id', 'import');
  827. const names = [];
  828. const close = this._tokenizer.accept('(');
  829. do {
  830. const name = this._parseName(true).id;
  831. let asname = null;
  832. if (this._tokenizer.accept('id', 'as')) {
  833. asname = this._parseName(true).id;
  834. }
  835. const node = new ast.alias(name, asname);
  836. names.push(node);
  837. }
  838. while (this._tokenizer.accept(','));
  839. if (close) {
  840. this._tokenizer.expect(')');
  841. }
  842. const node = new ast.ImportFrom(module, names, level);
  843. return this._mark(node, position);
  844. }
  845. const decorator_list = this._decorator();
  846. position = this._position();
  847. if (this._eat('id', 'class')) {
  848. const name = this._parseName(true);
  849. const bases = [];
  850. if (this._tokenizer.accept('(')) {
  851. while (!this._tokenizer.accept(')')) {
  852. if (this._tokenizer.accept('\n')) {
  853. continue;
  854. }
  855. const expression = this._parseExpression(-1, [], false);
  856. if (expression === null) {
  857. throw new python.Error(`Expected expression ${this._location()}`);
  858. }
  859. bases.push(expression);
  860. if (!this._tokenizer.accept(',')) {
  861. this._tokenizer.accept('\n');
  862. this._tokenizer.expect(')');
  863. break;
  864. }
  865. }
  866. }
  867. this._tokenizer.expect(':');
  868. const body = this._parseSuite();
  869. const node = new ast.ClassDef(name.id, bases, null, body, decorator_list, null);
  870. return this._mark(node, position);
  871. }
  872. const async = this._eat('id', 'async') !== null;
  873. if (async &&
  874. !this._tokenizer.match('id', 'def') &&
  875. !this._tokenizer.match('id', 'with') &&
  876. !this._tokenizer.match('id', 'for')) {
  877. throw new python.Error(`Expected 'def', 'with' or 'for' ${this._location()}`);
  878. }
  879. if (this._eat('id', 'def')) {
  880. const name = this._parseName(true);
  881. this._tokenizer.expect('(');
  882. const args = this._parseArguments(')');
  883. let returns = null;
  884. if (this._tokenizer.accept('->')) {
  885. returns = this._parseType();
  886. }
  887. this._tokenizer.expect(':');
  888. const body = this._parseSuite();
  889. const node = new ast.FunctionDef(name.id, args, body, decorator_list, returns, null, null);
  890. if (async) {
  891. node.async = async;
  892. }
  893. return this._mark(node, position);
  894. }
  895. if (decorator_list && decorator_list.length > 0) {
  896. throw new python.Error('Unexpected decorator.');
  897. }
  898. if (this._eat('id', 'del')) {
  899. const targets = this._parseExpression(-1, [], true);
  900. node = new ast.Del(targets);
  901. return this._mark(node, position);
  902. }
  903. if (this._eat('id', 'if')) {
  904. const test = this._parseExpression();
  905. this._tokenizer.expect(':');
  906. const body = this._parseSuite();
  907. const node = new ast.If(test, body);
  908. let current = node;
  909. this._tokenizer.accept('\n');
  910. while (this._tokenizer.accept('id', 'elif')) {
  911. const test = this._parseExpression();
  912. this._tokenizer.expect(':');
  913. const body = this._parseSuite();
  914. current.orelse = new ast.If(test, body);
  915. current = current.orelse;
  916. this._tokenizer.accept('\n');
  917. }
  918. if (this._tokenizer.accept('id', 'else')) {
  919. this._tokenizer.expect(':');
  920. current.orelse = this._parseSuite();
  921. }
  922. return this._mark(node, position);
  923. }
  924. if (this._eat('id', 'while')) {
  925. const test = this._parseExpression();
  926. this._tokenizer.expect(':');
  927. const body = this._parseSuite();
  928. let orelse = null;
  929. if (this._tokenizer.accept('id', 'else')) {
  930. this._tokenizer.expect(':');
  931. orelse = this._parseSuite();
  932. }
  933. const node = new ast.While(test, body, orelse);
  934. return this._mark(node, position);
  935. }
  936. if (this._eat('id', 'pass')) {
  937. const node = new ast.Pass();
  938. return this._mark(node, position);
  939. }
  940. if (this._eat('id', 'for')) {
  941. let target = this._parseExpression(-1, ['in']);
  942. while (this._tokenizer.accept(',')) {
  943. if (target instanceof ast.Tuple === false) {
  944. target = new ast.Tuple([target]);
  945. }
  946. if (this._tokenizer.match('id', 'in')) {
  947. target.elts.push({});
  948. break;
  949. }
  950. target.elts.push(this._parseExpression(-1, ['in']));
  951. }
  952. this._tokenizer.expect('id', 'in');
  953. let iter = this._parseExpression();
  954. while (this._tokenizer.accept(',')) {
  955. if (iter.type !== 'tuple') {
  956. iter = new ast.Tuple([iter]);
  957. }
  958. if (this._tokenizer.match(':')) {
  959. iter.elts.push({});
  960. break;
  961. }
  962. iter.elts.push(this._parseExpression(-1, ['in']));
  963. }
  964. this._tokenizer.expect(':');
  965. const body = this._parseSuite();
  966. let orelse = null;
  967. if (this._tokenizer.accept('id', 'else')) {
  968. this._tokenizer.expect(':');
  969. orelse = this._parseSuite();
  970. }
  971. const node = new ast.For(target, iter, body, orelse);
  972. return this._mark(node, position);
  973. }
  974. if (this._eat('id', 'with')) {
  975. const items = [];
  976. do {
  977. const context_expr = this._parseExpression();
  978. let optional_vars = null;
  979. if (this._tokenizer.accept('id', 'as')) {
  980. optional_vars = this._parseExpression();
  981. }
  982. const node = new ast.withitem(context_expr, optional_vars);
  983. items.push(node);
  984. }
  985. while (this._tokenizer.accept(','));
  986. this._tokenizer.expect(':');
  987. const body = this._parseSuite();
  988. const node = new ast.With(items, body, null);
  989. if (async) {
  990. node.async = async;
  991. }
  992. return this._mark(node, position);
  993. }
  994. if (this._eat('id', 'try')) {
  995. this._tokenizer.expect(':');
  996. const body = this._parseSuite();
  997. const handlers = [];
  998. let orelse = null;
  999. let finalbody = null;
  1000. while (this._tokenizer.match('id', 'except')) {
  1001. this._tokenizer.expect('id', 'except');
  1002. const type = this._parseExpression();
  1003. const name = this._tokenizer.accept('id', 'as') ? this._parseExpression() : null;
  1004. this._tokenizer.expect(':');
  1005. const body = this._parseSuite();
  1006. const except = new ast.ExceptHandler(type, name, body);
  1007. handlers.push(except);
  1008. }
  1009. if (this._tokenizer.match('id', 'else')) {
  1010. this._tokenizer.expect('id', 'else');
  1011. this._tokenizer.expect(':');
  1012. orelse = this._parseSuite();
  1013. }
  1014. if (this._tokenizer.match('id', 'finally')) {
  1015. this._tokenizer.expect('id', 'finally');
  1016. this._tokenizer.expect(':');
  1017. finalbody = this._parseSuite();
  1018. }
  1019. const node = new ast.Try(body, handlers, orelse, finalbody);
  1020. return this._mark(node, position);
  1021. }
  1022. const expr = this._parseExpression(-1, [], true);
  1023. if (expr) {
  1024. if (expr instanceof ast.Name && this._tokenizer.accept(':')) {
  1025. const position = this._position();
  1026. const annotation = this._parseExpression(-1, ['=']);
  1027. let value = null;
  1028. if (this._tokenizer.accept('=')) {
  1029. value = this._parseExpression();
  1030. }
  1031. node = new ast.AnnAssign(expr, annotation, value, expr instanceof ast.Name);
  1032. return this._mark(node, position);
  1033. }
  1034. if (expr instanceof ast.stmt) {
  1035. return expr;
  1036. }
  1037. switch (expr.__class__.__name__) {
  1038. case 'AnnAssign':
  1039. case 'Assert':
  1040. case 'Assign':
  1041. case 'Attribute':
  1042. case 'AugAssign':
  1043. case 'Await':
  1044. case 'BinOp':
  1045. case 'Call':
  1046. case 'Compare':
  1047. case 'Constant':
  1048. case 'Dict':
  1049. case 'Ellipsis':
  1050. case 'For':
  1051. case 'If':
  1052. case 'Lambda':
  1053. case 'List':
  1054. case 'Name':
  1055. case 'NamedExpr':
  1056. case 'Raise':
  1057. case 'Subscript':
  1058. case 'Tuple':
  1059. case 'Yield':
  1060. // return expr;
  1061. return new ast.Expr(expr);
  1062. default:
  1063. throw new python.Error(`Unhandled expression ${this._location()}`);
  1064. }
  1065. }
  1066. return null;
  1067. }
  1068. _parseExpression(minPrecedence, terminal, tuple) {
  1069. minPrecedence = minPrecedence || -1;
  1070. const terminalSet = new Set(terminal);
  1071. const stack = [];
  1072. for (;;) {
  1073. let position = this._position();
  1074. let node = null;
  1075. const token = this._tokenizer.peek();
  1076. if (stack.length === 1 && terminalSet.has(token.value)) {
  1077. break;
  1078. }
  1079. const precedence = ast._Parser._precedence[token.value];
  1080. if (precedence) {
  1081. if (precedence >= minPrecedence) {
  1082. this._tokenizer.read();
  1083. if (token.value === 'not' && this._tokenizer.accept('id', 'in')) {
  1084. token.value = 'not in';
  1085. } else if (token.value === 'is' && this._tokenizer.accept('id', 'not')) {
  1086. token.value = 'is not';
  1087. }
  1088. if (stack.length > 0) {
  1089. let op = null;
  1090. switch (token.value) {
  1091. case '+': op = new ast.Add(); break;
  1092. case '-': op = new ast.Sub(); break;
  1093. case '*': op = new ast.Mult(); break;
  1094. case '/': op = new ast.Div(); break;
  1095. case '//': op = new ast.FloorDiv(); break;
  1096. case '**': op = new ast.Pow(); break;
  1097. case '@': op = new ast.MatMult(); break;
  1098. case '&': op = new ast.BitAnd(); break;
  1099. case '^': op = new ast.BitXor(); break;
  1100. case '|': op = new ast.BitOr(); break;
  1101. case '%': op = new ast.Mod(); break;
  1102. case '>>': op = new ast.RShift(); break;
  1103. case '<<': op = new ast.LShift(); break;
  1104. default: break;
  1105. }
  1106. if (op) {
  1107. const left = stack.pop();
  1108. const right = this._parseExpression(precedence, terminal, tuple === true);
  1109. node = new ast.BinOp(left, op, right);
  1110. } else {
  1111. switch (token.value) {
  1112. case '==': op = new ast.Eq(); break;
  1113. case '!=': op = new ast.NotEq(); break;
  1114. case '>=': op = new ast.GtE(); break;
  1115. case '<=': op = new ast.LtE(); break;
  1116. case '<': op = new ast.Lt(); break;
  1117. case '>': op = new ast.Gt(); break;
  1118. case 'is': op = new ast.Is(); break;
  1119. case 'is not': op = new ast.IsNot(); break;
  1120. case 'in': op = new ast.In(); break;
  1121. case 'not in': op = new ast.NotIn(); break;
  1122. default: break;
  1123. }
  1124. const left = stack.pop();
  1125. const comparator = this._parseExpression(precedence, ['for', 'if'], tuple === true);
  1126. node = new ast.Compare(left, [op], [comparator]);
  1127. }
  1128. } else if (token.value === '*') {
  1129. const value = this._parseExpression(precedence, terminal, tuple === true);
  1130. node = new ast.Starred(value);
  1131. } else if (token.value === '**') {
  1132. const value = this._parseExpression(precedence, terminal, tuple === true);
  1133. node = new ast.keyword(null, value);
  1134. } else {
  1135. let op = null;
  1136. switch (token.value) {
  1137. case '-': op = new ast.USub(); break;
  1138. case '+': op = new ast.UAdd(); break;
  1139. case '~': op = new ast.Invert(); break;
  1140. case 'not': op = new ast.Not(); break;
  1141. default: throw new python.Error(`Unsupported unary operator ${token.value} ${this._location()}`);
  1142. }
  1143. const operand = this._parseExpression(precedence, terminal, tuple === true);
  1144. node = new ast.UnaryOp(op, operand);
  1145. node = this._mark(node, position);
  1146. }
  1147. stack.push(node);
  1148. continue;
  1149. }
  1150. }
  1151. if (this._tokenizer.accept(':=')) {
  1152. const target = stack.pop();
  1153. const value = this._parseExpression(-1, terminal, tuple !== false);
  1154. const node = new ast.NamedExpr(target, value);
  1155. this._mark(node, position);
  1156. stack.push(node);
  1157. continue;
  1158. }
  1159. if (this._tokenizer.accept('=')) {
  1160. const position = this._position();
  1161. const targets = stack.pop();
  1162. const value = this._parseExpression(-1, terminal, tuple !== false);
  1163. const node = new ast.Assign([targets], value);
  1164. this._mark(node, position);
  1165. stack.push(node);
  1166. continue;
  1167. }
  1168. let op = null;
  1169. switch (token.type) {
  1170. case '+=': op = new ast.Add(); break;
  1171. case '-=': op = new ast.Sub(); break;
  1172. case '**=': op = new ast.Pow(); break;
  1173. case '*=': op = new ast.Mult(); break;
  1174. case '//=': op = new ast.FloorDiv(); break;
  1175. case '/=': op = new ast.Div(); break;
  1176. case '&=': op = new ast.BitAnd(); break;
  1177. case '%=': op = new ast.Mod(); break;
  1178. case '^=': op = new ast.BitXor(); break;
  1179. case '<<=': op = new ast.LShift(); break;
  1180. case '>>=': op = new ast.RShift(); break;
  1181. case '|=': op = new ast.BitOr(); break;
  1182. case '@=': op = new ast.MatMul(); break;
  1183. default: break;
  1184. }
  1185. if (op) {
  1186. this._tokenizer.expect(token.type);
  1187. const target = stack.pop();
  1188. const value = this._parseExpression(-1, terminal, true);
  1189. const node = new ast.AugAssign(target, op, value);
  1190. stack.push(node);
  1191. continue;
  1192. }
  1193. position = this._position();
  1194. if (this._eat('id', 'if')) {
  1195. const body = stack.pop();
  1196. const test = this._parseExpression();
  1197. this._tokenizer.expect('id', 'else');
  1198. const orelse = this._parseExpression();
  1199. const node = new ast.IfExp(test, body, orelse);
  1200. this._mark(node, position);
  1201. stack.push(node);
  1202. continue;
  1203. }
  1204. if (this._tokenizer.match('id', 'for') || this._tokenizer.match('id', 'async')) {
  1205. const position = this._position();
  1206. const elt = stack.pop();
  1207. const generators = this._parseGenerators();
  1208. let node = null;
  1209. if (elt instanceof ast.Dict) {
  1210. if (elt.keys.length !== 1 || elt.values.length !== 1) {
  1211. throw new python.Error(`Invalid dict comprehension ${this._location()}`);
  1212. }
  1213. node = new ast.DictComp(elt.keys[0], elt.values[0], generators);
  1214. } else if (elt instanceof ast.Set) {
  1215. if (elt.elts.length !== 1) {
  1216. throw new python.Error(`Invalid set comprehension ${this._location()}`);
  1217. }
  1218. node = new ast.SetComp(elt.elts[0], generators);
  1219. } else {
  1220. node = new ast.GeneratorExp(elt, generators);
  1221. }
  1222. this._mark(node, position);
  1223. stack.push(node);
  1224. continue;
  1225. }
  1226. if (this._eat('id', 'lambda')) {
  1227. const args = this._parseArguments(':');
  1228. const body = this._parseExpression(-1, terminal, false);
  1229. const node = new ast.Lambda(args, body);
  1230. this._mark(node, position);
  1231. stack.push(node);
  1232. continue;
  1233. }
  1234. if (this._eat('id', 'yield')) {
  1235. if (this._tokenizer.accept('id', 'from')) {
  1236. const value = this._parseExpression(-1, [], true);
  1237. node = new ast.YieldFrom(value);
  1238. stack.push(node);
  1239. } else {
  1240. const value = [];
  1241. do {
  1242. value.push(this._parseExpression(-1, [], false));
  1243. }
  1244. while (this._tokenizer.accept(','));
  1245. node = new ast.Yield(value);
  1246. stack.push(node);
  1247. }
  1248. continue;
  1249. }
  1250. if (this._eat('id', 'await')) {
  1251. const value = this._parseExpression(minPrecedence, terminal, tuple);
  1252. const node = new ast.Await(value);
  1253. this._mark(node, position);
  1254. stack.push(node);
  1255. continue;
  1256. }
  1257. if (this._eat('.')) {
  1258. const value = stack.pop();
  1259. const attr = this._parseName().id;
  1260. const node = new ast.Attribute(value, attr);
  1261. this._mark(node, position);
  1262. stack.push(node);
  1263. continue;
  1264. }
  1265. if (this._tokenizer.peek().type === '(') {
  1266. const position = this._position();
  1267. const args = [];
  1268. const keywords = [];
  1269. this._tokenizer.expect('(');
  1270. let tuple = false;
  1271. while (!this._tokenizer.accept(')')) {
  1272. if (this._tokenizer.accept('\n')) {
  1273. continue;
  1274. }
  1275. const position = this._position();
  1276. const expr = this._parseExpression(-1, [], false);
  1277. if (expr === null) {
  1278. throw new python.Error(`Expected expression ${this._location()}`);
  1279. }
  1280. if (expr instanceof ast.Assign && expr.targets.length === 1) {
  1281. const [target] = expr.targets;
  1282. if (target instanceof ast.Name === false) {
  1283. throw new python.Error(`Expected name ${this._location()}`);
  1284. }
  1285. const node = new ast.keyword(target.id, expr.value);
  1286. this._mark(node, position);
  1287. keywords.push(node);
  1288. } else {
  1289. args.push(expr);
  1290. }
  1291. if (this._tokenizer.accept(',')) {
  1292. tuple = true;
  1293. } else {
  1294. this._tokenizer.accept('\n');
  1295. this._tokenizer.expect(')');
  1296. break;
  1297. }
  1298. }
  1299. if (stack.length === 0 && keywords.length === 0) {
  1300. node = args.length === 1 && !tuple ? args[0] : new ast.Tuple(args);
  1301. this._mark(node, position);
  1302. } else {
  1303. const func = stack.pop();
  1304. node = new ast.Call(func, args, keywords);
  1305. let start = func;
  1306. while (start instanceof ast.Attribute) {
  1307. start = start.value;
  1308. }
  1309. position.lineno = start.lineno;
  1310. position.col_offset = start.col_offset;
  1311. this._mark(node, position);
  1312. }
  1313. stack.push(node);
  1314. continue;
  1315. }
  1316. if (this._tokenizer.peek().type === '[') {
  1317. if (stack.length === 0) {
  1318. stack.push(this._parseList());
  1319. } else {
  1320. const value = stack.pop();
  1321. const position = this._position();
  1322. const slice = this._parseSlice();
  1323. node = new ast.Subscript(value, slice);
  1324. this._mark(node, position);
  1325. stack.push(node);
  1326. }
  1327. continue;
  1328. }
  1329. if (this._tokenizer.peek().type === '{') {
  1330. const elts = [];
  1331. const keys = [];
  1332. const values = [];
  1333. this._tokenizer.expect('{');
  1334. let dict = true;
  1335. while (!this._tokenizer.accept('}')) {
  1336. const item = this._parseExpression(-1, [], false);
  1337. if (item === null) {
  1338. throw new python.Error(`Expected expression ${this._location()}`);
  1339. }
  1340. if (!this._tokenizer.accept(':')) {
  1341. dict = false;
  1342. }
  1343. if (dict) {
  1344. const value = this._parseExpression(-1, ['for'], false);
  1345. if (value === null) {
  1346. throw new python.Error(`Expected expression ${this._location()}`);
  1347. }
  1348. if (this._eat('id', 'for')) {
  1349. if (keys.length > 0 || values.length > 0 || elts.length > 0) {
  1350. throw new python.Error(`Invalid list expression ${this._location()}`);
  1351. }
  1352. const target = this._parseExpression(-1, ['in'], true);
  1353. this._tokenizer.expect('id', 'in');
  1354. const iter = this._parseExpression(-1, ['for', 'if'], true);
  1355. const ifs = [];
  1356. while (this._tokenizer.accept('id', 'if')) {
  1357. ifs.push(this._parseExpression(-1, ['for', 'if']));
  1358. }
  1359. const comprehension = new ast.comprehension(target, iter, ifs /*, async */);
  1360. const generators = [comprehension];
  1361. this._tokenizer.expect('}');
  1362. return new ast.DictComp(item, value, generators);
  1363. }
  1364. keys.push(item);
  1365. values.push(value);
  1366. } else {
  1367. elts.push(item);
  1368. }
  1369. this._tokenizer.accept(',');
  1370. this._tokenizer.accept('\n');
  1371. if (this._tokenizer.accept('}')) {
  1372. break;
  1373. }
  1374. }
  1375. if (keys.length !== values.length || (keys.length > 0 && elts.length > 0)) {
  1376. throw new python.Error(`Invalid set expression ${this._location()}`);
  1377. }
  1378. const node = elts.length > 0 ? new ast.Set(elts) : new ast.Dict(keys, values);
  1379. stack.push(node);
  1380. continue;
  1381. }
  1382. const literal = this._parseLiteral();
  1383. if (literal) {
  1384. if (stack.length === 1 && literal.type === 'str' && stack[0] instanceof ast.Constant && typeof stack[0].value === 'string') {
  1385. stack[0].value += literal.value.substring(1, literal.value.length - 1);
  1386. } else {
  1387. let value = literal.value;
  1388. switch (literal.type) {
  1389. case 'int':
  1390. case 'float':
  1391. value = value === 'inf' ? Infinity : Number(value);
  1392. break;
  1393. case 'complex':
  1394. value = new builtins.complex(0, Number(value.slice(0, -1)));
  1395. break;
  1396. case 'str':
  1397. value = value.substring(1, value.length - 1);
  1398. break;
  1399. default:
  1400. throw new python.Error(`Invalid literal type '${literal.type}' ${this._location()}`);
  1401. }
  1402. const node = new ast.Constant(value, literal.type);
  1403. this._mark(node, position);
  1404. stack.push(node);
  1405. }
  1406. continue;
  1407. }
  1408. if (this._eat('id', 'False')) {
  1409. const node = new ast.Constant(false, 'bool');
  1410. this._mark(node, position);
  1411. stack.push(node);
  1412. continue;
  1413. }
  1414. if (this._eat('id', 'True')) {
  1415. const node = new ast.Constant(true, 'bool');
  1416. this._mark(node, position);
  1417. stack.push(node);
  1418. continue;
  1419. }
  1420. if (this._eat('id', 'None')) {
  1421. const node = new ast.Constant(null);
  1422. this._mark(node, position);
  1423. stack.push(node);
  1424. continue;
  1425. }
  1426. if (this._tokenizer.peek().keyword) {
  1427. break;
  1428. }
  1429. if (this._eat('...')) {
  1430. const node = new ast.Ellipsis();
  1431. this._mark(node, position);
  1432. stack.push(node);
  1433. continue;
  1434. }
  1435. const name = this._parseName();
  1436. if (name) {
  1437. stack.push(name);
  1438. continue;
  1439. }
  1440. if (tuple === true && stack.length === 1 && this._tokenizer.accept(',')) {
  1441. if (stack[0] instanceof ast.Tuple) {
  1442. [node] = stack;
  1443. } else {
  1444. const position = this._position();
  1445. const elts = [stack.pop()];
  1446. node = new ast.Tuple(elts);
  1447. this._mark(node, position);
  1448. stack.push(node);
  1449. }
  1450. // for, bar, = <expr>
  1451. if (this._tokenizer.peek().type === '=') {
  1452. continue;
  1453. }
  1454. if (!this._tokenizer.match('=') && !terminalSet.has(this._tokenizer.peek().value)) {
  1455. const nextTerminal = terminal.slice(0).concat([',', '=']);
  1456. const expression = this._parseExpression(minPrecedence, nextTerminal, tuple);
  1457. if (expression) {
  1458. node.elts.push(expression);
  1459. continue;
  1460. }
  1461. }
  1462. break;
  1463. }
  1464. break;
  1465. }
  1466. if (stack.length === 1) {
  1467. return stack.pop();
  1468. }
  1469. if (stack.length !== 0) {
  1470. throw new python.Error(`Unexpected expression ${this._location()}`);
  1471. }
  1472. return null;
  1473. }
  1474. _decorator() {
  1475. const list = [];
  1476. while (this._tokenizer.accept('@')) {
  1477. const value = this._parseExpression();
  1478. if (!value || (value instanceof ast.Call === false && value instanceof ast.Name === false && value instanceof ast.Attribute === false)) {
  1479. throw new python.Error(`Invalid decorator ${this._location()}`);
  1480. }
  1481. this._tokenizer.accept('\n');
  1482. list.push(value);
  1483. }
  1484. return list;
  1485. }
  1486. _parseGenerators() {
  1487. const generators = [];
  1488. while (this._tokenizer.match('id', 'for') || this._tokenizer.match('id', 'async')) {
  1489. const is_async = this._eat('id', 'async') ? 1 : 0;
  1490. this._tokenizer.expect('id', 'for');
  1491. const target = this._parseExpression(-1, ['in'], true);
  1492. this._tokenizer.expect('id', 'in');
  1493. const iter = this._parseExpression(-1, ['for', 'if'], true);
  1494. const ifs = [];
  1495. while (this._tokenizer.accept('id', 'if')) {
  1496. ifs.push(this._parseExpression(-1, ['for', 'if']));
  1497. }
  1498. const comprehension = new ast.comprehension(target, iter, ifs, is_async);
  1499. generators.push(comprehension);
  1500. }
  1501. return generators;
  1502. }
  1503. _parseList() {
  1504. const elts = [];
  1505. this._tokenizer.expect('[');
  1506. if (!this._tokenizer.match(']')) {
  1507. const position = this._position();
  1508. const expr = this._parseExpression(-1, ['for']);
  1509. if (this._tokenizer.match('id', 'for')) {
  1510. const generators = this._parseGenerators();
  1511. this._tokenizer.expect(']');
  1512. const node = new ast.ListComp(expr, generators);
  1513. this._mark(node, position);
  1514. return node;
  1515. }
  1516. if (expr === null) {
  1517. throw new python.Error(`Expected expression ${this._location()}`);
  1518. }
  1519. elts.push(expr);
  1520. while (this._tokenizer.accept(',')) {
  1521. if (this._tokenizer.match(']')) {
  1522. break;
  1523. }
  1524. const expr = this._parseExpression(-1, ['for']);
  1525. if (!expr) {
  1526. throw new python.Error(`Expected expression ${this._location()}`);
  1527. }
  1528. elts.push(expr);
  1529. }
  1530. }
  1531. this._tokenizer.expect(']');
  1532. return new ast.List(elts);
  1533. }
  1534. _parseSlice() {
  1535. const elts = [];
  1536. let slice = [null, null, null];
  1537. let index = 0;
  1538. let valid = false;
  1539. this._tokenizer.expect('[');
  1540. while (true) {
  1541. if (this._tokenizer.accept(':')) {
  1542. index++;
  1543. valid = true;
  1544. } else if (index > 2 || this._tokenizer.match(',') || this._tokenizer.match(']')) {
  1545. if (!valid || index > 2) {
  1546. throw new python.Error(`Invalid slice at ${this._location()}`);
  1547. }
  1548. elts.push(index === 0 ? slice[0] : new ast.Slice(slice[0], slice[1], slice[2]));
  1549. slice = [null, null, null];
  1550. index = 0;
  1551. if (this._tokenizer.accept(']')) {
  1552. break;
  1553. }
  1554. this._tokenizer.expect(',');
  1555. } else {
  1556. const expression = this._parseExpression();
  1557. if (expression === null) {
  1558. throw new python.Error(`Expected expression ${this._location()}`);
  1559. }
  1560. slice[index] = expression;
  1561. valid = true;
  1562. }
  1563. }
  1564. if (elts.length > 1) {
  1565. return new ast.Tuple(elts);
  1566. }
  1567. return elts[0];
  1568. }
  1569. _parseName(required) {
  1570. const token = this._tokenizer.peek();
  1571. if (token.type === 'id' && !token.keyword) {
  1572. const position = this._position();
  1573. this._tokenizer.read();
  1574. const node = new ast.Name(token.value);
  1575. return this._mark(node, position);
  1576. }
  1577. if (required) {
  1578. throw new python.Error(`Invalid syntax ${this._location()}`);
  1579. }
  1580. return null;
  1581. }
  1582. _parseDottedName() {
  1583. const list = [];
  1584. do {
  1585. const name = this._parseName(true);
  1586. list.push(name.id);
  1587. }
  1588. while (this._tokenizer.accept('.'));
  1589. return list.join('.');
  1590. }
  1591. _parseLiteral() {
  1592. const token = this._tokenizer.peek();
  1593. if (token.type === 'str' || token.type === 'bool' || token.type === 'int' || token.type === 'float' || token.type === 'complex') {
  1594. this._tokenizer.read();
  1595. return token;
  1596. }
  1597. return null;
  1598. }
  1599. _parseTypeArguments() {
  1600. const list = [];
  1601. this._tokenizer.expect('[');
  1602. while (!this._tokenizer.accept(']')) {
  1603. const type = this._parseType();
  1604. if (type === null) {
  1605. throw new python.Error(`Expected type ${this._location()}`);
  1606. }
  1607. list.push(type);
  1608. if (!this._tokenizer.accept(',')) {
  1609. this._tokenizer.expect(']');
  1610. break;
  1611. }
  1612. }
  1613. return list;
  1614. }
  1615. _parseType() {
  1616. const target = this._parseExpression(-1, ['[', '=']);
  1617. if (target) {
  1618. if (this._tokenizer.peek().value === '[') {
  1619. const list = this._parseList();
  1620. const slice = list.elts.length === 1 ? list.elts[0] : new ast.Tuple(list.elts);
  1621. return new ast.Subscript(target, slice);
  1622. }
  1623. return target;
  1624. }
  1625. return null;
  1626. }
  1627. _parseArguments(terminal) {
  1628. let posonlyargs = [];
  1629. let args = [];
  1630. let vararg = null;
  1631. const kwonlyargs = [];
  1632. const kw_defaults = [];
  1633. let kwarg = null;
  1634. const defaults = [];
  1635. let is_slash = false;
  1636. let is_vararg = false; // '*'
  1637. let is_kwarg = false; // '**'
  1638. const read = (required) => {
  1639. const name = this._parseName(required);
  1640. if (name) {
  1641. const annotation = terminal !== ':' && this._tokenizer.accept(':') ? this._parseType() : null;
  1642. return new ast.arg(name.id, annotation, null);
  1643. }
  1644. return null;
  1645. };
  1646. while (!this._tokenizer.accept(terminal)) {
  1647. this._tokenizer.accept('\n');
  1648. if (this._tokenizer.accept('/')) {
  1649. if (is_slash || is_vararg || is_kwarg) {
  1650. throw new python.Error(`Invalid '/' in arguments ${this._location()}`);
  1651. }
  1652. is_slash = true;
  1653. } else if (this._tokenizer.accept('*')) {
  1654. if (is_vararg) {
  1655. throw new python.Error(`Multiple '*' arguments ${this._location()}`);
  1656. }
  1657. is_vararg = true;
  1658. const arg = read(false);
  1659. vararg = arg ? arg : vararg;
  1660. } else if (this._tokenizer.accept('**')) {
  1661. if (is_kwarg) {
  1662. throw new python.Error(`Multiple '**' arguments ${this._location()}`);
  1663. }
  1664. is_kwarg = true;
  1665. kwarg = read(true);
  1666. } else {
  1667. const arg = read(false);
  1668. if (!arg) {
  1669. this._tokenizer.expect(terminal);
  1670. break;
  1671. }
  1672. const default_value = this._tokenizer.accept('=') ? this._parseExpression() : null;
  1673. if (!is_vararg && !is_kwarg) {
  1674. if (is_slash) {
  1675. args.push(arg);
  1676. } else {
  1677. posonlyargs.push(arg);
  1678. }
  1679. if (default_value !== null) {
  1680. defaults.push(default_value);
  1681. }
  1682. } else if (is_vararg && !is_kwarg) {
  1683. kwonlyargs.push(arg);
  1684. kw_defaults.push(default_value);
  1685. } else {
  1686. throw new python.Error(`Argument after '**' parameter ${this._location()}`);
  1687. }
  1688. }
  1689. this._tokenizer.accept('\n');
  1690. if (!this._tokenizer.accept(',')) {
  1691. this._tokenizer.expect(terminal);
  1692. break;
  1693. }
  1694. }
  1695. if (!is_slash) {
  1696. args = posonlyargs.concat(args);
  1697. posonlyargs = [];
  1698. }
  1699. return new ast.arguments(posonlyargs, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults);
  1700. }
  1701. _eat(type, value) {
  1702. if (this._tokenizer.match(type, value)) {
  1703. const position = this._position();
  1704. this._tokenizer.expect(type, value);
  1705. return position;
  1706. }
  1707. return null;
  1708. }
  1709. _mark(node, position) {
  1710. node.filename = position.filename;
  1711. node.lineno = position.lineno;
  1712. node.col_offset = position.col_offset;
  1713. node.end_lineno = this._tokenizer.lineno;
  1714. node.end_col_offset = this._tokenizer.col_offset;
  1715. return node;
  1716. }
  1717. _position() {
  1718. return {
  1719. filename: this._tokenizer.filename,
  1720. lineno: this._tokenizer.lineno,
  1721. col_offset: this._tokenizer.col_offset
  1722. };
  1723. }
  1724. _location() {
  1725. return this._tokenizer.location();
  1726. }
  1727. });
  1728. this.registerType('ast._Tokenizer', class {
  1729. constructor(text, file) {
  1730. this._text = text;
  1731. this.filename = file;
  1732. this.linepos = 0;
  1733. this.lineno = 1;
  1734. this._position = 0;
  1735. this._token = { type: '', value: '' };
  1736. this._brackets = 0;
  1737. this._indentation = [];
  1738. this._outdent = 0;
  1739. if (!ast._Tokenizer._whitespace) {
  1740. ast._Tokenizer._whitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  1741. 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';
  1742. 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';
  1743. ast._Tokenizer._identifierStart = new RegExp(`[${identifierStartChars}]`);
  1744. /* eslint-disable no-misleading-character-class */
  1745. ast._Tokenizer._identifierChar = new RegExp(`[${identifierStartChars}${identifierChars}]`);
  1746. /* eslint-enable no-misleading-character-class */
  1747. }
  1748. }
  1749. peek() {
  1750. if (!this._cache) {
  1751. this._tokenize();
  1752. this._cache = true;
  1753. }
  1754. return this._token;
  1755. }
  1756. read() {
  1757. if (!this._cache) {
  1758. this._tokenize();
  1759. }
  1760. const next = this._position + this._token.value.length;
  1761. while (this._position < next) {
  1762. if (ast._Tokenizer._isNewline(this._get(this._position))) {
  1763. this._position = this._newLine(this._position);
  1764. this.linepos = this._position;
  1765. this.lineno++;
  1766. } else {
  1767. this._position++;
  1768. }
  1769. }
  1770. this._cache = false;
  1771. return this._token;
  1772. }
  1773. match(type, value) {
  1774. const token = this.peek();
  1775. if (token.type === type && (!value || token.value === value)) {
  1776. return true;
  1777. }
  1778. return false;
  1779. }
  1780. accept(type, value) {
  1781. const token = this.peek();
  1782. if (token.type === type && (!value || token.value === value)) {
  1783. this.read();
  1784. return true;
  1785. }
  1786. return false;
  1787. }
  1788. expect(type, value) {
  1789. const token = this.peek();
  1790. if (token.type !== type) {
  1791. throw new python.Error(`Unexpected '${token.value}' instead of '${type}' ${this.location()}`);
  1792. }
  1793. if (value && token.value !== value) {
  1794. throw new python.Error(`Unexpected '${token.value}' instead of '${value}' ${this.location()}`);
  1795. }
  1796. this.read();
  1797. }
  1798. location() {
  1799. return `at ${this.filename}:${this.lineno}:${this.col_offset}.`;
  1800. }
  1801. get col_offset() {
  1802. return this._position - this.linepos + 1;
  1803. }
  1804. static _isSpace(c) {
  1805. if (c === ' ' || c === '\t' || c === '\v' || c === '\f' || c === '\xA0') {
  1806. return true;
  1807. }
  1808. if (c.charCodeAt(0) >= 0x1680) {
  1809. return ast._Tokenizer._whitespace.test(c);
  1810. }
  1811. return false;
  1812. }
  1813. static _isNewline(c) {
  1814. switch (c) {
  1815. case '\n':
  1816. case '\r':
  1817. case '\u2028': // 8232
  1818. case '\u2029': // 8233
  1819. return true;
  1820. default:
  1821. return false;
  1822. }
  1823. }
  1824. static _isIdentifierStartChar(c) {
  1825. if (c < 'A') {
  1826. return c === '$';
  1827. }
  1828. if (c <= 'Z') {
  1829. return true;
  1830. }
  1831. if (c < 'a') {
  1832. return c === '_';
  1833. }
  1834. if (c <= 'z') {
  1835. return true;
  1836. }
  1837. const code = c.charCodeAt(0);
  1838. if (code >= 0xAA) {
  1839. return ast._Tokenizer._identifierStart.test(c);
  1840. }
  1841. return false;
  1842. }
  1843. static _isIdentifierChar(c) {
  1844. if (c < '0') {
  1845. return c === '$';
  1846. }
  1847. if (c <= '9') {
  1848. return true;
  1849. }
  1850. if (c < 'A') {
  1851. return false;
  1852. }
  1853. if (c <= 'Z') {
  1854. return true;
  1855. }
  1856. if (c < 'a') {
  1857. return c === '_';
  1858. }
  1859. if (c <= 'z') {
  1860. return true;
  1861. }
  1862. const code = c.charCodeAt(0);
  1863. if (code >= 0xAA) {
  1864. return ast._Tokenizer._identifierChar.test(c);
  1865. }
  1866. return false;
  1867. }
  1868. _get(position) {
  1869. return position >= this._text.length ? '\0' : this._text[position];
  1870. }
  1871. _skipLine() {
  1872. while (this._position < this._text.length) {
  1873. if (ast._Tokenizer._isNewline(this._get(this._position))) {
  1874. break;
  1875. }
  1876. this._position++;
  1877. }
  1878. }
  1879. _skipWhitespace() {
  1880. while (this._position < this._text.length) {
  1881. const c = this._text[this._position];
  1882. if (c === '#') {
  1883. this._skipLine();
  1884. } else if (ast._Tokenizer._isSpace(c)) {
  1885. this._position++;
  1886. } else if (c === '\\') {
  1887. // Explicit Line Continuation
  1888. this._position++;
  1889. if (ast._Tokenizer._isNewline(this._get(this._position))) {
  1890. this._position = this._newLine(this._position);
  1891. this.linepos = this._position;
  1892. this.lineno += 1;
  1893. } else {
  1894. throw new python.Error(`Unexpected '${this._text[this._position]}' after line continuation ${this.location()}`);
  1895. }
  1896. } else if (this._brackets > 0 && ast._Tokenizer._isNewline(c)) {
  1897. // Implicit Line Continuation
  1898. this._position = this._newLine(this._position);
  1899. this.linepos = this._position;
  1900. this.lineno += 1;
  1901. } else {
  1902. break;
  1903. }
  1904. }
  1905. }
  1906. _newLine(position) {
  1907. if ((this._get(position) === '\n' && this._get(position + 1) === '\r') || (this._get(position) === '\r' && this._get(position + 1) === '\n')) {
  1908. return position + 2;
  1909. }
  1910. return position + 1;
  1911. }
  1912. _tokenize() {
  1913. if (this._token.type !== '\n') {
  1914. this._skipWhitespace();
  1915. }
  1916. if (this._token.type === 'dedent') {
  1917. this._indentation.pop();
  1918. this._outdent--;
  1919. if (this._outdent > 0) {
  1920. this._token = { type: 'dedent', value: '' };
  1921. return;
  1922. }
  1923. }
  1924. if (this._token.type === '\n') {
  1925. let indent = '';
  1926. let i = this._position;
  1927. while (i < this._text.length) {
  1928. const c = this._text[i];
  1929. if (ast._Tokenizer._isSpace(c)) {
  1930. indent += c;
  1931. i++;
  1932. } else if (ast._Tokenizer._isNewline(c)) {
  1933. indent = '';
  1934. i = this._newLine(i);
  1935. this._position = i;
  1936. this.linepos = i;
  1937. this.lineno += 1;
  1938. } else if (c === '#') {
  1939. indent = '';
  1940. while (i < this._text.length && !ast._Tokenizer._isNewline(this._text[i])) {
  1941. i++;
  1942. }
  1943. continue;
  1944. } else {
  1945. break;
  1946. }
  1947. }
  1948. let type = null;
  1949. if (indent.length > 0) {
  1950. const current = this._indentation.length > 0 ? this._indentation[this._indentation.length - 1] : '';
  1951. if (indent.length > current.length) {
  1952. type = 'indent';
  1953. this._indentation.push(indent);
  1954. } else if (indent.length > 0 && indent.length < current.length) {
  1955. type = 'dedent';
  1956. this._outdent = 0;
  1957. for (let j = this._indentation.length - 1; j >= 0 && indent.length < this._indentation[j].length; j--) {
  1958. this._outdent++;
  1959. }
  1960. } else {
  1961. this._position += indent.length;
  1962. }
  1963. } else if (i >= this._text.length) {
  1964. this._token = { type: 'eof', value: '' };
  1965. return;
  1966. } else if (this._indentation.length > 0) {
  1967. type = 'dedent';
  1968. this._outdent = this._indentation.length;
  1969. }
  1970. if (type === 'indent' || type === 'dedent') {
  1971. this._token = { type, value: indent };
  1972. return;
  1973. }
  1974. }
  1975. if (this._position >= this._text.length) {
  1976. this._token = { type: 'eof', value: '' };
  1977. return;
  1978. }
  1979. const c = this._get(this._position);
  1980. const string = this._string();
  1981. if (string) {
  1982. this._token = string;
  1983. return;
  1984. }
  1985. switch (c) {
  1986. case '(':
  1987. case '[':
  1988. case '{':
  1989. this._brackets++;
  1990. this._token = { type: c, value: c };
  1991. return;
  1992. case ')':
  1993. case ']':
  1994. case '}':
  1995. if (this._brackets === 0) {
  1996. throw new python.Error(`Unexpected '${c}' ${this.location}`);
  1997. }
  1998. this._brackets--;
  1999. this._token = { type: c, value: c };
  2000. return;
  2001. case ',':
  2002. case ';':
  2003. case '?':
  2004. this._token = { type: c, value: c };
  2005. return;
  2006. default: {
  2007. const number = this._number();
  2008. if (number) {
  2009. this._token = number;
  2010. return;
  2011. }
  2012. if (c === '.') {
  2013. let end = this._position + 1;
  2014. while (this._get(end) === '.') {
  2015. end++;
  2016. }
  2017. const text = this._text.substring(this._position, end);
  2018. this._token = { type: text, value: text };
  2019. return;
  2020. }
  2021. const identifier = this._identifier();
  2022. if (identifier) {
  2023. this._token = identifier;
  2024. return;
  2025. }
  2026. const operator = this._operator();
  2027. if (operator) {
  2028. this._token = operator;
  2029. return;
  2030. }
  2031. break;
  2032. }
  2033. }
  2034. if (c === '.') {
  2035. this._token = { type: c, value: c };
  2036. return;
  2037. }
  2038. if (c === '\\') {
  2039. this._token = { type: '\\', value: c };
  2040. return;
  2041. }
  2042. if (ast._Tokenizer._isNewline(c)) {
  2043. this._token = { type: '\n', value: this._text.substring(this._position, this._newLine(this._position)) };
  2044. return;
  2045. }
  2046. throw new python.Error(`Unexpected token '${c}' ${this.location()}`);
  2047. }
  2048. _number() {
  2049. const octal = (c) => c >= '0' && c <= '7' || c === '_';
  2050. const binary = (c) => c === '0' || c === '1' || c === '_';
  2051. const decimal = (c) => c >= '0' && c <= '9' || c === '_';
  2052. const hex = (c) => decimal(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') || c === '_';
  2053. let c = this._get(this._position);
  2054. let i = this._position;
  2055. c = this._get(i);
  2056. if (c === '0') {
  2057. let radix = 0;
  2058. const n = this._get(i + 1);
  2059. if ((n === 'x' || n === 'X') && hex(this._get(i + 2))) {
  2060. i += 2;
  2061. while (hex(this._get(i))) {
  2062. i += 1;
  2063. }
  2064. if (this._get(i) === 'l' || this._get(i) === 'L') {
  2065. i += 1;
  2066. }
  2067. radix = 16;
  2068. } else if ((n === 'b' || n === 'B') && binary(this._get(i + 2))) {
  2069. i += 2;
  2070. while (binary(this._get(i))) {
  2071. i++;
  2072. }
  2073. radix = 2;
  2074. } else if ((n === 'o' || n === 'O') && octal(this._get(i + 2))) {
  2075. i += 2;
  2076. while (octal(this._get(i))) {
  2077. i++;
  2078. }
  2079. radix = 8;
  2080. } else if (n >= '0' && n <= '7') {
  2081. i++;
  2082. while (octal(this._get(i))) {
  2083. i += 1;
  2084. }
  2085. if (this._get(i) === 'l' || this._get(i) === 'L') {
  2086. i += 1;
  2087. }
  2088. radix = 8;
  2089. }
  2090. if (radix > 0 && this._get(i) !== '.') {
  2091. const radixText = this._text.substring(this._position, i);
  2092. const radixParseText = radixText.indexOf('_') === -1 ? radixText : radixText.split('_').join('');
  2093. if (!isNaN(parseInt(radixParseText, radix))) {
  2094. return { type: 'int', value: radixText };
  2095. }
  2096. }
  2097. }
  2098. i = this._position;
  2099. let isDecimal = false;
  2100. if (this._get(i) >= '1' && this._get(i) <= '9') {
  2101. while (decimal(this._get(i))) {
  2102. i++;
  2103. }
  2104. c = this._get(i).toLowerCase();
  2105. isDecimal = c !== '.' && c !== 'e';
  2106. }
  2107. if (this._get(i) === '0') {
  2108. i++;
  2109. c = this._get(i).toLowerCase();
  2110. isDecimal = !decimal(c) && c !== '.' && c !== 'e' && c !== 'j';
  2111. }
  2112. if (isDecimal) {
  2113. if (this._get(i) === 'j' || this._get(i) === 'J') {
  2114. return { 'type': 'complex', value: this._text.substring(this._position, i + 1) };
  2115. }
  2116. // if (this._get(i) === 'l' || this._get(i) === 'L') {
  2117. // Python 2 long integer
  2118. // }
  2119. const intText = this._text.substring(this._position, i);
  2120. if (!isNaN(parseInt(intText, 10))) {
  2121. return { type: 'int', value: intText };
  2122. }
  2123. }
  2124. i = this._position;
  2125. if ((this._get(i) >= '0' && this._get(i) <= '9') ||
  2126. (this._get(i) === '.' && this._get(i + 1) >= '0' && this._get(i + 1) <= '9')) {
  2127. while (decimal(this._get(i))) {
  2128. i++;
  2129. }
  2130. if (this._get(i) === '.') {
  2131. i++;
  2132. }
  2133. while (decimal(this._get(i))) {
  2134. i++;
  2135. }
  2136. if (i > this._position) {
  2137. if (this._get(i) === 'e' || this._get(i) === 'E') {
  2138. i++;
  2139. if (this._get(i) === '-' || this._get(i) === '+') {
  2140. i++;
  2141. }
  2142. if (decimal(this._get(i))) {
  2143. while (decimal(this._get(i))) {
  2144. i++;
  2145. }
  2146. } else {
  2147. i = this._position;
  2148. }
  2149. } else {
  2150. while (decimal(this._get(i))) {
  2151. i++;
  2152. }
  2153. }
  2154. }
  2155. if (i > this._position) {
  2156. if (this._get(i) === 'j' || this._get(i) === 'J') {
  2157. return { type: 'complex', value: this._text.substring(this._position, i + 1) };
  2158. }
  2159. const floatText = this._text.substring(this._position, i);
  2160. const floatParseText = floatText.indexOf('_') === -1 ? floatText : floatText.split('_').join('');
  2161. if (!isNaN(parseFloat(floatParseText))) {
  2162. return { type: 'float', value: floatText };
  2163. }
  2164. }
  2165. }
  2166. return null;
  2167. }
  2168. _identifier() {
  2169. let i = this._position;
  2170. if (ast._Tokenizer._isIdentifierStartChar(this._get(i))) {
  2171. i++;
  2172. while (ast._Tokenizer._isIdentifierChar(this._get(i))) {
  2173. i++;
  2174. }
  2175. }
  2176. if (i > this._position) {
  2177. const text = this._text.substring(this._position, i);
  2178. let keyword = false;
  2179. switch (text) {
  2180. case 'and':
  2181. case 'as':
  2182. case 'else':
  2183. case 'For':
  2184. case 'If':
  2185. case 'Import':
  2186. case 'in':
  2187. case 'is':
  2188. case 'not':
  2189. case 'or':
  2190. keyword = true;
  2191. break;
  2192. default:
  2193. break;
  2194. }
  2195. return { type: 'id', value: text, keyword };
  2196. }
  2197. return null;
  2198. }
  2199. _operator() {
  2200. let length = 0;
  2201. const c0 = this._get(this._position);
  2202. const c1 = this._get(this._position + 1);
  2203. const c2 = this._get(this._position + 2);
  2204. switch (c0) {
  2205. case '+': case '&': case '|': case '^': case '=': case '!': case '%': case '~':
  2206. length = c1 === '=' ? 2 : 1;
  2207. break;
  2208. case '-':
  2209. length = c1 === '=' || c1 === '>' ? 2 : 1;
  2210. break;
  2211. case '*':
  2212. switch (c1) {
  2213. case '*': length = c2 === '=' ? 3 : 2; break;
  2214. case '=': length = 2; break;
  2215. default: length = 1; break;
  2216. }
  2217. break;
  2218. case '/':
  2219. switch (c1) {
  2220. case '/': length = c2 === '=' ? 3 : 2; break;
  2221. case '=': length = 2; break;
  2222. default: length = 1; break;
  2223. }
  2224. break;
  2225. case '<':
  2226. switch (c1) {
  2227. case '>': length = 2; break;
  2228. case '<': length = c2 === '=' ? 3 : 2; break;
  2229. case '=': length = 2; break;
  2230. default: length = 1; break;
  2231. }
  2232. break;
  2233. case '>':
  2234. switch (c1) {
  2235. case '>': length = c2 === '=' ? 3 : 2; break;
  2236. case '=': length = 2; break;
  2237. default: length = 1; break;
  2238. }
  2239. break;
  2240. case '@':
  2241. length = c1 === '=' ? 2 : 1;
  2242. break;
  2243. case ':':
  2244. length = c1 === '=' ? 2 : 1;
  2245. break;
  2246. default:
  2247. return null;
  2248. }
  2249. const text = this._text.substring(this._position, this._position + length);
  2250. return { type: text, value: text };
  2251. }
  2252. _string() {
  2253. let i = this._position;
  2254. let prefix = -1;
  2255. if (this._get(i) === "'" || this._get(i) === '"') {
  2256. prefix = '';
  2257. } else if (this._get(i + 1) === "'" || this._get(i + 1) === '"') {
  2258. const c = this._get(i);
  2259. const cc = c.toLowerCase();
  2260. if (cc === 'b' || cc === 'f' || cc === 'r' || cc === 'u') {
  2261. prefix = c;
  2262. }
  2263. } else if (this._get(i + 2) === "'" || this._get(i + 2) === '"') {
  2264. const c = this._text.substring(this._position, this._position + 2);
  2265. const cc = c.toLowerCase();
  2266. if (cc === 'br' || cc === 'fr' || cc === 'rb' || cc === 'rf' || cc === 'ur') {
  2267. prefix = c;
  2268. }
  2269. }
  2270. if (prefix.length >= 0) {
  2271. i += prefix.length;
  2272. let quote = '';
  2273. let count = 0;
  2274. const q0 = this._get(i);
  2275. const q1 = this._get(i + 1);
  2276. const q2 = this._get(i + 2);
  2277. switch (q0) {
  2278. case "'":
  2279. quote = q0;
  2280. count = (q1 === "'" && q2 === "'") ? 3 : 1;
  2281. break;
  2282. case '"':
  2283. quote = q0;
  2284. count = (q1 === '"' && q2 === '"') ? 3 : 1;
  2285. break;
  2286. default:
  2287. throw new python.Error(`Unsupported string quote '${q0}'.`);
  2288. }
  2289. i += count;
  2290. if (count === 1) {
  2291. while (i < this._text.length) {
  2292. if (this._text[i] === quote) {
  2293. return { type: 'str', value: this._text.substring(this._position, i + 1) };
  2294. } else if (this._text[i] === '\\' &&
  2295. (this._get(i + 1) === quote || this._get(i + 1) === '\n' || this._get(i + 1) === '\\')) {
  2296. i += 2;
  2297. } else if (this._text[i] === '\r' || this._text[i] === '\n') {
  2298. break;
  2299. } else {
  2300. i++;
  2301. }
  2302. }
  2303. } else if (count === 3) {
  2304. while (i < this._text.length) {
  2305. if (this._get(i) === quote && this._get(i + 1) === quote && this._get(i + 2) === quote) {
  2306. return { type: 'str', value: this._text.substring(this._position, i + 3) };
  2307. } else if (this._get(i) === '\\' && this._get(i + 1) === quote) {
  2308. i += 2;
  2309. continue;
  2310. }
  2311. i++;
  2312. }
  2313. }
  2314. }
  2315. i = this._position;
  2316. if (this._get(i) === '`') {
  2317. i++;
  2318. while (i < this._text.length) {
  2319. if (this._text[i] === '`') {
  2320. return { type: 'str', value: this._text.substring(this._position, i + 1) };
  2321. }
  2322. i++;
  2323. }
  2324. }
  2325. return null;
  2326. }
  2327. });
  2328. this.registerType('builtins.dict', dict);
  2329. this.registerType('builtins.ellipsis', class {});
  2330. this.registerType('builtins.cell', class {});
  2331. this.registerType('builtins.list', class extends Array {
  2332. constructor(iterable) {
  2333. super();
  2334. if (Array.isArray(iterable)) {
  2335. this.push(...iterable);
  2336. }
  2337. }
  2338. });
  2339. this.registerType('builtins.number', class {});
  2340. this.registerFunction('builtins.__import__', (name, globals, locals, fromlist, level) => {
  2341. return execution.__import__(name, globals, locals, fromlist, level);
  2342. });
  2343. this.registerType('builtins.bool', class extends Boolean {
  2344. constructor(value) {
  2345. if (value && value.__bool__) {
  2346. value = value.__bool__();
  2347. } else if (value && value.__len__) {
  2348. value = value.__len__() > 0;
  2349. } else {
  2350. value = value ? true : false;
  2351. }
  2352. super(value);
  2353. }
  2354. });
  2355. this.registerType('builtins.int', class extends Number {
  2356. constructor(value) {
  2357. if (value && value.__int__) {
  2358. value = value.__int__();
  2359. } else if (!Number.isInteger(value)) {
  2360. value = NaN;
  2361. }
  2362. super(value);
  2363. }
  2364. });
  2365. this.registerType('builtins.float', class extends Number {
  2366. constructor(value) {
  2367. if (value && value.__float__) {
  2368. value = value.__float__();
  2369. } else if (Number(value) !== value) {
  2370. value = NaN;
  2371. }
  2372. super(value);
  2373. }
  2374. });
  2375. this.registerType('builtins.long', class extends Number {
  2376. constructor(value) {
  2377. if (value && value.__int__) {
  2378. value = value.__int__();
  2379. } else if (!Number.isInteger(value)) {
  2380. value = NaN;
  2381. }
  2382. super(value);
  2383. }
  2384. });
  2385. this.registerType('builtins.str', class extends String {
  2386. constructor(value) {
  2387. if (value && value.__str__) {
  2388. value = value.__str__();
  2389. } else if (typeof value !== 'string') {
  2390. value = JSON.stringify(value);
  2391. }
  2392. super(value);
  2393. }
  2394. });
  2395. this.registerType('builtins.complex', class {
  2396. constructor(real, imaginary) {
  2397. this.real = real;
  2398. this.imag = imaginary;
  2399. }
  2400. toString() {
  2401. return `${this.real}${this.imag < 0 ? '' : '+'}${this.imag}j`;
  2402. }
  2403. });
  2404. this.registerType('builtins.NoneType', class {});
  2405. this.registerType('builtins.object', class {
  2406. static __new__(cls, ...args) {
  2407. return execution.invoke(cls, args);
  2408. }
  2409. static __setattr__(obj, name, value) {
  2410. builtins.setattr(obj, name, value);
  2411. }
  2412. });
  2413. this.registerType('builtins.tuple', class extends Array {
  2414. constructor(items) {
  2415. super(items ? items.length : 0);
  2416. if (items) {
  2417. for (let i = 0; i < items.length; i++) {
  2418. this[i] = items[i];
  2419. }
  2420. }
  2421. }
  2422. });
  2423. this.registerType('builtins.staticmethod', class {});
  2424. this.registerType('builtins.Warning', class {});
  2425. this.registerType('builtins.FutureWarning', class extends builtins.Warning {});
  2426. this.registerType('builtins.BaseException', class {});
  2427. this.registerType('builtins.Exception', class extends builtins.BaseException {});
  2428. this.registerType('builtins.AttributeError', class extends builtins.Exception {});
  2429. this.registerType('builtins.SyntaxError', class extends builtins.Exception {});
  2430. this.registerFunction('builtins.print', () => {});
  2431. this.registerFunction('builtins.unicode');
  2432. builtins.Ellipsis = new builtins.ellipsis();
  2433. this.registerType('typing._Final', class {});
  2434. this.registerType('typing._SpecialForm', class extends typing._Final {});
  2435. this.registerType('typing._BaseGenericAlias', class extends typing._Final {});
  2436. this.registerType('typing._GenericAlias', class extends typing._BaseGenericAlias {});
  2437. this.registerType('typing._SpecialGenericAlias', class extends typing._BaseGenericAlias {});
  2438. this.registerType('typing._TupleType', class extends typing._SpecialGenericAlias {});
  2439. this.registerType('typing._CallableType', class {});
  2440. this.registerFunction('typing.cast');
  2441. typing.Any = Reflect.construct(typing._SpecialForm, []);
  2442. typing.Callable = Reflect.construct(typing._CallableType, []);
  2443. typing.Dict = Reflect.construct(typing._SpecialGenericAlias, []);
  2444. typing.List = Reflect.construct(typing._SpecialGenericAlias, []);
  2445. typing.Optional = Reflect.construct(typing._SpecialForm, []);
  2446. typing.OrderedDict = Reflect.construct(typing._SpecialGenericAlias, []);
  2447. typing.Sequence = Reflect.construct(typing._SpecialGenericAlias, []);
  2448. typing.Tuple = Reflect.construct(typing._TupleType, []);
  2449. typing.Union = Reflect.construct(typing._SpecialForm, []);
  2450. this.registerType('enum.Enum', class {
  2451. // __reduce_ex__(proto) {
  2452. // return self.__class__, (self._value_, )
  2453. // }
  2454. });
  2455. this.registerFunction('operator.add');
  2456. this.registerFunction('operator.and_');
  2457. this.registerFunction('operator.and_');
  2458. this.registerFunction('operator.eq');
  2459. this.registerFunction('operator.floordiv');
  2460. this.registerFunction('operator.ge');
  2461. this.registerFunction('operator.getitem');
  2462. this.registerFunction('operator.gt');
  2463. this.registerFunction('operator.le');
  2464. this.registerFunction('operator.lt');
  2465. this.registerFunction('operator.mod');
  2466. this.registerFunction('operator.mul');
  2467. this.registerFunction('operator.ne');
  2468. this.registerFunction('operator.neg');
  2469. this.registerFunction('operator.or_');
  2470. this.registerFunction('operator.pos');
  2471. this.registerFunction('operator.pow');
  2472. this.registerFunction('operator.sub');
  2473. this.registerFunction('operator.truediv');
  2474. this.registerFunction('sys.path.append', () => {});
  2475. this.registerFunction('sys.path.insert', () => {});
  2476. this.registerType('argparse.Namespace', class {
  2477. constructor(args) {
  2478. this.args = args;
  2479. }
  2480. });
  2481. this.registerType('catboost._catboost._CatBoost', class {
  2482. _deserialize_model(/* serialized_model_str */) {
  2483. }
  2484. });
  2485. this.registerType('catboost.core._CatBoostBase', class {
  2486. constructor() {
  2487. this._object = new catboost._catboost._CatBoost();
  2488. }
  2489. __setstate__(state) {
  2490. for (const [key, value] of state) {
  2491. if (key === '__model') {
  2492. this._load_from_string(value);
  2493. continue;
  2494. }
  2495. this[key] = value;
  2496. }
  2497. }
  2498. _load_from_string(dump_model_str) {
  2499. this._deserialize_model(dump_model_str);
  2500. }
  2501. _deserialize_model(dump_model_str) {
  2502. this._object._deserialize_model(dump_model_str);
  2503. }
  2504. });
  2505. this.registerType('catboost.core.CatBoost', class extends catboost.core._CatBoostBase {
  2506. load_model(/* blob */) {
  2507. throw new python.Error("'catboost.core.CatBoostClassifier.load_model' not implemented.");
  2508. // this._load_from_string(blob);
  2509. }
  2510. });
  2511. this.registerType('catboost.core.CatBoostClassifier', class extends catboost.core.CatBoost {});
  2512. this.registerType('catboost.core.CatBoostRegressor', class extends catboost.core.CatBoost {});
  2513. catboost.CatBoostClassifier = catboost.core.CatBoostClassifier;
  2514. catboost.CatBoostRegressor = catboost.core.CatBoostRegressor;
  2515. catboost.CatBoost = catboost.core.CatBoost;
  2516. this.registerType('collections.deque', class extends Array {
  2517. constructor(iterable) {
  2518. super();
  2519. if (Array.isArray(iterable)) {
  2520. for (const value of iterable) {
  2521. this.push(value);
  2522. }
  2523. }
  2524. }
  2525. });
  2526. this.registerType('collections.OrderedDict', class extends dict {});
  2527. this.registerType('cuml.common.array_descriptor.CumlArrayDescriptorMeta', class {});
  2528. this.registerType('cuml.ensemble.randomforestclassifier.RandomForestClassifier', class {});
  2529. this.registerType('cuml.internals.array.CumlArray', class {});
  2530. this.registerType('cuml.internals.mem_type.MemoryType', class {});
  2531. this.registerType('cuml.raft.common.handle.Handle', class {
  2532. __setstate__(state) {
  2533. this._handle = state;
  2534. }
  2535. });
  2536. this.registerType('cuml.svm.svr.SVR', class {});
  2537. this.registerType('datetime.date', class {});
  2538. this.registerType('datetime.datetime', class extends datetime.date {});
  2539. this.registerType('datetime.timedelta', class {});
  2540. this.registerType('datetime.tzinfo', class {});
  2541. this.registerType('datetime.timezone', class extends datetime.tzinfo {});
  2542. this.registerType('dnnlib.tflib.network.Network', class {});
  2543. this.registerType('dnnlib.util.EasyDict', class extends dict {});
  2544. this.registerType('haiku._src.data_structures.FlatMapping', class {
  2545. constructor(dict) {
  2546. Object.assign(this, dict);
  2547. }
  2548. });
  2549. this.registerType('haiku._src.data_structures.frozendict', class {
  2550. constructor(obj) {
  2551. Object.assign(this, obj);
  2552. }
  2553. });
  2554. this.registerType('hmmlearn.hmm.GaussianHMM', class {});
  2555. this.registerType('hmmlearn.hmm.GMMHMM', class {});
  2556. this.registerType('hmmlearn.hmm.MultinomialHMM', class {});
  2557. this.registerType('hmmlearn.base.ConvergenceMonitor', class {});
  2558. this.registerType('io.BytesIO', class {
  2559. constructor(buf, mode) {
  2560. this.mode = mode || 'r';
  2561. this._buf = this.mode === 'w' ? null : buf;
  2562. this._point = 0;
  2563. }
  2564. seek(offset) {
  2565. if (this._buf.seek) {
  2566. this._buf.seek(offset);
  2567. }
  2568. this._point = offset;
  2569. }
  2570. read(size, stream) {
  2571. if (this._buf.stream && stream) {
  2572. return this._buf.stream(size);
  2573. }
  2574. if (this._buf.peek) {
  2575. return this._buf.read(size);
  2576. }
  2577. if (this._buf instanceof Uint8Array) {
  2578. const start = this._point;
  2579. this._point = size === undefined ? this._buf.length : start + size;
  2580. return this._buf.subarray(start, this._point);
  2581. }
  2582. throw new python.Error('Unsupported buffer type.');
  2583. }
  2584. write(data) {
  2585. const src = this._buf || new Uint8Array();
  2586. const end = this._point + data.length;
  2587. const size = Math.max(src.length, end);
  2588. this._buf = new Uint8Array(size);
  2589. this._buf.set(src, 0);
  2590. this._buf.set(data, this._point);
  2591. this._point = end;
  2592. }
  2593. getbuffer() {
  2594. return new builtins.memoryview(this._buf);
  2595. }
  2596. });
  2597. this.registerType('io.StringIO', class {
  2598. constructor() {
  2599. this._buf = [];
  2600. }
  2601. write(text) {
  2602. this._buf.push(text);
  2603. }
  2604. toString() {
  2605. return this._buf.join('');
  2606. }
  2607. });
  2608. this.registerType('numpy.dtype', class {
  2609. constructor(obj, align, copy) {
  2610. if (typeof obj !== 'string' && obj && Array.isArray(obj.names)) {
  2611. this.kind = 'V';
  2612. this.byteorder = '|';
  2613. this.itemsize = obj.itemsize;
  2614. this.names = obj.names;
  2615. this.fields = new Map();
  2616. for (let i = 0; i < obj.names.length; i++) {
  2617. this.fields.set(obj.names[i], new builtins.tuple([obj.formats[i], obj.offsets[i]]));
  2618. }
  2619. return;
  2620. }
  2621. if (typeof obj === 'string' && (obj.startsWith('<') || obj.startsWith('>') || obj.startsWith('|'))) {
  2622. this.byteorder = obj.substring(0, 1);
  2623. obj = obj.substring(1);
  2624. } else {
  2625. this.byteorder = '=';
  2626. }
  2627. switch (obj) {
  2628. case 'b1': case 'bool': this.itemsize = 1; this.kind = 'b'; break;
  2629. case 'i1': case 'int8': this.itemsize = 1; this.kind = 'i'; break;
  2630. case 'i2': case 'int16': this.itemsize = 2; this.kind = 'i'; break;
  2631. case 'i4': case 'int32': this.itemsize = 4; this.kind = 'i'; break;
  2632. case 'i8': case 'int64': case 'int': this.itemsize = 8; this.kind = 'i'; break;
  2633. case 'u1': case 'uint8': this.itemsize = 1; this.kind = 'u'; break;
  2634. case 'u2': case 'uint16': this.itemsize = 2; this.kind = 'u'; break;
  2635. case 'u4': case 'uint32': this.itemsize = 4; this.kind = 'u'; break;
  2636. case 'u8': case 'uint64': case 'uint': this.itemsize = 8; this.kind = 'u'; break;
  2637. case 'f1': case 'float8_e5m2': this.itemsize = 1; this.kind = 'f'; break;
  2638. case 'f2': case 'float16': this.itemsize = 2; this.kind = 'f'; break;
  2639. case 'f4': case 'float32': this.itemsize = 4; this.kind = 'f'; break;
  2640. case 'f8': case 'float64': case 'float': this.itemsize = 8; this.kind = 'f'; break;
  2641. case 'c8': case 'complex64': this.itemsize = 8; this.kind = 'c'; break;
  2642. case 'c16': case 'complex128': case 'complex': this.itemsize = 16; this.kind = 'c'; break;
  2643. case 'M8': case 'M': this.itemsize = 8; this.kind = 'M'; break;
  2644. case 'm8': case 'm': this.itemsize = 8; this.kind = 'm'; break;
  2645. case 'V': case 'void': this.itemsize = 0; this.kind = 'V'; break;
  2646. default:
  2647. if (obj.startsWith('V')) {
  2648. this.itemsize = parseInt(obj.substring(1), 10);
  2649. this.kind = 'V';
  2650. } else if (obj.startsWith('O')) {
  2651. this.itemsize = obj === 'O' ? 8 : parseInt(obj.substring(1), 10);
  2652. this.kind = 'O';
  2653. } else if (obj.startsWith('S')) {
  2654. this.itemsize = parseInt(obj.substring(1), 10);
  2655. this.kind = 'S';
  2656. } else if (obj.startsWith('U')) { // Unicode string
  2657. this.kind = 'U';
  2658. this.itemsize = 4 * parseInt(obj.substring(1), 10);
  2659. } else if (obj.startsWith('T')) {
  2660. this.kind = 'T';
  2661. this.itemsize = parseInt(obj.substring(1), 10);
  2662. } else {
  2663. throw new python.Error(`Unsupported dtype '${obj}'.`);
  2664. }
  2665. break;
  2666. }
  2667. if (align) {
  2668. this.align = align;
  2669. }
  2670. if (copy) {
  2671. this.copy = copy;
  2672. }
  2673. }
  2674. get str() {
  2675. return (this.byteorder === '=' ? '<' : this.byteorder) + this.kind + this.itemsize.toString();
  2676. }
  2677. get name() {
  2678. switch (this.kind) {
  2679. case 'V': return `void${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2680. case 'S': return `bytes${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2681. case 'U': return `str${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2682. case 'T': return `StringDType${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2683. case 'M': return 'datetime64';
  2684. case 'm': return 'timedelta64';
  2685. case 'b': return 'bool';
  2686. default: return this.__name__;
  2687. }
  2688. }
  2689. __setstate__(state) {
  2690. switch (state.length) {
  2691. case 8:
  2692. [
  2693. this.version, this.byteorder, this.subarray, this.names,
  2694. this.fields, this.elsize, this.alignment, this.int_dtypeflags
  2695. ] = state;
  2696. break;
  2697. case 9:
  2698. [
  2699. this.version, this.byteorder, this.subarray, this.names,
  2700. this.fields, this.elsize, this.alignment, this.int_dtypeflags,
  2701. this.metadata
  2702. ] = state;
  2703. break;
  2704. default:
  2705. throw new python.Error(`Unsupported numpy.dtype setstate length '${state.length}'.`);
  2706. }
  2707. }
  2708. get __name__() {
  2709. switch (this.kind) {
  2710. case 'b':
  2711. switch (this.itemsize) {
  2712. case 1: return 'boolean';
  2713. default: throw new python.Error(`Unsupported boolean itemsize '${this.itemsize}'.`);
  2714. }
  2715. case 'i':
  2716. switch (this.itemsize) {
  2717. case 1: return 'int8';
  2718. case 2: return 'int16';
  2719. case 4: return 'int32';
  2720. case 8: return 'int64';
  2721. default: throw new python.Error(`Unsupported int itemsize '${this.itemsize}'.`);
  2722. }
  2723. case 'u':
  2724. switch (this.itemsize) {
  2725. case 1: return 'uint8';
  2726. case 2: return 'uint16';
  2727. case 4: return 'uint32';
  2728. case 8: return 'uint64';
  2729. default: throw new python.Error(`Unsupported uint itemsize '${this.itemsize}'.`);
  2730. }
  2731. case 'f':
  2732. switch (this.itemsize) {
  2733. case 1: return 'float8e5m2';
  2734. case 2: return 'float16';
  2735. case 4: return 'float32';
  2736. case 8: return 'float64';
  2737. default: throw new python.Error(`Unsupported float itemsize '${this.itemsize}'.`);
  2738. }
  2739. case 'c':
  2740. switch (this.itemsize) {
  2741. case 8: return 'complex<float32>';
  2742. case 16: return 'complex<float64>';
  2743. default: throw new python.Error(`Unsupported complex itemsize '${this.itemsize}'.`);
  2744. }
  2745. case 'S':
  2746. case 'T':
  2747. return 'string';
  2748. case 'U':
  2749. return 'string';
  2750. case 'M':
  2751. return 'datetime';
  2752. case 'm':
  2753. return 'timedelta';
  2754. case 'O':
  2755. return 'object';
  2756. case 'V':
  2757. return 'void';
  2758. default:
  2759. throw new python.Error(`Unsupported dtype kind '${this.kind}'.`);
  2760. }
  2761. }
  2762. });
  2763. this.registerType('numpy.generic', class {});
  2764. this.registerType('numpy.inexact', class {});
  2765. this.registerType('numpy.flexible', class extends numpy.generic {});
  2766. this.registerType('numpy.void', class extends numpy.flexible {});
  2767. this.registerType('numpy.bool_', class extends numpy.generic {});
  2768. this.registerType('numpy.number', class extends numpy.generic {});
  2769. this.registerType('numpy.integer', class extends numpy.number {});
  2770. this.registerType('numpy.floating', class extends numpy.inexact {});
  2771. this.registerType('numpy.float16', class extends numpy.floating {});
  2772. this.registerType('numpy.float32', class extends numpy.floating {});
  2773. this.registerType('numpy.float64', class extends numpy.floating {});
  2774. this.registerType('numpy.signedinteger', class extends numpy.integer {});
  2775. this.registerType('numpy.int8', class extends numpy.signedinteger {});
  2776. this.registerType('numpy.int16', class extends numpy.signedinteger {});
  2777. this.registerType('numpy.int32', class extends numpy.signedinteger {});
  2778. this.registerType('numpy.int64', class extends numpy.signedinteger {});
  2779. this.registerType('numpy.unsignedinteger', class extends numpy.integer {});
  2780. this.registerType('numpy.uint8', class extends numpy.unsignedinteger {});
  2781. this.registerType('numpy.uint16', class extends numpy.unsignedinteger {});
  2782. this.registerType('numpy.uint32', class extends numpy.unsignedinteger {});
  2783. this.registerType('numpy.uint64', class extends numpy.unsignedinteger {});
  2784. this.registerType('numpy.datetime64', class extends numpy.generic {
  2785. constructor(...args) {
  2786. super();
  2787. if (args.length === 1 && args[0] instanceof Uint8Array) {
  2788. [this.buffer] = args;
  2789. }
  2790. }
  2791. toString() {
  2792. const view = new DataView(this.buffer.buffer, this.buffer.byteOffset, 8);
  2793. const value = view.getBigInt64(0, true);
  2794. if (value === -9223372036854775808n) {
  2795. return 'NaT';
  2796. }
  2797. const date = new Date(Number(value / 1000000n));
  2798. return date.toISOString().slice(0, -1);
  2799. }
  2800. });
  2801. this.registerType('numpy.dtypes.StringDType', class extends numpy.dtype {
  2802. constructor() {
  2803. super('|T16');
  2804. }
  2805. });
  2806. this.registerType('gensim.models.doc2vec.Doctag', class {});
  2807. this.registerType('gensim.models.doc2vec.Doc2Vec', class {});
  2808. this.registerType('gensim.models.doc2vec.Doc2VecTrainables', class {});
  2809. this.registerType('gensim.models.doc2vec.Doc2VecVocab', class {});
  2810. this.registerType('gensim.models.fasttext.FastText', class {});
  2811. this.registerType('gensim.models.fasttext.FastTextTrainables', class {});
  2812. this.registerType('gensim.models.fasttext.FastTextVocab', class {});
  2813. this.registerType('gensim.models.fasttext.FastTextKeyedVectors', class {});
  2814. this.registerType('gensim.models.keyedvectors.Doc2VecKeyedVectors', class {});
  2815. this.registerType('gensim.models.keyedvectors.FastTextKeyedVectors', class {});
  2816. this.registerType('gensim.models.keyedvectors.KeyedVectors', class {});
  2817. this.registerType('gensim.models.keyedvectors.Vocab', class {});
  2818. this.registerType('gensim.models.keyedvectors.Word2VecKeyedVectors', class {});
  2819. this.registerType('gensim.models.ldamodel.LdaState', class {});
  2820. this.registerType('gensim.models.ldamulticore.LdaMulticore', class {});
  2821. this.registerFunction('gensim.models.phrases.original_scorer');
  2822. this.registerType('gensim.models.phrases.Phraser', class {});
  2823. this.registerType('gensim.models.phrases.Phrases', class {});
  2824. this.registerType('gensim.models.tfidfmodel.TfidfModel', class {});
  2825. this.registerType('gensim.models.word2vec.Vocab', class {});
  2826. this.registerType('gensim.models.word2vec.Word2Vec', class {});
  2827. this.registerType('gensim.models.word2vec.Word2VecTrainables', class {});
  2828. this.registerType('gensim.models.word2vec.Word2VecVocab', class {});
  2829. this.registerFunction('gensim.models.tfidfmodel.df2idf');
  2830. this.registerFunction('gensim.utils.call_on_class_only', () => {
  2831. throw new builtins.AttributeError('This method should be called on a class object.');
  2832. });
  2833. this.registerFunction('gensim.utils.identity');
  2834. this.registerType('google3.learning.deepmind.research.nbr.pbl_jax.clean_jaxline.utils.optimizers.ScaleByLarsState', class {
  2835. constructor(obj) {
  2836. Object.assign(this, obj);
  2837. }
  2838. });
  2839. this.registerType('joblib._store_backends.FileSystemStoreBackend', class {});
  2840. this.registerType('joblib.memory.NotMemorizedFunc', class {});
  2841. this.registerType('joblib.numpy_pickle.NumpyArrayWrapper', class {
  2842. __read__(unpickler) {
  2843. if (this.dtype.__name__ === 'object') {
  2844. return unpickler.load();
  2845. }
  2846. if (this.numpy_array_alignment_bytes) {
  2847. const [size] = unpickler.read(1);
  2848. unpickler.read(size);
  2849. }
  2850. const size = this.dtype.itemsize * this.shape.reduce((a, b) => a * b, 1);
  2851. this.data = unpickler.read(size);
  2852. return new this.subclass(this.shape, this.dtype, this.data, undefined, undefined, this.order);
  2853. }
  2854. });
  2855. this.registerType('joblib.numpy_pickle.NDArrayWrapper', class {
  2856. __setstate__(state) {
  2857. this.subclass = state.get('subclass');
  2858. this.filename = state.get('state');
  2859. this.allow_mmap = state.get('allow_mmap');
  2860. }
  2861. __read__(/* unpickler */) {
  2862. return this; // return execution.invoke(this.subclass, [ this.shape, this.dtype, this.data ]);
  2863. }
  2864. });
  2865. sklearn.externals.joblib.numpy_pickle.NDArrayWrapper = joblib.numpy_pickle.NDArrayWrapper;
  2866. sklearn.externals.joblib.numpy_pickle.NumpyArrayWrapper = joblib.numpy_pickle.NumpyArrayWrapper;
  2867. this.registerType('keras.engine.sequential.Sequential', class {});
  2868. this.registerType('keras.src.legacy.preprocessing.text.Tokenizer', class {});
  2869. this.registerType('lasagne.layers.conv.Conv2DLayer', class {});
  2870. this.registerType('lasagne.layers.dense.DenseLayer', class {});
  2871. this.registerType('lasagne.layers.input.InputLayer', class {});
  2872. this.registerType('lasagne.layers.pool.MaxPool2DLayer', class {});
  2873. this.registerType('lightgbm.sklearn.LGBMRegressor', class {});
  2874. this.registerType('lightgbm.sklearn.LGBMClassifier', class {});
  2875. this.registerType('lightgbm.basic.Booster', class {
  2876. constructor() {
  2877. this.average_output = false;
  2878. this.models = [];
  2879. this.loaded_parameter = '';
  2880. }
  2881. __setstate__(state) {
  2882. const model_str = state.get('_handle', state.get('handle', null));
  2883. if (model_str) {
  2884. this.LoadModelFromString(model_str);
  2885. return;
  2886. }
  2887. for (const [key, value] of state) {
  2888. this[key] = value;
  2889. }
  2890. }
  2891. LoadModelFromString(model_str) {
  2892. const lines = model_str.split('\n');
  2893. const signature = lines.shift() || '?';
  2894. if (signature.trim() !== 'tree') {
  2895. throw new python.Error(`Invalid signature '${signature.trim()}'.`);
  2896. }
  2897. // GBDT::LoadModelFromString() in https://github.com/microsoft/LightGBM/blob/master/src/boosting/gbdt_model_text.cpp
  2898. const key_vals = new Map();
  2899. while (lines.length > 0 && !lines[0].startsWith('Tree=')) {
  2900. const cur_line = lines.shift().trim();
  2901. if (cur_line.length > 0) {
  2902. const strs = cur_line.split('=');
  2903. if (strs.length === 1) {
  2904. key_vals.set(strs[0], '');
  2905. } else if (strs.length === 2) {
  2906. key_vals.set(strs[0], strs[1]);
  2907. } else if (strs.length > 2) {
  2908. if (strs[0] === "feature_names") {
  2909. key_vals.set(strs[0], cur_line.substring("feature_names=".length));
  2910. } else if (strs[0] === 'monotone_constraints') {
  2911. key_vals.set(strs[0], cur_line.substring('monotone_constraints='.length));
  2912. } else {
  2913. throw new python.Error(`Wrong line: ${cur_line.substring(0, Math.min(128, cur_line.length))}`);
  2914. }
  2915. }
  2916. }
  2917. }
  2918. const atoi = (key, value) => {
  2919. if (key_vals.has(key)) {
  2920. return parseInt(key_vals.get(key), 10);
  2921. }
  2922. if (value !== undefined) {
  2923. return value;
  2924. }
  2925. throw new python.Error(`Model file does not specify ${key}.`);
  2926. };
  2927. const list = (key, size) => {
  2928. if (key_vals.has(key)) {
  2929. const value = key_vals.get(key).split(' ');
  2930. if (value.length !== size) {
  2931. throw new python.Error(`Wrong size of ${key}.`);
  2932. }
  2933. return value;
  2934. }
  2935. throw new python.Error(`Model file does not contain ${key}.`);
  2936. };
  2937. this.version = key_vals.get('version') || '';
  2938. this.num_class = atoi('num_class');
  2939. this.num_tree_per_iteration = atoi('num_tree_per_iteration', this.num_class);
  2940. this.label_index = atoi('label_index');
  2941. this.max_feature_idx = atoi('max_feature_idx');
  2942. if (key_vals.has('average_output')) {
  2943. this.average_output = true;
  2944. }
  2945. this.feature_names = list('feature_names', this.max_feature_idx + 1);
  2946. this.feature_infos = list('feature_infos', this.max_feature_idx + 1);
  2947. if (key_vals.has('monotone_constraints')) {
  2948. this.monotone_constraints = list('monotone_constraints', this.max_feature_idx + 1);
  2949. }
  2950. if (key_vals.has('objective')) {
  2951. this.objective = key_vals.get('objective');
  2952. }
  2953. let tree = null;
  2954. while (lines.length > 0) {
  2955. const text = lines.shift();
  2956. const line = text.trim();
  2957. if (line.length === 0) {
  2958. continue;
  2959. }
  2960. if (line.startsWith('Tree=')) {
  2961. tree = { index: parseInt(line.split('=').pop(), 10) };
  2962. this.models.push(tree);
  2963. continue;
  2964. }
  2965. if (line === 'end of trees') {
  2966. break;
  2967. }
  2968. const param = line.split('=');
  2969. if (param.length !== 2) {
  2970. throw new python.Error(`Invalid property '${line}'.`);
  2971. }
  2972. const name = param[0].trim();
  2973. const value = param[1].trim();
  2974. tree[name] = value;
  2975. }
  2976. const ss = [];
  2977. let is_inparameter = false;
  2978. while (lines.length > 0) {
  2979. const text = lines.shift();
  2980. const line = text.trim();
  2981. if (line === 'parameters:') {
  2982. is_inparameter = true;
  2983. continue;
  2984. } else if (line === 'end of parameters') {
  2985. break;
  2986. } else if (is_inparameter) {
  2987. ss.push(line);
  2988. }
  2989. }
  2990. if (ss.length > 0) {
  2991. this.loaded_parameter = ss.join('\n');
  2992. }
  2993. }
  2994. });
  2995. this.registerFunction('megengine.functional.elemwise.clip', () => {});
  2996. this.registerFunction('megengine.functional.elemwise.sqrt', () => {});
  2997. this.registerFunction('megengine.functional.nn.conv2d', () => {});
  2998. this.registerFunction('megengine.functional.nn.relu', () => {});
  2999. this.registerFunction('megengine.functional.nn.sigmoid', () => {});
  3000. this.registerFunction('megengine.functional.tensor.arange', () => {});
  3001. this.registerFunction('megengine.functional.tensor.broadcast_to', () => {});
  3002. this.registerFunction('megengine.functional.tensor.concat', () => {});
  3003. this.registerFunction('megengine.functional.tensor.expand_dims', () => {});
  3004. this.registerFunction('megengine.functional.tensor.flatten', () => {});
  3005. this.registerFunction('megengine.functional.tensor.full', () => {});
  3006. this.registerFunction('megengine.functional.tensor.reshape', () => {});
  3007. this.registerFunction('megengine.functional.tensor.split', () => {});
  3008. this.registerFunction('megengine.functional.tensor.stack', () => {});
  3009. this.registerFunction('megengine.functional.tensor.transpose', () => {});
  3010. this.registerFunction('megengine.functional.vision.interpolate', () => {});
  3011. this.registerFunction('megengine.module.qat.module.QATModule._apply_fakequant_with_observer', () => {});
  3012. this.registerType('megengine.core._imperative_rt.common.CompNode', class {});
  3013. this.registerType('megengine.core._imperative_rt.ops.ElemwiseMultiType', class {});
  3014. this.registerType('megengine.core._imperative_rt.ops.FakeQuant', class {});
  3015. this.registerType('megengine.core._imperative_rt.ops.GetVarShape', class {});
  3016. this.registerType('megengine.core._imperative_rt.ops.Resize', class {});
  3017. this.registerType('megengine.core.ops._internal.param_defs.ConvolutionV0.Mode', class {});
  3018. this.registerType('megengine.core.ops._internal.param_defs.Convolution.ComputeMode', class {});
  3019. this.registerType('megengine.distributed.group.Group', class {});
  3020. this.registerType('megengine.module.activation.ReLU', class {});
  3021. this.registerType('megengine.module.activation.Softmax', class {});
  3022. this.registerType('megengine.module.adaptive_pooling.AdaptiveAvgPool2d', class {});
  3023. this.registerType('megengine.module.batchnorm.BatchNorm1d', class {});
  3024. this.registerType('megengine.module.batchnorm.BatchNorm2d', class {});
  3025. this.registerType('megengine.module.conv.Conv2d', class {});
  3026. this.registerType('megengine.module.conv.ConvTranspose2d', class {});
  3027. this.registerType('megengine.module.conv_bn.ConvBn2d', class {});
  3028. this.registerType('megengine.module.dropout.Dropout', class {});
  3029. this.registerType('megengine.module.identity.Identity', class {});
  3030. this.registerType('megengine.module.linear.Linear', class {});
  3031. this.registerType('megengine.module.module.Module', class {});
  3032. this.registerType('megengine.module.normalization.InstanceNorm', class {});
  3033. this.registerType('megengine.module.normalization.GroupNorm', class {});
  3034. this.registerType('megengine.module.normalization.LayerNorm', class {});
  3035. this.registerType('megengine.module.pooling.AvgPool2d', class {});
  3036. this.registerType('megengine.module.pooling.MaxPool2d', class {});
  3037. this.registerType('megengine.module.qat.concat.Concat', class {});
  3038. this.registerType('megengine.module.qat.elemwise.Elemwise', class {});
  3039. this.registerType('megengine.module.sequential.Sequential', class {});
  3040. this.registerType('megengine.quantization.fake_quant.FakeQuantize', class {});
  3041. this.registerType('megengine.quantization.fake_quant.LSQ', class {});
  3042. this.registerType('megengine.quantization.fake_quant.TQT', class {});
  3043. this.registerType('megengine.quantization.utils.QParams', class {});
  3044. this.registerType('megengine.quantization.utils.QuantMode', class {});
  3045. this.registerType('megengine.quantization.observer.ExponentialMovingAverageObserver', class {});
  3046. this.registerType('megengine.quantization.observer.HistogramObserver', class {});
  3047. this.registerType('megengine.quantization.observer.MinMaxObserver', class {});
  3048. this.registerType('megengine.quantization.observer.PassiveObserver', class {});
  3049. this.registerType('megengine.quantization.observer.SyncExponentialMovingAverageObserver', class {});
  3050. this.registerType('megengine.quantization.observer.SyncMinMaxObserver', class {});
  3051. this.registerType('megengine.traced_module.expr.Apply', class {});
  3052. this.registerType('megengine.traced_module.expr.CallFunction', class {});
  3053. this.registerType('megengine.traced_module.expr.CallMethod', class {});
  3054. this.registerType('megengine.traced_module.expr.Constant', class {});
  3055. this.registerType('megengine.traced_module.expr.GetAttr', class {});
  3056. this.registerType('megengine.traced_module.expr.Input', class {});
  3057. this.registerType('megengine.traced_module.fake_quant.FakeQuantize', class {});
  3058. this.registerType('megengine.traced_module.node.ModuleNode', class {});
  3059. this.registerType('megengine.traced_module.node.NodeMixin', class {});
  3060. this.registerType('megengine.traced_module.node.TensorNode', class {});
  3061. this.registerType('megengine.traced_module.pytree.ArgsIndex', class {});
  3062. this.registerType('megengine.traced_module.serialization._ModuleState', class {});
  3063. this.registerType('megengine.traced_module.traced_module.InternalGraph', class {});
  3064. this.registerType('megengine.traced_module.traced_module.NameSpace', class {});
  3065. this.registerType('megengine.traced_module.traced_module.TracedModule', class {});
  3066. this.registerType('megengine.tensor.Parameter', class {
  3067. constructor(data, dtype, device) {
  3068. this.data = data;
  3069. this.dtype = dtype;
  3070. this.device = device;
  3071. }
  3072. });
  3073. this.registerType('megengine.traced_module.pytree.TreeDef', class {
  3074. toString() {
  3075. let content = '';
  3076. for (const child of this.children_defs) {
  3077. content += `${child},`;
  3078. }
  3079. if (typeof this.type === "string") {
  3080. return `${this.type.split(".").slice(-1)}(${content})`;
  3081. }
  3082. return `${this.type.__name__}(${content})`;
  3083. }
  3084. });
  3085. this.registerType('megengine.traced_module.pytree.LeafDef', class {
  3086. toString() {
  3087. let content = '';
  3088. if (this.const_val === null) {
  3089. content += '[';
  3090. } else {
  3091. content += this.const_val;
  3092. }
  3093. for (const t of Object.values(this.type)) {
  3094. content += t.__name__;
  3095. }
  3096. content += ']';
  3097. return content;
  3098. }
  3099. });
  3100. this.registerType('megengine.tensor.Tensor', class {
  3101. constructor(data, dtype, device) {
  3102. this.data = data;
  3103. this.dtype = dtype;
  3104. this.device = device;
  3105. }
  3106. });
  3107. this.registerType('megengine.core.tensor.dtype.QuantDtypeMeta', class {
  3108. constructor(name, cname, np_dtype, qmin, qmax, is_signed) {
  3109. this.name = name;
  3110. this.cname = cname;
  3111. this.np_dtype = np_dtype;
  3112. this.qmin = qmin;
  3113. this.qmax = qmax;
  3114. this.is_signed = is_signed;
  3115. }
  3116. });
  3117. this.registerType('nolearn.lasagne.base.BatchIterator', class {});
  3118. this.registerType('nolearn.lasagne.base.Layers', class {});
  3119. this.registerType('nolearn.lasagne.base.NeuralNet', class {});
  3120. this.registerType('nolearn.lasagne.base.TrainSplit', class {});
  3121. this.registerType('nolearn.lasagne.handlers.PrintLayerInfo', class {});
  3122. this.registerType('nolearn.lasagne.handlers.PrintLog', class {});
  3123. this.registerType('numpy.ndarray', class {
  3124. constructor(shape, dtype, buffer, offset, strides, order) {
  3125. this.shape = shape;
  3126. this.dtype = dtype;
  3127. this.data = buffer === undefined ? null : buffer;
  3128. this.offset = offset === undefined ? 0 : offset;
  3129. this._strides = strides === undefined ? null : strides;
  3130. this.order = order === undefined ? null : order;
  3131. this.flags = {};
  3132. this._read();
  3133. }
  3134. static __new__(cls, shape, dtype, buffer, offset, strides, order) {
  3135. return new cls(shape, dtype, buffer, offset, strides, order);
  3136. }
  3137. __setstate__(state) {
  3138. [this.version, this.shape, this.dtype, this.flags.fn, this.data] = state;
  3139. this._read();
  3140. }
  3141. flatten() {
  3142. const size = this.shape.reduce((a, b) => a * b, 1);
  3143. const value = new numpy.ndarray([size], this.dtype, this.data, this.offset, this.strides, this.order);
  3144. value.flags = this.flags;
  3145. return value;
  3146. }
  3147. reshape(shape, order) {
  3148. return new numpy.ndarray(shape, this.dtype, this.data, this.offset, this.strides, order);
  3149. }
  3150. tobytes() {
  3151. return this.data;
  3152. }
  3153. tolist() {
  3154. if (this.shape.length < 0 || this.shape.length > 1) {
  3155. throw new python.Error(`Unsupported shape '${JSON.stringify(this.shape)}'.`);
  3156. }
  3157. const size = this.shape.reduce((a, b) => a * b, 1);
  3158. const list = new Array(size);
  3159. switch (this.dtype.kind) {
  3160. case 'U': {
  3161. const data = new Uint32Array(new Uint8Array(this.data).buffer);
  3162. const itemsize = this.dtype.itemsize >> 2;
  3163. let offset = 0;
  3164. for (let i = 0; i < size; i++) {
  3165. const buffer = data.subarray(offset, offset + itemsize);
  3166. const index = buffer.indexOf(0);
  3167. list[i] = Array.from(index >= 0 ? buffer.subarray(0, index) : buffer).map((c) => String.fromCodePoint(c)).join('');
  3168. offset += itemsize;
  3169. }
  3170. return list;
  3171. }
  3172. case 'S': {
  3173. const data = this.data;
  3174. const itemsize = this.dtype.itemsize;
  3175. const decoder = new TextDecoder('utf-8');
  3176. let offset = 0;
  3177. for (let i = 0; i < size; i++) {
  3178. const buffer = data.subarray(offset, offset + itemsize);
  3179. const index = buffer.indexOf(0);
  3180. list[i] = decoder.decode(index >= 0 ? buffer.subarray(0, index) : buffer);
  3181. offset += itemsize;
  3182. }
  3183. return list;
  3184. }
  3185. case 'V': {
  3186. const itemsize = this.dtype.itemsize;
  3187. let offset = 0;
  3188. for (let i = 0; i < size; i++) {
  3189. list[i] = this.data.slice(offset, offset + itemsize);
  3190. offset += itemsize;
  3191. }
  3192. return list;
  3193. }
  3194. case 'M': {
  3195. const itemsize = this.dtype.itemsize;
  3196. let offset = 0;
  3197. for (let i = 0; i < size; i++) {
  3198. const buffer = this.data.slice(offset, offset + itemsize);
  3199. list[i] = new numpy.datetime64(buffer);
  3200. offset += itemsize;
  3201. }
  3202. return list;
  3203. }
  3204. case 'T': {
  3205. return this.data;
  3206. }
  3207. case 'O': {
  3208. return this.data;
  3209. }
  3210. default: {
  3211. throw new python.Error(`Type kind '${this.dtype.kind}' not implemented.`);
  3212. }
  3213. }
  3214. }
  3215. get itemsize() {
  3216. return this.dtype.itemsize;
  3217. }
  3218. get size() {
  3219. return (this.shape || []).reduce((a, b) => a * b, 1);
  3220. }
  3221. get strides() {
  3222. if (!this._strides) {
  3223. const shape = this.shape;
  3224. const strides = new Array(shape.length);
  3225. let stride = this.itemsize;
  3226. if (this.order === 'F' || this.flags.fn) {
  3227. for (let i = 0; i < shape.length; i++) {
  3228. strides[i] = stride;
  3229. stride *= shape[i];
  3230. }
  3231. } else {
  3232. for (let i = shape.length - 1; i >= 0; i--) {
  3233. strides[i] = stride;
  3234. stride *= shape[i];
  3235. }
  3236. }
  3237. return strides;
  3238. }
  3239. return this._strides;
  3240. }
  3241. _read() {
  3242. if (this.data) {
  3243. const length = this.dtype.itemsize * this.size;
  3244. if (typeof this.data === 'string') {
  3245. this.data = this._unescape(this.data, length);
  3246. if (this.data.length !== length) {
  3247. throw new python.Error('Invalid string array data size.');
  3248. }
  3249. } else if (this.data.length !== length) {
  3250. // throw new python.Error('Invalid array data size.');
  3251. }
  3252. }
  3253. }
  3254. _unescape(token, size) {
  3255. const length = token.length;
  3256. const a = new Uint8Array(length);
  3257. if (size && size === length) {
  3258. for (let p = 0; p < size; p++) {
  3259. a[p] = token.charCodeAt(p);
  3260. }
  3261. return a;
  3262. }
  3263. let i = 0;
  3264. let o = 0;
  3265. while (i < length) {
  3266. let c = token.charCodeAt(i++);
  3267. if (c !== 0x5C || i >= length) {
  3268. a[o++] = c;
  3269. } else {
  3270. c = token.charCodeAt(i++);
  3271. switch (c) {
  3272. case 0x27: a[o++] = 0x27; break; // '
  3273. case 0x5C: a[o++] = 0x5C; break; // \\
  3274. case 0x22: a[o++] = 0x22; break; // "
  3275. case 0x72: a[o++] = 0x0D; break; // \r
  3276. case 0x6E: a[o++] = 0x0A; break; // \n
  3277. case 0x74: a[o++] = 0x09; break; // \t
  3278. case 0x62: a[o++] = 0x08; break; // \b
  3279. case 0x58: // x
  3280. case 0x78: { // X
  3281. const xsi = i - 1;
  3282. const xso = o;
  3283. for (let xi = 0; xi < 2; xi++) {
  3284. if (i >= length) {
  3285. i = xsi;
  3286. o = xso;
  3287. a[o] = 0x5c;
  3288. break;
  3289. }
  3290. let c = token.charCodeAt(i++);
  3291. if (c >= 65 && c <= 70) {
  3292. c -= 55;
  3293. } else if (c >= 97 && c <= 102) {
  3294. c -= 87;
  3295. } else if (c >= 48 && c <= 57) {
  3296. c -= 48;
  3297. } else {
  3298. c = -1;
  3299. }
  3300. if (c === -1) {
  3301. i = xsi;
  3302. o = xso;
  3303. a[o] = 0x5c;
  3304. break;
  3305. }
  3306. a[o] = a[o] << 4 | c;
  3307. }
  3308. o++;
  3309. break;
  3310. }
  3311. default:
  3312. if (c < 48 || c > 57) { // 0-9
  3313. a[o++] = 0x5c;
  3314. a[o++] = c;
  3315. } else {
  3316. i--;
  3317. const osi = i;
  3318. const oso = o;
  3319. for (let oi = 0; oi < 3; oi++) {
  3320. if (i >= length) {
  3321. i = osi;
  3322. o = oso;
  3323. a[o] = 0x5c;
  3324. break;
  3325. }
  3326. const od = token.charCodeAt(i++);
  3327. if (od < 48 || od > 57) {
  3328. i = osi;
  3329. o = oso;
  3330. a[o] = 0x5c;
  3331. break;
  3332. }
  3333. a[o] = a[o] << 3 | od - 48;
  3334. }
  3335. o++;
  3336. }
  3337. break;
  3338. }
  3339. }
  3340. }
  3341. return a.slice(0, o);
  3342. }
  3343. });
  3344. this.registerType('numpy.matrix', class extends numpy.ndarray {
  3345. static __new__(/* subtype, data, dtype, copy */) {
  3346. throw new python.Error("'numpy.matrix.__new__' not implemented.");
  3347. }
  3348. });
  3349. numpy.matrixlib.defmatrix.matrix = numpy.matrix;
  3350. this.registerType('numpy.ma.core.MaskedArray', class extends numpy.ndarray {
  3351. constructor(data /*, mask, dtype, copy, subok, ndmin, fill_value, keep_mask, hard_mask, shrink, order */) {
  3352. super(data.shape, data.dtype, data.data);
  3353. }
  3354. });
  3355. this.registerType('numpy.core.memmap.memmap', class extends numpy.ndarray {});
  3356. this.registerType('pandas.core.arrays.categorical.Categorical', class {});
  3357. this.registerType('pandas.core.arrays.base.ExtensionArray', class {});
  3358. this.registerType('pandas.core.arrays.masked.BaseMaskedArray', class extends pandas.core.arrays.base.ExtensionArray {});
  3359. this.registerType('pandas.core.arrays.numeric.NumericArray', class extends pandas.core.arrays.masked.BaseMaskedArray {});
  3360. this.registerType('pandas.core.arrays.datetimes.DatetimeArray', class {
  3361. __setstate__(state) {
  3362. [this._dtype, this._ndarray] = state;
  3363. Object.assign(this, Object.fromEntries(state[2]));
  3364. }
  3365. });
  3366. this.registerType('pandas.core.arrays.timedeltas.TimedeltaArray', class {
  3367. __setstate__(state) {
  3368. [this._dtype, this._ndarray] = state;
  3369. Object.assign(this, Object.fromEntries(state[2]));
  3370. }
  3371. });
  3372. this.registerType('pandas.core.arrays.period.PeriodArray', class {
  3373. __setstate__(state) {
  3374. [this._dtype, this._ndarray] = state;
  3375. Object.assign(this, Object.fromEntries(state[2]));
  3376. }
  3377. });
  3378. this.registerType('pandas.core.arrays.interval.IntervalArray', class {});
  3379. this.registerType('pandas.core.arrays.integer.IntegerArray', class extends pandas.core.arrays.numeric.NumericArray {});
  3380. this.registerType('pandas.core.arrays.integer.Int64Dtype', class {});
  3381. this.registerType('pandas._libs.tslibs.dtypes.PeriodDtypeBase', class {});
  3382. this.registerType('pandas.core.dtypes.dtypes.PeriodDtype', class extends pandas._libs.tslibs.dtypes.PeriodDtypeBase {});
  3383. this.registerType('pandas.core.dtypes.dtypes.IntervalDtype', class {});
  3384. this.registerType('pandas.core.generic.Flags', class {});
  3385. this.registerType('pandas.core.generic.NDFrame', class {
  3386. constructor(data) {
  3387. this._internal_names = ["_mgr", "_item_cache", "_cache", "_name", "_metadata", "_flags"];
  3388. this._metadata = [];
  3389. builtins.object.__setattr__(self, "_mgr", data);
  3390. builtins.object.__setattr__(self, "_attrs", {});
  3391. builtins.object.__setattr__(self, "_flags", new pandas.core.generic.Flags(this, true));
  3392. }
  3393. __setstate__(state) {
  3394. if (state instanceof pandas.core.internals.managers.BlockManager) {
  3395. this._mgr = state;
  3396. } else if (state instanceof builtins.dict) {
  3397. if (state.__contains__('_data') && !state.__contains__('_mgr')) {
  3398. state.__setitem__('_mgr', state.pop('_data'));
  3399. }
  3400. const typ = state.get('_typ');
  3401. if (typ) {
  3402. let attrs = state.get('_attrs', new builtins.dict());
  3403. if (!attrs) {
  3404. attrs = new builtins.dict();
  3405. }
  3406. builtins.object.__setattr__(this, '_attrs', attrs);
  3407. const flags = state.get('_flags', new builtins.dict({ 'allows_duplicate_labels': true }));
  3408. builtins.object.__setattr__(this, '_flags', new pandas.core.generic.Flags(this, flags));
  3409. const meta = new builtins.set(this._internal_names.concat(this._metadata));
  3410. for (const k of meta) {
  3411. if (state.__contains__(k) && k !== '_flags') {
  3412. const v = state.__getitem__(k);
  3413. builtins.object.__setattr__(this, k, v);
  3414. }
  3415. }
  3416. for (const [k, v] of state) {
  3417. if (!meta.has(k)) {
  3418. builtins.object.__setattr__(this, k, v);
  3419. }
  3420. }
  3421. } else {
  3422. throw new python.Error('Pre-0.12 pickles are no longer supported.');
  3423. }
  3424. } else if (state.size === 2) {
  3425. throw new python.Error('Pre-0.12 pickles are no longer supported.');
  3426. }
  3427. }
  3428. });
  3429. this.registerType('pandas.core.frame.DataFrame', class extends pandas.core.generic.NDFrame {
  3430. });
  3431. this.registerFunction('pandas.core.indexes.base._new_Index', (cls, d) => {
  3432. return new cls(d);
  3433. });
  3434. this.registerType('pandas.core.indexes.datetimes._new_DatetimeIndex', class {});
  3435. this.registerType('pandas.core.indexes.datetimes.DatetimeIndex', class {});
  3436. this.registerType('pandas.core.indexes.base.Index', class {});
  3437. this.registerType('pandas.core.indexes.range.RangeIndex', class {});
  3438. this.registerType('pandas.core.indexes.multi.MultiIndex', class {});
  3439. this.registerType('pandas.core.indexes.numeric.Int64Index', class {});
  3440. this.registerType('pandas.core.index.Int64Index', class {});
  3441. this.registerFunction('pandas.core.internals.blocks.Block', class {
  3442. });
  3443. this.registerFunction('pandas.core.internals.blocks.NumpyBlock', class extends pandas.core.internals.blocks.Block {
  3444. });
  3445. this.registerFunction('pandas.core.internals.blocks.get_block_type', (/* dtype */) => {
  3446. return pandas.core.internals.blocks.NumpyBlock;
  3447. });
  3448. this.registerFunction('pandas.core.internals.blocks.maybe_coerce_values', (values) => {
  3449. return values;
  3450. });
  3451. this.registerFunction('pandas.core.internals.blocks.new_block', (values, placement, ndim, refs) => {
  3452. const klass = execution.invoke('pandas.core.internals.blocks.get_block_type', [values.dtype]);
  3453. return new klass(values, ndim, placement, refs);
  3454. });
  3455. this.registerType('pandas.core.internals.managers.SingleBlockManager', class {});
  3456. this.registerType('pandas.core.internals.managers.BlockManager', class {});
  3457. this.registerType('pandas.core.series.Series', class {});
  3458. this.registerFunction('pandas._libs.arrays.__pyx_unpickle_NDArrayBacked', (cls, checksum, state) => {
  3459. const obj = new cls();
  3460. if (state && obj.__setstate__) {
  3461. obj.__setstate__(state);
  3462. }
  3463. return obj;
  3464. });
  3465. this.registerFunction('pandas._libs.interval.__pyx_unpickle_IntervalMixin', (cls, checksum, state) => {
  3466. const obj = new cls();
  3467. if (state && obj.__setstate__) {
  3468. obj.__setstate__(state);
  3469. }
  3470. return obj;
  3471. });
  3472. this.registerFunction('pandas._libs.internals._unpickle_block', (values, placement, ndim) => {
  3473. values = pandas.core.internals.blocks.maybe_coerce_values(values);
  3474. // if not isinstance(placement, BlockPlacement):
  3475. // placement = BlockPlacement(placement)
  3476. return pandas.core.internals.blocks.new_block(values, placement, ndim);
  3477. });
  3478. this.registerType('pandas._libs.tslibs.base.ABCTimestamp', class extends datetime.datetime {});
  3479. this.registerType('pandas._libs.tslibs.offsets.BaseOffset', class {});
  3480. this.registerType('pandas._libs.tslibs.offsets.SingleConstructorOffset', class extends pandas._libs.tslibs.offsets.BaseOffset {});
  3481. this.registerType('pandas._libs.tslibs.offsets.Tick', class extends pandas._libs.tslibs.offsets.SingleConstructorOffset {});
  3482. this.registerType('pandas._libs.tslibs.offsets.Day', class extends pandas._libs.tslibs.offsets.Tick {});
  3483. this.registerType('pandas._libs.tslibs.offsets.Minute', class extends datetime.datetime {});
  3484. this.registerFunction('pandas._libs.tslibs.timestamps._unpickle_timestamp');
  3485. this.registerType('pandas._libs.tslibs.timestamps._Timestamp', class extends pandas._libs.tslibs.base.ABCTimestamp {});
  3486. this.registerType('pandas._libs.tslibs.timestamps.Timestamp', class extends pandas._libs.tslibs.timestamps._Timestamp {});
  3487. pandas.indexes.base._new_Index = pandas.core.indexes.base._new_Index;
  3488. pandas.indexes.base.Index = pandas.core.indexes.base.Index;
  3489. pandas.indexes.range.RangeIndex = pandas.core.indexes.range.RangeIndex;
  3490. pandas.core.index.Index = pandas.core.indexes.base.Index;
  3491. pandas.core.index._new_Index = pandas.core.indexes.base._new_Index;
  3492. pandas.core.internals.BlockManager = pandas.core.internals.managers.BlockManager;
  3493. pandas._libs.tslib.Timestamp = pandas._libs.tslibs.timestamps.Timestamp;
  3494. this.registerType('pathlib.Path', class {});
  3495. this.registerType('pathlib._local.PosixPath', class {});
  3496. this.registerType('pathlib._local.WindowsPath', class {});
  3497. const pathlib = this.register('pathlib');
  3498. pathlib.PosixPath = pathlib._local.PosixPath;
  3499. pathlib.WindowsPath = pathlib._local.WindowsPath;
  3500. this.registerType('shap._serializable.Serializable', class {});
  3501. this.registerType('shap.explainers._explainer.Explainer', class extends shap._serializable.Serializable {});
  3502. this.registerType('shap.explainers._linear.LinearExplainer', class extends shap.explainers._explainer.Explainer {});
  3503. shap.explainers.LinearExplainer = shap.explainers._linear.LinearExplainer;
  3504. shap.explainers.linear.LinearExplainer = shap.explainers._linear.LinearExplainer;
  3505. this.registerType('sklearn._loss.link.BaseLink', class {});
  3506. this.registerType('sklearn._loss._loss.__pyx_unpickle_CyHalfBinomialLoss', class {});
  3507. this.registerType('sklearn._loss._loss.__pyx_unpickle_CyHalfMultinomialLoss', class {});
  3508. this.registerType('sklearn._loss._loss.CyLossFunction', class {});
  3509. this.registerType('sklearn._loss._loss.CyHalfBinomialLoss', class {});
  3510. this.registerType('sklearn._loss._loss.CyHalfMultinomialLoss', class {});
  3511. this.registerType('sklearn._loss._loss.CyHalfSquaredError', class extends sklearn._loss._loss.CyLossFunction {});
  3512. this.registerType('sklearn._loss.link.IdentityLink', class extends sklearn._loss.link.BaseLink {});
  3513. this.registerType('sklearn._loss.link.Interval', class {});
  3514. this.registerType('sklearn._loss.link.LogitLink', class {});
  3515. this.registerType('sklearn._loss.link.MultinomialLogit', class extends sklearn._loss.link.BaseLink {});
  3516. this.registerFunction('sklearn._loss._loss.__pyx_unpickle_CyHalfSquaredError');
  3517. this.registerType('sklearn._loss.loss.BaseLoss', class {});
  3518. this.registerType('sklearn._loss.loss.HalfBinomialLoss', class {});
  3519. this.registerType('sklearn._loss.loss.HalfMultinomialLoss', class extends sklearn._loss.loss.BaseLoss {});
  3520. this.registerType('sklearn._loss.loss.HalfSquaredError', class extends sklearn._loss.loss.BaseLoss {});
  3521. this.registerType('sklearn.base.BaseEstimator', class {});
  3522. this.registerType('sklearn.base.TransformerMixin', class {});
  3523. this.registerType('sklearn.calibration._CalibratedClassifier', class {});
  3524. this.registerType('sklearn.calibration._SigmoidCalibration', class {});
  3525. this.registerType('sklearn.calibration.CalibratedClassifierCV', class {});
  3526. this.registerType('sklearn.cluster._agglomerative.FeatureAgglomeration', class {});
  3527. this.registerType('sklearn.cluster._dbscan.DBSCAN', class {});
  3528. this.registerType('sklearn.cluster._kmeans.KMeans', class {});
  3529. this.registerType('sklearn.cluster._kmeans.MiniBatchKMeans', class {});
  3530. this.registerType('sklearn.cluster.k_means_.MiniBatchKMeans', class {});
  3531. this.registerType('sklearn.compose._column_transformer._RemainderColsList', class {});
  3532. this.registerType('sklearn.compose._column_transformer.ColumnTransformer', class {});
  3533. this.registerType('sklearn.compose._column_transformer.make_column_selector', class {});
  3534. this.registerType('sklearn.compose._target.TransformedTargetRegressor', class {});
  3535. this.registerType('sklearn.cross_decomposition._pls.PLSRegression', class {});
  3536. this.registerType('sklearn.cross_decomposition._pls.CCA', class {});
  3537. this.registerType('sklearn.decomposition._fastica.FastICA', class {});
  3538. this.registerType('sklearn.decomposition._incremental_pca.IncrementalPCA', class {});
  3539. this.registerType('sklearn.decomposition._pca.PCA', class {});
  3540. this.registerType('sklearn.decomposition._truncated_svd.TruncatedSVD', class {});
  3541. this.registerType('sklearn.decomposition.pca.PCA', class {});
  3542. this.registerType('sklearn.decomposition.PCA', class {});
  3543. this.registerType('sklearn.decomposition.truncated_svd.TruncatedSVD', class {});
  3544. this.registerType('sklearn.discriminant_analysis.LinearDiscriminantAnalysis', class {});
  3545. this.registerType('sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis', class {});
  3546. this.registerType('sklearn.dummy.DummyClassifier', class {});
  3547. this.registerType('sklearn.dummy.DummyRegressor', class {});
  3548. this.registerType('sklearn.ensemble._bagging.BaggingClassifier', class {});
  3549. this.registerType('sklearn.ensemble._bagging.BaggingRegressor', class {});
  3550. this.registerType('sklearn.ensemble._forest.RandomForestClassifier', class {});
  3551. this.registerType('sklearn.ensemble._forest.RandomForestRegressor', class {});
  3552. this.registerType('sklearn.ensemble._forest.ExtraTreesClassifier', class {});
  3553. this.registerType('sklearn.ensemble._forest.ExtraTreesRegressor', class {});
  3554. this.registerType('sklearn.ensemble._gb_losses.BinomialDeviance', class {});
  3555. this.registerType('sklearn.ensemble._gb_losses.ExponentialLoss', class {});
  3556. this.registerType('sklearn.ensemble._gb_losses.LeastAbsoluteError', class {});
  3557. this.registerType('sklearn.ensemble._gb_losses.LeastSquaresError', class {});
  3558. this.registerType('sklearn.ensemble._gb_losses.MultinomialDeviance', class {});
  3559. this.registerType('sklearn.ensemble._gb.GradientBoostingClassifier', class {});
  3560. this.registerType('sklearn.ensemble._gb.GradientBoostingRegressor', class {});
  3561. this.registerType('sklearn.ensemble._hist_gradient_boosting.binning._BinMapper', class {});
  3562. this.registerType('sklearn.ensemble._hist_gradient_boosting.gradient_boosting.HistGradientBoostingRegressor', class {});
  3563. this.registerType('sklearn.ensemble._hist_gradient_boosting.gradient_boosting.HistGradientBoostingClassifier', class {});
  3564. this.registerType('sklearn.ensemble._hist_gradient_boosting.loss.LeastSquares', class {});
  3565. this.registerType('sklearn.ensemble._hist_gradient_boosting.predictor.TreePredictor', class {});
  3566. this.registerType('sklearn.ensemble._iforest.IsolationForest', class {});
  3567. this.registerType('sklearn.ensemble._stacking.StackingClassifier', class {});
  3568. this.registerType('sklearn.ensemble._stacking.StackingRegressor', class {});
  3569. this.registerType('sklearn.ensemble._voting.VotingClassifier', class {});
  3570. this.registerType('sklearn.ensemble._voting.VotingRegressor', class {});
  3571. this.registerType('sklearn.ensemble._weight_boosting.AdaBoostClassifier', class {});
  3572. this.registerType('sklearn.ensemble._weight_boosting.AdaBoostRegressor', class {});
  3573. this.registerType('sklearn.ensemble.forest.RandomForestClassifier', class {});
  3574. this.registerType('sklearn.ensemble.forest.RandomForestRegressor', class {});
  3575. this.registerType('sklearn.ensemble.forest.ExtraTreesClassifier', class {});
  3576. this.registerType('sklearn.ensemble.gradient_boosting.BinomialDeviance', class {});
  3577. this.registerType('sklearn.ensemble.gradient_boosting.GradientBoostingClassifier', class {});
  3578. this.registerType('sklearn.ensemble.gradient_boosting.LogOddsEstimator', class {});
  3579. this.registerType('sklearn.ensemble.gradient_boosting.MultinomialDeviance', class {});
  3580. this.registerType('sklearn.ensemble.gradient_boosting.PriorProbabilityEstimator', class {});
  3581. this.registerType('sklearn.ensemble.voting_classifier.VotingClassifier', class {});
  3582. this.registerType('sklearn.ensemble.weight_boosting.AdaBoostClassifier', class {});
  3583. this.registerType('sklearn.feature_extraction._dict_vectorizer.DictVectorizer', class {});
  3584. this.registerType('sklearn.feature_extraction._hashing.FeatureHasher', class {});
  3585. this.registerType('sklearn.feature_extraction._hash.FeatureHasher', class {});
  3586. this.registerType('sklearn.feature_extraction.text.CountVectorizer', class {});
  3587. this.registerType('sklearn.feature_extraction.text.HashingVectorizer', class {});
  3588. this.registerType('sklearn.feature_extraction.text.TfidfTransformer', class {});
  3589. this.registerType('sklearn.feature_extraction.text.TfidfVectorizer', class {});
  3590. this.registerType('sklearn.feature_selection._from_model.SelectFromModel', class {});
  3591. this.registerFunction('sklearn.feature_selection._mutual_info.mutual_info_classif');
  3592. this.registerFunction('sklearn.feature_selection._univariate_selection.chi2');
  3593. this.registerType('sklearn.feature_selection._univariate_selection.GenericUnivariateSelect', class {});
  3594. this.registerType('sklearn.feature_selection._univariate_selection.SelectKBest', class {});
  3595. this.registerType('sklearn.feature_selection._univariate_selection.SelectPercentile', class {});
  3596. this.registerType('sklearn.feature_selection._variance_threshold.VarianceThreshold', class {});
  3597. this.registerType('sklearn.feature_selection._rfe.RFE', class {});
  3598. this.registerType('sklearn.feature_selection._rfe.RFECV', class extends sklearn.feature_selection._rfe.RFE {});
  3599. this.registerType('sklearn.feature_selection.univariate_selection.SelectKBest', class {});
  3600. this.registerType('sklearn.feature_selection.variance_threshold.VarianceThreshold', class {});
  3601. this.registerType('sklearn.gaussian_process._gpc.GaussianProcessClassifier', class {});
  3602. this.registerType('sklearn.gaussian_process._gpr.GaussianProcessRegressor', class {});
  3603. this.registerType('sklearn.gaussian_process.gpc.GaussianProcessClassifier', class {});
  3604. this.registerType('sklearn.gaussian_process.kernels.ConstantKernel', class {});
  3605. this.registerType('sklearn.gaussian_process.kernels.DotProduct', class {});
  3606. this.registerType('sklearn.gaussian_process.kernels.Product', class {});
  3607. this.registerType('sklearn.gaussian_process.kernels.RBF', class {});
  3608. this.registerType('sklearn.gaussian_process.kernels.Sum', class {});
  3609. this.registerType('sklearn.gaussian_process.kernels.WhiteKernel', class {});
  3610. this.registerType('sklearn.grid_search._CVScoreTuple', class {});
  3611. this.registerType('sklearn.grid_search.GridSearchCV', class {});
  3612. this.registerType('sklearn.impute._base.SimpleImputer', class {});
  3613. this.registerType('sklearn.impute._iterative.IterativeImputer', class {});
  3614. this.registerType('sklearn.impute._iterative._ImputerTriplet', class {});
  3615. this.registerType('sklearn.impute.SimpleImputer', class {});
  3616. this.registerType('sklearn.isotonic.IsotonicRegression', class {});
  3617. this.registerType('sklearn.kernel_ridge.KernelRidge', class {});
  3618. this.registerType('sklearn.linear_model._base.LinearRegression', class {});
  3619. this.registerType('sklearn.linear_model._bayes.BayesianRidge', class {});
  3620. this.registerType('sklearn.linear_model._coordinate_descent.ElasticNetCV', class {});
  3621. this.registerType('sklearn.linear_model._coordinate_descent.ElasticNet', class {});
  3622. this.registerType('sklearn.linear_model._coordinate_descent.Lasso', class {});
  3623. this.registerType('sklearn.linear_model._least_angle.LassoLarsCV', class {});
  3624. this.registerType('sklearn.linear_model._logistic.LogisticRegression', class {});
  3625. this.registerType('sklearn.linear_model._logistic.LogisticRegressionCV', class {});
  3626. this.registerType('sklearn.linear_model._perceptron.Perceptron', class {});
  3627. this.registerType('sklearn.linear_model._quantile.QuantileRegressor', class {});
  3628. this.registerType('sklearn.linear_model._ridge.Ridge', class {});
  3629. this.registerType('sklearn.linear_model._ridge.RidgeClassifier', class {});
  3630. this.registerType('sklearn.linear_model._ridge.RidgeClassifierCV', class {});
  3631. this.registerType('sklearn.linear_model._sgd_fast.Hinge', class {});
  3632. this.registerType('sklearn.linear_model._sgd_fast.Log', class {});
  3633. this.registerType('sklearn.linear_model._sgd_fast.ModifiedHuber', class {});
  3634. this.registerType('sklearn.linear_model._sgd_fast.SquaredHinge', class {});
  3635. this.registerType('sklearn.linear_model._stochastic_gradient.SGDClassifier', class {});
  3636. this.registerType('sklearn.linear_model._stochastic_gradient.SGDRegressor', class {});
  3637. this.registerType('sklearn.linear_model.base.LinearRegression', class {});
  3638. this.registerType('sklearn.linear_model.coordinate_descent.ElasticNet', class {});
  3639. this.registerType('sklearn.linear_model.sgd_fast.Hinge', class {});
  3640. this.registerType('sklearn.linear_model.LogisticRegression', class {});
  3641. this.registerType('sklearn.linear_model.logistic.LogisticRegression', class {});
  3642. this.registerType('sklearn.linear_model.logistic.LogisticRegressionCV', class {});
  3643. this.registerType('sklearn.linear_model.LassoLars​', class {});
  3644. this.registerType('sklearn.linear_model.ridge.Ridge', class {});
  3645. this.registerType('sklearn.linear_model.sgd_fast.Log', class {});
  3646. this.registerType('sklearn.linear_model.stochastic_gradient.SGDClassifier', class {});
  3647. this.registerType('sklearn.manifold._t_sne.TSNE', class {});
  3648. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric', class extends builtins.object {});
  3649. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric32', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3650. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric64', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3651. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3652. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance32', class extends sklearn.metrics._dist_metrics.DistanceMetric32 {});
  3653. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance64', class extends sklearn.metrics._dist_metrics.DistanceMetric64 {});
  3654. this.registerType('sklearn.metrics._dist_metrics.ManhattanDistance', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3655. this.registerType('sklearn.metrics._dist_metrics.ManhattanDistance64', class extends sklearn.metrics._dist_metrics.DistanceMetric64 {});
  3656. this.registerType('sklearn.metrics._scorer._PassthroughScorer', class {});
  3657. this.registerType('sklearn.metrics._scorer._PredictScorer', class {});
  3658. this.registerType('sklearn.metrics.scorer._PredictScorer', class {});
  3659. this.registerType('sklearn.metrics._scorer._ThresholdScorer', class {});
  3660. this.registerType('sklearn.metrics._scorer._Scorer', class {});
  3661. this.registerType('sklearn.mixture._bayesian_mixture.BayesianGaussianMixture', class {});
  3662. this.registerType('sklearn.mixture._gaussian_mixture.GaussianMixture', class {});
  3663. this.registerType('sklearn.model_selection._search.GridSearchCV', class {});
  3664. this.registerType('sklearn.model_selection._search.RandomizedSearchCV', class {});
  3665. this.registerType('sklearn.model_selection._split.KFold', class {});
  3666. this.registerType('sklearn.model_selection._split.PredefinedSplit', class {});
  3667. this.registerType('sklearn.model_selection._split.RepeatedKFold', class {});
  3668. this.registerType('sklearn.model_selection._split.StratifiedKFold', class {});
  3669. this.registerType('sklearn.model_selection._split.StratifiedShuffleSplit', class {});
  3670. this.registerType('sklearn.model_selection._split.TimeSeriesSplit', class {});
  3671. this.registerType('sklearn.multiclass.OneVsRestClassifier', class {});
  3672. this.registerType('sklearn.multioutput.ClassifierChain', class {});
  3673. this.registerType('sklearn.multioutput.MultiOutputClassifier', class {});
  3674. this.registerType('sklearn.multioutput.MultiOutputRegressor', class {});
  3675. this.registerType('sklearn.naive_bayes.BernoulliNB', class {});
  3676. this.registerType('sklearn.naive_bayes.ComplementNB', class {});
  3677. this.registerType('sklearn.naive_bayes.GaussianNB', class {});
  3678. this.registerType('sklearn.naive_bayes.MultinomialNB', class {});
  3679. this.registerType('sklearn.neighbors.ball_tree.BallTree', class {});
  3680. this.registerFunction('sklearn.neighbors.ball_tree.newObj', (obj) => {
  3681. return obj.__new__(obj);
  3682. });
  3683. this.registerType('sklearn.neighbors._classification.KNeighborsClassifier', class {});
  3684. this.registerFunction('sklearn.neighbors._dist_metrics.newObj');
  3685. this.registerType('sklearn.neighbors._dist_metrics.EuclideanDistance', class {});
  3686. this.registerType('sklearn.neighbors._kd_tree.BinaryTree64', class extends builtins.object {});
  3687. this.registerType('sklearn.neighbors._kd_tree.KDTree64', class extends sklearn.neighbors._kd_tree.BinaryTree64 {});
  3688. this.registerType('sklearn.neighbors._kd_tree.KDTree', class extends sklearn.neighbors._kd_tree.KDTree64 {});
  3689. this.registerFunction('sklearn.neighbors._kd_tree.newObj', (obj) => {
  3690. return obj.__new__(obj);
  3691. });
  3692. this.registerType('sklearn.neighbors._regression.KNeighborsRegressor', class {});
  3693. this.registerType('sklearn.neighbors._unsupervised.NearestNeighbors', class {});
  3694. this.registerType('sklearn.neighbors.classification.KNeighborsClassifier', class {});
  3695. this.registerFunction('sklearn.neighbors.dist_metrics.newObj', (obj) => {
  3696. return obj.__new__(obj);
  3697. });
  3698. this.registerType('sklearn.neighbors.dist_metrics.EuclideanDistance', class {});
  3699. this.registerFunction('sklearn.neighbors.kd_tree.newObj', (obj) => {
  3700. return obj.__new__(obj);
  3701. });
  3702. this.registerType('sklearn.neighbors.kd_tree.KDTree', class {});
  3703. this.registerType('sklearn.neighbors.KNeighborsClassifier', class {});
  3704. this.registerType('sklearn.neighbors.KNeighborsRegressor', class {});
  3705. this.registerType('sklearn.neighbors.regression.KNeighborsRegressor', class {});
  3706. this.registerType('sklearn.neighbors.unsupervised.NearestNeighbors', class {});
  3707. this.registerType('sklearn.neural_network._multilayer_perceptron.MLPClassifier', class {});
  3708. this.registerType('sklearn.neural_network._multilayer_perceptron.MLPRegressor', class {});
  3709. this.registerType('sklearn.neural_network._stochastic_optimizers.AdamOptimizer', class {});
  3710. this.registerType('sklearn.neural_network._stochastic_optimizers.SGDOptimizer', class {});
  3711. this.registerType('sklearn.neural_network.rbm.BernoulliRBM', class {});
  3712. this.registerType('sklearn.neural_network.multilayer_perceptron.MLPClassifier', class {});
  3713. this.registerType('sklearn.neural_network.multilayer_perceptron.MLPRegressor', class {});
  3714. this.registerType('sklearn.neural_network.stochastic_gradient.SGDClassifier', class {});
  3715. this.registerType('sklearn.pipeline.Pipeline', class {});
  3716. this.registerType('sklearn.pipeline.FeatureUnion', class {});
  3717. this.registerType('sklearn.preprocessing._data.MinMaxScaler', class {});
  3718. this.registerType('sklearn.preprocessing._data.MaxAbsScaler', class {});
  3719. this.registerType('sklearn.preprocessing._data.Normalizer', class {});
  3720. this.registerType('sklearn.preprocessing._data.PolynomialFeatures', class {});
  3721. this.registerType('sklearn.preprocessing._data.PowerTransformer', class {});
  3722. this.registerType('sklearn.preprocessing._data.QuantileTransformer', class {});
  3723. this.registerType('sklearn.preprocessing._data.RobustScaler', class {});
  3724. this.registerType('sklearn.preprocessing._data.StandardScaler', class {});
  3725. this.registerType('sklearn.preprocessing._discretization.KBinsDiscretizer', class {});
  3726. this.registerType('sklearn.preprocessing._encoders.OneHotEncoder', class {});
  3727. this.registerType('sklearn.preprocessing._encoders.OrdinalEncoder', class {});
  3728. this.registerType('sklearn.preprocessing._function_transformer.FunctionTransformer', class {});
  3729. this.registerType('sklearn.preprocessing._label.LabelBinarizer', class {});
  3730. this.registerType('sklearn.preprocessing._label.LabelEncoder', class {});
  3731. this.registerType('sklearn.preprocessing._label.MultiLabelBinarizer', class {});
  3732. this.registerType('sklearn.preprocessing._polynomial.PolynomialFeatures', class {});
  3733. this.registerType('sklearn.preprocessing.data.Binarizer', class {});
  3734. this.registerType('sklearn.preprocessing.data.MaxAbsScaler', class {});
  3735. this.registerType('sklearn.preprocessing.data.MinMaxScaler', class {});
  3736. this.registerType('sklearn.preprocessing.data.Normalizer', class {});
  3737. this.registerType('sklearn.preprocessing.data.OneHotEncoder', class {});
  3738. this.registerType('sklearn.preprocessing.data.PolynomialFeatures', class {});
  3739. this.registerType('sklearn.preprocessing.data.PowerTransformer', class {});
  3740. this.registerType('sklearn.preprocessing.data.RobustScaler', class {});
  3741. this.registerType('sklearn.preprocessing.data.QuantileTransformer', class {});
  3742. this.registerType('sklearn.preprocessing.data.StandardScaler', class {});
  3743. this.registerType('sklearn.preprocessing.imputation.Imputer', class {});
  3744. this.registerType('sklearn.preprocessing.label.LabelBinarizer', class {});
  3745. this.registerType('sklearn.preprocessing.label.LabelEncoder', class {});
  3746. this.registerType('sklearn.preprocessing.label.MultiLabelBinarizer', class {});
  3747. this.registerType('sklearn.random_projection.GaussianRandomProjection', class {});
  3748. this.registerType('sklearn.svm._classes.LinearSVC', class {});
  3749. this.registerType('sklearn.svm._classes.NuSVC', class {});
  3750. this.registerType('sklearn.svm._classes.OneClassSVM', class {});
  3751. this.registerType('sklearn.svm._classes.SVC', class {});
  3752. this.registerType('sklearn.svm._classes.SVR', class {});
  3753. this.registerType('sklearn.svm.classes.LinearSVC', class {});
  3754. this.registerType('sklearn.svm.classes.OneClassSVM', class {});
  3755. this.registerType('sklearn.svm.classes.SVC', class {});
  3756. this.registerType('sklearn.svm.classes.SVR', class {});
  3757. this.registerType('sklearn.tree._classes.DecisionTreeClassifier', class {});
  3758. this.registerType('sklearn.tree._classes.DecisionTreeRegressor', class {});
  3759. this.registerType('sklearn.tree._classes.ExtraTreeClassifier', class {});
  3760. this.registerType('sklearn.tree._classes.ExtraTreeRegressor', class {});
  3761. this.registerType('sklearn.tree._tree.Tree', class {
  3762. constructor(n_features, n_classes, n_outputs) {
  3763. this.n_features = n_features;
  3764. this.n_classes = n_classes;
  3765. this.n_outputs = n_outputs;
  3766. }
  3767. __setstate__(state) {
  3768. this.max_depth = state.get('max_depth');
  3769. this.node_count = state.get('node_count');
  3770. this.nodes = state.get('nodes');
  3771. this.values = state.get('values');
  3772. }
  3773. });
  3774. this.registerType('sklearn.tree.tree.DecisionTreeClassifier', class {});
  3775. this.registerType('sklearn.tree.tree.DecisionTreeRegressor', class {});
  3776. this.registerType('sklearn.tree.tree.ExtraTreeClassifier', class {});
  3777. this.registerType('sklearn.utils._bunch.Bunch', class {});
  3778. this.registerType('sklearn.utils._metadata_requests.MetadataRequest', class {});
  3779. this.registerType('sklearn.utils._metadata_requests.MethodMetadataRequest', class {});
  3780. this.registerType('sklearn.utils.deprecation.DeprecationDict', class {});
  3781. this.registerType('pickle.Unpickler', class {
  3782. constructor(data) {
  3783. this._reader = data instanceof Uint8Array ? new python.BinaryReader(data) : new python.StreamReader(data);
  3784. this.persistent_load = () => {
  3785. throw new python.Error('Unsupported persistent id.');
  3786. };
  3787. }
  3788. load() {
  3789. const reader = this._reader;
  3790. const marker = [];
  3791. let stack = [];
  3792. const memo = {};
  3793. let size = 0;
  3794. while (reader.position < reader.length) {
  3795. const opcode = reader.byte();
  3796. // console.log(`${(reader.position - 1).toString()} ${opcode}`);
  3797. // https://svn.python.org/projects/python/trunk/Lib/pickletools.py
  3798. // https://github.com/python/cpython/blob/master/Lib/pickle.py
  3799. switch (opcode) {
  3800. case 128: { // PROTO
  3801. const version = reader.byte();
  3802. if (version > 5) {
  3803. throw new python.Error(`Unsupported protocol version '${version}'.`);
  3804. }
  3805. break;
  3806. }
  3807. case 99: { // GLOBAL 'c'
  3808. const module = reader.line();
  3809. const name = reader.line();
  3810. stack.push(this.find_class(module, name));
  3811. break;
  3812. }
  3813. case 147: { // STACK_GLOBAL '\x93' (Protocol 4)
  3814. const name = stack.pop();
  3815. const module = stack.pop();
  3816. stack.push(this.find_class(module, name));
  3817. break;
  3818. }
  3819. case 111: { // OBJ 'o'
  3820. const args = stack;
  3821. const cls = args.pop();
  3822. stack = marker.pop();
  3823. const obj = this._instantiate(cls, args);
  3824. stack.push(obj);
  3825. break;
  3826. }
  3827. case 112 : { // PUT 'p'
  3828. const index = parseInt(reader.line(), 10);
  3829. if (stack.length === 0) {
  3830. throw new python.Error(`Empty stack during 'PUT' operation.`);
  3831. }
  3832. memo[index] = stack[stack.length - 1];
  3833. size++;
  3834. break;
  3835. }
  3836. case 103: { // GET 'g'
  3837. const index = parseInt(reader.line(), 10);
  3838. if (index in memo === false) {
  3839. throw new python.Error(`Memo value not found at index '${index}'.`);
  3840. }
  3841. stack.push(memo[index]);
  3842. break;
  3843. }
  3844. case 48: // POP '0'
  3845. stack.pop();
  3846. break;
  3847. case 49: // POP_MARK '1'
  3848. stack = marker.pop();
  3849. break;
  3850. case 50: // DUP '2'
  3851. if (stack.length === 0) {
  3852. throw new python.Error(`Empty stack during 'DUP' operation.`);
  3853. }
  3854. stack.push(stack[stack.length - 1]);
  3855. break;
  3856. case 80: // PERSID 'P'
  3857. stack.push(this.persistent_load(reader.line()));
  3858. break;
  3859. case 81: // BINPERSID 'Q'
  3860. stack.push(this.persistent_load(stack.pop()));
  3861. break;
  3862. case 82: { // REDUCE 'R'
  3863. const args = stack.pop();
  3864. const func = stack.pop();
  3865. stack.push(this._reduce(func, args));
  3866. break;
  3867. }
  3868. case 129: { // NEWOBJ
  3869. const args = stack.pop();
  3870. const cls = stack.pop();
  3871. const obj = this._newobj(cls, args);
  3872. stack.push(obj);
  3873. break;
  3874. }
  3875. case 146: { // NEWOBJ_EX '\x92' (Protocol 4)
  3876. const kwargs = stack.pop();
  3877. const args = stack.pop();
  3878. const cls = stack.pop();
  3879. if (Object.entries(kwargs).length > 0) {
  3880. throw new python.Error("Unpickle 'NEWOBJ_EX' not implemented.");
  3881. }
  3882. const obj = this._newobj(cls, args);
  3883. stack.push(obj);
  3884. break;
  3885. }
  3886. case 104: { // BINGET 'h'
  3887. const index = reader.byte();
  3888. if (index in memo === false) {
  3889. throw new python.Error(`Memo value not found at index '${index}'.`);
  3890. }
  3891. stack.push(memo[index]);
  3892. break;
  3893. }
  3894. case 105: { // INST 'i'
  3895. const module = reader.line();
  3896. const name = reader.line();
  3897. const args = stack;
  3898. const cls = `${module}.${name}`;
  3899. stack = marker.pop();
  3900. // cls = this.find_class(module, name)
  3901. const obj = this._instantiate(cls, args);
  3902. stack.push(obj);
  3903. break;
  3904. }
  3905. case 106: { // LONG_BINGET 'j'
  3906. const index = reader.uint32();
  3907. if (index in memo === false) {
  3908. throw new python.Error(`Memo value not found at index '${index}'.`);
  3909. }
  3910. stack.push(memo[index]);
  3911. break;
  3912. }
  3913. case 113: // BINPUT 'q'
  3914. if (stack.length === 0) {
  3915. throw new python.Error(`Empty stack during 'BINPUT' operation.`);
  3916. }
  3917. memo[reader.byte()] = stack[stack.length - 1];
  3918. size++;
  3919. break;
  3920. case 114: // LONG_BINPUT 'r'
  3921. if (stack.length === 0) {
  3922. throw new python.Error(`Empty stack during 'LONG_BINPUT' operation.`);
  3923. }
  3924. memo[reader.uint32()] = stack[stack.length - 1];
  3925. size++;
  3926. break;
  3927. case 74: // BININT 'J'
  3928. stack.push(reader.int32());
  3929. break;
  3930. case 75: // BININT1 'K'
  3931. stack.push(reader.byte());
  3932. break;
  3933. case 76: // LONG 'L'
  3934. stack.push(parseInt(reader.line(), 10));
  3935. break;
  3936. case 77: // BININT2 'M'
  3937. stack.push(reader.uint16());
  3938. break;
  3939. case 66: // BINBYTES 'B' (Protocol 3)
  3940. stack.push(reader.read(reader.int32()));
  3941. break;
  3942. case 67: // SHORT_BINBYTES 'C' (Protocol 3)
  3943. stack.push(reader.read(reader.byte()));
  3944. break;
  3945. case 142: // BINBYTES8 '\x8e' (Protocol 4)
  3946. stack.push(reader.read(reader.int64().toNumber()));
  3947. break;
  3948. case 70: // FLOAT 'F'
  3949. stack.push(parseFloat(reader.line()));
  3950. break;
  3951. case 71: // BINFLOAT 'G'
  3952. stack.push(reader.float64());
  3953. break;
  3954. case 73: { // INT 'I'
  3955. const value = reader.line();
  3956. if (value === '01') {
  3957. stack.push(true);
  3958. } else if (value === '00') {
  3959. stack.push(false);
  3960. } else {
  3961. stack.push(parseInt(value, 10));
  3962. }
  3963. break;
  3964. }
  3965. case 93: // EMPTY_LIST ']'
  3966. stack.push(new builtins.list());
  3967. break;
  3968. case 41: // EMPTY_TUPLE ')'
  3969. stack.push([]);
  3970. break;
  3971. case 143: // EMPTY_SET '\x8f' (Protocol 4)
  3972. stack.push([]);
  3973. break;
  3974. case 144: { // ADDITEMS '\x90' (Protocol 4)
  3975. const items = stack;
  3976. stack = marker.pop();
  3977. const obj = stack[stack.length - 1];
  3978. for (let i = 0; i < items.length; i++) {
  3979. obj.push(items[i]);
  3980. }
  3981. break;
  3982. }
  3983. case 145: { // FROZENSET '\x91' (Protocol 4)
  3984. const items = stack;
  3985. stack = marker.pop();
  3986. stack.push(items);
  3987. break;
  3988. }
  3989. case 100: { // DICT 'd'
  3990. const items = stack;
  3991. stack = marker.pop();
  3992. const dict = new builtins.dict();
  3993. for (let i = 0; i < items.length; i += 2) {
  3994. dict.__setitem__(items[i], items[i + 1]);
  3995. }
  3996. stack.push(dict);
  3997. break;
  3998. }
  3999. case 108: { // LIST 'l'
  4000. const items = stack;
  4001. stack = marker.pop();
  4002. stack.push(items);
  4003. break;
  4004. }
  4005. case 116: { // TUPLE 't'
  4006. const items = stack;
  4007. stack = marker.pop();
  4008. stack.push(items);
  4009. break;
  4010. }
  4011. case 133: { // TUPLE1 // '\x85'
  4012. stack.push([stack.pop()]);
  4013. break;
  4014. }
  4015. case 134: { // TUPLE2 '\x86'
  4016. const b = stack.pop();
  4017. const a = stack.pop();
  4018. stack.push([a, b]);
  4019. break;
  4020. }
  4021. case 135: { // TUPLE3 '\x87'
  4022. const c = stack.pop();
  4023. const b = stack.pop();
  4024. const a = stack.pop();
  4025. stack.push([a, b, c]);
  4026. break;
  4027. }
  4028. case 115: { // SETITEM 's'
  4029. const value = stack.pop();
  4030. const key = stack.pop();
  4031. const obj = stack[stack.length - 1];
  4032. if (obj.__setitem__) {
  4033. obj.__setitem__(key, value);
  4034. } else {
  4035. obj[key] = value;
  4036. }
  4037. break;
  4038. }
  4039. case 117: { // SETITEMS 'u'
  4040. const items = stack;
  4041. stack = marker.pop();
  4042. const obj = stack[stack.length - 1];
  4043. if (obj.__setitem__) {
  4044. for (let i = 0; i < items.length; i += 2) {
  4045. obj.__setitem__(items[i], items[i + 1]);
  4046. }
  4047. } else {
  4048. for (let i = 0; i < items.length; i += 2) {
  4049. obj[items[i]] = items[i + 1];
  4050. }
  4051. }
  4052. break;
  4053. }
  4054. case 125: // EMPTY_DICT '}'
  4055. stack.push(new builtins.dict());
  4056. break;
  4057. case 97: { // APPEND 'a'
  4058. const append = stack.pop();
  4059. stack[stack.length - 1].push(append);
  4060. break;
  4061. }
  4062. case 101: { // APPENDS 'e'
  4063. const appends = stack;
  4064. stack = marker.pop();
  4065. const list = stack[stack.length - 1];
  4066. list.push(...appends);
  4067. break;
  4068. }
  4069. case 83: { // STRING 'S'
  4070. const str = reader.line();
  4071. stack.push(str.substring(1, str.length - 1));
  4072. break;
  4073. }
  4074. case 84: // BINSTRING 'T'
  4075. stack.push(reader.string(reader.uint32()));
  4076. break;
  4077. case 85 : // SHORT_BINSTRING 'U'
  4078. stack.push(reader.string(reader.byte()));
  4079. break;
  4080. case 86: // UNICODE 'V'
  4081. stack.push(reader.line());
  4082. break;
  4083. case 88: // BINUNICODE 'X
  4084. stack.push(reader.string(reader.uint32(), 'utf-8'));
  4085. break;
  4086. case 140: // SHORT_BINUNICODE '\x8c' (Protocol 4)
  4087. stack.push(reader.string(reader.byte(), 'utf-8'));
  4088. break;
  4089. case 98: { // BUILD 'b'
  4090. const state = stack.pop();
  4091. let obj = stack.pop();
  4092. if (obj.__setstate__) {
  4093. if (obj.__setstate__.__call__) {
  4094. obj.__setstate__.__call__([obj, state]);
  4095. } else {
  4096. obj.__setstate__(state);
  4097. }
  4098. } else if (ArrayBuffer.isView(state) || Object(state) !== state) {
  4099. obj.__state__ = state;
  4100. } else if (obj instanceof Map && state instanceof Map) {
  4101. for (const [key, value] of state) {
  4102. obj.set(key, value);
  4103. }
  4104. } else if (obj instanceof Map) {
  4105. /* eslint-disable guard-for-in */
  4106. for (const key in state) {
  4107. obj.set(key, state[key]);
  4108. }
  4109. /* eslint-enable guard-for-in */
  4110. } else if (state instanceof Map) {
  4111. for (const [key, value] of state) {
  4112. obj[key] = value;
  4113. }
  4114. } else {
  4115. Object.assign(obj, state);
  4116. }
  4117. if (obj.__read__) {
  4118. obj = obj.__read__(this);
  4119. }
  4120. stack.push(obj);
  4121. break;
  4122. }
  4123. case 40: // MARK '('
  4124. marker.push(stack);
  4125. stack = [];
  4126. break;
  4127. case 136: // NEWTRUE '\x88'
  4128. stack.push(true);
  4129. break;
  4130. case 137: // NEWFALSE '\x89'
  4131. stack.push(false);
  4132. break;
  4133. case 138: { // LONG1 '\x8a'
  4134. const data = reader.read(reader.byte());
  4135. let number = 0;
  4136. switch (data.length) {
  4137. case 0: number = 0; break;
  4138. case 1: [number] = data; break;
  4139. case 2: number = data[1] << 8 | data[0]; break;
  4140. case 3: number = data[2] << 16 | data[1] << 8 | data[0]; break;
  4141. case 4: number = (data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]) >>> 0; break;
  4142. case 5: number = data[4] * 0x100000000 + ((data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]) >>> 0); break;
  4143. default: number = Array.prototype.slice.call(data, 0); break;
  4144. }
  4145. stack.push(number);
  4146. break;
  4147. }
  4148. case 139: // LONG4 '\x8b'
  4149. // decode LONG4
  4150. stack.push(reader.read(reader.uint32()));
  4151. break;
  4152. case 148: // MEMOIZE '\x94' (Protocol 4)
  4153. memo[size++] = stack[stack.length - 1];
  4154. break;
  4155. case 149: // FRAME '\x95' (Protocol 4)
  4156. reader.read(8);
  4157. break;
  4158. case 150: { // BYTEARRAY8 '\x96' (Protocol 5)
  4159. stack.push(reader.read(reader.int64().toNumber()));
  4160. break;
  4161. }
  4162. case 78: // NONE 'N'
  4163. stack.push(null);
  4164. break;
  4165. case 46: // STOP '.'
  4166. return stack.pop();
  4167. case 141: // BINUNICODE8 '\x8d' (Protocol 4)
  4168. case 151: // NEXT_BUFFER '\x97' (Protocol 5)
  4169. case 152: // READONLY_BUFFER '\x98' (Protocol 5)
  4170. default:
  4171. throw new python.Error(`Unknown opcode ${opcode} at position ${(reader.position - 1)}.`);
  4172. }
  4173. }
  4174. throw new python.Error('Unexpected end of file.');
  4175. }
  4176. find_class(module, name) {
  4177. execution.__import__(module);
  4178. return execution.resolve(`${module}.${name}`);
  4179. }
  4180. _instantiate(cls, args) {
  4181. return execution.invoke(cls, args);
  4182. }
  4183. _newobj(cls, args) {
  4184. // cls.__new__(cls, args)
  4185. return execution.invoke(cls, args);
  4186. }
  4187. _reduce(func, args) {
  4188. return execution.invoke(func, args);
  4189. }
  4190. read(size) {
  4191. return this._reader.read(size);
  4192. }
  4193. stream(size) {
  4194. return this._reader.stream(size);
  4195. }
  4196. });
  4197. this.registerType('random.Random', class {});
  4198. this.registerType('re.Pattern', class {
  4199. constructor(pattern, flags) {
  4200. this.pattern = pattern;
  4201. this.flags = flags;
  4202. }
  4203. });
  4204. this.registerType('spacy._ml.PrecomputableAffine', class {
  4205. __setstate__(state) {
  4206. Object.assign(this, new pickle.Unpickler(state).load());
  4207. }
  4208. });
  4209. this.registerType('spacy.syntax._parser_model.ParserModel', class {
  4210. __setstate__(state) {
  4211. Object.assign(this, new pickle.Unpickler(state).load());
  4212. }
  4213. });
  4214. this.registerType('theano.compile.function_module._constructor_Function', class {});
  4215. this.registerType('theano.compile.function_module._constructor_FunctionMaker', class {});
  4216. this.registerType('theano.compile.function_module.Function', class {});
  4217. this.registerType('theano.compile.function_module.Supervisor', class {});
  4218. this.registerType('theano.compile.io.In', class {});
  4219. this.registerType('theano.compile.io.SymbolicOutput', class {});
  4220. this.registerType('theano.compile.mode.Mode', class {});
  4221. this.registerType('theano.compile.ops.OutputGuard', class {});
  4222. this.registerType('theano.compile.ops.Shape', class {});
  4223. this.registerType('theano.compile.ops.Shape_i', class {});
  4224. this.registerType('theano.gof.destroyhandler.DestroyHandler', class {});
  4225. this.registerType('theano.gof.fg.FunctionGraph', class {});
  4226. this.registerType('theano.gof.graph.Apply', class {});
  4227. this.registerType('theano.gof.link.Container', class {});
  4228. this.registerType('theano.gof.opt._metadict', class {});
  4229. this.registerType('theano.gof.opt.ChangeTracker', class {});
  4230. this.registerType('theano.gof.opt.MergeFeature', class {});
  4231. this.registerType('theano.gof.optdb.Query', class {});
  4232. this.registerType('theano.gof.toolbox.PreserveVariableAttributes', class {});
  4233. this.registerType('theano.gof.toolbox.ReplaceValidate', class {});
  4234. this.registerType('theano.gof.utils.scratchpad', class {});
  4235. this.registerType('theano.misc.ordered_set.Link', class {});
  4236. this.registerType('theano.misc.ordered_set.OrderedSet', class {});
  4237. this.registerType('theano.sandbox.cuda.basic_ops.HostFromGpu', class {});
  4238. this.registerType('theano.sandbox.cuda.type.CudaNdarray_unpickler', class {});
  4239. this.registerType('theano.sandbox.cuda.type.CudaNdarrayType', class {});
  4240. this.registerType('theano.sandbox.cuda.var.CudaNdarraySharedVariable', class {});
  4241. this.registerType('theano.scalar.basic.Abs', class {});
  4242. this.registerType('theano.scalar.basic.Add', class {});
  4243. this.registerType('theano.scalar.basic.Cast', class {});
  4244. this.registerType('theano.scalar.basic.Composite', class {});
  4245. this.registerType('theano.scalar.basic.EQ', class {});
  4246. this.registerType('theano.scalar.basic.GE', class {});
  4247. this.registerType('theano.scalar.basic.Identity', class {});
  4248. this.registerType('theano.scalar.basic.IntDiv', class {});
  4249. this.registerType('theano.scalar.basic.Inv', class {});
  4250. this.registerType('theano.scalar.basic.LE', class {});
  4251. this.registerType('theano.scalar.basic.LT', class {});
  4252. this.registerType('theano.scalar.basic.Mul', class {});
  4253. this.registerType('theano.scalar.basic.Neg', class {});
  4254. this.registerType('theano.scalar.basic.Pow', class {});
  4255. this.registerType('theano.scalar.basic.Scalar', class {});
  4256. this.registerType('theano.scalar.basic.ScalarConstant', class {});
  4257. this.registerType('theano.scalar.basic.ScalarVariable', class {});
  4258. this.registerType('theano.scalar.basic.Second', class {});
  4259. this.registerType('theano.scalar.basic.Sgn', class {});
  4260. this.registerType('theano.scalar.basic.specific_out', class {});
  4261. this.registerType('theano.scalar.basic.Sub', class {});
  4262. this.registerType('theano.scalar.basic.Switch', class {});
  4263. this.registerType('theano.scalar.basic.Tanh', class {});
  4264. this.registerType('theano.scalar.basic.transfer_type', class {});
  4265. this.registerType('theano.scalar.basic.TrueDiv', class {});
  4266. this.registerType('theano.tensor.basic.Alloc', class {});
  4267. this.registerType('theano.tensor.basic.Dot', class {});
  4268. this.registerType('theano.tensor.basic.MaxAndArgmax', class {});
  4269. this.registerType('theano.tensor.basic.Reshape', class {});
  4270. this.registerType('theano.tensor.basic.ScalarFromTensor', class {});
  4271. this.registerType('theano.tensor.blas.Dot22', class {});
  4272. this.registerType('theano.tensor.blas.Dot22Scalar', class {});
  4273. this.registerType('theano.tensor.blas.Gemm', class {});
  4274. this.registerType('theano.tensor.elemwise.DimShuffle', class {});
  4275. this.registerType('theano.tensor.elemwise.Elemwise', class {});
  4276. this.registerType('theano.tensor.elemwise.Sum', class {});
  4277. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d', class {});
  4278. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d_gradInputs', class {});
  4279. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d_gradWeights', class {});
  4280. this.registerType('theano.tensor.nnet.corr.CorrMM', class {});
  4281. this.registerType('theano.tensor.nnet.corr.CorrMM_gradInputs', class {});
  4282. this.registerType('theano.tensor.nnet.corr.CorrMM_gradWeights', class {});
  4283. this.registerType('theano.tensor.nnet.nnet.CrossentropyCategorical1Hot', class {});
  4284. this.registerType('theano.tensor.nnet.nnet.CrossentropyCategorical1HotGrad', class {});
  4285. this.registerType('theano.tensor.nnet.nnet.CrossentropySoftmax1HotWithBiasDx', class {});
  4286. this.registerType('theano.tensor.nnet.nnet.CrossentropySoftmaxArgmax1HotWithBias', class {});
  4287. this.registerType('theano.tensor.nnet.nnet.Softmax', class {});
  4288. this.registerType('theano.tensor.nnet.nnet.SoftmaxGrad', class {});
  4289. this.registerType('theano.tensor.nnet.nnet.SoftmaxWithBias', class {});
  4290. this.registerType('theano.tensor.opt.MakeVector', class {});
  4291. this.registerType('theano.tensor.opt.ShapeFeature', class {});
  4292. this.registerType('theano.tensor.sharedvar.TensorSharedVariable', class {});
  4293. this.registerType('theano.tensor.signal.pool.MaxPoolGrad', class {});
  4294. this.registerType('theano.tensor.signal.pool.Pool', class {});
  4295. this.registerType('theano.tensor.subtensor.Subtensor', class {});
  4296. this.registerType('theano.tensor.type.TensorType', class {});
  4297. this.registerType('theano.tensor.var.TensorConstant', class {});
  4298. this.registerType('theano.tensor.var.TensorConstantSignature', class {});
  4299. this.registerType('theano.tensor.var.TensorVariable', class {});
  4300. this.registerType('thinc.describe.Biases', class {});
  4301. this.registerType('thinc.describe.Dimension', class {});
  4302. this.registerType('thinc.describe.Gradient', class {});
  4303. this.registerType('thinc.describe.Weights', class {});
  4304. this.registerType('thinc.describe.Synapses', class {});
  4305. this.registerType('thinc.neural._classes.affine.Affine', class {
  4306. __setstate__(state) {
  4307. Object.assign(this, new pickle.Unpickler(state).load());
  4308. }
  4309. });
  4310. this.registerType('thinc.neural._classes.convolution.ExtractWindow', class {
  4311. __setstate__(state) {
  4312. Object.assign(this, new pickle.Unpickler(state).load());
  4313. }
  4314. });
  4315. this.registerType('thinc.neural._classes.feature_extracter.FeatureExtracter', class {
  4316. __setstate__(state) {
  4317. Object.assign(this, new pickle.Unpickler(state).load());
  4318. }
  4319. });
  4320. this.registerType('thinc.neural._classes.feed_forward.FeedForward', class {
  4321. __setstate__(state) {
  4322. Object.assign(this, new pickle.Unpickler(state).load());
  4323. }
  4324. });
  4325. this.registerType('thinc.neural._classes.function_layer.FunctionLayer', class {
  4326. __setstate__(state) {
  4327. Object.assign(this, new pickle.Unpickler(state).load());
  4328. }
  4329. });
  4330. this.registerType('thinc.neural._classes.hash_embed.HashEmbed', class {
  4331. __setstate__(state) {
  4332. Object.assign(this, new pickle.Unpickler(state).load());
  4333. }
  4334. });
  4335. this.registerType('thinc.neural._classes.layernorm.LayerNorm', class {
  4336. __setstate__(state) {
  4337. Object.assign(this, new pickle.Unpickler(state).load());
  4338. }
  4339. });
  4340. this.registerType('thinc.neural._classes.maxout.Maxout', class {
  4341. __setstate__(state) {
  4342. Object.assign(this, new pickle.Unpickler(state).load());
  4343. }
  4344. });
  4345. this.registerType('thinc.neural._classes.resnet.Residual', class {
  4346. __setstate__(state) {
  4347. Object.assign(this, new pickle.Unpickler(state).load());
  4348. }
  4349. });
  4350. this.registerType('thinc.neural._classes.softmax.Softmax', class {
  4351. __setstate__(state) {
  4352. Object.assign(this, new pickle.Unpickler(state).load());
  4353. }
  4354. });
  4355. this.registerType('thinc.neural.mem.Memory', class {
  4356. });
  4357. this.registerType('thinc.neural.ops.NumpyOps', class {
  4358. });
  4359. this.registerType('__main__.BYOLState', class {
  4360. constructor(dict) {
  4361. Object.assign(this, dict);
  4362. }
  4363. });
  4364. const types = this.register('types');
  4365. this.registerType('types.GenericAlias', class {});
  4366. this.registerType('types.SimpleNamespace', class {});
  4367. this.registerType('types.BuiltinFunctionType', class {});
  4368. this.registerType('types.BuiltinMethodType', class {});
  4369. this.registerFunction('types.resolve_bases', (bases) => {
  4370. return bases;
  4371. });
  4372. this.registerFunction('types.prepare_class', (name, bases, kwds) => {
  4373. if (kwds) {
  4374. kwds = new builtins.dict(kwds);
  4375. } else {
  4376. kwds = new builtins.dict();
  4377. }
  4378. let meta = null;
  4379. if (kwds.__contains__('metaclass')) {
  4380. meta = kwds.pop('metaclass');
  4381. } else if (bases && bases.length > 0) {
  4382. meta = builtins.type(bases[0]);
  4383. } else {
  4384. meta = builtins.type;
  4385. }
  4386. if (meta instanceof builtins.type) {
  4387. meta = types._calculate_meta(meta, bases);
  4388. }
  4389. let ns = null;
  4390. if (builtins.hasattr(meta, '__prepare__')) {
  4391. // ns = meta.__prepare__(name, bases, **kwds)
  4392. } else {
  4393. ns = new builtins.dict();
  4394. }
  4395. return [meta, ns, kwds];
  4396. });
  4397. this.registerFunction('types._calculate_meta', (meta /*, bases*/) => {
  4398. const winner = meta;
  4399. return winner;
  4400. });
  4401. this.registerFunction('types.new_class', (name, bases, kwds, exec_body) => {
  4402. const resolved_bases = types.resolve_bases(bases);
  4403. const [meta, ns] = types.prepare_class(name, bases, kwds);
  4404. if (exec_body) {
  4405. exec_body(ns);
  4406. }
  4407. return new meta(name, resolved_bases, ns);
  4408. });
  4409. types.ObjectType = builtins.object;
  4410. types.ModuleType = builtins.module;
  4411. types.MethodType = builtins.method;
  4412. types.FunctionType = builtins.function;
  4413. types.TypeType = builtins.type;
  4414. types.CodeType = builtins.code;
  4415. this.registerType('xgboost.compat.XGBoostLabelEncoder', class {});
  4416. this.registerType('xgboost.core.Booster', class {
  4417. load_model(fname) {
  4418. if (fname instanceof Uint8Array) {
  4419. // XGBoosterLoadModel()
  4420. } else {
  4421. // XGBoosterUnserializeFromBuffer(handle) {
  4422. }
  4423. }
  4424. __setstate__(state) {
  4425. const handle = state.get('handle');
  4426. if (handle) {
  4427. this.handle = handle;
  4428. // XGBoosterLoadModelFromBuffer()
  4429. }
  4430. }
  4431. });
  4432. this.registerType('xgboost.sklearn.XGBClassifier', class {});
  4433. this.registerType('xgboost.sklearn.XGBRegressor', class {});
  4434. this.registerType('xgboost.sklearn.XGBRFClassifier', class {});
  4435. this.registerFunction('_codecs.encode', (obj, encoding) => {
  4436. return new builtins.bytearray(obj, encoding);
  4437. });
  4438. this.registerType('builtins.bytearray', class extends Uint8Array {
  4439. constructor(source, encoding /*, errors */) {
  4440. source = builtins.bytes.__encode__(source, encoding);
  4441. super(Number.isInteger(source) ? source : source.length);
  4442. if (Array.isArray(source)) {
  4443. for (let i = 0; i < source.length; i++) {
  4444. this[i] = source;
  4445. }
  4446. } else if (source instanceof Uint8Array) {
  4447. this.set(source, 0);
  4448. } else if (typeof source === 'string') {
  4449. for (let i = 0; i < source.length; i++) {
  4450. this[i] = source.charCodeAt(i);
  4451. }
  4452. }
  4453. }
  4454. static __encode__(source, encoding) {
  4455. if (source === undefined) {
  4456. return 0;
  4457. }
  4458. if (Number.isInteger(source)) {
  4459. return source;
  4460. }
  4461. if (Array.isArray(source) || source instanceof Uint8Array) {
  4462. return source;
  4463. }
  4464. if (typeof source === 'string') {
  4465. switch (encoding) {
  4466. case 'latin1':
  4467. case 'latin-1':
  4468. return source;
  4469. case 'utf8':
  4470. case 'utf-8':
  4471. return new TextEncoder('utf-8').encode(source);
  4472. case undefined:
  4473. throw new python.Error('Unsupported string argument without an encoding.');
  4474. default:
  4475. throw new python.Error(`Unsupported encoding '${encoding}'.`);
  4476. }
  4477. }
  4478. throw new python.Error('Unsupported source.');
  4479. }
  4480. });
  4481. this.registerType('builtins.bytes', class extends Uint8Array {
  4482. constructor(source, encoding /*, errors */) {
  4483. source = builtins.bytes.__encode__(source, encoding);
  4484. super(Number.isInteger(source) ? source : source.length);
  4485. if (Array.isArray(source)) {
  4486. for (let i = 0; i < source.length; i++) {
  4487. this[i] = source;
  4488. }
  4489. } else if (source instanceof Uint8Array) {
  4490. this.set(source, 0);
  4491. } else if (typeof source === 'string') {
  4492. for (let i = 0; i < source.length; i++) {
  4493. this[i] = source.charCodeAt(i);
  4494. }
  4495. }
  4496. }
  4497. static __encode__(source, encoding) {
  4498. if (source === undefined) {
  4499. return 0;
  4500. }
  4501. if (Number.isInteger(source)) {
  4502. return source;
  4503. }
  4504. if (Array.isArray(source) || source instanceof Uint8Array) {
  4505. return source;
  4506. }
  4507. if (typeof source === 'string') {
  4508. switch (encoding) {
  4509. case 'latin1':
  4510. case 'latin-1':
  4511. return source;
  4512. case 'utf8':
  4513. case 'utf-8':
  4514. return new TextEncoder('utf-8').encode(source);
  4515. case undefined:
  4516. throw new python.Error('Unsupported string argument without an encoding.');
  4517. default:
  4518. throw new python.Error(`Unsupported encoding '${encoding}'.`);
  4519. }
  4520. }
  4521. throw new python.Error('Unsupported source.');
  4522. }
  4523. });
  4524. this.registerType('builtins.memoryview', class {
  4525. constructor(buf) {
  4526. this._buf = buf;
  4527. }
  4528. get nbytes() {
  4529. return this._buf.length;
  4530. }
  4531. });
  4532. this.registerType('builtins.frozenset', class extends Set {
  4533. constructor(iterable) {
  4534. super();
  4535. if (iterable) {
  4536. for (const item of iterable) {
  4537. this.add(item);
  4538. }
  4539. }
  4540. }
  4541. });
  4542. this.registerFunction('builtins.exec');
  4543. this.registerFunction('builtins.issubclass', (obj, type) => {
  4544. const name = `${type.__module__}.${type.__name__}`;
  4545. if (obj.__module__ && obj.__name__) {
  4546. if (name === `${obj.__module__}.${obj.__name__}`) {
  4547. return true;
  4548. }
  4549. }
  4550. if (obj.__bases__) {
  4551. for (const base of obj.__bases__) {
  4552. if (builtins.issubclass(base, type)) {
  4553. return true;
  4554. }
  4555. }
  4556. }
  4557. return false;
  4558. });
  4559. this.registerFunction('builtins.isinstance', (obj, type) => {
  4560. if (obj && type && obj instanceof type) {
  4561. return true;
  4562. }
  4563. if (obj && obj.__class__) {
  4564. return builtins.issubclass(obj.__class__, type);
  4565. }
  4566. return false;
  4567. });
  4568. this.registerFunction('builtins.hasattr', (obj, name) => {
  4569. if (obj instanceof Map && obj.__contains__) {
  4570. return obj.__contains__(name);
  4571. }
  4572. return Object.prototype.hasOwnProperty.call(obj, name);
  4573. });
  4574. this.registerFunction('builtins.getattr', (obj, name, defaultValue) => {
  4575. if (obj && obj.__getattr__) {
  4576. return obj.__getattr__(name);
  4577. }
  4578. if (Object.prototype.hasOwnProperty.call(obj, name)) {
  4579. return obj[name];
  4580. }
  4581. return defaultValue;
  4582. });
  4583. this.registerFunction('builtins.len', (obj) => {
  4584. return obj.length;
  4585. });
  4586. this.registerFunction('builtins.setattr', (obj, name, value) => {
  4587. if (obj && obj.__setattr__) {
  4588. obj.__setattr__(name, value);
  4589. } else {
  4590. obj[name] = value;
  4591. }
  4592. });
  4593. this.registerType('builtins.set', class extends Set {
  4594. __contains__(item) {
  4595. return this.has(item);
  4596. }
  4597. update(iterable) {
  4598. for (const item of iterable) {
  4599. this.add(item);
  4600. }
  4601. }
  4602. });
  4603. this.registerType('builtins.slice', class {
  4604. constructor(start, stop, step) {
  4605. this.start = start;
  4606. this.stop = stop;
  4607. this.step = step;
  4608. }
  4609. });
  4610. this.registerFunction('builtins.hash');
  4611. this.registerType('functools.partial', class {});
  4612. this.registerFunction('functools.reduce', (func, iterable, ...args) => {
  4613. const iter = Array.from(iterable);
  4614. let acc = args.length > 0 ? args[0] : iter.shift();
  4615. for (const item of iter) {
  4616. acc = func(acc, item);
  4617. }
  4618. return acc;
  4619. });
  4620. builtins.reduce = functools.reduce;
  4621. this.registerFunction('cloudpickle.cloudpickle._builtin_type', (name) => {
  4622. return name;
  4623. });
  4624. this.registerFunction('cloudpickle.cloudpickle._fill_function');
  4625. this.registerType('cloudpickle.cloudpickle._empty_cell_value', class {});
  4626. this.registerFunction('cloudpickle.cloudpickle._make_cell', (value) => {
  4627. value = value || cloudpickle.cloudpickle._empty_cell_value;
  4628. const cell = cloudpickle.cloudpickle._make_empty_cell();
  4629. if (value !== cloudpickle.cloudpickle._empty_cell_value) {
  4630. cell.cell_contents = value;
  4631. }
  4632. return cell;
  4633. });
  4634. this.registerFunction('cloudpickle.cloudpickle._make_function', (code, globals, name, argdefs, closure) => {
  4635. // globals["__builtins__"] = __builtins__
  4636. return new types.FunctionType(code, globals, name, argdefs, closure);
  4637. });
  4638. this.registerFunction('cloudpickle.cloudpickle._make_skel_func');
  4639. cloudpickle.cloudpickle._DYNAMIC_CLASS_TRACKER_BY_ID = new builtins.dict();
  4640. this.registerFunction('cloudpickle.cloudpickle._lookup_class_or_track', (class_tracker_id, class_def) => {
  4641. if (class_tracker_id) {
  4642. class_def = cloudpickle.cloudpickle._DYNAMIC_CLASS_TRACKER_BY_ID.setdefault(class_tracker_id, class_def);
  4643. }
  4644. return class_def;
  4645. });
  4646. this.registerFunction('cloudpickle.cloudpickle._make_skeleton_class', (type_constructor, name, bases, type_kwargs, class_tracker_id /*, extra */) => {
  4647. // https://github.com/ray-project/ray/blob/5cd8967f1c0c16d3ae5fedb8449d0d25dd4f9f3e/python/ray/cloudpickle/cloudpickle.py#L523
  4648. const kwds = { 'metaclass': type_constructor };
  4649. const skeleton_class = types.new_class(name, bases, kwds, (ns) => ns.update(type_kwargs));
  4650. return cloudpickle.cloudpickle._lookup_class_or_track(class_tracker_id, skeleton_class);
  4651. });
  4652. this.registerFunction('cloudpickle.cloudpickle._make_empty_cell', () => {
  4653. return new builtins.cell();
  4654. });
  4655. this.registerFunction('cloudpickle.cloudpickle._class_setstate', (obj, state) => {
  4656. [state] = state;
  4657. let registry = null;
  4658. for (const [attrname, attr] of state.items()) {
  4659. if (attrname === '_abc_impl') {
  4660. registry = attr;
  4661. } else {
  4662. builtins.setattr(obj, attrname, attr);
  4663. }
  4664. }
  4665. if (sys.version_info >= (3, 13) && state.__contains__('__firstlineno__')) {
  4666. obj.__firstlineno__ = state.get('__firstlineno__');
  4667. }
  4668. if (registry) {
  4669. for (const subclass of registry) {
  4670. obj.register(subclass);
  4671. }
  4672. }
  4673. return obj;
  4674. });
  4675. this.registerFunction('cloudpickle.cloudpickle._function_setstate', (obj, state) => {
  4676. const [, slotstate] = state;
  4677. [state] = state;
  4678. // obj.__dict__.update(state)
  4679. /* const obj_globals = */ slotstate.pop('__globals__');
  4680. const obj_closure = slotstate.pop('__closure__');
  4681. slotstate.pop('_cloudpickle_submodules');
  4682. if (obj.__globals__) {
  4683. // obj.__globals__.update(obj_globals);
  4684. // obj.__globals__.__builtins__ = __builtins__;
  4685. }
  4686. if (obj_closure) {
  4687. // let value = null;
  4688. for (let i = 0; i < obj_closure.length; i++) {
  4689. // const cell = obj_closure[i];
  4690. try {
  4691. // value = cell.cell_contents;
  4692. } catch {
  4693. // cell is empty
  4694. }
  4695. // obj.__closure__[i].cell_contents = value;
  4696. }
  4697. }
  4698. for (const [k, v] of slotstate.items()) {
  4699. builtins.setattr(obj, k, v);
  4700. }
  4701. });
  4702. this.registerFunction('cloudpickle.cloudpickle.subimport', (name) => {
  4703. execution.__import__(name);
  4704. return sys.modules.get(name);
  4705. });
  4706. this.registerFunction('cloudpickle.cloudpickle_fast._class_setstate');
  4707. this.registerFunction('cloudpickle.cloudpickle_fast._function_setstate');
  4708. const ray = this.register('ray');
  4709. this.register('ray.cloudpickle.cloudpickle');
  4710. this.register('ray.cloudpickle.cloudpickle_fast');
  4711. ray.cloudpickle.cloudpickle._builtin_type = cloudpickle.cloudpickle._builtin_type;
  4712. ray.cloudpickle.cloudpickle._fill_function = cloudpickle.cloudpickle._fill_function;
  4713. ray.cloudpickle.cloudpickle._make_cell = cloudpickle.cloudpickle._make_cell;
  4714. ray.cloudpickle.cloudpickle._make_function = cloudpickle.cloudpickle._make_function;
  4715. ray.cloudpickle.cloudpickle._make_skel_func = cloudpickle.cloudpickle._make_skel_func;
  4716. ray.cloudpickle.cloudpickle._make_skeleton_class = cloudpickle.cloudpickle._make_skeleton_class;
  4717. ray.cloudpickle.cloudpickle._make_empty_cell = cloudpickle.cloudpickle._make_empty_cell;
  4718. ray.cloudpickle.cloudpickle._empty_cell_value = cloudpickle.cloudpickle._empty_cell_value;
  4719. ray.cloudpickle.cloudpickle._class_setstate = cloudpickle.cloudpickle._class_setstate;
  4720. ray.cloudpickle.cloudpickle._function_setstate = cloudpickle.cloudpickle._function_setstate;
  4721. ray.cloudpickle.cloudpickle._lookup_class_or_track = cloudpickle.cloudpickle._lookup_class_or_track;
  4722. ray.cloudpickle.cloudpickle_fast._class_setstate = cloudpickle.cloudpickle._class_setstate;
  4723. ray.cloudpickle.cloudpickle_fast._function_setstate = cloudpickle.cloudpickle._function_setstate;
  4724. this.registerType('ray.rllib.algorithms.ppo.ppo.PPO', class {});
  4725. this.registerType('ray.rllib.algorithms.ppo.ppo.PPOConfig', class {});
  4726. this.registerType('ray.rllib.algorithms.algorithm_config.AlgorithmConfig', class {});
  4727. this.registerFunction('ray.rllib.algorithms.algorithm_config.AlgorithmConfig.DEFAULT_POLICY_MAPPING_FN');
  4728. this.registerType('ray.rllib.algorithms.algorithm_config.TorchCompileWhatToCompile', class {});
  4729. this.registerType('ray.rllib.evaluation.collectors.simple_list_collector.SimpleListCollector', class {});
  4730. this.registerType('ray.rllib.callbacks.callbacks.RLlibCallback', class {});
  4731. this.registerType('ray.rllib.core.learner.learner.TorchCompileWhatToCompile', class {});
  4732. this.registerType('ray.rllib.policy.policy.PolicySpec', class {});
  4733. this.registerType('ray.rllib.policy.sample_batch.SampleBatch', class {});
  4734. this.registerType('ray.rllib.utils.metrics.stats.mean.MeanStats', class {});
  4735. this.registerType('ray.rllib.utils.metrics.stats.ema.EmaStats', class {});
  4736. this.registerType('ray.rllib.utils.metrics.stats.min.MinStats', class {});
  4737. this.registerType('ray.rllib.utils.metrics.stats.max.MaxStats', class {});
  4738. this.registerType('ray.rllib.utils.metrics.stats.sum.SumStats', class {});
  4739. this.registerType('ray.rllib.utils.metrics.stats.lifetime_sum.LifetimeSumStats', class {});
  4740. this.registerType('ray.rllib.utils.metrics.stats.percentiles.PercentilesStats', class {});
  4741. this.registerType('ray.rllib.utils.metrics.stats.item.ItemStats', class {});
  4742. this.registerType('ray.rllib.utils.metrics.stats.item_series.ItemSeriesStats', class {});
  4743. this.registerType('collections.Counter', class {});
  4744. this.registerFunction('collections.defaultdict', (/* default_factory */) => {
  4745. return {};
  4746. });
  4747. this.registerFunction('copy.deepcopy');
  4748. this.registerFunction('copy_reg._reconstructor', (cls, base, state) => {
  4749. // copyreg._reconstructor in Python 3
  4750. if (base === '__builtin__.object' || base === builtins.object) {
  4751. return self.invoke(cls, []);
  4752. } else if (base === '__builtin__.tuple' || base === builtins.tuple) {
  4753. const obj = self.invoke(cls, []);
  4754. for (let i = 0; i < state.length; i++) {
  4755. obj[i] = state[i];
  4756. }
  4757. return obj;
  4758. }
  4759. throw new python.Error(`Unsupported copy_reg._reconstructor base type '${base}'.`);
  4760. });
  4761. this.registerFunction('copy.deepcopy', (/* x */) => {
  4762. throw new python.Error('Unsupported copy.deepcopy().');
  4763. });
  4764. this.registerFunction('dill._dill._create_array', (f, args, state, npdict) => {
  4765. const array = f(...args);
  4766. if (array.__setstate__) {
  4767. array.__setstate__(state);
  4768. }
  4769. if (npdict) {
  4770. throw new python.Error("'dill._dill._create_array::npdict' not implemented.");
  4771. }
  4772. return array;
  4773. });
  4774. this.registerFunction('dill._dill._create_cell', (/* args */) => {
  4775. return function() {
  4776. };
  4777. });
  4778. this.registerFunction('dill._dill._create_code', (args) => {
  4779. return self.invoke('types.CodeType', [args]);
  4780. });
  4781. this.registerFunction('dill._dill._create_function', (/* fcode, fglobals, fname, fdefaults, fclosure, fdict, fkwdefaults */) => {
  4782. return function() {
  4783. };
  4784. });
  4785. this.registerFunction('dill._dill._create_namedtuple', (name, fieldnames, modulename /*, defaults */) => {
  4786. const obj = execution.invoke('dill._dill._import_module', [`${modulename}.${name}`]);
  4787. if (obj) {
  4788. return obj;
  4789. }
  4790. return undefined;
  4791. });
  4792. this.registerFunction('dill._dill._create_type', (typeobj, ...args) => {
  4793. const [name, bases, dict] = args;
  4794. const type = class extends bases[0] {};
  4795. const identifier = dict.__contains__('__module__') ? `${dict.__getitem__('__module__')}.${name}` : name;
  4796. return self.registerType(identifier, Object.assign(type, dict));
  4797. });
  4798. this.registerFunction('dill._dill._eval_repr');
  4799. this.registerFunction('dill._dill._get_attr', (self, name) => {
  4800. if (Object.prototype.hasOwnProperty.call(self, name)) {
  4801. return self[name];
  4802. }
  4803. return undefined;
  4804. });
  4805. this.registerFunction('dill._dill._import_module', (import_name, safe) => {
  4806. try {
  4807. if (import_name.startsWith('__runtime__.')) {
  4808. return execution.module(import_name);
  4809. } else if (import_name.indexOf('.') === -1) {
  4810. return execution.__import__(import_name);
  4811. }
  4812. return execution.resolve(import_name);
  4813. } catch (error) {
  4814. if (safe) {
  4815. return null;
  4816. }
  4817. throw error;
  4818. }
  4819. });
  4820. this.registerFunction('dill._dill._load_type', (name) => {
  4821. const _dill = self.register('dill._dill');
  4822. if (!_dill._reverse_typemap) {
  4823. _dill._reverse_typemap = new Map();
  4824. for (const name of ['__builtin__', 'types']) {
  4825. const module = self.register(name);
  4826. for (const [name, obj] of Object.entries(module)) {
  4827. if (obj.__module__ === 'builtins' && obj.__class__ === builtins.type) {
  4828. _dill._reverse_typemap.set(name, obj);
  4829. }
  4830. }
  4831. }
  4832. _dill._reverse_typemap.set('PartialType', functools.partial);
  4833. _dill._reverse_typemap.set('CellType', builtins.cell);
  4834. }
  4835. if (!_dill._reverse_typemap.has(name)) {
  4836. throw new python.Error(`Unknown type name '${name}' in 'dill._dill._load_type'.`);
  4837. }
  4838. return _dill._reverse_typemap.get(name);
  4839. });
  4840. this.registerFunction('dill._dill.loads');
  4841. this.registerFunction('jax._src.array._reconstruct_array', (fun, args, arr_state, aval_state) => {
  4842. const np_value = fun(...args);
  4843. np_value.__setstate__(arr_state);
  4844. const jnp_value = jax.device_put(np_value);
  4845. jnp_value.aval = jnp_value.aval.update(aval_state);
  4846. return jnp_value;
  4847. });
  4848. jax._src.device_array.reconstruct_device_array = jax._src.array._reconstruct_array;
  4849. this.registerFunction('jax.device_put', (x) => {
  4850. const aval = new jax._src.core.ShapedArray(x.shape, x.dtype);
  4851. return new jax.Array(aval, x.data);
  4852. });
  4853. this.registerType('jax._src.core.AbstractValue', class {});
  4854. this.registerType('jax._src.core.UnshapedArray', class extends jax._src.core.AbstractValue {});
  4855. this.registerType('jax._src.core.ShapedArray', class extends jax._src.core.UnshapedArray {
  4856. constructor(shape, dtype, weak_type) {
  4857. super();
  4858. this.shape = shape;
  4859. this.dtype = dtype;
  4860. this.weak_type = weak_type || false;
  4861. }
  4862. update(dict) {
  4863. const shape = dict.get('shape') || this.shape;
  4864. const dtype = dict.get('dtype') || this.dtype;
  4865. const weak_type = dict.get('weak_type') || this.weak_type;
  4866. return new jax._src.core.ShapedArray(shape, dtype, weak_type);
  4867. }
  4868. });
  4869. this.registerType('jax.Array', class {
  4870. constructor(aval, data) {
  4871. this.aval = aval;
  4872. this.data = data;
  4873. }
  4874. get dtype() {
  4875. return this.aval.dtype;
  4876. }
  4877. get shape() {
  4878. return this.aval.shape;
  4879. }
  4880. tobytes() {
  4881. return this.data;
  4882. }
  4883. });
  4884. jax.numpy.ndarray = jax.Array;
  4885. this.registerFunction('keras.saving.pickle_utils.deserialize_model_from_bytecode', (/* serialized_model */) => {
  4886. return null; // throw new python.Error("'keras.saving.pickle_utils.deserialize_model_from_bytecode' not implemented.");
  4887. });
  4888. this.registerFunction('keras.src.saving.pickle_utils.deserialize_model_from_bytecode', keras.saving.pickle_utils.deserialize_model_from_bytecode);
  4889. this.registerFunction('lasagne.nonlinearities.rectify');
  4890. this.registerFunction('lasagne.nonlinearities.softmax');
  4891. this.registerFunction('lasagne.objectives.categorical_crossentropy');
  4892. this.registerFunction('lasagne.updates.nesterov_momentum');
  4893. this.registerFunction('msgpack.unpackb', (packed, ext_hook) => {
  4894. const BinaryReader = class {
  4895. constructor(buffer, ext_hook) {
  4896. // https://github.com/msgpack/msgpack-javascript/blob/master/src/Decoder.ts
  4897. // https://github.com/msgpack/msgpack-python/blob/main/msgpack/_unpacker.pyx
  4898. this._buffer = buffer;
  4899. this._position = 0;
  4900. this._view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  4901. this._ext_hook = ext_hook;
  4902. }
  4903. value() {
  4904. const c = this._view.getUint8(this.skip(1));
  4905. if (c >= 0xe0) {
  4906. return c - 0x100;
  4907. }
  4908. if (c < 0xC0) {
  4909. if (c < 0x80) {
  4910. return c;
  4911. }
  4912. if (c < 0x90) {
  4913. return this.map(c - 0x80);
  4914. }
  4915. if (c < 0xa0) {
  4916. return this.array(c - 0x90);
  4917. }
  4918. return this.string(c - 0xa0);
  4919. }
  4920. switch (c) {
  4921. case 0xC0: return null;
  4922. case 0xC2: return false;
  4923. case 0xC3: return true;
  4924. case 0xC4: return this.read(this._view.getUint8(this.skip(1)));
  4925. case 0xC5: return this.read(this._view.getUint16(this.skip(2)));
  4926. case 0xC6: return this.read(this._view.getUint32(this.skip(4)));
  4927. case 0xC7: return this.extension(this._view.getUint8(this.skip(1)));
  4928. case 0xC8: return this.extension(this._view.getUint16(this.skip(2)));
  4929. case 0xC9: return this.extension(this._view.getUint32(this.skip(4)));
  4930. case 0xCA: return this._view.getFloat32(this.skip(4));
  4931. case 0xCB: return this._view.getFloat64(this.skip(8));
  4932. case 0xCC: return this._view.getUint8(this.skip(1));
  4933. case 0xCD: return this._view.getUint16(this.skip(2));
  4934. case 0xCE: return this._view.getUint32(this.skip(4));
  4935. case 0xCF: return this._view.getBitUint64(this.skip(8));
  4936. case 0xD0: return this._view.getInt8(this.skip(1));
  4937. case 0xD1: return this._view.getInt16(this.skip(2));
  4938. case 0xD2: return this._view.getInt32(this.skip(4));
  4939. case 0xD3: return this._view.getBigInt64(this.skip(8));
  4940. case 0xD4: return this.extension(1);
  4941. case 0xD5: return this.extension(2);
  4942. case 0xD6: return this.extension(4);
  4943. case 0xD7: return this.extension(8);
  4944. case 0xD8: return this.extension(16);
  4945. case 0xD9: return this.string(this._view.getUint8(this.skip(1)));
  4946. case 0xDA: return this.string(this._view.getUint16(this.skip(2)));
  4947. case 0xDB: return this.string(this._view.getUint32(this.skip(4)));
  4948. case 0xDC: return this.array(this._view.getUint16(this.skip(2)));
  4949. case 0xDD: return this.array(this._view.getUint32(this.skip(4)));
  4950. case 0xDE: return this.map(this._view.getUint16(this.skip(2)));
  4951. case 0xDF: return this.map(this._view.getUint32(this.skip(4)));
  4952. default: throw new python.Error(`Invalid code '${c}'.`);
  4953. }
  4954. }
  4955. map(size) {
  4956. const map = {};
  4957. for (let i = 0; i < size; i++) {
  4958. const key = this.value();
  4959. const value = this.value();
  4960. map[key] = value;
  4961. }
  4962. return map;
  4963. }
  4964. array(size) {
  4965. const array = new Array(size);
  4966. for (let i = 0; i < size; i++) {
  4967. array[i] = this.value();
  4968. }
  4969. return array;
  4970. }
  4971. extension(size) {
  4972. const code = this._view.getUint8(this.skip(1));
  4973. const data = this.read(size);
  4974. return this._ext_hook(code, data);
  4975. }
  4976. skip(offset) {
  4977. const position = this._position;
  4978. this._position += offset;
  4979. if (this._position > this._buffer.length) {
  4980. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  4981. }
  4982. return position;
  4983. }
  4984. read(size) {
  4985. const data = this._buffer.subarray(this._position, this._position + size);
  4986. this._position += size;
  4987. return data;
  4988. }
  4989. string(size) {
  4990. const buffer = this.read(size);
  4991. this._decoder = this._decoder || new TextDecoder('utf8');
  4992. return this._decoder.decode(buffer);
  4993. }
  4994. };
  4995. return new BinaryReader(packed, ext_hook).value();
  4996. });
  4997. this.registerFunction('nolearn.lasagne.base.objective');
  4998. this.registerFunction('numpy.core._DType_reconstruct');
  4999. this.registerFunction('numpy.core._ufunc_reconstruct');
  5000. this.registerFunction('numpy.core.multiarray._reconstruct', (subtype, shape, dtype) => {
  5001. return numpy.ndarray.__new__(subtype, shape, dtype);
  5002. });
  5003. this.registerFunction('numpy.core.multiarray.frombuffer', (buf, dtype) => {
  5004. const shape = [buf.length / dtype.itemsize];
  5005. return new numpy.ndarray(shape, dtype, buf);
  5006. });
  5007. this.registerFunction('numpy._core.numeric._frombuffer', (buf, dtype, shape, order) => {
  5008. return numpy._core.multiarray.frombuffer(buf, dtype).reshape(shape, order);
  5009. });
  5010. this.registerFunction('numpy._core._internal._convert_to_stringdtype_kwargs', () => {
  5011. return new numpy.dtypes.StringDType();
  5012. });
  5013. this.registerFunction('numpy.core.multiarray.scalar', (dtype, rawData) => {
  5014. let data = rawData;
  5015. if (typeof rawData === 'string' || rawData instanceof String) {
  5016. data = new Uint8Array(rawData.length);
  5017. for (let i = 0; i < rawData.length; i++) {
  5018. data[i] = rawData.charCodeAt(i);
  5019. }
  5020. }
  5021. switch (dtype.kind) {
  5022. case 'b': {
  5023. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5024. switch (dtype.itemsize) {
  5025. case 1: return view.getInt8(0) ? true : false;
  5026. default: throw new python.Error(`Unsupported scalar dtype boolean itemsize '${dtype.itemsize}'.`);
  5027. }
  5028. }
  5029. case 'f': {
  5030. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5031. switch (dtype.itemsize) {
  5032. case 2: return view.getFloat16(0, dtype.byteorder === '<');
  5033. case 4: return view.getFloat32(0, dtype.byteorder === '<');
  5034. case 8: return view.getFloat64(0, dtype.byteorder === '<');
  5035. default: throw new python.Error(`Unsupported scalar dtype float itemsize '${dtype.itemsize}'.`);
  5036. }
  5037. }
  5038. case 'i': {
  5039. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5040. switch (dtype.itemsize) {
  5041. case 1: return view.getInt8(0);
  5042. case 2: return view.getInt16(0, dtype.byteorder === '<');
  5043. case 4: return view.getInt32(0, dtype.byteorder === '<');
  5044. case 8: return view.getBigInt64(0, dtype.byteorder === '<');
  5045. default: throw new python.Error(`Unsupported scalar dtype int itemsize '${dtype.itemsize}'.`);
  5046. }
  5047. }
  5048. case 'u': {
  5049. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5050. switch (dtype.itemsize) {
  5051. case 1: return view.getUint8(0);
  5052. case 2: return view.getUint16(0, dtype.byteorder === '<');
  5053. case 4: return view.getUint32(0, dtype.byteorder === '<');
  5054. case 8: return view.getBigUint64(0, dtype.byteorder === '<');
  5055. default: throw new python.Error(`Unsupported scalar dtype uint itemsize '${dtype.itemsize}'.`);
  5056. }
  5057. }
  5058. case 'U': {
  5059. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5060. const list = [];
  5061. for (let i = 0; i < dtype.itemsize; i += 4) {
  5062. list.push(String.fromCodePoint(view.getUint32(i, true)));
  5063. }
  5064. return list.join('');
  5065. }
  5066. default: {
  5067. throw new python.Error(`Unsupported scalar dtype kind '${dtype.kind}'.`);
  5068. }
  5069. }
  5070. });
  5071. this.registerFunction('numpy.core._multiarray_umath.cbrt');
  5072. this.registerFunction('numpy.core._multiarray_umath.fmin');
  5073. this.registerFunction('numpy.core._multiarray_umath.fmax');
  5074. this.registerFunction('numpy.core._multiarray_umath.greater');
  5075. this.registerFunction('numpy.core._multiarray_umath.less');
  5076. this.registerFunction('numpy.core._multiarray_umath.log');
  5077. this.registerFunction('numpy.core._multiarray_umath.scalar', (dtype, rawData) => {
  5078. let data = rawData;
  5079. if (typeof rawData === 'string') {
  5080. data = new Uint8Array(rawData.length);
  5081. for (let i = 0; i < rawData.length; i++) {
  5082. data[i] = rawData.charCodeAt(i);
  5083. }
  5084. }
  5085. const dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5086. switch (dtype.__name__) {
  5087. case 'uint8':
  5088. return dataView.getUint8(0);
  5089. case 'float32':
  5090. return dataView.getFloat32(0, true);
  5091. case 'float64':
  5092. return dataView.getFloat64(0, true);
  5093. case 'int8':
  5094. return dataView.getInt8(0, true);
  5095. case 'int16':
  5096. return dataView.getInt16(0, true);
  5097. case 'int32':
  5098. return dataView.getInt32(0, true);
  5099. case 'int64':
  5100. return dataView.getBigInt64(0, true);
  5101. default:
  5102. throw new python.Error(`Unsupported scalar type '${dtype.__name__}'.`);
  5103. }
  5104. });
  5105. this.registerFunction('numpy.core._multiarray_umath.sin');
  5106. this.registerFunction('numpy.core._multiarray_umath.sqrt');
  5107. this.register('numpy._core.multiarray', numpy.core.multiarray);
  5108. this.register('numpy._core._multiarray_umath', numpy.core._multiarray_umath);
  5109. this.register('numpy._core._multiarray_umath', numpy.core._multiarray_umath);
  5110. this.register('numpy.core.numeric', numpy._core.numeric);
  5111. numpy._core._multiarray_umath._reconstruct = numpy.core.multiarray._reconstruct;
  5112. this.registerFunction('numpy.load', (file) => {
  5113. // https://github.com/numpy/numpy/blob/main/numpy/lib/_format_impl.py
  5114. const signature = [0x93, 0x4E, 0x55, 0x4D, 0x50, 0x59];
  5115. if (!file.read(6).every((v, i) => v === signature[i])) {
  5116. throw new python.Error('Invalid signature.');
  5117. }
  5118. const version = file.read(2);
  5119. const [major, minor] = version;
  5120. if (major > 3) {
  5121. throw new python.Error(`Invalid version '${[major, minor].join('.')}'.`);
  5122. }
  5123. const [shape, fortran_order, dtype] = numpy.lib._format_impl._read_array_header(file, version);
  5124. let data = null;
  5125. switch (dtype.byteorder) {
  5126. case '|': {
  5127. data = file.read();
  5128. if (dtype.kind === 'O') {
  5129. const unpickler = new pickle.Unpickler(data);
  5130. return unpickler.load();
  5131. }
  5132. break;
  5133. }
  5134. case '>':
  5135. case '<': {
  5136. const count = shape.length === 0 ? 1 : shape.reduce((a, b) => a * b, 1);
  5137. const stream = file.getbuffer().nbytes > 0x1000000;
  5138. data = file.read(dtype.itemsize * count, stream);
  5139. break;
  5140. }
  5141. default: {
  5142. throw new python.Error(`Unsupported data type '${dtype.str}'.`);
  5143. }
  5144. }
  5145. const order = fortran_order ? 'F' : 'C';
  5146. return new numpy.ndarray(shape, dtype, data, undefined, undefined, order);
  5147. });
  5148. this.registerFunction('numpy.save', (file, arr) => {
  5149. const descr = arr.dtype.str;
  5150. if (descr[0] !== '<' && descr[0] !== '>') {
  5151. throw new python.Error(`Unsupported byte order '${descr}'.`);
  5152. }
  5153. if ((descr.length !== 3 && descr.substring(1) !== 'c16') || (descr[1] !== 'f' && descr[1] !== 'i' && descr[1] !== 'u' && descr[1] !== 'c' && descr.substring(1) !== 'b1')) {
  5154. throw new python.Error(`Unsupported data type '${descr}'.`);
  5155. }
  5156. let shape = '';
  5157. switch (arr.shape.length) {
  5158. case 0: shape = '()'; break;
  5159. case 1: shape = `(${arr.shape[0]},)`; break;
  5160. default: shape = `(${arr.shape.map((dimension) => dimension.toString()).join(', ')})`; break;
  5161. }
  5162. const properties = [
  5163. `'descr': '${descr}'`,
  5164. "'fortran_order': False",
  5165. `'shape': ${shape}`
  5166. ];
  5167. let header = `{ ${properties.join(', ')} }`;
  5168. header += `${' '.repeat(64 - ((header.length + 2 + 8 + 1) & 0x3f))}\n`;
  5169. const encoder = new TextEncoder('ascii');
  5170. file.write([0x93, 0x4E, 0x55, 0x4D, 0x50, 0x59, 0x01, 0x00]); // '\\x93NUMPY' + version
  5171. file.write([header.length & 0xff, (header.length >> 8) & 0xff]);
  5172. file.write(encoder.encode(header));
  5173. file.write(arr.tobytes());
  5174. });
  5175. this.registerFunction('numpy.lib._format_impl._read_array_header', (file, version) => {
  5176. const buffer = new Uint8Array([0, 0, 0, 0]);
  5177. const [major] = version;
  5178. buffer.set(file.read(major >= 2 ? 4 : 2), 0);
  5179. const header_length = buffer[3] << 24 | buffer[2] << 16 | buffer[1] << 8 | buffer[0];
  5180. let header = file.read(header_length);
  5181. const decoder = new TextDecoder(major >= 3 ? 'utf-8' : 'ascii');
  5182. header = decoder.decode(header).trim();
  5183. try {
  5184. header = ast.literal_eval(header);
  5185. } catch {
  5186. if (major <= 2) {
  5187. header = numpy.lib._format_impl._filter_header(header);
  5188. header = ast.literal_eval(header);
  5189. }
  5190. }
  5191. if (header.descr === undefined) {
  5192. throw new python.Error("Invalid 'descr'.");
  5193. }
  5194. if (!Array.isArray(header.shape)) {
  5195. throw new python.Error("Invalid 'shape'.");
  5196. }
  5197. const dtype = numpy.lib._format_impl.descr_to_dtype(header.descr);
  5198. return [header.shape, header.fortran_order, dtype];
  5199. });
  5200. this.registerFunction('numpy.lib._format_impl.descr_to_dtype', (descr) => {
  5201. if (typeof descr === 'string') {
  5202. return new numpy.dtype(descr);
  5203. } else if (descr instanceof builtins.tuple) {
  5204. const dt = numpy.lib._format_impl.descr_to_dtype(descr[0]);
  5205. return new numpy.dtype([dt, descr[1]]);
  5206. }
  5207. const titles = [];
  5208. const names = [];
  5209. const formats = [];
  5210. const offsets = [];
  5211. let offset = 0;
  5212. for (const field of descr) {
  5213. let name = null;
  5214. let dt = null;
  5215. let descr_str = null;
  5216. let shape = null;
  5217. let title = null;
  5218. if (field.length === 2) {
  5219. [name, descr_str] = field;
  5220. dt = numpy.lib._format_impl.descr_to_dtype(descr_str);
  5221. } else {
  5222. [name, descr_str, shape] = field;
  5223. dt = new numpy.dtype([numpy.lib._format_impl.descr_to_dtype(descr_str), shape]);
  5224. }
  5225. const is_pad = name === '' && dt.type === numpy.void && dt.names === null;
  5226. if (!is_pad) {
  5227. [title, name] = name instanceof builtins.tuple ? name : [null, name];
  5228. titles.push(title);
  5229. names.push(name);
  5230. formats.push(dt);
  5231. offsets.push(offset);
  5232. }
  5233. offset += dt.itemsize;
  5234. }
  5235. return new numpy.dtype({ names, formats, titles, offsets, itemsize: offset });
  5236. });
  5237. this.registerFunction('numpy.lib._format_impl._filter_header', (s) => {
  5238. const tokens = [];
  5239. const tokenizer = new ast._Tokenizer(s, '');
  5240. while (!tokenizer.match('eof')) {
  5241. const token = tokenizer.read();
  5242. if (token.type === 'int') {
  5243. const next = tokenizer.peek();
  5244. if (next.type === 'id' && next.value === 'L') {
  5245. tokenizer.read();
  5246. }
  5247. }
  5248. tokens.push(token.value);
  5249. }
  5250. return tokens.join('');
  5251. });
  5252. this.registerFunction('numpy.amin');
  5253. this.registerFunction('numpy.amax');
  5254. this.registerFunction('numpy.std');
  5255. this.registerFunction('numpy.asarray', (a, dtype) => {
  5256. const encode = (context, data, dim) => {
  5257. const size = context.shape[dim];
  5258. const littleendian = context.littleendian;
  5259. if (dim === context.shape.length - 1) {
  5260. for (let i = 0; i < size; i++) {
  5261. switch (context.dtype) {
  5262. case 'f2':
  5263. context.view.setFloat16(context.position, data[i], littleendian);
  5264. break;
  5265. case 'f4':
  5266. context.view.setFloat32(context.position, data[i], littleendian);
  5267. break;
  5268. case 'f8':
  5269. context.view.setFloat64(context.position, data[i], littleendian);
  5270. break;
  5271. case 'i1':
  5272. context.view.setInt8(context.position, data[i], littleendian);
  5273. break;
  5274. case 'i2':
  5275. context.view.setInt16(context.position, data[i], littleendian);
  5276. break;
  5277. case 'i4':
  5278. context.view.setInt32(context.position, data[i], littleendian);
  5279. break;
  5280. case 'i8':
  5281. context.view.setBigInt64(context.position, typeof data[i] === 'number' ? BigInt(data[i]) : data[i], littleendian);
  5282. break;
  5283. case 'u1':
  5284. context.view.setUint8(context.position, data[i], littleendian);
  5285. break;
  5286. case 'u2':
  5287. context.view.setUint16(context.position, data[i], littleendian);
  5288. break;
  5289. case 'u4':
  5290. context.view.setUint32(context.position, data[i], littleendian);
  5291. break;
  5292. case 'u8':
  5293. context.view.setComplexFloat16(context.position, data[i], littleendian);
  5294. break;
  5295. case 'c8':
  5296. context.view.setComplexFloat32(context.position, data[i], littleendian);
  5297. break;
  5298. case 'c16':
  5299. context.view.setComplexFloat64(context.position, data[i], littleendian);
  5300. break;
  5301. case 'b1':
  5302. context.view.setInt8(context.position, data[i] ? 1 : 0);
  5303. break;
  5304. default:
  5305. throw new python.Error(`Unsupported tensor data type '${context.dtype}'.`);
  5306. }
  5307. context.position += context.itemsize;
  5308. }
  5309. } else {
  5310. for (let j = 0; j < size; j++) {
  5311. encode(context, data[j], dim + 1);
  5312. }
  5313. }
  5314. };
  5315. const array_size = (value) => {
  5316. if (value.every((item) => Array.isArray(item))) {
  5317. const dims = value.map((item) => array_size(item));
  5318. const [dim] = dims;
  5319. for (let i = 1; i < dims.length; i++) {
  5320. if (dim.length === dims[i].length) {
  5321. if (!dims[i].every((value, i) => value === dim[i])) {
  5322. throw new python.Error('Invalid array shape.');
  5323. }
  5324. }
  5325. }
  5326. return [value.length].concat(dim);
  5327. }
  5328. return [value.length];
  5329. };
  5330. const shape = Array.isArray(a) ? array_size(a) : [];
  5331. const size = dtype.itemsize * shape.reduce((a, b) => a * b, 1);
  5332. const context = {
  5333. position: 0,
  5334. itemsize: dtype.itemsize,
  5335. dtype: dtype.str.substring(1),
  5336. littleendian: dtype.str[0],
  5337. shape,
  5338. data: new Uint8Array(size)
  5339. };
  5340. context.view = new DataView(context.data.buffer, context.data.byteOffset, size);
  5341. encode(context, a, 0);
  5342. return self.invoke('numpy.ndarray', [shape, dtype, context.data]);
  5343. });
  5344. this.registerFunction('numpy.max');
  5345. this.registerFunction('numpy.mean');
  5346. this.registerFunction('numpy.min');
  5347. this.registerFunction('numpy.ma.core._mareconstruct', (subtype, baseclass, baseshape, basetype) => {
  5348. const data = self.invoke(baseclass, [baseshape, basetype]);
  5349. // = ndarray.__new__(ndarray, baseshape, make_mask_descr(basetype))
  5350. const mask = self.invoke('numpy.ndarray', [baseshape, '']);
  5351. return self.invoke(subtype, [data, mask, basetype]);
  5352. });
  5353. this.registerFunction('numpy.random.__RandomState_ctor', () => {
  5354. return {};
  5355. });
  5356. this.registerFunction('numpy.random._pickle.__randomstate_ctor', () => {
  5357. return {};
  5358. });
  5359. this.registerType('numpy.random.bit_generator.BitGenerator', class {
  5360. __setstate__(state) {
  5361. if (state instanceof Map || !Array.isArray(state)) {
  5362. this.state = state;
  5363. } else {
  5364. [this.state, this._seed_seq] = state;
  5365. }
  5366. }
  5367. });
  5368. this.registerType('numpy.random.bit_generator.SeedSequence', class extends builtins.object {
  5369. __setstate__(state) {
  5370. [this.entropy, this.n_children_spawned, this.pool, this.pool_size, this.spawn_key] = state;
  5371. }
  5372. });
  5373. this.registerFunction('numpy.random.bit_generator.__pyx_unpickle_SeedSequence', (cls, checksum, state) => {
  5374. const obj = new cls();
  5375. if (state) {
  5376. obj.__setstate__(state);
  5377. }
  5378. return obj;
  5379. });
  5380. this.registerType('numpy.random._mt19937.MT19937', class extends numpy.random.bit_generator.BitGenerator {});
  5381. this.registerType('numpy.random._pcg64.PCG64', class extends numpy.random.bit_generator.BitGenerator {});
  5382. this.registerType('numpy.random._pcg64.PCG64DXSM', class extends numpy.random.bit_generator.BitGenerator {});
  5383. this.registerType('numpy.random._philox.Philox', class extends numpy.random.bit_generator.BitGenerator {});
  5384. this.registerType('numpy.random._sfc64.SFC64', class extends numpy.random.bit_generator.BitGenerator {});
  5385. numpy.random._pickle.BitGenerators = {
  5386. 'MT19937': numpy.random._mt19937.MT19937,
  5387. 'PCG64': numpy.random._pcg64.PCG64,
  5388. 'PCG64DXSM': numpy.random._pcg64.PCG64DXSM,
  5389. 'Philox': numpy.random._philox.Philox,
  5390. 'SFC64': numpy.random._sfc64.SFC64,
  5391. };
  5392. this.registerType('numpy.random._generator.Generator', class {
  5393. constructor(bit_generator) {
  5394. this.bit_generator = bit_generator;
  5395. }
  5396. });
  5397. this.registerFunction('numpy.random._pickle.__bit_generator_ctor', (bit_generator) => {
  5398. bit_generator = bit_generator || 'MT19937';
  5399. let bit_gen_class = null;
  5400. if (builtins.isinstance(bit_generator, builtins.type)) {
  5401. bit_gen_class = bit_generator;
  5402. } else {
  5403. bit_gen_class = numpy.random._pickle.BitGenerators[bit_generator];
  5404. }
  5405. if (bit_gen_class) {
  5406. return new bit_gen_class();
  5407. }
  5408. throw new python.Error(`Unknown bit generator '${bit_generator}'.`);
  5409. });
  5410. this.registerFunction('numpy.random._pickle.__generator_ctor', (bit_generator_name, bit_generator_ctor) => {
  5411. if (bit_generator_name instanceof numpy.random.bit_generator.BitGenerator) {
  5412. return new numpy.random._generator.Generator(bit_generator_name);
  5413. }
  5414. bit_generator_ctor = bit_generator_ctor || numpy.random._pickle.__bit_generator_ctor;
  5415. return new numpy.random._generator.Generator(bit_generator_ctor(bit_generator_name));
  5416. });
  5417. this.registerFunction('numpy.reshape');
  5418. this.registerFunction('sklearn.feature_selection._univariate_selection.f_classif');
  5419. this.registerFunction('sklearn.feature_selection._univariate_selection.f_regression');
  5420. this.registerFunction('sklearn.metrics.scorer._passthrough_scorer');
  5421. this.registerFunction('sklearn.metrics._classification.accuracy_score');
  5422. this.registerFunction('sklearn.metrics._classification.balanced_accuracy_score');
  5423. this.registerFunction('sklearn.metrics._classification.cohen_kappa_score');
  5424. this.registerFunction('sklearn.metrics._classification.f1_score');
  5425. this.registerFunction('sklearn.metrics._classification.log_loss');
  5426. this.registerFunction('sklearn.metrics._classification.precision_score');
  5427. this.registerFunction('sklearn.metrics._classification.recall_score');
  5428. this.registerFunction('sklearn.metrics._dist_metrics.newObj', (obj) => {
  5429. return obj.__new__(obj);
  5430. });
  5431. this.registerFunction('sklearn.metrics._ranking.roc_auc_score');
  5432. this.registerFunction('sklearn.metrics._regression.mean_absolute_error');
  5433. this.registerFunction('sklearn.metrics._regression.mean_absolute_percentage_error');
  5434. this.registerFunction('sklearn.metrics._regression.mean_squared_error');
  5435. this.registerFunction('sklearn.metrics._regression.r2_score');
  5436. sklearn.metrics.regression = sklearn.metrics._regression;
  5437. sklearn.metrics.r2_score = sklearn.metrics._regression.r2_score;
  5438. this.registerFunction('sklearn.metrics._regression.root_mean_squared_error');
  5439. this.registerFunction('sklearn.metrics._scorer._passthrough_scorer');
  5440. this.registerFunction('re._compile', (pattern, flags) => {
  5441. return self.invoke('re.Pattern', [pattern, flags]);
  5442. });
  5443. this.registerFunction('srsly.cloudpickle.cloudpickle._builtin_type', (...args) => {
  5444. return function() {
  5445. return self.invoke(`types.${args[0]}`, args);
  5446. };
  5447. });
  5448. this.registerType('sympy.printing.defaults.Printable', class {});
  5449. this.registerType('sympy.core.basic.Basic', class extends sympy.printing.defaults.Printable {
  5450. constructor(...args) {
  5451. super();
  5452. this._args = args;
  5453. }
  5454. get args() {
  5455. return this._args;
  5456. }
  5457. });
  5458. this.registerType('sympy.core.function.Function', class extends sympy.core.basic.Basic {
  5459. });
  5460. this.registerType('sympy.core.expr.Expr', class extends sympy.core.basic.Basic {
  5461. });
  5462. this.registerType('sympy.core.operations.AssocOp', class extends sympy.core.expr.Expr /* sympy.core.basic.Basic */ {});
  5463. this.registerType('sympy.core.power.Pow', class extends sympy.core.expr.Expr {
  5464. __str__() {
  5465. return this._args.map((a) => a.__str__()).join('**');
  5466. }
  5467. });
  5468. this.registerType('sympy.core.add.Add', class extends sympy.core.operations.AssocOp {
  5469. __str__() {
  5470. return this._args.map((a) => a.__str__()).join(' + ');
  5471. }
  5472. });
  5473. this.registerType('sympy.core.mul.Mul', class extends sympy.core.operations.AssocOp {
  5474. __str__() {
  5475. return this._args.map((a) => a.__str__()).join('*');
  5476. }
  5477. });
  5478. this.registerType('sympy.core.numbers.Number', class extends sympy.core.expr.Expr {});
  5479. this.registerType('sympy.core.numbers.Rational', class extends sympy.core.numbers.Number {});
  5480. this.registerType('sympy.core.numbers.Integer', class extends sympy.core.numbers.Rational {
  5481. constructor(value) {
  5482. super();
  5483. this.value = value;
  5484. this.is_Integer = true;
  5485. }
  5486. __int__() {
  5487. return this.value;
  5488. }
  5489. __str__() {
  5490. return this.value.toString();
  5491. }
  5492. });
  5493. this.registerType('sympy.core.symbol.Symbol', class extends sympy.core.expr.Expr {
  5494. constructor(name) {
  5495. super();
  5496. this.name = name;
  5497. }
  5498. __int__() {
  5499. throw new python.Error('Cannot convert symbols to int.');
  5500. }
  5501. __str__() {
  5502. return this.name;
  5503. }
  5504. });
  5505. this.registerType('sympy.core.relational.Relational', class extends sympy.core.expr.Expr {
  5506. constructor(lhs, rhs, op) {
  5507. super();
  5508. this._args = [lhs, rhs];
  5509. this._op = op;
  5510. }
  5511. __str__() {
  5512. return `${this._args[0].__str__()} ${this._op} ${this._args[1].__str__()}`;
  5513. }
  5514. });
  5515. this.registerType('sympy.core.relational._Inequality', class extends sympy.core.relational.Relational {
  5516. });
  5517. this.registerType('sympy.core.relational._Greater', class extends sympy.core.relational._Inequality {
  5518. });
  5519. this.registerType('sympy.core.relational.GreaterThan', class extends sympy.core.relational._Greater {
  5520. constructor(lhs, rhs) {
  5521. super(lhs, rhs, '>=');
  5522. }
  5523. });
  5524. this.registerType('sympy.core.relational._Less', class extends sympy.core.relational._Inequality {
  5525. });
  5526. this.registerType('sympy.core.relational.LessThan', class extends sympy.core.relational.Relational {
  5527. constructor(lhs, rhs) {
  5528. super(lhs, rhs, '<=');
  5529. }
  5530. });
  5531. this.registerType('sympy.core.relational.StrictLessThan', class extends sympy.core.relational.Relational {
  5532. constructor(lhs, rhs) {
  5533. super(lhs, rhs, '<');
  5534. }
  5535. });
  5536. this.registerType('sympy.core.relational.StrictGreaterThan', class extends sympy.core.relational.Relational {
  5537. constructor(lhs, rhs) {
  5538. super(lhs, rhs, '>');
  5539. }
  5540. });
  5541. this.registerType('sympy.core.relational.Equality', class extends sympy.core.relational.Relational {
  5542. constructor(lhs, rhs) {
  5543. super(lhs, rhs, '==');
  5544. }
  5545. });
  5546. this.registerType('sympy.functions.elementary.miscellaneous.MinMaxBase', class extends sympy.core.expr.Expr {
  5547. });
  5548. this.registerType('sympy.functions.elementary.miscellaneous.Max', class extends sympy.functions.elementary.miscellaneous.MinMaxBase {
  5549. __str__() {
  5550. return `Max(${this._args.map((a) => a.__str__()).join(', ')})`;
  5551. }
  5552. });
  5553. this.registerFunction('sympy.core.sympify.sympify', (a /*, locals */) => {
  5554. if (a instanceof sympy.core.expr.Expr) {
  5555. return a;
  5556. }
  5557. const p = ast.parse(a);
  5558. const sympify = (node) => {
  5559. if (node instanceof ast.Call) {
  5560. switch (node.func.id) {
  5561. case 'Symbol': return new sympy.core.symbol.Symbol(node.args[0].value);
  5562. case 'Mul': return new sympy.core.mul.Mul(...node.args.map((arg) => sympify(arg)));
  5563. case 'Add': return new sympy.core.add.Add(...node.args.map((arg) => sympify(arg)));
  5564. case 'Pow': return new sympy.core.power.Pow(...node.args.map((arg) => sympify(arg)));
  5565. case 'Max': return new sympy.functions.elementary.miscellaneous.Max(...node.args.map((arg) => sympify(arg)));
  5566. case 'Integer': return new sympy.core.numbers.Integer(node.args[0].value);
  5567. case 'GreaterThan': return new sympy.core.relational.GreaterThan(sympify(node.args[0]), sympify(node.args[1]));
  5568. case 'StrictGreaterThan': return new sympy.core.relational.StrictGreaterThan(sympify(node.args[0]), sympify(node.args[1]));
  5569. case 'LessThan': return new sympy.core.relational.LessThan(sympify(node.args[0]), sympify(node.args[1]));
  5570. case 'StrictLessThan': return new sympy.core.relational.StrictLessThan(sympify(node.args[0]), sympify(node.args[1]));
  5571. case 'Equality': return new sympy.core.relational.Equality(sympify(node.args[0]), sympify(node.args[1]));
  5572. case 'FloorDiv': return new torch.utils._sympy.functions.FloorDiv(sympify(node.args[0]), sympify(node.args[1]));
  5573. default: throw new python.Error(`Unsupported SymPy function '${node.func.id}'.`);
  5574. }
  5575. }
  5576. if (node instanceof ast.Name) {
  5577. return new sympy.core.symbol.Symbol(node.id);
  5578. }
  5579. if (node instanceof ast.Constant) {
  5580. if (node.type === 'int') {
  5581. return new sympy.core.numbers.Integer(node.value);
  5582. }
  5583. }
  5584. if (node instanceof ast.BinOp) {
  5585. if (node.op instanceof ast.Mult) {
  5586. return new sympy.core.mul.Mul(sympify(node.left), sympify(node.right));
  5587. }
  5588. if (node.op instanceof ast.Pow) {
  5589. return new sympy.core.power.Pow(sympify(node.left), sympify(node.right));
  5590. }
  5591. throw new python.Error(`Unsupported SymPy BinOp op '${node.op.__class__.__name__}'.`);
  5592. }
  5593. if (node instanceof ast.Compare) {
  5594. const left = sympify(node.left);
  5595. const right = sympify(node.comparators[0]);
  5596. const [op] = node.ops;
  5597. if (op instanceof ast.Gt) {
  5598. return new sympy.core.relational.StrictGreaterThan(left, right);
  5599. }
  5600. if (op instanceof ast.GtE) {
  5601. return new sympy.core.relational.GreaterThan(left, right);
  5602. }
  5603. if (op instanceof ast.Lt) {
  5604. return new sympy.core.relational.StrictLessThan(left, right);
  5605. }
  5606. if (op instanceof ast.LtE) {
  5607. return new sympy.core.relational.LessThan(left, right);
  5608. }
  5609. if (op instanceof ast.Eq) {
  5610. return new sympy.core.relational.Equality(left, right);
  5611. }
  5612. throw new python.Error(`Unsupported comparison operator '${op.__class__.__name__}'.`);
  5613. }
  5614. throw new python.Error(`Unsupported SymPy expression '${node.__class__.__name__}'.`);
  5615. };
  5616. return sympify(p.body[0].value);
  5617. });
  5618. this.registerFunction('theano.scalar.basic.same_out');
  5619. this.registerFunction('theano.scalar.basic.same_out_nocomplex');
  5620. this.registerFunction('theano.scalar.basic.upcast_out');
  5621. this.registerFunction('theano.scalar.basic.upgrade_to_float');
  5622. this.registerFunction('theano.tensor.nnet.conv2d');
  5623. this.registerFunction('theano.tensor.type.values_eq_approx_remove_inf_nan');
  5624. this.registerFunction('theano.tensor.type.values_eq_approx_remove_nan');
  5625. this.registerType('torch.nn.modules.module.Module', class {
  5626. constructor() {
  5627. this._modules = new collections.OrderedDict();
  5628. this._parameters = new collections.OrderedDict();
  5629. this._buffers = new collections.OrderedDict();
  5630. }
  5631. __setattr__(name, value) {
  5632. if (value instanceof torch.nn.modules.module.Module) {
  5633. this._modules.set(name, value);
  5634. } else {
  5635. this[name] = value;
  5636. }
  5637. }
  5638. __getattr__(name) {
  5639. if (this._modules.has(name)) {
  5640. return this._modules.get(name);
  5641. }
  5642. return this[name];
  5643. }
  5644. __delattr__(name) {
  5645. if (this._modules.has(name)) {
  5646. this._modules.delete(name);
  5647. }
  5648. }
  5649. children() {
  5650. return this._modules.values();
  5651. }
  5652. named_modules(memo, prefix, remove_duplicate) {
  5653. memo = memo || new Set();
  5654. prefix = prefix || '';
  5655. const modules = new builtins.dict();
  5656. if (!memo.has(this)) {
  5657. if (remove_duplicate) {
  5658. memo.add(this);
  5659. }
  5660. modules.set(prefix, this);
  5661. for (const [name, module] of this._modules.items()) {
  5662. if (module && module.named_modules) {
  5663. const submodule_prefix = `${prefix}${(prefix ? '.' : '')}${name}`;
  5664. for (const [k, v] of module.named_modules(memo, submodule_prefix, remove_duplicate)) {
  5665. modules.set(k, v);
  5666. }
  5667. }
  5668. }
  5669. }
  5670. return modules;
  5671. }
  5672. named_children() {
  5673. return this._modules;
  5674. }
  5675. parameters() {
  5676. return this._parameters.values();
  5677. }
  5678. named_parameters(recurse) {
  5679. if (recurse) {
  5680. throw new python.Error('Named parameters with recurse not implemented.');
  5681. }
  5682. return this._parameters;
  5683. }
  5684. buffers() {
  5685. return this._buffers.values();
  5686. }
  5687. named_buffers(recurse) {
  5688. if (recurse) {
  5689. throw new python.Error('Named parameters with recurse not implemented.');
  5690. }
  5691. return this._buffers;
  5692. }
  5693. _get_name() {
  5694. return this.__class__.__name__;
  5695. }
  5696. add_module(name, module) {
  5697. this._modules.set(name, module);
  5698. }
  5699. register_module(name, module) {
  5700. this.add_module(name, module);
  5701. }
  5702. });
  5703. torch.nn.Module = torch.nn.modules.module.Module;
  5704. torch.nn.modules.Module = torch.nn.modules.module.Module;
  5705. this.registerType('torch._C._TensorBase', class extends builtins.object {});
  5706. this.registerType('torch._C._TensorMeta', class extends builtins.type {});
  5707. this.registerType('torch._C._VariableFunctionsClass', class extends builtins.object {});
  5708. this.registerType('torch._C.SchemaParser', class {
  5709. constructor(str, allow_typevars) {
  5710. this.L = new torch._C.Lexer(str);
  5711. this.type_parser = new torch._C.SchemaTypeParser(this.L, false, allow_typevars);
  5712. }
  5713. parseName() {
  5714. const L = this.L;
  5715. let name = L.expect('id').text();
  5716. if (L.nextIf(':')) {
  5717. L.expect(':');
  5718. name = `${name}::${L.expect('ident').text()}`;
  5719. }
  5720. let overload_name = '';
  5721. if (L.nextIf('.')) {
  5722. overload_name = L.expect('ident').text();
  5723. }
  5724. // const is_a_valid_overload_name = !((overload_name === "default") || (overload_name.rfind("__", 0) == 0));
  5725. // TORCH_CHECK(is_a_valid_overload_name, overload_name, " is not a legal overload name for aten operators");
  5726. return new torch._C.OperatorName(name, overload_name);
  5727. }
  5728. parseDeclaration() {
  5729. const L = this.L;
  5730. const name = this.parseName();
  5731. if (L.cur().kind !== '(') {
  5732. return name;
  5733. }
  5734. throw new python.Error('Not implemented.');
  5735. }
  5736. parseExactlyOneDeclaration() {
  5737. // const L = this.L;
  5738. const result = this.parseDeclaration();
  5739. // L.nextIf(TK_NEWLINE);
  5740. // L.expect(TK_EOF);
  5741. return result;
  5742. }
  5743. parseArgument(idx, is_return, kwarg_only) {
  5744. const L = this.L;
  5745. const type_parser = this.type_parser;
  5746. let [fake_type, real_type, alias_info] = type_parser.parseFakeAndRealType();
  5747. let N = null;
  5748. if (L.nextIf('[')) {
  5749. fake_type = torch.ListType.create(fake_type);
  5750. real_type = torch.ListType.create(real_type);
  5751. if (L.cur().kind === '#') {
  5752. N = Number(L.cur().text());
  5753. L.next();
  5754. }
  5755. L.expect(']');
  5756. let container = type_parser.parseAliasAnnotation();
  5757. if (alias_info) {
  5758. if (!container) {
  5759. container = new torch._C.AliasInfo();
  5760. container.is_write = alias_info.is_write;
  5761. }
  5762. container.addContainedType(alias_info);
  5763. }
  5764. alias_info = container;
  5765. if (L.nextIf('?')) {
  5766. fake_type = torch.OptionalType.create(fake_type);
  5767. real_type = torch.OptionalType.create(real_type);
  5768. }
  5769. }
  5770. let name = null;
  5771. /* eslint-disable no-undef-init */
  5772. let default_value = undefined;
  5773. /* eslint-enable no-undef-init */
  5774. if (is_return) {
  5775. kwarg_only = false;
  5776. if (L.cur().kind === 'id') {
  5777. name = L.next().text();
  5778. } else {
  5779. name = '';
  5780. }
  5781. } else {
  5782. name = L.expect('id').text();
  5783. if (L.nextIf('=')) {
  5784. default_value = this.parseDefaultValue(fake_type, fake_type.kind(), real_type, N);
  5785. }
  5786. }
  5787. return new torch.Argument(name, fake_type, real_type, N, default_value, kwarg_only, alias_info);
  5788. }
  5789. parseDefaultValue(arg_type, kind, real_type, arg_N) {
  5790. // auto range = L.cur().range;
  5791. const L = this.L;
  5792. const range = null;
  5793. switch (kind) {
  5794. case torch._C.TypeKind.StringType:
  5795. case torch._C.TypeKind.OptionalType:
  5796. case torch._C.TypeKind.NumberType:
  5797. case torch._C.TypeKind.IntType:
  5798. case torch._C.TypeKind.BoolType:
  5799. case torch._C.TypeKind.FloatType:
  5800. case torch._C.TypeKind.ComplexType:
  5801. return this.parseSingleConstant(arg_type, kind, real_type);
  5802. case torch._C.TypeKind.ListType: {
  5803. const elem_type = arg_type.containedType(0);
  5804. const real_elem_type = real_type.containedType(0);
  5805. if (L.cur().kind === 'id') {
  5806. return this.parseTensorDefault(range);
  5807. } else if (arg_N && L.cur().kind !== '[') {
  5808. const v = this.parseSingleConstant(elem_type, elem_type.kind(), real_elem_type);
  5809. const repeated = Array(arg_N).fill(v);
  5810. // std::vector<IValue> repeated(arg_N, v);
  5811. return this.convertToList(elem_type, elem_type.kind(), range, repeated);
  5812. }
  5813. return this.parseConstantList(elem_type, elem_type.kind(), real_elem_type);
  5814. }
  5815. case torch._C.TypeKind.DynamicType:
  5816. return this.parseDefaultValue(arg_type, arg_type.dynamicKind(), real_type, arg_N);
  5817. default:
  5818. throw new python.Error(`Unsupported default value kind '${kind}'.`);
  5819. }
  5820. }
  5821. parseSingleConstant(type, kind, real_type) {
  5822. const L = this.L;
  5823. if (kind === torch._C.TypeKind.DynamicType) {
  5824. return this.parseSingleConstant(type, type.dynamicKind(), real_type);
  5825. }
  5826. // const auto& str2dtype = c10::getStringToDtypeMap();
  5827. if (L.cur().kind === 'id') {
  5828. if (L.cur().text() === 'True') {
  5829. L.next();
  5830. return new torch._C.IValue(true);
  5831. }
  5832. if (L.cur().text() === 'False') {
  5833. L.next();
  5834. return new torch._C.IValue(false);
  5835. }
  5836. if (L.cur().text() === 'None') {
  5837. L.next();
  5838. return new torch._C.IValue();
  5839. }
  5840. } else if (L.cur().kind === 'string') {
  5841. const token = L.next();
  5842. return new torch._C.IValue(torch._C.parseStringLiteral(null, token.text()));
  5843. } else if (L.cur().kind === '#') {
  5844. let n = '';
  5845. if (L.nextIf('-')) {
  5846. n = `-${L.expect('#').text()}`; // # .text();
  5847. } else {
  5848. n = L.expect('#').text(); // # .text();
  5849. }
  5850. if (kind === torch._C.TypeKind.ComplexType || n.indexOf('j') !== -1) {
  5851. throw new Error("Complex type not implemented.");
  5852. /*
  5853. const imag = std::stod(n.substr(0, n.size() - 1));
  5854. return c10::complex<double>(0, imag);
  5855. */
  5856. } else if (kind === torch._C.TypeKind.FloatType || n.indexOf('.') !== -1 || n.indexOf('e') !== -1) {
  5857. const v = parseFloat(n);
  5858. return new torch._C.IValue(v, 'Double');
  5859. } else {
  5860. const v = parseInt(n, 10);
  5861. return new torch._C.IValue(v, 'Int');
  5862. }
  5863. }
  5864. throw new python.Error('Not implemented.');
  5865. /*
  5866. switch (L.cur().kind) {
  5867. case TK_TRUE:
  5868. L.next();
  5869. return true;
  5870. case TK_FALSE:
  5871. L.next();
  5872. return false;
  5873. case TK_NONE:
  5874. L.next();
  5875. return IValue();
  5876. case TK_STRINGLITERAL: {
  5877. const token = L.next();
  5878. return parseStringLiteral(token.range, token.text());
  5879. }
  5880. case TK_IDENT: {
  5881. const tok = L.next();
  5882. const text_view = tok.text_view();
  5883. // NB: float/complex/long are here for BC purposes. Other dtypes
  5884. // are handled via str2dtype.
  5885. // Please don't add more cases to this if-else block.
  5886. if ("float" == text_view) {
  5887. return static_cast<int64_t>("at::kFloat");
  5888. } else if ("complex" == text_view) {
  5889. return static_cast<int64_t>("at::kComplexFloat");
  5890. } else if ("long" == text_view) {
  5891. return static_cast<int64_t>("at::kLong");
  5892. } else if ("strided" == text_view) {
  5893. return static_cast<int64_t>("at::kStrided");
  5894. } else if ("Mean" == text_view) {
  5895. return static_cast<int64_t>("at::Reduction::Mean");
  5896. } else if ("contiguous_format" == text_view) {
  5897. return static_cast<int64_t>("c10::MemoryFormat::Contiguous");
  5898. } else {
  5899. const text = tok.text();
  5900. if (isPossiblyOptionalScalarType(real_type) &&
  5901. str2dtype.count(text) > 0) {
  5902. return static_cast<int64_t>(str2dtype.at(text));
  5903. } else {
  5904. throw(ErrorReport(L.cur().range) << "invalid numeric default value");
  5905. }
  5906. }
  5907. }
  5908. default: {
  5909. let n;
  5910. if (L.nextIf('-')) {
  5911. n = "-" + L.expect(TK_NUMBER).text();
  5912. }
  5913. else {
  5914. n = L.expect(TK_NUMBER).text();
  5915. }
  5916. if (kind == torch._C.TypeKind.ComplexType || n.find('j') != "std::string::npos") {
  5917. throw new python.Error('Complex type not implemented.');
  5918. const imag = std::stod(n.substr(0, n.size() - 1));
  5919. return c10::complex<double>(0, imag);
  5920. } else if (kind == torch._C.TypeKind.FloatType || n.find('.') != "std::string::npos" || n.find('e') != "std::string::npos") {
  5921. throw new python.Error('Float type not implemented.');
  5922. return std::stod(n);
  5923. } else {
  5924. throw new python.Error("'torch._C.SchemaParser.parseSingleConstant' not implemented.");
  5925. int64_t v = std::stoll(n);
  5926. return v;
  5927. }
  5928. }
  5929. }
  5930. */
  5931. }
  5932. parseConstantList(type, kind, real_type) {
  5933. const L = this.L;
  5934. const tok = L.expect('[');
  5935. const vs = [];
  5936. if (L.cur().kind !== ']') {
  5937. do {
  5938. vs.push(this.parseSingleConstant(type, kind, real_type));
  5939. } while (L.nextIf(','));
  5940. }
  5941. L.expect(']');
  5942. return this.convertToList(type, kind, tok.range, vs);
  5943. }
  5944. convertToList(type, kind, range, vs) {
  5945. switch (kind) {
  5946. case torch._C.TypeKind.ComplexType:
  5947. return new torch._C.IValue(new torch._C.List(torch.ComplexType.get(), vs.map((v) => v)));
  5948. case torch._C.TypeKind.FloatType:
  5949. return new torch._C.IValue(new torch._C.List(torch.FloatType.get(), vs.map((v) => v)));
  5950. case torch._C.TypeKind.IntType:
  5951. return new torch._C.IValue(new torch._C.List(torch.IntType.get(), vs.map((v) => v)));
  5952. case torch._C.TypeKind.BoolType:
  5953. return new torch._C.IValue(new torch._C.List(torch.BoolType.get(), vs.map((v) => v)));
  5954. case torch._C.TypeKindDynamicType:
  5955. return this.convertToList(type.dynamicKind(), range, vs);
  5956. default:
  5957. // throw(ErrorReport(range) << "lists are only supported for float, int and complex types");
  5958. throw new python.Error('lists are only supported for float, int and complex types');
  5959. }
  5960. }
  5961. });
  5962. this.registerType('torch.FunctionSchema', class {
  5963. constructor(name, overload_name, args, returns, is_vararg, is_varret) {
  5964. const index = name.indexOf('(');
  5965. if (index === -1) {
  5966. this._name = name;
  5967. this._overload_name = overload_name || '';
  5968. this._arguments = args || [];
  5969. this._returns = returns || [];
  5970. this._is_vararg = is_vararg || false;
  5971. this._is_varret = is_varret || false;
  5972. } else {
  5973. const value = name.substring(0, index).trim();
  5974. const dot = value.indexOf('.');
  5975. if (dot === -1) {
  5976. this._name = value;
  5977. this._overload_name = '';
  5978. } else {
  5979. this._name = value.substring(0, dot);
  5980. this._overload_name = value.substring(dot + 1, value.length);
  5981. }
  5982. this._buffer = name.substring(index, name.length);
  5983. }
  5984. }
  5985. static parse(schema) {
  5986. return new torch.FunctionSchema(schema);
  5987. }
  5988. get name() {
  5989. return this._name;
  5990. }
  5991. get overload_name() {
  5992. return this._overload_name;
  5993. }
  5994. get arguments() {
  5995. this._parse();
  5996. return this._arguments;
  5997. }
  5998. get returns() {
  5999. this._parse();
  6000. return this._returns;
  6001. }
  6002. get is_vararg() {
  6003. this._parse();
  6004. return this._is_vararg;
  6005. }
  6006. get is_varret() {
  6007. this._parse();
  6008. return this._is_varret;
  6009. }
  6010. argumentIndexWithName(name) {
  6011. const index = this.arguments.findIndex((arg) => arg.name === name);
  6012. return index === -1 ? null : index;
  6013. }
  6014. _parse() {
  6015. if (this._buffer) {
  6016. const parser = new torch._C.SchemaParser(this._buffer, true /* parseSchemaOrName */);
  6017. const L = parser.L;
  6018. this._arguments = [];
  6019. this._is_vararg = false;
  6020. this._kwarg_only = false;
  6021. let idx = 0;
  6022. L.expect('(');
  6023. if (!L.nextIf(')')) {
  6024. while (true) {
  6025. if (this._is_vararg) {
  6026. throw new python.Error("Unexpected 'torch.FunctionSchema._is_vararg'.");
  6027. }
  6028. if (L.nextIf('*')) {
  6029. this._kwarg_only = true;
  6030. } else if (L.nextIf('...')) {
  6031. this._is_vararg = true;
  6032. } else {
  6033. const argument = parser.parseArgument(idx++, false, this._kwarg_only);
  6034. this._arguments.push(argument);
  6035. }
  6036. if (!L.nextIf(',')) {
  6037. break;
  6038. }
  6039. }
  6040. L.expect(')');
  6041. }
  6042. L.expect('->');
  6043. this._returns = [];
  6044. this._is_varret = false;
  6045. if (L.nextIf('...')) {
  6046. this._is_varret = true;
  6047. } else if (L.nextIf('(')) {
  6048. if (!L.nextIf(')')) {
  6049. while (true) {
  6050. if (this._is_varret) {
  6051. throw new python.Error("Unexpected 'torch.FunctionSchema._is_varret'.");
  6052. }
  6053. if (L.nextIf('...')) {
  6054. this._is_varret = true;
  6055. } else {
  6056. const argument = parser.parseArgument(idx++, true, false);
  6057. this._returns.push(argument);
  6058. }
  6059. if (!L.nextIf(',')) {
  6060. break;
  6061. }
  6062. }
  6063. L.expect(')');
  6064. }
  6065. } else {
  6066. this._returns.push(parser.parseArgument(0, true, false));
  6067. }
  6068. delete this._buffer;
  6069. }
  6070. }
  6071. __str__() {
  6072. const list = [this.name];
  6073. const overload_name = this.overload_name;
  6074. if (overload_name !== '' && overload_name !== 'default') {
  6075. list.push(`.${this.overload_name}`);
  6076. }
  6077. list.push('(');
  6078. let first = true;
  6079. let kwarg_only = false;
  6080. for (const argument of this.arguments) {
  6081. if (!first) {
  6082. list.push(', ');
  6083. }
  6084. if (argument.kwarg_only && !kwarg_only) {
  6085. list.push('*, ');
  6086. kwarg_only = true;
  6087. }
  6088. first = false;
  6089. list.push(argument.str());
  6090. }
  6091. if (this.is_vararg) {
  6092. if (!first) {
  6093. list.push(', ');
  6094. }
  6095. first = true;
  6096. list.push('...');
  6097. }
  6098. list.push(') -> ');
  6099. const returns = this.returns;
  6100. const braces = !this.is_varret &&
  6101. (returns.length !== 1 ||
  6102. returns[0].name ||
  6103. returns[0].real_type instanceof torch.TupleType ||
  6104. returns[0].real_type instanceof torch.ListType && returns[0].real_type.getElementType() instanceof torch.TupleType);
  6105. if (braces) {
  6106. list.push('(');
  6107. }
  6108. first = true;
  6109. for (const argument of this.returns) {
  6110. if (!first) {
  6111. list.push(', ');
  6112. }
  6113. first = false;
  6114. list.push(argument.str());
  6115. }
  6116. if (this.is_varret) {
  6117. if (!first) {
  6118. list.push(', ');
  6119. }
  6120. first = true;
  6121. list.push('...');
  6122. }
  6123. if (braces) {
  6124. list.push(')');
  6125. }
  6126. return list.join('');
  6127. }
  6128. aliasAnalysis() {
  6129. return this._alias_kind || 'CONSERVATIVE';
  6130. }
  6131. setAliasAnalysis(v) {
  6132. this._alias_kind = v;
  6133. }
  6134. hasAnyAliasInfo() {
  6135. for (const arg of this.arguments) {
  6136. if (arg.alias_info !== null) {
  6137. return true;
  6138. }
  6139. }
  6140. for (const ret of this.returns) {
  6141. if (ret.alias_info !== null) {
  6142. return true;
  6143. }
  6144. }
  6145. return false;
  6146. }
  6147. is_mutable() {
  6148. return this.arguments.some((arg) => {
  6149. const aliasInfo = arg.alias_info;
  6150. return aliasInfo && aliasInfo.is_write;
  6151. });
  6152. }
  6153. });
  6154. this.registerType('torch._C.SchemaInfo', class {
  6155. constructor(schema) {
  6156. this._schema = schema;
  6157. this._alias_maps_current = false;
  6158. this._has_init = false;
  6159. }
  6160. is_nondeterministic() {
  6161. if (this._schema.name === 'aten::dropout' && this._schema.overload === '') {
  6162. //
  6163. }
  6164. torch._C.nondeterministic_op_strings = torch._C.nondeterministic_op_strings || new Set([
  6165. 'aten::dropout(Tensor input, float p, bool train) -> Tensor',
  6166. 'aten::_fused_dropout(Tensor self, float p, Generator? generator) -> (Tensor, Tensor)',
  6167. 'aten::_standard_gamma(Tensor self, Generator? generator) -> Tensor',
  6168. 'aten::bernoulli(Tensor self, *, Generator? generator) -> Tensor',
  6169. 'aten::bernoulli(Tensor self, float p, *, Generator? generator) -> Tensor',
  6170. 'aten::multinomial(Tensor self, int num_samples, bool replacement, *, Generator? generator) -> Tensor',
  6171. 'aten::native_dropout(Tensor input, float p, bool? train) -> (Tensor, Tensor)',
  6172. 'aten::normal(Tensor mean, Tensor std, *, Generator? generator) -> Tensor',
  6173. 'aten::normal(float mean, Tensor std, *, Generator? generator) -> Tensor',
  6174. 'aten::normal(Tensor mean, float std, *, Generator? generator) -> Tensor',
  6175. 'aten::poisson(Tensor self, Generator? generator) -> Tensor',
  6176. 'aten::binomial(Tensor count, Tensor prob, Generator? generator=None) -> Tensor',
  6177. 'aten::rrelu(Tensor self, Scalar lower, Scalar upper, bool training, Generator? generator) -> Tensor',
  6178. 'aten::rrelu_with_noise(Tensor self, Tensor noise, Scalar lower, Scalar upper, bool training, Generator? generator) -> Tensor',
  6179. 'aten::rand(int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6180. 'aten::rand_like(Tensor self, *, int? dtype=None, int? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor',
  6181. 'aten::randint(int high, int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6182. 'aten::randint(int low, int high, int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6183. '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',
  6184. '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',
  6185. 'aten::randn(int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6186. 'aten::randn_like(Tensor self, *, int? dtype=None, int? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor',
  6187. 'aten::randperm(int n, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor'
  6188. ]);
  6189. if (torch._C.nondeterministic_op_strings.has(this._schema.__str__())) {
  6190. return true;
  6191. }
  6192. /*
  6193. const auto& op = c10::Dispatcher::singleton().findOp(
  6194. c10::OperatorName(schema_.name(), schema_.overload_name()));
  6195. return op && op->hasTag(at::Tag::nondeterministic_seeded);
  6196. */
  6197. return false;
  6198. }
  6199. });
  6200. this.registerType('torch._C.OperatorRegistry', class {
  6201. constructor() {
  6202. this.to_register = [];
  6203. this.operators = new Map();
  6204. }
  6205. registerPendingOperators() {
  6206. for (const op of this.to_register) {
  6207. const sym = op.schema().name;
  6208. if (!this.operators.has(sym)) {
  6209. this.operators.set(sym, []);
  6210. }
  6211. this.operators.get(sym).push(op);
  6212. }
  6213. this.to_register = [];
  6214. }
  6215. registerOperator(op) {
  6216. this.to_register.push(op);
  6217. }
  6218. getOperators(name) {
  6219. this.registerPendingOperators();
  6220. if (this.operators.has(name)) {
  6221. return this.operators.get(name);
  6222. }
  6223. return [];
  6224. }
  6225. });
  6226. this.registerFunction('torch._C.getAllOperatorsFor', (name) => {
  6227. return torch._C.getRegistry().getOperators(name);
  6228. });
  6229. this.registerType('torch._C.Operator', class {
  6230. constructor(schema) {
  6231. this._schema = schema;
  6232. }
  6233. schema() {
  6234. return this._schema;
  6235. }
  6236. getOperation(/* node */) {
  6237. return null;
  6238. }
  6239. aliasAnalysisKind() {
  6240. const schemaRef = this.schema();
  6241. const alias_analysis = schemaRef.aliasAnalysis();
  6242. torch._C.TORCH_CHECK(alias_analysis === 'FROM_SCHEMA' || !schemaRef.hasAnyAliasInfo());
  6243. return alias_analysis;
  6244. }
  6245. });
  6246. this.registerFunction('torch._C.getRegistry', () => {
  6247. torch._C.r = torch._C.r || new torch._C.OperatorRegistry();
  6248. return torch._C.r;
  6249. });
  6250. this.registerFunction('torch._C._get_schema', (op_name, overload_name) => {
  6251. const operations = torch._C.getAllOperatorsFor(op_name);
  6252. for (const op of operations) {
  6253. if (op.schema().overload_name === overload_name) {
  6254. return op.schema();
  6255. }
  6256. }
  6257. throw new python.Error(`Schema '${op_name}.${overload_name}' not found.`);
  6258. });
  6259. this.registerFunction('torch._C._jit_get_schemas_for_operator', (op_name) => {
  6260. return torch._C.getAllOperatorsFor(op_name).map((op) => op.schema());
  6261. });
  6262. this.registerFunction('torch._C._jit_get_operation', (op_name) => {
  6263. const sortedOps = torch._C.getAllOperatorsFor(op_name);
  6264. if (sortedOps.length === 0) {
  6265. return [null, null];
  6266. }
  6267. const overload_names = sortedOps.map((op) => op.schema().overload_name);
  6268. return [{}, overload_names];
  6269. });
  6270. this.registerFunction('torch._C._get_operation_overload', (op_name, overload_name) => {
  6271. const operations = torch._C.getAllOperatorsFor(op_name);
  6272. for (const op of operations) {
  6273. if (op.schema().overload_name === overload_name) {
  6274. return [{}, {}, null];
  6275. }
  6276. }
  6277. return null;
  6278. });
  6279. this.registerFunction('torch._C._unset_dispatch_mode', () => {
  6280. return null;
  6281. });
  6282. this.registerFunction('torch._C._set_dispatch_mode', () => {
  6283. });
  6284. this.registerType('torch._C.MatchedSchema', class {
  6285. constructor(inputs, return_types, return_field_names, schema_name) {
  6286. this.inputs = inputs;
  6287. this.return_types = return_types;
  6288. this.register_field_names = return_field_names;
  6289. this.schema_name = schema_name;
  6290. }
  6291. });
  6292. this.registerType('torch._C.Self', class {
  6293. });
  6294. this.registerFunction('torch._C.toValues', (g, nvs) => {
  6295. return nvs.map((v) => v.value(g));
  6296. });
  6297. this.registerType('torch._C.SimpleSelf', class extends torch._C.Self {
  6298. constructor(classType) {
  6299. super();
  6300. this._classType = classType;
  6301. }
  6302. makeSugared(v) {
  6303. v.setType(this._classType);
  6304. return new torch._C.SimpleValue(v);
  6305. }
  6306. getClassType() {
  6307. return this._classType;
  6308. }
  6309. });
  6310. this.registerType('torch._C.Function', class {
  6311. isGraphFunction() {
  6312. return false;
  6313. }
  6314. name() {
  6315. return this.qualname().name();
  6316. }
  6317. });
  6318. this.registerType('torch._C.BuiltinOpFunction', class extends torch._C.Function {
  6319. constructor(qualname, schema) {
  6320. super();
  6321. this._name = qualname;
  6322. this._schema = schema;
  6323. }
  6324. qualname() {
  6325. return this._name;
  6326. }
  6327. getSchema() {
  6328. return this._schema;
  6329. }
  6330. ensure_defined() {
  6331. }
  6332. });
  6333. this.registerType('torch._C.DeadCodeEliminator', class {
  6334. constructor(...args) {
  6335. this._aliasDb = null;
  6336. this._useAliasDb = false;
  6337. this._memo = new Map();
  6338. this._marked = new Set();
  6339. this._liveValues = new Set();
  6340. this._deleteCallback = () => {};
  6341. if (args.length > 0 && args[0] instanceof torch.Graph) {
  6342. [this._graph, this._sideEffectPolicy] = args;
  6343. this._useAliasDb = true;
  6344. } else {
  6345. [this._sideEffectPolicy] = args;
  6346. }
  6347. }
  6348. run(block, recurse) {
  6349. this.eliminateDeadForkInputs(block, recurse);
  6350. this.mark(block.return_node());
  6351. this.mark(block);
  6352. this._deleteCallback(this._liveValues);
  6353. this.sweep(block, recurse);
  6354. }
  6355. setDeleteCallback(deleteCallback) {
  6356. this._deleteCallback = deleteCallback;
  6357. }
  6358. eliminateDeadForkInputs(block, recurse) {
  6359. for (const node of block.nodes()) {
  6360. if (recurse) {
  6361. for (const sb of node.blocks()) {
  6362. this.eliminateDeadForkInputs(sb, recurse);
  6363. }
  6364. }
  6365. if (node.kind() !== 'prim::fork') {
  6366. continue;
  6367. }
  6368. const g = node.g("Subgraph");
  6369. for (let i = 0; i < g.inputs().length; i++) {
  6370. if (!g.inputs()[i].hasUses()) {
  6371. g.eraseInput(i);
  6372. node.removeInput(i);
  6373. }
  6374. }
  6375. }
  6376. }
  6377. markReturnNode(node) {
  6378. if (this._marked.has(node)) {
  6379. return false;
  6380. }
  6381. torch._C.AT_ASSERT(node.owningBlock().return_node() === node);
  6382. const outerNode = node.owningBlock().owningNode();
  6383. if (outerNode === null || outerNode.kind() === 'prim::Reverse') {
  6384. return this.mark(node);
  6385. }
  6386. if (outerNode.kind() === 'prim::Loop' || outerNode.kind() === 'c10::onnx::Loop') {
  6387. const loop = new torch._C.LoopView(outerNode);
  6388. for (let i = 0; i < loop.carriedOutputs().length; i++) {
  6389. if (outerNode.kind() === 'onnx::Loop') {
  6390. this._liveValues.add(loop.bodyCarriedOutputs()[i]);
  6391. continue;
  6392. }
  6393. const innerInput = loop.bodyCarriedInputs()[i];
  6394. const innerOutput = loop.bodyCarriedOutputs()[i];
  6395. const outerOutput = loop.carriedOutputs()[i];
  6396. if (this._liveValues.has(outerOutput) || innerInput.hasUses()) {
  6397. this._liveValues.add(innerOutput);
  6398. }
  6399. }
  6400. this._liveValues.add(loop.nextCond());
  6401. } else {
  6402. torch._C.AT_ASSERT(outerNode.outputs().length === node.inputs().length);
  6403. for (let i = 0; i < outerNode.outputs().length; i++) {
  6404. const innerOutput = node.inputs()[i];
  6405. const outerOutput = outerNode.outputs()[i];
  6406. if (!this._liveValues.has(outerOutput)) {
  6407. this._liveValues.add(innerOutput);
  6408. }
  6409. }
  6410. }
  6411. this._marked.add(node);
  6412. return true;
  6413. }
  6414. markLoop(node) {
  6415. torch._C.TORCH_INTERNAL_ASSERT(node.kind() === 'prim::Loop');
  6416. let marked = false;
  6417. let anyMarked = false;
  6418. do {
  6419. marked = this.mark(node.blocks().at(0));
  6420. anyMarked = anyMarked || marked;
  6421. } while (marked);
  6422. return anyMarked;
  6423. }
  6424. mark(...args) {
  6425. if (args.length === 1 && args[0] instanceof torch.Block) {
  6426. const [block] = args;
  6427. let anyMarked = false;
  6428. for (const node of block.nodes()) {
  6429. if (this._sideEffectPolicy === 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS' && this.hasSideEffects(node)) {
  6430. const marked = this.mark(node);
  6431. anyMarked = anyMarked || marked;
  6432. }
  6433. }
  6434. const marked = this.markReturnNode(block.return_node());
  6435. anyMarked = anyMarked || marked;
  6436. for (const node of block.nodes()) {
  6437. if (node.kind() === 'prim::Loop') {
  6438. const marked = this.markLoop(node);
  6439. anyMarked = anyMarked || marked;
  6440. } else {
  6441. for (const subBlock of node.blocks()) {
  6442. const marked = this.mark(subBlock);
  6443. anyMarked = anyMarked || marked;
  6444. }
  6445. }
  6446. const marked = this.markIfLive(node);
  6447. anyMarked = anyMarked || marked;
  6448. }
  6449. return anyMarked;
  6450. }
  6451. if (args.length === 1 && args[0] instanceof torch.Node) {
  6452. const [node] = args;
  6453. if (this._marked.has(node)) {
  6454. return false;
  6455. }
  6456. this._marked.add(node);
  6457. let curNode = node;
  6458. while (curNode && curNode.owningBlock()) {
  6459. this.mark(curNode);
  6460. curNode = curNode.owningBlock().owningNode();
  6461. }
  6462. for (const input of node.inputs()) {
  6463. if (!this._liveValues.has(input)) {
  6464. this._liveValues.add(input);
  6465. }
  6466. }
  6467. return true;
  6468. }
  6469. throw new python.Error('Not implemented.');
  6470. }
  6471. markIfLive(node) {
  6472. for (const output of node.outputs()) {
  6473. if (this._liveValues.has(output)) {
  6474. return this.mark(node);
  6475. }
  6476. }
  6477. if (this._useAliasDb) {
  6478. if (this.getOrCreateAliasDb().writesToAlias(node, this._liveValues)) {
  6479. return this.mark(node);
  6480. }
  6481. }
  6482. return false;
  6483. }
  6484. sweep(block, recurse) {
  6485. const nodes = Array.from(block.nodes()).reverse();
  6486. for (const node of nodes) {
  6487. this.removeDeadBlockOutputs(node);
  6488. this.removeDeadLoopOutputs(node);
  6489. if (recurse) {
  6490. for (const block of node.blocks()) {
  6491. this.sweep(block, true);
  6492. }
  6493. }
  6494. if (!this._marked.has(node) && !node.hasUses()) {
  6495. node.destroy();
  6496. }
  6497. }
  6498. }
  6499. hasUntrackedMutation(node) {
  6500. if (!this._useAliasDb) {
  6501. if (node.kind() === 'prim::SetAttr') {
  6502. return true;
  6503. }
  6504. const schema = node.maybeSchema();
  6505. return schema && schema.is_mutable();
  6506. }
  6507. return this.getOrCreateAliasDb().writesToWildcard(node);
  6508. }
  6509. hasSideEffects(node) {
  6510. const it = this._memo.get(node);
  6511. if (it) {
  6512. return it;
  6513. }
  6514. const has_side_effects = node.hasSideEffects() ||
  6515. node.blocks().some((b) => Array.from(b.nodes()).some((n) => this.hasSideEffects(n))) ||
  6516. this.hasUntrackedMutation(node);
  6517. this._memo.set(node, has_side_effects);
  6518. return has_side_effects;
  6519. }
  6520. removeDeadBlockOutputs(node) {
  6521. if (node.kind() !== 'prim::If' && node.kind() !== 'prim::GradOf') {
  6522. return;
  6523. }
  6524. for (let i_1 = node.outputs().length; i_1 > 0; i_1--) {
  6525. const i = i_1 - 1;
  6526. if (!node.outputs()[i].hasUses()) {
  6527. node.eraseOutput(i);
  6528. for (const b of node.blocks()) {
  6529. b.eraseOutput(i);
  6530. }
  6531. }
  6532. }
  6533. }
  6534. removeDeadLoopOutputs() {
  6535. }
  6536. getOrCreateAliasDb() {
  6537. if (!this._aliasDb) {
  6538. this._aliasDb = new torch._C.AliasDb(this._graph);
  6539. }
  6540. return this._aliasDb;
  6541. }
  6542. });
  6543. this.registerFunction('torch._C.EliminateDeadCode', (...args) => {
  6544. if (args.length === 1 && args[0] instanceof torch.Graph) {
  6545. const [graph] = args;
  6546. const sideEffectPolicy = 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS';
  6547. const worker = new torch._C.DeadCodeEliminator(graph, sideEffectPolicy);
  6548. worker.run(graph.block(), /*recurse=*/true);
  6549. } else if (args.length > 0 && args[0] instanceof torch.Block) {
  6550. const [block] = args;
  6551. const recurse = false;
  6552. const sideEffectPolicy = 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS';
  6553. const worker = new torch._C.DeadCodeEliminator(sideEffectPolicy);
  6554. worker.run(block, recurse);
  6555. } else {
  6556. throw new python.Error('Not implemented.');
  6557. }
  6558. });
  6559. this.registerFunction('torch._C.removeTupleNodes', () => {
  6560. });
  6561. this.registerFunction('torch._C.LowerSimpleTuples', (...args) => {
  6562. if (args.length === 1 && args[0] instanceof torch.Graph) {
  6563. const [graph] = args;
  6564. torch._C.LowerSimpleTuples(graph.block());
  6565. torch._C.EliminateDeadCode(graph);
  6566. } else if (args.length === 1 && args[0] instanceof torch.Block) {
  6567. const [block] = args;
  6568. for (const n of block.nodes()) {
  6569. torch._C.removeTupleNodes(n, false);
  6570. for (const b of n.blocks()) {
  6571. torch._C.LowerSimpleTuples(b);
  6572. }
  6573. }
  6574. } else {
  6575. throw new python.Error('Not implemented.');
  6576. }
  6577. });
  6578. this.registerFunction('torch._C.attributesEqualCSE', (lhs, rhs) => {
  6579. torch._C.AT_ASSERT(lhs !== null);
  6580. torch._C.AT_ASSERT(rhs !== null);
  6581. if (lhs.hasAttributes() !== rhs.hasAttributes()) {
  6582. return false;
  6583. }
  6584. if (!lhs.hasAttributes() && !rhs.hasAttributes()) {
  6585. return true;
  6586. }
  6587. const lnames = lhs.attributeNames();
  6588. const rnames = rhs.attributeNames();
  6589. lnames.sort();
  6590. rnames.sort();
  6591. if (lnames.length !== rnames.length && !lnames.every((v, i) => v !== rnames[i])) {
  6592. return false;
  6593. }
  6594. for (const name of lnames) {
  6595. if (lhs.kindOf(name) !== rhs.kindOf(name)) {
  6596. return false;
  6597. }
  6598. const kind = lhs.kindOf(name);
  6599. switch (kind) {
  6600. case 'i':
  6601. case 'f':
  6602. case 's':
  6603. case 't': {
  6604. if (lhs[kind](name) !== rhs[kind](name)) {
  6605. return false;
  6606. }
  6607. break;
  6608. }
  6609. case 'c': {
  6610. const lc = lhs.c(name);
  6611. const rc = rhs.c(name);
  6612. if (lc.real !== rc.real || lc.imag !== rc.imag) {
  6613. return false;
  6614. }
  6615. break;
  6616. }
  6617. case 'ival': {
  6618. if (lhs[kind](name) !== rhs[kind](name)) {
  6619. return false;
  6620. }
  6621. break;
  6622. }
  6623. default: {
  6624. throw new python.Error('Not implemented.');
  6625. }
  6626. }
  6627. }
  6628. return true;
  6629. });
  6630. this.registerFunction('torch._C.get_hash', (...args) => {
  6631. let hash = 0;
  6632. for (const value of args) {
  6633. if (typeof value === 'number') {
  6634. hash += (value | 0);
  6635. } else if (typeof value === 'string') {
  6636. hash += (value.length | 0);
  6637. } else if (Array.isArray(value)) {
  6638. for (const item of value) {
  6639. hash += torch._C.get_hash(item);
  6640. }
  6641. } else if (value instanceof builtins.complex) {
  6642. hash += (value.real | 0) + (value.imag | 0);
  6643. }
  6644. }
  6645. return hash;
  6646. });
  6647. this.registerFunction('torch._C.HashNode', (k) => {
  6648. torch._C.AT_ASSERT(k !== null);
  6649. let constant_hash = 0;
  6650. if (k.kind() === 'prim::Constant') {
  6651. const type = k.output().type();
  6652. if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'i') {
  6653. constant_hash = k.i('value');
  6654. } else if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'f') {
  6655. constant_hash = k.f('value');
  6656. } else if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'c') {
  6657. constant_hash = k.c('value');
  6658. } else if (type.isSubtypeOf(torch.BoolType.get())) {
  6659. constant_hash = k.i('value');
  6660. }
  6661. }
  6662. return torch._C.get_hash(k.kind(), k.outputs().map((v) => v.type().kind()), k.inputs().map((v) => v.unique()), constant_hash);
  6663. });
  6664. this.registerFunction('torch._C.EqualNode', (lhs, rhs) => {
  6665. if (lhs === null && rhs === null) {
  6666. return true;
  6667. }
  6668. if (lhs === null || rhs === null) {
  6669. return false;
  6670. }
  6671. if (lhs.kind() !== rhs.kind()) {
  6672. return false;
  6673. }
  6674. const lhs_outputs = lhs.outputs();
  6675. const rhs_outputs = rhs.outputs();
  6676. if (lhs_outputs.length !== rhs_outputs.length) {
  6677. return false;
  6678. }
  6679. for (let i = 0; i < lhs_outputs.length; i++) {
  6680. const lt = lhs_outputs[i].type();
  6681. const rt = rhs_outputs[i].type();
  6682. if (!lt.equals(rt)) {
  6683. return false;
  6684. }
  6685. }
  6686. const lhs_inputs = lhs.inputs();
  6687. const rhs_inputs = rhs.inputs();
  6688. if (lhs_inputs.length !== rhs_inputs.length) {
  6689. return false;
  6690. }
  6691. if (!lhs_inputs.every((v, i) => v === rhs_inputs[i])) {
  6692. return false;
  6693. }
  6694. if (!torch._C.attributesEqualCSE(lhs, rhs)) {
  6695. return false;
  6696. }
  6697. if (lhs.blocks().length !== rhs.blocks().length) {
  6698. return false;
  6699. }
  6700. for (let i = 0; i < lhs.blocks().length; i++) {
  6701. if (lhs.blocks().at(i) !== rhs.blocks().at(i)) {
  6702. return false;
  6703. }
  6704. }
  6705. return true;
  6706. });
  6707. this.registerType('torch._C.NodeSet', class {
  6708. constructor() {
  6709. this._nodes = new Map();
  6710. }
  6711. insert(n) {
  6712. const key = torch._C.HashNode(n);
  6713. if (this._nodes.has(key)) {
  6714. this._nodes.get(key).push(n);
  6715. } else {
  6716. this._nodes.set(key, [n]);
  6717. }
  6718. }
  6719. get(n) {
  6720. const key = torch._C.HashNode(n);
  6721. if (this._nodes.has(key)) {
  6722. const nodes = this._nodes.get(key);
  6723. for (const node of nodes) {
  6724. if (torch._C.EqualNode(node, n)) {
  6725. return node;
  6726. }
  6727. }
  6728. }
  6729. return null;
  6730. }
  6731. has(n) {
  6732. return this.get(n) !== null;
  6733. }
  6734. });
  6735. this.registerFunction('torch._C.isinstance', (stack, types) => {
  6736. const ty = stack.pop().type();
  6737. for (const candidate of types) {
  6738. if (ty.isSubtypeOf(candidate)) {
  6739. stack.push(new torch._C.IValue(true, 'Bool'));
  6740. stack.push(true);
  6741. return;
  6742. }
  6743. }
  6744. stack.push(new torch._C.IValue(false, 'Bool'));
  6745. });
  6746. this.registerType('torch._C.Tuple', class {
  6747. constructor(elements) {
  6748. this._elements = elements;
  6749. }
  6750. static create(elements) {
  6751. return new torch._C.Tuple(elements);
  6752. }
  6753. elements() {
  6754. return this._elements;
  6755. }
  6756. });
  6757. this.registerFunction('torch._C.tupleConstruct', (stack, num_inputs) => {
  6758. torch._C.TORCH_CHECK(num_inputs <= stack.length);
  6759. const elems = stack.splice(stack.length - num_inputs, num_inputs);
  6760. const tuple = torch._C.Tuple.create(elems.reverse());
  6761. stack.push(new torch._C.IValue(tuple));
  6762. });
  6763. this.registerFunction('torch._C.runNodeIfInputsAreConstant', (n, ignore_custom_classes, db) => {
  6764. let stack = [];
  6765. for (const input of n.inputs()) {
  6766. const ival = torch._C.toIValue(input);
  6767. if (ival) {
  6768. stack.push(ival);
  6769. } else {
  6770. return null;
  6771. }
  6772. }
  6773. switch (n.kind()) {
  6774. case 'prim::ListUnpack': {
  6775. if (stack.back().toList().size() !== n.outputs().length) {
  6776. return null;
  6777. }
  6778. torch._C.listUnpack(stack, n.outputs().length);
  6779. break;
  6780. }
  6781. case 'prim::TupleConstruct': {
  6782. const tt = n.output().type().expect(torch.TupleType);
  6783. if (tt.name()) {
  6784. torch._C.namedTupleConstruct(stack, tt, n.inputs().length);
  6785. } else {
  6786. torch._C.tupleConstruct(stack, n.inputs().length);
  6787. }
  6788. break;
  6789. }
  6790. case 'prim::ListConstruct': {
  6791. torch._C.listConstruct(stack, n.output().type().expect(torch.ListType), n.inputs().length);
  6792. break;
  6793. }
  6794. case 'prim::DictConstruct': {
  6795. torch._C.dictConstruct(stack, n.output().type().expect(torch.DictType), n.inputs().length);
  6796. break;
  6797. }
  6798. case 'prim::CreateObject': {
  6799. torch._C.createObject(stack, n.output().type().expect(torch.ClassType), /*use_weak_ref*/ true);
  6800. break;
  6801. }
  6802. case 'prim::GetAttr': {
  6803. const attr = torch._C.pop(stack).toObject().getAttr(n.s('name'));
  6804. torch._C.push(stack, attr);
  6805. break;
  6806. }
  6807. case 'prim::isinstance': {
  6808. torch._C.isinstance(stack, n.tys('types'));
  6809. break;
  6810. }
  6811. default: {
  6812. const maybe_schema = n.maybeSchema();
  6813. if (maybe_schema && maybe_schema.is_vararg) {
  6814. return null;
  6815. }
  6816. // try
  6817. // {
  6818. // const op = n.getOperation();
  6819. // op(stack);
  6820. const [module, name] = n.kind().split('::');
  6821. const obj = torch.ops[module];
  6822. if (!obj) {
  6823. throw new python.Error(`Unknown constant module 'torch.ops.${module}'.`);
  6824. }
  6825. const fn = torch.ops[module].__getattr__(name);
  6826. if (!fn || !fn.__call__) {
  6827. throw new python.Error(`Unknown constant function 'torch.ops.${module}.${name}'.`);
  6828. }
  6829. const args = stack.map((v) => v.value);
  6830. const result = fn.__call__(...args);
  6831. if (result === undefined) {
  6832. stack = [];
  6833. } else if (result instanceof torch._C.IValue) {
  6834. stack = [result];
  6835. } else if (Array.isArray(result) && result.every((v) => v instanceof torch._C.IValue)) {
  6836. stack = result;
  6837. } else {
  6838. stack = [new torch._C.IValue(result)];
  6839. }
  6840. // } catch {
  6841. // stack = [];
  6842. // return null;
  6843. // }
  6844. break;
  6845. }
  6846. }
  6847. for (const v of stack) {
  6848. if (v.isTensor()) {
  6849. const t = v.toTensor();
  6850. if (t.defined() && t.requires_grad()) {
  6851. return null;
  6852. }
  6853. }
  6854. if (ignore_custom_classes) {
  6855. if (v.isCustomClass()) {
  6856. return null;
  6857. }
  6858. }
  6859. if (v.isCustomClass()) {
  6860. if (v.toObject().is_weak_compilation_ref()) {
  6861. continue;
  6862. }
  6863. if (!db) {
  6864. continue;
  6865. }
  6866. const n_non_const = n;
  6867. if (db.mayContainAlias(n_non_const.inputs(), [n_non_const.outputs()])) {
  6868. continue;
  6869. }
  6870. const obj = v.toObject();
  6871. obj.unsafe_make_weak_compilation_ref();
  6872. }
  6873. if (v.isObject()) {
  6874. if (!v.toObject().is_weak_compilation_ref()) {
  6875. return null;
  6876. }
  6877. }
  6878. }
  6879. return stack;
  6880. });
  6881. this.registerType('torch._C.ConstantPropagator', class {
  6882. constructor(graph, aliasing_types, ignore_custom_classes) {
  6883. this._made_change = false;
  6884. this._graph = graph;
  6885. this._aliasing_types = aliasing_types;
  6886. this._ignore_custom_classes = ignore_custom_classes;
  6887. }
  6888. static NoAliasDb(graph) {
  6889. return new torch._C.ConstantPropagator(graph, false, false);
  6890. }
  6891. run() {
  6892. this.ConstantPropagation(this._graph.block());
  6893. return this._made_change;
  6894. }
  6895. propagateNode(n) {
  6896. let outputs = [];
  6897. const outputs_opt = torch._C.runNodeIfInputsAreConstant(n, this._ignore_custom_classes);
  6898. if (outputs_opt) {
  6899. outputs = outputs_opt;
  6900. const graph = n.owningGraph();
  6901. const guard = new torch._C.WithInsertPoint(n);
  6902. for (let i = 0; i < outputs.length; i++) {
  6903. const new_output = torch._C.tryInsertConstant(graph, outputs[i]);
  6904. if (new_output) {
  6905. this._made_change = true;
  6906. if (outputs[i].isNone()) {
  6907. new_output.setType(n.outputs()[i].type());
  6908. }
  6909. n.outputs()[i].replaceAllUsesWith(new_output);
  6910. }
  6911. }
  6912. guard.dispose();
  6913. }
  6914. }
  6915. removeLoopNode(n) {
  6916. const loop_input_offset = 2;
  6917. for (let i = 0; i < n.outputs().length; i++) {
  6918. n.outputs()[i].replaceAllUsesWith(n.inputs()[i + loop_input_offset]);
  6919. }
  6920. this._made_change = true;
  6921. n.destroy();
  6922. }
  6923. loopWillNotRun(node) {
  6924. const [trip_count, start_cond] = node.inputs();
  6925. const iter_len = torch._C.constant_as(trip_count, 'toInt', 1);
  6926. const cond_val = torch._C.constant_as(start_cond, 'toBool', true);
  6927. const loop_might_run = cond_val && iter_len > 0;
  6928. return !loop_might_run;
  6929. }
  6930. inlineIfBody(body) {
  6931. const n = body.owningNode();
  6932. for (const body_node of body.nodes()) {
  6933. body_node.moveBefore(n);
  6934. }
  6935. for (let i = 0; i < n.outputs().length; i++) {
  6936. n.outputs()[i].replaceAllUsesWith(body.outputs()[i]);
  6937. }
  6938. n.destroy();
  6939. }
  6940. inlineIf(n) {
  6941. const input_bool = torch._C.constant_as(n.input(), 'toBool');
  6942. torch._C.AT_ASSERT(input_bool !== null);
  6943. const block_index = input_bool ? 0 : 1;
  6944. this.ConstantPropagation(n.blocks().at(block_index));
  6945. this.inlineIfBody(n.blocks().at(block_index));
  6946. this._made_change = true;
  6947. }
  6948. replaceAndRemoveIfOutput(n, i, replacement) {
  6949. n.outputs()[i].replaceAllUsesWith(replacement);
  6950. n.eraseOutput(i);
  6951. n.blocks().at(0).eraseOutput(i);
  6952. n.blocks().at(1).eraseOutput(i);
  6953. }
  6954. removeExtraIfOutputs(n) {
  6955. torch._C.TORCH_CHECK(n.kind() === 'prim::If');
  6956. const [true_block, false_block] = n.blocks();
  6957. const graph = n.owningGraph();
  6958. const initial_outputs = true_block.outputs().length;
  6959. const guard = new torch._C.WithInsertPoint(n);
  6960. for (let i = 0; i < true_block.outputs().length;) {
  6961. const t_out = true_block.outputs()[i];
  6962. const f_out = false_block.outputs()[i];
  6963. if (true_block.outputs()[i] === false_block.outputs()[i]) {
  6964. this.replaceAndRemoveIfOutput(n, i, true_block.outputs()[i]);
  6965. continue;
  6966. }
  6967. const maybe_const = torch._C.toIValue(t_out);
  6968. if (maybe_const && torch._C.EqualNode(t_out.node(), f_out.node())) {
  6969. const new_const = graph.insertConstant(maybe_const);
  6970. this.replaceAndRemoveIfOutput(n, i, new_const);
  6971. continue;
  6972. }
  6973. i++;
  6974. }
  6975. this._made_change = this._made_change || (initial_outputs !== true_block.outputs().length);
  6976. guard.dispose();
  6977. }
  6978. removeExtraLoopOutputs(node) {
  6979. const initial_outputs = node.outputs().length;
  6980. const [loop_body] = node.blocks();
  6981. const loop_input_offset = 2;
  6982. const loop_body_offset = 1;
  6983. for (let i_1 = node.outputs().length; i_1 > 0; i_1--) {
  6984. const i = i_1 - 1;
  6985. if (loop_body.inputs()[loop_body_offset + i] === loop_body.outputs()[loop_body_offset + i]) {
  6986. const node_input = node.inputs()[loop_input_offset + i];
  6987. node.outputs().at(i).replaceAllUsesWith(node_input);
  6988. loop_body.inputs()[loop_body_offset + i].replaceAllUsesWith(node_input);
  6989. node.eraseOutput(i);
  6990. node.removeInput(loop_input_offset + i);
  6991. loop_body.eraseInput(loop_body_offset + i);
  6992. loop_body.eraseOutput(loop_body_offset + i);
  6993. }
  6994. }
  6995. this._made_change = this._made_change || (initial_outputs !== node.outputs().length);
  6996. }
  6997. noMutableValues(values) {
  6998. return values.every((v) => !torch._C.AliasDb.isMutableType(v));
  6999. }
  7000. getOrCreateAliasDb() {
  7001. if (!this._aliasDb) {
  7002. this._aliasDb = new torch._C.AliasDb(this._graph);
  7003. }
  7004. return this._aliasDb;
  7005. }
  7006. supportedNode(n) {
  7007. torch._C.skip_list = torch._C.skip_list || new Set([
  7008. 'prim::If',
  7009. 'prim::Loop',
  7010. 'prim::Closure',
  7011. 'prim::Constant',
  7012. 'prim::AutogradZero',
  7013. 'prim::Uninitialized',
  7014. 'prim::Guard',
  7015. 'prim::profile',
  7016. 'prim::profile_ivalue',
  7017. 'prim::unchecked_unwrap_optional',
  7018. 'prim::awaitable',
  7019. 'aten::dequantize'
  7020. ]);
  7021. let no_mutation = false;
  7022. if (this._aliasing_types) {
  7023. no_mutation = !this.getOrCreateAliasDb().hasWriters(n);
  7024. } else {
  7025. no_mutation = this.noMutableValues(n.inputs()) && this.noMutableValues(n.outputs());
  7026. }
  7027. return no_mutation && !n.kind().startsWith('onnx::') && !torch._C.skip_list.has(n.kind()) && !n.isNondeterministic() && !n.hasSideEffects() && n.blocks().length === 0;
  7028. }
  7029. ConstantPropagation(...args) {
  7030. if (args[0] instanceof torch.Graph) {
  7031. throw new python.Error('Not implemented.');
  7032. } else if (args[0] instanceof torch.Block) {
  7033. const [block] = args;
  7034. for (const n of block.nodes()) {
  7035. this.ConstantPropagation(n);
  7036. }
  7037. } else if (args[0] instanceof torch.Node) {
  7038. const [n] = args;
  7039. const constant_inputs = n.inputs().every((v) => v.node().kind() === 'prim::Constant');
  7040. if (n.kind() === 'prim::If') {
  7041. if (constant_inputs) {
  7042. this.inlineIf(n);
  7043. } else {
  7044. this.ConstantPropagation(n.blocks());
  7045. this.removeExtraIfOutputs(n);
  7046. }
  7047. } else if (n.kind() === 'prim::Loop') {
  7048. if (this.loopWillNotRun(n)) {
  7049. this.removeLoopNode(n);
  7050. } else {
  7051. this.ConstantPropagation(n.blocks());
  7052. this.removeExtraLoopOutputs(n);
  7053. }
  7054. } else if (constant_inputs && this.supportedNode(n)) {
  7055. this.propagateNode(n);
  7056. } else {
  7057. this.ConstantPropagation(n.blocks()); // not implemented
  7058. }
  7059. } else if (args.length === 1 && Array.isArray(args[0]) && args[0].every((b) => b instanceof torch.Block)) {
  7060. const [blocks] = args;
  7061. for (const block of blocks) {
  7062. this.ConstantPropagation(block);
  7063. }
  7064. } else {
  7065. throw new python.Error('Not implemented.');
  7066. }
  7067. }
  7068. });
  7069. this.registerFunction('torch._C.ConstantPropagationImmutableTypes', (graph) => {
  7070. const cp = torch._C.ConstantPropagator.NoAliasDb(graph);
  7071. const made_change = cp.run();
  7072. if (made_change) {
  7073. torch._C.EliminateDeadCode(graph);
  7074. }
  7075. return made_change;
  7076. });
  7077. this.registerType('torch._C.MutableTypePtrHelper', class {
  7078. constructor(mutable_type_cache) {
  7079. this._mutable_type_cache = mutable_type_cache;
  7080. }
  7081. mapTypeToAliasTypeSet(type) {
  7082. if (this._mutable_type_cache) {
  7083. const result = this.mapTypeToBorrowedAliasTypeSet(type);
  7084. if (result) {
  7085. return result;
  7086. }
  7087. }
  7088. return this.mapTypeToAliasTypeSetImpl(type);
  7089. }
  7090. mapTypeToAliasTypeSetImpl(type) {
  7091. if (type instanceof torch.ListType ||
  7092. type instanceof torch.DictType ||
  7093. type instanceof torch.ClassType ||
  7094. type instanceof torch.TensorType) {
  7095. return [torch._C.unshapedType(type)];
  7096. }
  7097. if (type instanceof torch.UnionType) {
  7098. const mutable_types = [];
  7099. for (const inner of type.expect(torch.UnionType).containedTypes()) {
  7100. const maybe_inner_types = this.mapTypeToAliasTypeSet(inner);
  7101. if (maybe_inner_types) {
  7102. mutable_types.push(...maybe_inner_types);
  7103. }
  7104. }
  7105. if (mutable_types.length === 0) {
  7106. return null;
  7107. }
  7108. return mutable_types;
  7109. }
  7110. if (type instanceof torch.OptionalType) {
  7111. const inner = type.getElementType();
  7112. return this.mapTypeToAliasTypeSet(inner);
  7113. }
  7114. if (type instanceof torch.AnyType) {
  7115. return [torch._C.AliasTypeSet([type])];
  7116. }
  7117. if (type instanceof torch.FutureType) {
  7118. const maybe_mut_types = this.mapTypeToAliasTypeSet(type.getElementType());
  7119. if (maybe_mut_types) {
  7120. return [torch._C.AliasTypeSet([torch.FutureType.create(torch._C.toSingleType(maybe_mut_types))])];
  7121. }
  7122. return null;
  7123. }
  7124. if (type instanceof torch.AwaitType) {
  7125. const maybe_mut_types = this.mapTypeToAliasTypeSet(type.getElementType());
  7126. if (maybe_mut_types) {
  7127. return [torch._C.AliasTypeSet([torch.AwaitType.create(torch._C.toSingleType(maybe_mut_types))])];
  7128. }
  7129. return null;
  7130. }
  7131. if (type instanceof torch.TupleType) {
  7132. const mutable_types = [];
  7133. for (const inner of type.elements()) {
  7134. const maybe_inner_types = this.mapTypeToAliasTypeSet(inner);
  7135. if (maybe_inner_types) {
  7136. mutable_types.push(...maybe_inner_types);
  7137. }
  7138. }
  7139. if (mutable_types.length === 0) {
  7140. return null;
  7141. }
  7142. return [[torch.TupleType.create(mutable_types)]];
  7143. }
  7144. return null;
  7145. }
  7146. });
  7147. this.registerFunction('torch._C.isMutableTypeImpl', (type, mutable_type_cache) => {
  7148. if (type instanceof torch.TensorType || type instanceof torch.ListType ||
  7149. type instanceof torch.ClassType || type instanceof torch.DictType) {
  7150. return true;
  7151. }
  7152. const helper = new torch._C.MutableTypePtrHelper(mutable_type_cache);
  7153. if (mutable_type_cache) {
  7154. return helper.mapTypeToBorrowedAliasTypeSet(type) !== null;
  7155. }
  7156. return helper.mapTypeToAliasTypeSet(type) !== null;
  7157. });
  7158. this.registerType('torch._C.AliasDb', class {
  7159. constructor() {
  7160. this._writeIndex = new Map();
  7161. }
  7162. static isMutableType(...args) {
  7163. if (args[0] instanceof torch.Type) {
  7164. const [type] = args;
  7165. return torch._C.isMutableTypeImpl(type, null);
  7166. }
  7167. if (args[0] instanceof torch.Value) {
  7168. const [value] = args;
  7169. return torch._C.AliasDb.isMutableType(value.type());
  7170. }
  7171. throw new python.Error('Not implemented.');
  7172. }
  7173. writesToAlias(/* n, vs */) {
  7174. /*
  7175. const writtenTo = this.getWrites(n);
  7176. if (writtenTo.length === 0) {
  7177. return false;
  7178. }
  7179. MemoryLocations locs;
  7180. for (const v of vs) {
  7181. const it = elementMap_.find(v);
  7182. if (it != elementMap_.end()) {
  7183. const auto& vlocs = memoryDAG_->getMemoryLocations(it->second);
  7184. if (writtenTo.intersects(vlocs)) {
  7185. return true;
  7186. }
  7187. }
  7188. }
  7189. */
  7190. return false;
  7191. }
  7192. writesToWildcard(n) {
  7193. if (!this._writeIndex.has(n)) {
  7194. return false;
  7195. }
  7196. const writes = this._writeIndex.get(n);
  7197. for (const pr of this._wildcardIndex) {
  7198. const [, wildcardElement] = pr;
  7199. if (writes.test(wildcardElement.index)) {
  7200. return true;
  7201. }
  7202. }
  7203. return false;
  7204. }
  7205. safeToChangeAliasingRelationship(a, b) {
  7206. if (torch._C.hasWriters(a) || torch._C.hasWriters(b)) {
  7207. return false;
  7208. }
  7209. return !(torch._C.escapesScope(a) && torch._C.escapesScope(b));
  7210. }
  7211. });
  7212. this.registerFunction('torch._C.hasWriters', () => {
  7213. });
  7214. this.registerFunction('torch._C.escapesScope', () => {
  7215. });
  7216. this.registerType('torch._C.DepthFirstGraphNodeIterator', class {
  7217. constructor(graph) {
  7218. this._current = graph.block().nodes().front();
  7219. }
  7220. next() {
  7221. return null;
  7222. }
  7223. });
  7224. this.registerType('torch._C.ConcatCombiner', class {
  7225. constructor(graph) {
  7226. this._graph = graph;
  7227. this._aliasDb = new torch._C.AliasDb(graph);
  7228. this._combinable_concats = [];
  7229. }
  7230. collectOptimizableConcats() {
  7231. const graph_it = new torch._C.DepthFirstGraphNodeIterator(this._graph);
  7232. for (let node = graph_it.next(); node !== null; node = graph_it.next()) {
  7233. if (node.kind() === 'aten::cat') {
  7234. this.handleConcat(node);
  7235. }
  7236. }
  7237. }
  7238. combineConcats() {
  7239. if (this._combinable_concats.length === 0) {
  7240. return false;
  7241. }
  7242. const list_construct_inputs = this.getListConstructInputs();
  7243. for (const node_and_new_list of list_construct_inputs) {
  7244. const [node, inputs] = node_and_new_list;
  7245. const new_list_construct = this.createListConstruct(inputs);
  7246. const old_list_construct = node.input(0).node();
  7247. new_list_construct.output().setType(old_list_construct.output().type());
  7248. new_list_construct.insertBefore(node);
  7249. old_list_construct.replaceAllUsesWith(new_list_construct);
  7250. }
  7251. return true;
  7252. }
  7253. run() {
  7254. this.collectOptimizableConcats();
  7255. const changed = this.combineConcats();
  7256. if (changed) {
  7257. torch._C.EliminateDeadCode(this._graph);
  7258. }
  7259. return changed;
  7260. }
  7261. });
  7262. this.registerFunction('torch._C.CombineConcats', (graph) => {
  7263. const changed = new torch._C.ConcatCombiner(graph).run();
  7264. return changed;
  7265. });
  7266. this.registerType('torch._C.PeepholeOptimizeImpl', class {
  7267. constructor(graph, disable_shape_peepholes) {
  7268. this._graph = graph;
  7269. this._shape_peepholes = !disable_shape_peepholes;
  7270. }
  7271. run() {
  7272. let changed = this.optimizeBlock(this._graph.block());
  7273. /* changed |= torch._C.PeepholeOptimizeListIdioms(this._graph);
  7274. changed |= torch._C.PeepholeOptimizeDictIdioms(this._graph);
  7275. changed |= torch._C.PeepholeOptimizeAliasSensitive(this._graph, this._shape_peepholes);
  7276. changed |= torch._C.PeepholeOptimizeNonTensor(this._graph); */
  7277. changed = changed || torch._C.CombineConcats(this._graph);
  7278. return changed;
  7279. }
  7280. optimizeBlock(block) {
  7281. let changed = false;
  7282. for (const node of block.nodes()) {
  7283. for (const sub_block of node.blocks()) {
  7284. changed = changed || this.optimizeBlock(sub_block);
  7285. }
  7286. if (node.kind() !== 'prim::Constant') {
  7287. const guard = new torch._C.WithInsertPoint(node);
  7288. for (const output of node.outputs()) {
  7289. if (output.type() instanceof torch.NoneType) {
  7290. output.replaceAllUsesWith(this._graph.insertConstant(new torch._C.IValue()));
  7291. changed = true;
  7292. }
  7293. }
  7294. guard.dispose();
  7295. }
  7296. if (node.kind() === 'prim::If') {
  7297. // throw new python.Error('Not implemented.');
  7298. /*
  7299. const n = new torch._C.IfView(node);
  7300. // this handles redundant short circuits like "x and True" or "x or
  7301. // False"
  7302. for (const auto i : c10::irange(n.outputs().length)) {
  7303. if (n.outputs().at(i).type() != torch.BoolType.get()) {
  7304. continue;
  7305. }
  7306. const true_val = constant_as<bool>(n.thenOutputs().at(i)).value_or(false);
  7307. const false_val = constant_as<bool>(n.elseOutputs().at(i)).value_or(true);
  7308. if (true_val && !false_val) {
  7309. n.outputs().at(i).replaceAllUsesWith(n.cond());
  7310. changed = true;
  7311. }
  7312. }
  7313. for (let i = 0; i < n.outputs().length; ++i) {
  7314. const inputs_non_optional = !n.thenOutputs().at(i).type().cast<OptionalType>() && !n.elseOutputs().at(i).type().cast<OptionalType>();
  7315. const output_optional = n.outputs()[i].type();
  7316. if (inputs_non_optional && output_optional instanceof torch.OptionalType) {
  7317. const unif = torch._c.unifyTypes(n.thenOutputs().at(i).type(), n.elseOutputs().at(i).type())
  7318. if (unif) {
  7319. n.outputs()[i].setType(unif);
  7320. changed = true;
  7321. }
  7322. }
  7323. }
  7324. */
  7325. } else if (node.kind() === 'aten::__is__' || node.kind() === 'aten::__isnot__') {
  7326. torch._C.AT_ASSERT(node.inputs().length === 2);
  7327. for (const check_none_index of [0, 1]) {
  7328. const input_must_be_none = node.inputs()[check_none_index].mustBeNone();
  7329. const other_must_not_be_none = node.inputs().at(1 - check_none_index).mustNotBeNone();
  7330. if (input_must_be_none && other_must_not_be_none) {
  7331. const guard = new torch._C.WithInsertPoint(node);
  7332. const output = node.owningGraph().insertConstant(node.kind() === 'aten::__isnot__');
  7333. node.output().replaceAllUsesWith(output);
  7334. changed = true;
  7335. guard.dispose();
  7336. }
  7337. }
  7338. } else if (node.kind() === 'prim::unchecked_unwrap_optional' || node.kind() === 'aten::_unwrap_optional') {
  7339. throw new python.Error('Not implemented.');
  7340. /*
  7341. // we are unwrapping an input that can't be None, remove the unwrap
  7342. const input = node.input();
  7343. if (input.mustNotBeNone()) {
  7344. node.output().replaceAllUsesWith(node.input());
  7345. changed = true;
  7346. }
  7347. */
  7348. } else if (node.kind() === 'prim::unchecked_cast') {
  7349. const input_type = torch._C.unshapedType(node.input().type());
  7350. const output_type = torch._C.unshapedType(node.output().type());
  7351. if (input_type.isSubtypeOf(output_type)) {
  7352. node.output().replaceAllUsesWith(node.input());
  7353. changed = true;
  7354. }
  7355. } else if ((node.kind() === 'aten::Int' || node.kind() === 'aten::ceil') && node.inputs().length === 1 && node.input().type() instanceof torch.IntType) {
  7356. node.output().replaceAllUsesWith(node.input());
  7357. changed = true;
  7358. } else if (node.kind() === 'aten::ne' || node.kind() === 'aten::eq') {
  7359. if (node.inputs().length !== 2 || node.inputs()[0] !== node.inputs()[1]) {
  7360. continue;
  7361. }
  7362. const inp_type = node.inputs()[0].type();
  7363. const immut_type = (type) => {
  7364. const kind = type.kind();
  7365. const handled_immutable_types = new Set('BoolType', 'IntType', 'FloatType', 'NoneType');
  7366. return handled_immutable_types.has(kind);
  7367. };
  7368. let non_throwing_type = false;
  7369. if (inp_type instanceof torch.ListType) {
  7370. non_throwing_type = immut_type(inp_type.getElementType());
  7371. } else if (inp_type instanceof torch.DictType) {
  7372. non_throwing_type = immut_type(inp_type.getKeyType()) && immut_type(inp_type.getValueType());
  7373. } else {
  7374. non_throwing_type = immut_type(inp_type);
  7375. }
  7376. if (non_throwing_type) {
  7377. const guard = new torch._C.WithInsertPoint(node);
  7378. node.output().replaceAllUsesWith(this._graph.insertConstant(node.kind() === 'aten::eq'));
  7379. changed = true;
  7380. guard.dispose();
  7381. }
  7382. } else if (node.kind() === 'aten::mul' || node.kind() === 'aten::floordiv' || node.kind() === 'aten::div') {
  7383. // changed = changed || torch._C.trySimplifyMulOrDiv(node);
  7384. } else if (node.kind() === 'aten::add' || node.kind() === 'aten::sub') {
  7385. // changed = changed || torch._C.trySimplifyAddOrSub(node);
  7386. }
  7387. }
  7388. return changed;
  7389. }
  7390. });
  7391. this.registerFunction('torch._C.PeepholeOptimize', (graph, addmm_fusion_enabled) => {
  7392. const peephole = new torch._C.PeepholeOptimizeImpl(graph, addmm_fusion_enabled);
  7393. const changed = peephole.run();
  7394. if (changed) {
  7395. torch._C.EliminateDeadCode(graph.block());
  7396. }
  7397. return changed;
  7398. });
  7399. this.registerFunction('torch._C.TORCH_INTERNAL_ASSERT', (cond) => {
  7400. if (!cond) {
  7401. throw new python.Error('Assertion failed.');
  7402. }
  7403. });
  7404. this.registerFunction('torch._C.TORCH_CHECK', (cond) => {
  7405. if (!cond) {
  7406. throw new python.Error('Assertion failed.');
  7407. }
  7408. });
  7409. this.registerFunction('torch._C.AT_ASSERT', (cond) => {
  7410. if (!cond) {
  7411. throw new python.Error('Assertion failed.');
  7412. }
  7413. });
  7414. this.registerFunction('torch._C.eraseListLiterals', (graph) => {
  7415. const it = new torch._C.DepthFirstGraphNodeIterator(graph);
  7416. for (let next_node = it.next(); next_node !== null;) {
  7417. const node = next_node;
  7418. next_node = it.next();
  7419. if (node.kind() === 'prim::EmptyListLiteral') {
  7420. if (node.hasUses()) {
  7421. torch._C.TORCH_INTERNAL_ASSERT(node.output().type().isSubtypeOf(torch.ListType.ofTensors()));
  7422. }
  7423. const li = graph.createList(torch.TensorType.get(), []);
  7424. li.insertBefore(node);
  7425. node.replaceAllUsesWith(li);
  7426. }
  7427. node.destroy();
  7428. }
  7429. });
  7430. this.registerFunction('torch._C.ConstantPooling', (...args) => {
  7431. if (args.length === 1 && args[0] instanceof torch.Graph) {
  7432. const [graph] = args;
  7433. const aliasDb = new torch._C.AliasDb(graph);
  7434. const constants = new torch._C.NodeSet();
  7435. torch._C.ConstantPooling(graph.block(), constants, aliasDb);
  7436. } else if (args.length === 3 && args[0] instanceof torch.Block) {
  7437. const [block, constants, aliasDb] = args;
  7438. for (const node of block.nodes()) {
  7439. if (node.blocks().length > 0) {
  7440. for (const block of node.blocks()) {
  7441. torch._C.ConstantPooling(block, constants, aliasDb);
  7442. }
  7443. continue;
  7444. }
  7445. if (node.kind() !== 'prim::Constant') {
  7446. continue;
  7447. }
  7448. if (constants.has(node)) {
  7449. const existing = constants.get(node);
  7450. const old_ivalue = torch._C.toIValue(existing.output());
  7451. const new_ivalue = torch._C.toIValue(node.output());
  7452. const same_identity = (old_ivalue && new_ivalue && (old_ivalue.is(new_ivalue)));
  7453. if (!same_identity && !aliasDb.safeToChangeAliasingRelationship(node.outputs(), existing.outputs())) {
  7454. continue;
  7455. }
  7456. node.replaceAllUsesWith(existing);
  7457. node.destroy();
  7458. continue;
  7459. } else {
  7460. constants.insert(node);
  7461. }
  7462. const [first_node] = node.owningGraph().block().nodes();
  7463. if (node !== first_node) {
  7464. node.moveBefore(first_node);
  7465. }
  7466. }
  7467. } else {
  7468. throw new python.Error('Not implemented.');
  7469. }
  7470. });
  7471. this.registerFunction('torch._C.handleBlock', (/* block, initial_state */) =>{
  7472. /*
  7473. const autocast_stack = [];
  7474. let incompatible_amp = null;
  7475. const current_state = () => autocast_stack.length === 0 ? initial_state : autocast_stack.top().context;
  7476. for (const node of block.nodes()) {
  7477. switch (node.kind()) {
  7478. case 'prim::CallFunction':
  7479. if (current_state() === initial_state) {
  7480. if (current_state()) {
  7481. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7482. }
  7483. break;
  7484. }
  7485. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || incompatible_amp.value(), "Calls are not expected with AMP & JIT");
  7486. incompatible_amp = true;
  7487. break;
  7488. case 'prim::CallMethod':
  7489. if (current_state() === initial_state) {
  7490. if (current_state()) {
  7491. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7492. }
  7493. break;
  7494. }
  7495. if (node.input(0).type() instanceof torch.ClassType) {
  7496. const class_type = node.input(0).type();
  7497. const name = node.s('name');
  7498. const fn = class_type.getMethod(name);
  7499. if (!fn.isGraphFunction()) {
  7500. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || incompatible_amp.value());
  7501. incompatible_amp = true;
  7502. }
  7503. } else {
  7504. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || incompatible_amp.value());
  7505. incompatible_amp = true;
  7506. }
  7507. break;
  7508. case 'prim::Enter': {
  7509. const autocast_scope = torch._C.parseAutocast(node.input(), current_state());
  7510. if (autocast_scope) {
  7511. if (node.hasUses()) {
  7512. torch._C.TORCH_CHECK(false, "`with autocast() as ...` is not supported");
  7513. }
  7514. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || !incompatible_amp.value());
  7515. incompatible_amp = false;
  7516. autocast_stack.push(autocast_scope);
  7517. }
  7518. break;
  7519. }
  7520. case 'prim::Exit': {
  7521. if (torch._C.isAutocastNode(node.input(0))) {
  7522. torch._C.TORCH_INTERNAL_ASSERT(!autocast_stack.empty());
  7523. torch._C.TORCH_INTERNAL_ASSERT(autocast_stack.top().instance === node.input());
  7524. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || !incompatible_amp.value());
  7525. incompatible_amp = false;
  7526. autocast_stack.pop();
  7527. }
  7528. break;
  7529. }
  7530. case 'aten::is_autocast_enabled': {
  7531. torch._C.updateAutocastEnabledCheck(node, current_state().gpu_enabled);
  7532. break;
  7533. }
  7534. case 'aten::is_autocast_cpu_enabled': {
  7535. torch._C.updateAutocastEnabledCheck(node, current_state().cpu_enabled);
  7536. break;
  7537. }
  7538. case 'aten::_convolution':
  7539. case 'aten::conv1d':
  7540. case 'aten::conv2d':
  7541. case 'aten::conv3d':
  7542. case 'aten::conv_tbc':
  7543. case 'aten::conv_transpose1d':
  7544. case 'aten::convolution':
  7545. case 'aten::cudnn_convolution':
  7546. case 'aten::cudnn_convolution_transpose':
  7547. case 'aten::prelu':
  7548. case 'aten::addmm':
  7549. case 'aten::addmv':
  7550. case 'aten::addr':
  7551. case 'aten::matmul':
  7552. case 'aten::mm':
  7553. case 'aten::mv':
  7554. case 'aten::linear':
  7555. case 'aten::addbmm':
  7556. case 'aten::baddbmm':
  7557. case 'aten::bmm':
  7558. case 'aten::chain_matmul':
  7559. case 'aten::_thnn_fused_lstm_cell':
  7560. case 'aten::_thnn_fused_gru_cell':
  7561. case 'aten::lstm_cell':
  7562. case 'aten::gru_cell':
  7563. case 'aten::rnn_tanh_cell':
  7564. case 'aten::rnn_relu_cell': {
  7565. if (!node.schema().is_mutable()) {
  7566. torch._C.castTensorInputs(node, 'aten::_autocast_to_reduced_precision', current_state());
  7567. }
  7568. break;
  7569. }
  7570. case 'aten::native_layer_norm':
  7571. case 'aten::acos':
  7572. case 'aten::asin':
  7573. case 'aten::cosh':
  7574. case 'aten::erfinv':
  7575. case 'aten::exp':
  7576. case 'aten::expm1':
  7577. case 'aten::log':
  7578. case 'aten::log10':
  7579. case 'aten::log2':
  7580. case 'aten::log1p':
  7581. case 'aten::reciprocal':
  7582. case 'aten::rsqrt':
  7583. case 'aten::sinh':
  7584. case 'aten::tan':
  7585. case 'aten::pow':
  7586. case 'aten::softplus':
  7587. case 'aten::gelu':
  7588. case 'aten::layer_norm':
  7589. case 'aten::group_norm':
  7590. case 'aten::frobenius_norm':
  7591. case 'aten::nuclear_norm':
  7592. case 'aten::cosine_similarity':
  7593. case 'aten::cosine_embedding_loss':
  7594. case 'aten::nll_loss':
  7595. case 'aten::nll_loss2d':
  7596. case 'aten::hinge_embedding_loss':
  7597. case 'aten::kl_div':
  7598. case 'aten::l1_loss':
  7599. case 'aten::smooth_l1_loss':
  7600. case 'aten::mse_loss':
  7601. case 'aten::margin_ranking_loss':
  7602. case 'aten::multilabel_margin_loss':
  7603. case 'aten::soft_margin_loss':
  7604. case 'aten::triplet_margin_loss':
  7605. case 'aten::multi_margin_loss':
  7606. case 'aten::binary_cross_entropy_with_logits':
  7607. case 'aten::dist':
  7608. case 'aten::pdist':
  7609. case 'aten::cdist':
  7610. case 'aten::renorm':
  7611. case 'aten::logsumexp': {
  7612. if (!node.schema().is_mutable()) {
  7613. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7614. }
  7615. break;
  7616. }
  7617. case 'aten::prod':
  7618. case 'aten::log_softmax':
  7619. case 'aten::cumprod':
  7620. case 'aten::cumsum':
  7621. case 'aten::sum': {
  7622. if (!node.schema().is_mutable() && !torch._C.hasExplicitDtypeArgument(node)) {
  7623. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7624. }
  7625. break;
  7626. }
  7627. case 'aten::softmax': {
  7628. if (!node.schema().is_mutable() && !torch._C.hasExplicitDtypeArgument(node)) {
  7629. const context = current_state();
  7630. context.cpu_enabled = false;
  7631. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', context);
  7632. }
  7633. break;
  7634. }
  7635. case 'aten::addcdiv':
  7636. case 'aten::addcmul':
  7637. case 'aten::atan2':
  7638. case 'aten::bilinear':
  7639. case 'aten::cat':
  7640. case 'aten::cross':
  7641. case 'aten::dot':
  7642. case 'aten::equal':
  7643. case 'aten::index_put':
  7644. case 'aten::stack':
  7645. case 'aten::tensordot':
  7646. case 'aten::add':
  7647. case 'aten::sub':
  7648. case 'aten::mul':
  7649. case 'aten::div': {
  7650. if (!node.schema().is_mutable()) {
  7651. torch._C.castInputsToWidestType(node, current_state());
  7652. }
  7653. break;
  7654. }
  7655. case 'aten::binary_cross_entropy': {
  7656. if (current_state()) {
  7657. torch._C.TORCH_CHECK(false, "Unsafe to autocast");
  7658. }
  7659. break;
  7660. }
  7661. default: {
  7662. break;
  7663. }
  7664. }
  7665. for (const sub_block of node.blocks()) {
  7666. torch._C.handleBlock(sub_block, current_state());
  7667. }
  7668. }
  7669. torch._C.TORCH_INTERNAL_ASSERT(autocast_stack.length === 0);
  7670. */
  7671. });
  7672. this.registerFunction('torch._C.autocastEnabled', () => {
  7673. return true;
  7674. });
  7675. this.registerFunction('torch._C.Autocast', (graph) => {
  7676. if (torch._C.autocastEnabled()) {
  7677. const init = null;
  7678. /* AutocastContext init = {
  7679. at::autocast::is_autocast_enabled(at::kCUDA),
  7680. at::autocast::is_autocast_enabled(at::kCPU),
  7681. at::autocast::get_autocast_dtype(at::kCUDA),
  7682. at::autocast::get_autocast_dtype(at::kCPU)}; */
  7683. torch._C.handleBlock(graph.block(), init);
  7684. }
  7685. });
  7686. this.registerFunction('torch._C.preoptimizeGraph', (graph, disable_autocast) => {
  7687. disable_autocast = disable_autocast || false;
  7688. torch._C.Inline(graph);
  7689. torch._C.PeepholeOptimize(graph, true);
  7690. torch._C.ConstantPropagationImmutableTypes(graph);
  7691. if (!disable_autocast) {
  7692. torch._C.Autocast(graph);
  7693. }
  7694. torch._C.ConstantPooling(graph);
  7695. });
  7696. this.registerType('torch._C.GraphFunction', class extends torch._C.Function {
  7697. constructor(name, graph, function_creator, executor_execution_mode) {
  7698. super();
  7699. this._name = name;
  7700. this._graph = graph;
  7701. this._executor_execution_mode = executor_execution_mode || null;
  7702. this._function_creator = function_creator;
  7703. this._force_no_amp = false;
  7704. }
  7705. isGraphFunction() {
  7706. return true;
  7707. }
  7708. qualname() {
  7709. return this._name;
  7710. }
  7711. graph() {
  7712. return this._graph;
  7713. }
  7714. optimized_graph() {
  7715. const graph_ref = this._graph.copy();
  7716. torch._C.preoptimizeGraph(graph_ref, this._force_no_amp);
  7717. return graph_ref;
  7718. }
  7719. ensure_defined() {
  7720. if (this._function_creator) {
  7721. const creator = this._function_creator;
  7722. this._function_creator = () => {
  7723. throw new python.Error('Recursive method call.');
  7724. };
  7725. creator(this);
  7726. this._function_creator = null;
  7727. }
  7728. this.check_single_output();
  7729. }
  7730. check_single_output() {
  7731. if (this.graph().outputs().length !== 1) {
  7732. throw new python.Error('Graph must have a single output.');
  7733. }
  7734. }
  7735. getSchema() {
  7736. this._schema = this._schema || this.defaultSchemaFor(this);
  7737. return this._schema;
  7738. }
  7739. setSchema(schema) {
  7740. this._schema = schema;
  7741. }
  7742. num_inputs() {
  7743. return this.graph().inputs().length;
  7744. }
  7745. unshapedType(type) {
  7746. if (type.isSubtypeOf(torch.TensorType.get())) {
  7747. return torch.TensorType.get();
  7748. }
  7749. const contained = type.containedTypes();
  7750. if (contained.length === 0) {
  7751. return type;
  7752. }
  7753. return type.withContained(type.containedTypes((type) => this.unshapedType(type)));
  7754. }
  7755. defaultSchemaFor(fn) {
  7756. const args = [];
  7757. const returns = [];
  7758. const g = fn.graph();
  7759. const num_inputs = fn.num_inputs();
  7760. for (let i = 0; i < num_inputs; i++) {
  7761. const v = g.inputs()[i];
  7762. const name = v.hasDebugName() ? v.debugNameBase() : `argument_${i}`;
  7763. const argument = new torch.Argument(name, this.unshapedType(g.inputs()[i].type()));
  7764. args.push(argument);
  7765. }
  7766. const num_outputs = g.outputs().length;
  7767. for (let i = 0; i < num_outputs; i++) {
  7768. const argument = new torch.Argument('', this.unshapedType(g.outputs()[i].type()));
  7769. returns.push(argument);
  7770. }
  7771. return new torch.FunctionSchema(fn.name(), '', args, returns);
  7772. }
  7773. });
  7774. this.registerType('torch.utils._contextlib._DecoratorContextManager', class {});
  7775. this.registerType('torch.utils._contextlib._NoParamDecoratorContextManager', class extends torch.utils._contextlib._DecoratorContextManager {});
  7776. this.registerType('torch.utils._sympy.symbol.SymT', class extends this.enum.Enum {});
  7777. this.registerType('torch.utils._sympy.functions.FloorDiv', class extends sympy.core.function.Function {
  7778. __str__() {
  7779. return this._args.map((a) => a.__str__()).join('//');
  7780. }
  7781. });
  7782. this.registerType('torch.utils._sympy.functions.ModularIndexing', class {});
  7783. this.registerType('torch.utils._sympy.functions.Where', class {});
  7784. this.registerType('torch.utils._sympy.functions.PythonMod', class {});
  7785. this.registerType('torch.utils._sympy.functions.Mod', class {});
  7786. this.registerType('torch.utils._sympy.functions.CleanDiv', class {});
  7787. this.registerType('torch.utils._sympy.functions.CeilToInt', class {});
  7788. this.registerType('torch.utils._sympy.functions.FloorToInt', class {});
  7789. this.registerType('torch.utils._sympy.functions.CeilDiv', class {});
  7790. this.registerType('torch.utils._sympy.functions.LShift', class {});
  7791. this.registerType('torch.utils._sympy.functions.RShift', class {});
  7792. this.registerType('torch.utils._sympy.functions.PowByNatural', class {});
  7793. this.registerType('torch.utils._sympy.functions.FloatPow', class {});
  7794. this.registerType('torch.utils._sympy.functions.FloatTrueDiv', class {});
  7795. this.registerType('torch.utils._sympy.functions.IntTrueDiv', class {});
  7796. this.registerType('torch.utils._sympy.functions.IsNonOverlappingAndDenseIndicator', class {});
  7797. this.registerType('torch.utils._sympy.functions.TruncToFloat', class {});
  7798. this.registerType('torch.utils._sympy.functions.TruncToInt', class {});
  7799. this.registerType('torch.utils._sympy.functions.RoundToInt', class {});
  7800. this.registerType('torch.utils._sympy.functions.RoundDecimal', class {});
  7801. this.registerType('torch.utils._sympy.functions.ToFloat', class {});
  7802. this.registerType('torch.utils._sympy.functions.Identity', class {});
  7803. this.registerType('torch.utils._traceback.CapturedTraceback', class {
  7804. static extract() {
  7805. }
  7806. });
  7807. this.registerFunction('torch.utils.checkpoint.checkpoint');
  7808. this.registerType('torch.utils.data.dataloader._MultiProcessingDataLoaderIter', class {});
  7809. this.registerType('torch.utils.data.dataloader.DataLoader', class {});
  7810. this.registerFunction('torch.utils.data._utils.collate.default_collate');
  7811. torch.utils.data.dataloader.default_collate = torch.utils.data._utils.collate.default_collate;
  7812. this.registerType('torch.utils.data.dataset.Subset', class {});
  7813. this.registerType('torch.utils.data.dataset.Dataset', class {});
  7814. this.registerType('torch.utils.data.dataset.ConcatDataset', class {});
  7815. this.registerType('torch.utils.data.dataset.TensorDataset', class {});
  7816. this.registerType('torch.utils.data.sampler.BatchSampler', class {});
  7817. this.registerType('torch.utils.data.sampler.RandomSampler', class {});
  7818. this.registerType('torch.utils.data.sampler.SequentialSampler', class {});
  7819. this.registerType('torch.utils.data.sampler.SubsetRandomSampler', class {});
  7820. this.registerType('torch.ao.quantization.fake_quantize.FakeQuantize', class {});
  7821. this.registerType('torch.ao.quantization.fake_quantize.FusedMovingAvgObsFakeQuantize', class {});
  7822. this.registerType('torch.ao.quantization.observer._PartialWrapper', class {});
  7823. this.registerType('torch.ao.quantization.observer.HistogramObserver', class {});
  7824. this.registerType('torch.ao.quantization.observer.MovingAverageMinMaxObserver', class {});
  7825. this.registerType('torch.ao.quantization.observer.MovingAveragePerChannelMinMaxObserver', class {});
  7826. this.registerType('torch.ao.quantization.observer.MinMaxObserver', class {});
  7827. this.registerType('torch.ao.quantization.observer.PerChannelMinMaxObserver', class {});
  7828. this.registerType('torch.ao.quantization.observer.PlaceholderObserver', class {});
  7829. this.registerType('torch.ao.quantization.qconfig.QConfig', class {});
  7830. this.registerType('torch.ao.quantization.qconfig.QConfigDynamic', class {});
  7831. this.registerType('torch.ao.quantization.stubs.DeQuantStub', class {});
  7832. this.registerType('torch.ao.quantization.stubs.QuantStub', class {});
  7833. this.registerType('torch.ao.quantization.stubs.QuantWrapper', class {});
  7834. this.registerFunction('torch.ao.quantization.qconfig._activation_is_memoryless');
  7835. this.registerFunction('torch.ao.quantization.qconfig._add_module_to_qconfig_obs_ctr');
  7836. this.registerFunction('torch.ao.quantization.fx.graph_module._save_packed_weight');
  7837. this.registerFunction('torch.ao.quantization.fx._lower_to_native_backend._load_packed_weight');
  7838. this.registerFunction('torch.ao.quantization.fx._lower_to_native_backend._save_packed_weight');
  7839. this.registerFunction('torch.ao.quantization.observer._is_activation_post_process');
  7840. this.registerFunction('torch.ao.quantization.quantize._observer_forward_hook');
  7841. this.registerFunction('torch.ao.quantization.quantization_mappings._get_special_act_post_process');
  7842. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_dynamic_quant_module_mappings');
  7843. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_qat_module_mappings');
  7844. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_qconfig_propagation_list');
  7845. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_static_quant_module_mappings');
  7846. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_static_quant_reference_module_mappings');
  7847. this.registerFunction('torch.ao.quantization.quantization_mappings.no_observer_set');
  7848. this.registerFunction('torch.ao.quantization.quantization_mappings._has_special_act_post_process');
  7849. this.registerFunction('torch.ao.quantization.utils.get_qparam_dict');
  7850. this.registerFunction('torch.ao.quantization.utils.has_no_children_ignoring_parametrizations');
  7851. this.registerFunction('torch.amp.grad_scaler._refresh_per_optimizer_state');
  7852. this.registerType('torch.amp.grad_scaler.GradScaler', class {});
  7853. this.registerType('torch._C._LegacyVariableBase', class {});
  7854. this.registerType('torch.autograd.grad_mode.no_grad', class extends torch.utils._contextlib._NoParamDecoratorContextManager {});
  7855. this.registerType('torch.autograd.variable.Variable', class extends torch._C._LegacyVariableBase {});
  7856. this.registerType('torch.autograd.function._SingleLevelFunction', class {});
  7857. this.registerType('torch.autograd.function.Function', class extends torch.autograd.function._SingleLevelFunction {});
  7858. this.registerType('torch.backends.cudnn.rnn.Unserializable', class {});
  7859. this.registerFunction('torch.distributed._shard.sharded_tensor.pre_load_state_dict_hook');
  7860. this.registerFunction('torch.distributed._shard.sharded_tensor.state_dict_hook');
  7861. this.registerFunction('torch.distributed._sharded_tensor.state_dict_hook');
  7862. this.registerFunction('torch.distributed._sharded_tensor.pre_load_state_dict_hook');
  7863. this.registerType('torch.distributed.algorithms.join._JoinConfig', class {});
  7864. this.registerType('torch.distributed.remote_device._remote_device', class {});
  7865. this.registerType('torch.distributed._shard.metadata.ShardMetadata', class {});
  7866. this.registerType('torch.distributed._shard.sharded_tensor.api.ShardedTensor', class {});
  7867. this.registerType('torch.distributed._shard.sharded_tensor.metadata.ShardedTensorMetadata', class {});
  7868. this.registerType('torch.distributed._shard.sharded_tensor.metadata.TensorProperties', class {});
  7869. this.registerType('torch.distributed._shard.sharded_tensor.shard.Shard', class {});
  7870. this.registerType('torch.distributed._tensor.api.DTensor', class extends torch._C._TensorMeta {});
  7871. this.registerType('torch.distributed._tensor.placement_types.DTensorSpec', class {});
  7872. this.registerType('torch.distributed._tensor.placement_types.Shard', class {});
  7873. this.registerType('torch.distributed._tensor.placement_types.TensorMeta', class {});
  7874. this.registerType('torch.distributed.device_mesh.DeviceMesh', class {});
  7875. this.registerType('torch.distributions.bernoulli.Bernoulli', class {});
  7876. this.registerType('torch.distributions.beta.Beta', class {});
  7877. this.registerType('torch.distributions.binomial.Binomial', class {});
  7878. this.registerType('torch.distributions.categorical.Categorical', class {});
  7879. this.registerType('torch.distributions.constraints._GreaterThan', class {});
  7880. this.registerType('torch.distributions.constraints._Interval', class {});
  7881. this.registerType('torch.distributions.constraints._LowerCholesky', class {});
  7882. this.registerType('torch.distributions.constraints._Real', class {});
  7883. this.registerType('torch.distributions.dirichlet.Dirichlet', class {});
  7884. this.registerType('torch.distributions.mixture_same_family.MixtureSameFamily', class {});
  7885. this.registerType('torch.distributions.multivariate_normal.MultivariateNormal', class {});
  7886. this.registerType('torch.distributions.normal.Normal', class {});
  7887. this.registerType('torch.distributions.transforms._InverseTransform', class {});
  7888. this.registerType('torch.distributions.transforms.AffineTransform', class {});
  7889. this.registerType('torch.distributions.transforms.ComposeTransform', class {});
  7890. this.registerType('torch.distributions.transforms.ExpTransform', class {});
  7891. this.registerType('torch.distributions.transforms.LowerCholeskyTransform', class {});
  7892. this.registerType('torch.distributions.uniform.Uniform', class {});
  7893. this.registerType('torch.nn.backends.thnn._get_thnn_function_backend', class {});
  7894. this.registerType('torch.nn.intrinsic.modules.fused._FusedModule', class {});
  7895. this.registerType('torch.nn.intrinsic.modules.fused.ConvBnReLU2d', class {});
  7896. this.registerType('torch.nn.intrinsic.modules.fused.ConvReLU2d', class {});
  7897. this.registerType('torch.nn.intrinsic.modules.fused.BNReLU2d', class {});
  7898. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvBn2d', class {});
  7899. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU2d', class {});
  7900. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvReLU2d', class {});
  7901. this.registerType('torch.nn.intrinsic.quantized.modules.bn_relu.BNReLU2d', class {});
  7902. this.registerType('torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU1d', class {});
  7903. this.registerType('torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', class {});
  7904. this.registerType('torch.nn.intrinsic.quantized.modules.linear_relu.LinearReLU', class {});
  7905. this.registerType('torch.nn.modules.activation.CELU', class extends torch.nn.modules.module.Module {});
  7906. this.registerType('torch.nn.modules.activation.ELU', class extends torch.nn.modules.module.Module {});
  7907. this.registerType('torch.nn.modules.activation.GELU', class extends torch.nn.modules.module.Module {});
  7908. this.registerType('torch.nn.modules.activation.GLU', class extends torch.nn.modules.module.Module {});
  7909. this.registerType('torch.nn.modules.activation.Hardtanh', class extends torch.nn.modules.module.Module {});
  7910. this.registerType('torch.nn.modules.activation.Hardshrink', class extends torch.nn.modules.module.Module {});
  7911. this.registerType('torch.nn.modules.activation.Hardsigmoid', class extends torch.nn.modules.module.Module {});
  7912. this.registerType('torch.nn.modules.activation.Hardswish', class extends torch.nn.modules.module.Module {});
  7913. this.registerType('torch.nn.modules.activation.LeakyReLU', class extends torch.nn.modules.module.Module {});
  7914. this.registerType('torch.nn.modules.activation.LogSigmoid', class extends torch.nn.modules.module.Module {});
  7915. this.registerType('torch.nn.modules.activation.LogSoftmax', class extends torch.nn.modules.module.Module {});
  7916. this.registerType('torch.nn.modules.activation.Mish', class extends torch.nn.modules.module.Module {});
  7917. this.registerType('torch.nn.modules.activation.MultiheadAttention', class extends torch.nn.modules.module.Module {});
  7918. this.registerType('torch.nn.modules.activation.ReLU', class extends torch.nn.modules.module.Module {});
  7919. this.registerType('torch.nn.modules.activation.ReLU6', class extends torch.nn.modules.module.Module {});
  7920. this.registerType('torch.nn.modules.activation.PReLU', class extends torch.nn.modules.module.Module {});
  7921. this.registerType('torch.nn.modules.activation.RReLU', class extends torch.nn.modules.module.Module {});
  7922. this.registerType('torch.nn.modules.activation.SELU', class extends torch.nn.modules.module.Module {});
  7923. this.registerType('torch.nn.modules.activation.Sigmoid', class extends torch.nn.modules.module.Module {});
  7924. this.registerType('torch.nn.modules.activation.SiLU', class extends torch.nn.modules.module.Module {});
  7925. this.registerType('torch.nn.modules.activation.Softmax', class extends torch.nn.modules.module.Module {});
  7926. this.registerType('torch.nn.modules.activation.Softmax2d', class extends torch.nn.modules.module.Module {});
  7927. this.registerType('torch.nn.modules.activation.Softmin', class extends torch.nn.modules.module.Module {});
  7928. this.registerType('torch.nn.modules.activation.Softplus', class extends torch.nn.modules.module.Module {});
  7929. this.registerType('torch.nn.modules.activation.Softshrink', class extends torch.nn.modules.module.Module {});
  7930. this.registerType('torch.nn.modules.activation.Softsign', class extends torch.nn.modules.module.Module {});
  7931. this.registerType('torch.nn.modules.activation.Tanh', class extends torch.nn.modules.module.Module {});
  7932. this.registerType('torch.nn.modules.activation.Tanhshrink', class extends torch.nn.modules.module.Module {});
  7933. this.registerType('torch.nn.modules.activation.Threshold', class extends torch.nn.modules.module.Module {});
  7934. this.registerType('torch.nn.modules.adaptive.AdaptiveLogSoftmaxWithLoss', class {});
  7935. this.registerType('torch.nn.modules.batchnorm._NormBase', class extends torch.nn.modules.module.Module {});
  7936. this.registerType('torch.nn.modules.batchnorm._BatchNorm', class extends torch.nn.modules.batchnorm._NormBase {});
  7937. this.registerType('torch.nn.modules.batchnorm.BatchNorm1d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  7938. this.registerType('torch.nn.modules.batchnorm.BatchNorm2d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  7939. this.registerType('torch.nn.modules.batchnorm.BatchNorm3d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  7940. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm1d', class {});
  7941. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm2d', class {});
  7942. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm3d', class {});
  7943. this.registerType('torch.nn.modules.batchnorm.SyncBatchNorm', class {});
  7944. this.registerType('torch.nn.modules.byted_batchnorm.BytedBatchNorm2d', class {});
  7945. this.registerType('torch.nn.modules.channelshuffle.ChannelShuffle', class {});
  7946. this.registerType('torch.nn.modules.container.ModuleDict', class extends torch.nn.modules.module.Module {});
  7947. this.registerType('torch.nn.modules.container.ModuleList', class extends torch.nn.modules.module.Module {});
  7948. this.registerType('torch.nn.modules.container.ParameterDict', class extends torch.nn.modules.module.Module {});
  7949. this.registerType('torch.nn.modules.container.ParameterList', class extends torch.nn.modules.module.Module {});
  7950. this.registerType('torch.nn.modules.container.Sequential', class extends torch.nn.modules.module.Module {});
  7951. this.registerType('torch.nn.modules.conv._ConvNd', class extends torch.nn.modules.module.Module {});
  7952. this.registerType('torch.nn.modules.conv.Conv1d', class extends torch.nn.modules.conv._ConvNd {});
  7953. this.registerType('torch.nn.modules.conv.Conv2d', class extends torch.nn.modules.conv._ConvNd {});
  7954. this.registerType('torch.nn.modules.conv.Conv3d', class extends torch.nn.modules.conv._ConvNd {});
  7955. this.registerType('torch.nn.modules.conv._ConvTransposeNd', class extends torch.nn.modules.module.Module {});
  7956. this.registerType('torch.nn.modules.conv.ConvTranspose1d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  7957. this.registerType('torch.nn.modules.conv.ConvTranspose2d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  7958. this.registerType('torch.nn.modules.conv.ConvTranspose3d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  7959. this.registerType('torch.nn.modules.conv.LazyConv1d', class {});
  7960. this.registerType('torch.nn.modules.conv.LazyConv2d', class {});
  7961. this.registerType('torch.nn.modules.conv.LazyConv3d', class {});
  7962. this.registerType('torch.nn.modules.conv.LazyConvTranspose2d', class {});
  7963. this.registerType('torch.nn.modules.conv.LazyConvTranspose3d', class {});
  7964. this.registerType('torch.nn.modules.distance.CosineSimilarity', class extends torch.nn.modules.module.Module {});
  7965. this.registerType('torch.nn.modules.distance.PairwiseDistance', class extends torch.nn.modules.module.Module {});
  7966. this.registerType('torch.nn.modules.dropout._DropoutNd', class extends torch.nn.modules.module.Module {});
  7967. this.registerType('torch.nn.modules.dropout.AlphaDropout', class extends torch.nn.modules.dropout._DropoutNd {});
  7968. this.registerType('torch.nn.modules.dropout.Dropout', class extends torch.nn.modules.dropout._DropoutNd {});
  7969. this.registerType('torch.nn.modules.dropout.Dropout1d', class extends torch.nn.modules.dropout._DropoutNd {});
  7970. this.registerType('torch.nn.modules.dropout.Dropout2d', class extends torch.nn.modules.dropout._DropoutNd {});
  7971. this.registerType('torch.nn.modules.dropout.Dropout3d', class extends torch.nn.modules.dropout._DropoutNd {});
  7972. this.registerType('torch.nn.modules.dropout.FeatureAlphaDropout', class extends torch.nn.modules.dropout._DropoutNd {});
  7973. this.registerType('torch.nn.modules.fold.Fold', class extends torch.nn.modules.module.Module {});
  7974. this.registerType('torch.nn.modules.fold.Unfold', class extends torch.nn.modules.module.Module {});
  7975. this.registerType('torch.nn.modules.flatten.Flatten', class extends torch.nn.modules.module.Module {});
  7976. this.registerType('torch.nn.modules.flatten.Unflatten', class extends torch.nn.modules.module.Module {});
  7977. this.registerType('torch.nn.modules.instancenorm.InstanceNorm1d', class {});
  7978. this.registerType('torch.nn.modules.instancenorm.InstanceNorm2d', class {});
  7979. this.registerType('torch.nn.modules.instancenorm.InstanceNorm3d', class {});
  7980. this.registerType('torch.nn.modules.instancenorm.LazyInstanceNorm2d', class {});
  7981. this.registerType('torch.nn.modules.instancenorm.LazyInstanceNorm3d', class {});
  7982. this.registerType('torch.nn.modules.linear._LinearWithBias', class {});
  7983. this.registerType('torch.nn.modules.linear.Bilinear', class extends torch.nn.modules.module.Module {});
  7984. this.registerType('torch.nn.modules.linear.Identity', class extends torch.nn.modules.module.Module {});
  7985. this.registerType('torch.nn.modules.linear.LazyLinear', class extends torch.nn.modules.module.Module {});
  7986. this.registerType('torch.nn.modules.linear.Linear', class extends torch.nn.modules.module.Module {});
  7987. this.registerType('torch.nn.modules.linear.NonDynamicallyQuantizableLinear', class extends torch.nn.modules.linear.Linear {});
  7988. this.registerType('torch.nn.modules.loss._Loss', class extends torch.nn.modules.module.Module {});
  7989. this.registerType('torch.nn.modules.loss._WeightedLoss', class extends torch.nn.modules.loss._Loss {});
  7990. this.registerType('torch.nn.modules.loss.BCELoss', class extends torch.nn.modules.loss._WeightedLoss {});
  7991. this.registerType('torch.nn.modules.loss.BCEWithLogitsLoss', class extends torch.nn.modules.loss._Loss {});
  7992. this.registerType('torch.nn.modules.loss.CrossEntropyLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  7993. this.registerType('torch.nn.modules.loss.CosineEmbeddingLoss', class extends torch.nn.modules.loss._Loss {});
  7994. this.registerType('torch.nn.modules.loss.CTCLoss', class extends torch.nn.modules.loss._Loss {});
  7995. this.registerType('torch.nn.modules.loss.GaussianNLLLoss', class extends torch.nn.modules.loss._Loss {});
  7996. this.registerType('torch.nn.modules.loss.HuberLoss', class extends torch.nn.modules.loss._Loss {});
  7997. this.registerType('torch.nn.modules.loss.HingeEmbeddingLoss', class extends torch.nn.modules.loss._Loss {});
  7998. this.registerType('torch.nn.modules.loss.KLDivLoss', class extends torch.nn.modules.loss._Loss {});
  7999. this.registerType('torch.nn.modules.loss.L1Loss', class extends torch.nn.modules.loss._Loss {});
  8000. this.registerType('torch.nn.modules.loss.MarginRankingLoss', class extends torch.nn.modules.loss._Loss {});
  8001. this.registerType('torch.nn.modules.loss.MultiLabelMarginLoss', class extends torch.nn.modules.loss._Loss {});
  8002. this.registerType('torch.nn.modules.loss.MultiLabelSoftMarginLoss', class extends torch.nn.modules.loss._Loss {});
  8003. this.registerType('torch.nn.modules.loss.MultiMarginLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  8004. this.registerType('torch.nn.modules.loss.MSELoss', class extends torch.nn.modules.loss._Loss {});
  8005. this.registerType('torch.nn.modules.loss.NLLLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  8006. this.registerType('torch.nn.modules.loss.NLLLoss2d', class extends torch.nn.modules.loss.NLLLoss {});
  8007. this.registerType('torch.nn.modules.loss.PoissonNLLLoss', class {});
  8008. this.registerType('torch.nn.modules.loss.SmoothL1Loss', class {});
  8009. this.registerType('torch.nn.modules.loss.SoftMarginLoss', class {});
  8010. this.registerType('torch.nn.modules.loss.TripletMarginLoss', class {});
  8011. this.registerType('torch.nn.modules.loss.TripletMarginWithDistanceLoss', class {});
  8012. this.registerType('torch.nn.modules.module._IncompatibleKeys', class {});
  8013. this.registerType('torch.nn.modules.module._WrappedHook', class {});
  8014. this.registerType('torch.nn.modules.module.PatchForward', class {});
  8015. this.registerType('torch.nn.modules.normalization.CrossMapLRN2d', class {});
  8016. this.registerType('torch.nn.modules.normalization.GroupNorm', class extends torch.nn.modules.module.Module {});
  8017. this.registerType('torch.nn.modules.normalization.LayerNorm', class extends torch.nn.modules.module.Module {});
  8018. this.registerType('torch.nn.modules.normalization.LocalResponseNorm', class {});
  8019. this.registerType('torch.nn.modules.normalization.RMSNorm', class {});
  8020. this.registerType('torch.nn.modules.padding._ReflectionPadNd', class extends torch.nn.modules.module.Module {});
  8021. this.registerType('torch.nn.modules.padding.ReflectionPad1d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  8022. this.registerType('torch.nn.modules.padding.ReflectionPad2d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  8023. this.registerType('torch.nn.modules.padding.ReflectionPad3d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  8024. this.registerType('torch.nn.modules.padding._ReplicationPadNd', class extends torch.nn.modules.module.Module {});
  8025. this.registerType('torch.nn.modules.padding.ReplicationPad1d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  8026. this.registerType('torch.nn.modules.padding.ReplicationPad2d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  8027. this.registerType('torch.nn.modules.padding.ReplicationPad3d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  8028. this.registerType('torch.nn.modules.padding.ZeroPad1d', class {});
  8029. this.registerType('torch.nn.modules.padding.ZeroPad2d', class {});
  8030. this.registerType('torch.nn.modules.padding.ZeroPad3d', class {});
  8031. this.registerType('torch.nn.modules.padding.ConstantPad1d', class {});
  8032. this.registerType('torch.nn.modules.padding.ConstantPad2d', class {});
  8033. this.registerType('torch.nn.modules.padding.ConstantPad3d', class {});
  8034. this.registerType('torch.nn.modules.padding.CircularPad3d', class {});
  8035. this.registerType('torch.nn.modules.pixelshuffle.PixelShuffle', class {});
  8036. this.registerType('torch.nn.modules.pixelshuffle.PixelUnshuffle', class {});
  8037. this.registerType('torch.nn.modules.pooling._AdaptiveAvgPoolNd', class extends torch.nn.modules.module.Module {});
  8038. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool1d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  8039. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool2d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  8040. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool3d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  8041. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool1d', class {});
  8042. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool2d', class {});
  8043. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool3d', class {});
  8044. this.registerType('torch.nn.modules.pooling.AvgPool1d', class {});
  8045. this.registerType('torch.nn.modules.pooling.AvgPool2d', class {});
  8046. this.registerType('torch.nn.modules.pooling.AvgPool3d', class {});
  8047. this.registerType('torch.nn.modules.pooling.FractionalMaxPool2d', class {});
  8048. this.registerType('torch.nn.modules.pooling.FractionalMaxPool3d', class {});
  8049. this.registerType('torch.nn.modules.pooling.LPPool1d', class {});
  8050. this.registerType('torch.nn.modules.pooling.LPPool2d', class {});
  8051. this.registerType('torch.nn.modules.pooling.LPPool3d', class {});
  8052. this.registerType('torch.nn.modules.pooling._MaxPoolNd', class extends torch.nn.modules.module.Module {});
  8053. this.registerType('torch.nn.modules.pooling.MaxPool1d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  8054. this.registerType('torch.nn.modules.pooling.MaxPool2d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  8055. this.registerType('torch.nn.modules.pooling.MaxPool3d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  8056. this.registerType('torch.nn.modules.pooling._MaxUnpoolNd', class extends torch.nn.modules.module.Module {});
  8057. this.registerType('torch.nn.modules.pooling.MaxUnpool1d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  8058. this.registerType('torch.nn.modules.pooling.MaxUnpool2d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  8059. this.registerType('torch.nn.modules.pooling.MaxUnpool3d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  8060. this.registerType('torch.nn.modules.rnn.GRU', class {});
  8061. this.registerType('torch.nn.modules.rnn.GRUCell', class {});
  8062. this.registerType('torch.nn.modules.rnn.LSTM', class {});
  8063. this.registerType('torch.nn.modules.rnn.LSTMCell', class {});
  8064. this.registerType('torch.nn.modules.rnn.RNNBase', class extends torch.nn.modules.module.Module {});
  8065. this.registerType('torch.nn.modules.rnn.RNN', class extends torch.nn.modules.rnn.RNNBase {});
  8066. this.registerType('torch.nn.modules.rnn.RNNCellBase', class extends torch.nn.modules.module.Module {});
  8067. this.registerType('torch.nn.modules.rnn.RNNCell', class extends torch.nn.modules.rnn.RNNCellBase {});
  8068. this.registerType('torch.nn.modules.sparse.Embedding', class {});
  8069. this.registerType('torch.nn.modules.sparse.EmbeddingBag', class {});
  8070. this.registerType('torch.nn.modules.transformer.Transformer', class {});
  8071. this.registerType('torch.nn.modules.transformer.TransformerDecoder', class {});
  8072. this.registerType('torch.nn.modules.transformer.TransformerDecoderLayer', class {});
  8073. this.registerType('torch.nn.modules.transformer.TransformerEncoder', class {});
  8074. this.registerType('torch.nn.modules.transformer.TransformerEncoderLayer', class {});
  8075. this.registerType('torch.nn.modules.upsampling.Upsample', class {});
  8076. this.registerType('torch.nn.modules.upsampling.UpsamplingBilinear2d', class {});
  8077. this.registerType('torch.nn.modules.upsampling.UpsamplingNearest2d', class {});
  8078. this.registerType('torch.nn.parallel.data_parallel.DataParallel', class {});
  8079. this.registerType('torch.nn.parallel.distributed._DDPUnevenInputsConfig', class {});
  8080. this.registerType('torch.nn.parallel.distributed.DistributedDataParallel', class {});
  8081. this.registerType('torch.nn.qat.modules.conv.Conv2d', class {});
  8082. this.registerType('torch.nn.qat.modules.linear.Linear', class {});
  8083. this.registerType('torch.nn.quantized.modules.activation.ReLU', class {});
  8084. this.registerType('torch.nn.quantized.modules.activation.LeakyReLU', class {});
  8085. this.registerType('torch.nn.quantized.modules.activation.Softmax', class {});
  8086. this.registerType('torch.nn.quantized.dynamic.modules.linear.Linear', class {});
  8087. this.registerType('torch.nn.quantized.dynamic.modules.rnn.GRU', class {});
  8088. this.registerType('torch.nn.quantized.dynamic.modules.rnn.LSTM', class {});
  8089. this.registerType('torch.nn.quantized.dynamic.modules.rnn.LSTMCell', class {});
  8090. this.registerType('torch.nn.quantized.dynamic.modules.rnn.PackedParameter', class {});
  8091. this.registerType('torch.nn.quantized.modules.activation.ReLU6', class {});
  8092. this.registerType('torch.nn.quantized.modules.batchnorm.BatchNorm2d', class {});
  8093. this.registerType('torch.nn.quantized.modules.conv.Conv1d', class {});
  8094. this.registerType('torch.nn.quantized.modules.conv.Conv2d', class {});
  8095. this.registerType('torch.nn.quantized.modules.conv.ConvTranspose2d', class {});
  8096. this.registerType('torch.nn.quantized.modules.DeQuantize', class {});
  8097. this.registerType('torch.nn.quantized.modules.dropout.Dropout', class {});
  8098. this.registerType('torch.nn.quantized.modules.embedding_ops.Embedding', class {});
  8099. this.registerType('torch.nn.quantized.modules.embedding_ops.EmbeddingPackedParams', class {});
  8100. this.registerType('torch.nn.quantized.modules.functional_modules.FloatFunctional', class {});
  8101. this.registerType('torch.nn.quantized.modules.functional_modules.QFunctional', class {});
  8102. this.registerType('torch.nn.quantized.modules.linear.Linear', class {});
  8103. this.registerType('torch.nn.quantized.modules.linear.LinearPackedParams', class {});
  8104. this.registerType('torch.nn.quantized.modules.normalization.InstanceNorm2d', class {});
  8105. this.registerType('torch.nn.quantized.modules.normalization.GroupNorm', class extends torch.nn.modules.normalization.GroupNorm {});
  8106. this.registerType('torch.nn.quantized.modules.normalization.LayerNorm', class extends torch.nn.modules.normalization.LayerNorm {});
  8107. this.registerType('torch.nn.quantized.modules.Quantize', class {});
  8108. this.registerType('torch.ao.nn.quantizable.modules.activation.MultiheadAttention', class extends torch.nn.modules.activation.MultiheadAttention {});
  8109. this.registerType('torch.ao.nn.quantizable.modules.rnn._LSTMLayer', class {});
  8110. this.registerType('torch.ao.nn.quantizable.modules.rnn._LSTMSingleLayer', class {});
  8111. this.registerType('torch.ao.nn.quantizable.modules.rnn.LSTM', class {});
  8112. this.registerType('torch.ao.nn.quantizable.modules.rnn.LSTMCell', class {});
  8113. this.registerType('torch.ao.nn.quantized.modules.activation.ELU', class extends torch.nn.modules.activation.ELU {});
  8114. this.registerType('torch.ao.nn.quantized.modules.activation.Hardswish', class extends torch.nn.modules.activation.Hardswish {});
  8115. this.registerType('torch.ao.nn.quantized.modules.activation.MultiheadAttention', class extends torch.ao.nn.quantizable.modules.activation.MultiheadAttention {});
  8116. this.registerType('torch.ao.nn.quantized.modules.activation.PReLU', class extends torch.nn.modules.module.Module {});
  8117. this.registerType('torch.ao.nn.quantized.modules.activation.ReLU6', class extends torch.nn.modules.activation.ReLU {});
  8118. this.registerType('torch.ao.nn.quantized.modules.activation.LeakyReLU', class extends torch.nn.modules.activation.LeakyReLU {});
  8119. this.registerType('torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule', class extends torch.nn.modules.module.Module {});
  8120. this.registerType('torch.ao.nn.quantized.modules.batchnorm._BatchNorm', class extends torch.nn.modules.batchnorm._BatchNorm {});
  8121. this.registerType('torch.ao.nn.quantized.modules.batchnorm.BatchNorm2d', class extends torch.ao.nn.quantized.modules.batchnorm._BatchNorm {});
  8122. this.registerType('torch.ao.nn.quantized.modules.conv.Conv1d', class extends torch.nn.modules.module.Module {});
  8123. this.registerType('torch.ao.nn.quantized.modules.conv.Conv2d', class extends torch.nn.modules.module.Module {});
  8124. this.registerType('torch.ao.nn.quantized.modules.conv._ConvNd', class extends torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule {});
  8125. this.registerType('torch.ao.nn.quantized.modules.conv._ConvTransposeNd', class extends torch.ao.nn.quantized.modules.conv._ConvNd {});
  8126. this.registerType('torch.ao.nn.quantized.modules.conv.ConvTranspose1d', class extends torch.ao.nn.quantized.modules.conv._ConvTransposeNd {});
  8127. this.registerType('torch.ao.nn.quantized.modules.conv.ConvTranspose2d', class extends torch.ao.nn.quantized.modules.conv._ConvTransposeNd {});
  8128. this.registerType('torch.ao.nn.quantized.modules.Quantize', class extends torch.nn.modules.module.Module {});
  8129. this.registerType('torch.ao.nn.quantized.modules.DeQuantize', class extends torch.nn.modules.module.Module {});
  8130. this.registerType('torch.ao.nn.quantized.modules.dropout.Dropout', class extends torch.nn.modules.dropout.Dropout {});
  8131. this.registerType('torch.ao.nn.quantized.modules.embedding_ops.Embedding', class extends torch.nn.modules.module.Module {});
  8132. this.registerType('torch.ao.nn.quantized.modules.embedding_ops.EmbeddingPackedParams', class extends torch.nn.modules.module.Module {});
  8133. this.registerType('torch.ao.nn.quantized.modules.functional_modules.FloatFunctional', class extends torch.nn.modules.module.Module {});
  8134. this.registerType('torch.ao.nn.quantized.modules.functional_modules.QFunctional', class extends torch.nn.modules.module.Module {});
  8135. this.registerType('torch.ao.nn.quantized.modules.functional_modules.FXFloatFunctional', class extends torch.nn.modules.module.Module {});
  8136. this.registerType('torch.ao.nn.quantized.modules.linear.Linear', class extends torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule {});
  8137. this.registerType('torch.ao.nn.quantized.modules.linear.LinearPackedParams', class extends torch.nn.modules.module.Module {});
  8138. this.registerType('torch.ao.nn.quantized.modules.normalization.LayerNorm', class extends torch.nn.modules.normalization.LayerNorm {});
  8139. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm1d', class extends torch.nn.modules.instancenorm.InstanceNorm1d {});
  8140. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm2d', class extends torch.nn.modules.instancenorm.InstanceNorm2d {});
  8141. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm3d', class extends torch.nn.modules.instancenorm.InstanceNorm3d {});
  8142. this.registerType('torch.ao.nn.quantized.modules.rnn.LSTM', class {});
  8143. this.registerType('torch.ao.nn.quantized.dynamic.modules.linear.Linear', class extends torch.ao.nn.quantized.modules.linear.Linear {});
  8144. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.PackedParameter', class extends torch.nn.modules.module.Module {});
  8145. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase', class extends torch.nn.modules.module.Module {});
  8146. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.GRU', class extends torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase {});
  8147. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.LSTM', class extends torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase {});
  8148. this.registerType('torch.ao.nn.quantized.reference.modules.conv.Conv1d', class {});
  8149. this.registerType('torch.ao.nn.quantized.reference.modules.conv.Conv2d', class {});
  8150. this.registerType('torch.ao.nn.quantized.reference.modules.linear.Linear', class {});
  8151. this.registerType('torch.ao.nn.qat.modules.conv.Conv2d', class {});
  8152. this.registerType('torch.ao.nn.qat.modules.linear.Linear', class {});
  8153. this.registerType('torch.ao.nn.intrinsic.quantized.modules.conv_relu.ConvReLU1d', class extends torch.ao.nn.quantized.modules.conv.Conv1d {});
  8154. this.registerType('torch.ao.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', class extends torch.ao.nn.quantized.modules.conv.Conv2d {});
  8155. this.registerType('torch.ao.nn.intrinsic.quantized.modules.linear_relu.LinearReLU', class extends torch.ao.nn.quantized.modules.linear.Linear {});
  8156. this.registerType('torch.ao.nn.intrinsic.quantized.modules.bn_relu.BNReLU2d', class extends torch.ao.nn.quantized.modules.batchnorm.BatchNorm2d {});
  8157. this.registerType('torch.ao.nn.intrinsic.modules.fused._FusedModule', class extends torch.nn.modules.container.Sequential {});
  8158. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvBn2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8159. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvReLU1d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8160. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvReLU2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8161. this.registerType('torch.ao.nn.intrinsic.modules.fused.LinearReLU', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8162. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvBnReLU2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8163. this.registerType('torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU2d', class {});
  8164. this.registerType('torch.nn.utils.prune.CustomFromMask', class {});
  8165. this.registerType('torch.nn.utils.prune.Identity', class {});
  8166. this.registerType('torch.nn.utils.prune.L1Unstructured', class {});
  8167. this.registerType('torch.nn.utils.prune.LnStructured', class {});
  8168. this.registerType('torch.nn.utils.prune.PruningContainer', class {});
  8169. this.registerType('torch.nn.utils.prune.RandomUnstructured', class {});
  8170. this.registerType('torch.nn.utils.spectral_norm.SpectralNorm', class {});
  8171. this.registerType('torch.nn.utils.spectral_norm.SpectralNormStateDictHook', class {});
  8172. this.registerType('torch.nn.utils.spectral_norm.SpectralNormLoadStateDictPreHook', class {});
  8173. this.registerType('torch.nn.utils.weight_norm.WeightNorm', class {});
  8174. this.registerFunction('torch.nn.utils.parametrize.type_before_parametrizations');
  8175. this.registerType('torch.nn.utils.parametrize.ParametrizationList', class extends torch.nn.modules.container.ModuleList {});
  8176. this.registerType('torch.torch_version.TorchVersion', class extends String {});
  8177. this.registerType('torch.optim.optimizer.Optimizer', class {});
  8178. this.registerType('torch.optim.adam.Adam', class extends torch.optim.optimizer.Optimizer {});
  8179. this.registerType('torch.optim.adamw.AdamW', class {});
  8180. this.registerType('torch.optim.adagrad.Adagrad', class {});
  8181. this.registerType('torch.optim.adadelta.Adadelta', class {});
  8182. this.registerType('torch.optim.lbfgs.LBFGS', class {});
  8183. this.registerType('torch.optim.lr_scheduler.CosineAnnealingLR', class {});
  8184. this.registerType('torch.optim.lr_scheduler.CosineAnnealingWarmRestarts', class {});
  8185. this.registerType('torch.optim.lr_scheduler.CyclicLR', class {});
  8186. this.registerType('torch.optim.lr_scheduler.ExponentialLR', class {});
  8187. this.registerType('torch.optim.lr_scheduler.LambdaLR', class {});
  8188. this.registerType('torch.optim.lr_scheduler.LinearLR', class {});
  8189. this.registerType('torch.optim.lr_scheduler.MultiStepLR', class {});
  8190. this.registerType('torch.optim.lr_scheduler.OneCycleLR', class {});
  8191. this.registerType('torch.optim.lr_scheduler.ReduceLROnPlateau', class {});
  8192. this.registerType('torch.optim.lr_scheduler.StepLR', class {});
  8193. this.registerType('torch.optim.optimizer._RequiredParameter', class {});
  8194. this.registerType('torch.optim.radam.RAdam', class extends torch.optim.optimizer.Optimizer {});
  8195. this.registerType('torch.optim.rmsprop.RMSprop', class {});
  8196. this.registerType('torch.optim.sgd.SGD', class {});
  8197. this.registerType('torch.optim.sparse_adam.SparseAdam', class {});
  8198. this.registerType('torch.optim.swa_utils.SWALR', class {});
  8199. torch.optim.RAdam = torch.optim.radam.RAdam;
  8200. this.registerType('torch.quantization.fake_quantize.FakeQuantize', class {});
  8201. this.registerFunction('torch.quantization.fx.graph_module._save_packed_weight');
  8202. this.registerType('torch.quantization.observer._PartialWrapper', class {});
  8203. this.registerType('torch.quantization.observer.HistogramObserver', class {});
  8204. this.registerType('torch.quantization.observer.MinMaxObserver', class {});
  8205. this.registerType('torch.quantization.observer.MovingAverageMinMaxObserver', class {});
  8206. this.registerType('torch.quantization.observer.MovingAveragePerChannelMinMaxObserver', class {});
  8207. this.registerFunction('torch.quantization.observer._with_args');
  8208. this.registerType('torch.quantization.qconfig.QConfig', class {});
  8209. this.registerType('torch.quantization.stubs.DeQuantStub', class {});
  8210. this.registerType('torch.quantization.stubs.QuantStub', class {});
  8211. this.registerType('torch.utils._pytree.LeafSpec', class {});
  8212. this.registerType('torch.utils._pytree.TreeSpec', class {});
  8213. this.registerType('torch.utils._python_dispatch.TorchDispatchMode', class {
  8214. __enter__() {
  8215. return this;
  8216. }
  8217. __exit__(/* exc_type, exc_value, traceback */) {
  8218. }
  8219. });
  8220. this.registerFunction('torch.utils._pytree.tree_map');
  8221. torch.nn.Sequential = torch.nn.modules.container.Sequential;
  8222. this.registerFunction('torch.fx.experimental.sym_node.SymNode', class {
  8223. constructor(expr, shape_env, pytype, hint, constant, fx_node, optimized_summation) {
  8224. this._expr = expr;
  8225. this.shape_env = shape_env;
  8226. this.pytype = pytype;
  8227. this._optimized_summation = optimized_summation;
  8228. this._hint = hint;
  8229. this.constant = constant;
  8230. const tx_validation_en = this.shape_env && this.shape_env._translation_validation_enabled ? true : false;
  8231. this.fx_node = tx_validation_en && fx_node ? fx_node : null;
  8232. }
  8233. __str__() {
  8234. return this._expr.__str__();
  8235. }
  8236. });
  8237. this.registerType('torch.fx.experimental.symbolic_shapes.ShapeEnv', class {
  8238. constructor() {
  8239. this.var_to_val = new Map();
  8240. this.var_to_stack = new Map();
  8241. }
  8242. add_var_to_val(expr, val) {
  8243. this.var_to_val.set(expr, new sympy.core.numbers.Integer(val));
  8244. }
  8245. constrain_symbol_range(/* s, compiler_min, compiler_max */) {
  8246. }
  8247. create_symintnode(sym, hint, source) {
  8248. let out = null;
  8249. let fx_node = null;
  8250. if (this._translation_validation_enabled && source !== null) {
  8251. throw new python.Error('Not implemented.');
  8252. } else {
  8253. fx_node = null;
  8254. }
  8255. if (builtins.isinstance(sym, sympy.core.numbers.Integer)) {
  8256. out = builtins.int(sym);
  8257. if (hint !== null && out !== hint) {
  8258. throw new python.Error(`Symbolic integer has value '${out}' but expected '${hint}'.`);
  8259. }
  8260. } else {
  8261. // if free_unbacked_symbols(sym):
  8262. // hint = None
  8263. out = new torch.SymInt(new torch.fx.experimental.sym_node.SymNode(sym, this, builtins.int, hint, null, fx_node));
  8264. }
  8265. return out;
  8266. }
  8267. create_symboolnode(sym) {
  8268. return new torch.SymBool(new torch.fx.experimental.sym_node.SymNode(sym, this, builtins.bool, null));
  8269. }
  8270. });
  8271. this.registerFunction('torch.fx.experimental.symbolic_shapes.symbol_is_type', (/* sym, prefix */) => {
  8272. /*
  8273. assert isinstance(sym, sympy.Symbol)
  8274. const name_str = sym.name.toLowerCase();
  8275. if (builtins.isinstance(prefix, torch.utils._sympy.symbol.SymT)) {
  8276. return name_str.startsWith(prefix_str[prefix])
  8277. }
  8278. return name_str.startswith(tuple(prefix_str[p] for p in prefix));
  8279. */
  8280. return false;
  8281. });
  8282. this.registerType('torch.fx.proxy.TracerBase', class {
  8283. constructor() {
  8284. this.traced_func_name = 'forward';
  8285. }
  8286. });
  8287. this.registerType('torch.fx._symbolic_trace.Tracer', class extends torch.fx.proxy.TracerBase {
  8288. trace(root /*, concrete_args */) {
  8289. let fn = null;
  8290. if (root instanceof torch.nn.Module) {
  8291. // torch.fx._lazy_graph_module._LazyGraphModule.force_recompile(root)
  8292. this.root = root;
  8293. fn = builtins.getattr(new builtins.type(root), this.traced_func_name);
  8294. this.root_module_name = root._get_name();
  8295. this.submodule_paths = new builtins.dict(root.named_modules());
  8296. } else {
  8297. this.root = new torch.nn.Module();
  8298. fn = root;
  8299. }
  8300. const tracer_cls = builtins.getattr(this, '__class__', null);
  8301. this.graph = new torch.fx.graph.Graph(null, tracer_cls);
  8302. if (builtins.hasattr(this, '__code__')) {
  8303. const code = fn.__code__;
  8304. this.graph._co_fields = {
  8305. co_name: code.co_name,
  8306. co_filename: code.co_filename,
  8307. co_firstlineno: code.co_firstlineno,
  8308. };
  8309. }
  8310. return this.graph;
  8311. }
  8312. is_leaf_module(m /*, module_qualified_name */) {
  8313. return (m.__module__.startsWith('torch.nn') || m.__module__.startsWith('torch.ao.nn')) && m instanceof torch.nn.Sequential === false;
  8314. }
  8315. });
  8316. this.registerType('torch.fx.experimental.proxy_tensor.PythonKeyTracer', class extends torch.fx._symbolic_trace.Tracer {});
  8317. this.registerType('torch.fx.experimental.proxy_tensor._ModuleStackTracer', class extends torch.fx.experimental.proxy_tensor.PythonKeyTracer {});
  8318. this.registerFunction('torch.fx._lazy_graph_module._make_graph_module', (...args) => {
  8319. const graph_module_cls = args.pop() || torch.fx.graph_module.GraphModule;
  8320. return new graph_module_cls(...args);
  8321. });
  8322. this.registerFunction('torch.fx.graph_module._deserialize_graph_module', (forward, body, graph_module_cls) => {
  8323. let tracer_cls = body.get('_tracer_cls');
  8324. if (!tracer_cls) {
  8325. tracer_cls = torch.fx._symbolic_trace.Tracer;
  8326. }
  8327. const graphmodule_cls_name = body.get('_graphmodule_cls_name', 'GraphModule');
  8328. const cls_tracer = tracer_cls;
  8329. const KeepModules = class extends cls_tracer {
  8330. is_leaf_module() {
  8331. return true;
  8332. }
  8333. };
  8334. const com = new torch.fx.graph_module._CodeOnlyModule(body);
  8335. const tracer_extras = body.get('_tracer_extras', new builtins.dict());
  8336. const graph = new KeepModules().trace(com, tracer_extras);
  8337. graph._tracer_cls = tracer_cls;
  8338. const gm = torch.fx._lazy_graph_module._make_graph_module(com, graph, graphmodule_cls_name, graph_module_cls);
  8339. for (const [k, v] of body.items()) {
  8340. if (!builtins.hasattr(gm, k)) {
  8341. builtins.setattr(gm, k, v);
  8342. }
  8343. }
  8344. return gm;
  8345. });
  8346. this.registerFunction('torch.fx.graph_module._forward_from_src', (src, globals /*, co_fields */) => {
  8347. globals = { ...globals };
  8348. const context = new python.Execution.Context(globals, null);
  8349. execution.exec(src, context);
  8350. const forward_fn = globals.forward;
  8351. delete globals.forward;
  8352. return forward_fn;
  8353. });
  8354. this.registerFunction('torch.fx.graph_module.reduce_graph_module', (body, import_block) => {
  8355. // https://github.com/pytorch/pytorch/blob/master/torch/fx/graph_module.py
  8356. let fn_src = null;
  8357. if (body.has('_code')) {
  8358. fn_src = body.get('_code');
  8359. } else if (body.has('code')) {
  8360. fn_src = body.get('code');
  8361. } else {
  8362. fn_src = body._code || body.code;
  8363. }
  8364. const forward = torch.fx.graph_module._forward_from_src(import_block + fn_src, {});
  8365. return torch.fx.graph_module._deserialize_graph_module(forward, body);
  8366. });
  8367. this.registerFunction('torch.fx.graph_module.reduce_package_graph_module', (importer, body, generated_module_name) => {
  8368. const forward = importer.import_module(generated_module_name).forward;
  8369. return torch.fx.graph_module._deserialize_graph_module(forward, body);
  8370. });
  8371. this.registerType('torch.fx.graph.CodeGen', class {});
  8372. this.registerType('torch.fx.graph._PyTreeInfo', class {
  8373. constructor(orig_args, in_spec, out_spec) {
  8374. this.orig_args = orig_args;
  8375. this.in_spec = in_spec;
  8376. this.out_spec = out_spec;
  8377. }
  8378. });
  8379. this.registerType('torch.fx.graph._Namespace', class {
  8380. constructor() {
  8381. this._obj_to_name = new Map();
  8382. this._unassociated_names = new Set();
  8383. this._used_names = new Set();
  8384. this._base_count = {};
  8385. }
  8386. create_name(candidate, obj) {
  8387. if (obj && this._obj_to_name.has(obj)) {
  8388. return self._obj_to_name.get(obj);
  8389. }
  8390. candidate = candidate || '_unnamed';
  8391. candidate = /^\d+$/.test(candidate) ? `_${candidate}` : candidate;
  8392. candidate = candidate.replace(/[^0-9a-zA-Z_]+/, '_');
  8393. const match = candidate.match(/(.*)_(\d+)$"/);
  8394. let base = candidate;
  8395. let num = null;
  8396. if (match) {
  8397. [, base] = match;
  8398. num = parseInt(match[2], 10);
  8399. }
  8400. candidate = num ? `${base}_${num}` : base;
  8401. if (!num) {
  8402. num = this._base_count[base] || 0;
  8403. }
  8404. while (this._used_names.has(candidate) || this._is_illegal_name(candidate, obj)) {
  8405. num += 1;
  8406. candidate = `${base}_${num}`;
  8407. }
  8408. this._used_names.add(candidate);
  8409. this._base_count[base] = num;
  8410. if (obj) {
  8411. this._obj_to_name[obj] = candidate;
  8412. } else {
  8413. this._unassociated_names.add(candidate);
  8414. }
  8415. return candidate;
  8416. }
  8417. _is_illegal_name(/* name, obj */) {
  8418. /*
  8419. if name in keyword.kwlist:
  8420. return True
  8421. if name in builtins.__dict__:
  8422. return obj is not builtins.__dict__[name]
  8423. if name in _custom_builtins:
  8424. return obj is not _custom_builtins[name].obj
  8425. */
  8426. return false;
  8427. }
  8428. associate_name_with_obj() {
  8429. }
  8430. });
  8431. this.registerType('torch.fx.node.Node', class {
  8432. constructor(graph, name, op, target, args, kwargs, return_type) {
  8433. this.graph = graph;
  8434. this.name = name;
  8435. this.op = op;
  8436. this.target = target;
  8437. this._input_nodes = new builtins.dict();
  8438. this.__update_args_kwargs(args, kwargs);
  8439. this.users = new builtins.dict();
  8440. this.type = return_type;
  8441. this._prev = this;
  8442. this._next = this;
  8443. this._erased = false;
  8444. this._repr_fn = null;
  8445. this.meta = new builtins.dict();
  8446. }
  8447. get args() {
  8448. return this._args;
  8449. }
  8450. get kwargs() {
  8451. return this._kwargs;
  8452. }
  8453. get next() {
  8454. return this._next;
  8455. }
  8456. prepend(x) {
  8457. x._remove_from_list();
  8458. const p = this._prev;
  8459. [p._next, x._prev] = [x, p];
  8460. [x._next, this._prev] = [this, x];
  8461. }
  8462. _remove_from_list() {
  8463. const [p, n] = [this._prev, this._next];
  8464. [p._next, n._prev] = [n, p];
  8465. }
  8466. __update_args_kwargs(new_args, new_kwargs) {
  8467. const update_users_and_input_nodes = (n) => {
  8468. if (n instanceof torch.fx.node.Node) {
  8469. this._input_nodes.setdefault(n);
  8470. n.users.setdefault(this);
  8471. }
  8472. return n;
  8473. };
  8474. const map_aggregate = (a, fn) => {
  8475. if (a instanceof builtins.tuple) {
  8476. const t = new builtins.tuple(a.map((elem) => map_aggregate(elem, fn)));
  8477. if (!builtins.hasattr(a, '_fields')) {
  8478. return t;
  8479. }
  8480. throw new python.Error('Not implemented.');
  8481. // return type(a)(*t);
  8482. } else if (Array.isArray(a)) {
  8483. return a.map((elem) => map_aggregate(elem, fn));
  8484. } else if (a instanceof builtins.dict) {
  8485. const rv = new builtins.dict();
  8486. for (const [k, v] of a) {
  8487. rv.__setitem__(k, map_aggregate(v, fn));
  8488. }
  8489. return rv;
  8490. } else if (a instanceof builtins.slice) {
  8491. throw new python.Error('Not implemented.');
  8492. // return slice(map_aggregate(a.start, fn), map_aggregate(a.stop, fn), map_aggregate(a.step, fn))
  8493. }
  8494. return fn(a);
  8495. };
  8496. for (const old_use of this._input_nodes.keys()) {
  8497. old_use.users.pop(this);
  8498. }
  8499. // object.__setattr__(self, "_input_nodes", {})
  8500. this._input_nodes = new builtins.dict();
  8501. // object.__setattr__(self, "_args", map_aggregate(new_args, update_users_and_input_nodes))
  8502. this._args = map_aggregate(new_args, update_users_and_input_nodes);
  8503. // object.__setattr__(self, "_kwargs", map_aggregate(new_kwargs, update_users_and_input_nodes))
  8504. this._kwargs = map_aggregate(new_kwargs, update_users_and_input_nodes);
  8505. }
  8506. });
  8507. torch.fx.Node = torch.fx.node.Node;
  8508. torch.fx.graph.Node = torch.fx.node.Node;
  8509. this.registerType('torch.fx.graph.Graph', class {
  8510. constructor(owning_module, tracer_cls, tracer_extras) {
  8511. this._root = new torch.fx.node.Node(self, '', 'root', '', new builtins.list(), new builtins.dict());
  8512. this._used_names = new Map();
  8513. this._len = 0;
  8514. this._graph_namespace = new torch.fx.graph._Namespace();
  8515. this._owning_module = owning_module;
  8516. this._tracer_cls = tracer_cls;
  8517. this._tracer_extras = tracer_extras;
  8518. // this._codegen = CodeGen()
  8519. // this._co_fields = {}
  8520. }
  8521. get nodes() {
  8522. const array = new Array(this._len);
  8523. let node = this._root.next;
  8524. for (let i = 0; node !== this._root; i++) {
  8525. array[i] = node;
  8526. node = node.next;
  8527. }
  8528. return array;
  8529. }
  8530. placeholder(name, type_expr /*, default_value */) {
  8531. const args = []; // () if default_value is inspect.Signature.empty else (default_value,)
  8532. const kwargs = new builtins.dict();
  8533. return this.create_node('placeholder', name, args, kwargs, type_expr);
  8534. }
  8535. create_node(op, target, args, kwargs, name, type_expr) {
  8536. args = args || new builtins.tuple();
  8537. kwargs = kwargs || new builtins.dict();
  8538. const candidate = name || this._target_to_str(target);
  8539. name = this._graph_namespace.create_name(candidate, null);
  8540. const n = new torch.fx.node.Node(this, name, op, target, args, kwargs, type_expr);
  8541. this._graph_namespace.associate_name_with_obj(name, n);
  8542. this._insert(n);
  8543. this._len += 1;
  8544. return n;
  8545. }
  8546. _insert(n) {
  8547. this._root.prepend(n);
  8548. }
  8549. output(result, type_expr) {
  8550. return this.create_node('output', 'output', new builtins.tuple(result), null, type_expr);
  8551. }
  8552. _target_to_str(target) {
  8553. if (typeof target === 'string') {
  8554. if (target.startsWith('__') && target.endsWith('__')) {
  8555. target = target.substring(2, target.length - 2);
  8556. }
  8557. } else {
  8558. target = target.__name__;
  8559. }
  8560. return this._snake_case(target);
  8561. }
  8562. _snake_case(s) {
  8563. const chars = [];
  8564. let prev_lower = false;
  8565. for (const c of s) {
  8566. const x = c.toLowerCase();
  8567. if (prev_lower && x !== c) {
  8568. chars.push('_');
  8569. } else {
  8570. prev_lower = true;
  8571. }
  8572. chars.push(x);
  8573. }
  8574. return chars.join('');
  8575. }
  8576. });
  8577. this.registerType('torch.fx.graph_module._CodeOnlyModule', class extends torch.nn.modules.module.Module {
  8578. constructor(body) {
  8579. super();
  8580. for (const [k, v] of body.items()) {
  8581. builtins.setattr(this, k, v);
  8582. }
  8583. }
  8584. });
  8585. this.registerFunction('torch.fx.graph_module._copy_attr', (from_module, to_module, target) => {
  8586. const parts = target.split('.');
  8587. const field = parts.pop();
  8588. for (const item of parts) {
  8589. const f = builtins.getattr(from_module, item);
  8590. let t = builtins.getattr(to_module, item, null);
  8591. if (f === t) {
  8592. return;
  8593. }
  8594. if (t === null) {
  8595. t = new torch.nn.modules.module.Module();
  8596. builtins.setattr(to_module, item, t);
  8597. }
  8598. from_module = f;
  8599. to_module = t;
  8600. }
  8601. const orig = builtins.getattr(from_module, field);
  8602. builtins.setattr(to_module, field, orig);
  8603. });
  8604. this.registerType('torch.fx.graph_module.GraphModule', class extends torch.nn.modules.module.Module {
  8605. constructor(root, graph, class_name) {
  8606. super();
  8607. this.__class__.__name__ = class_name || 'GraphModule';
  8608. this.graph = graph;
  8609. if (root instanceof torch.nn.modules.module.Module && graph && graph.nodes) {
  8610. for (const node of graph.nodes) {
  8611. if (node.op === 'get_attr' || node.op === 'call_module') {
  8612. torch.fx.graph_module._copy_attr(root, this, node.target);
  8613. }
  8614. }
  8615. }
  8616. }
  8617. });
  8618. torch.fx.Graph = torch.fx.graph.Graph;
  8619. torch.fx.GraphModule = torch.fx.graph_module.GraphModule;
  8620. this.registerType('torch.fx.immutable_collections.immutable_dict', class extends builtins.dict {});
  8621. this.registerType('torch.fx.immutable_collections.immutable_list', class extends builtins.list {});
  8622. this.registerFunction('torch.fx._symbolic_trace.wrap', (fn_or_name) => {
  8623. return fn_or_name;
  8624. });
  8625. this.registerFunction('torch.fx._symbolic_trace._assert_is_none');
  8626. this.registerFunction('torchvision.datasets.folder.default_loader');
  8627. this.registerType('torchvision.datasets.folder.ImageFolder', class {});
  8628. this.registerType('torchvision.datasets.mnist.FashionMNIST', class {});
  8629. this.registerType('torchvision.datasets.mnist.MNIST', class {});
  8630. this.registerType('torchvision.datasets.video_utils.VideoClips', class {});
  8631. this.registerType('torchvision.datasets.vision.StandardTransform', class {});
  8632. this.registerType('torchvision.ops.deform_conv.DeformConv2d', class {});
  8633. this.registerType('torchvision.ops.feature_pyramid_network.FeaturePyramidNetwork', class {});
  8634. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelMaxPool', class {});
  8635. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelP6P7', class {});
  8636. this.registerType('torchvision.ops.misc.Conv2dNormActivation', class {});
  8637. this.registerType('torchvision.ops.misc.ConvNormActivation', class {});
  8638. this.registerType('torchvision.ops.misc.MLP', class extends torch.nn.modules.container.Sequential {});
  8639. this.registerType('torchvision.ops.misc.ConvTranspose2d', class {});
  8640. this.registerType('torchvision.ops.misc.FrozenBatchNorm2d', class {});
  8641. this.registerType('torchvision.ops.misc.Permute', class {});
  8642. this.registerType('torchvision.ops.misc.SqueezeExcitation', class {});
  8643. this.registerType('torchvision.ops.poolers.LevelMapper', class {});
  8644. this.registerType('torchvision.ops.poolers.MultiScaleRoIAlign', class {});
  8645. this.registerType('torchvision.ops.roi_align.RoIAlign', class {});
  8646. this.registerType('torchvision.ops.stochastic_depth.StochasticDepth', class {});
  8647. this.registerType('torchvision.models._api.Weights', class {});
  8648. this.registerType('torchvision.models.alexnet.AlexNet', class {});
  8649. this.registerType('torchvision.models.convnext.ConvNeXt', class {});
  8650. this.registerType('torchvision.models.convnext.CNBlock', class {});
  8651. this.registerType('torchvision.models.convnext.LayerNorm2d', class {});
  8652. this.registerType('torchvision.models.densenet.DenseNet', class extends torch.nn.modules.module.Module {});
  8653. this.registerType('torchvision.models.densenet._DenseBlock', class extends torch.nn.modules.container.ModuleDict {});
  8654. this.registerType('torchvision.models.densenet._DenseLayer', class extends torch.nn.modules.module.Module {});
  8655. this.registerType('torchvision.models.densenet._Transition', class extends torch.nn.modules.container.Sequential {});
  8656. this.registerType('torchvision.models.detection._utils.BalancedPositiveNegativeSampler', class {});
  8657. this.registerType('torchvision.models.detection._utils.BoxCoder', class {});
  8658. this.registerType('torchvision.models.detection._utils.Matcher', class {});
  8659. this.registerType('torchvision.models.detection._utils.SSDMatcher', class {});
  8660. this.registerType('torchvision.models.detection.anchor_utils.AnchorGenerator', class {});
  8661. this.registerType('torchvision.models.detection.anchor_utils.DefaultBoxGenerator', class {});
  8662. this.registerType('torchvision.models.detection.backbone_utils.BackboneWithFPN', class {});
  8663. this.registerType('torchvision.models.detection.faster_rcnn.FasterRCNN', class {});
  8664. this.registerType('torchvision.models.detection.faster_rcnn.FastRCNNConvFCHead', class {});
  8665. this.registerType('torchvision.models.detection.faster_rcnn.FastRCNNPredictor', class {});
  8666. this.registerType('torchvision.models.detection.faster_rcnn.TwoMLPHead', class {});
  8667. this.registerType('torchvision.models.detection.fcos.FCOS', class {});
  8668. this.registerType('torchvision.models.detection.fcos.FCOSHead', class {});
  8669. this.registerType('torchvision.models.detection.fcos.FCOSClassificationHead', class {});
  8670. this.registerType('torchvision.models.detection.fcos.FCOSRegressionHead', class {});
  8671. this.registerType('torchvision.models.detection._utils.BoxLinearCoder', class {});
  8672. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNN', class {});
  8673. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNHeads', class {});
  8674. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNPredictor', class {});
  8675. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNN', class {});
  8676. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNHeads', class {});
  8677. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNPredictor', class {});
  8678. this.registerType('torchvision.models.detection.retinanet.RetinaNet', class {});
  8679. this.registerType('torchvision.models.detection.retinanet.RetinaNetClassificationHead', class {});
  8680. this.registerType('torchvision.models.detection.retinanet.RetinaNetHead', class {});
  8681. this.registerType('torchvision.models.detection.retinanet.RetinaNetRegressionHead', class {});
  8682. this.registerType('torchvision.models.detection.roi_heads.RoIHeads', class {});
  8683. this.registerType('torchvision.models.detection.rpn.AnchorGenerator', class {});
  8684. this.registerType('torchvision.models.detection.rpn.RegionProposalNetwork', class {});
  8685. this.registerType('torchvision.models.detection.rpn.RPNHead', class {});
  8686. this.registerType('torchvision.models.detection.ssd.SSD', class {});
  8687. this.registerType('torchvision.models.detection.ssd.SSDClassificationHead', class {});
  8688. this.registerType('torchvision.models.detection.ssd.SSDHead', class {});
  8689. this.registerType('torchvision.models.detection.ssd.SSDFeatureExtractorVGG', class {});
  8690. this.registerType('torchvision.models.detection.ssd.SSDRegressionHead', class {});
  8691. this.registerType('torchvision.models.detection.ssdlite.SSDLiteClassificationHead', class {});
  8692. this.registerType('torchvision.models.detection.ssdlite.SSDLiteFeatureExtractorMobileNet', class {});
  8693. this.registerType('torchvision.models.detection.ssdlite.SSDLiteHead', class {});
  8694. this.registerType('torchvision.models.detection.ssdlite.SSDLiteRegressionHead', class {});
  8695. this.registerType('torchvision.models.detection.transform.GeneralizedRCNNTransform', class {});
  8696. this.registerType('torchvision.models.efficientnet.EfficientNet', class {});
  8697. this.registerType('torchvision.models.efficientnet.EfficientNet_B3_Weights', class {});
  8698. this.registerType('torchvision.models.efficientnet.FusedMBConv', class {});
  8699. this.registerType('torchvision.models.efficientnet.MBConv', class {});
  8700. this.registerType('torchvision.models.feature_extraction.LeafModuleAwareTracer', class extends torch.fx._symbolic_trace.Tracer {});
  8701. this.registerType('torchvision.models.feature_extraction.NodePathTracer', class extends torchvision.models.feature_extraction.LeafModuleAwareTracer {});
  8702. this.registerType('torchvision.models.googlenet.BasicConv2d', class {});
  8703. this.registerType('torchvision.models.googlenet.GoogLeNet', class {});
  8704. this.registerType('torchvision.models.googlenet.Inception', class {});
  8705. this.registerType('torchvision.models.googlenet.InceptionAux', class {});
  8706. this.registerType('torchvision.models.inception.BasicConv2d', class {});
  8707. this.registerType('torchvision.models.inception.Inception3', class {});
  8708. this.registerType('torchvision.models.inception.InceptionAux', class {});
  8709. this.registerType('torchvision.models.inception.InceptionA', class {});
  8710. this.registerType('torchvision.models.inception.InceptionB', class {});
  8711. this.registerType('torchvision.models.inception.InceptionC', class {});
  8712. this.registerType('torchvision.models.inception.InceptionD', class {});
  8713. this.registerType('torchvision.models.inception.InceptionE', class {});
  8714. this.registerFunction('torchvision.models.inception.inception_v3');
  8715. this.registerType('torchvision.models.mnasnet._InvertedResidual', class {});
  8716. this.registerType('torchvision.models.mnasnet.MNASNet', class {});
  8717. this.registerType('torchvision.models.maxvit.MaxVit', class {});
  8718. this.registerType('torchvision.models.maxvit.MaxVitBlock', class {});
  8719. this.registerType('torchvision.models.maxvit.MaxVitLayer', class {});
  8720. this.registerType('torchvision.models.maxvit.MBConv', class {});
  8721. this.registerType('torchvision.models.maxvit.PartitionAttentionLayer', class {});
  8722. this.registerType('torchvision.models.maxvit.RelativePositionalMultiHeadAttention', class {});
  8723. this.registerType('torchvision.models.maxvit.SwapAxes', class {});
  8724. this.registerType('torchvision.models.maxvit.WindowDepartition', class {});
  8725. this.registerType('torchvision.models.mobilenet.ConvBNReLU', class {});
  8726. this.registerType('torchvision.models.mobilenet.MobileNetV2', class {});
  8727. this.registerType('torchvision.models.mobilenet.InvertedResidual', class {});
  8728. this.registerType('torchvision.models.mobilenetv2.ConvBNActivation', class {});
  8729. this.registerType('torchvision.models.mobilenetv2.InvertedResidual', class {});
  8730. this.registerType('torchvision.models.mobilenetv2.MobileNetV2', class {});
  8731. this.registerType('torchvision.models.mobilenetv3.InvertedResidual', class {});
  8732. this.registerType('torchvision.models.mobilenetv3.MobileNetV3', class {});
  8733. this.registerType('torchvision.models.mobilenetv3.SqueezeExcitation', class {});
  8734. this.registerType('torchvision.models.regnet.AnyStage', class extends torch.nn.modules.container.Sequential {});
  8735. this.registerType('torchvision.models.regnet.BottleneckTransform', class {});
  8736. this.registerType('torchvision.models.regnet.ResBottleneckBlock', class {});
  8737. this.registerType('torchvision.models.regnet.RegNet', class {});
  8738. this.registerType('torchvision.models.regnet.SimpleStemIN', class {});
  8739. this.registerType('torchvision.models.resnet.Bottleneck', class {});
  8740. this.registerType('torchvision.models.resnet.BasicBlock', class {});
  8741. this.registerType('torchvision.models.quantization.mobilenet.QuantizableInvertedResidual', class {});
  8742. this.registerType('torchvision.models.quantization.mobilenet.QuantizableMobileNetV2', class {});
  8743. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableInvertedResidual', class {});
  8744. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableMobileNetV2', class {});
  8745. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableMobileNetV3', class {});
  8746. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableInvertedResidual', class {});
  8747. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableSqueezeExcitation', class {});
  8748. this.registerType('torchvision.models.quantization.resnet.QuantizableBasicBlock', class {});
  8749. this.registerType('torchvision.models.quantization.resnet.QuantizableBottleneck', class {});
  8750. this.registerType('torchvision.models.quantization.resnet.QuantizableResNet', class {});
  8751. this.registerType('torchvision.models.segmentation.deeplabv3.ASPP', class {});
  8752. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPConv', class {});
  8753. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPPooling', class {});
  8754. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabHead', class {});
  8755. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabV3', class {});
  8756. this.registerType('torchvision.models.segmentation.fcn.FCN', class {});
  8757. this.registerType('torchvision.models.segmentation.fcn.FCNHead', class {});
  8758. this.registerType('torchvision.models.segmentation.lraspp.LRASPP', class {});
  8759. this.registerType('torchvision.models.segmentation.lraspp.LRASPPHead', class {});
  8760. this.registerType('torchvision.models.shufflenetv2.ShuffleNetV2', class {});
  8761. this.registerType('torchvision.models.shufflenetv2.InvertedResidual', class {});
  8762. this.registerType('torchvision.models.squeezenet.Fire', class {});
  8763. this.registerType('torchvision.models.squeezenet.SqueezeNet', class {});
  8764. this.registerType('torchvision.models.swin_transformer.PatchMerging', class {});
  8765. this.registerType('torchvision.models.swin_transformer.PatchMergingV2', class {});
  8766. this.registerType('torchvision.models.swin_transformer.ShiftedWindowAttention', class {});
  8767. this.registerType('torchvision.models.swin_transformer.ShiftedWindowAttentionV2', class {});
  8768. this.registerType('torchvision.models.swin_transformer.SwinTransformer', class {});
  8769. this.registerType('torchvision.models.swin_transformer.SwinTransformerBlock', class {});
  8770. this.registerType('torchvision.models.swin_transformer.SwinTransformerBlockV2', class {});
  8771. this.registerType('torchvision.models.resnet.ResNet', class {});
  8772. this.registerType('torchvision.models.vgg.VGG', class {});
  8773. this.registerType('torchvision.models.video.resnet.BasicBlock', class {});
  8774. this.registerType('torchvision.models.video.resnet.BasicStem', class {});
  8775. this.registerType('torchvision.models.video.resnet.Conv2Plus1D', class {});
  8776. this.registerType('torchvision.models.video.resnet.Conv3DNoTemporal', class {});
  8777. this.registerType('torchvision.models.video.resnet.Conv3DSimple', class {});
  8778. this.registerType('torchvision.models.video.resnet.R2Plus1dStem', class {});
  8779. this.registerType('torchvision.models.video.resnet.VideoResNet', class {});
  8780. this.registerType('torchvision.models.vision_transformer.Encoder', class extends torch.nn.modules.module.Module {});
  8781. this.registerType('torchvision.models.vision_transformer.EncoderBlock', class extends torch.nn.modules.module.Module {});
  8782. this.registerType('torchvision.models.vision_transformer.MLPBlock', class extends torchvision.ops.misc.MLP {});
  8783. this.registerType('torchvision.models.vision_transformer.VisionTransformer', class extends torch.nn.modules.module.Module {});
  8784. this.registerType('torchvision.models._utils.IntermediateLayerGetter', class {});
  8785. this.registerType('torchvision.transforms._presets.ImageClassification', class extends torch.nn.modules.module.Module {});
  8786. this.registerType('torchvision.transforms.autoaugment.AutoAugment', class {});
  8787. this.registerType('torchvision.transforms.autoaugment.AutoAugmentPolicy', class {});
  8788. this.registerType('torchvision.transforms.autoaugment.AugMix', class {});
  8789. this.registerType('torchvision.transforms.functional.InterpolationMode', class {});
  8790. this.registerFunction('torchvision.transforms.functional.adjust_brightness');
  8791. this.registerFunction('torchvision.transforms.functional.adjust_contrast');
  8792. this.registerFunction('torchvision.transforms.functional.adjust_brightness');
  8793. this.registerFunction('torchvision.transforms.functional.adjust_contrast');
  8794. this.registerFunction('torchvision.transforms.functional.adjust_gamma');
  8795. this.registerFunction('torchvision.transforms.functional.adjust_hue');
  8796. this.registerFunction('torchvision.transforms.functional.adjust_saturation');
  8797. this.registerType('torchvision.transforms.transforms.ColorJitter', class extends torch.nn.modules.module.Module {});
  8798. this.registerType('torchvision.transforms.transforms.Compose', class {});
  8799. this.registerType('torchvision.transforms.transforms.ConvertImageDtype', class {});
  8800. this.registerType('torchvision.transforms.transforms.CenterCrop', class extends torch.nn.modules.module.Module {});
  8801. this.registerType('torchvision.transforms.transforms.GaussianBlur', class extends torch.nn.modules.module.Module {});
  8802. this.registerType('torchvision.transforms.transforms.Grayscale', class extends torch.nn.modules.module.Module {});
  8803. this.registerType('torchvision.transforms.transforms.Lambda', class {});
  8804. this.registerType('torchvision.transforms.transforms.Normalize', class extends torch.nn.modules.module.Module {});
  8805. this.registerType('torchvision.transforms.transforms.PILToTensor', class {});
  8806. this.registerType('torchvision.transforms.transforms.RandomAffine', class extends torch.nn.modules.module.Module {});
  8807. this.registerType('torchvision.transforms.transforms.RandomApply', class extends torch.nn.modules.module.Module {});
  8808. this.registerType('torchvision.transforms.transforms.RandomCrop', class extends torch.nn.modules.module.Module {});
  8809. this.registerType('torchvision.transforms.transforms.RandomChoice', class {});
  8810. this.registerType('torchvision.transforms.transforms.RandomErasing', class {});
  8811. this.registerType('torchvision.transforms.transforms.RandomInvert', class {});
  8812. this.registerType('torchvision.transforms.transforms.RandomPerspective', class {});
  8813. this.registerType('torchvision.transforms.transforms.RandomHorizontalFlip', class extends torch.nn.modules.module.Module {});
  8814. this.registerType('torchvision.transforms.transforms.RandomVerticalFlip', class extends torch.nn.modules.module.Module {});
  8815. this.registerType('torchvision.transforms.transforms.RandomResizedCrop', class extends torch.nn.modules.module.Module {});
  8816. this.registerType('torchvision.transforms.transforms.RandomRotation', class extends torch.nn.modules.module.Module {});
  8817. this.registerType('torchvision.transforms.transforms.Resize', class extends torch.nn.modules.module.Module {});
  8818. this.registerType('torchvision.transforms.transforms.Scale', class extends torch.nn.modules.module.Module {});
  8819. this.registerType('torchvision.transforms.transforms.ToPILImage', class {});
  8820. this.registerType('torchvision.transforms.transforms.ToTensor', class {});
  8821. this.registerType('torchvision.transforms.v2._color.Grayscale', class {});
  8822. this.registerType('torchvision.transforms.v2._color.RandomGrayscale', class {});
  8823. this.registerType('torchvision.transforms.v2._container.Compose', class {});
  8824. this.registerType('torchvision.transforms.v2._deprecated.ToTensor', class {});
  8825. this.registerType('torchvision.transforms.v2._misc.ConvertImageDtype', class {});
  8826. this.registerType('torchvision.transforms.v2._misc.Normalize', class {});
  8827. this.registerType('torchvision.transforms.v2._misc.ToDtype', class {});
  8828. this.registerType('torchvision.transforms.v2._geometry.CenterCrop', class {});
  8829. this.registerType('torchvision.transforms.v2._geometry.Resize', class {});
  8830. this.registerType('torchvision.transforms.v2._geometry.Pad', class {});
  8831. this.registerType('torchvision.transforms.v2._geometry.RandomCrop', class {});
  8832. this.registerType('torchvision.transforms.v2._transform.Transform', class extends torch.nn.modules.module.Module {});
  8833. this.registerType('torchvision.transforms.v2._type_conversion.ToImage', class extends torchvision.transforms.v2._transform.Transform {});
  8834. this.registerType('torchvision.transforms.v2._type_conversion.PILToTensor', class {});
  8835. this.registerFunction('torchvision.models.resnet.resnet18', () => {});
  8836. this.registerFunction('torchvision.models.resnet.resnet34', () => {});
  8837. this.registerFunction('torchvision.models.resnet.resnet50', () => {});
  8838. this.registerFunction('torchvision.models.resnet.resnet101', () => {});
  8839. this.registerFunction('torchvision.models.resnet.resnet152', () => {});
  8840. this.registerFunction('torchvision.models.vision_transformer.vit_h_14', () => {});
  8841. this.registerFunction('torchvision.ops.boxes.box_iou');
  8842. this.registerFunction('torchvision.ops.focal_loss.sigmoid_focal_loss');
  8843. this.registerType('ultralytics.nn.modules.block.Attention', class extends torch.nn.modules.module.Module {});
  8844. this.registerType('ultralytics.nn.modules.block.Bottleneck', class extends torch.nn.modules.module.Module {});
  8845. this.registerType('ultralytics.nn.modules.block.C1', class extends torch.nn.modules.module.Module {});
  8846. this.registerType('ultralytics.nn.modules.block.C2', class extends torch.nn.modules.module.Module {});
  8847. this.registerType('ultralytics.nn.modules.block.C2f', class extends torch.nn.modules.module.Module {});
  8848. this.registerType('ultralytics.nn.modules.block.C2fAttn', class extends torch.nn.modules.module.Module {});
  8849. this.registerType('ultralytics.nn.modules.block.C2fCIB', class extends torch.nn.modules.module.Module {});
  8850. this.registerType('ultralytics.nn.modules.block.C2fPSA', class extends torch.nn.modules.module.Module {});
  8851. this.registerType('ultralytics.nn.modules.block.C2PSA', class extends torch.nn.modules.module.Module {});
  8852. this.registerType('ultralytics.nn.modules.block.C3', class extends torch.nn.modules.module.Module {});
  8853. this.registerType('ultralytics.nn.modules.block.C3Ghost', class extends torch.nn.modules.module.Module {});
  8854. this.registerType('ultralytics.nn.modules.block.C3k', class extends torch.nn.modules.module.Module {});
  8855. this.registerType('ultralytics.nn.modules.block.C3k2', class extends torch.nn.modules.module.Module {});
  8856. this.registerType('ultralytics.nn.modules.block.C3k2_v2', class extends torch.nn.modules.module.Module {});
  8857. this.registerType('ultralytics.nn.modules.block.C3TR', class extends torch.nn.modules.module.Module {});
  8858. this.registerType('ultralytics.nn.modules.block.C3x', class extends torch.nn.modules.module.Module {});
  8859. this.registerType('ultralytics.nn.modules.block.CIB', class extends torch.nn.modules.module.Module {});
  8860. this.registerType('ultralytics.nn.modules.block.DFL', class extends torch.nn.modules.module.Module {});
  8861. this.registerType('ultralytics.nn.modules.block.GhostBottleneck', class extends torch.nn.modules.module.Module {});
  8862. this.registerType('ultralytics.nn.modules.block.HGBlock', class extends torch.nn.modules.module.Module {});
  8863. this.registerType('ultralytics.nn.modules.block.HGStem', class extends torch.nn.modules.module.Module {});
  8864. this.registerType('ultralytics.nn.modules.block.Proto', class extends torch.nn.modules.module.Module {});
  8865. this.registerType('ultralytics.nn.modules.block.PSA', class extends torch.nn.modules.module.Module {});
  8866. this.registerType('ultralytics.nn.modules.block.PSABlock', class extends torch.nn.modules.module.Module {});
  8867. this.registerType('ultralytics.nn.modules.block.RepC3', class extends torch.nn.modules.module.Module {});
  8868. this.registerType('ultralytics.nn.modules.block.SCDown', class extends torch.nn.modules.module.Module {});
  8869. this.registerType('ultralytics.nn.modules.block.SPP', class extends torch.nn.modules.module.Module {});
  8870. this.registerType('ultralytics.nn.modules.block.SPPF', class extends torch.nn.modules.module.Module {});
  8871. this.registerType('ultralytics.nn.modules.conv.Concat', class extends torch.nn.modules.module.Module {});
  8872. this.registerType('ultralytics.nn.modules.conv.Conv', class extends torch.nn.modules.module.Module {});
  8873. this.registerType('ultralytics.nn.modules.conv.Conv2', class extends torch.nn.modules.module.Module {});
  8874. this.registerType('ultralytics.nn.modules.conv.ConvTranspose', class extends torch.nn.modules.module.Module {});
  8875. this.registerType('ultralytics.nn.modules.conv.DWConv', class extends torch.nn.modules.module.Module {});
  8876. this.registerType('ultralytics.nn.modules.conv.DWConvTranspose2d', class extends torch.nn.modules.module.Module {});
  8877. this.registerType('ultralytics.nn.modules.conv.Focus', class extends torch.nn.modules.module.Module {});
  8878. this.registerType('ultralytics.nn.modules.conv.GhostConv', class extends torch.nn.modules.module.Module {});
  8879. this.registerType('ultralytics.nn.modules.conv.LightConv', class extends torch.nn.modules.module.Module {});
  8880. this.registerType('ultralytics.nn.modules.conv.RepConv', class extends torch.nn.modules.module.Module {});
  8881. this.registerType('ultralytics.nn.modules.head.Classify', class extends torch.nn.modules.module.Module {});
  8882. this.registerType('ultralytics.nn.modules.head.Detect', class extends torch.nn.modules.module.Module {});
  8883. this.registerType('ultralytics.nn.modules.head.OBB', class extends torch.nn.modules.module.Module {});
  8884. this.registerType('ultralytics.nn.modules.head.Pose', class extends torch.nn.modules.module.Module {});
  8885. this.registerType('ultralytics.nn.modules.head.RTDETRDecoder', class extends torch.nn.modules.module.Module {});
  8886. this.registerType('ultralytics.nn.modules.head.Segment', class extends torch.nn.modules.module.Module {});
  8887. this.registerType('ultralytics.nn.modules.head.WorldDetect', class extends torch.nn.modules.module.Module {});
  8888. this.registerType('ultralytics.nn.modules.head.v10Detect', class extends torch.nn.modules.module.Module {});
  8889. this.registerType('ultralytics.nn.modules.transformer.AIFI', class extends torch.nn.modules.module.Module {});
  8890. this.registerType('ultralytics.nn.modules.transformer.DeformableTransformerDecoder', class extends torch.nn.modules.module.Module {});
  8891. this.registerType('ultralytics.nn.modules.transformer.DeformableTransformerDecoderLayer', class extends torch.nn.modules.module.Module {});
  8892. this.registerType('ultralytics.nn.modules.transformer.MLP', class extends torch.nn.modules.module.Module {});
  8893. this.registerType('ultralytics.nn.modules.transformer.TransformerEncoderLayer', class extends torch.nn.modules.module.Module {});
  8894. this.registerType('ultralytics.nn.modules.transformer.TransformerLayer', class extends torch.nn.modules.module.Module {});
  8895. this.registerType('ultralytics.nn.modules.Bottleneck', class extends torch.nn.modules.module.Module {});
  8896. this.registerType('ultralytics.nn.modules.C2f', class extends torch.nn.modules.module.Module {});
  8897. this.registerType('ultralytics.nn.modules.Concat', class extends torch.nn.modules.module.Module {});
  8898. this.registerType('ultralytics.nn.modules.Conv', class extends torch.nn.modules.module.Module {});
  8899. this.registerType('ultralytics.nn.modules.DFL', class extends torch.nn.modules.module.Module {});
  8900. this.registerType('ultralytics.nn.modules.Detect', class extends torch.nn.modules.module.Module {});
  8901. this.registerType('ultralytics.nn.modules.SPPF', class extends torch.nn.modules.module.Module {});
  8902. this.registerType('ultralytics.nn.modules.CA.CoordAtt', class extends torch.nn.modules.module.Module {});
  8903. this.registerType('ultralytics.nn.modules.CA.h_sigmoid', class extends torch.nn.modules.module.Module {});
  8904. this.registerType('ultralytics.nn.modules.CA.h_swish', class extends torch.nn.modules.module.Module {});
  8905. this.registerType('ultralytics.nn.modules.CoordConv.AddCoords', class extends torch.nn.modules.module.Module {});
  8906. this.registerType('ultralytics.nn.modules.CoordConv.CoordConv', class extends torch.nn.modules.module.Module {});
  8907. this.registerType('ultralytics.nn.modules.ECA.ECA', class extends torch.nn.modules.module.Module {});
  8908. this.registerType('ultralytics.nn.extra_modules.Down_WT.Down_wt', class extends torch.nn.modules.module.Module {});
  8909. this.registerType('ultralytics.nn.extra_modules.prune_module.C3k2_v2', class extends torch.nn.modules.module.Module {});
  8910. this.registerType('ultralytics.nn.tasks.BaseModel', class extends torch.nn.modules.module.Module {});
  8911. this.registerType('ultralytics.nn.tasks.ClassificationModel', class extends torch.nn.modules.module.Module {});
  8912. this.registerType('ultralytics.nn.tasks.DetectionModel', class extends torch.nn.modules.module.Module {});
  8913. this.registerType('ultralytics.nn.tasks.Ensemble', class extends torch.nn.modules.module.Module {});
  8914. this.registerType('ultralytics.nn.tasks.OBBModel', class extends torch.nn.modules.module.Module {});
  8915. this.registerType('ultralytics.nn.tasks.PoseModel', class extends torch.nn.modules.module.Module {});
  8916. this.registerType('ultralytics.nn.tasks.RTDETRDetectionModel', class extends torch.nn.modules.module.Module {});
  8917. this.registerType('ultralytics.nn.tasks.SegmentationModel', class extends torch.nn.modules.module.Module {});
  8918. this.registerType('ultralytics.nn.tasks.WorldModel', class extends torch.nn.modules.module.Module {});
  8919. this.registerType('ultralytics.nn.tasks.YOLOEModel', class extends torch.nn.modules.module.Module {});
  8920. this.registerType('ultralytics.nn.tasks.YOLOESegModel', class extends torch.nn.modules.module.Module {});
  8921. this.registerType('ultralytics.utils.IterableSimpleNamespace', class {});
  8922. this.registerType('ultralytics.utils.loss.BboxLoss', class extends torch.nn.modules.module.Module {});
  8923. this.registerType('ultralytics.utils.loss.DFLoss', class extends torch.nn.modules.module.Module {});
  8924. this.registerType('ultralytics.utils.loss.E2EDetectLoss', class {});
  8925. this.registerType('ultralytics.utils.loss.E2ELoss', class {});
  8926. this.registerType('ultralytics.utils.loss.v8ClassificationLoss', class {});
  8927. this.registerType('ultralytics.utils.loss.v8DetectionLoss', class {});
  8928. this.registerType('ultralytics.utils.loss.v8OBBLoss', class {});
  8929. this.registerType('ultralytics.utils.loss.v8PoseLoss', class {});
  8930. this.registerType('ultralytics.utils.loss.v8SegmentationLoss', class {});
  8931. this.registerType('ultralytics.utils.tal.TaskAlignedAssigner', class extends torch.nn.modules.module.Module {});
  8932. this.registerType('ultralytics.utils.torch_utils.ModelEMA', class {});
  8933. this.registerType('ultralytics.yolo.utils.IterableSimpleNamespace', class {});
  8934. this.registerFunction('builtins.annotate', (type, value) => {
  8935. if (type === builtins.int) {
  8936. return Number.isInteger(value) ? value : NaN;
  8937. }
  8938. if (type === builtins.float) {
  8939. return typeof value === 'number' ? value : NaN;
  8940. }
  8941. if (type === builtins.number) {
  8942. // if (pytorch.Utility.isTensor(value)) {
  8943. // value.resize_([]);
  8944. // }
  8945. }
  8946. return value;
  8947. });
  8948. this.registerFunction('builtins.uninitialized', (/* type */) => {
  8949. return undefined;
  8950. });
  8951. this.registerFunction('builtins.range', (start, stop, step) => {
  8952. if (stop === undefined && step === undefined) {
  8953. if (Number.isInteger(start)) {
  8954. return Array(start).keys();
  8955. }
  8956. if (isNaN(start)) {
  8957. return [];
  8958. }
  8959. }
  8960. if (Number.isInteger(start) && Number.isInteger(stop) && (step === undefined || Number.isInteger(step))) {
  8961. step = step === undefined ? 1 : step;
  8962. const result = [];
  8963. if (step > 0) {
  8964. for (let i = start; i < stop; i += step) {
  8965. result.push(i);
  8966. }
  8967. } else if (step < 0) {
  8968. for (let i = start; i > stop; i += step) {
  8969. result.push(i);
  8970. }
  8971. }
  8972. return result;
  8973. }
  8974. throw new python.Error(`Unsupported range(${JSON.stringify(start)}, ${JSON.stringify(stop)}, ${JSON.stringify(step)})`);
  8975. });
  8976. this.registerFunction('math.trunc');
  8977. builtins.xrange = builtins.range;
  8978. this.registerFunction('torch._C._nn.gelu');
  8979. this.registerFunction('torch._C._nn.avg_pool2d');
  8980. this.registerFunction('torch._C._nn.avg_pool3d');
  8981. this.registerFunction('torch._C._nn.scaled_dot_product_attention');
  8982. this.registerFunction('torch._C._nn.softplus');
  8983. this.registerFunction('torch._native_multi_head_attention');
  8984. this.registerFunction('torch._utils._rebuild_sparse_tensor', (layout, data) => {
  8985. if (layout === torch.sparse_coo) {
  8986. return self.invoke('torch._sparse_coo_tensor_unsafe', data);
  8987. }
  8988. throw new python.Error(`Unsupported sparse tensor layout '${layout ? layout.__str__() : ''}'.`);
  8989. });
  8990. this.registerFunction('torch._utils._get_restore_location', (device) => {
  8991. return device;
  8992. });
  8993. this.registerFunction('torch._utils._rebuild_wrapper_subclass', (cls, dtype, size, stride, storage_offset, layout, device, requires_grad) => {
  8994. device = torch._utils._get_restore_location(device);
  8995. return torch.Tensor._make_wrapper_subclass(cls, size, stride, dtype, storage_offset, layout, device, requires_grad);
  8996. });
  8997. this.registerFunction('torch.from_numpy', (obj) => {
  8998. const dtypes = new Map([
  8999. ['<f2', torch.float16],
  9000. ['<f4', torch.float32],
  9001. ['<f8', torch.float64],
  9002. ['<i2', torch.int16],
  9003. ['<i4', torch.int32],
  9004. ['<i8', torch.int64],
  9005. ]);
  9006. if (!dtypes.has(obj.dtype.str)) {
  9007. throw new python.Error(`Unsupported numpy.ndarray type '${obj.dtype.str}'.`);
  9008. }
  9009. const dtype = dtypes.get(obj.dtype.str);
  9010. const strides = obj.strides.map((stride) => stride / obj.itemsize);
  9011. const storage = new torch.storage.TypedStorage(obj.size, dtype);
  9012. storage._set_cdata(obj.data);
  9013. const tensor = new torch.Tensor();
  9014. tensor.__setstate__([storage, 0, obj.shape, strides]);
  9015. return tensor;
  9016. });
  9017. this.registerFunction('torch._utils._rebuild_device_tensor_from_numpy', (data, dtype, device, requires_grad) => {
  9018. const tensor = torch.from_numpy(data);
  9019. // tensor = tensor.to(dtype, device)
  9020. tensor.requires_grad = requires_grad;
  9021. return tensor;
  9022. });
  9023. this.registerFunction('torch._utils._rebuild_device_tensor_from_cpu_tensor', (data, dtype, device, requires_grad) => {
  9024. data = data.clone();
  9025. data.requires_grad = requires_grad;
  9026. return data;
  9027. });
  9028. this.registerFunction('torch._sparse_coo_tensor_unsafe', (indices, values, size) => {
  9029. const tensor = self.invoke('torch.Tensor', []);
  9030. tensor._layout = torch.sparse_coo;
  9031. tensor._indices = indices;
  9032. tensor._values = values;
  9033. tensor._shape = size;
  9034. return tensor;
  9035. });
  9036. this.registerFunction('torch._utils.set_tensor_metadata', (tensor, metadata) => {
  9037. torch._C._set_tensor_metadata(tensor, metadata);
  9038. });
  9039. this.registerFunction('torch._utils._restore_device_fake_mode', (tensor) => {
  9040. return tensor;
  9041. });
  9042. this.registerFunction('torch._utils._rebuild_meta_tensor_no_storage', (dtype, size, stride, requires_grad) => {
  9043. return torch.empty_strided(size, stride, dtype, null, 'meta', false, requires_grad);
  9044. });
  9045. this.registerFunction('torch._utils._rebuild_tensor', (storage, storage_offset, size, stride) => {
  9046. if (Array.isArray(storage) && storage.length === 5 && storage[0] === 'storage') {
  9047. const [, storage_type, , ,size] = storage;
  9048. storage = new storage_type(size);
  9049. }
  9050. const tensor = new torch.Tensor();
  9051. tensor.__setstate__([storage, storage_offset, size, stride]);
  9052. return tensor;
  9053. });
  9054. this.registerFunction('torch._utils._rebuild_tensor_v2', (storage, storage_offset, size, stride, requires_grad, backward_hooks, metadata) => {
  9055. const tensor = torch._utils._rebuild_tensor(storage, storage_offset, size, stride);
  9056. tensor.requires_grad = requires_grad;
  9057. if (metadata) {
  9058. torch._utils.set_tensor_metadata(tensor, metadata);
  9059. }
  9060. tensor.backward_hooks = backward_hooks;
  9061. return tensor;
  9062. });
  9063. this.registerFunction('torch._utils._rebuild_tensor_v3', (storage, storage_offset, size, stride, requires_grad, backward_hooks, dtype, metadata) => {
  9064. const t = new torch.Tensor(null, null, dtype);
  9065. t.set_(storage, storage_offset, size, stride);
  9066. if (metadata) {
  9067. torch._utils.set_tensor_metadata(t, metadata);
  9068. }
  9069. t._backward_hooks = backward_hooks;
  9070. return torch._utils._restore_device_fake_mode(t);
  9071. });
  9072. this.registerFunction('torch._utils._rebuild_parameter', (data, requires_grad, backward_hooks) => {
  9073. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  9074. param.backward_hooks = backward_hooks;
  9075. return param;
  9076. });
  9077. this.registerFunction('torch._utils._rebuild_parameter_v2', (data, requires_grad, backward_hooks, state) => {
  9078. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  9079. param.backward_hooks = backward_hooks;
  9080. torch._utils._set_obj_state(param, state);
  9081. return param;
  9082. });
  9083. this.registerFunction('torch._utils._rebuild_parameter_with_state', (data, requires_grad, backward_hooks, state) => {
  9084. const _set_obj_state = (obj, state) => {
  9085. const [dict_state, slots_state] = Array.isArray(state) ? state : [state, null];
  9086. if (dict_state) {
  9087. for (const [k, v] of Object.entries(dict_state)) {
  9088. builtins.setattr(obj, k, v);
  9089. }
  9090. }
  9091. if (slots_state) {
  9092. for (const [k, v] of Object.entries(slots_state)) {
  9093. builtins.setattr(obj, k, v);
  9094. }
  9095. }
  9096. };
  9097. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  9098. param._backward_hooks = backward_hooks;
  9099. _set_obj_state(param, state);
  9100. return param;
  9101. });
  9102. this.registerFunction('torch._utils._rebuild_qtensor', (storage, storage_offset, size, stride, quantizer_params, requires_grad, backward_hooks) => {
  9103. const tensor = torch._utils._rebuild_tensor_v2(storage, storage_offset, size, stride, requires_grad, backward_hooks);
  9104. tensor.quantizer_params = quantizer_params;
  9105. return tensor;
  9106. });
  9107. this.registerFunction('torch._utils._set_obj_state', (obj, state) => {
  9108. let dict_state = state;
  9109. let slots_state = null;
  9110. if (state instanceof self.builtins.tuple) {
  9111. if (state.length !== 2) {
  9112. throw new python.Error(`Invalid serialized state: '${state}'.`);
  9113. }
  9114. [dict_state, slots_state] = state;
  9115. }
  9116. if (dict_state) {
  9117. for (const [name, value] of Object.entries(dict_state)) {
  9118. builtins.setattr(obj, name, value);
  9119. }
  9120. }
  9121. if (slots_state) {
  9122. for (const [name, value] of Object.entries(slots_state)) {
  9123. builtins.setattr(obj, name, value);
  9124. }
  9125. }
  9126. return obj;
  9127. });
  9128. this.registerFunction('torch._set_item', (dict, key, value) => {
  9129. dict[key] = value;
  9130. });
  9131. this.registerFunction('torch._tensor._rebuild_from_type_v2', (func, new_type, args, state) => {
  9132. let ret = func(...args);
  9133. if (ret.__class__ !== new_type) {
  9134. // ret = ret.as_subclass(new_type);
  9135. }
  9136. const setstate = builtins.getattr(ret.__class__, '__setstate__', torch.Tensor.__setstate__);
  9137. if (setstate === torch.Tensor.__setstate__) {
  9138. ret = torch._utils._set_obj_state(ret, state);
  9139. } else {
  9140. ret.__setstate__(state);
  9141. }
  9142. return ret;
  9143. });
  9144. this.registerFunction('torch.__range_length', (lo, hi, step) => {
  9145. if (step === 0) {
  9146. throw new python.Error('range() arg 3 must not be zero');
  9147. }
  9148. if (step > 0 && lo < hi) {
  9149. return 1 + (hi - 1 - lo) / step;
  9150. } else if (step < 0 && lo > hi) {
  9151. return 1 + (lo - 1 - hi) / (0 - step);
  9152. }
  9153. return 0;
  9154. });
  9155. this.registerFunction('torch._nested_tensor_from_mask_left_aligned');
  9156. this.registerOperator('aten::_unwrap_optional', (value) => {
  9157. return value;
  9158. });
  9159. this.registerFunction('torch.get_default_dtype', () => {
  9160. torch._default_type = torch._default_type || torch.float32;
  9161. return torch._default_type;
  9162. });
  9163. this.registerFunction('torch.set_default_dtype', (value) => {
  9164. torch._default_type = value;
  9165. });
  9166. this.registerFunction('torch._prims_common.dtype_or_default', (value) => {
  9167. return value || torch.get_default_dtype();
  9168. });
  9169. this.registerFunction('torch.empty_strided', (size, stride, dtype, layout, device, pin_memory, requires_grad) => {
  9170. const shape = size;
  9171. dtype = torch._prims_common.dtype_or_default(dtype);
  9172. let storage = null;
  9173. if (size.every((d) => d instanceof torch.SymInt === false)) {
  9174. const size = shape.reduce((a, b) => a * b, 1);
  9175. storage = new torch.storage.TypedStorage(size, dtype);
  9176. }
  9177. const tensor = new torch.Tensor(storage, shape, dtype, layout, device, requires_grad);
  9178. tensor.__setstate__([storage, 0, shape, stride]);
  9179. return tensor;
  9180. });
  9181. this.registerFunction('torch.all', (input) => {
  9182. if (Array.isArray(input) && input.length === 0) {
  9183. return true;
  9184. }
  9185. throw new python.Error(`Unsupported 'torch.all' expression type.`);
  9186. });
  9187. this.registerFunction('torch.append', (list, value) => {
  9188. list.push(value);
  9189. return value;
  9190. });
  9191. this.registerFunction('torch.clear', (value) => {
  9192. if (value instanceof torch.Value) {
  9193. throw new python.Error('Invalid value.');
  9194. }
  9195. if (Object(value) === value) {
  9196. for (const key of Object.keys(value)) {
  9197. delete value[key];
  9198. }
  9199. }
  9200. });
  9201. this.registerFunction('torch.dict', (args) => {
  9202. const obj = {};
  9203. if (args) {
  9204. if (Array.isArray(args)) {
  9205. for (const [key, value] of args) {
  9206. obj[key] = value;
  9207. }
  9208. } else {
  9209. throw new python.Error("'torch.dict' arguments not supported.");
  9210. }
  9211. }
  9212. return obj;
  9213. });
  9214. this.registerOperator('aten::cosine_similarity', () => {
  9215. throw new python.Error(`'aten::cosine_similarity' not implemented.`);
  9216. });
  9217. this.registerOperator('aten::extend', (list, value) => {
  9218. list.push(...value);
  9219. });
  9220. this.registerOperator('aten::insert', (list, index, value) => {
  9221. list.splice(index, 0, value);
  9222. return value;
  9223. });
  9224. this.registerOperator('aten::replace', (value, oldvalue, newvalue /*, max */) => {
  9225. return value.replace(oldvalue, newvalue);
  9226. });
  9227. this.registerOperator('aten::add', (a, b) => {
  9228. if ((typeof a === 'number' || a instanceof Number) && (typeof b === 'number' || b instanceof Number)) {
  9229. return a + b;
  9230. }
  9231. if (typeof a === 'number' && b instanceof builtins.complex) {
  9232. return new builtins.complex(a + b.real, b.imag);
  9233. }
  9234. if (a instanceof builtins.complex && typeof b === 'number') {
  9235. return new builtins.complex(a.real + b, a.imag);
  9236. }
  9237. if (a instanceof builtins.complex && b instanceof builtins.complex) {
  9238. return new builtins.complex(a.real + b.real, a.imag + b.imag);
  9239. }
  9240. if (Array.isArray(a) && Array.isArray(b)) {
  9241. return a.concat(b);
  9242. }
  9243. if (typeof a === 'string' && typeof b === 'string') {
  9244. return a + b;
  9245. }
  9246. throw new python.Error('Unsupported aten::add expression type.');
  9247. });
  9248. this.registerOperator('aten::log', (x) => {
  9249. if (typeof x === 'number' || x instanceof Number) {
  9250. return Math.log(x);
  9251. }
  9252. throw new python.Error('Unsupported aten::log expression type.');
  9253. });
  9254. this.registerOperator('aten::dim', (tensor) => {
  9255. if (tensor && tensor.size) {
  9256. const size = tensor.size();
  9257. if (size) {
  9258. return size.length;
  9259. }
  9260. }
  9261. return NaN;
  9262. });
  9263. this.registerOperator('aten::numel', (tensor) => {
  9264. if (tensor && tensor.size) {
  9265. const size = tensor.size();
  9266. if (size) {
  9267. return size.reduce((a, b) => a * b, 1);
  9268. }
  9269. }
  9270. return NaN;
  9271. });
  9272. this.registerOperator('aten::eq', (left, right) => {
  9273. if (typeof left === 'string' && typeof right === 'string') {
  9274. return left === right;
  9275. }
  9276. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9277. if (isNaN(left) && isNaN(right)) {
  9278. return true;
  9279. }
  9280. return left === right;
  9281. }
  9282. if (left === undefined || right === undefined) {
  9283. return true;
  9284. }
  9285. if (Array.isArray(left) && Array.isArray(right)) {
  9286. return left.length === right.length && left.every((item, index) => item === right[index]);
  9287. }
  9288. throw new python.Error("Unsupported 'torch.eq' expression type.");
  9289. });
  9290. this.registerOperator('aten::floor', (value) => {
  9291. return Math.floor(value);
  9292. });
  9293. this.registerOperator('aten::ceil', (value) => {
  9294. return Math.ceil(value);
  9295. });
  9296. this.registerOperator('aten::floordiv', (left, right) => {
  9297. return Math.floor(left / right);
  9298. });
  9299. this.registerOperator('aten::format', (...args) => {
  9300. const list = args.shift().split(/({}D?)/);
  9301. return list.map((text) => {
  9302. if (text === '{}' || text === '{}D') {
  9303. const arg = args.shift();
  9304. if (Array.isArray(arg)) {
  9305. return `[${arg.map((item) => item.toString()).join(', ')}]`;
  9306. }
  9307. return arg ? arg.toString() : '?';
  9308. }
  9309. return text;
  9310. }).join('');
  9311. });
  9312. this.registerOperator('aten::strip', (self, chars) => {
  9313. chars = chars || '\\n\\t\\f\\v';
  9314. const regex = new RegExp(`[${chars}]`, 'g');
  9315. return self.replace(regex, '');
  9316. });
  9317. this.registerOperator('aten::gt', (left, right) => {
  9318. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9319. if (!isNaN(left) && !isNaN(right)) {
  9320. return left > right;
  9321. }
  9322. }
  9323. if (isNaN(left) && !isNaN(right)) {
  9324. return true;
  9325. }
  9326. throw new python.Error("Unsupported 'ops.aten.gt' expression type.");
  9327. });
  9328. this.registerOperator('aten::ge', (left, right) => {
  9329. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9330. if (!isNaN(left) && !isNaN(right)) {
  9331. return left > right;
  9332. }
  9333. }
  9334. if (isNaN(left) && !isNaN(right)) {
  9335. return true;
  9336. }
  9337. throw new python.Error("Unsupported 'ops.aten.ge' expression type.");
  9338. });
  9339. this.registerOperator('aten::is_floating_point', (tensor) => {
  9340. const type = tensor.dtype.scalar_type();
  9341. return (type === 5 || type === 6 || type === 7);
  9342. });
  9343. this.registerOperator('aten::is_grad_enabled', () => {
  9344. return false;
  9345. });
  9346. this.registerOperator('aten::is_autocast_enabled', () => {
  9347. return false;
  9348. });
  9349. this.registerOperator('aten::isfinite');
  9350. this.registerOperator('aten::set_grad_enabled', (/* value */) => {
  9351. });
  9352. this.registerFunction('torch.serialization._get_layout', (name) => {
  9353. const value = name.startsWith('torch.') ? torch[name.split('.')[1]] : null;
  9354. return value instanceof torch.layout ? value : null;
  9355. });
  9356. this.registerFunction('torch.storage._load_from_bytes', (b) => {
  9357. return torch.load(b);
  9358. });
  9359. this.registerFunction('torch.jit._pickle.build_boollist', (data) => {
  9360. return data;
  9361. });
  9362. this.registerFunction('torch.jit._pickle.build_doublelist', (data) => {
  9363. return data;
  9364. });
  9365. this.registerFunction('torch.jit._pickle.build_intlist', (data) => {
  9366. return data;
  9367. });
  9368. this.registerFunction('torch.jit._pickle.build_tensorlist', (data) => {
  9369. return data;
  9370. });
  9371. this.registerFunction('torch.jit._pickle.build_tensor_from_id', (data) => {
  9372. return self.builtins.CONSTANTS[`c${data}`];
  9373. });
  9374. this.registerFunction('torch.jit._pickle.restore_type_tag', (value /*, type_str */) => {
  9375. return value;
  9376. });
  9377. this.registerOperator('aten::keys', (dict) => {
  9378. return Object.keys(dict);
  9379. });
  9380. this.registerOperator('aten::len', (value) => {
  9381. if (Array.isArray(value)) {
  9382. return value.length;
  9383. }
  9384. if (value && value.shape && value.__len__) {
  9385. return value.__len__();
  9386. }
  9387. return NaN;
  9388. });
  9389. this.registerOperator('aten::le', (left, right) => {
  9390. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9391. if (isNaN(left) || isNaN(right)) {
  9392. return false;
  9393. }
  9394. return left <= right;
  9395. }
  9396. if (left === undefined || right === undefined) {
  9397. return true;
  9398. }
  9399. throw new python.Error("Unsupported 'torch.le' expression type.");
  9400. });
  9401. this.registerOperator('aten::list', (args) => {
  9402. return args;
  9403. });
  9404. this.registerOperator('aten::list_with_default', (size /*, defaults */) => {
  9405. return size;
  9406. });
  9407. this.registerType('torch.PyTorchFileReader', class {
  9408. constructor(entries) {
  9409. let prefix = 0;
  9410. const paths = Array.from(entries.keys()).map((path) => path.replace(/\\/g, '/').split('/').reverse());
  9411. for (let set = new Set(); set && paths.length > 0;) {
  9412. set = new Set(paths.map((path) => path.length > 1 ? path.pop() : null));
  9413. set = set.size > 1 || set.keys().next().value === null ? null : set;
  9414. prefix += set ? set.keys().next().value.length + 1 : 0;
  9415. }
  9416. this._records = new Map(Array.from(entries).map(([name, value]) => [name.substring(prefix), value]));
  9417. this._version = 0;
  9418. this.init();
  9419. }
  9420. init() {
  9421. let stream = null;
  9422. if (this.has_record('.data/version')) {
  9423. stream = this.get_record('.data/version');
  9424. } else if (this.has_record('version')) {
  9425. stream = this.get_record('version');
  9426. }
  9427. if (stream) {
  9428. const decoder = new TextDecoder('utf-8');
  9429. const buffer = stream.peek();
  9430. const text = decoder.decode(buffer);
  9431. this._version = Number(text.split('\n').shift().trim());
  9432. }
  9433. }
  9434. has_record(name) {
  9435. return this._records.has(name);
  9436. }
  9437. get_record(name) {
  9438. if (!this.has_record(name)) {
  9439. throw new python.Error(`Record '${name}' not found.`);
  9440. }
  9441. return this._records.get(name);
  9442. }
  9443. get_all_records() {
  9444. return Array.from(this._records.keys());
  9445. }
  9446. version() {
  9447. return this._version;
  9448. }
  9449. });
  9450. this.registerFunction('torch.load', (f) => {
  9451. const legacy_load = (entries) => {
  9452. const deserialized_objects = {};
  9453. if (entries.has('storages')) {
  9454. const data = entries.get('storages');
  9455. const unpickler = new pickle.Unpickler(data);
  9456. const num_storages = unpickler.load();
  9457. for (let i = 0; i < num_storages; i++) {
  9458. const args = unpickler.load();
  9459. const [key, , storage_type] = args;
  9460. const obj = storage_type._new_with_file(unpickler);
  9461. deserialized_objects[key] = obj;
  9462. }
  9463. /*
  9464. let storage_views = unpickler.load();
  9465. for target_cdata, root_cdata, offset, size in storage_views:
  9466. root = deserialized_objects[root_cdata]
  9467. deserialized_objects[target_cdata] = root[offset:offset + size]
  9468. */
  9469. }
  9470. if (entries.has('tensors')) {
  9471. const data = entries.get('tensors');
  9472. const unpickler = new pickle.Unpickler(data);
  9473. const num_tensors = unpickler.load();
  9474. const int32 = (unpickler) => {
  9475. const buffer = unpickler.read(4);
  9476. return buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24);
  9477. };
  9478. const int64 = (unpickler) => {
  9479. const buffer = unpickler.read(8);
  9480. if (buffer[6] !== 0 && buffer[7] !== 0) {
  9481. throw new python.Error('Unsigned 64-bit value exceeds 32-bit range.');
  9482. }
  9483. return buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24) + (buffer[4] * 4294967296) + (buffer[5] * 1099511627776);
  9484. };
  9485. for (let i = 0; i < num_tensors; i++) {
  9486. const args = unpickler.load();
  9487. const [key, storage_id] = args;
  9488. const storage = deserialized_objects[storage_id];
  9489. const ndim = int32(unpickler);
  9490. unpickler.read(4);
  9491. const shape = Array.from(new Array(ndim)).map(() => int64(unpickler));
  9492. const stride = Array.from(new Array(ndim)).map(() => int64(unpickler));
  9493. const storage_offset = int64(unpickler);
  9494. const tensor = torch._utils._rebuild_tensor(storage, storage_offset, shape, stride);
  9495. deserialized_objects[key] = tensor;
  9496. }
  9497. }
  9498. const data = entries.get('pickle');
  9499. const unpickler = new pickle.Unpickler(data);
  9500. unpickler.persistent_load = (saved_id) => deserialized_objects[saved_id];
  9501. return unpickler.load();
  9502. };
  9503. const _legacy_load = () => {
  9504. const unpickler = new pickle.Unpickler(f);
  9505. unpickler.load(); // magic_number
  9506. const protocol_version = unpickler.load();
  9507. if (protocol_version !== 1001) {
  9508. throw new python.Error(`Unsupported protocol version '${protocol_version}'.`);
  9509. }
  9510. const sys_info = unpickler.load();
  9511. if (sys_info.get('protocol_version') !== 1001) {
  9512. throw new python.Error(`Unsupported protocol version '${sys_info.protocol_version}'.`);
  9513. }
  9514. if (sys_info.get('little_endian') === false) {
  9515. throw new python.Error("Unsupported big-endian storage data.");
  9516. }
  9517. const module_source_map = new Map();
  9518. const deserialized_objects = new Map();
  9519. unpickler.persistent_load = (saved_id) => {
  9520. switch (saved_id[0]) {
  9521. case 'module': {
  9522. const [, module, ,source] = saved_id;
  9523. module_source_map.set(module, source);
  9524. return saved_id[1];
  9525. }
  9526. case 'storage': {
  9527. const [, storage_type, key, , size, view_metadata] = saved_id;
  9528. if (!deserialized_objects.has(key)) {
  9529. const obj = new storage_type(size);
  9530. deserialized_objects.set(key, obj);
  9531. }
  9532. if (view_metadata) {
  9533. const view_key = view_metadata.shift();
  9534. view_metadata.shift(); // view_offset
  9535. view_metadata.shift(); // view_size
  9536. if (!deserialized_objects.has(view_key)) {
  9537. const view = null; // storage.slice(view_offset, view_offset + view_size);
  9538. deserialized_objects.set(view_key, view);
  9539. }
  9540. return deserialized_objects.get(view_key);
  9541. }
  9542. return deserialized_objects.get(key);
  9543. }
  9544. default: {
  9545. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  9546. }
  9547. }
  9548. };
  9549. const obj = unpickler.load();
  9550. const deserialized_storage_keys = unpickler.load();
  9551. for (const deserialized_storage_key of deserialized_storage_keys) {
  9552. const storage = deserialized_objects.get(deserialized_storage_key);
  9553. storage._set_from_file(unpickler);
  9554. }
  9555. if (!obj) {
  9556. throw new python.Error('File format is not PyTorch.');
  9557. }
  9558. if (obj === 'None') {
  9559. throw new python.Error("File contains 'None' root object.");
  9560. }
  9561. return obj;
  9562. };
  9563. const _load = (entries) => {
  9564. if (f.has('constant.pkl')) {
  9565. throw python.Error("TorchScript 'torch.load' not supported.");
  9566. }
  9567. const loaded_storages = new Map();
  9568. const persistent_load = (saved_id) => {
  9569. switch (saved_id[0]) {
  9570. case 'storage': {
  9571. const [, storage_type, key, , numel] = saved_id;
  9572. if (!loaded_storages.has(key)) {
  9573. const storage = new storage_type(numel);
  9574. if (!storage._set_cdata) {
  9575. throw new python.Error(`'${storage_type.__name__}._set_cdata' is not a function.`);
  9576. }
  9577. const name = `data/${key}`;
  9578. const stream = entries.get(name);
  9579. if (!stream) {
  9580. throw new python.Error(`Record '${name}' not found.`);
  9581. }
  9582. storage._set_cdata(stream);
  9583. loaded_storages.set(key, storage);
  9584. }
  9585. return loaded_storages.get(key);
  9586. }
  9587. default: {
  9588. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  9589. }
  9590. }
  9591. };
  9592. const data_file = entries.get('data.pkl');
  9593. const unpickler = new pickle.Unpickler(data_file);
  9594. unpickler.persistent_load = persistent_load;
  9595. const result = unpickler.load();
  9596. return result;
  9597. };
  9598. if (f instanceof Map) {
  9599. const reader = new torch.PyTorchFileReader(f);
  9600. const records = reader.get_all_records().map((name) => [name, reader.get_record(name)]);
  9601. f = new Map(records);
  9602. if (f.has('pickle')) {
  9603. return legacy_load(f);
  9604. }
  9605. if (f.has('data.pkl')) {
  9606. return _load(f);
  9607. }
  9608. throw new python.Error(`Unsupported 'torch.load' input '${JSON.stringify(Array.from(f.keys()))}'.`);
  9609. }
  9610. return _legacy_load(f);
  9611. });
  9612. this.registerOperator('prim::abs', (a) => {
  9613. if (typeof a === 'number' || a instanceof Number) {
  9614. return Math.abs(a);
  9615. }
  9616. if (a instanceof builtins.complex) {
  9617. return Math.hypot(a.real, a.imag);
  9618. }
  9619. throw new python.Error('Unsupported prim::abs expression type.');
  9620. });
  9621. this.registerOperator('prim::unchecked_cast', (type, value) => {
  9622. return value;
  9623. });
  9624. this.registerOperator('prim::data', (tensor) => {
  9625. return tensor;
  9626. });
  9627. this.registerOperator('prim::device', (tensor) => {
  9628. return tensor.device;
  9629. });
  9630. this.registerOperator('prim::dtype', (tensor) => {
  9631. return tensor.dtype.scalar_type();
  9632. });
  9633. this.registerOperator('prim::is_quantized', (tensor) => {
  9634. return tensor.is_quantized;
  9635. });
  9636. this.registerOperator('prim::is_cuda', (/* tensor */) => {
  9637. return false;
  9638. });
  9639. this.registerOperator('prim::is_nested', (tensor) => {
  9640. return tensor.is_nested;
  9641. });
  9642. this.registerOperator('prim::is_sparse', (tensor) => {
  9643. return tensor.is_sparse;
  9644. });
  9645. this.registerOperator('prim::unchecked_unwrap_optional', (value) => {
  9646. return value;
  9647. });
  9648. this.registerOperator('prim::NumToTensor', (value) => {
  9649. const tensor = self.invoke('torch.Tensor', []);
  9650. tensor.value = value;
  9651. return tensor;
  9652. });
  9653. this.registerOperator('prim::min', (...args) => {
  9654. if (Array.isArray(args[0])) {
  9655. return Math.min.apply(null, args[0]);
  9656. }
  9657. return Math.min.apply(null, args);
  9658. });
  9659. this.registerOperator('prim::max', (...args) => {
  9660. if (Array.isArray(args[0])) {
  9661. return Math.max.apply(null, args[0]);
  9662. }
  9663. return Math.max.apply(null, args);
  9664. });
  9665. this.registerOperator('prim::shape', (tensor) => {
  9666. return tensor && tensor.size ? tensor.size() : undefined;
  9667. });
  9668. this.registerOperator('quantized::conv_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9669. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9670. params.weight = weight;
  9671. params.bias = bias;
  9672. params.stride = stride;
  9673. params.padding = padding;
  9674. params.dilation = dilation;
  9675. params.groups = groups;
  9676. return params;
  9677. });
  9678. this.registerOperator('quantized::conv1d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9679. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9680. params.weight = weight;
  9681. params.bias = bias;
  9682. params.stride = stride;
  9683. params.padding = padding;
  9684. params.dilation = dilation;
  9685. params.groups = groups;
  9686. return params;
  9687. });
  9688. this.registerOperator('quantized::conv2d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9689. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9690. params.weight = weight;
  9691. params.bias = bias;
  9692. params.stride = stride;
  9693. params.padding = padding;
  9694. params.dilation = dilation;
  9695. params.groups = groups;
  9696. return params;
  9697. });
  9698. this.registerOperator('quantized::conv3d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9699. const params = self.invoke('__torch__.torch.classes.quantized.Conv3dPackedParamsBase', []);
  9700. params.weight = weight;
  9701. params.bias = bias;
  9702. params.stride = stride;
  9703. params.padding = padding;
  9704. params.dilation = dilation;
  9705. params.groups = groups;
  9706. return params;
  9707. });
  9708. this.registerOperator('quantized::conv_transpose1d_prepack', (weight, bias, stride, padding, output_padding, dilation, groups) => {
  9709. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9710. params.weight = weight;
  9711. params.bias = bias;
  9712. params.stride = stride;
  9713. params.padding = padding;
  9714. params.output_padding = output_padding;
  9715. params.dilation = dilation;
  9716. params.groups = groups;
  9717. return params;
  9718. });
  9719. this.registerOperator('quantized::conv_transpose2d_prepack', (weight, bias, stride, padding, output_padding, dilation, groups) => {
  9720. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9721. params.weight = weight;
  9722. params.bias = bias;
  9723. params.stride = stride;
  9724. params.padding = padding;
  9725. params.output_padding = output_padding;
  9726. params.dilation = dilation;
  9727. params.groups = groups;
  9728. return params;
  9729. });
  9730. this.registerOperator('quantized::linear_prepack', (weight, bias) => {
  9731. const params = self.invoke('__torch__.torch.classes.quantized.LinearPackedParamsBase', []);
  9732. params.weight = weight;
  9733. params.bias = bias;
  9734. return params;
  9735. });
  9736. this.registerOperator('prim::RaiseException', (message) => {
  9737. throw new python.Error(message);
  9738. });
  9739. this.registerOperator('prim::TupleIndex', (t, i) => {
  9740. return t.elements()[i];
  9741. });
  9742. this.registerOperator('prim::TupleUnpack', (t) => {
  9743. return t.elements();
  9744. });
  9745. this.registerOperator('aten::is_scripting', () => {
  9746. return true;
  9747. });
  9748. this.registerOperator('aten::__and__', (left, right) => {
  9749. return left && right;
  9750. });
  9751. this.registerOperator('aten::__contains__', (dict, key) => {
  9752. return builtins.hasattr(dict, key);
  9753. });
  9754. this.registerFunction('torch.__derive_index', (index, start, step) => {
  9755. return start + index * step;
  9756. });
  9757. this.registerOperator('aten::__is__', (left, right) => {
  9758. return left === right;
  9759. });
  9760. this.registerOperator('aten::__isnot__', (left, right) => {
  9761. return left !== right;
  9762. });
  9763. this.registerOperator('aten::__not__', (value) => {
  9764. if (Number.isInteger(value)) {
  9765. value = Boolean(value);
  9766. }
  9767. if (typeof value === 'boolean') {
  9768. return !value;
  9769. }
  9770. throw new python.Error("Unsupported 'ops.aten.__not__' expression type.");
  9771. });
  9772. this.registerOperator('aten::log10', (value) => {
  9773. return Math.log10(value);
  9774. });
  9775. this.registerOperator('aten::device', (type, index) => {
  9776. return new torch.device(type, index);
  9777. });
  9778. this.registerOperator('aten::lt', (left, right) => {
  9779. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9780. return left < right;
  9781. }
  9782. throw new python.Error("Unsupported 'ops.aten.lt' expression type.");
  9783. });
  9784. this.registerOperator('aten::mul', (left, right) => {
  9785. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9786. return left * right;
  9787. }
  9788. if (isNaN(left) || isNaN(right)) {
  9789. return NaN;
  9790. }
  9791. if (Array.isArray(left) && left.every((value) => typeof value === 'number' || value instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9792. return left.map((value) => value * right);
  9793. }
  9794. throw new python.Error("Unsupported 'ops.aten.mul' expression type.");
  9795. });
  9796. this.registerOperator('aten::div', (left, right) => {
  9797. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9798. return left / right;
  9799. }
  9800. if (isNaN(left) || isNaN(right)) {
  9801. return NaN;
  9802. }
  9803. throw new python.Error("Unsupported 'ops.aten.div' expression type.");
  9804. });
  9805. this.registerFunction('torch.round', (value) => {
  9806. if (typeof value === 'number' || value instanceof Number) {
  9807. return Math.round(value);
  9808. }
  9809. if (isNaN(value)) {
  9810. return value;
  9811. }
  9812. throw new python.Error("Unsupported 'torch.round' expression type.");
  9813. });
  9814. this.registerOperator('aten::remainder', (left, right) => {
  9815. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9816. return left % right;
  9817. }
  9818. if (isNaN(left) || isNaN(right)) {
  9819. return NaN;
  9820. }
  9821. throw new python.Error("Unsupported 'ops.aten.remainder' expression type.");
  9822. });
  9823. this.registerOperator('aten::ne', (left, right) => {
  9824. if (typeof left === 'boolean' && typeof right === 'boolean') {
  9825. return left !== right;
  9826. }
  9827. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9828. if (isNaN(left) || isNaN(right)) {
  9829. return false;
  9830. }
  9831. return left !== right;
  9832. }
  9833. if (Array.isArray(left) && Array.isArray(right) && left.length === right.length) {
  9834. return false;
  9835. }
  9836. if (typeof left === 'string' && typeof right === 'string') {
  9837. return left !== right;
  9838. }
  9839. if (left === undefined || right === undefined) {
  9840. return true;
  9841. }
  9842. throw new python.Error("Unsupported 'ops.aten.ne' expression type.");
  9843. });
  9844. this.registerOperator('aten::neg', (value) => {
  9845. if (typeof value === 'number') {
  9846. return -value;
  9847. }
  9848. throw new python.Error("Unsupported 'ops.aten.neg' expression type.");
  9849. });
  9850. this.registerOperator('aten::pow', (left, right) => {
  9851. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9852. return Math.pow(left, right);
  9853. }
  9854. throw new python.Error("Unsupported 'ops.aten.pow' expression type.");
  9855. });
  9856. this.registerFunction('torch.q_scale', (/* tensor */) => {
  9857. return -1;
  9858. });
  9859. this.registerFunction('torch.t', (tensor) => {
  9860. return tensor;
  9861. });
  9862. this.registerOperator('aten::size', (tensor, dim) => {
  9863. if (tensor && tensor.size) {
  9864. const size = tensor.size();
  9865. if (Array.isArray(size)) {
  9866. if (dim === undefined) {
  9867. return size;
  9868. }
  9869. if (Number.isInteger(dim)) {
  9870. if (dim >= 0 && dim < size.length) {
  9871. return size[dim];
  9872. }
  9873. if (dim < 0 && -dim < size.length) {
  9874. return size[size.length + dim];
  9875. }
  9876. }
  9877. throw new python.Error(`Dimension out of range (expected to be in range of ${JSON.stringify(size)}, but got ${JSON.stringify(dim)}).`);
  9878. }
  9879. }
  9880. if (Number.isInteger(dim)) {
  9881. return NaN;
  9882. }
  9883. return [];
  9884. });
  9885. this.registerFunction('aten::sqrt', (x) => {
  9886. return Math.sqrt(x);
  9887. });
  9888. this.registerOperator('aten::slice', (l, start, end, step) => {
  9889. if (!Array.isArray(l)) {
  9890. throw new python.Error('Slicing expected array');
  9891. }
  9892. step = step || 1;
  9893. if (step !== 1) {
  9894. throw new python.Error('Slicing only supports step=1');
  9895. }
  9896. start = Math.max(0, start >= 0 ? start : l.length + start);
  9897. end = Math.min(l.length, end || Number.MAX_SAFE_INTEGER);
  9898. return l.slice(start, end);
  9899. });
  9900. this.registerOperator('aten::sub', (left, right) => {
  9901. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9902. return left - right;
  9903. }
  9904. if (typeof left === 'number' && right instanceof builtins.complex) {
  9905. return new builtins.complex(left - right.real, right.imag);
  9906. }
  9907. if (left instanceof builtins.complex && typeof right === 'number') {
  9908. return new builtins.complex(left.real - right, left.imag);
  9909. }
  9910. if (left instanceof builtins.complex && right instanceof builtins.complex) {
  9911. return new builtins.complex(left.real - right.real, left.imag - right.imag);
  9912. }
  9913. throw new python.Error("Unsupported 'torch.sub' expression type.");
  9914. });
  9915. this.registerFunction('torch.sym_int');
  9916. this.registerFunction('torch.sym_float');
  9917. this.registerFunction('torch.sym_ite');
  9918. this.registerFunction('torch.sym_max');
  9919. this.registerFunction('torch.sym_min');
  9920. this.registerFunction('torch.sym_not');
  9921. this.registerFunction('torch.sym_sqrt');
  9922. this.registerFunction('torch.sym_sqrt');
  9923. this.registerFunction('torch.functional.einsum');
  9924. this.registerFunction('torch.functional.norm');
  9925. this.registerFunction('torch.functional.split');
  9926. this.registerFunction('torch.nn.init.constant_');
  9927. this.registerFunction('torch.nn.init.normal_');
  9928. this.registerFunction('torch.nn.init.xavier_uniform_');
  9929. this.registerFunction('torch.nn.functional.adaptive_avg_pool2d');
  9930. this.registerFunction('torch.nn.functional.binary_cross_entropy');
  9931. this.registerFunction('torch.nn.functional.binary_cross_entropy_with_logits');
  9932. this.registerFunction('torch.nn.functional.cross_entropy');
  9933. this.registerFunction('torch.nn.functional.elu');
  9934. this.registerFunction('torch.nn.functional.gelu');
  9935. this.registerFunction('torch.nn.functional.hardsigmoid');
  9936. this.registerFunction('torch.nn.functional.hardswish');
  9937. this.registerFunction('torch.nn.functional.hardtanh');
  9938. this.registerFunction('torch.nn.functional.interpolate');
  9939. this.registerFunction('torch.nn.functional.leaky_relu');
  9940. this.registerFunction('torch.nn.functional.l1_loss');
  9941. this.registerFunction('torch.nn.functional.linear');
  9942. this.registerFunction('torch.nn.functional.log_softmax');
  9943. this.registerFunction('torch.nn.functional._max_pool2d');
  9944. this.registerFunction('torch.nn.functional.max_pool2d_with_indices');
  9945. this.registerFunction('torch.nn.functional.mse_loss');
  9946. this.registerFunction('torch.nn.functional.pad');
  9947. this.registerFunction('torch.nn.functional.relu');
  9948. this.registerFunction('torch.nn.functional.relu6');
  9949. this.registerFunction('torch.nn.functional.sigmoid');
  9950. this.registerFunction('torch.nn.functional.silu');
  9951. this.registerFunction('torch.nn.functional.softmax');
  9952. this.registerFunction('torch.nn.functional.tanh');
  9953. this.registerFunction('torch.values', (dict) => {
  9954. return Object.values(dict);
  9955. });
  9956. this.registerFunction('torch.warn', () => {
  9957. });
  9958. this.registerType('torch._ops.OperatorBase', class {
  9959. constructor() {
  9960. this.functorch_table = {};
  9961. }
  9962. });
  9963. this.registerType('torch._ops.HigherOrderOperator', class extends torch._ops.OperatorBase {
  9964. constructor(name, cacheable) {
  9965. super();
  9966. this._name = name;
  9967. this.__name__ = name;
  9968. this._ns = 'higher_order';
  9969. this.__module__ = 'torch.ops.higher_order';
  9970. this._cacheable = cacheable;
  9971. }
  9972. get namespace() {
  9973. return this._ns;
  9974. }
  9975. get name() {
  9976. return this._name;
  9977. }
  9978. });
  9979. this.registerType('torch._higher_order_ops.wrap.WrapWithAutocast', class extends torch._ops.HigherOrderOperator {
  9980. constructor(name) {
  9981. super(name, false);
  9982. this._schema = torch.FunctionSchema.parse('higher_order::wrap_with_autocast(str device_type, ScalarType? dtype, bool enabled, bool? cache_enabled, Any wrapped_func, ...) -> Tensor');
  9983. }
  9984. });
  9985. torch.ops.higher_order.wrap_with_autocast = new torch._higher_order_ops.wrap.WrapWithAutocast('wrap_with_autocast');
  9986. this.registerType('torch._higher_order_ops.wrap.WrapWithSetGradEnabled', class extends torch._ops.HigherOrderOperator {
  9987. constructor(name) {
  9988. super(name, false);
  9989. this._schema = torch.FunctionSchema.parse('higher_order::wrap_with_set_grad_enabled(bool enable_grad, Any wrapped_func) -> Tensor');
  9990. }
  9991. });
  9992. torch.ops.higher_order.wrap_with_set_grad_enabled = new torch._higher_order_ops.wrap.WrapWithSetGradEnabled('wrap_with_set_grad_enabled');
  9993. this.registerType('torch._higher_order_ops.wrap.Wrap', class extends torch._ops.HigherOrderOperator {
  9994. constructor(name) {
  9995. super(name, false);
  9996. this._schema = torch.FunctionSchema.parse('higher_order::wrap(Any func) -> Tensor');
  9997. }
  9998. });
  9999. torch.ops.higher_order.wrap = new torch._higher_order_ops.wrap.Wrap('wrap');
  10000. this.registerType('torch._higher_order_ops.wrap.WrapActivationCheckpoint', class extends torch._ops.HigherOrderOperator {
  10001. constructor(name) {
  10002. super(name, false);
  10003. }
  10004. });
  10005. torch.ops.higher_order.wrap_activation_checkpoint = new torch._higher_order_ops.wrap.WrapActivationCheckpoint('wrap_activation_checkpoint', false);
  10006. this.registerType('torch._higher_order_ops.wrap.TagActivationCheckpoint', class extends torch._ops.HigherOrderOperator {
  10007. constructor(name) {
  10008. super(name, false);
  10009. }
  10010. });
  10011. torch.ops.higher_order.tag_activation_checkpoint = new torch._higher_order_ops.wrap.TagActivationCheckpoint('tag_activation_checkpoint', false);
  10012. this.registerType('torch.Type', class {
  10013. constructor(kind, annotation_str) {
  10014. this._kind = kind;
  10015. if (annotation_str) {
  10016. this._annotation_str = annotation_str;
  10017. }
  10018. }
  10019. static get(kind, annotation_str) {
  10020. torch.Type.cache = torch.Type.cache || new Map();
  10021. if (!annotation_str) {
  10022. if (!torch.Type.cache.has(kind)) {
  10023. torch.Type.cache.set(kind, new torch.Type(kind));
  10024. }
  10025. return torch.Type.cache.get(kind);
  10026. }
  10027. return new torch.Type(kind, annotation_str);
  10028. }
  10029. kind() {
  10030. return this._kind;
  10031. }
  10032. get annotation_str() {
  10033. return this._annotation_str;
  10034. }
  10035. equals(rhs) {
  10036. return this.kind() === rhs.kind();
  10037. }
  10038. isSubtypeOf(rhs) {
  10039. if (rhs.kind() === 'AnyType' || this === rhs) {
  10040. return true;
  10041. }
  10042. if (rhs instanceof torch.OptionalType && this instanceof torch.OptionalType === false) {
  10043. return this.isSubtypeOf(rhs.getElementType());
  10044. }
  10045. if (rhs instanceof torch.UnionType) {
  10046. return rhs.containedTypes().some((inner) => this.isSubtypeOf(inner));
  10047. }
  10048. if (rhs instanceof torch._C.DynamicType) {
  10049. return torch._C.DynamicType.create(this).isSubtypeOf(rhs);
  10050. }
  10051. return this.equals(rhs);
  10052. }
  10053. containedTypes() {
  10054. return [];
  10055. }
  10056. containedType(i) {
  10057. return this.containedTypes()[i];
  10058. }
  10059. withContained(contained_types) {
  10060. const current_contained = this.containedTypes();
  10061. torch._C.TORCH_INTERNAL_ASSERT(current_contained.length > 0 && current_contained.length === contained_types.length);
  10062. if (current_contained.length === contained_types.length && current_contained.every((x, index) => x === contained_types[index])) {
  10063. return this;
  10064. }
  10065. return this.createWithContained(contained_types);
  10066. }
  10067. createWithContained(/* createWithContained */) {
  10068. throw new python.Error('Not implemented.');
  10069. }
  10070. isUnionType() {
  10071. return false;
  10072. }
  10073. hasFreeVariables() {
  10074. return false;
  10075. }
  10076. is_module() {
  10077. return false;
  10078. }
  10079. expect(type) {
  10080. torch._C.AT_ASSERT(this instanceof type);
  10081. return this;
  10082. }
  10083. str() {
  10084. if (this instanceof torch._C.VarType && this._annotation_str) {
  10085. return this._annotation_str;
  10086. } else if (this._kind === 'ScalarTypeType') {
  10087. return 'ScalarType';
  10088. } else if (this._kind === 'QSchemeType') {
  10089. return 'QScheme';
  10090. } else if (this._kind) {
  10091. return this._kind;
  10092. }
  10093. throw new python.Error(`Not implemented '${this.kind()}'.`);
  10094. }
  10095. __str__() {
  10096. return this.str();
  10097. }
  10098. toString() {
  10099. return this.__str__();
  10100. }
  10101. });
  10102. this.registerType('torch.ClassType', class extends torch.Type {
  10103. constructor(qualified_name, cu, is_module) {
  10104. super('ClassType', typeof qualified_name === 'string' ? qualified_name : qualified_name.qualifiedName());
  10105. this._name = typeof qualified_name === 'string' ? new torch._C.QualifiedName(qualified_name) : qualified_name;
  10106. this._is_module = is_module;
  10107. this._attributes = [];
  10108. this._attributeTypes = [];
  10109. this._methods = [];
  10110. this._staticmethods = new Map();
  10111. this._forward_hooks = [];
  10112. this._forward_pre_hooks = [];
  10113. this._properties = [];
  10114. this._constants = new Map();
  10115. }
  10116. static create(qualifiedName, cu, is_module /*, doc_string, unresolved_class_attributes */) {
  10117. return new torch.ClassType(qualifiedName, cu, is_module);
  10118. }
  10119. qualified_name() {
  10120. return this.annotation_str;
  10121. }
  10122. name() {
  10123. return this._name;
  10124. }
  10125. is_module() {
  10126. return this._is_module;
  10127. }
  10128. is_parameter(slot) {
  10129. return this._attributes[slot].is_parameter === true;
  10130. }
  10131. is_buffer(slot) {
  10132. return this._attributes[slot].is_buffer === true;
  10133. }
  10134. addMethod(method) {
  10135. torch._C.TORCH_CHECK(this.findMethod(method.name()) === null);
  10136. this._methods.push(method);
  10137. }
  10138. findMethod(name) {
  10139. for (const method of this._methods) {
  10140. if (name === method.name()) {
  10141. return method;
  10142. }
  10143. }
  10144. return null;
  10145. }
  10146. getMethod(name) {
  10147. const method = this.findMethod(name);
  10148. if (!method) {
  10149. throw new python.Error(`Method '${name}' not found on class '${this.str()}.`);
  10150. }
  10151. return method;
  10152. }
  10153. methods() {
  10154. return this._methods;
  10155. }
  10156. addStaticMethod(func) {
  10157. this._staticmethods.set(func.name, func);
  10158. }
  10159. findStaticMethod(name) {
  10160. return this._staticmethods.get(name);
  10161. }
  10162. findHook(name) {
  10163. let hook = this.findForwardHook(name);
  10164. if (hook === null) {
  10165. hook = this.findForwardPreHook(name);
  10166. }
  10167. return hook;
  10168. }
  10169. findForwardHook(name) {
  10170. for (const hook of this._forward_hooks) {
  10171. if (name === hook.name()) {
  10172. return hook;
  10173. }
  10174. }
  10175. return null;
  10176. }
  10177. findForwardPreHook(name) {
  10178. for (const pre_hook of this._forward_pre_hooks) {
  10179. if (name === pre_hook.name()) {
  10180. return pre_hook;
  10181. }
  10182. }
  10183. return null;
  10184. }
  10185. numAttributes() {
  10186. return this._attributes.length;
  10187. }
  10188. addAttribute(name, type, is_parameter, is_buffer) {
  10189. is_parameter = is_parameter || false;
  10190. is_buffer = is_buffer || false;
  10191. const slot = this._attributes.length;
  10192. this._attributes.push({ name, type, is_parameter, is_buffer });
  10193. this._attributeTypes.push(type);
  10194. return slot;
  10195. }
  10196. addOrCheckAttribute(name, ty, is_parameter, is_buffer) {
  10197. is_parameter = is_parameter || false;
  10198. is_buffer = is_buffer || false;
  10199. const slot_idx = this.findAttributeSlot(name);
  10200. if (slot_idx === null) {
  10201. return this.addAttribute(name, ty, is_parameter, is_buffer);
  10202. }
  10203. // TORCH_CHECK(is_parameter == this.is_parameter(*slot_idx), "Parameter field mismatch for the field '", name, "'");
  10204. // const TypePtr& atype = getAttribute(*slot_idx);
  10205. // TORCH_CHECK(ty.isSubtypeOf(*atype), ty.repr_str(), " is not compatible with the type ", atype.repr_str(), " for the field '", name, "'");
  10206. return slot_idx;
  10207. }
  10208. findAttributeSlot(name) {
  10209. for (let pos = 0; pos < this._attributes.length; pos++) {
  10210. if (name === this._attributes[pos].name) {
  10211. return pos;
  10212. }
  10213. }
  10214. return null;
  10215. }
  10216. findAttribute(name) {
  10217. const slot = this.findAttributeSlot(name);
  10218. if (slot !== null) {
  10219. return this._attributes[slot].type;
  10220. }
  10221. return null;
  10222. }
  10223. hasAttribute(name) {
  10224. return this._attributes.find((attr) => attr.name === name);
  10225. }
  10226. getAttribute(arg) {
  10227. const slot = Number.isInteger(arg) ? arg : this.findAttributeSlot(arg);
  10228. return this._attributes[slot].type;
  10229. }
  10230. getAttributeName(slot) {
  10231. return this._attributes[slot].name;
  10232. }
  10233. addConstant(name, value) {
  10234. this._constants.set(name, value);
  10235. }
  10236. hasConstant(name) {
  10237. return this._constants.has(name);
  10238. }
  10239. getProperty(name) {
  10240. for (const prop of this._properties) {
  10241. if (name === prop.name) {
  10242. return prop;
  10243. }
  10244. }
  10245. return null;
  10246. }
  10247. containedTypes() {
  10248. return this._attributeTypes;
  10249. }
  10250. createWithContained(contained_types) {
  10251. const ptr = torch.ClassType.create(this.name(), this._compilation_unit, this.is_module());
  10252. torch._C.AT_ASSERT(this.numAttributes() === contained_types.length);
  10253. for (let i = 0; i < this._attributes.length; i++) {
  10254. torch._C.AT_ASSERT(this._attributes[i].type.isSubtypeOf(contained_types[i]));
  10255. ptr.addAttribute(this._attributes[i].name, contained_types[i]);
  10256. }
  10257. for (const method of this.methods()) {
  10258. ptr.addMethod(method);
  10259. }
  10260. return ptr;
  10261. }
  10262. str() {
  10263. return this.qualified_name();
  10264. }
  10265. });
  10266. this.registerType('torch.EnumType', class extends torch.Type {
  10267. constructor(qualified_class_name, value_type, enum_names_values, cu) {
  10268. super('EnumType', qualified_class_name);
  10269. this._name = qualified_class_name;
  10270. this._value_type = value_type;
  10271. this._enum_names_values = enum_names_values;
  10272. this._cu = cu;
  10273. }
  10274. static create(qualified_class_name, value, enum_names_values, cu) {
  10275. if (value instanceof torch.IntType || value instanceof torch.FloatType || value instanceof torch.StringType) {
  10276. return new torch.EnumType(qualified_class_name, value, enum_names_values, cu);
  10277. }
  10278. torch._C.TORCH_CHECK(false);
  10279. return null;
  10280. }
  10281. name() {
  10282. return this._name;
  10283. }
  10284. get annotation_str() {
  10285. return this._name.qualifiedName();
  10286. }
  10287. enumNamesValues() {
  10288. return this._enum_names_values;
  10289. }
  10290. compilation_unit() {
  10291. return this._cu;
  10292. }
  10293. getValueType() {
  10294. return this._value_type;
  10295. }
  10296. equals(rhs) {
  10297. if (rhs instanceof torch.EnumType) {
  10298. return this.name() && this.name() === rhs.name() && this.getValueType() === rhs.getValueType() && this.compilation_unit() === rhs.compilation_unit();
  10299. }
  10300. return false;
  10301. }
  10302. isSubtypeOf(rhs) {
  10303. if (rhs instanceof torch.AnyType || rhs.kind() === 'AnyEnumType' || this === rhs) {
  10304. return true;
  10305. }
  10306. return super.isSubtypeOf(rhs);
  10307. }
  10308. });
  10309. this.registerFunction('torch._C.standardizeVectorForUnion', (...args) => {
  10310. if (args.length === 1) {
  10311. const [to_flatten] = args;
  10312. torch._C.TORCH_INTERNAL_ASSERT(to_flatten !== null);
  10313. const to_fill = [];
  10314. torch._C.standardizeVectorForUnion(to_flatten, to_fill);
  10315. to_flatten.splice(0, to_flatten.length);
  10316. to_flatten.push(...to_fill);
  10317. } else if (args.length === 2) {
  10318. const [reference, to_fill] = args;
  10319. for (const type of reference) {
  10320. torch._C.flattenUnion(type, to_fill);
  10321. }
  10322. torch._C.filterDuplicateSubtypes(to_fill);
  10323. torch._C.sortUnion(to_fill);
  10324. } else {
  10325. throw new python.Error('Not implemented.');
  10326. }
  10327. });
  10328. this.registerFunction('torch._C.flattenUnion', (type, to_fill) => {
  10329. if (type instanceof torch.UnionType) {
  10330. for (const inner of type.containedTypes()) {
  10331. torch._C.flattenUnion(inner, to_fill);
  10332. }
  10333. } else if (type instanceof torch.OptionalType) {
  10334. const inner = type.getElementType();
  10335. torch._C.flattenUnion(inner, to_fill);
  10336. to_fill.push(torch.NoneType.get());
  10337. } else if (type instanceof torch.NumberType) {
  10338. to_fill.push(torch.IntType.get());
  10339. to_fill.push(torch.FloatType.get());
  10340. to_fill.push(torch.ComplexType.get());
  10341. } else {
  10342. to_fill.push(type);
  10343. }
  10344. });
  10345. this.registerFunction('torch._C.filterDuplicateSubtypes', (types) => {
  10346. if (types.length === 0) {
  10347. // return;
  10348. }
  10349. /*
  10350. const get_supertype = [](const TypePtr& t1, const TypePtr& t2) -> std::optional<TypePtr> {
  10351. // We don't want nested Optionals. Also, prematurely unifying to
  10352. // `Optional` could prevent us from coalescing other types
  10353. if ((t1->isSubtypeOf(*NoneType::get()) && !t2->isSubtypeOf(*NoneType::get()))
  10354. || (!t1->isSubtypeOf(*NoneType::get()) && t2->isSubtypeOf(*NoneType::get()))) {
  10355. return null;
  10356. } else {
  10357. return unifyTypes(t1, t2, default_to_union=false);
  10358. }
  10359. };
  10360. size_t end_idx = types->size()-1;
  10361. for (size_t i = types->size()-1; i > 0; --i) {
  10362. for (size_t j = std::min(i-1, end_idx); ; --j) {
  10363. std::optional<TypePtr> unified;
  10364. unified = get_supertype((*types)[i], (*types)[j]);
  10365. if (unified) {
  10366. (*types)[j] = *unified;
  10367. (*types)[i] = (*types)[end_idx];
  10368. --end_idx;
  10369. break;
  10370. }
  10371. if (j == 0) {
  10372. break;
  10373. }
  10374. }
  10375. }
  10376. types.erase(types->begin() + static_cast<std::ptrdiff_t>(end_idx) + 1, types->end());
  10377. */
  10378. });
  10379. this.registerFunction('torch._C.sortUnion', (/* types */) => {
  10380. /*
  10381. std::sort(types->begin(), types->end(),
  10382. [](const TypePtr& a, const TypePtr& b) -> bool {
  10383. if (a->kind() != b->kind()) {
  10384. return a->kind() < b->kind();
  10385. }
  10386. return a->str() < b->str();
  10387. });
  10388. */
  10389. });
  10390. this.registerType('torch.UnionType', class extends torch.Type {
  10391. constructor(reference, kind) {
  10392. super(kind || 'UnionType');
  10393. torch._C.TORCH_INTERNAL_ASSERT(reference.length > 0);
  10394. this._types = [];
  10395. torch._C.standardizeVectorForUnion(reference, this._types);
  10396. if (this._types.length === 1) {
  10397. throw new python.Error('Invalid union type reference.');
  10398. }
  10399. this._can_hold_none = false;
  10400. this._has_free_variables = false;
  10401. for (const type of this._types) {
  10402. if (type instanceof torch.NoneType) {
  10403. this._can_hold_none = true;
  10404. }
  10405. if (type.hasFreeVariables()) {
  10406. this._has_free_variables = true;
  10407. }
  10408. }
  10409. }
  10410. static create(reference) {
  10411. const union_type = new torch.UnionType(reference);
  10412. /*
  10413. bool int_found = false;
  10414. bool float_found = false;
  10415. bool complex_found = false;
  10416. bool nonetype_found = false;
  10417. const update_is_opt_flags = [&](const TypePtr& t) {
  10418. if (t == IntType::get()) {
  10419. int_found = true;
  10420. } else if (t == FloatType::get()) {
  10421. float_found = true;
  10422. } else if (t == ComplexType::get()) {
  10423. complex_found = true;
  10424. } else if (t == NoneType::get()) {
  10425. nonetype_found = true;
  10426. }
  10427. };
  10428. for (const auto& t : union_type->containedTypes()) {
  10429. update_is_opt_flags(t);
  10430. }
  10431. bool numbertype_found = int_found && float_found && complex_found;
  10432. if (nonetype_found) {
  10433. if (union_type->containedTypes().size() == 4 && numbertype_found) {
  10434. return OptionalType::create(NumberType::get());
  10435. }
  10436. if (union_type->containedTypes().size() == 2) {
  10437. const not_none = union_type->containedTypes()[0] != NoneType::get()
  10438. ? union_type->containedTypes()[0]
  10439. : union_type->containedTypes()[1];
  10440. return OptionalType::create(not_none);
  10441. }
  10442. }
  10443. */
  10444. return union_type;
  10445. }
  10446. containedTypes() {
  10447. return this._types;
  10448. }
  10449. isUnionType() {
  10450. return true;
  10451. }
  10452. hasFreeVariables() {
  10453. return this._has_free_variables;
  10454. }
  10455. equals(rhs) {
  10456. if (rhs instanceof torch.UnionType) {
  10457. if (rhs.containedTypes().length !== this.containedTypes().length) {
  10458. return false;
  10459. }
  10460. return this.containedTypes().every((lhs_type) => rhs.containedTypes().some((rhs_type) => lhs_type === rhs_type));
  10461. } else if (rhs instanceof torch.OptionalType) {
  10462. if (rhs.getElementType() === torch.NumberType.get()) {
  10463. return this.containedTypes().length === 4 && this._can_hold_none && this.canHoldType(torch.NumberType.get());
  10464. }
  10465. const optional_lhs = this.toOptional();
  10466. return optional_lhs && rhs === optional_lhs.expect(torch.OptionalType);
  10467. } else if (rhs instanceof torch.NumberType) {
  10468. return this.containedTypes().length === 3 && this.canHoldType(torch.NumberType.get());
  10469. }
  10470. return false;
  10471. }
  10472. isSubtypeOf(rhs) {
  10473. const rhs_types = [];
  10474. if (rhs instanceof torch.UnionType) {
  10475. if (this.containedTypes() === rhs.containedTypes()) {
  10476. return true;
  10477. }
  10478. for (const typePtr of rhs.containedTypes()) {
  10479. rhs_types.push(typePtr);
  10480. }
  10481. } else if (rhs instanceof torch.OptionalType) {
  10482. rhs_types.push(torch.NoneType.get());
  10483. if (rhs.getElementType() === torch.NumberType.get()) {
  10484. const number_types = [torch.IntType.get(), torch.FloatType.get(), torch.ComplexType.get()];
  10485. rhs_types.push(...number_types);
  10486. } else {
  10487. rhs_types.push(rhs.getElementType());
  10488. }
  10489. } else if (rhs instanceof torch.NumberType) {
  10490. const number_types = [torch.IntType.get(), torch.FloatType.get(), torch.ComplexType.get()];
  10491. rhs_types.push(...number_types);
  10492. } else {
  10493. rhs_types.push(rhs);
  10494. }
  10495. return this.containedTypes().every((lhs_type) => rhs_types.some((rhs_type) => lhs_type.isSubtypeOf(rhs_type)));
  10496. }
  10497. });
  10498. this.registerType('torch.OptionalType', class extends torch.UnionType {
  10499. constructor(contained) {
  10500. super([contained, torch.NoneType.get()], 'OptionalType');
  10501. let is_numbertype = false;
  10502. if (contained instanceof torch.UnionType) {
  10503. is_numbertype = contained.containedTypes().length === 3 && contained.canHoldType(torch.NumberType.get());
  10504. }
  10505. if (super.containedTypes().length === 2) {
  10506. this._contained = super.containedTypes()[0] instanceof torch.NoneType ? super.containedTypes()[1] : super.containedTypes()[0];
  10507. } else if (contained === torch.NumberType.get() || is_numbertype) {
  10508. this._contained = torch.NumberType.get();
  10509. this._types.splice(0, this._types.length);
  10510. this._types.push(torch.NumberType.get());
  10511. this._types.push(torch.NoneType.get());
  10512. } else {
  10513. const to_subtract = [torch.NoneType.get()];
  10514. const without_none = this.subtractTypeSetFrom(to_subtract, this._types);
  10515. this._contained = torch.UnionType.create([without_none]);
  10516. }
  10517. this._has_free_variables = contained.hasFreeVariables();
  10518. }
  10519. static create(elem) {
  10520. return new torch.OptionalType(elem);
  10521. }
  10522. getElementType() {
  10523. return this._contained;
  10524. }
  10525. equals(rhs) {
  10526. return this.kind() === rhs.kind() && this.getElementType().equals(rhs.getElementType());
  10527. }
  10528. isSubtypeOf(rhs) {
  10529. if (rhs instanceof torch.OptionalType) {
  10530. return this.getElementType().isSubtypeOf(rhs.getElementType());
  10531. } else if (rhs instanceof torch.UnionType) {
  10532. throw new python.Error('Not implemented.');
  10533. }
  10534. // return super.isSubtypeOf(rhs);
  10535. return torch.Type.prototype.isSubtypeOf.call(this, rhs);
  10536. }
  10537. containedTypes() {
  10538. return [this._contained];
  10539. }
  10540. createWithContained(contained_types) {
  10541. torch._C.AT_ASSERT(contained_types.length === 1);
  10542. return torch.OptionalType.create(contained_types[0]);
  10543. }
  10544. subtractTypeSetFrom(to_subtract, from) {
  10545. const types = [];
  10546. const should_subtract = (lhs) => to_subtract.some((rhs) => lhs.isSubtypeOf(rhs));
  10547. for (const t of from) {
  10548. if (!should_subtract(t)) {
  10549. types.push(t);
  10550. }
  10551. }
  10552. if (types.length === 0) {
  10553. return null;
  10554. } else if (types.length === 1) {
  10555. return types[0];
  10556. }
  10557. return torch.UnionType.create(types);
  10558. }
  10559. str() {
  10560. return `${this.getElementType().str()}?`;
  10561. }
  10562. __str__() {
  10563. return `Optional[${this.getElementType().__str__()}]`;
  10564. }
  10565. });
  10566. this.registerType('torch.ListType', class extends torch.Type {
  10567. constructor(elem) {
  10568. super('ListType');
  10569. this._elem = elem;
  10570. }
  10571. static create(elem) {
  10572. return new torch.ListType(elem);
  10573. }
  10574. getElementType() {
  10575. return this._elem;
  10576. }
  10577. equals(rhs) {
  10578. if (rhs instanceof torch.ListType) {
  10579. return this.getElementType().equals(rhs.getElementType());
  10580. }
  10581. return false;
  10582. }
  10583. isSubtypeOf(rhs) {
  10584. if (super.isSubtypeOf(rhs)) {
  10585. return true;
  10586. }
  10587. if (rhs.kind() === 'AnyListType') {
  10588. return true;
  10589. }
  10590. return false;
  10591. }
  10592. containedTypes() {
  10593. return [this._elem];
  10594. }
  10595. createWithContained(contained_types) {
  10596. return new torch.ListType(contained_types[0]);
  10597. }
  10598. hasFreeVariables() {
  10599. return this.getElementType().hasFreeVariables();
  10600. }
  10601. str() {
  10602. return `${this.getElementType().str()}[]`;
  10603. }
  10604. __str__() {
  10605. return `List[${this.getElementType().__str__()}]`;
  10606. }
  10607. });
  10608. this.registerType('torch.FutureType', class extends torch.Type {
  10609. constructor(elem) {
  10610. super('FutureType');
  10611. this._elem = elem;
  10612. }
  10613. static create(elem) {
  10614. return new torch.FutureType(elem);
  10615. }
  10616. getElementType() {
  10617. return this._elem;
  10618. }
  10619. containedTypes() {
  10620. throw new python.Error('Not implemented.');
  10621. }
  10622. str() {
  10623. return `Future(${this.getElementType().str()})`;
  10624. }
  10625. __str__() {
  10626. return `Future[${this.getElementType().__str__()}]`;
  10627. }
  10628. });
  10629. this.registerType('torch.RRefType', class extends torch.Type {
  10630. constructor(elem) {
  10631. super('RRefType');
  10632. this._elem = elem;
  10633. }
  10634. static create(elem) {
  10635. return new torch.RRefType(elem);
  10636. }
  10637. getElementType() {
  10638. return this._elem;
  10639. }
  10640. containedTypes() {
  10641. throw new python.Error('Not implemented.');
  10642. }
  10643. str() {
  10644. return `RRef(${this.getElementType().str()})`;
  10645. }
  10646. __str__() {
  10647. return `RRef[${this.getElementType().__str__()}]`;
  10648. }
  10649. });
  10650. this.registerType('torch.AwaitType', class extends torch.Type {
  10651. constructor(elem) {
  10652. super('AwaitType');
  10653. this._elem = elem;
  10654. }
  10655. static get(elem) {
  10656. return new torch.AwaitType(elem);
  10657. }
  10658. getElementType() {
  10659. return this._elem;
  10660. }
  10661. containedTypes() {
  10662. throw new python.Error('Not implemented.');
  10663. }
  10664. str() {
  10665. return `Await(${this.getElementType().str()})`;
  10666. }
  10667. __str__() {
  10668. return `Await[${this.getElementType().__str__()}]`;
  10669. }
  10670. });
  10671. this.registerType('torch.TupleType', class extends torch.Type {
  10672. constructor(elements, annotation_str, schema) {
  10673. super('TupleType', annotation_str);
  10674. this._elements = elements;
  10675. this._has_free_variables = elements.some((v) => {
  10676. if (!v) {
  10677. throw new python.Error('Can not create tuple with None type');
  10678. }
  10679. return v.hasFreeVariables();
  10680. });
  10681. this._schema = schema;
  10682. }
  10683. static create(elements) {
  10684. return new torch.TupleType(elements, null, null);
  10685. }
  10686. static createNamed(qualified_name, field_names, field_types /*, field_defaults */) {
  10687. const args = [];
  10688. for (let i = 0; i < field_names.length; i++) {
  10689. const arg = new torch.Argument(field_names[i], field_types[i], field_types[i]);
  10690. args.push(arg);
  10691. }
  10692. const schema = new torch.FunctionSchema(qualified_name, '', args, []);
  10693. return new torch.TupleType(field_types, qualified_name, schema);
  10694. }
  10695. elements() {
  10696. return this._elements;
  10697. }
  10698. name() {
  10699. return this.annotation_str;
  10700. }
  10701. containedTypes() {
  10702. return this._elements;
  10703. }
  10704. createWithContained(createWithContained) {
  10705. return new torch.TupleType(createWithContained, this.name(), this.schema());
  10706. }
  10707. hasFreeVariables() {
  10708. return this._has_free_variables;
  10709. }
  10710. schema() {
  10711. return this._schema;
  10712. }
  10713. str() {
  10714. if (this._schema) {
  10715. return `NamedTuple(...)`;
  10716. }
  10717. return `(${this.elements().map((elem) => elem.str()).join(', ')})`;
  10718. }
  10719. __str__() {
  10720. if (this.annotation_str) {
  10721. return this.annotation_str;
  10722. }
  10723. return `Tuple[${this.elements().map((elem) => elem.__str__()).join(', ')}]`;
  10724. }
  10725. });
  10726. this.registerType('torch.AnyType', class extends torch.Type {
  10727. constructor() {
  10728. super('AnyType');
  10729. }
  10730. static get() {
  10731. torch.AnyType.value = torch.AnyType.value || new torch.AnyType();
  10732. return torch.AnyType.value;
  10733. }
  10734. str() {
  10735. return 'Any';
  10736. }
  10737. __str__() {
  10738. return 'Any';
  10739. }
  10740. });
  10741. this.registerType('torch.NoneType', class extends torch.Type {
  10742. constructor() {
  10743. super('NoneType');
  10744. }
  10745. static get() {
  10746. torch.NoneType.value = torch.NoneType.value || new torch.NoneType();
  10747. return torch.NoneType.value;
  10748. }
  10749. equals(rhs) {
  10750. return this.kind() === rhs.kind();
  10751. }
  10752. isSubtypeOf(rhs) {
  10753. if (rhs.kind() === 'OptionalType') {
  10754. return true;
  10755. }
  10756. return super.isSubtypeOf(rhs);
  10757. }
  10758. str() {
  10759. return 'NoneType';
  10760. }
  10761. __str__() {
  10762. return 'NoneType';
  10763. }
  10764. });
  10765. this.registerType('torch.TensorType', class extends torch.Type {
  10766. constructor() {
  10767. super('TensorType');
  10768. this._is_inferred = false;
  10769. }
  10770. static get() {
  10771. torch.TensorType.value = torch.TensorType.value || new torch.TensorType();
  10772. return torch.TensorType.value;
  10773. }
  10774. equals(rhs) {
  10775. return this.kind() === rhs.kind();
  10776. }
  10777. isInferredType() {
  10778. return this._is_inferred;
  10779. }
  10780. str() {
  10781. return 'Tensor';
  10782. }
  10783. __str__() {
  10784. return 'Tensor';
  10785. }
  10786. });
  10787. this.registerType('torch.NumberType', class extends torch.Type {
  10788. constructor() {
  10789. super('NumberType');
  10790. }
  10791. static get() {
  10792. torch.NumberType.value = torch.NumberType.value || new torch.NumberType();
  10793. return torch.NumberType.value;
  10794. }
  10795. str() {
  10796. return 'Scalar';
  10797. }
  10798. __str__() {
  10799. return 'number';
  10800. }
  10801. });
  10802. this.registerType('torch.BoolType', class extends torch.Type {
  10803. constructor() {
  10804. super('BoolType');
  10805. }
  10806. static get() {
  10807. torch.BoolType.value = torch.BoolType.value || new torch.BoolType();
  10808. return torch.BoolType.value;
  10809. }
  10810. equals(rhs) {
  10811. return this.kind() === rhs.kind();
  10812. }
  10813. str() {
  10814. return 'bool';
  10815. }
  10816. __str__() {
  10817. return 'bool';
  10818. }
  10819. });
  10820. this.registerType('torch.IntType', class extends torch.Type {
  10821. constructor() {
  10822. super('IntType');
  10823. }
  10824. static get() {
  10825. torch.IntType.value = torch.IntType.value || new torch.IntType();
  10826. return torch.IntType.value;
  10827. }
  10828. equals(rhs) {
  10829. return this.kind() === rhs.kind();
  10830. }
  10831. isSubtypeOf(rhs) {
  10832. return rhs instanceof torch.NumberType || rhs instanceof torch.FloatType || super.isSubtypeOf(rhs);
  10833. }
  10834. str() {
  10835. return 'int';
  10836. }
  10837. __str__() {
  10838. return 'int';
  10839. }
  10840. });
  10841. this.registerType('torch.SymIntType', class extends torch.Type {
  10842. constructor() {
  10843. super('SymIntType');
  10844. }
  10845. static get() {
  10846. torch.SymIntType.value = torch.SymIntType.value || new torch.SymIntType();
  10847. return torch.SymIntType.value;
  10848. }
  10849. equals(rhs) {
  10850. return this.kind() === rhs.kind();
  10851. }
  10852. str() {
  10853. return 'SymInt';
  10854. }
  10855. __str__() {
  10856. return 'int';
  10857. }
  10858. });
  10859. this.registerType('torch.FloatType', class extends torch.Type {
  10860. constructor() {
  10861. super('FloatType');
  10862. }
  10863. static get() {
  10864. torch.FloatType.value = torch.FloatType.value || new torch.FloatType();
  10865. return torch.FloatType.value;
  10866. }
  10867. equals(rhs) {
  10868. return this.kind() === rhs.kind();
  10869. }
  10870. isSubtypeOf(rhs) {
  10871. return rhs.kind() === 'NumberType' || super.isSubtypeOf(rhs);
  10872. }
  10873. str() {
  10874. return 'float';
  10875. }
  10876. __str__() {
  10877. return 'float';
  10878. }
  10879. });
  10880. this.registerType('torch.StringType', class extends torch.Type {
  10881. constructor() {
  10882. super('StringType');
  10883. }
  10884. static get() {
  10885. torch.StringType.value = torch.StringType.value || new torch.StringType();
  10886. return torch.StringType.value;
  10887. }
  10888. equals(rhs) {
  10889. return this.kind() === rhs.kind();
  10890. }
  10891. str() {
  10892. return 'str';
  10893. }
  10894. __str__() {
  10895. return 'str';
  10896. }
  10897. });
  10898. this.registerType('torch.ComplexType', class extends torch.Type {
  10899. constructor() {
  10900. super('ComplexType');
  10901. }
  10902. static get() {
  10903. torch.ComplexType.value = torch.ComplexType.value || new torch.ComplexType();
  10904. return torch.ComplexType.value;
  10905. }
  10906. equals(rhs) {
  10907. return this.kind() === rhs.kind();
  10908. }
  10909. isSubtypeOf(rhs) {
  10910. return rhs.kind() === 'NumberType' || super.isSubtypeOf(rhs);
  10911. }
  10912. str() {
  10913. return 'complex';
  10914. }
  10915. __str__() {
  10916. return 'complex';
  10917. }
  10918. });
  10919. this.registerType('torch.DictType', class extends torch.Type {
  10920. constructor(key, value) {
  10921. super('DictType');
  10922. this.types = [key, value];
  10923. }
  10924. static create(key, value) {
  10925. let kind = key.kind();
  10926. if (key instanceof torch._C.DynamicType) {
  10927. kind = key.dynamicKind();
  10928. }
  10929. switch (kind) {
  10930. case 'AnyType':
  10931. case 'IntType':
  10932. case 'BoolType':
  10933. case 'FloatType':
  10934. case 'ComplexType':
  10935. case 'StringType':
  10936. case 'TensorType':
  10937. case 'DeviceObjType':
  10938. return new torch.DictType(key, value);
  10939. default:
  10940. throw new python.Error(`Invalid dict key type '${kind}'.`);
  10941. }
  10942. }
  10943. createWithContained(contained_types) {
  10944. if (contained_types.length !== 2) {
  10945. throw new python.Error('Expected 2 contained types.');
  10946. }
  10947. return torch.DictType.create(contained_types[0], contained_types[1]);
  10948. }
  10949. getKeyType() {
  10950. return this.types[0];
  10951. }
  10952. getValueType() {
  10953. return this.types[1];
  10954. }
  10955. hasFreeVariables() {
  10956. return this.getKeyType().hasFreeVariables() || this.getValueType().hasFreeVariables();
  10957. }
  10958. containedTypes() {
  10959. return this.types;
  10960. }
  10961. equals(rhs) {
  10962. if (rhs instanceof torch.DictType) {
  10963. return this.getKeyType().equals(rhs.getKeyType()) && this.getValueType().equals(rhs.getValueType());
  10964. }
  10965. return false;
  10966. }
  10967. str() {
  10968. return `Dict(${this.getKeyType().str()}, ${this.getValueType().str()})`;
  10969. }
  10970. __str__() {
  10971. return `Dict(${this.getKeyType().__str__()}, ${this.getValueType().__str__()})`;
  10972. }
  10973. });
  10974. this.registerType('torch.DeviceObjType', class extends torch.Type {
  10975. constructor() {
  10976. super('DeviceObjType');
  10977. }
  10978. static get() {
  10979. torch.DeviceObjType.value ||= new torch.DeviceObjType();
  10980. return torch.DeviceObjType.value;
  10981. }
  10982. str() {
  10983. return 'Device';
  10984. }
  10985. __str__() {
  10986. return 'Device';
  10987. }
  10988. });
  10989. this.registerType('torch.StreamObjType', class extends torch.Type {
  10990. constructor() {
  10991. super('StreamObjType');
  10992. }
  10993. str() {
  10994. return 'Stream';
  10995. }
  10996. __str__() {
  10997. return 'Stream';
  10998. }
  10999. });
  11000. this.registerType('torch._C._GeneratorType', class extends torch.Type {
  11001. constructor() {
  11002. super('GeneratorType');
  11003. }
  11004. static get() {
  11005. torch._C._GeneratorType.value = torch._C._GeneratorType.value || new torch._C._GeneratorType();
  11006. return torch._C._GeneratorType.value;
  11007. }
  11008. str() {
  11009. return 'Generator';
  11010. }
  11011. __str__() {
  11012. return 'Generator';
  11013. }
  11014. });
  11015. this.registerType('torch.InterfaceType', class extends torch.Type {
  11016. constructor() {
  11017. super('InterfaceType');
  11018. }
  11019. });
  11020. this.registerType('torch._C.DynamicType', class extends torch.Type {
  11021. constructor() {
  11022. super('DynamicType');
  11023. }
  11024. });
  11025. this.registerType('torch._C.FunctionType', class extends torch.Type {
  11026. constructor(func) {
  11027. super('FunctionType');
  11028. this._func = func;
  11029. }
  11030. static create(func) {
  11031. return new torch._C.FunctionType(func);
  11032. }
  11033. function() {
  11034. return this._func;
  11035. }
  11036. });
  11037. this.registerType('torch._C.VarType', class extends torch.Type {
  11038. constructor(name) {
  11039. super('VarType', name);
  11040. }
  11041. static create(name) {
  11042. return new torch._C.VarType(name);
  11043. }
  11044. name() {
  11045. return this._annotation_str;
  11046. }
  11047. hasFreeVariables() {
  11048. return true;
  11049. }
  11050. });
  11051. this.registerType('torch._C.AliasInfo', class {
  11052. constructor() {
  11053. this.is_write = false;
  11054. this.before_set = [];
  11055. this.after_set = [];
  11056. this.containedTypes = [];
  11057. }
  11058. addBeforeSet(value) {
  11059. this.before_set.push(value);
  11060. }
  11061. addAfterSet(value) {
  11062. this.after_set.push(value);
  11063. }
  11064. addContainedType(alias_info) {
  11065. this.containedTypes.push(alias_info);
  11066. }
  11067. str() {
  11068. const list = ['('];
  11069. list.push(this.before_set.join('|'));
  11070. if (this.after_set.length > 0) {
  11071. list.push(' -> ');
  11072. list.push(this.after_set.join('|'));
  11073. }
  11074. if (this.is_write) {
  11075. list.push('!');
  11076. }
  11077. list.push(')');
  11078. return list.join('');
  11079. }
  11080. });
  11081. this.registerFunction('torch._C.parseStringLiteral', (range, str) => {
  11082. if (str.startsWith('"') && str.endsWith('"')) {
  11083. return str.slice(1, -1);
  11084. }
  11085. if (str.startsWith("'") && str.endsWith("'")) {
  11086. return str.slice(1, -1);
  11087. }
  11088. throw new python.Error(`Invalid string literal '${str}'.`);
  11089. // inline std::string parseStringLiteral(
  11090. });
  11091. this.registerType('torch._C.Token', class {
  11092. constructor() {
  11093. this.kind = '';
  11094. this.value = '';
  11095. }
  11096. text() {
  11097. return this.value;
  11098. }
  11099. });
  11100. this.registerType('torch._C.Lexer', class {
  11101. constructor(buffer) {
  11102. this.buffer = buffer;
  11103. this.position = 0;
  11104. this.next_tokens = [new torch._C.Token(), new torch._C.Token(), new torch._C.Token(), new torch._C.Token()];
  11105. this.next();
  11106. }
  11107. cur() {
  11108. return this.next_tokens[0];
  11109. }
  11110. lookahead() {
  11111. if (!this.next_tokens[1].kind) {
  11112. this.position += this.cur().text().length;
  11113. this.lex(this.next_tokens[1]);
  11114. }
  11115. return this.next_tokens[1];
  11116. }
  11117. next() {
  11118. const [cur] = this.next_tokens;
  11119. [, this.next_tokens[0], this.next_tokens[1], this.next_tokens[2]] = this.next_tokens;
  11120. this.next_tokens[1].kind = '';
  11121. this.next_tokens[3] = cur;
  11122. const [token] = this.next_tokens;
  11123. if (token.kind) {
  11124. return cur;
  11125. }
  11126. this.position += cur.text().length;
  11127. this.lex(token);
  11128. return cur;
  11129. }
  11130. nextIf(kind) {
  11131. if (this.cur().kind !== kind) {
  11132. return false;
  11133. }
  11134. this.next();
  11135. return true;
  11136. }
  11137. expect(kind) {
  11138. if (this.cur().kind !== kind) {
  11139. throw new python.Error(`Unexpected '${this.cur().kind}' instead of '${kind}'.`);
  11140. }
  11141. return this.next();
  11142. }
  11143. lex(token) {
  11144. while (this.buffer[this.position] === ' ') {
  11145. this.position += 1;
  11146. }
  11147. let i = this.position;
  11148. if (i >= this.buffer.length) {
  11149. token.kind = '\0';
  11150. token.value = '';
  11151. } else if (this.buffer[i] === '.' && this.buffer[i + 1] === '.' && this.buffer[i + 2] === '.') {
  11152. token.kind = '...';
  11153. token.value = '...';
  11154. /* } else if (this.buffer[i] === '[' && this.buffer[i + 1] === ']') {
  11155. this.kind = '[]';
  11156. this.value = '[]'; */
  11157. } 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] === '|') {
  11158. token.kind = this.buffer[i];
  11159. token.value = this.buffer[i];
  11160. } else if ((this.buffer[i] >= 'a' && this.buffer[i] <= 'z') || (this.buffer[i] >= 'A' && this.buffer[i] <= 'Z') || this.buffer[i] === '_') {
  11161. i += 1;
  11162. 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] === '_')) {
  11163. i += 1;
  11164. }
  11165. token.kind = 'id';
  11166. token.value = this.buffer.slice(this.position, i);
  11167. } else if (this.buffer[i] === '-' && this.buffer[i + 1] === '>') {
  11168. token.kind = '->';
  11169. token.value = '->';
  11170. } else if ((this.buffer[i] >= '0' && this.buffer[i] <= '9') || this.buffer[i] === '-') {
  11171. i += 1;
  11172. while (i < this.buffer.length && ((this.buffer[i] >= '0' && this.buffer[i] <= '9') || this.buffer[i] === '.' || this.buffer[i] === 'e' || this.buffer[i] === '-')) {
  11173. i += 1;
  11174. }
  11175. token.kind = '#';
  11176. token.value = this.buffer.slice(this.position, i);
  11177. } else if (this.buffer[i] === "'" || this.buffer[i] === '"') {
  11178. const quote = this.buffer[i];
  11179. i += 1;
  11180. while (i < this.buffer.length && this.buffer[i] !== quote) {
  11181. i += (this.buffer[i] === '\\' && (this.buffer[i + 1] === "'" || this.buffer[i + 1] === '"' || this.buffer[i + 1] === '\\')) ? 2 : 1;
  11182. }
  11183. i += 1;
  11184. token.kind = 'string';
  11185. token.value = this.buffer.slice(this.position, i);
  11186. } else {
  11187. throw new python.Error(`Unsupported token at '${this.position}'.`);
  11188. }
  11189. }
  11190. });
  11191. this.registerType('torch._C.SchemaTypeParser', class {
  11192. constructor(L, complete_tensor_types, allow_typevars) {
  11193. this.L = L;
  11194. this.complete_tensor_types = complete_tensor_types;
  11195. this._allow_typevars = allow_typevars;
  11196. }
  11197. parseType() {
  11198. const r = this.parseFakeAndRealType();
  11199. return { first: r[0], second: r[2] };
  11200. }
  11201. parseBaseType() {
  11202. const L = this.L;
  11203. const tok = L.cur();
  11204. const text = tok.text();
  11205. L.next();
  11206. switch (text) {
  11207. case 'Tensor': return torch.TensorType.get();
  11208. case 'bool': return torch.BoolType.get();
  11209. case 'int': return torch.IntType.get();
  11210. case 'float': return torch.FloatType.get();
  11211. case 'complex': return torch.ComplexType.get();
  11212. case 'str': return torch.StringType.get();
  11213. case 'SymInt': return torch.SymIntType.get();
  11214. case 'Scalar': return torch.NumberType.get();
  11215. case 'ScalarType': return torch.Type.get('ScalarTypeType');
  11216. case 'Device': return torch.DeviceObjType.get();
  11217. case 'Layout': return torch.Type.get('Layout');
  11218. case 'MemoryFormat': return torch.Type.get('MemoryFormat');
  11219. case 'Generator': return torch._C._GeneratorType.get();
  11220. case 't': case 't1': case 't2': case 'tVal': return torch._C.VarType.create(text);
  11221. case 'Any': return torch.AnyType.get();
  11222. case 'AnyEnumType': return torch.Type.get('AnyEnumType');
  11223. case 'Dimname': return torch.StringType.get();
  11224. case 'QScheme': return torch.Type.get('QSchemeType');
  11225. case 'Stream': return torch.StreamObjType.get();
  11226. case 'Storage': return torch.Type.get('Storage');
  11227. case 'AnyClassType': return torch.Type.get('AnyClassType');
  11228. case 'NoneType': return torch.NoneType.get();
  11229. default: throw new python.Error(`Unsupported type '${text}'.`);
  11230. }
  11231. }
  11232. parseFakeAndRealType() {
  11233. const L = this.L;
  11234. let fake_value = null;
  11235. let real_value = null;
  11236. let alias_info = null;
  11237. if (L.nextIf('(')) {
  11238. const types = [];
  11239. while (!L.nextIf(')')) {
  11240. const r = this.parseType();
  11241. types.push(r.first);
  11242. if (alias_info && r.second) {
  11243. alias_info.addContainedType(r.second);
  11244. }
  11245. L.nextIf(',');
  11246. }
  11247. real_value = torch.TupleType.create(types);
  11248. fake_value = real_value;
  11249. } else if (L.cur().text() === 'Future') {
  11250. L.next();
  11251. L.expect('(');
  11252. const p = this.parseType();
  11253. const subtype = p.first;
  11254. // const subalias = p.second;
  11255. L.expect(')');
  11256. real_value = torch.FutureType.create(subtype);
  11257. fake_value = real_value;
  11258. } else if (L.cur().text() === 'Await') {
  11259. L.next();
  11260. L.expect('(');
  11261. const p = this.parseType();
  11262. const subtype = p.first;
  11263. // const subalias = p.second;
  11264. L.expect(')');
  11265. real_value = torch.AwaitType.get(subtype);
  11266. fake_value = real_value;
  11267. } else if (L.cur().text() === 'RRef') {
  11268. L.next();
  11269. L.expect('(');
  11270. const p = this.parseType();
  11271. const subtype = p.first;
  11272. // const subalias = p.second;
  11273. L.expect(')');
  11274. real_value = torch.RRefType.create(subtype);
  11275. fake_value = real_value;
  11276. } else if (L.cur().text() === 'Tensor') {
  11277. L.next();
  11278. real_value = torch.TensorType.get();
  11279. fake_value = real_value;
  11280. alias_info = this.parseAliasAnnotation();
  11281. } else if (L.cur().text() === 'Dict') {
  11282. L.next();
  11283. L.expect('(');
  11284. const key_type = this.parseType().first;
  11285. L.expect(',');
  11286. const value_type = this.parseType().first;
  11287. L.expect(')');
  11288. alias_info = this.parseAliasAnnotation();
  11289. real_value = torch.DictType.create(key_type, value_type);
  11290. fake_value = real_value;
  11291. } else if (L.nextIf('Union')) {
  11292. L.next();
  11293. L.expect('(');
  11294. const types = [];
  11295. types.push(this.parseType().first);
  11296. while (L.cur().kind !== ')') {
  11297. L.expect(',');
  11298. types.push(this.parseType().first);
  11299. }
  11300. L.expect(')');
  11301. alias_info = this.parseAliasAnnotation();
  11302. real_value = new torch.UnionType(types);
  11303. fake_value = real_value;
  11304. /* } else if (complete_tensor_types && L.cur().kind == TK_IDENT && parseTensorDType(L.cur().text())) {
  11305. fake_value = real_value = parseRefinedTensor();
  11306. alias_info = parseAliasAnnotation(); */
  11307. } else if (L.cur().kind === 'id' && L.cur().text() === '__torch__') {
  11308. L.next();
  11309. L.expect('.');
  11310. const torch_tok = L.expect('id');
  11311. if (torch_tok.text() !== 'torch') {
  11312. throw new python.Error('Expected classes namespace.');
  11313. }
  11314. L.expect('.');
  11315. const classes_tok = L.expect('id');
  11316. if (classes_tok.text() !== 'classes') {
  11317. throw new python.Error('Expected classes namespace.');
  11318. }
  11319. L.expect('.');
  11320. const ns_tok = L.expect('id');
  11321. L.expect('.');
  11322. const class_tok = L.expect('id');
  11323. real_value = torch._C.getCustomClass(`__torch__.torch.classes.${ns_tok.text()}.${class_tok.text()}`);
  11324. fake_value = real_value;
  11325. if (!fake_value) {
  11326. throw new python.Error(`Unknown custom class type '${ns_tok.text()}.${class_tok.text()}'.`);
  11327. }
  11328. } else {
  11329. real_value = this.parseBaseType();
  11330. fake_value = real_value;
  11331. if (real_value.kind() === 'ScalarTypeType' ||
  11332. real_value.kind() === 'MemoryFormat' ||
  11333. real_value.kind() === 'Layout' ||
  11334. real_value.kind() === 'SymIntType') {
  11335. fake_value = torch.IntType.get();
  11336. }
  11337. alias_info = this.parseAliasAnnotation();
  11338. }
  11339. while (true) {
  11340. if (L.cur().kind === '[' && L.lookahead().kind === ']') {
  11341. L.expect('[');
  11342. L.expect(']');
  11343. fake_value = torch.ListType.create(fake_value);
  11344. real_value = torch.ListType.create(real_value);
  11345. let container = this.parseAliasAnnotation();
  11346. if (alias_info) {
  11347. if (!container) {
  11348. container = new torch._C.AliasInfo();
  11349. container.is_write = alias_info.is_write;
  11350. }
  11351. container.addContainedType(alias_info);
  11352. }
  11353. alias_info = container;
  11354. } else if (L.nextIf('?')) {
  11355. fake_value = torch.OptionalType.create(fake_value);
  11356. real_value = torch.OptionalType.create(real_value);
  11357. } else {
  11358. break;
  11359. }
  11360. }
  11361. return [fake_value, real_value, alias_info];
  11362. }
  11363. parseAliasAnnotation() {
  11364. const L = this.L;
  11365. let alias_info = null;
  11366. if (L.nextIf('(')) {
  11367. alias_info = new torch._C.AliasInfo();
  11368. do {
  11369. alias_info.addBeforeSet(L.cur().text());
  11370. L.next();
  11371. if (L.nextIf('!')) {
  11372. alias_info.is_write = true;
  11373. }
  11374. }
  11375. while (L.nextIf('|'));
  11376. if (L.nextIf('->')) {
  11377. do {
  11378. alias_info.addAfterSet(L.cur().text());
  11379. L.next();
  11380. }
  11381. while (L.nextIf('|'));
  11382. }
  11383. L.expect(')');
  11384. }
  11385. return alias_info;
  11386. }
  11387. });
  11388. this.registerType('torch.Argument', class {
  11389. constructor(...args) {
  11390. // torch/aten/src/ATen/core/function_schema.h
  11391. this.N = null;
  11392. this.default_value = null;
  11393. this.kwarg_only = false;
  11394. this.alias_info = null;
  11395. if (args.length === 2) {
  11396. [this.name, this.type] = args;
  11397. this.real_type = this.type;
  11398. } else if (args.length === 3 && args[1] instanceof torch.Type && args[2] instanceof torch.Type) {
  11399. [this.name, this.type, this.real_type] = args;
  11400. } else if (args.length === 6) {
  11401. [this.name, this.type, this.real_type, this.N, this.default_value, this.kwarg_only] = args;
  11402. } else if (args.length === 7) {
  11403. [this.name, this.type, this.real_type, this.N, this.default_value, this.kwarg_only, this.alias_info] = args;
  11404. } else {
  11405. throw new python.Error('Invalid arguments.');
  11406. }
  11407. const is_alias = this.alias_info && this.alias_info.is_write;
  11408. this.is_out = this.kwarg_only && is_alias;
  11409. }
  11410. has_default_value() {
  11411. return this.default_value !== undefined;
  11412. }
  11413. is_inferred_type() {
  11414. if (this.type instanceof torch.TensorType) {
  11415. return this.type.isInferredType();
  11416. }
  11417. return false;
  11418. }
  11419. str() {
  11420. const list = [];
  11421. const type = this.real_type;
  11422. const is_opt = type instanceof torch.OptionalType;
  11423. const unopt_type = is_opt ? type.getElementType() : type;
  11424. if (unopt_type instanceof torch.ListType) {
  11425. list.push(unopt_type.getElementType().str());
  11426. if (this.alias_info && this.alias_info.containedTypes.length > 0) {
  11427. list.push(this.alias_info.containedTypes[0].str());
  11428. }
  11429. list.push(this.N === null ? `[]` : `[${this.N}]`);
  11430. } else {
  11431. list.push(unopt_type.str());
  11432. }
  11433. if (this.alias_info && this.alias_info.before_set.length > 0) {
  11434. list.push(this.alias_info.str());
  11435. }
  11436. if (is_opt) {
  11437. list.push('?');
  11438. }
  11439. if (this.name) {
  11440. list.push(' ');
  11441. list.push(this.name);
  11442. }
  11443. if (this.default_value !== undefined) {
  11444. const value = this.default_value;
  11445. if (value === null) {
  11446. list.push('=None');
  11447. } else if (typeof value === 'boolean') {
  11448. list.push('=');
  11449. list.push(value ? 'True' : 'False');
  11450. } else if (typeof value === 'string') {
  11451. list.push(`="${value}"`);
  11452. } else if (typeof value === 'number') {
  11453. list.push(`=${value}`);
  11454. if (Number.isInteger(value) && this.real_type instanceof torch.FloatType) {
  11455. list.push(`.`);
  11456. }
  11457. } else if (Array.isArray(value)) {
  11458. list.push(`=[${value.join(', ')}]`);
  11459. }
  11460. }
  11461. return list.join('');
  11462. }
  11463. });
  11464. torch._C.TypeKind = {
  11465. StringType: 'StringType',
  11466. NumberType: 'NumberType',
  11467. IntType: 'IntType',
  11468. BoolType: 'BoolType',
  11469. DynamicType: 'DynamicType',
  11470. OptionalType: 'OptionalType',
  11471. FloatType: 'FloatType',
  11472. ComplexType: 'ComplexType',
  11473. ListType: 'ListType',
  11474. };
  11475. this.registerType('torch._C.List', class extends Array {
  11476. constructor(type, elements) {
  11477. super(elements ? elements.length : 0);
  11478. if (Array.isArray(elements)) {
  11479. for (let i = 0; i < elements.length; i++) {
  11480. this[i] = elements[i];
  11481. }
  11482. }
  11483. this.type = type;
  11484. }
  11485. elementType() {
  11486. return this.type;
  11487. }
  11488. });
  11489. this.registerFunction('torch._C.builtin_cast_method_to_scalar_type', () => {
  11490. return new Map();
  11491. });
  11492. this.registerFunction('torch._C.string_to_type_lut', () => {
  11493. if (!torch._C.string_to_type_lut.basePythonTypes) {
  11494. const map = new Map();
  11495. map.set('Tensor', torch.TensorType.get());
  11496. map.set('int', torch.IntType.get());
  11497. map.set('float', torch.FloatType.get());
  11498. map.set('bool', torch.BoolType.get());
  11499. map.set('complex', torch.ComplexType.get());
  11500. map.set('str', torch.StringType.get());
  11501. map.set('Device', torch.DeviceObjType.get());
  11502. map.set('number', torch.NumberType.get());
  11503. map.set('None', torch.NoneType.get());
  11504. map.set('NoneType', torch.NoneType.get());
  11505. map.set('Any', torch.AnyType.get());
  11506. map.set('list', torch.Type.get('AnyListType'));
  11507. map.set('tuple', torch.Type.get('AnyTupleType'));
  11508. torch._C.string_to_type_lut.basePythonTypes = map;
  11509. }
  11510. return torch._C.string_to_type_lut.basePythonTypes;
  11511. });
  11512. this.registerType('torch._C.ScriptTypeParser', class {
  11513. constructor(resolver) {
  11514. this._resolver = resolver;
  11515. }
  11516. parseSchemaFromDef(def, skip_self) {
  11517. const name = def.name;
  11518. const args = this.parseArgsFromDecl(def, skip_self);
  11519. const returns = this.parseReturnFromDecl(def);
  11520. return new torch.FunctionSchema(name, '', args, returns, false, false);
  11521. }
  11522. parseArgsFromDecl(decl, skip_self) {
  11523. const retval = [];
  11524. if (decl.args.posonlyargs.length > 0 || decl.args.kwonlyargs.length > 0) {
  11525. throw new python.Error('Unsupported function argument.');
  11526. }
  11527. const params = decl.args.args.slice();
  11528. const kwonlyargs = new Set(Array.from(decl.args.kwonlyargs));
  11529. const start = skip_self ? 1 : 0;
  11530. for (let i = start; i < params.length; i++) {
  11531. const decl_arg = params[i];
  11532. const N = null;
  11533. const default_value = undefined;
  11534. const type = decl_arg.annotation ? this.parseTypeFromExpr(decl_arg.annotation) : null;
  11535. const arg = new torch.Argument(decl_arg.arg, type, type, N, default_value, kwonlyargs.has(decl_arg), null);
  11536. retval.push(arg);
  11537. }
  11538. return retval;
  11539. }
  11540. parseReturnFromDecl(decl) {
  11541. if (!decl.returns) {
  11542. return [];
  11543. }
  11544. if (this.parseBroadcastList(decl.returns)) {
  11545. throw new python.Error('Broadcastable lists cannot appear as a return type.');
  11546. }
  11547. const parsed_type = this.parseTypeFromExpr(decl.returns);
  11548. return [new torch.Argument('', parsed_type, parsed_type, null, undefined, false)];
  11549. }
  11550. parseTypeFromExpr(expr) {
  11551. if (this._resolver) {
  11552. if (expr instanceof ast.Name) {
  11553. const type = this._resolver.resolveType(expr.id);
  11554. if (type) {
  11555. return type;
  11556. }
  11557. }
  11558. }
  11559. return this.parseTypeFromExprImpl(expr);
  11560. }
  11561. parseTypeFromExprImpl(expr) {
  11562. if (expr instanceof ast.Subscript) {
  11563. const value_name = this.parseBaseTypeName(expr.value);
  11564. if (!value_name) {
  11565. throw new python.Error('Subscripted type must be a type identifier.');
  11566. }
  11567. return this.subscriptToType(value_name, expr);
  11568. }
  11569. const name = this.parseBaseTypeName(expr);
  11570. if (name) {
  11571. const itr = torch._C.string_to_type_lut().get(name);
  11572. if (itr) {
  11573. return itr;
  11574. }
  11575. if (this._resolver) {
  11576. const typePtr = this._resolver.resolveType(name, expr);
  11577. if (typePtr) {
  11578. return typePtr;
  11579. }
  11580. }
  11581. }
  11582. throw new python.Error(`Unknown type name '${name}'.`);
  11583. }
  11584. parseBaseTypeName(expr) {
  11585. if (expr instanceof ast.Name) {
  11586. return expr.id;
  11587. } else if (expr instanceof ast.Constant && expr.value === null) {
  11588. return 'None';
  11589. } else if (expr instanceof ast.Attribute) {
  11590. const name = expr.attr;
  11591. const tensor_subtypes = new Set(['Tensor', 'LongTensor', 'FloatTensor', 'DoubleTensor', 'IntTensor', 'ShortTensor', 'HalfTensor', 'CharTensor', 'ByteTensor', 'BoolTensor']);
  11592. if (torch._C.isTorch(expr.value) && tensor_subtypes.has(name)) {
  11593. return name;
  11594. }
  11595. return torch._C.collectQualname(expr);
  11596. }
  11597. throw new python.Error(`Unsupported type '${expr.__class__.__name__}'.`);
  11598. }
  11599. parseBroadcastList(/* expr */) {
  11600. return null;
  11601. }
  11602. parseType(str) {
  11603. const expr = ast.parse(str);
  11604. return this.parseTypeFromExpr(expr.body[0].value);
  11605. }
  11606. subscriptToType(typeName, subscript) {
  11607. if (typeName === 'Tuple' || typeName === 'tuple') {
  11608. const subscript_expr_types = [];
  11609. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11610. for (const expr of elts) {
  11611. subscript_expr_types.push(this.parseTypeFromExprImpl(expr));
  11612. }
  11613. return torch.TupleType.create(subscript_expr_types);
  11614. } else if (typeName === 'List' || typeName === 'list') {
  11615. if (subscript.slice instanceof ast.Slice || subscript.slice instanceof ast.Tuple) {
  11616. throw new python.Error('List type must have exactly one element type.');
  11617. }
  11618. const elem_type = this.parseTypeFromExprImpl(subscript.slice);
  11619. return torch.ListType.create(elem_type);
  11620. } else if (typeName === 'Optional') {
  11621. if (subscript.slice instanceof ast.Slice || subscript.slice instanceof ast.Tuple) {
  11622. throw new python.Error('Optional type must have exactly one element type.');
  11623. }
  11624. const elem_type = this.parseTypeFromExprImpl(subscript.slice);
  11625. return torch.OptionalType.create(elem_type);
  11626. } else if (typeName === 'Union') {
  11627. const subscript_expr_types = [];
  11628. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11629. for (const expr of elts) {
  11630. subscript_expr_types.push(this.parseTypeFromExprImpl(expr));
  11631. }
  11632. return torch.UnionType.create(subscript_expr_types);
  11633. } else if (typeName === 'Future' || typeName === 'torch.jit.Future') {
  11634. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11635. if (elts.length !== 1) {
  11636. throw new python.Error('Future type must have exactly one element type.');
  11637. }
  11638. const elem_type = this.parseTypeFromExprImpl(elts[0]);
  11639. return torch.FutureType.create(elem_type);
  11640. } else if (typeName === 'Await' || typeName === 'torch.jit._Await') {
  11641. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11642. if (elts.length !== 1) {
  11643. throw new python.Error('Await type must have exactly one element type.');
  11644. }
  11645. const elem_type = this.parseTypeFromExprImpl(elts[0]);
  11646. return torch.AwaitType.create(elem_type);
  11647. } else if (typeName === 'RRef') {
  11648. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11649. if (elts.length !== 1) {
  11650. throw new python.Error('RRef type must have exactly one element type.');
  11651. }
  11652. const elem_type = this.parseTypeFromExprImpl(elts[0]);
  11653. return torch.RRefType.create(elem_type);
  11654. } else if (typeName === 'Dict' || typeName === 'dict') {
  11655. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11656. if (elts.length !== 2) {
  11657. throw new python.Error('Dict type must have exactly two element types.');
  11658. }
  11659. const key_type = this.parseTypeFromExprImpl(elts[0]);
  11660. const value_type = this.parseTypeFromExprImpl(elts[1]);
  11661. return torch.DictType.create(key_type, value_type);
  11662. }
  11663. throw new python.Error(`Unknown type constructor '${typeName}'.`);
  11664. }
  11665. });
  11666. this.registerFunction('torch._C.isTorch', (expr) => {
  11667. return expr instanceof ast.Name && expr.id === 'torch';
  11668. });
  11669. this.registerFunction('torch._C.collectQualname', (select) => {
  11670. const base = select.value;
  11671. if (base instanceof ast.Name) {
  11672. return `${base.id}.${select.attr}`;
  11673. }
  11674. const basename = torch._C.collectQualname(base);
  11675. return `${basename}.${select.attr}`;
  11676. });
  11677. this.registerType('torch._ops.OpOverload', class extends torch._ops.OperatorBase {
  11678. constructor(overloadpacket, op, op_dk, schema, tags) {
  11679. super();
  11680. this._op = op;
  11681. this._op_dk = op_dk;
  11682. this._schema = schema;
  11683. this._overloadpacket = overloadpacket;
  11684. this._tags = tags;
  11685. this._overloadname = schema.overload_name === '' ? 'default' : schema.overload_name;
  11686. this._name = this._schema.name;
  11687. this._name = schema.overload_name ? `${this._name}.${schema.overload_name}` : this._name;
  11688. this.__name__ = `${this._schema.name.split('::')[1]}.${this._overloadname}`;
  11689. this.__module__ = overloadpacket.__module__;
  11690. op.__module__ = overloadpacket.__module__;
  11691. this.__qualname__ = self._name;
  11692. this.__annotations__ = {};
  11693. // this._defined_in_python = this.__qualname__ in torch.library._defs
  11694. let is_write = null;
  11695. for (const a of this._schema.arguments) {
  11696. if (a.alias_info) {
  11697. is_write = is_write === null ? a.alias_info.is_write : a.alias_info.is_write || is_write;
  11698. }
  11699. }
  11700. this.is_view = is_write !== null && !is_write;
  11701. }
  11702. name() {
  11703. return this._name;
  11704. }
  11705. });
  11706. this.registerType('torch._ops.OpOverloadPacket', class {
  11707. constructor(qualified_op_name, op_name, op, overload_names) {
  11708. this._qualified_op_name = qualified_op_name;
  11709. this.__name__ = op_name;
  11710. this._op = op;
  11711. this._overload_names = overload_names;
  11712. this._dir = [];
  11713. this._has_torchbind_op_overload = this._schemas.some((schema) => this._has_script_object_arg(schema));
  11714. }
  11715. get _schemas() {
  11716. return this._overload_names.map((overload_name) => torch._C._get_schema(this._qualified_op_name, overload_name));
  11717. }
  11718. __getattr__(key) {
  11719. key = key === 'default' ? '' : key;
  11720. const op_dk_tags = torch._C._get_operation_overload(this._qualified_op_name, key);
  11721. const [op_, op_dk_, tags] = op_dk_tags;
  11722. const schema = torch._C._get_schema(this._qualified_op_name, key);
  11723. const overload = this._has_script_object_arg(schema) ?
  11724. new torch._ops.TorchBindOpOverload(this, op_, op_dk_, schema, tags) :
  11725. new torch._ops.OpOverload(this, op_, op_dk_, schema, tags);
  11726. builtins.setattr(self, key, overload);
  11727. this._dir.push(key);
  11728. return overload;
  11729. }
  11730. _has_script_object_arg(schema) {
  11731. return schema.arguments.some((arg) => arg.type instanceof torch.ClassType);
  11732. }
  11733. __call__(...args) {
  11734. const fn = execution._operators.get(this._qualified_op_name);
  11735. if (!fn) {
  11736. throw new python.Error(`Operator call '${this._qualified_op_name}' is not registered.`);
  11737. }
  11738. return fn(...args);
  11739. }
  11740. });
  11741. this.registerType('torch._ops._OpNamespace', class extends types.ModuleType {
  11742. constructor(name) {
  11743. super(`torch.ops.${name}`);
  11744. this.name = name;
  11745. this._dir = [];
  11746. }
  11747. __getattr__(op_name) {
  11748. const namespace_name = this.name;
  11749. const qualified_op_name = `${namespace_name}::${op_name}`;
  11750. const module_name = `${this.__module__}.${namespace_name}`;
  11751. let op = null;
  11752. let overload_names = null;
  11753. try {
  11754. [op, overload_names] = this._get_packet(qualified_op_name, module_name);
  11755. } catch {
  11756. // continue regardless of error
  11757. }
  11758. if (!op) {
  11759. throw new python.Error(`Unknown operator type '${qualified_op_name}'.`);
  11760. }
  11761. op.__module__ = module_name;
  11762. const opoverloadpacket = new torch._ops.OpOverloadPacket(qualified_op_name, op_name, op, overload_names);
  11763. opoverloadpacket.__module__ = `${this.__module__}.${namespace_name}`;
  11764. builtins.setattr(this, op_name, opoverloadpacket);
  11765. this._dir.push(op_name);
  11766. return opoverloadpacket;
  11767. }
  11768. _get_packet(qualname, op_module) {
  11769. const [op, overload_names] = torch._C._jit_get_operation(qualname);
  11770. if (op) {
  11771. // torch.jit._builtins._register_builtin(op, qualname);
  11772. }
  11773. op.__module__ = op_module;
  11774. return [op, overload_names];
  11775. }
  11776. });
  11777. this.registerType('torch._C.graph_node_list', class {
  11778. constructor(head) {
  11779. this.head = head;
  11780. }
  11781. front() {
  11782. return this.head.next;
  11783. }
  11784. end() {
  11785. return this.head.prev;
  11786. }
  11787. [Symbol.iterator]() {
  11788. let current = this.head.next;
  11789. const prev = this.head.prev;
  11790. return {
  11791. next() {
  11792. if (current !== prev) {
  11793. const value = current;
  11794. current = current.next;
  11795. return { value, done: false };
  11796. }
  11797. return { done: true };
  11798. }
  11799. };
  11800. }
  11801. });
  11802. this.registerType('torch.Graph', class {
  11803. constructor() {
  11804. this._next_unique = 0;
  11805. this._unique_names = new Map();
  11806. this._name_base_suffix = new Map();
  11807. this.all_nodes = new Set();
  11808. this.all_values = new Set();
  11809. this.all_blocks = new Set();
  11810. this._block = new torch.Block(this, null);
  11811. this._insert_before = this.return_node();
  11812. }
  11813. insert(opname, args, kwargs, range) {
  11814. return torch._C.emitBuiltinCall(range, this, opname, args, kwargs);
  11815. }
  11816. create(kind, ...args) {
  11817. let inputs = null;
  11818. let num_outputs = 1;
  11819. if (args.length === 2 && Array.isArray(args[0]) && typeof args[1] === 'number') {
  11820. [inputs, num_outputs] = args;
  11821. } else if (args.length === 1) {
  11822. if (typeof args[0] === 'number') {
  11823. [num_outputs] = args;
  11824. } else if (Array.isArray(args[0])) {
  11825. [inputs] = args;
  11826. }
  11827. }
  11828. const n = new torch.Node(this, kind);
  11829. if (inputs) {
  11830. for (const i of inputs) {
  11831. n.addInput(i);
  11832. }
  11833. }
  11834. for (let i = 0; i < num_outputs; i++) {
  11835. n.addOutput();
  11836. }
  11837. return n;
  11838. }
  11839. createClone(n, value_map, copy_blocks) {
  11840. copy_blocks = copy_blocks === undefined ? true : copy_blocks;
  11841. const r = n.allocNewInstance(this);
  11842. for (const o of n.outputs()) {
  11843. r.addOutput().copyMetadata(o);
  11844. }
  11845. r.cloneFrom(n);
  11846. for (const i of n.inputs()) {
  11847. r.addInput(value_map(i));
  11848. }
  11849. if (copy_blocks) {
  11850. for (const b of n.blocks()) {
  11851. r.addBlock().cloneFrom(b, value_map);
  11852. }
  11853. }
  11854. return r;
  11855. }
  11856. createNone() {
  11857. const n = this.create('prim::Constant');
  11858. n.output().setType(torch.NoneType.get());
  11859. return n;
  11860. }
  11861. createUninitialized(typ) {
  11862. const n = this.create('prim::Uninitialized');
  11863. n.output().setType(typ);
  11864. return n;
  11865. }
  11866. createEnumValue(e) {
  11867. const enum_type = e.type().expect(torch.EnumType);
  11868. const n = this.create('prim::EnumValue', [e]);
  11869. n.output().setType(enum_type.getValueType());
  11870. return n;
  11871. }
  11872. createList(contained_type, values) {
  11873. const n = this.create('prim::ListConstruct', values);
  11874. for (const v of values) {
  11875. if (!v.type().isSubtypeOf(contained_type)) {
  11876. throw new python.Error('Invalid list item.');
  11877. }
  11878. }
  11879. n.output().setType(torch.ListType.create(contained_type));
  11880. return n;
  11881. }
  11882. createListUnpack(v, size) {
  11883. const list_type = v.type().expect(torch.ListType);
  11884. const elem_type = list_type.getElementType();
  11885. const n = this.create('prim::ListUnpack', [v], 0);
  11886. for (let i = 0; i < size; i++) {
  11887. n.addOutput().setType(elem_type);
  11888. }
  11889. return n;
  11890. }
  11891. createTuple(values, tuple_type) {
  11892. if (!tuple_type) {
  11893. const types = values.map((v) => v.type());
  11894. tuple_type = torch.TupleType.create(types);
  11895. }
  11896. const n = this.create('prim::TupleConstruct', values);
  11897. n.output().setType(tuple_type);
  11898. return n;
  11899. }
  11900. createTupleUnpack(v) {
  11901. const tt = v.type().expect(torch.TupleType);
  11902. const n = this.create('prim::TupleUnpack', [v], 0);
  11903. for (const element of tt.elements()) {
  11904. n.addOutput().setType(element);
  11905. }
  11906. return n;
  11907. }
  11908. createTupleIndex(tup, idx, output_type) {
  11909. const n = this.create('prim::TupleIndex', [tup, idx]);
  11910. n.output().setType(output_type);
  11911. return n;
  11912. }
  11913. createTupleSlice(tup, beg, step_size, num_values) {
  11914. const new_vals = [];
  11915. const tt = tup.type().expect(torch.TupleType);
  11916. let i = beg;
  11917. for (let j = 0; j < num_values; j++) {
  11918. const idx = this.insertConstant(new torch._C.IValue(i, 'Int'));
  11919. const tupleIndex = this.insertNode(this.createTupleIndex(tup, idx, tt.elements()[i]));
  11920. new_vals.push(tupleIndex.output());
  11921. i += step_size;
  11922. }
  11923. const n = this.createTuple(new_vals);
  11924. return n;
  11925. }
  11926. createDict(key_type, value_type, keys, values) {
  11927. if (keys.length !== values.length) {
  11928. throw new python.Error('Invalid dictionary size.');
  11929. }
  11930. const n = this.create('prim::DictConstruct');
  11931. const length = keys.length;
  11932. for (let i = 0; i < length; i++) {
  11933. if (!keys[i].type().isSubtypeOf(key_type)) {
  11934. throw new python.Error('Invalid key.');
  11935. }
  11936. if (!values[i].type().isSubtypeOf(value_type)) {
  11937. throw new python.Error('Invalid value.');
  11938. }
  11939. n.addInput(keys[i]);
  11940. n.addInput(values[i]);
  11941. }
  11942. n.output().setType(torch.DictType.create(key_type, value_type));
  11943. return n;
  11944. }
  11945. createObject(type) {
  11946. const node = this.create('prim::CreateObject');
  11947. node.output().setType(type);
  11948. return node;
  11949. }
  11950. createIsInstance(v, types) {
  11951. const n = this.create('prim::isinstance', [v], 1);
  11952. n.tys_('types', types);
  11953. n.output().setType(torch.BoolType.get());
  11954. return n;
  11955. }
  11956. createSetAttr(obj, field, newValue) {
  11957. const n = this.create('prim::SetAttr', [obj, newValue], 0);
  11958. n.s_('name', field);
  11959. return n;
  11960. }
  11961. createGetAttr(obj, field) {
  11962. const n = this.create('prim::GetAttr', [obj]);
  11963. n.s_('name', field);
  11964. const classType = obj.type();
  11965. const outputType = classType.getAttribute(field);
  11966. n.output().setType(outputType);
  11967. n.output().setDebugName(torch._C.normalizeAttrName(field));
  11968. return n;
  11969. }
  11970. createLoad(name, type) {
  11971. const n = this.create('prim::Load', [], 1);
  11972. n.s_('name', name);
  11973. n.output().setType(type);
  11974. return n;
  11975. }
  11976. createStore(name, v) {
  11977. const n = this.create('prim::Store', [v], 0);
  11978. n.s_('name', name);
  11979. return n;
  11980. }
  11981. inputs() {
  11982. return this._block.inputs();
  11983. }
  11984. outputs() {
  11985. return this._block.outputs();
  11986. }
  11987. nodes() {
  11988. return this._block.nodes();
  11989. }
  11990. param_node() {
  11991. return this._block.param_node();
  11992. }
  11993. return_node() {
  11994. return this._block.return_node();
  11995. }
  11996. block() {
  11997. return this._block;
  11998. }
  11999. addInput(name) {
  12000. return this._block.addInput(name);
  12001. }
  12002. insertNode(node) {
  12003. torch._C.AT_ASSERT(this._insert_before.inBlockList());
  12004. return node.insertBefore(this._insert_before);
  12005. }
  12006. insertConstant(val, loc, scope) {
  12007. return torch._C.insertConstant(this, val, loc, scope);
  12008. }
  12009. insertMethodCall(method_name, matched) {
  12010. const result = this.insertNode(this.create('prim::CallMethod', matched.inputs))
  12011. .s_('name', method_name)
  12012. .output().setType(matched.return_types[0]);
  12013. return result;
  12014. }
  12015. insertUncheckedCast(v, type) {
  12016. const n = this.create('prim::unchecked_cast', [v]);
  12017. this.insertNode(n);
  12018. n.output().setType(type);
  12019. return n.output();
  12020. }
  12021. insertToList(v, type) {
  12022. let dim = 0;
  12023. let ptr = type;
  12024. while (ptr instanceof torch.ListType) {
  12025. ptr = ptr.getElementType();
  12026. dim += 1;
  12027. }
  12028. let elem_ty = 0;
  12029. if (ptr instanceof torch.IntType) {
  12030. elem_ty = 0;
  12031. } else if (ptr instanceof torch.FloatType) {
  12032. elem_ty = 1;
  12033. } else if (ptr instanceof torch.BoolType) {
  12034. elem_ty = 2;
  12035. } else if (ptr instanceof torch.ComplexType) {
  12036. elem_ty = 3;
  12037. } else {
  12038. throw new python.Error(`Unsupported list type '${type.kind()}'.`);
  12039. }
  12040. const dim_val = this.insertConstant(dim);
  12041. const elem_ty_val = this.insertConstant(elem_ty);
  12042. const n = this.insertNode(this.create('prim::tolist', [v, dim_val, elem_ty_val]));
  12043. n.output().setType(type);
  12044. return n.output();
  12045. }
  12046. insertFunctionCall(callee, matched) {
  12047. const func_name = callee.name();
  12048. const fn_constant = this.insertNode(this.create('prim::Constant')).s_('name', func_name).output().setType(torch._C.FunctionType.create(callee));
  12049. const inputs = [fn_constant, ...matched.inputs];
  12050. const result = this.insertNode(this.create('prim::CallFunction', inputs)).output().setType(matched.return_types[0]);
  12051. return result;
  12052. }
  12053. insertPoint() {
  12054. return this._insert_before;
  12055. }
  12056. setInsertPoint(node) {
  12057. if (node instanceof torch.Block) {
  12058. node = node.return_node();
  12059. }
  12060. this._insert_before = node;
  12061. }
  12062. freeNode(n) {
  12063. this.all_nodes.delete(n);
  12064. }
  12065. freeValue(v) {
  12066. v.setDebugName('');
  12067. this.all_values.delete(v);
  12068. }
  12069. freeBlock(b) {
  12070. this.all_blocks.delete(b);
  12071. }
  12072. copy() {
  12073. const new_g = new torch.Graph();
  12074. new_g.cloneFrom(this);
  12075. return new_g;
  12076. }
  12077. cloneFrom(src) {
  12078. const env = (v) => {
  12079. throw new python.Error(`Use of value '${v.debugName()}' not in scope.`);
  12080. };
  12081. this.block().cloneFrom(src.block(), env);
  12082. }
  12083. set_op_version(version) {
  12084. this._op_version = version;
  12085. }
  12086. get_op_version() {
  12087. return this._op_version;
  12088. }
  12089. print(out, print_source_locations) {
  12090. out.write('graph(');
  12091. torch._C.const_value_list_with_types(out, this.inputs(), ',\n ');
  12092. out.write('):\n');
  12093. const groups = [];
  12094. for (const node of this.nodes()) {
  12095. node.print(out, 1, groups, print_source_locations);
  12096. }
  12097. out.write(' return (');
  12098. torch._C.printValueRefs(out, this.outputs());
  12099. out.write(')\n');
  12100. for (let i = 0; i < groups.length; i++) {
  12101. const fg = groups[i];
  12102. out.write('with ');
  12103. out.write(fg.kind());
  12104. out.write(`_${i} = `);
  12105. out.write(fg.g('Subgraph'));
  12106. }
  12107. return out;
  12108. }
  12109. toString() {
  12110. const out = new io.StringIO();
  12111. this.print(out, true);
  12112. return out.toString();
  12113. }
  12114. });
  12115. this.registerType('torch.Block', class {
  12116. constructor(graph, node) {
  12117. this._graph = graph;
  12118. this._input = graph.create('prim::Param', 0);
  12119. this._output = graph.create('prim::Return', 0);
  12120. this._owning_node = node;
  12121. this._input.next = this._output;
  12122. this._input.prev = this._output;
  12123. this._output.next = this._input;
  12124. this._output.prev = this._input;
  12125. this._graph.all_blocks.add(this);
  12126. this._output._owning_block = this;
  12127. // output_.topo_position_ = kUpperBound;
  12128. this._input._owning_block = this;
  12129. // input_.topo_position_ = kLowerBound;
  12130. }
  12131. inputs() {
  12132. return this._input.outputs();
  12133. }
  12134. outputs() {
  12135. return this._output.inputs();
  12136. }
  12137. nodes() {
  12138. return new torch._C.graph_node_list(this._input);
  12139. }
  12140. return_node() {
  12141. return this._output;
  12142. }
  12143. param_node() {
  12144. return this._input;
  12145. }
  12146. owningNode() {
  12147. return this._owning_node;
  12148. }
  12149. owningGraph() {
  12150. return this._graph;
  12151. }
  12152. addInput(name) {
  12153. const value = this._input.addOutput();
  12154. value.setDebugName(name || '');
  12155. return value;
  12156. }
  12157. registerOutput(value) {
  12158. this._output.addInput(value);
  12159. return this.outputs().length - 1;
  12160. }
  12161. appendNode(n) {
  12162. if (n._graph !== this._graph || n.inBlockList()) {
  12163. throw new python.Error('Node not in graph.');
  12164. }
  12165. n.insertBefore(this._output);
  12166. return n;
  12167. }
  12168. cloneFrom(src, value_map) {
  12169. const local_map = new Map();
  12170. const env = (v) => {
  12171. if (local_map.has(v)) {
  12172. return local_map.get(v);
  12173. }
  12174. return value_map(v);
  12175. };
  12176. const graph = this.owningGraph();
  12177. for (const input of src.inputs()) {
  12178. local_map.set(input, this.addInput().copyMetadata(input));
  12179. }
  12180. for (const node of src.nodes()) {
  12181. const new_node = this.appendNode(graph.createClone(node, env));
  12182. for (let i = 0; i < node.outputs().length; i++) {
  12183. const oo = node.outputs()[i];
  12184. const no = new_node.outputs()[i];
  12185. local_map.set(oo, no);
  12186. no.copyMetadata(oo);
  12187. }
  12188. }
  12189. for (const output of src.outputs()) {
  12190. this.registerOutput(env(output));
  12191. }
  12192. }
  12193. eraseOutput(i) {
  12194. this._output.removeInput(i);
  12195. }
  12196. destroy() {
  12197. this._output.removeAllInputs();
  12198. for (const n of this.nodes()) {
  12199. n.destroy();
  12200. }
  12201. this._output.destroy();
  12202. this._input.destroy();
  12203. this._graph.freeBlock(this);
  12204. }
  12205. });
  12206. this.registerType('torch.Node', class {
  12207. constructor(graph, kind) {
  12208. this._kind = kind;
  12209. this._graph = graph;
  12210. this._owning_block = null;
  12211. this._values = new Map();
  12212. this._inputs = [];
  12213. this._outputs = [];
  12214. this._blocks = [];
  12215. this._graph.all_nodes.add(this);
  12216. this._prev = null;
  12217. this._next = null;
  12218. this._source_range = null;
  12219. this._op = null;
  12220. }
  12221. owningGraph() {
  12222. return this._graph;
  12223. }
  12224. owningBlock() {
  12225. return this._owning_block;
  12226. }
  12227. kind() {
  12228. return this._kind;
  12229. }
  12230. schema() {
  12231. if (this._op) {
  12232. return this._op.schema();
  12233. }
  12234. // Node::schema() throws while torch.Node.schema() does not.
  12235. const op = this.maybeOperator();
  12236. if (op) {
  12237. return op.schema();
  12238. }
  12239. return null;
  12240. // return this.getOperator().schema();
  12241. }
  12242. hasNamedInput(name) {
  12243. for (const argument of this.schema().arguments) {
  12244. if (argument.name === name) {
  12245. return true;
  12246. }
  12247. }
  12248. return false;
  12249. }
  12250. matches(schema) {
  12251. if (torch._C.isBlockListedSchema(schema)) {
  12252. return false;
  12253. }
  12254. if (this.kind() !== schema.name) {
  12255. return false;
  12256. }
  12257. const actuals = this.inputs();
  12258. const formals = schema.arguments;
  12259. if (actuals.length < formals.length) {
  12260. return false;
  12261. }
  12262. const type_env = new Map();
  12263. for (let i = 0; i < formals.length; i++) {
  12264. let formal = formals[i].type;
  12265. const matched_type = torch._C.matchTypeVariables(formal, actuals[i].type(), type_env);
  12266. if (!matched_type.success()) {
  12267. return false;
  12268. }
  12269. const resolved = torch._C.tryEvalTypeVariables(formal, type_env);
  12270. if (resolved) {
  12271. formal = resolved;
  12272. }
  12273. if (!actuals[i].type().isSubtypeOf(formal)) {
  12274. return false;
  12275. }
  12276. }
  12277. if (!schema.is_vararg && actuals.length !== formals.length) {
  12278. return false;
  12279. }
  12280. return true;
  12281. }
  12282. mustBeNone() {
  12283. return this._kind === 'prim::AutogradZero' ||
  12284. (this.outputs().length === 1 && this.output().type() === torch.NoneType.get()) ||
  12285. (this._kind === 'prim::Constant' && !this.hasAttributes() && this.output().type() instanceof torch.OptionalType);
  12286. }
  12287. maybeSchema() {
  12288. const op = this.maybeOperator();
  12289. if (op) {
  12290. return op.schema();
  12291. }
  12292. return null;
  12293. }
  12294. maybeOperator() {
  12295. if (!this._op) {
  12296. const candidates = torch._C.getAllOperatorsFor(this.kind());
  12297. for (const candidate of candidates) {
  12298. if (this.matches(candidate.schema())) {
  12299. this._op = candidate;
  12300. break;
  12301. }
  12302. }
  12303. }
  12304. return this._op;
  12305. }
  12306. getOperator() {
  12307. const maybe = this.maybeOperator();
  12308. if (maybe) {
  12309. return maybe;
  12310. }
  12311. throw new python.Error(`Schema not found for node '${this.kind()}'.`);
  12312. }
  12313. getOperation() {
  12314. return this.getOperator().getOperation(this);
  12315. }
  12316. isNondeterministic() {
  12317. const schema = this.maybeSchema();
  12318. if (!this.kind().startsWith('aten::')) {
  12319. return false;
  12320. }
  12321. if (!schema) {
  12322. return false;
  12323. }
  12324. const schema_info = new torch._C.SchemaInfo(schema);
  12325. if (this.hasNamedInput('train')) {
  12326. throw new python.Error('Not Implemented.');
  12327. // const value = constant_as<bool>(this.namedInput("train"));
  12328. // if (value) {
  12329. // schema_info.addArgumentValue('train', value);
  12330. // }
  12331. }
  12332. return schema_info.is_nondeterministic();
  12333. }
  12334. hasSideEffects() {
  12335. switch (this._kind) {
  12336. case 'prim::PythonOp':
  12337. case 'prim::IgnoredPythonOp':
  12338. case 'prim::Print':
  12339. case 'prim::RaiseException':
  12340. case 'aten::warn':
  12341. case 'aten::save':
  12342. case 'aten::manual_seed':
  12343. case 'prim::AddStatValue':
  12344. case 'prim::TimePoint':
  12345. case 'prim::CallFunction':
  12346. case 'prim::CallMethod':
  12347. case 'prim::BailoutTemplate':
  12348. case 'prim::BailOut':
  12349. case 'prim::rpc_async':
  12350. case 'prim::rpc_sync':
  12351. case 'prim::rpc_remote':
  12352. case 'aten::wait':
  12353. case 'cuda::set_stream':
  12354. case 'cuda::_set_device':
  12355. case 'cuda::_current_device':
  12356. case 'cuda::synchronize':
  12357. case 'prim::Enter':
  12358. case 'prim::Exit':
  12359. return true;
  12360. default:
  12361. break;
  12362. }
  12363. const op = this.maybeOperator();
  12364. if (!op) {
  12365. torch._C.TORCH_INTERNAL_ASSERT(this._kind.startsWith('prim::'));
  12366. return false;
  12367. }
  12368. if (this._kind.startsWith('prim::') || this._kind.startsWith('aten::') || this._kind.startsWith('cuda::')) {
  12369. torch._C.TORCH_INTERNAL_ASSERT(
  12370. op.aliasAnalysisKind() === 'INTERNAL_SPECIAL_CASE' ||
  12371. op.aliasAnalysisKind() === 'FROM_SCHEMA' ||
  12372. op.aliasAnalysisKind() === 'CONSERVATIVE');
  12373. }
  12374. switch (op.aliasAnalysisKind()) {
  12375. case 'PURE_FUNCTION':
  12376. case 'FROM_SCHEMA':
  12377. case 'INTERNAL_SPECIAL_CASE':
  12378. return false;
  12379. case 'CONSERVATIVE':
  12380. return true;
  12381. default:
  12382. break;
  12383. }
  12384. torch._C.TORCH_INTERNAL_ASSERT(false);
  12385. return false;
  12386. }
  12387. inputs() {
  12388. return this._inputs;
  12389. }
  12390. outputs() {
  12391. return this._outputs;
  12392. }
  12393. input(i) {
  12394. if (i === undefined) {
  12395. torch._C.AT_ASSERT(this._inputs.length === 1);
  12396. return this._inputs[0];
  12397. }
  12398. return this._inputs[i];
  12399. }
  12400. output(i) {
  12401. if (i === undefined) {
  12402. torch._C.AT_ASSERT(this._outputs.length === 1);
  12403. return this._outputs[0];
  12404. }
  12405. return this._outputs[i];
  12406. }
  12407. hasUses() {
  12408. for (const o of this.outputs()) {
  12409. if (o.uses().length > 0) {
  12410. return true;
  12411. }
  12412. }
  12413. return false;
  12414. }
  12415. blocks() {
  12416. return this._blocks;
  12417. }
  12418. insertInput(i, value) {
  12419. torch._C.AT_ASSERT(this._graph === value.owningGraph());
  12420. this._op = null;
  12421. for (let use_itr = i; use_itr < this._inputs.length; use_itr++) {
  12422. const use = this.findUseForInput(use_itr);
  12423. use.offset += 1;
  12424. }
  12425. this._inputs.splice(i, 0, value);
  12426. value._uses.push(new torch.Use(this, i));
  12427. return value;
  12428. }
  12429. addInput(value) {
  12430. torch._C.AT_ASSERT(this._graph === value.owningGraph());
  12431. this._op = null;
  12432. const use = new torch.Use(this, this._inputs.length);
  12433. value.uses().push(use);
  12434. this._inputs.push(value);
  12435. return value;
  12436. }
  12437. addOutput() {
  12438. const value = new torch.Value(this, this._outputs.length);
  12439. this._outputs.push(value);
  12440. return value;
  12441. }
  12442. addBlock() {
  12443. this._op = null;
  12444. this._blocks.push(new torch.Block(this.owningGraph(), this));
  12445. return this._blocks[this._blocks.length - 1];
  12446. }
  12447. get prev() {
  12448. return this._prev;
  12449. }
  12450. set prev(value) {
  12451. this._prev = value;
  12452. }
  12453. get next() {
  12454. return this._next;
  12455. }
  12456. set next(value) {
  12457. this._next = value;
  12458. }
  12459. insertBefore(n) {
  12460. if (!n.inBlockList()) {
  12461. throw new python.Error('Node not in block.');
  12462. }
  12463. this.insertAfter(n.prev);
  12464. return this;
  12465. }
  12466. insertAfter(n) {
  12467. torch._C.AT_ASSERT(!this.inBlockList() || n.inBlockList());
  12468. torch._C.AT_ASSERT(n.owningBlock());
  12469. torch._C.TORCH_INTERNAL_ASSERT(n.kind() !== 'prim::Return');
  12470. this._owning_block = n.owningBlock();
  12471. const next = n.next;
  12472. n.next = this;
  12473. this.prev = n;
  12474. this.next = next;
  12475. next.prev = this;
  12476. // this.assignTopoPosition();
  12477. return this;
  12478. }
  12479. allocNewInstance(g) {
  12480. return new torch.Node(g, this.kind());
  12481. }
  12482. cloneFrom(s) {
  12483. this._source_range = s._source_range;
  12484. if (s._scope && !s._scope.isBlank()) {
  12485. this._scope = s._scope;
  12486. }
  12487. this.copyAttributes(s);
  12488. this._callstack = s._callstack;
  12489. }
  12490. copyAttributes(rhs) {
  12491. this._values = new Map(rhs._values);
  12492. return this;
  12493. }
  12494. dropInput(i) {
  12495. torch._C.AT_ASSERT(i < this._inputs.length);
  12496. const input_node = this._inputs[i];
  12497. const use_it = this.findUseForInput(i);
  12498. input_node._uses = input_node._uses.filter((use) => use !== use_it);
  12499. this._inputs[i] = null;
  12500. return input_node;
  12501. }
  12502. eraseOutput(i) {
  12503. torch._C.AT_ASSERT(i < this._outputs.length);
  12504. // torch._C.AT_ASSERT(this._outputs[i].uses().length === 0);
  12505. this._op = null;
  12506. const n = this._outputs[i];
  12507. this._outputs.splice(i, 1);
  12508. this.owningGraph().freeValue(n);
  12509. for (let j = i; j < this._outputs.length; j++) {
  12510. this._outputs[j]._offset--;
  12511. }
  12512. }
  12513. eraseBlock(i) {
  12514. this._op = null;
  12515. const n = this._blocks[i];
  12516. this._blocks.splice(i, 1);
  12517. n.destroy();
  12518. }
  12519. findUseForInput(i) {
  12520. const input_uses = this._inputs[i]._uses;
  12521. for (const use_it of input_uses) {
  12522. if (use_it.user === this && use_it.offset === i) {
  12523. return use_it;
  12524. }
  12525. }
  12526. throw new python.Error('Input use not found.');
  12527. }
  12528. moveBefore(n) {
  12529. this.removeFromList();
  12530. this.insertBefore(n);
  12531. }
  12532. removeInput(i) {
  12533. this._op = null;
  12534. this.dropInput(i);
  12535. for (let j = i + 1; j < this._inputs.length; j++) {
  12536. const it = this.findUseForInput(j);
  12537. it.offset--;
  12538. }
  12539. this._inputs.splice(i, 1);
  12540. }
  12541. removeAllInputs() {
  12542. this._op = null;
  12543. for (let i = 0; i < this._inputs.length; i++) {
  12544. this.dropInput(i);
  12545. }
  12546. this._inputs = [];
  12547. }
  12548. inBlockList() {
  12549. return this.next !== null;
  12550. }
  12551. removeFromList() {
  12552. this._owning_block = null;
  12553. const next = this.next;
  12554. const prev = this.prev;
  12555. prev.next = next;
  12556. next.prev = prev;
  12557. this.next = null;
  12558. this.prev = null;
  12559. }
  12560. destroy() {
  12561. while (this.outputs().length > 0) {
  12562. this.eraseOutput(this.outputs().length - 1);
  12563. }
  12564. while (this.blocks().length > 0) {
  12565. this.eraseBlock(this.blocks().length - 1);
  12566. }
  12567. this.removeAllInputs();
  12568. if (this.inBlockList()) {
  12569. this.removeFromList();
  12570. }
  12571. this._graph.freeNode(this);
  12572. }
  12573. replaceAllUsesWith(n) {
  12574. torch._C.AT_ASSERT(this.outputs().length === n.outputs().length);
  12575. const nOutputs = this.outputs().length;
  12576. for (let i = 0; i < nOutputs; i++) {
  12577. this.outputs()[i].replaceAllUsesWith(n.outputs()[i]);
  12578. }
  12579. }
  12580. s_(name, value) {
  12581. this._values.set(name, [value, 's']);
  12582. return this;
  12583. }
  12584. s(name) {
  12585. return this._values.get(name)[0];
  12586. }
  12587. ss_(name, value) {
  12588. this._values.set(name, [value, 'ss']);
  12589. return this;
  12590. }
  12591. ss(name) {
  12592. return this._values.get(name)[0];
  12593. }
  12594. i_(name, value) {
  12595. this._values.set(name, [value, 'i']);
  12596. return this;
  12597. }
  12598. i(name) {
  12599. return this._values.get(name)[0];
  12600. }
  12601. f_(name, value) {
  12602. this._values.set(name, [value, 'f']);
  12603. return this;
  12604. }
  12605. f(name) {
  12606. return this._values.get(name)[0];
  12607. }
  12608. c_(name, value) {
  12609. this._values.set(name, [value, 'c']);
  12610. return this;
  12611. }
  12612. c(name) {
  12613. return this._values.get(name)[0];
  12614. }
  12615. t_(name, value) {
  12616. this._values.set(name, [value, 't']);
  12617. return this;
  12618. }
  12619. t(name) {
  12620. return this._values.get(name)[0];
  12621. }
  12622. tys_(name, value) {
  12623. this._values.set(name, [value, 'tys']);
  12624. return this;
  12625. }
  12626. tys(name) {
  12627. return this._values.get(name)[0];
  12628. }
  12629. ival_(name, value) {
  12630. this._values.set(name, [value, 'ival']);
  12631. return this;
  12632. }
  12633. ival(name) {
  12634. return this._values.get(name)[0];
  12635. }
  12636. hasAttribute(name) {
  12637. return this._values.has(name);
  12638. }
  12639. hasAttributes() {
  12640. return this._values.size > 0;
  12641. }
  12642. attributeNames() {
  12643. return Array.from(this._values.keys());
  12644. }
  12645. kindOf(name) {
  12646. return this._values.get(name)[1];
  12647. }
  12648. setSourceRange(r) {
  12649. torch._C.AT_ASSERT(r instanceof torch._C.SourceRange);
  12650. this._source_range = r;
  12651. return this;
  12652. }
  12653. sourceRange() {
  12654. if (this._source_range) {
  12655. return this._source_range;
  12656. }
  12657. return new torch._C.SourceRange();
  12658. }
  12659. print_attributes(out, ignore_subgraph) {
  12660. ignore_subgraph = ignore_subgraph || false;
  12661. out.write('[');
  12662. const names = this.attributeNames();
  12663. for (let i = 0; i < names.length; i++) {
  12664. const name = names[i];
  12665. if (ignore_subgraph && name === 'Subgraph') {
  12666. continue;
  12667. }
  12668. if (i > 0) {
  12669. out.write(', ');
  12670. }
  12671. out.write(`${name}=`);
  12672. this.printAttrValue(out, name);
  12673. }
  12674. out.write(']');
  12675. }
  12676. printTypeList(out, items) {
  12677. out.write('[');
  12678. for (let i = 0; i < items.length; i++) {
  12679. const item = items[i];
  12680. if (i++ > 0) {
  12681. out.write(', ');
  12682. }
  12683. out.write(item.str());
  12684. }
  12685. out.write(']');
  12686. }
  12687. printAttrValue(out, name) {
  12688. const kind = this.kindOf(name);
  12689. switch (kind) {
  12690. case 'c': case 'cs': case 'f': case 'fs': case 'i': case 'is':
  12691. case 'ss': case 'ival': case 'ty':
  12692. out.write(this[kind](name));
  12693. break;
  12694. case 's':
  12695. out.write(`"${this.s(name)}"`);
  12696. break;
  12697. case 't':
  12698. out.write(`"{}"`);
  12699. break;
  12700. case 'ts': out.write('[<Tensors>]'); break;
  12701. case 'g': out.write('[<Graph>]'); break;
  12702. case 'gs': out.write('[<Graphs>]'); break;
  12703. case 'tys': this.printTypeList(out, this.tys(name)); break;
  12704. default: throw new python.Error(`Unknown attribute kind '${kind}'.`);
  12705. }
  12706. }
  12707. print(out, level, groups, print_source_locations, print_attributes, print_scopes, print_body) {
  12708. print_source_locations = print_source_locations === false ? false : true;
  12709. print_attributes = print_attributes === false ? false : true;
  12710. print_scopes = print_scopes === false ? false : true;
  12711. print_body = print_body === false ? false : true;
  12712. const outs = this.outputs();
  12713. torch._C.indent(out, level);
  12714. torch._C.const_value_list_with_types(out, outs, ', ');
  12715. out.write(' = ');
  12716. if (this.kind() === 'prim::PythonOp') {
  12717. throw new python.Error('Not implemented.');
  12718. } else if (this.hasAttribute('Subgraph') && groups) {
  12719. throw new python.Error('Not implemented.');
  12720. } else {
  12721. out.write(this.kind());
  12722. if (print_attributes && this.hasAttributes()) {
  12723. this.print_attributes(out);
  12724. }
  12725. }
  12726. out.write('(');
  12727. torch._C.printValueRefs(out, this.inputs());
  12728. out.write(')');
  12729. if (print_scopes) {
  12730. //
  12731. }
  12732. if (print_source_locations) {
  12733. let r = this.sourceRange();
  12734. if (r.source()) {
  12735. const orig = this.sourceRange().source().findSourceRangeThatGenerated(r);
  12736. if (orig) {
  12737. r = orig;
  12738. }
  12739. }
  12740. const file_line_col = r.file_line_col();
  12741. if (file_line_col !== null) {
  12742. const [filename, line, col] = file_line_col;
  12743. out.write(` # ${filename}:${line}:${col}`);
  12744. }
  12745. }
  12746. if (!print_body) {
  12747. return out;
  12748. }
  12749. out.write('\n');
  12750. for (let i = 0; i < this.blocks().length; i++) {
  12751. const b = this.blocks().at(i);
  12752. torch._C.indent(out, level + 1);
  12753. out.write(`block${i}(`);
  12754. torch._C.const_value_list_with_types(out, b.inputs());
  12755. out.write('):\n');
  12756. for (const nested of b.nodes()) {
  12757. nested.print(out, level + 2, groups);
  12758. }
  12759. torch._C.indent(out, level + 2);
  12760. out.write('-> (');
  12761. torch._C.printValueRefs(out, b.outputs());
  12762. out.write(')\n');
  12763. }
  12764. return out;
  12765. }
  12766. toString() {
  12767. const out = new io.StringIO();
  12768. this.print(out, 0, true);
  12769. return out.toString();
  12770. }
  12771. });
  12772. this.registerType('torch.Value', class {
  12773. constructor(node, offset) {
  12774. this._node = node;
  12775. this._offset = offset;
  12776. this._unique = node._graph._next_unique++;
  12777. this._uses = [];
  12778. this._node._graph.all_values.add(this);
  12779. }
  12780. unique() {
  12781. return this._unique;
  12782. }
  12783. node() {
  12784. return this._node;
  12785. }
  12786. owningGraph() {
  12787. return this._node.owningGraph();
  12788. }
  12789. uses() {
  12790. return this._uses;
  12791. }
  12792. hasUses() {
  12793. return this._uses.length > 0;
  12794. }
  12795. mustBeNone() {
  12796. return this.type() instanceof torch.NoneType || this._node.mustBeNone();
  12797. }
  12798. mustNotBeNone() {
  12799. return this._node.kind() !== 'prim::AutogradAdd' &&
  12800. this.type() !== torch.NoneType.get() &&
  12801. !(this.type() instanceof torch.OptionalType) &&
  12802. !(this.type() instanceof torch.UnionType && this.type().expect(torch.UnionType).canHoldType(torch.NoneType.get()));
  12803. }
  12804. isValidName(name) {
  12805. if (name.length === 0) {
  12806. return true;
  12807. }
  12808. if (torch._C.isNumber(name)) {
  12809. return false;
  12810. }
  12811. return true;
  12812. }
  12813. hasDebugName() {
  12814. return this._unique_name && this._unique_name.length > 0;
  12815. }
  12816. setDebugName(name) {
  12817. if (!this.isValidName(name)) {
  12818. throw new python.Error(`Invalid name '${name}'.`);
  12819. }
  12820. const names = this.node().owningGraph()._unique_names;
  12821. if (this.hasDebugName()) {
  12822. names.delete(this._unique_name);
  12823. this._unique_name = '';
  12824. }
  12825. if (!name) {
  12826. return this;
  12827. }
  12828. const old_owner_of_name = names.get(name);
  12829. if (old_owner_of_name) {
  12830. let suffix = 1;
  12831. let name_base = name;
  12832. const last_dot_pos = name.lastIndexOf('.');
  12833. if (last_dot_pos !== -1) {
  12834. if (/^\d+$/.test(name.substring(last_dot_pos + 1))) {
  12835. suffix = Number(name.substring(last_dot_pos + 1));
  12836. name_base = name.substring(0, last_dot_pos);
  12837. }
  12838. }
  12839. const names_suffixes = this.node().owningGraph()._name_base_suffix;
  12840. if (names_suffixes.has(name_base)) {
  12841. suffix = Math.max(suffix, names_suffixes.get(name_base));
  12842. }
  12843. let replacement_name = null;
  12844. do {
  12845. replacement_name = `${name_base}.${suffix++}`;
  12846. } while (names.has(replacement_name));
  12847. names_suffixes.set(name_base, suffix);
  12848. old_owner_of_name.setDebugName(replacement_name);
  12849. }
  12850. names.set(name, this);
  12851. this._unique_name = name;
  12852. return this;
  12853. }
  12854. debugName() {
  12855. if (this.hasDebugName()) {
  12856. return this._unique_name;
  12857. }
  12858. return this.unique().toString();
  12859. }
  12860. type() {
  12861. return this._type;
  12862. }
  12863. setType(type) {
  12864. // torch._C.AT_ASSERT(type instanceof torch.Type);
  12865. if (type instanceof torch._C.DynamicType) {
  12866. type = type.fallback();
  12867. }
  12868. this._type = type;
  12869. for (const use of this._uses) {
  12870. use.user._op = null;
  12871. }
  12872. return this;
  12873. }
  12874. set value(value) { // remove
  12875. if (value instanceof torch.Value) {
  12876. throw new python.Error('Value cannot be a value.');
  12877. }
  12878. this._value = value;
  12879. }
  12880. get value() { // remove
  12881. return this._value;
  12882. }
  12883. replaceFirstUseWith(newValue) {
  12884. torch._C.AT_ASSERT(this.owningGraph() === newValue.owningGraph());
  12885. const [u] = this.uses();
  12886. u.user._inputs[u.offset] = newValue;
  12887. newValue._uses.push(u);
  12888. this._uses.shift();
  12889. }
  12890. replaceAllUsesWith(newValue) {
  12891. while (this.uses().length > 0) {
  12892. this.replaceFirstUseWith(newValue);
  12893. }
  12894. }
  12895. copyMetadata(from) {
  12896. this.setType(from.type());
  12897. if (from.hasDebugName()) {
  12898. this.setDebugName(from.debugName());
  12899. }
  12900. return this;
  12901. }
  12902. toString() {
  12903. return `${this.debugName()} : ${this.type().toString()}`;
  12904. }
  12905. });
  12906. this.registerType('torch.Use', class {
  12907. constructor(user, offset) {
  12908. this.user = user;
  12909. this.offset = offset;
  12910. }
  12911. });
  12912. this.registerType('torch._C.IValue', class {
  12913. constructor(value, tag) {
  12914. this.value = value;
  12915. if (tag) {
  12916. this.tag = tag;
  12917. } else if (value === undefined) {
  12918. this.tag = 'None';
  12919. this.value = null;
  12920. } else if (typeof value === 'boolean') {
  12921. this.tag = 'Bool';
  12922. } else if (typeof value === 'string') {
  12923. this.tag = 'String';
  12924. } else if (value instanceof torch.Tensor) {
  12925. this.tag = 'Tensor';
  12926. } else if (value instanceof torch.ScriptObject) {
  12927. this.tag = 'Object';
  12928. } else if (Array.isArray(value)) {
  12929. this.tag = 'GenericList';
  12930. } else if (value instanceof torch._C.Tuple) {
  12931. this.tag = 'Tuple';
  12932. } else if (value instanceof torch.device) {
  12933. this.tag = 'Device';
  12934. } else if (Number.isInteger(value)) {
  12935. this.tag = 'Int';
  12936. } else if (typeof value === 'number') {
  12937. this.tag = 'Double';
  12938. } else if (value instanceof builtins.complex) {
  12939. this.tag = 'ComplexDouble';
  12940. } else if (value instanceof torch._C.EnumHolder) {
  12941. this.tag = 'Enum';
  12942. } else {
  12943. throw new python.Error('Unsupported type.');
  12944. }
  12945. }
  12946. isNone() {
  12947. return this.tag === 'None';
  12948. }
  12949. isBool() {
  12950. return this.tag === 'Bool';
  12951. }
  12952. toBool() {
  12953. return this.value;
  12954. }
  12955. isObject() {
  12956. return this.tag === 'Object';
  12957. }
  12958. toObject() {
  12959. return this.value;
  12960. }
  12961. isTensor() {
  12962. return this.tag === 'Tensor';
  12963. }
  12964. toTensor() {
  12965. return this.value;
  12966. }
  12967. isDouble() {
  12968. return this.tag === 'Double';
  12969. }
  12970. toDouble() {
  12971. return this.value;
  12972. }
  12973. isComplexDouble() {
  12974. return this.tag === 'ComplexDouble' || this.tag === 'Complex';
  12975. }
  12976. toComplexDouble() {
  12977. return this.value;
  12978. }
  12979. isInt() {
  12980. return this.tag === 'Int';
  12981. }
  12982. toInt() {
  12983. if (this.isInt()) {
  12984. return this.value;
  12985. } else if (this.isSymInt()) {
  12986. return this.toSymInt().guard_int(/* __FILE__, __LINE__ */);
  12987. }
  12988. throw new python.Error('Expected int.');
  12989. }
  12990. isString() {
  12991. return this.tag === 'String';
  12992. }
  12993. toStringRef() {
  12994. return this.value;
  12995. }
  12996. isList() {
  12997. return this.tag === 'GenericList';
  12998. }
  12999. toList() {
  13000. return this.value;
  13001. }
  13002. toListRef() {
  13003. return this.value;
  13004. }
  13005. isBoolList() {
  13006. return this.value instanceof torch._C.List && this.value.elementType() instanceof torch.BoolType;
  13007. }
  13008. isIntList() {
  13009. return this.value instanceof torch._C.List && this.value.elementType() instanceof torch.IntType;
  13010. }
  13011. isDoubleList() {
  13012. return this.value instanceof torch._C.List && this.value.elementType() instanceof torch.FloatType;
  13013. }
  13014. isDevice() {
  13015. return this.tag === 'Device';
  13016. }
  13017. toDevice() {
  13018. return this.value;
  13019. }
  13020. isGenerator() {
  13021. return this.tag === 'Generator';
  13022. }
  13023. isStream() {
  13024. return this.tag === 'Stream';
  13025. }
  13026. isGenericDict() {
  13027. return this.tag === 'GenericDict';
  13028. }
  13029. isEnum() {
  13030. return this.tag === 'Enum';
  13031. }
  13032. toEnumHolder() {
  13033. return this.value;
  13034. }
  13035. isTuple() {
  13036. return this.tag === 'Tuple';
  13037. }
  13038. toTupleRef() {
  13039. return this.value;
  13040. }
  13041. isCustomClass() {
  13042. return torch._C.isCustomClass(this);
  13043. }
  13044. equals(rhs) {
  13045. switch (this.tag) {
  13046. case 'None': return rhs.isNone();
  13047. case 'Bool': return rhs.isBool() && this.toBool() === rhs.toBool();
  13048. case 'Int': return rhs.isInt() && this.toInt() === rhs.toInt();
  13049. case 'Double': return rhs.isDouble() && this.toDouble() === rhs.toDouble();
  13050. case 'String': return rhs.isString() && this.toString() === rhs.toString();
  13051. case 'Tensor': return rhs.isTensor() && this.toTensor() === rhs.toTensor();
  13052. case 'Object': return rhs.isObject() && this.toObject() === rhs.toObject();
  13053. case 'Device': return rhs.isObject() && this.toDevice() === rhs.toDevice();
  13054. case 'GenericList': {
  13055. if (rhs.isList()) {
  13056. const a = this.toList();
  13057. const b = rhs.toList();
  13058. return (a.length === b.length) && a.every((v, i) => v === b[i]);
  13059. }
  13060. return false;
  13061. }
  13062. default: throw new python.Error(`IValue.equals() not implemented for '${this.tag}.`);
  13063. }
  13064. }
  13065. is(rhs) {
  13066. return this.equals(rhs);
  13067. }
  13068. type() {
  13069. switch (this.tag) {
  13070. case 'None': return torch.NoneType.get();
  13071. case 'Bool': return torch.BoolType.get();
  13072. case 'Int': return torch.IntType.get();
  13073. case 'Double': return torch.FloatType.get();
  13074. case 'String': return torch.StringType.get();
  13075. case 'Device': return torch.DeviceObjType.get();
  13076. case 'Tuple': return torch.TupleType.create(this.value.elements().map((ivalue) => ivalue.type()));
  13077. case 'Enum': return this.toEnumHolder().type();
  13078. case 'GenericList': return torch.ListType.create(this.toList().elementType());
  13079. default: throw new python.Error(`IValue.type('${this.tag}') not implemented.`);
  13080. }
  13081. }
  13082. });
  13083. this.registerFunction('torch._C.indent', (out, level) => {
  13084. for (let i = 0; i < level; i++) {
  13085. out.write(' ');
  13086. }
  13087. return out;
  13088. });
  13089. this.registerFunction('torch._C.printValueRef', (out, n) => {
  13090. out.write(`%${n.debugName()}`);
  13091. });
  13092. this.registerFunction('torch._C.printValueRefs', (out, nodes) => {
  13093. for (let i = 0; i < nodes.length; i++) {
  13094. const n = nodes[i];
  13095. if (i > 0) {
  13096. out.write(', ');
  13097. }
  13098. torch._C.printValueRef(out, n);
  13099. }
  13100. return out;
  13101. });
  13102. this.registerFunction('torch._C.const_value_list_with_types', (out, values, delim) => {
  13103. for (let i = 0; i < values.length; i++) {
  13104. const n = values[i];
  13105. if (i > 0) {
  13106. out.write(delim);
  13107. }
  13108. torch._C.printValueRef(out, n);
  13109. out.write(' : ');
  13110. out.write(n.type().str());
  13111. }
  13112. });
  13113. this.register('torch.jit._script');
  13114. this.register('torch.jit._trace');
  13115. this.registerType('torch._C.Parser', class {
  13116. constructor(source) {
  13117. this.L = source;
  13118. }
  13119. parse() {
  13120. const p = ast.parse(this.L.text_str(), this.L.filename());
  13121. return p;
  13122. }
  13123. parseExp() {
  13124. const expr = ast.parse(this.L.text_str());
  13125. return expr.body[0].value;
  13126. }
  13127. });
  13128. this.registerType('torch._C.StringCordView', class {
  13129. });
  13130. this.registerType('torch._C.Source', class {
  13131. constructor(text_view, filename, starting_line_no, gen_ranges /*, copies_str */) {
  13132. if (text_view instanceof Uint8Array) {
  13133. const decoder = new TextDecoder('utf-8');
  13134. this._text_view = decoder.decode(text_view);
  13135. } else if (typeof text_view === 'string') {
  13136. this._text_view = text_view;
  13137. } else {
  13138. throw new python.Error('Invalid text view.');
  13139. }
  13140. this._filename = filename;
  13141. this._starting_line_no = starting_line_no;
  13142. this._gen_ranges = gen_ranges;
  13143. this.calc_line_start_offsets();
  13144. }
  13145. text_str() {
  13146. return this._text_view;
  13147. }
  13148. size() {
  13149. return this._text_view.length;
  13150. }
  13151. filename() {
  13152. return this._filename;
  13153. }
  13154. calc_line_start_offsets() {
  13155. let pos = 0;
  13156. this._line_starting_offsets = [0];
  13157. while ((pos = this._text_view.indexOf('\n', pos)) !== -1) {
  13158. pos += 1;
  13159. this._line_starting_offsets.push(pos);
  13160. }
  13161. }
  13162. offset_for_line(line) {
  13163. return this._line_starting_offsets[line];
  13164. }
  13165. lineno_for_offset(offset) {
  13166. const iter = this._line_starting_offsets.findIndex((value) => value > offset);
  13167. return (iter === -1 ? this._line_starting_offsets.length : iter) - 1;
  13168. }
  13169. lineno_to_source_lineno(lineno) {
  13170. if (this._filename) {
  13171. return lineno + this._starting_line_no;
  13172. }
  13173. return lineno;
  13174. }
  13175. findSourceRangeThatGenerated(range) {
  13176. if (!this._gen_ranges) {
  13177. return null;
  13178. }
  13179. return this._gen_ranges.findSourceRangeThatGenerated(range);
  13180. }
  13181. });
  13182. this.registerType('torch._C.SourceRange', class {
  13183. constructor(...args) {
  13184. if (args.length === 0) {
  13185. this._source_view = null;
  13186. } else if (args.length === 2) {
  13187. let node = null;
  13188. [this._source_view, node] = args;
  13189. this._start = this._source_view.offset_for_line(node.lineno - 1) + (node.col_offset - 1);
  13190. this._end = this._source_view.offset_for_line(node.end_lineno - 1) + (node.end_col_offset - 1);
  13191. } else if (args.length === 3) {
  13192. [this._source_view, this._start, this._end] = args;
  13193. } else {
  13194. throw new python.Error('Not implemented.');
  13195. }
  13196. }
  13197. source() {
  13198. return this._source_view;
  13199. }
  13200. file_line_col() {
  13201. if (!this._source_view || this.source().filename() === null) {
  13202. return null;
  13203. }
  13204. const lineno = this._source_view.lineno_for_offset(this._start);
  13205. const col_offset = this._start - this._source_view.offset_for_line(lineno);
  13206. return [this._source_view.filename(), this._source_view.lineno_to_source_lineno(lineno), col_offset];
  13207. }
  13208. start() {
  13209. return this._start;
  13210. }
  13211. toString() {
  13212. const loc = this.file_line_col();
  13213. return loc ? `${loc[0]}:${loc[1]}:${loc[2]}` : '';
  13214. }
  13215. });
  13216. this.registerType('torch._C.QualifiedName', class {
  13217. constructor(...args) {
  13218. let name = null;
  13219. if (args.length === 1 && typeof args[0] === 'string') {
  13220. [name] = args;
  13221. } else if (args.length === 1 && Array.isArray(args[0]) && args[0].every((arg) => typeof arg === 'string')) {
  13222. name = args[0].join('.');
  13223. } else {
  13224. name = `${args[0].qualifiedName()}.${args[1]}`;
  13225. }
  13226. const index = name.lastIndexOf('.');
  13227. this._qualifiedName = name;
  13228. this._prefix = index === -1 ? '' : name.substring(0, index);
  13229. this._name = index === -1 ? name : name.substring(index + 1);
  13230. }
  13231. qualifiedName() {
  13232. return this._qualifiedName; // "foo.bar.baz"
  13233. }
  13234. prefix() {
  13235. return this._prefix; // "foo.bar"
  13236. }
  13237. name() {
  13238. return this._name; // "baz"
  13239. }
  13240. atoms() {
  13241. return this._qualifiedName.split('.');
  13242. }
  13243. });
  13244. this.registerType('torch._C.Resolver', class {
  13245. resolveValue() {
  13246. throw new python.Error('Not implemented.');
  13247. }
  13248. resolveType() {
  13249. throw new python.Error('Not implemented.');
  13250. }
  13251. });
  13252. this.registerFunction('torch._C.registerCustomClass', (class_type) => {
  13253. torch._C.customClasses = torch._C.customClasses || new Map();
  13254. torch._C.TORCH_INTERNAL_ASSERT(class_type.name());
  13255. const name = class_type.name().qualifiedName();
  13256. torch._C.TORCH_CHECK(!torch._C.customClasses.has(name));
  13257. torch._C.customClasses.set(name, class_type);
  13258. });
  13259. this.registerFunction('torch._C.getCustomClass', (class_name) => {
  13260. torch._C.customClasses = torch._C.customClasses || new Map();
  13261. const ret = torch._C.customClasses.has(class_name) ? torch._C.customClasses.get(class_name) : null;
  13262. return ret;
  13263. });
  13264. this.registerFunction('torch._C.isCustomClass', (v) => {
  13265. return v.isObject() && v.toObject().type().name() && torch._C.getCustomClass(v.toObject().type().name().qualifiedName());
  13266. });
  13267. this.registerType('torch._C.SourceImporter', class extends torch._C.Resolver {
  13268. constructor(cu, constant_table, source_loader, version) {
  13269. super();
  13270. this._cu = cu;
  13271. this._constant_table = constant_table;
  13272. this._source_loader = source_loader;
  13273. this._version = version;
  13274. this._loaded_sources = new Set();
  13275. this._sources = new Map();
  13276. const sources = this._sources;
  13277. ast.AST.prototype.range = function() {
  13278. if (!this._range) {
  13279. if (sources.has(this.filename)) {
  13280. const source_view = sources.get(this.filename);
  13281. this._range = new torch._C.SourceRange(source_view, this);
  13282. } else {
  13283. this._range = new torch._C.SourceRange();
  13284. }
  13285. }
  13286. return this._range;
  13287. };
  13288. this._to_be_defined = new Map();
  13289. this._env = new Map([
  13290. ['torch', new torch._C.BuiltinModule('aten', version)],
  13291. ['ops', new torch._C.OpsValue(version)],
  13292. ['CONSTANTS', new torch._C.ConstantTableValue(constant_table)],
  13293. ['fork', torch._C.SpecialFormValue.create('prim::fork')],
  13294. ['awaitable', torch._C.SpecialFormValue.create('prim::awaitable')],
  13295. ['annotate', torch._C.SpecialFormValue.create('prim::annotate')],
  13296. ['unchecked_cast', torch._C.SpecialFormValue.create('prim::unchecked_cast')],
  13297. ['uninitialized', torch._C.SpecialFormValue.create('prim::Uninitialized')],
  13298. ]);
  13299. }
  13300. loadType(name) {
  13301. const type_parser = new torch._C.ScriptTypeParser(this);
  13302. return type_parser.parseType(name.qualifiedName());
  13303. }
  13304. resolveType(name) {
  13305. name = new torch._C.QualifiedName(name);
  13306. return this.findNamedType(name);
  13307. }
  13308. resolveValue(name, m, loc) {
  13309. if (this._env.has(name)) {
  13310. return this._env.get(name);
  13311. }
  13312. const graph = m.graph();
  13313. switch (name) {
  13314. case 'inf': return new torch._C.SimpleValue(graph.insertConstant(Infinity /* 'std::numeric_limits<double>::infinity()' */, loc));
  13315. case 'nan': return new torch._C.SimpleValue(graph.insertConstant(NaN /* 'std::numeric_limits<double>::quiet_NaN()' */, loc));
  13316. case 'infj': return new torch._C.SimpleValue(graph.insertConstant('c10::complex<double>(0, std::numeric_limits<double>::infinity())', loc));
  13317. case 'nanj': return new torch._C.SimpleValue(graph.insertConstant('c10::complex<double>(0, std::numeric_limits<double>::quiet_NaN()', loc));
  13318. case '__torch__': return new torch._C.ClassNamespaceValue(new torch._C.QualifiedName(name), this);
  13319. default: return null;
  13320. }
  13321. }
  13322. findNamedType(name) {
  13323. const custom_class = torch._C.getCustomClass(name.qualifiedName());
  13324. if (custom_class) {
  13325. return custom_class;
  13326. }
  13327. this.parseSourceIfNeeded(name.prefix());
  13328. const key = name.qualifiedName();
  13329. const it = this._to_be_defined.get(key);
  13330. if (it && it instanceof ast.ClassDef) {
  13331. this._to_be_defined.delete(key);
  13332. this.importNamedType(name.prefix(), it);
  13333. }
  13334. return this._cu.get_type(name);
  13335. }
  13336. importNamedType(qualifier, class_def) {
  13337. const qualified_name = new torch._C.QualifiedName(`${qualifier}.${class_def.name}`);
  13338. if (class_def.bases.length === 0) {
  13339. this.importClass(qualified_name, class_def, false);
  13340. return;
  13341. }
  13342. const superclass_name = class_def.bases[0].id;
  13343. if (superclass_name === 'Module') {
  13344. this.importClass(qualified_name, class_def, true);
  13345. } else if (superclass_name === 'NamedTuple') {
  13346. this.importNamedTuple(qualified_name, class_def);
  13347. } else if (superclass_name === 'Interface') {
  13348. // this._cu.define_interface(qualified_name, class_def, shared_from_this(), is_module=false);
  13349. } else if (superclass_name === 'ModuleInterface') {
  13350. // this._cu.define_interface(qualified_name, class_def, shared_from_this(), is_module=true);
  13351. } else if (superclass_name === 'Enum') {
  13352. this.importEnum(qualified_name, class_def);
  13353. } else {
  13354. throw new python.Error('TorchScript does not support class inheritance.');
  13355. }
  13356. }
  13357. importClass(qualified_classname, class_def, is_module) {
  13358. if (qualified_classname.prefix().startsWith('__torch__.torch.classes')) {
  13359. return;
  13360. }
  13361. const parameter_names = new Set();
  13362. const buffer_names = new Set();
  13363. const methods = [];
  13364. const method_resolvers = [];
  13365. const attributes = [];
  13366. const constants = [];
  13367. const pre_hook_names = new Set();
  13368. const pre_hook_def_map = new Map();
  13369. const hook_names = new Set();
  13370. const hook_def_map = new Map();
  13371. const class_type = torch.ClassType.create(qualified_classname.qualifiedName(), this._cu, is_module);
  13372. for (const stmt of class_def.body) {
  13373. if (stmt instanceof ast.Assign || stmt instanceof ast.AnnAssign) {
  13374. let target = null;
  13375. let annotation = null;
  13376. let value = null;
  13377. if (stmt instanceof ast.Assign) {
  13378. [target] = stmt.targets;
  13379. value = stmt.value;
  13380. } else {
  13381. target = stmt.target;
  13382. annotation = stmt.annotation;
  13383. value = stmt.value;
  13384. }
  13385. if (target instanceof ast.Name) {
  13386. const name = this._cu.execution.identifier(target);
  13387. switch (name) {
  13388. case '__annotations__': {
  13389. continue;
  13390. }
  13391. case '__parameters__': {
  13392. for (const elt of value.elts) {
  13393. parameter_names.add(elt.value);
  13394. }
  13395. break;
  13396. }
  13397. case '__buffers__': {
  13398. for (const elt of value.elts) {
  13399. buffer_names.add(elt.value);
  13400. }
  13401. break;
  13402. }
  13403. case '__forward_pre_hooks__': {
  13404. for (const elt of value.elts) {
  13405. pre_hook_names.add(elt.value);
  13406. }
  13407. break;
  13408. }
  13409. case '__forward_hooks__': {
  13410. for (const elt of value.elts) {
  13411. hook_names.add(elt.value);
  13412. }
  13413. break;
  13414. }
  13415. default: {
  13416. const fixed_up = this.attributeAssignmentSpecialHandlingHack(qualified_classname, stmt);
  13417. if (fixed_up) {
  13418. attributes.push({ name: fixed_up.target.id, value: fixed_up.value, annotation: fixed_up.annotation });
  13419. } else if (value) {
  13420. constants.push({ name, value, annotation });
  13421. } else {
  13422. attributes.push({ name, value, annotation });
  13423. }
  13424. break;
  13425. }
  13426. }
  13427. } else if (target instanceof ast.Subscript && target.value instanceof ast.Name && target.value.id === '__annotations__') {
  13428. const name = target.slice.value;
  13429. attributes.push({ name, value, annotation: stmt.value });
  13430. continue;
  13431. } else {
  13432. throw new python.Error('Unexpected statement kind in module metadata.');
  13433. }
  13434. } else if (stmt instanceof ast.FunctionDef) {
  13435. const def = stmt;
  13436. const def_name = def.name;
  13437. if (pre_hook_names.has(def_name)) {
  13438. pre_hook_def_map.set(def_name, def);
  13439. } else if (hook_names.has(def_name)) {
  13440. hook_def_map.set(def_name, def);
  13441. } else {
  13442. methods.push(def);
  13443. method_resolvers.push(this);
  13444. }
  13445. } else {
  13446. throw new python.Error('Unexpected statement kind in class body.');
  13447. }
  13448. }
  13449. const type_parser = new torch._C.ScriptTypeParser(this);
  13450. for (const assign of attributes) {
  13451. const name = assign.name;
  13452. const annotation = type_parser.parseTypeFromExpr(assign.annotation);
  13453. const is_parameter = parameter_names.has(name);
  13454. const is_buffer = buffer_names.has(name);
  13455. class_type.addAttribute(name, annotation, is_parameter, is_buffer);
  13456. }
  13457. for (const constant of constants) {
  13458. class_type.addConstant(constant.name, constant.value);
  13459. }
  13460. this._cu.register_type(class_type);
  13461. const self = new torch._C.SimpleSelf(class_type);
  13462. this._cu.define(qualified_classname, [], [], methods, method_resolvers, self, false, this._version);
  13463. }
  13464. importEnum(qualified_name, enum_def) {
  13465. const names_values = [];
  13466. let value_type = null;
  13467. const set_or_check_type = (t) => {
  13468. if (!value_type) {
  13469. value_type = t;
  13470. } else if (value_type !== t) {
  13471. throw new python.Error('Enum class with varying value types are not supported.');
  13472. }
  13473. };
  13474. for (const stmt of enum_def.body) {
  13475. if (stmt instanceof ast.Assign === false) {
  13476. throw new python.Error('Unexpected statement in Enum class body.');
  13477. }
  13478. const assign = stmt;
  13479. const name = assign.targets[0].id;
  13480. let ivalue = null;
  13481. const rhs = assign.value;
  13482. switch (rhs.type) {
  13483. case 'str':
  13484. ivalue = new torch._C.IValue(rhs.value, 'String');
  13485. set_or_check_type(torch.StringType.get());
  13486. break;
  13487. case 'int':
  13488. ivalue = new torch._C.IValue(rhs.value, 'Int');
  13489. set_or_check_type(torch.IntType.get());
  13490. break;
  13491. case 'float':
  13492. ivalue = new torch._C.IValue(rhs.value, 'Double');
  13493. set_or_check_type(torch.FloatType.get());
  13494. break;
  13495. default:
  13496. throw new python.Error(`Unsupported enum value type '${rhs.type}'.`);
  13497. }
  13498. names_values.push([name, ivalue]);
  13499. }
  13500. if (!value_type) {
  13501. throw new python.Error('No enum values defined.');
  13502. }
  13503. const enum_type = torch.EnumType.create(qualified_name, value_type, names_values, this._cu);
  13504. this._cu.register_type(enum_type);
  13505. }
  13506. importNamedTuple(qualified_name, named_tuple_def) {
  13507. const type_parser = new torch._C.ScriptTypeParser(this);
  13508. const field_names = [];
  13509. const field_types = [];
  13510. const field_defaults = [];
  13511. for (const stmt of named_tuple_def.body) {
  13512. if (stmt instanceof ast.AnnAssign === false) {
  13513. throw new python.Error('Unexpected statement in NamedTuple body.');
  13514. }
  13515. const assign = stmt;
  13516. const target = this._cu.execution.identifier(stmt.target);
  13517. // const annotation = this._cu.execution.type(stmt.annotation);
  13518. const type = type_parser.parseTypeFromExpr(assign.annotation);
  13519. field_names.push(target);
  13520. // field_types.push(annotation);
  13521. field_types.push(type);
  13522. }
  13523. const tt = torch.TupleType.createNamed(qualified_name.qualifiedName(), field_names, field_types, field_defaults);
  13524. this._cu.register_type(tt);
  13525. }
  13526. importFunction(qualifier, def) {
  13527. const definitions = [def];
  13528. const resolvers = [this];
  13529. this._cu.define(new torch._C.QualifiedName(qualifier), /*properties=*/[], /*propResolvers=*/[], definitions, resolvers, null);
  13530. }
  13531. parseSourceIfNeeded(qualifier) {
  13532. if (!qualifier || this._loaded_sources.has(qualifier)) {
  13533. return;
  13534. }
  13535. this._loaded_sources.add(qualifier);
  13536. const src = this._source_loader(qualifier);
  13537. if (!src) {
  13538. return;
  13539. }
  13540. this._sources.set(src.filename(), src);
  13541. const p = new torch._C.Parser(src);
  13542. const L = p.parse();
  13543. this.parsePossibleVersionNumber(p);
  13544. for (const stmt of L.body) {
  13545. if (stmt instanceof ast.ClassDef) {
  13546. const name = `${qualifier}.${stmt.name}`;
  13547. this._to_be_defined.set(name, stmt);
  13548. } else if (stmt instanceof ast.FunctionDef) {
  13549. const name = `${qualifier}.${stmt.name}`;
  13550. this._to_be_defined.set(name, stmt);
  13551. }
  13552. }
  13553. }
  13554. parsePossibleVersionNumber(/* p */) {
  13555. }
  13556. parseImports(/* p */) {
  13557. }
  13558. attributeAssignmentSpecialHandlingHack(qualified_classname, assign) {
  13559. const replacements = new Map([
  13560. ['__torch__.torch.ao.nn.quantized.modules.linear.LinearPackedParams', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  13561. ['__torch__.torch.ao.nn.quantized.modules.linear.Linear', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  13562. ['__torch__.torch.ao.nn.quantized.dynamic.modules.linear.Linear', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  13563. ['__torch__.torch.ao.nn.quantized.modules.conv.Conv2d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv2dPackedParamsBase']],
  13564. ['__torch__.torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv2dPackedParamsBase']],
  13565. ['__torch__.torch.ao.nn.quantized.modules.conv.Conv3d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv3dPackedParamsBase']],
  13566. ['__torch__.torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU3d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv3dPackedParamsBase']],
  13567. ['__torch__.torch.nn.quantized.modules.linear.LinearPackedParams', ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]],
  13568. ["__torch__.torch.nn.quantized.modules.linear.Linear", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]],
  13569. ["__torch__.torch.nn.quantized.modules.conv.Conv2d", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.Conv2dPackedParamsBase"]],
  13570. ["__torch__.torch.nn.quantized.modules.conv.Conv3d", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.Conv3dPackedParamsBase"]],
  13571. ["__torch__.torch.nn.quantized.dynamic.modules.linear.Linear", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]]
  13572. ]);
  13573. const mangleRe = /\.___torch_mangle_\d+/g;
  13574. const demangled_classname = qualified_classname.qualifiedName().replace(mangleRe, '');
  13575. if (replacements.has(demangled_classname)) {
  13576. const lhs = assign.target;
  13577. if (!assign.annotation || assign.annotation instanceof ast.Name === false) {
  13578. return null;
  13579. }
  13580. const type = assign.annotation.id;
  13581. const [attr_name, expected_type, replacement_type] = replacements.get(demangled_classname);
  13582. if (lhs.id === attr_name && type === expected_type) {
  13583. const p = new torch._C.Parser(new torch._C.Source(replacement_type));
  13584. const typename_expr = p.parseExp();
  13585. return new ast.AnnAssign(lhs, typename_expr, assign.value, lhs instanceof ast.Name);
  13586. }
  13587. }
  13588. return null;
  13589. }
  13590. LEGACY_import_methods(mod, src) {
  13591. const self = new torch._C.SimpleSelf(mod.type());
  13592. const prefix = mod.type().name();
  13593. const p = new torch._C.Parser(src);
  13594. const L = p.parse();
  13595. this.parsePossibleVersionNumber(L);
  13596. this.parseImports(L);
  13597. const definitions = [];
  13598. const resolvers = [];
  13599. for (const def of L.body) {
  13600. if (def instanceof ast.FunctionDef) {
  13601. definitions.push(def);
  13602. resolvers.push(this);
  13603. }
  13604. }
  13605. this._cu.define(prefix, /*properties=*/[], /*propResolvers=*/[], definitions, resolvers, self);
  13606. }
  13607. findFunction(name) {
  13608. this.parseSourceIfNeeded(name.prefix());
  13609. const key = name.qualifiedName();
  13610. const it = this._to_be_defined.get(key);
  13611. if (it && it instanceof ast.FunctionDef) {
  13612. this._to_be_defined.delete(key);
  13613. this.importFunction(name.prefix(), it);
  13614. }
  13615. return this._cu.find_function(name);
  13616. }
  13617. });
  13618. this.registerType('torch._C.FunctionResolver', class extends torch._C.Resolver {
  13619. constructor(otherResolver, functionTable) {
  13620. super();
  13621. this._otherResolver = otherResolver;
  13622. this._functionTable = functionTable;
  13623. }
  13624. resolveValue(name, m, loc) {
  13625. const it = this._functionTable.get(name);
  13626. if (it) {
  13627. return new torch._C.FunctionValue(it);
  13628. }
  13629. return this._otherResolver.resolveValue(name, m, loc);
  13630. }
  13631. resolveType(name, loc) {
  13632. return this._otherResolver.resolveType(name, loc);
  13633. }
  13634. });
  13635. this.registerType('torch._C.SourceRangeDeserializer', class {
  13636. constructor(text_table) {
  13637. this.cached_sources = new Map();
  13638. this._text_table = text_table || [];
  13639. }
  13640. deserialize(iv) {
  13641. torch._C.TORCH_INTERNAL_ASSERT(iv.length === 3);
  13642. const [file, start, end] = iv;
  13643. const source = this.deserialize_source(file);
  13644. return new torch._C.SourceRange(source, start, end);
  13645. }
  13646. deserialize_source(iv) {
  13647. const tup = iv;
  13648. if (this.cached_sources.has(tup)) {
  13649. return this.cached_sources.get(tup);
  13650. }
  13651. let source = null;
  13652. const tup_elems = tup;
  13653. torch._C.TORCH_INTERNAL_ASSERT(tup_elems.length === 3);
  13654. if (this._text_table.length > 0) {
  13655. const [textIndex, fnameIndex, starting_line_no] = tup_elems;
  13656. torch._C.TORCH_CHECK(fnameIndex < this._text_table.length);
  13657. const filename = this._text_table[fnameIndex];
  13658. const pieces = [];
  13659. const strs = [];
  13660. for (const i of textIndex) {
  13661. pieces.push(this._text_table[i]);
  13662. strs.push(this._text_table[i]);
  13663. }
  13664. // const str_cord = new torch._C.StringCordView(pieces, strs);
  13665. source = new torch._C.Source(pieces.join(''), filename, starting_line_no);
  13666. } else {
  13667. const [text, filename, starting_line_no] = tup_elems;
  13668. source = new torch._C.Source(text, filename, starting_line_no);
  13669. }
  13670. this.cached_sources.set(tup, source);
  13671. return source;
  13672. }
  13673. });
  13674. this.registerType('torch._C.SourceRangeUnpickler', class {
  13675. });
  13676. this.registerType('torch._C.ConcreteSourceRangeUnpickler', class extends torch._C.SourceRangeUnpickler {
  13677. constructor (data) {
  13678. super();
  13679. this.data = data;
  13680. this.deserializer = null;
  13681. this.unpickled_records = null;
  13682. }
  13683. unpickle() {
  13684. if (this.unpickled_records) {
  13685. return;
  13686. }
  13687. const unpickler = new pickle.Unpickler(this.data);
  13688. const ivalues = unpickler.load();
  13689. torch._C.TORCH_CHECK(ivalues.length > 0);
  13690. this.unpickled_records = [];
  13691. let lines = null;
  13692. if (ivalues[0] === 'FORMAT_WITH_STRING_TABLE') {
  13693. this.deserializer = new torch._C.SourceRangeDeserializer(ivalues[1]);
  13694. lines = ivalues[2];
  13695. } else {
  13696. this.deserializer = new torch._C.SourceRangeDeserializer();
  13697. lines = ivalues;
  13698. }
  13699. for (const tup_elems of lines) {
  13700. const [offset, range] = tup_elems;
  13701. const source_range = this.deserializer.deserialize(range);
  13702. this.unpickled_records.push([offset, source_range]);
  13703. }
  13704. }
  13705. findSourceRangeThatGenerated(range) {
  13706. this.unpickle();
  13707. const start = range.start();
  13708. const records = this.unpickled_records;
  13709. for (let i = 0; i < records.length; i++) {
  13710. const [offset, target] = records[i];
  13711. const next = i < records.length - 1 ? records[i + 1][0] : range.source().size();
  13712. if (start >= offset && start < next) {
  13713. return target;
  13714. }
  13715. }
  13716. return null;
  13717. }
  13718. });
  13719. this.registerFunction('torch._C.qualifierToArchivePath', (qualifier, export_prefix) => {
  13720. return `${export_prefix}${qualifier.replace(/\./g, '/')}.py`;
  13721. });
  13722. this.registerFunction('torch._C.findSourceInArchiveFromQualifier', (reader, export_prefix, qualifier) =>{
  13723. const path = torch._C.qualifierToArchivePath(qualifier, export_prefix);
  13724. if (!reader.has_record(path)) {
  13725. return null;
  13726. }
  13727. const stream = reader.get_record(path);
  13728. let gen_ranges = null;
  13729. const debug_file = `${path}.debug_pkl`;
  13730. if (reader.has_record(debug_file)) {
  13731. const debug_stream = reader.get_record(debug_file);
  13732. gen_ranges = new torch._C.ConcreteSourceRangeUnpickler(debug_stream.peek());
  13733. }
  13734. return new torch._C.Source(stream.peek(), path, 1, gen_ranges);
  13735. });
  13736. this.registerType('torch._C.ScriptModuleDeserializer', class {
  13737. constructor(cu, reader, pickle_dir_prefix, tensor_dir_prefix, storage_context) {
  13738. this._compilation_unit = cu;
  13739. this._reader = reader;
  13740. this._storage_context = storage_context;
  13741. this._code_prefix = !pickle_dir_prefix && !tensor_dir_prefix ? 'code/' : '.data/ts_code/code/';
  13742. this._pickle_dir_prefix = pickle_dir_prefix || '';
  13743. this._tensor_dir_prefix = tensor_dir_prefix || '';
  13744. this._constant_table = [];
  13745. const SourceLoader = (qualifier) => {
  13746. return torch._C.findSourceInArchiveFromQualifier(this._reader, this._code_prefix, qualifier);
  13747. };
  13748. this._source_importer = new torch._C.SourceImporter(this._compilation_unit, this._constant_table, SourceLoader, reader.version());
  13749. }
  13750. deserialize() {
  13751. const execution = this._compilation_unit.execution;
  13752. const code_prefix = this._code_prefix;
  13753. for (const name of this._reader.get_all_records()) {
  13754. if (name.startsWith(code_prefix) && name.endsWith('.py')) {
  13755. const file = name.substring(code_prefix.length);
  13756. const stream = this._reader.get_record(name);
  13757. const buffer = stream.peek();
  13758. execution.add(file, buffer);
  13759. }
  13760. }
  13761. const torch = execution.import('torch');
  13762. execution.builtins.torch = torch;
  13763. execution.builtins.Tensor = torch.Tensor;
  13764. execution.builtins.ops = torch.ops;
  13765. execution.builtins.inf = torch.inf;
  13766. execution.builtins.CONSTANTS = {};
  13767. execution._resolver = this._source_importer;
  13768. if (this._reader.has_record('model.json')) {
  13769. return this.LEGACY_deserialize();
  13770. }
  13771. const constants = this.readArchive('constants');
  13772. for (let i = 0; i < constants.length; i++) {
  13773. let val = constants[i];
  13774. if (val && val.__class__ && val.__class__.__module__.startsWith('__torch__.torch.classes.')) {
  13775. const type = this._source_importer.resolveType(`${val.__class__.__module__}.${val.__class__.__name__}`);
  13776. const obj = torch.ScriptObject.create(type);
  13777. obj._ivalue = val;
  13778. val = obj;
  13779. }
  13780. execution.builtins.CONSTANTS[`c${i}`] = val;
  13781. this._constant_table.push(val);
  13782. }
  13783. const obj = this.readArchive('data');
  13784. const convertObject = (obj) => {
  13785. if (obj.__class__) {
  13786. const name = `${obj.__class__.__module__}.${obj.__class__.__name__}`;
  13787. const type = this._source_importer.loadType(new torch._C.QualifiedName(name));
  13788. const module = type.is_module() ? new torch.ScriptModule(type, this._compilation_unit) : new torch.ScriptObject(type);
  13789. for (let i = 0; i < type.numAttributes(); i++) {
  13790. const k = type.getAttributeName(i);
  13791. const t = type.getAttribute(i);
  13792. const v = obj[k];
  13793. if (t instanceof torch.ClassType) {
  13794. module.__setattr__(k, convertObject(v));
  13795. } else {
  13796. if (t instanceof torch.TensorType && v && v.__class__ && v instanceof torch.Tensor === false && v.__class__.__module__ === '__torch__.torch.classes.quantized') {
  13797. const name = `${v.__class__.__module__}.${v.__class__.__name__}`;
  13798. type._attributes[i].type = this._source_importer.resolveType(name);
  13799. }
  13800. module.__setattr__(k, obj[k]);
  13801. }
  13802. }
  13803. for (const [key, value] of Object.entries(Object.getPrototypeOf(obj))) {
  13804. if (value && value.__class__ === builtins.method) {
  13805. module[key] = value;
  13806. }
  13807. }
  13808. return module;
  13809. }
  13810. throw new python.Error('Module class not found.');
  13811. };
  13812. return convertObject(obj);
  13813. }
  13814. LEGACY_deserialize() {
  13815. // https://github.com/pytorch/pytorch/blob/5e69e11d098a2cfccc8a59377c431e9c71cab9a8/torch/csrc/jit/serialization/import_legacy.cpp#L88
  13816. const execution = this._compilation_unit.execution;
  13817. const caffe2 = execution.proto.caffe2;
  13818. const torch = execution.import('torch');
  13819. const stream = this._reader.get_record('model.json');
  13820. const buffer = stream.peek();
  13821. const decoder = new TextDecoder('utf-8');
  13822. const content = decoder.decode(buffer);
  13823. const obj = JSON.parse(content);
  13824. const model = execution.proto.torch.ModelDef.decodeJson(obj);
  13825. const tensorTypeMap = new Map([
  13826. [caffe2.TensorProto.DataType.FLOAT, 'Float'],
  13827. [caffe2.TensorProto.DataType.FLOAT16, 'Half'],
  13828. [caffe2.TensorProto.DataType.DOUBLE, 'Double'],
  13829. [caffe2.TensorProto.DataType.INT8, 'Char'],
  13830. [caffe2.TensorProto.DataType.INT32, 'Int'],
  13831. [caffe2.TensorProto.DataType.INT64, 'Long']
  13832. ]);
  13833. const tensor_table = (model.tensors || []).map((constant) => {
  13834. const key = constant.data.key;
  13835. if (!tensorTypeMap.has(constant.data_type)) {
  13836. throw new python.Error(`Unsupported tensor data type '${constant.data_type}'.`);
  13837. }
  13838. const type = tensorTypeMap.get(constant.data_type);
  13839. const shape = constant.dims ? constant.dims.map((dim) => parseInt(dim, 10)) : null;
  13840. const strides = constant.strides ? constant.strides.map((dim) => parseInt(dim, 10)) : null;
  13841. const storage_type = execution.resolve(`torch.${type}Storage`);
  13842. const size = (shape || []).reduce((a, b) => a * b, 1);
  13843. const offset = parseInt(constant.offset, 10) || 0;
  13844. const storage = new storage_type(size);
  13845. const itemsize = storage.dtype.itemsize();
  13846. const stream = this._reader.get_record(key);
  13847. if (stream) {
  13848. const buffer = stream.peek();
  13849. const length = size * itemsize;
  13850. const data = buffer.slice(offset, offset + length);
  13851. storage._set_cdata(data);
  13852. }
  13853. const tensor = torch._utils._rebuild_tensor(storage, 0, shape, strides);
  13854. tensor.name = key;
  13855. return tensor;
  13856. });
  13857. execution.builtins.CONSTANTS = {};
  13858. for (let i = 0; i < tensor_table.length; i++) {
  13859. execution.builtins.CONSTANTS[`c${i}`] = tensor_table[i];
  13860. }
  13861. const attributes = [];
  13862. if (this._reader.has_record('attributes.pkl')) {
  13863. const stream = this._reader.get_record('attributes.pkl');
  13864. const buffer = stream.peek();
  13865. const unpickler = new pickle.Unpickler(buffer);
  13866. const obj = unpickler.load();
  13867. attributes.push(...obj);
  13868. }
  13869. this._LEGACY_moduleStack = ['__torch__'];
  13870. const module_def = model.main_module;
  13871. for (const tensor of tensor_table) {
  13872. this._constant_table.push(tensor);
  13873. }
  13874. return this.LEGACY_convertModule(module_def);
  13875. }
  13876. LEGACY_convertModule(module_def) {
  13877. const atoms = new torch._C.QualifiedName(module_def.name).atoms();
  13878. const numPushed = atoms.length;
  13879. for (const atom of atoms) {
  13880. const sanitized = /^\d+$/.test(atom) ? `_${atom}` : atom;
  13881. this._LEGACY_moduleStack.push(sanitized);
  13882. }
  13883. const qn = new torch._C.QualifiedName(this._LEGACY_moduleStack);
  13884. const module = new torch.ScriptModule(qn, this._compilation_unit);
  13885. for (const sub_def of module_def.submodules || []) {
  13886. const submodule = this.LEGACY_convertModule(sub_def);
  13887. module.register_module(sub_def.name, submodule);
  13888. }
  13889. for (const param_def of module_def.parameters || []) {
  13890. const tensor = this._constant_table[Number(param_def.tensor_id)];
  13891. if (param_def.isBuffer) {
  13892. module.register_buffer(param_def.name, tensor);
  13893. } else {
  13894. module.register_parameter(param_def.name, tensor, false);
  13895. }
  13896. }
  13897. // const typeParser = new torch._C.ScriptTypeParser(this._source_importer);
  13898. for (const attr_def of module_def.attributes || []) {
  13899. if (module.hasattr(attr_def.name)) {
  13900. continue;
  13901. }
  13902. throw new python.Error('Not implemented.');
  13903. // IValue ivalue;
  13904. // if (attr_def.id() >= 0) {
  13905. // ivalue = LEGACY_pickled_ivalues_.at(attr_def.id());
  13906. // }
  13907. // module.register_attribute(attr_def.name, typeParser.parseType(attr_def.type), ivalue);
  13908. }
  13909. if (module_def.torchscript_arena) {
  13910. const key = module_def.torchscript_arena.key;
  13911. const file = key.substring('code/'.length);
  13912. const name = file.replace(/\.py$/, '').split('/').join('.');
  13913. const code = execution.import(name);
  13914. if (code.forward.__class__ === execution.builtins.function) {
  13915. module.forward = code.forward;
  13916. }
  13917. }
  13918. // let gen_ranges = null;
  13919. if (module_def.torchscript_debug_arena) {
  13920. throw new python.Error('Not implemented.');
  13921. //const [data, size] = reader_->getRecord(module_def.torchscript_debug_arena().key());
  13922. //gen_ranges = std::make_shared<ConcreteSourceRangeUnpickler>(std::move(data), size);
  13923. }
  13924. if (module_def.torchscript_arena) {
  13925. const filename = module_def.torchscript_arena.key;
  13926. const stream = this._reader.get_record(filename);
  13927. const data = stream.peek();
  13928. const src = new torch._C.Source(data, filename);
  13929. this._source_importer.LEGACY_import_methods(module, src);
  13930. }
  13931. if (module_def.get_state_attribute_id) {
  13932. throw new python.Error('Not implemented.');
  13933. // LEGACY_moduleSetState(module, LEGACY_pickled_ivalues_.at(module_def.get_state_attribute_id()));
  13934. }
  13935. /*
  13936. const module_type = module._ivalue().type();
  13937. const N = module_type.numAttributes();
  13938. for (let i = 0; i < N; ++i) {
  13939. const v = module._ivalue().getSlot(i);
  13940. if (module_type.getAttribute(i) instanceof torch.OptionalType === false) {
  13941. torch._C.TORCH_CHECK(!v.isNone());
  13942. }
  13943. }
  13944. */
  13945. for (let i = 0; i < numPushed; i++) {
  13946. this._LEGACY_moduleStack.pop();
  13947. }
  13948. return module;
  13949. }
  13950. readArchive(archive_name) {
  13951. const type_resolver = (qn) => {
  13952. const cls = this._source_importer.loadType(qn);
  13953. return cls;
  13954. };
  13955. const ObjLoaderFunc = (/* type, ivalue */) => {
  13956. };
  13957. return this.readArchiveAndTensors(archive_name, this._pickle_dir_prefix, this._tensor_dir_prefix, type_resolver, ObjLoaderFunc, this._device, this._reader, null, this._storage_context);
  13958. }
  13959. readArchiveAndTensors(archive_name, pickle_prefix, tensor_prefix, type_resolver, obj_loader, device, stream_reader, type_parser, storage_context) {
  13960. const picklename = `${pickle_prefix + archive_name}.pkl`;
  13961. const stream = stream_reader.get_record(picklename);
  13962. if (!stream) {
  13963. throw new python.Error(`File '${picklename}' is not found.`);
  13964. }
  13965. const buffer = stream.peek();
  13966. const tensor_dir_path = tensor_prefix ? tensor_prefix : `${archive_name}/`;
  13967. const read_record = (name) => {
  13968. const stream = stream_reader.get_record(tensor_dir_path + name);
  13969. return stream.length <= 0x40000 ? stream.peek() : stream;
  13970. };
  13971. const execution = this._compilation_unit.execution;
  13972. const pickle = execution.__import__('pickle');
  13973. const Unpickler = class extends pickle.Unpickler {
  13974. find_class(module, name) {
  13975. return super.find_class(module, name);
  13976. }
  13977. };
  13978. const unpickler = new Unpickler(buffer);
  13979. unpickler.persistent_load = (saved_id) => {
  13980. if (saved_id[0] !== 'storage') {
  13981. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  13982. }
  13983. const [, storage_type, key, , size] = saved_id;
  13984. if (storage_context && storage_context.has_storage(key)) {
  13985. return storage_context.get_storage(key);
  13986. }
  13987. const storage = new storage_type(size);
  13988. if (!storage._set_cdata) {
  13989. throw new python.Error(`'${storage_type.__name__}._set_cdata' is not a function.`);
  13990. }
  13991. const storage_ptr = read_record(key);
  13992. storage._set_cdata(storage_ptr);
  13993. if (storage_context) {
  13994. storage_context.add_storage(key);
  13995. }
  13996. return storage;
  13997. };
  13998. return unpickler.load();
  13999. }
  14000. });
  14001. this.registerType('torch._C.WithInsertPoint', class {
  14002. constructor(...args) {
  14003. let n = null;
  14004. if (args.length === 1 && args[0] instanceof torch.Block) {
  14005. const [b] = args;
  14006. n = b.return_node();
  14007. } else if (args.length === 1 && args[0] instanceof torch.Node) {
  14008. [n] = args;
  14009. } else {
  14010. throw new python.Error('Invalid arguments.');
  14011. }
  14012. this._prev = n.owningGraph().insertPoint();
  14013. n.owningGraph().setInsertPoint(n);
  14014. }
  14015. dispose() {
  14016. this._prev.owningGraph().setInsertPoint(this._prev);
  14017. }
  14018. });
  14019. this.registerType('torch._C.Environment', class {
  14020. constructor(method, resolver, b, next) {
  14021. this.method = method;
  14022. this.resolver = resolver;
  14023. this.b = b;
  14024. this.next = next;
  14025. this.value_table = new Map();
  14026. this.type_table = new Map();
  14027. this.error_messages = new Map();
  14028. }
  14029. setVariableTypeError(name, msg) {
  14030. /* eslint-disable consistent-this */
  14031. let runner = this;
  14032. /* eslint-enable consistent-this */
  14033. while (runner.next) {
  14034. runner = runner.next;
  14035. }
  14036. runner.error_messages.set(name, msg);
  14037. }
  14038. insertLoad(name, type) {
  14039. const g = this.b.owningGraph();
  14040. const load = g.insertNode(g.createLoad(name, type));
  14041. if (torch._C.meaningfulName(name)) {
  14042. load.output().setDebugName(name);
  14043. }
  14044. return new torch._C.SimpleValue(load.output());
  14045. }
  14046. insertStore(name, loc, v, type) {
  14047. const g = this.b.owningGraph();
  14048. g.insertNode(g.createStore(name, v)).setSourceRange(loc);
  14049. this.type_table.set(name, type);
  14050. }
  14051. findInThisFrame(name) {
  14052. if (this.value_table.has(name)) {
  14053. return this.value_table.get(name);
  14054. }
  14055. if (this.type_table.has(name)) {
  14056. return this.insertLoad(name, this.type_table.get(name));
  14057. }
  14058. return null;
  14059. }
  14060. findInParentFrame(name) {
  14061. return this.next ? this.next.findInAnyFrame(name) : null;
  14062. }
  14063. setType(name, type) {
  14064. this.type_table.set(name, type);
  14065. }
  14066. findInAnyFrame(name) {
  14067. /* eslint-disable consistent-this */
  14068. const self = this;
  14069. /* eslint-enable consistent-this */
  14070. for (let runner = self; runner; runner = runner.next) {
  14071. const r = runner.findInThisFrame(name);
  14072. if (r) {
  14073. return r;
  14074. }
  14075. }
  14076. return null;
  14077. }
  14078. block() {
  14079. return this.b;
  14080. }
  14081. setVar(loc, name, value) {
  14082. this.setSugaredVar(loc, name, new torch._C.SimpleValue(value), null);
  14083. }
  14084. setSugaredVar(loc, name, value, annotated_type) {
  14085. let as_simple_value = torch._C.asSimple(value);
  14086. if (as_simple_value && !as_simple_value.hasDebugName() && torch._C.meaningfulName(name) && as_simple_value.node().owningBlock() === this.block()) {
  14087. as_simple_value.setDebugName(name);
  14088. }
  14089. const parent = this.findInParentFrame(name);
  14090. if (parent) {
  14091. if (annotated_type) {
  14092. throw new python.Error('Type already defined in an outer block.');
  14093. }
  14094. if (!as_simple_value) {
  14095. throw new python.Error('Only reassignments to first-class values are allowed.');
  14096. }
  14097. const simple_parent = torch._C.asSimple(parent);
  14098. if (!simple_parent) {
  14099. throw new python.Error('Only reassignments to first-class values are allowed.');
  14100. }
  14101. const parent_type = torch._C.unshapedType(simple_parent.type());
  14102. as_simple_value = torch._C.tryConvertToType(loc, this.b.owningGraph(), parent_type, as_simple_value, /*allow_conversions=*/true);
  14103. if (!as_simple_value.type().isSubtypeOf(parent_type)) {
  14104. throw new python.Error('Incompatible types.');
  14105. }
  14106. }
  14107. if (as_simple_value) {
  14108. if (annotated_type && !as_simple_value.type().isSubtypeOf(annotated_type)) {
  14109. throw new python.Error('Invalid type.');
  14110. }
  14111. const value_store_type = annotated_type ? annotated_type : as_simple_value.type();
  14112. this.insertStore(name, loc, as_simple_value, value_store_type);
  14113. } else {
  14114. this.value_table.set(name, value);
  14115. }
  14116. }
  14117. getSugaredVar(ident, range, required) {
  14118. required = required || true;
  14119. let retval = this.findInAnyFrame(ident);
  14120. if (!retval) {
  14121. torch._C.Environment.globals = torch._C.Environment.globals || new Map([
  14122. ['print', new torch._C.PrintValue()],
  14123. ['tuple', torch._C.SpecialFormValue.create('prim::TupleConstruct')],
  14124. ['float', new torch._C.MagicMethod('__float__', new torch._C.CastValue(torch.FloatType.get(), 'aten::Float'))],
  14125. ['int', new torch._C.MagicMethod('__int__', new torch._C.CastValue(torch.IntType.get(), 'aten::Int'))],
  14126. ['bool', new torch._C.MagicMethod('__bool__', new torch._C.CastValue(torch.BoolType.get(), 'aten::Bool'))],
  14127. ['str', new torch._C.MagicMethod('__str__', new torch._C.CastValue(torch.StringType.get(), 'aten::str'))],
  14128. ['getattr', torch._C.SpecialFormValue.create('prim::GetAttr')],
  14129. ['hasattr', torch._C.SpecialFormValue.create('prim::HasAttr')],
  14130. ['isinstance', torch._C.SpecialFormValue.create('prim::isinstance')],
  14131. ['range', torch._C.SpecialFormValue.create('prim::range')],
  14132. ['sorted', new torch._C.BuiltinFunction('aten::sorted', null)],
  14133. ]);
  14134. if (torch._C.Environment.globals.has(ident)) {
  14135. retval = torch._C.Environment.globals.get(ident);
  14136. }
  14137. }
  14138. if (!retval) {
  14139. const type = this.resolver.resolveType(ident, range);
  14140. if (type instanceof torch.TupleType) {
  14141. retval = new torch.jit.NamedTupleConstructor(type);
  14142. }
  14143. }
  14144. if (!retval) {
  14145. retval = this.resolver.resolveValue(ident, this.method, range);
  14146. }
  14147. if (!retval) {
  14148. const type = this.resolver.resolveType(ident, range);
  14149. if (type instanceof torch.ClassType) {
  14150. retval = new torch.jit.ClassValue(type);
  14151. }
  14152. }
  14153. if (!retval && required) {
  14154. throw new python.Error(`The name '${ident}' is not defined.`);
  14155. }
  14156. return retval;
  14157. }
  14158. getVar(ident, range) {
  14159. return this.getSugaredVar(ident, range).asValue(range, this.method);
  14160. }
  14161. definedVariables() {
  14162. return Array.from(this.type_table.keys());
  14163. }
  14164. });
  14165. this.registerType('torch._C.Refinement', class {
  14166. constructor(identifier, type) {
  14167. this._identifier = identifier;
  14168. this._type = type;
  14169. }
  14170. identifier() {
  14171. return this._identifier;
  14172. }
  14173. type() {
  14174. return this._type;
  14175. }
  14176. });
  14177. this.registerType('torch._C.RefinementSet', class {
  14178. constructor(...args) {
  14179. if (args.length === 1 && args[0] instanceof torch._C.Refinement) {
  14180. this._true_refinements = [args[0]];
  14181. this._false_refinements = [];
  14182. } else if (args.length === 2 && args[0] instanceof torch._C.Refinement && args[1] instanceof torch._C.Refinement) {
  14183. this._true_refinements = [args[0]];
  14184. this._false_refinements = [args[1]];
  14185. } else if (args.length === 2 && Array.isArray(args[0]) && Array.isArray(args[1])) {
  14186. [this._true_refinements, this._false_refinements] = args;
  14187. } else {
  14188. throw new python.Error('Not implemented.');
  14189. }
  14190. }
  14191. Not() {
  14192. return new torch._C.RefinementSet(this._false_refinements, this._true_refinements);
  14193. }
  14194. activeRefinements() {
  14195. return this._true_refinements;
  14196. }
  14197. });
  14198. this.registerFunction('torch._C.CondValue', class {
  14199. constructor(...args) {
  14200. if (args.length === 3) {
  14201. [this._value, this._refinements, this._static_if] = args;
  14202. } else if (args.length === 4) {
  14203. const [g, loc, static_value, refinements] = args;
  14204. this._value = g.insertConstant(static_value, loc);
  14205. this._refinements = refinements;
  14206. this._static_if = static_value;
  14207. } else {
  14208. throw new python.Error('Invalid number of arguments.');
  14209. }
  14210. }
  14211. value() {
  14212. return this._value;
  14213. }
  14214. staticIf() {
  14215. return this._static_if;
  14216. }
  14217. refinements() {
  14218. return this._refinements;
  14219. }
  14220. });
  14221. this.registerFunction('torch._C.asSimple', (value) => {
  14222. if (value instanceof torch._C.SimpleValue) {
  14223. return value.getValue();
  14224. }
  14225. return null;
  14226. });
  14227. this.registerFunction('torch._C.isNumber', (str) => {
  14228. return /^[0-9]+$/.test(str);
  14229. });
  14230. this.registerFunction('torch._C.normalizeAttrName', (field) => {
  14231. if (torch._C.isNumber(field)) {
  14232. return `_${field}`;
  14233. }
  14234. return field;
  14235. });
  14236. this.registerFunction('torch._C.meaningfulName', (name) => {
  14237. if (name.length === 0) {
  14238. return false;
  14239. }
  14240. if (name[0] === '$') {
  14241. return false;
  14242. }
  14243. if (name[0] !== '_') {
  14244. return true;
  14245. }
  14246. return !/\d+/.test(name.slice(1));
  14247. });
  14248. this.registerFunction('torch._C.materializeConstant', (val, graph, r, map) => {
  14249. const key = `${val.value}:${val.tag}`;
  14250. const existing_constant = map.get(key);
  14251. if (existing_constant) {
  14252. return existing_constant;
  14253. }
  14254. const guard = new torch._C.WithInsertPoint(graph.block().nodes().front());
  14255. const new_constant = graph.insertConstant(val, r);
  14256. map.set(key, new_constant);
  14257. guard.dispose();
  14258. return new_constant;
  14259. });
  14260. this.registerFunction('torch._C.getFullSchemaName', (schema) => {
  14261. if (schema.overload_name) {
  14262. return `${schema.name}.${schema.overload_name}`;
  14263. }
  14264. return schema.name;
  14265. });
  14266. this.registerFunction('torch._C.insertGraph', (g, callee, inputs, value_map) => {
  14267. const value_map_func = (v) => value_map.get(v);
  14268. torch._C.AT_ASSERT(callee.inputs().length === inputs.length);
  14269. for (let i = 0; i < inputs.length; i++) {
  14270. value_map.set(callee.inputs()[i], inputs[i]);
  14271. }
  14272. for (const node of callee.nodes()) {
  14273. const new_node = g.insertNode(g.createClone(node, value_map_func));
  14274. for (let i = 0; i < node.outputs().length; i++) {
  14275. value_map.set(node.outputs()[i], new_node.outputs()[i]);
  14276. }
  14277. }
  14278. const outputs = [];
  14279. for (const output of callee.outputs()) {
  14280. outputs.push(value_map_func(output));
  14281. }
  14282. return outputs;
  14283. });
  14284. this.registerType('TemplateEnv', class {
  14285. });
  14286. this.registerType('torch._C.BuiltinFunctionRegistry', class {
  14287. constructor() {
  14288. this.state = 'UNINITIALIZED';
  14289. this._builtins_by_name = new Map();
  14290. }
  14291. getAllBuiltinFunctionsFor(name) {
  14292. if (this.state === 'UNINITIALIZED') {
  14293. this.loadBuiltinFunctions();
  14294. this.state = 'INITIALIZED';
  14295. }
  14296. if (!this._builtins_by_name.has(name)) {
  14297. return [];
  14298. }
  14299. return this._builtins_by_name.get(name);
  14300. }
  14301. loadBuiltinFunctions() {
  14302. /*
  14303. for (const scalar of ['float', 'int', 'complex']) {
  14304. const env = new torch.C.TemplateEnv();
  14305. env.s('Scalar', scalar);
  14306. this.loadSource(scalar_operators_source.format(env), 'aten');
  14307. }
  14308. for (const scalar of ['float', 'int']) {
  14309. const env = new torch.C.TemplateEnv();
  14310. env.s('Scalar', scalar);
  14311. loadSource(scalar_operators_no_complex_source.format(env), 'aten');
  14312. }
  14313. using str_pair = std::pair<std::string, std::string>;
  14314. const std::vector<str_pair> name_len = {
  14315. str_pair('single', '1'),
  14316. str_pair('pair', '2'),
  14317. str_pair('triple', '3'),
  14318. str_pair('quadruple', '4'),
  14319. };
  14320. for (const auto scalar : {'float', 'int'}) {
  14321. for (const auto& pair : name_len) {
  14322. const env = new torch.C.TemplateEnv();
  14323. env.s('Scalar', scalar);
  14324. env.s('name', pair.first);
  14325. env.s('Length', pair.second);
  14326. this.loadSource(_ntuple_ops.format(env), 'aten');
  14327. }
  14328. }
  14329. for (auto rhs : {'number', 'Tensor'}) {
  14330. at::jit::TemplateEnv env;
  14331. env.s('Rhs_Type', rhs);
  14332. this.loadSource(floordiv.format(env), 'aten');
  14333. }
  14334. this.loadSource(aten_ops, 'aten');
  14335. this.loadSource(aten_ops_additional, 'aten');
  14336. this.loadSource(tensor_properties, 'prim');
  14337. */
  14338. }
  14339. loadSource(/* source, the_namespace */) {
  14340. }
  14341. });
  14342. this.registerFunction('torch._C.getAllBuiltinFunctionsFor', (name) => {
  14343. torch._C.registry = torch._C.registry || new torch._C.BuiltinFunctionRegistry();
  14344. return torch._C.registry.getAllBuiltinFunctionsFor(name);
  14345. });
  14346. this.registerFunction('torch._C.get_operator_version_map', () => {
  14347. return new Map();
  14348. });
  14349. this.registerFunction('torch._C.varargsCanBeUsedAsList', (schema, arg_index, arg) => {
  14350. const is_last_argument = arg_index + 1 === schema.arguments.length || schema.arguments[arg_index + 1].kwarg_only;
  14351. let arg_type = arg.type;
  14352. if (arg_type instanceof torch._C.DynamicType) {
  14353. arg_type = arg_type.fallback();
  14354. }
  14355. const argument_is_list = arg_type instanceof torch.ListType;
  14356. const typevar_list = argument_is_list && arg_type.getElementType() instanceof torch._C.VarType;
  14357. const arg_is_broadcasting_list = arg.N > 0;
  14358. return is_last_argument && argument_is_list && !arg_is_broadcasting_list && !typevar_list;
  14359. });
  14360. this.registerFunction('torch._C.isBlockListedSchema', (schema) => {
  14361. if ((schema.name === 'aten::view' && schema.overload_name === 'dtype') ||
  14362. (schema.name === 'aten::max' && schema.overload_name === 'unary_out') ||
  14363. (schema.name === 'aten::min' && schema.overload_name === 'unary_out')) {
  14364. return true;
  14365. }
  14366. return false;
  14367. });
  14368. this.registerFunction('torch._C.unwrapOptional', (opt_type) => {
  14369. if (opt_type instanceof torch._C.DynamicType) {
  14370. return torch._C.unwrapOptional(opt_type.fallback());
  14371. }
  14372. if (opt_type instanceof torch.OptionalType) {
  14373. return opt_type.getElementType();
  14374. }
  14375. return opt_type;
  14376. });
  14377. this.registerFunction('torch._C.loadPossibleHistoricOps', (name, version) => {
  14378. const possibleSchemas = [];
  14379. if (version === undefined) {
  14380. return possibleSchemas;
  14381. }
  14382. for (const entry of torch._C.get_operator_version_map()) {
  14383. const old_symbol_name = entry.first;
  14384. const base_name = old_symbol_name.substring(0, old_symbol_name.find('.'));
  14385. if (base_name === name) {
  14386. const possibleUpgrader = torch._C.findUpgrader(entry.second, version.value());
  14387. if (possibleUpgrader.has_value()) {
  14388. possibleSchemas.push_back(possibleUpgrader.value().old_schema);
  14389. }
  14390. }
  14391. }
  14392. return possibleSchemas;
  14393. });
  14394. this.registerFunction('torch._C.isOpCurrentBasedOnUpgraderEntries', (upgraders_for_schema, current_version) => {
  14395. const latest_update = upgraders_for_schema[upgraders_for_schema.length - 1].bumped_at_version;
  14396. return current_version < latest_update;
  14397. });
  14398. this.registerFunction('torch._C.isOpSymbolCurrent', (name, current_version) => {
  14399. const it = torch._C.get_operator_version_map().get(name);
  14400. if (it) {
  14401. return torch._C.isOpCurrentBasedOnUpgraderEntries(it, current_version);
  14402. }
  14403. return true;
  14404. });
  14405. this.registerFunction('torch._C.packOutputs', (g, values, field_names) => {
  14406. if (values.length === 1) {
  14407. return values[0];
  14408. }
  14409. let named_tuple = null;
  14410. if (field_names) {
  14411. const types = values.map((v) => v.type());
  14412. named_tuple = torch.TupleType.createNamed(null, field_names.value(), types);
  14413. }
  14414. return g.insertNode(g.createTuple(values, named_tuple)).output();
  14415. });
  14416. this.registerFunction('torch._C.isIntOrFloatUsedAsList', (value, arg) => {
  14417. const v_type = value.type();
  14418. if (v_type !== torch.FloatType.get() && v_type !== torch.IntType.get()) {
  14419. return false;
  14420. }
  14421. const arg_type = torch._C.unwrapOptional(arg.type);
  14422. return arg_type instanceof torch.ListType && arg_type.getElementType() === v_type && arg.N;
  14423. });
  14424. this.registerFunction('torch._C.convertibleToList', (type, list_type_) => {
  14425. const list_type = list_type_;
  14426. if (list_type instanceof torch.ListType === false) {
  14427. return false;
  14428. }
  14429. if (type.isSubtypeOf(list_type_)) {
  14430. return true;
  14431. }
  14432. if (type instanceof torch.TupleType) {
  14433. return type.elements().every((t) => t.isSubtypeOf(list_type.getElementType()));
  14434. }
  14435. return false;
  14436. });
  14437. this.registerFunction('torch._C.findInputWithName', (name, kwargs, is_aten) => {
  14438. for (let i = 0; i < kwargs.length; i++) {
  14439. if (is_aten && name === 'self' && kwargs[i].name() === 'input') {
  14440. return i;
  14441. }
  14442. if (kwargs[i].name() === name) {
  14443. return i;
  14444. }
  14445. }
  14446. return null;
  14447. });
  14448. this.registerFunction('torch._C.tryCreateList', (elem_type, graph, loc, varargs, failure_messages, err, convert_tensor_to_num, type_env) => {
  14449. const elem_arg = new torch.Argument('<varargs>', elem_type);
  14450. const list_elements = [];
  14451. for (const named_value of varargs) {
  14452. const matched_value = torch._C.tryMatchArgument(/*arg=*/elem_arg, graph, loc, named_value, failure_messages, err, /*allow_conversions=*/convert_tensor_to_num, type_env);
  14453. if (!matched_value) {
  14454. return null;
  14455. }
  14456. list_elements.push(matched_value);
  14457. }
  14458. return graph.insertNode(graph.createList(elem_type, list_elements)).output();
  14459. });
  14460. this.registerType('torch._C.MatchTypeReturn', class {
  14461. constructor(reason) {
  14462. this._reason = reason;
  14463. }
  14464. static Success() {
  14465. return new torch._C.MatchTypeReturn(null);
  14466. }
  14467. success() {
  14468. return this._reason === null;
  14469. }
  14470. });
  14471. this.registerFunction('torch._C.matchTypeVariables', (formal, actual, type_env) => {
  14472. if (!formal.hasFreeVariables()) {
  14473. if (formal instanceof torch._C.DynamicType) {
  14474. return torch._C.matchTypeVariables(formal.fallback(), actual, type_env);
  14475. }
  14476. return torch._C.MatchTypeReturn.Success();
  14477. }
  14478. if (formal instanceof torch._C.VarType) {
  14479. const it = type_env.has(formal.name()) ? type_env.get(formal.name()) : null;
  14480. if (it === null) {
  14481. type_env.set(formal.name(), actual);
  14482. return torch._C.MatchTypeReturn.Success();
  14483. } else if (torch._C.unifyTypes(it, actual)) {
  14484. return torch._C.MatchTypeReturn.Success();
  14485. }
  14486. return new torch._C.MatchTypeReturn('Cannot match var.');
  14487. } else if (formal instanceof torch.ListType) {
  14488. if (actual instanceof torch.ListType) {
  14489. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14490. if (!innerMatch.success()) {
  14491. return innerMatch;
  14492. }
  14493. return torch._C.MatchTypeReturn.Success();
  14494. } else if (actual instanceof torch.TupleType) {
  14495. const maybe_tuple_unified = torch._C.unifyTypeList(actual.elements(), '');
  14496. if (maybe_tuple_unified) {
  14497. return torch._C.matchTypeVariables(formal.getElementType(), maybe_tuple_unified, type_env);
  14498. }
  14499. }
  14500. return new torch._C.MatchTypeReturn('Cannot match list.');
  14501. } else if (formal instanceof torch.TupleType) {
  14502. if (actual instanceof torch.TupleType) {
  14503. if (formal.elements().length !== actual.elements().length) {
  14504. return torch._C.MatchTypeReturn('Cannot match tuples of mismatched size.');
  14505. }
  14506. for (let i = 0; i < formal.elements().length; i++) {
  14507. const result = torch._C.matchTypeVariables(formal.elements()[i], actual.elements()[i], type_env);
  14508. if (!result.success()) {
  14509. return result;
  14510. }
  14511. }
  14512. return torch._C.MatchTypeReturn.Success();
  14513. }
  14514. return new torch._C.MatchTypeReturn('Cannot match tuple.');
  14515. } else if (formal instanceof torch.FutureType) {
  14516. if (actual instanceof torch.FutureType) {
  14517. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14518. if (!innerMatch.success()) {
  14519. return innerMatch;
  14520. }
  14521. return torch._C.MatchTypeReturn.Success();
  14522. }
  14523. return new torch._C.MatchTypeReturn('Cannot match future.');
  14524. } else if (formal instanceof torch.AwaitType) {
  14525. if (actual instanceof torch.AwaitType) {
  14526. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14527. if (!innerMatch.success()) {
  14528. return innerMatch;
  14529. }
  14530. return torch._C.MatchTypeReturn.Success();
  14531. }
  14532. return new torch._C.MatchTypeReturn('Cannot match await.');
  14533. } else if (formal instanceof torch.RRefType) {
  14534. if (actual instanceof torch.RRefType) {
  14535. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14536. if (!innerMatch.success()) {
  14537. return innerMatch;
  14538. }
  14539. return torch._C.MatchTypeReturn.Success();
  14540. }
  14541. return new torch._C.MatchTypeReturn('Cannot match rref.');
  14542. } else if (formal instanceof torch.OptionalType) {
  14543. if (actual instanceof torch.OptionalType) {
  14544. const optionedMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14545. if (!optionedMatch.success()) {
  14546. return optionedMatch;
  14547. }
  14548. } else if (!actual.isSubtypeOf(torch.NoneType.get())) {
  14549. return torch._C.matchTypeVariables(formal.getElementType(), actual, type_env);
  14550. }
  14551. return torch._C.MatchTypeReturn.Success();
  14552. } else if (formal instanceof torch.DictType) {
  14553. if (actual instanceof torch.DictType) {
  14554. const key_match = torch._C.matchTypeVariables(formal.getKeyType(), actual.getKeyType(), type_env);
  14555. if (!key_match.success()) {
  14556. return key_match;
  14557. }
  14558. const value_match = torch._C.matchTypeVariables(formal.getValueType(), actual.getValueType(), type_env);
  14559. if (!value_match.success()) {
  14560. return value_match;
  14561. }
  14562. return torch._C.MatchTypeReturn.Success();
  14563. }
  14564. return new torch._C.MatchTypeReturn('Cannot match dict.');
  14565. }
  14566. throw new python.Error('Unhandled free variable container.');
  14567. });
  14568. this.registerFunction('torch._C.tryMatchArgument', (arg, graph, loc, named_value, failure_messages, err, allow_conversions, type_env) => {
  14569. let value = named_value.value(graph);
  14570. if (torch._C.isIntOrFloatUsedAsList(value, arg)) {
  14571. const repeated = Array(arg.N).fill(value);
  14572. value = graph.insertNode(graph.createList(value.type(), repeated)).output();
  14573. }
  14574. const matched = torch._C.matchTypeVariables(arg.type, value.type(), type_env);
  14575. if (!matched.success()) {
  14576. if (failure_messages) {
  14577. throw new python.Error(`Could not match type ${value.type().repr_str()} to ${arg.type().repr_str()} in argument '${arg.name()}'.`);
  14578. }
  14579. return null;
  14580. }
  14581. const concrete_type = torch._C.tryEvalTypeVariables(arg.type, type_env);
  14582. if (!concrete_type) {
  14583. if (failure_messages) {
  14584. throw new python.Error(`Could not infer type for argument '${arg.name}'.`);
  14585. }
  14586. return null;
  14587. }
  14588. value = torch._C.tryConvertToType(loc, graph, concrete_type, value, allow_conversions);
  14589. if (!value.type().isSubtypeOf(concrete_type)) {
  14590. if (failure_messages) {
  14591. throw new python.Error(`Could not match type in argument '${arg.name()}'.`);
  14592. }
  14593. return null;
  14594. }
  14595. return value;
  14596. });
  14597. this.registerFunction('torch._C.tryConvertToType', (loc, graph, concrete_type, value, allow_conversions) => {
  14598. if (concrete_type instanceof torch.OptionalType) {
  14599. const op = concrete_type;
  14600. if (value.type() instanceof torch.OptionalType === false && !value.type().isSubtypeOf(torch.NoneType.get())) {
  14601. return torch._C.tryConvertToType(loc, graph, op.getElementType(), value, allow_conversions);
  14602. }
  14603. }
  14604. if (value.node().kind() === 'prim::EmptyListLiteral' && concrete_type instanceof torch.ListType) {
  14605. value = graph.insertNode(graph.createList(concrete_type.getElementType(), [])).output();
  14606. }
  14607. if (value.type() instanceof torch.TupleType) {
  14608. const value_tuple = value.type();
  14609. if (torch._C.convertibleToList(value.type(), torch._C.unwrapOptional(concrete_type))) {
  14610. const unpacked = torch._C.createTupleUnpack(value);
  14611. const elem_type = torch._C.unwrapOptional(concrete_type).expect(torch.ListType).getElementType();
  14612. value = graph.insertNode(graph.createList(elem_type, unpacked)).output();
  14613. }
  14614. if (concrete_type instanceof torch.TupleType) {
  14615. const concrete_tuple = concrete_type;
  14616. if (!value_tuple.isSubtypeOf(concrete_tuple) &&
  14617. concrete_tuple.elements().length === value_tuple.elements().length) {
  14618. const unpacked = torch._C.createTupleUnpack(value);
  14619. const converted = [];
  14620. for (let i = 0; i < concrete_tuple.elements().length; i++) {
  14621. converted.push(torch._C.tryConvertToType(loc, graph, concrete_tuple.elements()[i], unpacked[i], allow_conversions));
  14622. }
  14623. value = graph.insertNode(graph.createTuple(converted)).output();
  14624. }
  14625. }
  14626. }
  14627. if (allow_conversions) {
  14628. const value_isa_tensor = value.type().isSubtypeOf(torch.TensorType.get());
  14629. const value_equals_number = value.type() === torch.NumberType.get();
  14630. const concrete_float = concrete_type === torch.FloatType.get();
  14631. const concrete_complex = concrete_type === torch.ComplexType.get();
  14632. const concrete_int = concrete_type === torch.IntType.get();
  14633. const concrete_number = concrete_type === torch.NumberType.get();
  14634. if (value_isa_tensor) {
  14635. if (concrete_float) {
  14636. value = graph.insert('aten::FloatImplicit', [new torch._C.NamedValue(value)], [], loc);
  14637. } else if (concrete_complex) {
  14638. value = graph.insert('aten::ComplexImplicit', [new torch._C.NamedValue(value)], [], loc);
  14639. } else if (concrete_int) {
  14640. value = graph.insert('aten::IntImplicit', [new torch._C.NamedValue(value)], [], loc);
  14641. } else if (concrete_number) {
  14642. value = graph.insert('aten::ScalarImplicit', [new torch._C.NamedValue(value)], [], loc);
  14643. }
  14644. } else if (value_equals_number) {
  14645. if (concrete_float) {
  14646. value = graph.insert('aten::Float', [new torch._C.NamedValue(value)], [], loc);
  14647. } else if (concrete_complex) {
  14648. value = graph.insert('aten::Complex', [new torch._C.NamedValue(value)], [], loc);
  14649. } else if (concrete_int) {
  14650. value = graph.insert('aten::Int', [new torch._C.NamedValue(value)], [], loc);
  14651. }
  14652. } else if (value.type() === torch.BoolType.get()) {
  14653. if (concrete_float) {
  14654. value = graph.insert('aten::Float', [new torch._C.NamedValue(value)], [], loc);
  14655. } else if (concrete_int || concrete_number) {
  14656. value = graph.insert('aten::Int', [new torch._C.NamedValue(value)], [], loc);
  14657. }
  14658. }
  14659. if (value.type().isSubtypeOf(torch.StringType.get()) && concrete_type.isSubtypeOf(torch.DeviceObjType.get())) {
  14660. return graph.insert('aten::device', [new torch._C.NamedValue(value)], [], loc);
  14661. }
  14662. }
  14663. return value;
  14664. });
  14665. this.registerFunction('torch._C.tryEvalTypeVariables', (type, type_env) => {
  14666. if (!type.hasFreeVariables()) {
  14667. if (type instanceof torch._C.DynamicType) {
  14668. return torch._C.tryEvalTypeVariables(type.fallback(), type_env);
  14669. }
  14670. return type;
  14671. }
  14672. if (type instanceof torch._C.VarType) {
  14673. return type_env.get(type.annotation_str);
  14674. }
  14675. const contained = type.containedTypes();
  14676. if (contained.length === 0) {
  14677. return type;
  14678. }
  14679. const new_contained = [];
  14680. for (const t of contained) {
  14681. const r = torch._C.tryEvalTypeVariables(t, type_env);
  14682. if (!r) {
  14683. return null;
  14684. }
  14685. new_contained.push(r);
  14686. }
  14687. return type.withContained(new_contained);
  14688. });
  14689. this.registerFunction('torch._C.tryMatchSchema', (schema, loc, graph, args, kwargs, self, failure_messages, allow_conversions) => {
  14690. if (torch._C.isBlockListedSchema(schema)) {
  14691. return null;
  14692. }
  14693. const err = null;
  14694. const type_env = new Map();
  14695. const positional_inputs = [];
  14696. const used_kwarg = kwargs.map(() => false);
  14697. const is_aten = schema.name.startsWith('aten::');
  14698. let used_args = 0;
  14699. for (let schema_i = 0; schema_i < schema.arguments.length; schema_i++) {
  14700. const arg = schema.arguments[schema_i];
  14701. let actual_named_value = null;
  14702. if (arg.name === 'self' && self) {
  14703. actual_named_value = self;
  14704. self = null;
  14705. } else if (!arg.kwarg_only && used_args < args.length) {
  14706. if (allow_conversions && torch._C.varargsCanBeUsedAsList(schema, schema_i, arg)) {
  14707. const value = args[used_args].value(graph);
  14708. const actual_type = value.type();
  14709. if (actual_type instanceof torch.ListType === false && !torch._C.convertibleToList(actual_type, torch._C.unwrapOptional(arg.type))) {
  14710. const formal_type = torch._C.unwrapOptional(arg.type).expect(torch.ListType).getElementType();
  14711. const list = torch._C.tryCreateList(formal_type, graph, loc, args.slice(used_args), failure_messages, err, allow_conversions, type_env);
  14712. if (!list) {
  14713. return null;
  14714. }
  14715. used_args = args.length;
  14716. positional_inputs.push(list);
  14717. continue;
  14718. }
  14719. }
  14720. actual_named_value = args[used_args];
  14721. used_args++;
  14722. } else {
  14723. const kwarg_idx = torch._C.findInputWithName(arg.name, kwargs, is_aten);
  14724. if (Number.isInteger(kwarg_idx)) {
  14725. const nv = kwargs[kwarg_idx];
  14726. if (used_kwarg[kwarg_idx]) {
  14727. if (failure_messages) {
  14728. throw new python.Error(`Argument '${nv.name()}' specified twice in schema.`);
  14729. }
  14730. return null;
  14731. }
  14732. used_kwarg[kwarg_idx] = true;
  14733. actual_named_value = nv;
  14734. } else if (arg.has_default_value()) {
  14735. actual_named_value = new torch._C.NamedValue(arg.default_value);
  14736. } else {
  14737. if (failure_messages) {
  14738. throw new python.Error(`Argument '${arg.name}' not provided.`);
  14739. }
  14740. return null;
  14741. }
  14742. }
  14743. const positional = torch._C.tryMatchArgument(arg, graph, loc, actual_named_value, failure_messages, err, allow_conversions, type_env);
  14744. if (!positional) {
  14745. return null;
  14746. }
  14747. positional_inputs.push(positional);
  14748. }
  14749. if (self !== null) {
  14750. if (failure_messages) {
  14751. throw new python.Error('Provided self argument not used in schema.');
  14752. }
  14753. return null;
  14754. }
  14755. if (schema.is_vararg) {
  14756. for (; used_args < args.length; used_args++) {
  14757. positional_inputs.push(args[used_args].value(graph));
  14758. }
  14759. }
  14760. if (used_args < args.length) {
  14761. if (failure_messages) {
  14762. throw new python.Error('Too many positional arguments.');
  14763. }
  14764. return null;
  14765. }
  14766. for (let i = 0; i < kwargs.length; i++) {
  14767. const nv = kwargs[i];
  14768. if (!used_kwarg[i]) {
  14769. if (failure_messages) {
  14770. if (schema.argumentIndexWithName(nv.name()) === null) {
  14771. throw new python.Error('Keyword argument unknown.');
  14772. } else {
  14773. throw new python.Error('Keyword argument specified twice.');
  14774. }
  14775. }
  14776. return null;
  14777. }
  14778. }
  14779. const returns = schema.returns;
  14780. const return_types = returns.map((r) => {
  14781. const result = torch._C.tryEvalTypeVariables(r.type, type_env);
  14782. if (!result) {
  14783. throw new python.Error('Unbound type variable.');
  14784. }
  14785. return result;
  14786. });
  14787. const return_has_field_names = returns.every((r) => !r.name);
  14788. let return_field_names = null;
  14789. if (return_has_field_names) {
  14790. return_field_names = returns.map((r) => r.name);
  14791. }
  14792. const schema_name = torch._C.getFullSchemaName(schema);
  14793. return new torch._C.MatchedSchema(positional_inputs, return_types, return_field_names, schema_name);
  14794. });
  14795. this.registerFunction('torch._C.matchSchema', (schema, loc, graph, args, kwargs, self) => {
  14796. self = self || null;
  14797. const result = torch._C.tryMatchSchema(schema, loc, graph, args, kwargs, self, null, true);
  14798. if (result) {
  14799. return result;
  14800. }
  14801. throw new python.Error(`No matching schema '${schema.name}' found.`);
  14802. });
  14803. this.registerFunction('torch._C.matchSchemas', (schemas, loc, graph, args, kwargs, self, render_errors) => {
  14804. self = self || null;
  14805. render_errors = render_errors || false;
  14806. torch._C.TORCH_INTERNAL_ASSERT(schemas.length > 0);
  14807. if (schemas.length === 1) {
  14808. return [0, torch._C.matchSchema(schemas[0], loc, graph, args, kwargs, self)];
  14809. }
  14810. for (const allow_conversions of [false, true]) {
  14811. for (let i = 0; i < schemas.length; i++) {
  14812. const matched_schema = torch._C.tryMatchSchema(schemas[i], loc, graph, args, kwargs, self, null, allow_conversions);
  14813. if (matched_schema) {
  14814. return [i, matched_schema];
  14815. }
  14816. }
  14817. }
  14818. if (!render_errors) {
  14819. return torch._C.matchSchemas(schemas, loc, graph, args, kwargs, self, /*render_errors=*/true);
  14820. }
  14821. throw new python.Error(`No matching schema '${schemas[0].name}' found.`);
  14822. });
  14823. this.registerFunction('torch._C.emitBuiltinCall', (loc, graph, name, args, kwargs, self) => {
  14824. const variants = torch._C.getAllOperatorsFor(name);
  14825. const builtin_functions = torch._C.getAllBuiltinFunctionsFor(name);
  14826. const graph_version = graph.get_op_version();
  14827. const schemas = [];
  14828. const upgrader_schemas = [];
  14829. for (const op of variants) {
  14830. let found_upgrader = false;
  14831. const op_name = torch._C.getFullSchemaName(op.schema());
  14832. if (Number.isInteger(graph_version)) {
  14833. const version_entry = torch._C.get_operator_version_map().get(op_name);
  14834. if (version_entry) {
  14835. const old_schema_entry = torch._C.findUpgrader(version_entry.second, graph_version.value());
  14836. if (old_schema_entry.has_value()) {
  14837. const old_schema = torch._C.parseSchema(old_schema_entry.value().old_schema);
  14838. upgrader_schemas.push(old_schema);
  14839. found_upgrader = true;
  14840. } else if (!torch._C.isOpCurrentBasedOnUpgraderEntries(version_entry.second, graph_version.value())) {
  14841. throw new python.Error('Valid upgrader must be present.');
  14842. }
  14843. }
  14844. }
  14845. if (!found_upgrader) {
  14846. schemas.push(op.schema());
  14847. }
  14848. }
  14849. if (variants.length === 0) {
  14850. const oldSchemas = torch._C.loadPossibleHistoricOps(name, graph_version);
  14851. for (const old_schema_entry of oldSchemas) {
  14852. const old_schema = torch._C.parseSchema(old_schema_entry);
  14853. upgrader_schemas.push(old_schema);
  14854. }
  14855. }
  14856. for (const schema of upgrader_schemas) {
  14857. schemas.push(schema);
  14858. }
  14859. for (const method of builtin_functions) {
  14860. method.ensure_defined();
  14861. schemas.push(method.getSchema());
  14862. }
  14863. if (schemas.length === 0) {
  14864. const inputs = args.map((arg) => arg.value(graph));
  14865. const n = graph.insertNode(graph.create(name, inputs, 0)).setSourceRange(loc);
  14866. n.addOutput().setType(torch.TensorType.get());
  14867. return n.output();
  14868. }
  14869. const matched = torch._C.matchSchemas(schemas, loc, graph, args, kwargs, self);
  14870. if (matched[0] < variants.length + upgrader_schemas.length) {
  14871. return torch._C.emitBuiltinNode(matched[1], loc, graph, name, graph_version);
  14872. }
  14873. const fn = builtin_functions[matched.first - variants.size()];
  14874. return torch._C.insertGraph(graph, torch._C.toGraphFunction(fn).graph(), matched.second.inputs, new Map())[0];
  14875. });
  14876. this.registerFunction('torch._C.emitBuiltinNode', (matched_schema, loc, graph, name, version) => {
  14877. const n = graph.insertNode(graph.create(name, matched_schema.inputs, 0)).setSourceRange(loc);
  14878. for (const ret of matched_schema.return_types) {
  14879. n.addOutput().setType(ret);
  14880. }
  14881. if (!Number.isInteger(version) || torch._C.isOpSymbolCurrent(matched_schema.schema_name, version)) {
  14882. n.getOperation();
  14883. } else {
  14884. n.setHistoricSchemaName(matched_schema.schema_name);
  14885. }
  14886. return torch._C.packOutputs(graph, n.outputs(), matched_schema.return_field_names);
  14887. });
  14888. this.registerFunction('torch._C.unshapedType', (type) => {
  14889. if (type.isSubtypeOf(torch.TensorType.get())) {
  14890. return torch.TensorType.get();
  14891. }
  14892. const contained = type.containedTypes();
  14893. if (contained.length === 0) {
  14894. return type;
  14895. }
  14896. return type.withContained(contained.map((t) => torch._C.unshapedType(t)));
  14897. });
  14898. this.registerFunction('torch._C.unifyTypesImpl', (t1, t2, default_to_union, type_hint) => {
  14899. default_to_union = default_to_union || false;
  14900. type_hint = type_hint || null;
  14901. if (t1.isSubtypeOf(t2)) {
  14902. return t2;
  14903. } else if (t2.isSubtypeOf(t1)) {
  14904. return t1;
  14905. }
  14906. if (t1.kind() === 'TensorType' && t2.kind() === 'TensorType') {
  14907. return t1.merge(t2);
  14908. }
  14909. if (t1.isSubtypeOf(torch.NoneType.get()) && !t2.isSubtypeOf(torch.NoneType.get())) {
  14910. return torch.OptionalType.create(t2);
  14911. } else if (t2.isSubtypeOf(torch.NoneType.get()) && !t1.isSubtypeOf(torch.NoneType.get())) {
  14912. return torch.OptionalType.create(t1);
  14913. }
  14914. if (t1 instanceof torch.OptionalType) {
  14915. const elem = torch._C.unifyTypes(t1.getElementType(), t2);
  14916. if (elem) {
  14917. return torch.OptionalType.create(elem);
  14918. }
  14919. } else if (t2 instanceof torch.OptionalType) {
  14920. const elem = torch._C.unifyTypes(t2.getElementType(), t1);
  14921. if (elem) {
  14922. return torch.OptionalType.create(elem);
  14923. }
  14924. }
  14925. if (t1 instanceof torch.TupleType && t2 instanceof torch.TupleType) {
  14926. if (t1.elements().size() !== t2.elements().size()) {
  14927. return null;
  14928. }
  14929. const elements = [];
  14930. for (let i = 0; i < t1.elements().length; i++) {
  14931. const elem = torch._C.unifyTypes(t1.elements()[i], t2.elements()[i], default_to_union);
  14932. if (elem) {
  14933. elements.push(elem);
  14934. } else {
  14935. return null;
  14936. }
  14937. }
  14938. return torch.TupleType.create(elements);
  14939. }
  14940. if (t1 instanceof torch.FutureType && t2 instanceof torch.FutureType) {
  14941. const elem = torch._C.unifyTypes(t1.getElementType(), t2.getElementType());
  14942. if (elem) {
  14943. return torch.FutureType.create(elem);
  14944. }
  14945. }
  14946. const t1_unshaped = torch._C.unshapedType(t1);
  14947. const t2_unshaped = torch._C.unshapedType(t2);
  14948. if (t1_unshaped.isSubtypeOf(t2_unshaped)) {
  14949. return t2_unshaped;
  14950. } else if (t2_unshaped.isSubtypeOf(t1_unshaped)) {
  14951. return t1_unshaped;
  14952. }
  14953. if (type_hint && t1.isSubtypeOf(type_hint) && t2.isSubtypeOf(type_hint)) {
  14954. return type_hint;
  14955. }
  14956. return null;
  14957. });
  14958. this.registerFunction('torch._C.unifyTypes', (t1, t2, default_to_union, type_hint) => {
  14959. const unified = torch._C.unifyTypesImpl(t1, t2, default_to_union, type_hint);
  14960. if (default_to_union && !unified) {
  14961. return torch.UnionType.create([t1, t2]);
  14962. }
  14963. return unified;
  14964. });
  14965. this.registerFunction('torch._C.unifyTypeList', (elements, why_not, default_to_union, type_hint) => {
  14966. if (elements.length === 0) {
  14967. return null;
  14968. }
  14969. let [ret_type] = elements;
  14970. for (let i = 1; i < elements.length && ret_type; i++) {
  14971. const maybe_unified = torch._C.unifyTypes(ret_type, elements[i], default_to_union, type_hint);
  14972. if (!maybe_unified) {
  14973. return null;
  14974. }
  14975. ret_type = maybe_unified;
  14976. }
  14977. return ret_type;
  14978. });
  14979. this.registerFunction('torch._C.insertableTensor', (ten) => {
  14980. return !ten.requires_grad() && ten.has_storage() && !ten.is_nested();
  14981. });
  14982. this.registerFunction('torch._C.insertableIValue', (ivalue) => {
  14983. if (ivalue.isInt() || ivalue.isNone() || ivalue.isBool() ||
  14984. ivalue.isDouble() || ivalue.isComplexDouble() || ivalue.isString() ||
  14985. ivalue.isDevice() || ivalue.isEnum()) {
  14986. return true;
  14987. }
  14988. if (ivalue.isTensor()) {
  14989. return torch._C.insertableTensor(ivalue.toTensor());
  14990. }
  14991. if (ivalue.isList() || ivalue.isTuple()) {
  14992. let elems = [];
  14993. if (ivalue.isTuple()) {
  14994. elems = ivalue.toTupleRef().elements();
  14995. } else {
  14996. elems = ivalue.toListRef();
  14997. }
  14998. return elems.every((tup_elem) => torch._C.insertableIValue(tup_elem));
  14999. }
  15000. if (ivalue.isGenericDict()) {
  15001. const dict = ivalue.toGenericDict();
  15002. return dict.every((entry) => torch._C.insertableIValue(entry.key()) && torch._C.insertableIValue(entry.value()));
  15003. }
  15004. return false;
  15005. });
  15006. this.registerFunction('torch._C.insertConstant', (g, val, loc, scope) => {
  15007. loc = loc || null;
  15008. scope = scope || null;
  15009. const value = torch._C.tryInsertConstant(g, val, loc, scope);
  15010. if (value !== undefined) {
  15011. return value;
  15012. }
  15013. throw new python.Error('Unsupported value kind.');
  15014. });
  15015. this.registerFunction('torch._C.tryInsertConstant', (g, val, loc, scope) => {
  15016. if (val instanceof torch._C.IValue) {
  15017. const n = g.create('prim::Constant');
  15018. if (val.isTensor()) {
  15019. const ref = val.toTensor();
  15020. if (!torch._C.insertableTensor(val.toTensor())) {
  15021. n.destroy();
  15022. return null;
  15023. }
  15024. if (!ref.defined()) {
  15025. n.destroy();
  15026. return g.insertNode(g.createNone()).output();
  15027. }
  15028. torch._C.TORCH_INTERNAL_ASSERT(!ref.requires_grad());
  15029. n.output().inferTypeFrom(ref); // note: before t_ because of std::move(ref)
  15030. n.t_('value', ref);
  15031. } else if (val.isInt()) {
  15032. n.i_('value', val.toInt());
  15033. n.output().setType(torch.IntType.get());
  15034. } else if (val.isDouble()) {
  15035. n.f_('value', val.toDouble());
  15036. n.output().setType(torch.FloatType.get());
  15037. } else if (val.isComplexDouble()) {
  15038. n.c_('value', val.toComplexDouble());
  15039. n.output().setType(torch.ComplexType.get());
  15040. } else if (val.isBool()) {
  15041. n.i_('value', val.toBool());
  15042. n.output().setType(torch.BoolType.get());
  15043. } else if (val.isList()) {
  15044. const fast_path_list = val.isBoolList() || val.isIntList() || val.isDoubleList();
  15045. if (fast_path_list || torch._C.insertableIValue(val)) {
  15046. n.ival_('value', val);
  15047. n.output().setType(val.type());
  15048. } else {
  15049. n.destroy();
  15050. return null;
  15051. }
  15052. } else if (val.isString()) {
  15053. n.s_('value', val.toStringRef());
  15054. n.output().setType(torch.StringType.get());
  15055. } else if (val.isDevice()) {
  15056. n.s_('value', val.toDevice().__str__());
  15057. n.output().setType(torch.DeviceObjType.get());
  15058. } else if (val.isGenerator()) {
  15059. n.ival_('value', val.toGenerator());
  15060. n.output().setType(torch._C_._GeneratorType.get());
  15061. } else if (val.isStream()) {
  15062. n.ival_('value', val);
  15063. n.output().setType(torch.StreamObjType.get());
  15064. } else if (val.isNone()) {
  15065. n.output().setType(torch.NoneType.get());
  15066. // n.ival_('value', null); // remove
  15067. } else if (val.isTuple()) {
  15068. if (torch._C.insertableIValue(val)) {
  15069. n.ival_('value', val);
  15070. n.output().setType(val.type());
  15071. } else {
  15072. n.destroy();
  15073. return null;
  15074. }
  15075. } else if (val.isObject()) {
  15076. const ref = val.toObjectRef();
  15077. // see: [Constant Object Weak CompilationUnit Reference]
  15078. if (!ref.type().is_module() && (ref.is_weak_compilation_ref() || ref.is_empty_strong_compilation_ref())) {
  15079. n.ival_('value', val);
  15080. n.output().setType(val.type());
  15081. } else {
  15082. n.destroy();
  15083. return null;
  15084. }
  15085. } else if ((val.isGenericDict() && torch._C.insertableIValue(val)) || (val.isEnum())) {
  15086. n.ival_('value', val);
  15087. n.output().setType(val.type());
  15088. } else {
  15089. n.destroy();
  15090. return null;
  15091. }
  15092. if (loc) {
  15093. n.setSourceRange(loc);
  15094. }
  15095. if (scope) {
  15096. n.setScope(scope);
  15097. }
  15098. return g.insertNode(n).output();
  15099. }
  15100. const n = g.create('prim::Constant');
  15101. let type = null;
  15102. if (val === null) {
  15103. n.ival_('value', val);
  15104. type = torch.NoneType.get();
  15105. } else if (typeof val === 'string') {
  15106. n.s_('value', val);
  15107. type = torch.StringType.get();
  15108. } else if (Array.isArray(val) && val.every((item) => typeof item === 'string')) {
  15109. n.ss_('value', val);
  15110. type = torch.ListType.create(torch.StringType.get());
  15111. } else if (typeof val === 'boolean') {
  15112. n.i_('value', val === true ? 1 : 0);
  15113. type = torch.BoolType.get();
  15114. } else if ((!val.type && Number.isInteger(val)) || val.type === 'int') {
  15115. n.i_('value', val);
  15116. type = torch.IntType.get();
  15117. } else if ((!val.type && typeof val === 'number') || val.type === 'float') {
  15118. n.f_('value', val);
  15119. type = torch.FloatType.get();
  15120. } else if (val instanceof torch.Tensor) {
  15121. n.t_('value', val);
  15122. type = torch.TensorType.get();
  15123. } else if (val instanceof torch.ScriptObject) {
  15124. n.ival_('value', val);
  15125. type = val.type();
  15126. } else if (Array.isArray(val) && val.every((item) => Number.isInteger(item))) {
  15127. n.ival_('value', val);
  15128. type = torch.ListType.create(torch.IntType.get());
  15129. } else {
  15130. throw new python.Error(`Unsupported value type '${typeof val}'.`);
  15131. }
  15132. if (type) {
  15133. n.output().setType(type);
  15134. }
  15135. if (loc) {
  15136. n.setSourceRange(loc);
  15137. }
  15138. if (scope) {
  15139. n.setScope(scope);
  15140. }
  15141. return g.insertNode(n).output();
  15142. });
  15143. this.registerFunction('torch._C.toIValue', (v) => {
  15144. if (v.node().kind() !== 'prim::Constant' || v.type() instanceof torch._C.FunctionType) {
  15145. return null;
  15146. }
  15147. const node = v.node();
  15148. const type = v.type();
  15149. if (type.isSubtypeOf(torch.TensorType.get())) {
  15150. return new torch._C.IValue(node.t('value'), 'Tensor');
  15151. } else if (type.isSubtypeOf(torch.BoolType.get())) {
  15152. return new torch._C.IValue(Boolean(node.i('value'), 'Bool'));
  15153. } else if (type.isSubtypeOf(torch.NumberType.get()) && node.kindOf('value') === 'i') {
  15154. return new torch._C.IValue(node.i('value'), 'Int');
  15155. } else if (type.isSubtypeOf(torch.NumberType.get()) && node.kindOf('value') === 'f') {
  15156. return new torch._C.IValue(node.f('value'), 'Double');
  15157. } else if (type.isSubtypeOf(torch.ComplexType.get()) && node.kindOf('value') === 'c') {
  15158. return new torch._C.IValue(node.c('value'), 'Complex');
  15159. } else if (type instanceof torch.ListType && node.kindOf('value') === 'ival') {
  15160. let list = node.ival('value');
  15161. list = list.isList ? list : new torch._C.IValue(list); // remove
  15162. torch._C.TORCH_INTERNAL_ASSERT(list.isList());
  15163. return list;
  15164. } else if (type instanceof torch.DictType && node.kindOf('value') === 'ival') {
  15165. const dict = node.ival('value');
  15166. torch._C.TORCH_INTERNAL_ASSERT(dict.isGenericDict());
  15167. return dict;
  15168. } else if (type instanceof torch.TupleType && node.kindOf('value') === 'ival') {
  15169. const tup = node.ival('value');
  15170. torch._C.TORCH_INTERNAL_ASSERT(tup.isTuple());
  15171. return tup;
  15172. } else if (type === torch.StringType.get()) {
  15173. const s = new torch._C.IValue(node.s('value'), 'String');
  15174. return s;
  15175. } else if (type === torch.DeviceObjType.get()) {
  15176. const d = new torch.device(node.s('value'));
  15177. return new torch._C.IValue(d);
  15178. } else if (type === torch._C._GeneratorType.get()) {
  15179. throw new python.Error('Not implemented.');
  15180. // const generator = node.ival('value').toGenerator();
  15181. // return generator;
  15182. } else if (type === torch.StreamObjType.get()) {
  15183. throw new python.Error('Not implemented.');
  15184. // const s = node.ival('value').toStream();
  15185. // return s;
  15186. } else if (node.mustBeNone()) {
  15187. return new torch._C.IValue();
  15188. } else if (type.kind() === 'EnumType') {
  15189. const enum_val = node.ival('value');
  15190. return enum_val;
  15191. } else if (type instanceof torch.ClassType && !type.is_module()) {
  15192. const class_val = node.ival('value');
  15193. return new torch._C.IValue(class_val, 'Object');
  15194. }
  15195. throw new python.Error('Unsupported constant literal.');
  15196. });
  15197. this.registerFunction('torch._C.constant_as', (v, target, default_value) => {
  15198. const ivalue = torch._C.toIValue(v);
  15199. if (ivalue) {
  15200. return ivalue[target]();
  15201. }
  15202. return default_value === undefined ? null : default_value;
  15203. });
  15204. this.registerType('torch._C.NamedValue', class {
  15205. constructor(...args) {
  15206. if (args.length === 1) {
  15207. if (args[0] instanceof torch.Value) {
  15208. [this._value] = args;
  15209. } else {
  15210. [this._ivalue] = args;
  15211. }
  15212. } else if (args.length === 3 && typeof args[1] === 'string' && args[2] instanceof torch.Value) {
  15213. [this._loc, this._name, this._value] = args;
  15214. } else {
  15215. throw new python.Error('Invalid argument.');
  15216. }
  15217. }
  15218. name() {
  15219. return this._name;
  15220. }
  15221. value(g) {
  15222. if (!this._value) {
  15223. return torch._C.insertConstant(g, this._ivalue);
  15224. }
  15225. return this._value;
  15226. }
  15227. type() {
  15228. if (this._value) {
  15229. return this._value.type();
  15230. }
  15231. return this._ivalue.type();
  15232. }
  15233. });
  15234. this.registerType('torch._C.SugaredValue', class {
  15235. kind() {
  15236. throw new python.Error('Not implemented.');
  15237. }
  15238. shouldEmitUnrolled() {
  15239. return this.staticLen() !== null;
  15240. }
  15241. });
  15242. this.registerType('torch._C.SimpleValue', class extends torch._C.SugaredValue {
  15243. constructor(value) {
  15244. super();
  15245. this._value = value;
  15246. }
  15247. kind() {
  15248. return `value of type '${this._value.type().annotation_str}'`;
  15249. }
  15250. asValue(/* range, m */) {
  15251. return this._value;
  15252. }
  15253. getValue() {
  15254. return this._value;
  15255. }
  15256. asTuple(loc, m, size_hint) {
  15257. const make_simple_value = (v) => new torch._C.SimpleValue(v);
  15258. if (this._value.type() instanceof torch.TupleType) {
  15259. const outputs = torch._C.createTupleUnpack(this._value);
  15260. return outputs.map((v) => make_simple_value(v));
  15261. } else if (this._value.type() instanceof torch.ListType) {
  15262. if (!size_hint) {
  15263. throw new python.Error('Cannot statically infer the expected size of a list in this context.');
  15264. }
  15265. const graph = this._value.owningGraph();
  15266. const unpack = graph.insertNode(graph.createListUnpack(this._value, size_hint));
  15267. return unpack.outputs().map((v) => make_simple_value(v));
  15268. } else if (this._value.type().kind() === 'AnyTupleType') {
  15269. throw new python.Error('Provided tuple is not fully defined including its element types.');
  15270. }
  15271. throw new python.Error(`Cannot use '${this._value.type().toString()}' as tuple.`);
  15272. }
  15273. attr(loc, m, field) {
  15274. if (this._value.type().isSubtypeOf(torch.TensorType.get())) {
  15275. if (torch._C.builtin_cast_method_to_scalar_type().has(field)) {
  15276. return new torch._C.TensorCastValue(torch._C.builtin_cast_method_to_scalar_type().get(field), new torch._C.NamedValue(loc, 'self', this._value));
  15277. }
  15278. }
  15279. if (this._value.type() instanceof torch.TupleType) {
  15280. throw new python.Error('Not implemented.');
  15281. }
  15282. if (this._value.type() instanceof torch.AwaitType) {
  15283. throw new python.Error('Not implemented.');
  15284. }
  15285. if (this._value.type() instanceof torch.ClassType) {
  15286. const classType = this._value.type();
  15287. if (classType.findMethod(field)) {
  15288. return new torch._C.MethodValue(this.getValue(), [field]);
  15289. }
  15290. if (classType.hasAttribute(field)) {
  15291. const g = m.graph();
  15292. const n = g.insertNode(g.createGetAttr(this._value, field));
  15293. return new torch._C.SimpleValue(n.output());
  15294. }
  15295. const prop = classType.getProperty(field);
  15296. if (prop) {
  15297. return new torch._C.MethodValue(this._value, [prop.getter.name()]).call(loc, m, {}, {}, /*n_binders=*/1);
  15298. }
  15299. } else if (this._value.type() instanceof torch.InterfaceType) {
  15300. throw new python.Error('Not implemented.');
  15301. } else if (this._value.type() instanceof torch.EnumType) {
  15302. const g = m.graph();
  15303. if (field === 'name') {
  15304. const n = g.insertNode(g.createEnumName(this._value));
  15305. return new torch._C.SimpleValue(n.output());
  15306. }
  15307. if (field === 'value') {
  15308. const n = g.insertNode(g.createEnumValue(this._value));
  15309. return new torch._C.SimpleValue(n.output());
  15310. }
  15311. }
  15312. if (field === 'type') {
  15313. const builtin = torch._C.BuiltinFunction.tryCreate('aten::to', new torch._C.NamedValue(loc, 'self', this._value));
  15314. if (builtin) {
  15315. return builtin;
  15316. }
  15317. }
  15318. const builtin = torch._C.BuiltinFunction.tryCreate(`aten::${field}`, new torch._C.NamedValue(loc, 'self', this._value));
  15319. if (builtin) {
  15320. return builtin;
  15321. }
  15322. if (this._value.type().isSubtypeOf(torch.TensorType.get()) && field === 'tolist') {
  15323. return torch._C.SpecialFormValue.create('prim::tolist');
  15324. }
  15325. if (this._value.type().isSubtypeOf(torch.TensorType.get()) && field === '__getitem__') {
  15326. return torch._C.SpecialFormValue.create('aten::index');
  15327. }
  15328. if (this._value.type() instanceof torch._C._GeneratorType && (field === 'manual_seed' || field === 'initial_seed' || field === 'seed')) {
  15329. const builtin = torch._C.BuiltinFunction.tryCreate(`aten::${field}`, new torch._C.NamedValue(loc, 'self', this._value));
  15330. if (builtin) {
  15331. return builtin;
  15332. }
  15333. }
  15334. throw new python.Error('Object has no attribute or method.');
  15335. }
  15336. setAttr(loc, m, field, newValue) {
  15337. const type = this._value.type();
  15338. if (type instanceof torch.ClassType === false) {
  15339. throw new python.Error('Cannot set attribute on non-class type.');
  15340. }
  15341. const classType = type;
  15342. let expectedType = classType.findAttribute(field);
  15343. if (!expectedType) {
  15344. const isInitializing = m.name() === '__init__' && m.graph().inputs().length > 0 && m.graph().inputs()[0].type() === classType;
  15345. if (isInitializing) {
  15346. if (this.isRecursive(classType, newValue.type())) {
  15347. throw new python.Error('Classes that recursively contain instances of themselves are not supported.');
  15348. }
  15349. classType.addAttribute(field, newValue.type());
  15350. expectedType = newValue.type();
  15351. const insertPoint = m.graph().insertPoint();
  15352. const topLevelBlock = m.graph().block();
  15353. if (insertPoint.owningBlock() !== topLevelBlock) {
  15354. throw new python.Error('First assignment cannot be in a control-flow block.');
  15355. }
  15356. } else {
  15357. const prop = classType.getProperty(field);
  15358. if (prop && prop.setter) {
  15359. new torch._C.MethodValue(this._value, prop.setter.name()).call(loc, m, [newValue], [], /*n_binders=*/1);
  15360. return;
  15361. }
  15362. if (prop && !prop.setter) {
  15363. throw new python.Error('Tried to set read-only attribute.');
  15364. }
  15365. throw new python.Error('Tried to set nonexistent attribute.');
  15366. }
  15367. }
  15368. torch._C.AT_ASSERT(expectedType);
  15369. const newType = newValue.type();
  15370. if (!newType.isSubtypeOf(expectedType)) {
  15371. throw new python.Error('Wrong type for attribute assignment.');
  15372. }
  15373. const g = m.graph();
  15374. g.insertNode(g.createSetAttr(this._value, field, newValue));
  15375. }
  15376. getitem(loc, m, idx, type_hint) {
  15377. const val = this.getValue();
  15378. const val_type = val.type();
  15379. const g = m.graph();
  15380. if (val_type instanceof torch.ListType || val_type instanceof torch.StringType) {
  15381. return new torch._C.SimpleValue(g.insert('aten::__getitem__', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc));
  15382. } else if (val_type instanceof torch.DictType) {
  15383. return new torch._C.SimpleValue(g.insert('aten::__getitem__', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc));
  15384. } else if (val_type.isSubtypeOf(torch.TensorType.get())) {
  15385. 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));
  15386. } else if (val_type instanceof torch.ClassType) {
  15387. const class_type = val_type;
  15388. if (class_type.is_module() && type_hint) {
  15389. const res = g.insert('prim::ModuleContainerIndex', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc);
  15390. res.setType(type_hint);
  15391. return new torch._C.SimpleValue(res);
  15392. }
  15393. return this.attr(loc, m, '__getitem__').call(loc, m, [new torch._C.NamedValue(idx)], [], 1);
  15394. }
  15395. throw new python.Error('Object is not subscriptable.');
  15396. }
  15397. });
  15398. this.registerType('torch._C.MethodValue', class extends torch._C.SugaredValue {
  15399. constructor(self, method_names) {
  15400. super();
  15401. this._self = self;
  15402. this._method_names = method_names;
  15403. }
  15404. call(loc, f, args, kwargs /*, n_binders */) {
  15405. const argsWithSelf = [new torch._C.NamedValue(this._self), ...args];
  15406. const schemas = [];
  15407. for (const method_name of this._method_names) {
  15408. const type = this._self.type();
  15409. if (type instanceof torch.ClassType) {
  15410. const class_type = type;
  15411. const method = class_type.getMethod(method_name);
  15412. method.ensure_defined();
  15413. schemas.push(method.getSchema());
  15414. } else if (type instanceof torch.InterfaceType) {
  15415. const interface_type = type;
  15416. schemas.push(interface_type.getMethod(method_name));
  15417. } else {
  15418. throw new python.Error('Method constructed that is not a class or interface.');
  15419. }
  15420. }
  15421. const match = torch._C.matchSchemas(schemas, loc, f.graph(), argsWithSelf, kwargs);
  15422. const output = f.graph().insertMethodCall(this._method_names[match[0]], match[1]);
  15423. output.node().setSourceRange(loc);
  15424. return new torch._C.SimpleValue(output);
  15425. }
  15426. });
  15427. this.registerType('torch._C.ClassValue', class extends torch._C.SugaredValue {
  15428. constructor(type) {
  15429. super();
  15430. this._type = type;
  15431. }
  15432. attr(loc, m, field) {
  15433. const hook = this._type.findHook(field);
  15434. if (hook) {
  15435. return new torch._C.FunctionValue(hook);
  15436. }
  15437. if (field !== '__new__') {
  15438. throw new python.Error('Tried to lookup unknown attribute on class.');
  15439. }
  15440. return torch._C.SpecialFormValue.create('prim::CreateObject');
  15441. }
  15442. });
  15443. this.registerType('torch._C.NamedTupleConstructor', class extends torch._C.SugaredValue {
  15444. constructor(type) {
  15445. super();
  15446. this._type = type;
  15447. }
  15448. call(loc, m, args, kwargs /*, n_binders */) {
  15449. const g = m.graph();
  15450. const schema = this._type.schema();
  15451. torch._C.TORCH_INTERNAL_ASSERT(schema);
  15452. const matched_schema = torch._C.matchSchema(schema, loc, g, args, kwargs);
  15453. const self = g.insertNode(g.createTuple(matched_schema.inputs, this._type).setSourceRange(loc)).output();
  15454. self.setType(this._type);
  15455. return new torch._C.SimpleValue(self);
  15456. }
  15457. });
  15458. this.registerType('torch._C.SugaredEnumClass', class extends torch._C.SugaredValue {
  15459. constructor(enum_type) {
  15460. super();
  15461. this._enum_type = enum_type;
  15462. }
  15463. attr(loc, m, field) {
  15464. const names_values = this._enum_type.enumNamesValues();
  15465. const it = names_values.find((nv) => nv[0] === field);
  15466. if (it === null) {
  15467. throw new python.Error(`Enum '${this._enum_type.name()}' has no attribute '${field}'.`);
  15468. }
  15469. const enum_holder = new torch._C.EnumHolder(this._enum_type, it[0], it[1]);
  15470. return new torch._C.SimpleValue(m.graph().insertConstant(new torch._C.IValue(enum_holder), loc));
  15471. }
  15472. });
  15473. this.registerType('torch._C.EnumHolder', class {
  15474. constructor(type, name, value) {
  15475. this._type = type;
  15476. this._name = name;
  15477. this._value = value;
  15478. }
  15479. name() {
  15480. return this._name;
  15481. }
  15482. type() {
  15483. return this._type;
  15484. }
  15485. });
  15486. this.registerType('torch._C.FunctionValue', class extends torch._C.SugaredValue {
  15487. constructor(...args) {
  15488. super();
  15489. if (args.length === 1 && args[0] instanceof torch._C.Function) {
  15490. this._callees = [args[0]];
  15491. } else {
  15492. throw new python.Error('Not implemented.');
  15493. }
  15494. }
  15495. call(loc, f, args, kwargs /*, n_binders */) {
  15496. const schemas = [];
  15497. for (const callee of this._callees) {
  15498. callee.ensure_defined();
  15499. schemas.push(callee.getSchema());
  15500. }
  15501. const match = torch._C.matchSchemas(schemas, loc, f.graph(), args, kwargs);
  15502. const output = f.graph().insertFunctionCall(this._callees[match[0]], match[1]);
  15503. output.node().setSourceRange(loc);
  15504. return new torch._C.SimpleValue(output);
  15505. }
  15506. });
  15507. this.registerType('torch._C.NoneValue', class extends torch._C.SugaredValue {
  15508. });
  15509. this.registerType('torch._C.PrintValue', class extends torch._C.SugaredValue {
  15510. call(loc, m, args, kwargs /*, n_binders */) {
  15511. const g = m.graph();
  15512. if (kwargs.length > 0) {
  15513. throw new python.Error(`Print doesn't accept any keyword arguments at ${loc}.`);
  15514. }
  15515. const lowered_inputs = torch._C.toValues(m.graph(), args);
  15516. g.insertNode(g.create('prim::Print', lowered_inputs, 0).setSourceRange(loc));
  15517. return new torch._C.NoneValue();
  15518. }
  15519. });
  15520. this.registerType('torch._C.SpecialFormValue', class extends torch._C.SugaredValue {
  15521. constructor(form) {
  15522. super();
  15523. this._form = form;
  15524. }
  15525. form() {
  15526. return this._form;
  15527. }
  15528. static create(form) {
  15529. return new torch._C.SpecialFormValue(form);
  15530. }
  15531. });
  15532. this.registerFunction('torch._C.makeMagic', (name, base) => {
  15533. return new torch._C.MagicMethod(name, base);
  15534. });
  15535. this.registerType('torch._C.BuiltinFunction', class extends torch._C.SugaredValue {
  15536. constructor(symbol, self) {
  15537. super();
  15538. this.symbol = symbol;
  15539. this.self = self;
  15540. }
  15541. call(loc, m, args, kwargs /*, n_binders */) {
  15542. return new torch._C.SimpleValue(torch._C.emitBuiltinCall(loc, m.graph(), this.symbol, args, kwargs, this.self));
  15543. }
  15544. static tryCreate(symbol, self) {
  15545. for (const op of torch._C.getAllOperatorsFor(symbol)) {
  15546. if (!self) {
  15547. return new torch._C.BuiltinFunction(symbol, null);
  15548. }
  15549. const index = op.schema().argumentIndexWithName('self');
  15550. if (index) {
  15551. const type_env = new Map();
  15552. const formal_type = op.schema().arguments()[index].type();
  15553. const matched = torch._C.matchTypeVariables(formal_type, self.type(), type_env);
  15554. if (!matched.success()) {
  15555. continue;
  15556. }
  15557. const concrete_type = torch._C.tryEvalTypeVariables(formal_type, type_env);
  15558. if (!concrete_type || !self.type().isSubtypeOf(concrete_type)) {
  15559. continue;
  15560. }
  15561. return new torch._C.BuiltinFunction(symbol, self);
  15562. }
  15563. }
  15564. return null;
  15565. }
  15566. });
  15567. this.registerType('torch._C.BuiltinModule', class extends torch._C.SugaredValue {
  15568. constructor(name, version) {
  15569. super();
  15570. this.name = name;
  15571. this.version = version || null;
  15572. }
  15573. attr(loc, m, field) {
  15574. if (field === 'autograd') {
  15575. return new torch._C.BuiltinModule('aten', this.version);
  15576. }
  15577. const sym = `${this.name}::${field}`;
  15578. return new torch._C.BuiltinFunction(sym, null);
  15579. }
  15580. });
  15581. this.registerType('torch._C.OpsValue', class extends torch._C.SugaredValue {
  15582. constructor(version) {
  15583. super();
  15584. this._version = version;
  15585. }
  15586. attr(loc, m, field) {
  15587. return new torch._C.BuiltinModule(field, this._version);
  15588. }
  15589. });
  15590. this.registerType('torch._C.ConstantTableValue', class extends torch._C.SugaredValue {
  15591. constructor(constants) {
  15592. super();
  15593. this._constants = constants;
  15594. this.non_holding_object_cache = new Map();
  15595. }
  15596. attr(loc, m, field) {
  15597. const offset = parseInt(field.substring(1), 10);
  15598. if (!Number.isInteger(offset)) {
  15599. throw new python.Error(`Invalid constant identifier '${field}.`);
  15600. }
  15601. if (offset < 0 || offset >= this._constants.length) {
  15602. throw new python.Error('Invalid constant index.');
  15603. }
  15604. const ivalue = new torch._C.IValue(this._constants[offset]); // remove IValue
  15605. let value = null;
  15606. if (ivalue.isObject() && !ivalue.toObject().is_weak_compilation_ref()) {
  15607. const obj = ivalue.toObject();
  15608. if (!this.non_holding_object_cache.has(obj)) {
  15609. this.non_holding_object_cache.set(obj, obj.copy_to_weak_compilation_ref());
  15610. }
  15611. value = m.graph().insertConstant(this.non_holding_object_cache[obj], loc);
  15612. } else {
  15613. value = m.graph().insertConstant(this._constants[offset], loc);
  15614. }
  15615. value.setType(torch._C.unshapedType(value.type()));
  15616. return new torch._C.SimpleValue(value);
  15617. }
  15618. });
  15619. this.registerType('torch._C.CastValue', class extends torch._C.BuiltinFunction {
  15620. constructor(type, method) {
  15621. super(method, null);
  15622. this._type = type;
  15623. }
  15624. call(loc, m, args, kwargs, n_binders) {
  15625. if (args.length === 1 && kwargs.length === 0) {
  15626. const len_op = new torch._C.BuiltinFunction('aten::len', null);
  15627. const gt_op = new torch._C.BuiltinFunction('aten::gt', null);
  15628. const zero = m.graph().insertConstant(new torch._C.IValue(0, 'Int'));
  15629. const v = args[0].value(m.graph());
  15630. if (v.type().isSubtypeOf(this._type)) {
  15631. return new torch._C.SimpleValue(v);
  15632. } 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)) {
  15633. const len = len_op.call(loc, m, [v], [], 1);
  15634. return gt_op.call(loc, m, [len.asValue(loc, m), zero], [], 1);
  15635. }
  15636. }
  15637. return super.call(loc, m, args, kwargs, n_binders);
  15638. }
  15639. });
  15640. this.registerType('torch._C.MagicMethod', class extends torch._C.SugaredValue {
  15641. constructor(desugared_name, base) {
  15642. super();
  15643. this._base_value = base;
  15644. this._desugared_name = desugared_name;
  15645. }
  15646. call(loc, m, args, kwargs, n_binders) {
  15647. if (args.length > 0) {
  15648. const self = args[0].value(m.graph());
  15649. if (self.type() instanceof torch.ClassType) {
  15650. return new torch._C.SimpleValue(self)
  15651. .attr(loc, m, this._desugared_name)
  15652. .call(loc, m, args.slice(1), kwargs, n_binders);
  15653. }
  15654. }
  15655. if (!this._base_value) {
  15656. throw new python.Error('Invalid magic method.');
  15657. }
  15658. return this._base_value.call(loc, m, args, kwargs, n_binders);
  15659. }
  15660. });
  15661. this.registerType('torch._C.RangeValue', class extends torch._C.SugaredValue {
  15662. constructor(loc, m, inputs, static_len) {
  15663. super();
  15664. static_len = static_len || null;
  15665. if (inputs.length === 0 || inputs.length > 3 || !inputs.every((value) => value.type() instanceof torch.IntType)) {
  15666. throw new python.Error('Invalid range inputs.');
  15667. }
  15668. const g = m.graph();
  15669. if (inputs.length === 1) {
  15670. [this._end] = inputs;
  15671. this._start = g.insertConstant(0, loc);
  15672. this._step = g.insertConstant(1, loc);
  15673. this._has_only_end = true;
  15674. } else {
  15675. [this._start, this._end] = inputs;
  15676. this._step = inputs.length === 3 ? inputs[2] : g.insertConstant(1, loc);
  15677. this._has_only_end = false;
  15678. }
  15679. this._static_len = static_len;
  15680. }
  15681. staticLen() {
  15682. return this._static_len;
  15683. }
  15684. iter() {
  15685. return this;
  15686. }
  15687. len(loc, m) {
  15688. if (this._static_len) {
  15689. return torch._C.insertConstant(m.graph(), this._static_len, loc);
  15690. }
  15691. if (this._has_only_end) {
  15692. return this._end;
  15693. }
  15694. const g = m.graph();
  15695. return g.insert('aten::__range_length', [this._start, this._end, this._step], [], loc);
  15696. }
  15697. getitem(loc, m, idx /*, type_hint */) {
  15698. if (this._has_only_end) {
  15699. return new torch._C.SimpleValue(idx);
  15700. }
  15701. const g = m.graph();
  15702. return new torch._C.SimpleValue(g.insert('aten::__derive_index', [idx, this._start, this._step], [], loc));
  15703. }
  15704. });
  15705. this.registerType('torch._C.SliceValue', class extends torch._C.SugaredValue {
  15706. });
  15707. this.registerType('torch._C.ClassNamespaceValue', class extends torch._C.SugaredValue {
  15708. constructor(name, si) {
  15709. super();
  15710. this._basename = name;
  15711. this._si = si;
  15712. }
  15713. attr(loc, m, name) {
  15714. const fullName = new torch._C.QualifiedName(this._basename, name);
  15715. const serializable_type = this._si.findNamedType(fullName);
  15716. if (serializable_type) {
  15717. if (serializable_type instanceof torch.ClassType) {
  15718. return new torch._C.ClassValue(serializable_type);
  15719. } else if (serializable_type instanceof torch.TupleType) {
  15720. return new torch._C.NamedTupleConstructor(serializable_type);
  15721. } else if (serializable_type instanceof torch.EnumType) {
  15722. return new torch._C.SugaredEnumClass(serializable_type);
  15723. }
  15724. }
  15725. const fn = this._si.findFunction(fullName);
  15726. if (fn) {
  15727. return new torch._C.FunctionValue(fn);
  15728. }
  15729. return new torch._C.ClassNamespaceValue(fullName, this._si);
  15730. }
  15731. });
  15732. this.registerType('torch.package.PackageImporter', class {
  15733. constructor(reader) {
  15734. this.zip_reader = reader;
  15735. }
  15736. load_pickle(module, resource) {
  15737. const name = `${module.replace(/\./, '/')}/${resource}`;
  15738. const stream = this.zip_reader.get_record(name);
  15739. const loaded_reduces = new Map();
  15740. this.storage_context = new torch._C.DeserializationStorageContext();
  15741. const unpickler = new pickle.Unpickler(stream);
  15742. unpickler.persistent_load = (saved_id) => {
  15743. switch (saved_id[0]) {
  15744. case 'storage': {
  15745. const [, storage_type, key, , size] = saved_id;
  15746. if (!this.storage_context.has_storage(key)) {
  15747. const storage = new storage_type(size);
  15748. if (!storage._set_cdata) {
  15749. throw new python.Error(`'${storage_type.__name__}._set_cdata' is not a function.`);
  15750. }
  15751. const stream = this.zip_reader.get_record(`.data/${key}.storage`);
  15752. const buffer = stream.peek();
  15753. storage._set_cdata(buffer);
  15754. this.storage_context.add_storage(key, storage);
  15755. }
  15756. return this.storage_context.get_storage(key);
  15757. }
  15758. case 'reduce_package': {
  15759. if (saved_id.length === 2) {
  15760. const [, func, args] = saved_id;
  15761. return execution.invoke(func, args);
  15762. }
  15763. const [, reduce_id, func, args] = saved_id;
  15764. if (!loaded_reduces.has(reduce_id)) {
  15765. const value = execution.invoke(func, [this].concat(args));
  15766. loaded_reduces.set(reduce_id, value);
  15767. }
  15768. return loaded_reduces.get(reduce_id);
  15769. }
  15770. default: {
  15771. throw new python.Error(`Unknown package typename '${saved_id[0]}'.`);
  15772. }
  15773. }
  15774. };
  15775. const obj = unpickler.load();
  15776. this.storage_context = null;
  15777. return obj;
  15778. }
  15779. import_module(name) {
  15780. return execution.import(name);
  15781. }
  15782. });
  15783. this.registerFunction('torch.jit.load', (file, map_location, extra_files) => {
  15784. const cu = new torch.jit.CompilationUnit();
  15785. cu.execution = execution;
  15786. const cpp_module = torch._C.import_ir_module(cu, file, map_location, extra_files);
  15787. const module = torch.jit._script.wrap_cpp_module(cpp_module);
  15788. module.forward = cpp_module.forward; // remove
  15789. return module;
  15790. });
  15791. this.registerFunction('torch._C.import_ir_module', function(cu, reader, ...args) {
  15792. switch (arguments.length) {
  15793. case 4: {
  15794. const [device, extra_files] = args;
  15795. const deserializer = new torch._C.ScriptModuleDeserializer(cu, reader);
  15796. return deserializer.deserialize(device, extra_files);
  15797. }
  15798. case 5: {
  15799. const [storage_context, device, ts_id] = args;
  15800. const deserializer = new torch._C.ScriptModuleDeserializer(cu, reader, `.data/ts_code/${ts_id}/`, '.data/', storage_context);
  15801. return deserializer.deserialize(device, null);
  15802. }
  15803. default: {
  15804. throw new python.Error("Invalid 'torch._C.import_ir_module' signature.");
  15805. }
  15806. }
  15807. });
  15808. this.registerFunction('torch._C._import_ir_module_from_package', (cu, reader, storage_context, map_location, ts_id) => {
  15809. return torch._C.import_ir_module(cu, reader, storage_context, null, ts_id);
  15810. });
  15811. this.registerFunction('torch._C.tryToGraphFunction', (value) => {
  15812. if (value instanceof torch.Node) {
  15813. const n = value;
  15814. if (n.kind() === 'prim::CallFunction') {
  15815. torch._C.AT_ASSERT(n.input(0).node().kind() === 'prim::Constant');
  15816. const function_constant = n.input(0).node();
  15817. const fun_type = function_constant.output().type().expect(torch._C.FunctionType);
  15818. return torch._C.tryToGraphFunction(fun_type.function());
  15819. }
  15820. if (n.kind() === 'prim::CallMethod') {
  15821. const name = n.s('name');
  15822. const class_type = n.input(0).type();
  15823. if (class_type instanceof torch.ClassType) {
  15824. const fn = class_type.getMethod(name);
  15825. return torch._C.tryToGraphFunction(fn);
  15826. }
  15827. }
  15828. return null;
  15829. } else if (value instanceof torch._C.Function) {
  15830. const fn = value;
  15831. if (!fn.isGraphFunction()) {
  15832. return null;
  15833. }
  15834. return fn;
  15835. }
  15836. throw new python.Error('Not implemented.');
  15837. });
  15838. this.registerType('torch._C.ModuleInstanceInfo', class {
  15839. constructor(module_type, instance_name) {
  15840. this._module_type = module_type;
  15841. this._instance_name = instance_name;
  15842. }
  15843. });
  15844. this.registerFunction('torch._C.slice_indices_adjust', (length, start, stop, step) => {
  15845. torch._C.TORCH_CHECK(step !== 0);
  15846. torch._C.TORCH_CHECK(step >= -Number.MAX_SAFE_INTEGER); // INT64_MAX
  15847. if (start._ === Number.MAX_SAFE_INTEGER) {
  15848. start._ = (step < 0) ? Number.MAX_SAFE_INTEGER : 0;
  15849. }
  15850. if (stop._ === Number.MAX_SAFE_INTEGER) {
  15851. stop._ = (step < 0) ? Number.MIN_SAFE_INTEGER : Number.MAX_SAFE_INTEGER;
  15852. }
  15853. if (start._ < 0) {
  15854. start._ += length;
  15855. if (start._ < 0) {
  15856. start._ = (step < 0) ? -1 : 0;
  15857. }
  15858. } else if (start._ >= length) {
  15859. start._ = (step < 0) ? length - 1 : length;
  15860. }
  15861. if (stop._ < 0) {
  15862. stop._ += length;
  15863. if (stop._ < 0) {
  15864. stop._ = (step < 0) ? -1 : 0;
  15865. }
  15866. } else if (stop._ >= length) {
  15867. stop._ = (step < 0) ? length - 1 : length;
  15868. }
  15869. if (step < 0) {
  15870. if (stop._ < start._) {
  15871. return Math.floor((start._ - stop._ - 1) / (-step) + 1);
  15872. }
  15873. } else if (start._ < stop._) {
  15874. return Math.floor((stop._ - start._ - 1) / step + 1);
  15875. }
  15876. return 0;
  15877. });
  15878. this.registerFunction('torch._C.createTupleUnpack', (v) => {
  15879. if (v.node().kind() === 'prim::TupleConstruct') {
  15880. return v.node().inputs();
  15881. }
  15882. const g = v.owningGraph();
  15883. return g.insertNode(g.createTupleUnpack(v)).outputs();
  15884. });
  15885. this.registerFunction('torch._C.inlineCallStackOfNode', (/* new_node, new_cs_entriesm, callee, to_replace, m_info */) => {
  15886. /*
  15887. const new_node_cs = new_node.callstack();
  15888. const raw_callstack_ptr = new_node_cs ? new_node_cs : nullptr;
  15889. if (!new_cs_entries.has(raw_callstack_ptr)) {
  15890. if (new_node_cs) {
  15891. new_cs_entries.set(raw_callstack_ptr, c10::make_intrusive<InlinedCallStack>(*new_node_cs, callee, to_replace.sourceRange(), m_info));
  15892. } else {
  15893. new_cs_entries.set(raw_callstack_ptr, c10::make_intrusive<InlinedCallStack>(callee, to_replace.sourceRange(), m_info);
  15894. }
  15895. }
  15896. new_node.setCallStack(new_cs_entries.at(raw_callstack_ptr));
  15897. for (const block of new_node.blocks()) {
  15898. torch._C.inlineCallStackOfBlock(block, new_cs_entries, callee, to_replace, m_info);
  15899. }
  15900. */
  15901. });
  15902. this.registerFunction('torch._C.inlineCallTo', (to_replace, callee, arg) => {
  15903. if (arg === undefined || typeof arg === 'boolean') {
  15904. const inline_optimized_graph = arg === undefined ? true : arg;
  15905. const graph = inline_optimized_graph ? callee.optimized_graph() : callee.graph();
  15906. return torch._C.inlineCallTo(to_replace, callee, graph);
  15907. }
  15908. if (arg instanceof torch.Graph === false) {
  15909. throw new python.Error('Invalid argument.');
  15910. }
  15911. const callee_graph = arg;
  15912. const guard = new torch._C.WithInsertPoint(to_replace);
  15913. const value_map = new Map();
  15914. const new_outputs = torch._C.insertGraph(to_replace.owningGraph(), callee_graph, to_replace.inputs(), value_map);
  15915. const new_callstack_entries = new Map();
  15916. let module_instance_info = null;
  15917. if (to_replace.kind() === 'prim::CallMethod') {
  15918. const class_type_ptr = to_replace.input(0).type();
  15919. if (to_replace.input(0).node().kind() === 'prim::GetAttr') {
  15920. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, to_replace.input(0).node().s('name'));
  15921. } else if (to_replace.owningGraph().inputs().length > 0 && to_replace.input(0) === to_replace.owningGraph().inputs()[0]) {
  15922. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, 'SELF');
  15923. } else {
  15924. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, 'INSTANCE_NAME_UNKNOWN');
  15925. }
  15926. }
  15927. const updated_nodes = new Set();
  15928. for (const kv of value_map) {
  15929. const is_graph_input = callee_graph.inputs().indexOf(kv[0]);
  15930. if (is_graph_input === -1) {
  15931. continue;
  15932. }
  15933. const new_node = kv[1].node();
  15934. if (updated_nodes.has(new_node)) {
  15935. continue;
  15936. }
  15937. updated_nodes.add(new_node);
  15938. torch._C.inlineCallStackOfNode(new_node, new_callstack_entries, callee, to_replace, module_instance_info);
  15939. }
  15940. const old_outputs = to_replace.outputs();
  15941. torch._C.AT_ASSERT(new_outputs.length === old_outputs.length);
  15942. for (let i = 0; i < old_outputs.length; i++) {
  15943. if (old_outputs[i].hasDebugName()) {
  15944. new_outputs[i].setDebugName(old_outputs[i].debugName());
  15945. }
  15946. old_outputs[i].replaceAllUsesWith(new_outputs[i]);
  15947. }
  15948. to_replace.destroy();
  15949. guard.dispose();
  15950. return new_outputs;
  15951. });
  15952. this.registerFunction('torch._C.inlineCalls', (block) => {
  15953. for (const cur of block.nodes()) {
  15954. switch (cur.kind()) {
  15955. case 'prim::CallFunction': {
  15956. const graphFunction = torch._C.tryToGraphFunction(cur);
  15957. if (graphFunction) {
  15958. const function_constant = cur.input(0).node();
  15959. // const fun_type = function_constant.output().type().expect(torch.FunctionType);
  15960. cur.removeInput(0);
  15961. let g = null;
  15962. const fallback = function_constant.hasAttribute('fallback');
  15963. if (fallback && graphFunction.get_executor().isOptimized()) {
  15964. const exec_plans = graphFunction.get_executor().getDebugState().execution_plans;
  15965. if (!exec_plans.empty()) {
  15966. g = exec_plans.begin().second.graph;
  15967. torch._C.Inline(g);
  15968. }
  15969. }
  15970. if (g === null) {
  15971. g = graphFunction.optimized_graph();
  15972. }
  15973. torch._C.inlineCallTo(cur, graphFunction, g);
  15974. }
  15975. break;
  15976. }
  15977. case 'prim::CallMethod': {
  15978. const graphFunction = torch._C.tryToGraphFunction(cur);
  15979. if (graphFunction) {
  15980. torch._C.inlineCallTo(cur, graphFunction);
  15981. }
  15982. break;
  15983. }
  15984. default: {
  15985. for (const b of cur.blocks()) {
  15986. torch._C.inlineCalls(b);
  15987. }
  15988. }
  15989. }
  15990. }
  15991. });
  15992. this.registerFunction('torch._C.Inline', (graph) => {
  15993. torch._C.inlineCalls(graph.block());
  15994. });
  15995. this.registerFunction('torch._C._jit_pass_inline', (graph) => {
  15996. torch._C.Inline(graph);
  15997. });
  15998. this.registerFunction('torch._C._set_tensor_metadata', (/* tensor, metadata */) => {
  15999. });
  16000. this.registerFunction('torch.jit._script.unpackage_script_module', (importer, script_module_id) => {
  16001. const cu = new torch.jit.CompilationUnit();
  16002. cu.execution = execution;
  16003. const cpp_module = torch._C._import_ir_module_from_package(cu, importer.zip_reader, importer.storage_context, importer.last_map_location, script_module_id);
  16004. return torch.jit._script.wrap_cpp_module(cpp_module);
  16005. });
  16006. this.registerFunction('torch.jit._script.wrap_cpp_module', (cpp_module) => {
  16007. const init_fn = (script_module) => {
  16008. for (const [name, module] of new torch.ModuleDict(script_module._c).items()) {
  16009. script_module.__setattr__(name, torch.jit._script.wrap_cpp_module(module));
  16010. }
  16011. };
  16012. return torch.jit._script.RecursiveScriptModule._construct(cpp_module, init_fn);
  16013. });
  16014. this.registerType('torch._C.DeserializationStorageContext', class extends Map {
  16015. has_storage(name) {
  16016. return this.has(name);
  16017. }
  16018. get_storage(name) {
  16019. return this.get(name);
  16020. }
  16021. add_storage(name, storage) {
  16022. return this.set(name, storage);
  16023. }
  16024. });
  16025. this.registerType('torch.ScriptFunction', class {
  16026. constructor(name, graph /*, function_creator */) {
  16027. this._name = name;
  16028. this._graph = graph;
  16029. }
  16030. });
  16031. this.registerType('torch.ScriptMethod', class {
  16032. constructor(owner, value) {
  16033. this._owner = owner;
  16034. this._function = value;
  16035. }
  16036. get name() {
  16037. return this._function.name();
  16038. }
  16039. get owner() {
  16040. return this._owner;
  16041. }
  16042. __call__(/* args, kwargs */) {
  16043. throw new python.Error("'torch.ScriptMethod.__call__' not implemented.");
  16044. }
  16045. get graph() {
  16046. return this._function.graph();
  16047. }
  16048. get schema() {
  16049. // return this.function().getSchema();
  16050. throw new python.Error("'torch.ScriptMethod.schema' not implemented.");
  16051. }
  16052. get code() {
  16053. throw new python.Error("'torch.ScriptMethod.code' not implemented.");
  16054. }
  16055. get code_with_constants() {
  16056. throw new python.Error("'torch.ScriptMethod.code_with_constants' not implemented.");
  16057. }
  16058. });
  16059. this.registerType('torch.ScriptObject', class {
  16060. constructor(type) {
  16061. this._typ = type;
  16062. this._ivalue = {};
  16063. }
  16064. static create(type) {
  16065. if (type.is_module()) {
  16066. return new torch.ScriptModule(type);
  16067. }
  16068. return new torch.ScriptObject(type);
  16069. }
  16070. type() {
  16071. return this._typ;
  16072. }
  16073. _type() {
  16074. return this._typ; // torch.ClassType
  16075. }
  16076. __setstate__(state) {
  16077. const [attrs, qualname] = state;
  16078. this._typ = torch._C.getCustomClass(qualname);
  16079. if (!this._typ) {
  16080. throw new python.Error(`Unsupported custom class '${qualname}'.`);
  16081. }
  16082. for (let i = 0; i < this._typ.numAttributes(); i++) {
  16083. const name = this._typ.getAttributeName(i);
  16084. this.__setattr__(name, attrs[i]);
  16085. }
  16086. }
  16087. find_method(basename) {
  16088. for (const fn of this.type().methods()) {
  16089. if (fn.name() === basename) {
  16090. return new torch.ScriptMethod(this /* _value() */, fn);
  16091. }
  16092. }
  16093. return null;
  16094. }
  16095. _get_method(name) {
  16096. const method = this.find_method(name);
  16097. if (method) {
  16098. return method;
  16099. }
  16100. torch._C.TORCH_CHECK(false, `Method '${name}' is not defined.`);
  16101. return null;
  16102. }
  16103. _has_method(name) {
  16104. return this.find_method(name) ? true : false;
  16105. }
  16106. _method_names() {
  16107. return this.type().methods().map((fn) => fn.name());
  16108. }
  16109. __setattr__(name, value) {
  16110. // if (this._type.hasContant(name))
  16111. this._ivalue[name] = value;
  16112. }
  16113. __getattr__(name) {
  16114. return this._ivalue[name];
  16115. }
  16116. hasattr(name) {
  16117. return this._typ.hasAttribute(name) || this._typ.hasConstant(name);
  16118. }
  16119. getattr(name) {
  16120. return this.__getattr__(name);
  16121. }
  16122. _properties() {
  16123. throw new python.Error("'torch.ScriptObject._properties' not implemented.");
  16124. }
  16125. is_weak_compilation_ref() {
  16126. return true; // not implemented
  16127. }
  16128. });
  16129. this.registerType('torch.ScriptModule', class extends torch.ScriptObject {
  16130. constructor(...args) {
  16131. if (args[0] instanceof torch._C.QualifiedName && args[1] instanceof torch.jit.CompilationUnit) {
  16132. const [class_name, cu, shouldMangle] = args;
  16133. super(...torch.ScriptModule.create_module_object(class_name, cu, shouldMangle));
  16134. } else {
  16135. super(...args);
  16136. }
  16137. }
  16138. get qualified_name() {
  16139. return this.type().qualified_name();
  16140. }
  16141. get code_with_constants() {
  16142. const const_map = {};
  16143. const_map.const_mapping = new Map(Object.entries(execution.builtins.CONSTANTS));
  16144. return [null, const_map];
  16145. }
  16146. get graph() {
  16147. if (!this._graph) {
  16148. const fn = this._typ.getMethod('forward');
  16149. this._graph = fn.graph();
  16150. }
  16151. return this._graph;
  16152. }
  16153. static create_module_object(class_name, cu, shouldMangle) {
  16154. shouldMangle = shouldMangle || false;
  16155. if (!class_name.prefix()) {
  16156. class_name = new torch._C.QualifiedName('__torch__', class_name.name());
  16157. }
  16158. if (shouldMangle && cu.get_class(class_name)) {
  16159. class_name = cu.mangle(class_name);
  16160. }
  16161. const cls = torch.ClassType.create(class_name, cu, true);
  16162. cu.register_type(cls);
  16163. return [cls, cu];
  16164. }
  16165. register_module(name, module) {
  16166. this.type().addOrCheckAttribute(name, module.type());
  16167. this.__setattr__(name, module); // _ivalue()->setAttr(name, module._ivalue());
  16168. }
  16169. register_buffer(name, v) {
  16170. this.type().addOrCheckAttribute(name, torch.TensorType.get(), false, true);
  16171. this.__setattr__(name, v); // _ivalue()->setAttr(name, std::move(v));
  16172. }
  16173. register_parameter(name, v, is_buffer) {
  16174. this.type().addOrCheckAttribute(name, torch.TensorType.get(), !is_buffer, is_buffer);
  16175. this.__setattr__(name, v); // _ivalue()->setAttr(name, std::move(v));
  16176. }
  16177. register_attribute(name, t, v, is_param, is_buffer) {
  16178. this.type().addOrCheckAttribute(name, t, is_param, is_buffer);
  16179. // _ivalue()->setAttr(name, v);
  16180. }
  16181. });
  16182. this.registerType('torch.ModuleDict', class {
  16183. constructor(mod) {
  16184. this._module = mod;
  16185. }
  16186. items() {
  16187. const result = new Map();
  16188. const type = this._module.type();
  16189. for (let i = 0; i < type.numAttributes(); i++) {
  16190. const k = type.getAttributeName(i);
  16191. const t = type.getAttribute(i);
  16192. if (t && t.is_module()) {
  16193. result.set(k, this._module.__getattr__(k));
  16194. }
  16195. }
  16196. return result;
  16197. }
  16198. });
  16199. this.registerType('torch.ParameterDict', class {
  16200. constructor(mod) {
  16201. this._module = mod;
  16202. }
  16203. items() {
  16204. const result = new Map();
  16205. const type = this._module.type();
  16206. for (let i = 0; i < type.numAttributes(); i++) {
  16207. if (type.is_parameter(i)) {
  16208. const k = type.getAttributeName(i);
  16209. const v = this._module.__getattr__(k);
  16210. if (v instanceof torch.Tensor) {
  16211. result.set(k, v);
  16212. }
  16213. }
  16214. }
  16215. return result;
  16216. }
  16217. });
  16218. this.registerType('torch.BufferDict', class {
  16219. constructor(mod) {
  16220. this._module = mod;
  16221. }
  16222. items() {
  16223. const result = new Map();
  16224. const type = this._module.type();
  16225. for (let i = 0; i < type.numAttributes(); i++) {
  16226. if (type.is_buffer(i)) {
  16227. const t = type.getAttribute(i);
  16228. if (t.isSubtypeOf(torch.TensorType.get())) {
  16229. const k = type.getAttributeName(i);
  16230. const v = this._module.__getattr__(k);
  16231. result.set(k, v);
  16232. }
  16233. }
  16234. }
  16235. return result;
  16236. }
  16237. });
  16238. this.registerType('torch._C.to_ir', class {
  16239. constructor(def, _resolver, self, method) {
  16240. this.method = method;
  16241. this.graph = method.graph();
  16242. this.resolver = _resolver;
  16243. this.integral_constants = new Map();
  16244. this.fp_constants = new Map();
  16245. this.complex_constants = new Map();
  16246. this.exit_blocks = new Set();
  16247. this._typeParser = new torch._C.ScriptTypeParser(this.resolver);
  16248. this._loop_status = 'NOT_IN_LOOP';
  16249. this.environment_stack = null;
  16250. this._def_stack = [];
  16251. this._temp_name_count = 0;
  16252. torch._C.AT_ASSERT(this.resolver);
  16253. this.pushFrame(this.graph.block(), true);
  16254. if (self && def && def.args.args.length === 0) {
  16255. throw new python.Error('Method must have a self argument.');
  16256. }
  16257. method.setSchema(this.emitDef(def, self, this.graph.block()));
  16258. // torch._C.ReplaceOldOperatorsWithUpgraders(this.graph);
  16259. torch._C.ConvertToSSA(this.graph);
  16260. torch._C.CanonicalizeModifiedLoops(this.graph);
  16261. torch._C.NormalizeOps(this.graph.block());
  16262. torch._C.runCleanupPasses(this.graph);
  16263. }
  16264. pushFrame(b, starts_def) {
  16265. starts_def = starts_def || false;
  16266. if (starts_def) {
  16267. this._def_stack.push({});
  16268. }
  16269. this.environment_stack = new torch._C.Environment(this.method, this.resolver, b, this.environment_stack);
  16270. }
  16271. popFrame(ends_def) {
  16272. const old_frame = this.environment_stack;
  16273. this.environment_stack = this.environment_stack.next;
  16274. if (ends_def) {
  16275. this._def_stack.pop();
  16276. }
  16277. return old_frame;
  16278. }
  16279. emitDef(def, self, block) {
  16280. const schema = this._typeParser.parseSchemaFromDef(def, self !== null);
  16281. if (schema.returns.length === 1) {
  16282. this._def_stack[this._def_stack.length - 1]._declared_return_type = schema.returns[0].type;
  16283. }
  16284. const args = this.emitFormalArguments(def, self, schema, block);
  16285. this.emitStatements(def.body);
  16286. this.handleMaybeNoReturn(def, block);
  16287. const returns = [this.emitOutput(def, schema, block)];
  16288. return new torch.FunctionSchema(def.name, '', args, returns);
  16289. }
  16290. emitFormalArguments(def, self, schema, block) {
  16291. const args = [];
  16292. const params = def.args.args;
  16293. const expected_annotation_size = self ? def.args.args.length - 1 : def.args.args.length;
  16294. if (schema.arguments.length !== expected_annotation_size) {
  16295. throw new python.Error('Invalid formal arguments.');
  16296. }
  16297. let it = 0;
  16298. if (self) {
  16299. const param = params[it];
  16300. const name = param.arg;
  16301. const new_input = block.addInput().setDebugName(name);
  16302. this.environment_stack.setSugaredVar(param.range(), name, self.makeSugared(new_input), null);
  16303. args.push(new torch.Argument(name, new_input.type()));
  16304. it++;
  16305. }
  16306. const shouldDeriveType = this.shouldDeriveSetStateType(def, schema);
  16307. let arg_annotation_idx = 0;
  16308. for (; it < params.length; it++) {
  16309. const param = params[it];
  16310. const name = param.arg;
  16311. const new_input = block.addInput();
  16312. if (torch._C.meaningfulName(name)) {
  16313. new_input.setDebugName(name);
  16314. }
  16315. let arg = schema.arguments[arg_annotation_idx++];
  16316. if (shouldDeriveType) {
  16317. if (schema.arguments.length === 1) {
  16318. throw new python.Error('Invalid schema.');
  16319. }
  16320. const inferredStateType = this.getTypeForSetStateArg(def, self);
  16321. arg = arg.cloneWithType(inferredStateType);
  16322. }
  16323. args.push(arg);
  16324. new_input.setType(arg.type);
  16325. this.environment_stack.setVar(param.range(), name, new_input);
  16326. }
  16327. return args;
  16328. }
  16329. emitOutput(range, schema, block) {
  16330. const ret_type = this._def_stack[this._def_stack.length - 1]._merged_return_type;
  16331. const placeholder_return = this.graph.insertNode(this.graph.createUninitialized(ret_type)).output();
  16332. block.registerOutput(placeholder_return);
  16333. return new torch.Argument('', this._def_stack[this._def_stack.length - 1]._merged_return_type);
  16334. }
  16335. emitStatements(stmts) {
  16336. for (let i = 0; i < stmts.length; i++) {
  16337. const stmt = stmts[i];
  16338. if (stmt instanceof ast.If) {
  16339. this.emitIf(stmt);
  16340. } else if (stmt instanceof ast.While) {
  16341. this.emitWhile(stmt);
  16342. } else if (stmt instanceof ast.For) {
  16343. this.emitFor(stmt);
  16344. } else if (stmt instanceof ast.Assign) {
  16345. this.emitAssignment(stmt);
  16346. } else if (stmt instanceof ast.AnnAssign) {
  16347. this.emitAssignment(stmt);
  16348. } else if (stmt instanceof ast.Expr) {
  16349. this.emitSugaredExpr(stmt.value, 0);
  16350. } else if (stmt instanceof ast.Return) {
  16351. this.emitReturn(stmt);
  16352. } else if (stmt instanceof ast.Pass) {
  16353. // pass
  16354. } else if (stmt instanceof ast.With) {
  16355. this.emitWith(stmt);
  16356. } else {
  16357. throw new python.Error(`Unrecognized statement kind '${stmt.__class__.__name__}'.`);
  16358. }
  16359. if (this.exit_blocks.has(this.environment_stack.block())) {
  16360. return;
  16361. }
  16362. }
  16363. }
  16364. emitWith(stmt) {
  16365. const targets = stmt.items;
  16366. const entered = [];
  16367. for (const target of targets) {
  16368. const e = target.context_expr;
  16369. const rhs = this.emitExpr(e);
  16370. const n = this.graph.insertNode(this.graph.create('prim::Enter', [rhs]));
  16371. entered.push(rhs);
  16372. if (rhs.type() instanceof torch.ClassType === false) {
  16373. throw new python.Error('With item expression must return an object.');
  16374. }
  16375. const rhsClass = rhs.type();
  16376. const enterMethod = rhsClass.findMethod('__enter__');
  16377. const exitMethod = rhsClass.findMethod('__exit__');
  16378. if (!enterMethod || !exitMethod) {
  16379. throw new python.Error('Object returned by with item expression does not define __enter__ and __exit__ methods.');
  16380. }
  16381. const enterSchema = enterMethod.getSchema();
  16382. if (enterSchema.arguments.length !== 1) {
  16383. throw new python.Error('__enter__ must have only one argument and one return value.');
  16384. }
  16385. const exitSchema = exitMethod.getSchema();
  16386. if (exitSchema.arguments.length === 4) {
  16387. for (let i = 1; i < 4; i++) {
  16388. if (exitSchema.arguments[i].type !== torch.AnyType.get()) {
  16389. throw new python.Error('Argument of __exit__ must have Any type.');
  16390. }
  16391. }
  16392. } else {
  16393. throw new python.Error('__exit__ must have four arguments');
  16394. }
  16395. n.output(0).setType(enterSchema.returns[0].type);
  16396. if (target.optional_vars) {
  16397. throw new python.Error('Not implemented.');
  16398. // Var i = target.var().get();
  16399. // this.environment_stack.setVar(i.range(), i.name().name(), n.output(0));
  16400. }
  16401. }
  16402. this.emitStatements(stmt.body);
  16403. while (entered.length > 0) {
  16404. const input = entered.pop();
  16405. const n = this.graph.create('prim::Exit');
  16406. this.graph.insertNode(n);
  16407. n.addInput(input);
  16408. }
  16409. }
  16410. emitLoopCommon(range, emit_body, iter_val, targets, cond) {
  16411. let max_trip_count_val = null;
  16412. if (iter_val === null) {
  16413. max_trip_count_val = torch._C.materializeConstant(Number.MAX_SAFE_INTEGER /*std::numeric_limits<int64_t>::max()*/, this.graph, range, this.integral_constants);
  16414. } else {
  16415. max_trip_count_val = iter_val.len(range, this.method);
  16416. }
  16417. const n = this.graph.insertNode(this.create('prim::Loop', range, 0));
  16418. const body_block = n.addBlock();
  16419. {
  16420. const condition_block = n.addBlock();
  16421. this.pushFrame(condition_block);
  16422. let out = null;
  16423. if (cond) {
  16424. const insert = new torch._C.WithInsertPoint(condition_block);
  16425. out = this.emitToBool(cond.range(), this.emitExpr(cond));
  16426. insert.dispose();
  16427. } else {
  16428. const insert = new torch._C.WithInsertPoint(n);
  16429. out = this.graph.insertConstant(true, range);
  16430. insert.dispose();
  16431. }
  16432. condition_block.registerOutput(out);
  16433. this.popFrame();
  16434. }
  16435. n.addInput(max_trip_count_val);
  16436. const loop_guard = new torch._C.WithLoopStatus(this, 'IN_LOOP');
  16437. const trip_count = body_block.addInput().setType(torch.IntType.get());
  16438. {
  16439. this.pushFrame(body_block);
  16440. const guard = new torch._C.WithInsertPoint(body_block);
  16441. if (iter_val !== null && targets) {
  16442. const cur_elem = iter_val.getitem(range, this.method, trip_count).asValue(range, this.method);
  16443. const sv = new torch._C.SimpleValue(cur_elem);
  16444. const target_exprs = targets;
  16445. this.validateAssignLhsExpr(target_exprs, range);
  16446. if (target_exprs.length > 1) {
  16447. throw new python.Error('Not implemented.');
  16448. // const tl = torch.TupleLiteral.create(range, target_exprs);
  16449. // target_exprs = ListExpr.create(range, [tl]);
  16450. }
  16451. this.emitExprsAssign(target_exprs, [sv], range, /*n_binders=*/1);
  16452. }
  16453. emit_body();
  16454. this.popFrame();
  16455. guard.dispose();
  16456. }
  16457. loop_guard.dispose();
  16458. }
  16459. emitFor(...args) {
  16460. if (args.length === 1 && args[0] instanceof ast.For) {
  16461. const [stmt] = args;
  16462. const emit_body = () => this.emitStatements(stmt.body);
  16463. this.emitFor(stmt.target, stmt.iter, stmt.range(), emit_body);
  16464. } else if (args.length === 4) {
  16465. const [targets, itrs, loc, emit_body] = args;
  16466. if (itrs instanceof ast.Tuple) {
  16467. throw new python.Error('List of iterables is not supported currently.');
  16468. }
  16469. const sv = this.emitSugaredExpr(itrs, 1);
  16470. const iterable = sv.iter(loc, this.method);
  16471. if (iterable.shouldEmitUnrolled()) {
  16472. this.emitUnrolledLoop(loc, emit_body, iterable, targets);
  16473. } else {
  16474. this.emitLoopCommon(loc, emit_body, iterable, [targets], null);
  16475. }
  16476. } else {
  16477. throw new python.Error('Not implemented.');
  16478. }
  16479. }
  16480. emitWhile(stmt) {
  16481. const cond = stmt.test;
  16482. const emit_body = () => this.emitStatements(stmt.body);
  16483. this.emitLoopCommon(stmt.range(), emit_body, null, [], cond);
  16484. }
  16485. emitIsInstance(obj, classinfo) {
  16486. const lhs_val = this.emitExpr(obj);
  16487. const lhs_types = [];
  16488. const rhs_types = [];
  16489. const gather_rhs = (expr) => {
  16490. if (expr instanceof ast.Tuple) {
  16491. for (const e of expr.elts) {
  16492. gather_rhs(e);
  16493. }
  16494. return;
  16495. }
  16496. const type = this._typeParser.parseTypeFromExpr(expr);
  16497. rhs_types.push(type);
  16498. };
  16499. lhs_types.push(lhs_val.type());
  16500. gather_rhs(classinfo);
  16501. torch._C.standardizeVectorForUnion(lhs_types);
  16502. torch._C.standardizeVectorForUnion(rhs_types);
  16503. let refinement = new torch._C.RefinementSet([], []);
  16504. let unified_true = null;
  16505. let unified_false = null;
  16506. const isinstance_types = [];
  16507. const not_isinstance_types = [];
  16508. let true_refinements = [];
  16509. let false_refinements = [];
  16510. let all_lhs_subtype_some_rhs = true;
  16511. for (const lhs_type of lhs_types) {
  16512. if (lhs_type === torch.AnyType.get()) {
  16513. isinstance_types.push(...rhs_types);
  16514. not_isinstance_types.push(torch.AnyType.get());
  16515. if (isinstance_types.length !== 1 || isinstance_types[0] !== torch.AnyType.get()) {
  16516. all_lhs_subtype_some_rhs = false;
  16517. }
  16518. break;
  16519. }
  16520. const get_smaller_type = (t1, t2) => {
  16521. if (t1.isSubtypeOf(t2)) {
  16522. return t1;
  16523. } else if (t2.isSubtypeOf(t1)) {
  16524. return t2;
  16525. }
  16526. return null;
  16527. };
  16528. let found_refinement = null;
  16529. for (const rhs_type of rhs_types) {
  16530. const maybe_smaller_type = get_smaller_type(lhs_type, rhs_type);
  16531. if (!maybe_smaller_type) {
  16532. continue;
  16533. } else if (maybe_smaller_type === lhs_type) {
  16534. found_refinement = lhs_type;
  16535. } else if (maybe_smaller_type === rhs_type) {
  16536. found_refinement = found_refinement ? torch._C.unifyTypes(found_refinement, rhs_type) : rhs_type;
  16537. }
  16538. }
  16539. if (found_refinement) {
  16540. if (found_refinement === lhs_type) {
  16541. all_lhs_subtype_some_rhs &= true;
  16542. }
  16543. isinstance_types.push(found_refinement);
  16544. } else {
  16545. not_isinstance_types.push(lhs_type);
  16546. all_lhs_subtype_some_rhs = false;
  16547. }
  16548. }
  16549. if (isinstance_types.length > 0) {
  16550. unified_true = torch._C.unifyTypeList(isinstance_types, null, /*default_to_union=*/true);
  16551. }
  16552. if (obj instanceof ast.Name && unified_true) {
  16553. const ident = obj.id;
  16554. true_refinements = [new torch._C.Refinement(ident, unified_true)];
  16555. }
  16556. if (not_isinstance_types.length > 0) {
  16557. unified_false = torch._C.unifyTypeList(not_isinstance_types, null, /*default_to_union=*/true);
  16558. }
  16559. if (obj instanceof ast.Name && unified_false) {
  16560. const ident = obj.id;
  16561. false_refinements = [new torch._C.Refinement(ident, unified_false)];
  16562. }
  16563. refinement = new torch._C.RefinementSet(true_refinements, false_refinements);
  16564. const is_statically_false = isinstance_types.length === 0;
  16565. if (all_lhs_subtype_some_rhs) {
  16566. return new torch._C.CondValue(this.graph, obj.range(), true, refinement);
  16567. }
  16568. if (is_statically_false) {
  16569. return new torch._C.CondValue(this.graph, obj.range(), false, refinement);
  16570. }
  16571. const result = this.graph.insertNode(this.graph.createIsInstance(lhs_val, rhs_types)).output();
  16572. return new torch._C.CondValue(result, refinement, null);
  16573. }
  16574. emitIf(stmt) {
  16575. const cond_value = this.emitCondExpr(stmt.test);
  16576. this.emitIfElseBlocks(stmt.range(), cond_value, stmt.body, stmt.orelse);
  16577. }
  16578. emitCondExpr(expr) {
  16579. /*
  16580. switch (expr.kind()) {
  16581. case TK_AND:
  16582. case TK_OR: {
  16583. const binop = BinOp(expr);
  16584. return emitShortCircuitLogical(
  16585. binop.range(), binop.lhs(), binop.rhs(), expr.kind() == TK_OR);
  16586. }
  16587. case TK_NOT: {
  16588. CondValue v = emitCondExpr(Expr(expr.tree().trees()[0]));
  16589. Value* result = emitBuiltinCall(
  16590. expr.range(), *graph, aten::__not__, {v.value()}, {});
  16591. std::optional<bool> static_if;
  16592. if (v.staticIf()) {
  16593. static_if = !*v.staticIf();
  16594. }
  16595. return CondValue(result, v.refinements().Not(), static_if);
  16596. } break;
  16597. case TK_IS:
  16598. case TK_ISNOT: {
  16599. // meta programming on AST for is/is not cases and emit branches base on
  16600. const cond_op = BinOp(expr);
  16601. Value* lhs_val = emitExpr(cond_op.lhs());
  16602. Value* rhs_val = emitExpr(cond_op.rhs());
  16603. const lhs_none = canBeNone(lhs_val);
  16604. const rhs_none = canBeNone(rhs_val);
  16605. // Dispatch logic (A: ALWAYS, N: NEVER, M: MAYBE):
  16606. // AA, -> statically IS always holds, IS_NOT never holds
  16607. // AN , NA-> statically IS_NOT always holds, IS never holds
  16608. // MA, MM, MN, NM, NN, AM -> cannot prove anything statically
  16609. bool its_is = expr.kind() == TK_IS;
  16610. if (lhs_none == ALWAYS && rhs_none == ALWAYS) {
  16611. return CondValue(*graph, expr.range(), its_is, {});
  16612. } else if (
  16613. (lhs_none == ALWAYS && rhs_none == NEVER) ||
  16614. (lhs_none == NEVER && rhs_none == ALWAYS)) {
  16615. // lhs_val/rhs_val with A/M: only emit never_none_branch
  16616. return CondValue(*graph, expr.range(), !its_is, {});
  16617. } else {
  16618. const kind = getNodeKind(expr.kind(), expr.get()->trees().size());
  16619. Value* cond_value = emitBuiltinCall(
  16620. expr.get()->range(),
  16621. *method.graph(),
  16622. kind,
  16623. {lhs_val, rhs_val},
  16624. {});
  16625. const refinements = RefinementSet(findIsNoneRefinements(
  16626. cond_op.lhs(), lhs_val, cond_op.rhs(), rhs_val, expr.kind()));
  16627. return CondValue(cond_value, refinements, null);
  16628. }
  16629. } break;
  16630. */
  16631. if (expr instanceof ast.UnaryOp) {
  16632. throw new python.Error('Not implemented.');
  16633. }
  16634. if (expr instanceof ast.Call) {
  16635. const apply = expr;
  16636. const callee = expr.func;
  16637. if (callee instanceof ast.Name) {
  16638. if (callee.id === 'isinstance') {
  16639. this.checkApplyNumInputs(apply, 2);
  16640. return this.emitIsInstance(apply.args[0], apply.args[1]);
  16641. }
  16642. if (callee.id === 'hasattr') {
  16643. this.checkApplyNumInputs(apply, 2);
  16644. return this.emitHasAttr(apply.args[0], apply.args[1]);
  16645. }
  16646. const sv = this.emitSugaredExpr(callee, 1);
  16647. if (sv instanceof torch._C.SpecialFormValue) {
  16648. if (sv.form() === 'prim::isinstance') {
  16649. this.checkApplyNumInputs(apply, 2);
  16650. return this.emitIsInstance(apply.inputs()[0], apply.inputs()[1]);
  16651. }
  16652. }
  16653. }
  16654. }
  16655. const expr_out = this.emitToBool(expr, this.emitExpr(expr));
  16656. let static_if = null;
  16657. const kind = expr_out.node().kind();
  16658. if (kind === 'aten::is_scripting') {
  16659. static_if = true;
  16660. } else if (kind === 'aten::has_torch_function') {
  16661. static_if = false;
  16662. }
  16663. const maybe_ivalue = torch._C.toIValue(expr_out);
  16664. if (maybe_ivalue) {
  16665. static_if = maybe_ivalue.toBool();
  16666. }
  16667. return new torch._C.CondValue(expr_out, new torch._C.RefinementSet([], []), static_if);
  16668. }
  16669. emitIfElseBlocks(loc, cond_value, trueBranch, falseBranch) {
  16670. if (cond_value.staticIf() !== null) {
  16671. if (cond_value.staticIf()) {
  16672. this.insertRefinements(loc, cond_value.refinements());
  16673. this.emitStatements(trueBranch);
  16674. } else {
  16675. this.insertRefinements(loc, cond_value.refinements().Not());
  16676. this.emitStatements(falseBranch);
  16677. }
  16678. return;
  16679. }
  16680. const n = this.graph.insertNode(this.create('prim::If', loc, 0));
  16681. n.addInput(cond_value.value());
  16682. const true_block = n.addBlock();
  16683. const false_block = n.addBlock();
  16684. const save_true = this.emitSingleIfBranch(true_block, trueBranch, cond_value.refinements());
  16685. const save_false = this.emitSingleIfBranch(false_block, falseBranch, cond_value.refinements().Not());
  16686. const true_exits = this.exit_blocks.has(true_block);
  16687. const false_exits = this.exit_blocks.has(false_block);
  16688. if (true_exits && false_exits) {
  16689. this.exit_blocks.add(n.owningBlock());
  16690. }
  16691. const mutated_variables = new Set();
  16692. for (const v of save_true.definedVariables()) {
  16693. const insert = new torch._C.WithInsertPoint(false_block);
  16694. if (save_false.findInAnyFrame(v) || false_exits) {
  16695. mutated_variables.add(v);
  16696. } else {
  16697. this.environment_stack.setVariableTypeError(v, () => 'Value is not defined in the false branch.');
  16698. }
  16699. insert.dispose();
  16700. }
  16701. for (const v of save_false.definedVariables()) {
  16702. const insert = new torch._C.WithInsertPoint(true_block);
  16703. if (save_true.findInAnyFrame(v) || true_exits) {
  16704. mutated_variables.add(v);
  16705. } else {
  16706. this.environment_stack.setVariableTypeError(v, () => 'Value is not defined in the true branch.');
  16707. }
  16708. insert.dispose();
  16709. }
  16710. for (const x of mutated_variables) {
  16711. let tv = null;
  16712. let fv = null;
  16713. {
  16714. const insert = new torch._C.WithInsertPoint(true_block);
  16715. if (!true_exits) {
  16716. tv = save_true.getVar(x, loc);
  16717. }
  16718. insert.dispose();
  16719. }
  16720. {
  16721. const insert = new torch._C.WithInsertPoint(false_block);
  16722. if (!false_exits) {
  16723. fv = save_false.getVar(x, loc);
  16724. }
  16725. insert.dispose();
  16726. }
  16727. if (true_exits && false_exits) {
  16728. continue;
  16729. } else if (true_exits) {
  16730. tv = this.graph.createUninitialized(fv.type()).insertBefore(true_block.return_node()).output();
  16731. this.graph.createStore(x, tv).insertBefore(true_block.return_node());
  16732. } else if (false_exits) {
  16733. fv = this.graph.createUninitialized(tv.type()).insertBefore(false_block.return_node()).output();
  16734. this.graph.createStore(x, fv).insertBefore(false_block.return_node());
  16735. }
  16736. const maybe_sugared_x = this.environment_stack.findInAnyFrame(x);
  16737. let full_type = null;
  16738. if (maybe_sugared_x) {
  16739. const maybe_simple = torch._C.asSimple(maybe_sugared_x);
  16740. if (maybe_simple) {
  16741. full_type = maybe_simple.type();
  16742. }
  16743. }
  16744. const default_to_union = full_type && (full_type instanceof torch.UnionType || full_type instanceof torch.OptionalType || full_type instanceof torch.NumberType);
  16745. const unified = torch._C.unifyTypes(tv.type(), fv.type(), /*default_to_union=*/default_to_union);
  16746. if (!unified) {
  16747. if (save_true.findInParentFrame(x) || save_false.findInParentFrame(x)) {
  16748. throw new python.Error('Type mismatch.');
  16749. } else {
  16750. this.environment_stack.setVariableTypeError(x, () => 'Type mismatch.');
  16751. continue;
  16752. }
  16753. }
  16754. this.environment_stack.setType(x, unified);
  16755. }
  16756. }
  16757. emitSingleIfBranch(b, branch, refinements) {
  16758. this.pushFrame(b);
  16759. const guard = new torch._C.WithInsertPoint(b);
  16760. this.insertRefinements(branch, refinements);
  16761. this.emitStatements(branch);
  16762. const frame = this.popFrame();
  16763. guard.dispose();
  16764. return frame;
  16765. }
  16766. create(kind, loc, n_outputs) {
  16767. return this.graph.create(kind, n_outputs).setSourceRange(loc);
  16768. }
  16769. refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint_ptr, all_candidates, match_repr, src, type_match, do_if_match, do_if_anytype, is_dict_constructor) {
  16770. is_dict_constructor = is_dict_constructor || false;
  16771. if (refined_type_hint_ptr._ instanceof torch.UnionType) {
  16772. const candidate_types = refined_type_hint_ptr._.containedTypes().filter((type_ptr) => type_match(type_ptr));
  16773. if (!is_dict_constructor && candidate_types.length === 0) {
  16774. throw new python.Error("No matching types found in Union type annotation.");
  16775. } else if (candidate_types.length === 1) {
  16776. [refined_type_hint_ptr._] = candidate_types;
  16777. } else {
  16778. all_candidates._ = candidate_types;
  16779. }
  16780. } else if (refined_type_hint_ptr._ instanceof torch.OptionalType) {
  16781. refined_type_hint_ptr._ = refined_type_hint_ptr._.getElementType();
  16782. }
  16783. if (is_dict_constructor) {
  16784. return;
  16785. }
  16786. if (all_candidates._.length === 0) {
  16787. if (type_match(refined_type_hint_ptr._)) {
  16788. do_if_match();
  16789. } else if (refined_type_hint_ptr._.kind() === 'AnyType') {
  16790. do_if_anytype();
  16791. } else {
  16792. throw new python.Error('Invalid annotation type.');
  16793. }
  16794. }
  16795. }
  16796. emitToBool(loc, v) {
  16797. let out = null;
  16798. const bool_cast = this.environment_stack.getSugaredVar('bool', loc);
  16799. out = torch._C.asSimple(bool_cast.call(loc, this.method, [new torch._C.NamedValue(v)], [], 0));
  16800. if (!out) {
  16801. throw new python.Error('Could not cast value to bool.');
  16802. }
  16803. if (!out.type().isSubtypeOf(torch.BoolType.get())) {
  16804. throw new python.Error('Expected a bool expression for condition.');
  16805. }
  16806. return out;
  16807. }
  16808. emitUnaryOp(tree, magicMethod, opSymbol) {
  16809. const inputs = [tree.operand];
  16810. const named_values = this.getNamedValues(inputs, /*maybe_unpack=*/false);
  16811. const val = torch._C.asSimple(torch._C.makeMagic(magicMethod, new torch._C.BuiltinFunction(opSymbol, null)).call(tree.range(), this.method, named_values, [], 0));
  16812. if (val.node().kind() !== opSymbol) {
  16813. return val;
  16814. }
  16815. const maybe_out_stack = torch._C.runNodeIfInputsAreConstant(val.node());
  16816. if (!maybe_out_stack) {
  16817. return val;
  16818. }
  16819. torch._C.TORCH_INTERNAL_ASSERT(maybe_out_stack.length === 1);
  16820. return this.graph.insertConstant(maybe_out_stack[0], tree);
  16821. }
  16822. emitAssignment(stmt) {
  16823. if (stmt instanceof ast.AnnAssign) {
  16824. return this.emitSingleAssignment(stmt);
  16825. }
  16826. if (stmt.targets.length === 1) {
  16827. const entries = Object.entries(stmt).filter(([key]) => key !== 'targets' && key !== 'value' && key !== 'ctx');
  16828. const assign = new ast.AnnAssign(stmt.targets[0], null, stmt.value, stmt.targets[0] instanceof ast.Name);
  16829. for (const [key, value] of entries) {
  16830. assign[key] = value;
  16831. }
  16832. return this.emitSingleAssignment(assign);
  16833. }
  16834. if (stmt.targets.length <= 1) {
  16835. throw new python.Error('Invalid assignment.');
  16836. }
  16837. throw new python.Error('Not implemented.');
  16838. /*
  16839. const tmp_name = this.createTempName('$tmp_assign_');
  16840. this.environment_stack.setSugaredVar(stmt.value, tmp_name, this.emitSugaredExpr(stmt.value, 1), annotated_type=null);
  16841. const ident = new ast.Name(tmp_name);
  16842. for (const expr of lhs_list) {
  16843. const assign = new ast.Assign(targets, value, ctx);
  16844. this.emitSingleAssignment(Assign.create(stmt,
  16845. List<Expr>.create(expr.range(), [expr]),
  16846. Maybe<Expr>::create(stmt.rhs().range(), ident),
  16847. Maybe<Expr>::create(stmt.range())));
  16848. }
  16849. */
  16850. }
  16851. emitSingleAssignment(stmt) {
  16852. torch._C.AT_ASSERT(stmt instanceof ast.AnnAssign);
  16853. const rhs = stmt.value;
  16854. const lhs = stmt.target;
  16855. if (lhs instanceof ast.Name) {
  16856. let type = null;
  16857. if (stmt.annotation) {
  16858. type = this._typeParser.parseTypeFromExpr(stmt.annotation);
  16859. }
  16860. const rhs_sugared_val = this.emitSugaredExpr(rhs, 1, type);
  16861. // BC HACK
  16862. this.environment_stack.setSugaredVar(stmt.range(), lhs.id, rhs_sugared_val, /*annotated_type=*/type);
  16863. } else if (lhs instanceof ast.Tuple) {
  16864. this.emitTupleAssign(lhs, rhs);
  16865. } else if (lhs instanceof ast.Attribute) {
  16866. this.emitSelectAssign(lhs, rhs, null, stmt.range());
  16867. } else {
  16868. throw new python.Error('Unexpected expression on left-hand side of assignment.');
  16869. }
  16870. }
  16871. emitSelectAssign(lhs, rhs, type, loc) {
  16872. if (!rhs) {
  16873. throw new python.Error('Expected RHS for assignment.');
  16874. }
  16875. let type_hint = null;
  16876. if (type) {
  16877. type_hint = this._typeParser.parseTypeFromExpr(type);
  16878. }
  16879. const lhsObject = this.emitSugaredExpr(lhs.value, 1);
  16880. const rhsValue = this.emitSugaredExpr(rhs, 1, type_hint).asValue(rhs.range(), this.method);
  16881. lhsObject.setAttr(loc, this.method, lhs.attr, rhsValue);
  16882. }
  16883. emitTupleAssign(...args) {
  16884. if (args.length === 2) {
  16885. const [tl, rhs] = args;
  16886. let n_binders = tl.elts.length;
  16887. const starred_unpack = this.validateAssignLhsExpr(tl.elts, tl);
  16888. if (starred_unpack) {
  16889. n_binders--;
  16890. }
  16891. const output = this.emitSugaredExpr(rhs, n_binders);
  16892. this.emitTupleAssign(tl, output, rhs.range(), n_binders, starred_unpack);
  16893. } else if (args.length === 5) {
  16894. const [tl, rhs_output, rhs_loc, n_binders, starred_unpack] = args;
  16895. const outputs = rhs_output.asTuple(rhs_loc, this.method, starred_unpack ? null : n_binders);
  16896. if (outputs.length < n_binders) {
  16897. throw new python.Error('Not enough values to unpack.');
  16898. }
  16899. if (outputs.length > n_binders && !starred_unpack) {
  16900. throw new python.Error('Too many values to unpack.');
  16901. }
  16902. this.emitExprsAssign(tl.elts, outputs, rhs_loc, n_binders);
  16903. } else {
  16904. throw new python.Error('Not implemented.');
  16905. }
  16906. }
  16907. emitExprsAssign(lhs_exprs, outputs /*, rhs_loc, n_binders */) {
  16908. let i = 0;
  16909. for (const assignee of lhs_exprs) {
  16910. if (assignee instanceof ast.Subscript) {
  16911. throw new python.Error('Not implemented.');
  16912. /*
  16913. this.emitSubscriptAssign(
  16914. rhs_loc,
  16915. Subscript(assignee),
  16916. NamedValue(rhs_loc, outputs.at(i).asValue(rhs_loc, method)));
  16917. i++;
  16918. */
  16919. } else if (assignee instanceof ast.Name) {
  16920. this.environment_stack.setSugaredVar(assignee.range(), assignee.id, outputs[i], /*annotated_type=*/null);
  16921. i++;
  16922. } else if (assignee instanceof ast.Starred) {
  16923. throw new python.Error('Not implemented.');
  16924. /*
  16925. const var = Starred(assignee).expr();
  16926. if (var.kind() != TK_VAR) {
  16927. throw(
  16928. ErrorReport(var) << 'Cannot pack a tuple into a non-variable');
  16929. }
  16930. size_t n_matched = outputs.size() - n_binders;
  16931. ArrayRef<std::shared_ptr<SugaredValue>> outputs_ref = outputs;
  16932. const values = fmap(
  16933. outputs_ref.slice(i, n_matched),
  16934. [&](const std::shared_ptr<SugaredValue>& v) {
  16935. return v.asValue(assignee.range(), method);
  16936. });
  16937. const tup = graph.insertNode(graph.createTuple(values)).output();
  16938. environment_stack.setVar(var.range(), Var(var).name().name(), tup);
  16939. i += n_matched;
  16940. */
  16941. } else if (assignee instanceof ast.Tuple) {
  16942. throw new python.Error('Not implemented.');
  16943. /*
  16944. // recursively emit tuple assignments on tuple literal input
  16945. TupleLiteral sub_tl = TupleLiteral(assignee);
  16946. size_t sub_n_binders = sub_tl.inputs().length;
  16947. bool sub_starred_unpack =
  16948. validateAssignLhsExpr(sub_tl.inputs(), sub_tl.range());
  16949. if (sub_starred_unpack)
  16950. sub_n_binders--;
  16951. emitTupleAssign(
  16952. sub_tl,
  16953. outputs.at(i),
  16954. rhs_loc,
  16955. sub_n_binders,
  16956. sub_starred_unpack);
  16957. i++;
  16958. */
  16959. } else if (assignee instanceof ast.Attribute) {
  16960. throw new python.Error('Not implemented.');
  16961. /*
  16962. emitSelectAssign(assignee, outputs.at(i), rhs_loc);
  16963. i++;
  16964. */
  16965. } else {
  16966. throw new python.Error('Unexpected expression on left-hand side of assignment.');
  16967. }
  16968. }
  16969. }
  16970. emitReturn(stmt) {
  16971. let declared_return_type = this._def_stack[this._def_stack.length - 1]._declared_return_type;
  16972. let actual_return = this.emitExpr(stmt.value, declared_return_type);
  16973. if (declared_return_type) {
  16974. if (!(actual_return.type().isSubtypeOf(torch.TensorType.get()) && actual_return.type().isSubtypeOf(torch.NoneType.get()))) {
  16975. actual_return = torch._C.tryConvertToType(stmt, this.graph, declared_return_type, actual_return, /*allow_conversions=*/true);
  16976. }
  16977. if (!actual_return.type().isSubtypeOf(declared_return_type)) {
  16978. throw new python.Error(`Invalid return type.`);
  16979. }
  16980. } else {
  16981. declared_return_type = this._def_stack[this._def_stack.length - 1]._merged_return_type;
  16982. if (!declared_return_type) {
  16983. declared_return_type = actual_return.type();
  16984. }
  16985. const merged_return_type = torch._C.unifyTypes(declared_return_type, actual_return.type());
  16986. if (!merged_return_type) {
  16987. throw new python.Error(`Invalid return type.`);
  16988. }
  16989. declared_return_type = merged_return_type;
  16990. }
  16991. this._def_stack[this._def_stack.length - 1]._merged_return_type = declared_return_type;
  16992. if (declared_return_type === torch.AnyType.get() && actual_return.type() !== torch.AnyType.get()) {
  16993. actual_return = this.graph.insertUncheckedCast(actual_return, declared_return_type);
  16994. }
  16995. this.graph.insertNode(this.graph.create('prim::ReturnStmt', [actual_return], 0));
  16996. this.exit_blocks.add(this.environment_stack.block());
  16997. }
  16998. getNamedValues(trees, maybe_unpack) {
  16999. const values = [];
  17000. for (const tree of trees) {
  17001. if (maybe_unpack && tree instanceof ast.Starred) {
  17002. throw new python.Error('Starred argument not supported.');
  17003. } else {
  17004. values.push(new torch._C.NamedValue(this.emitExpr(tree)));
  17005. }
  17006. }
  17007. return values;
  17008. }
  17009. getValues(trees, maybe_unpack) {
  17010. return this.getNamedValues(trees, maybe_unpack).map((value) => value.value(this.graph));
  17011. }
  17012. emitExpr(tree, type_hint) {
  17013. type_hint = type_hint || null;
  17014. let out_val = this.emitSugaredExpr(tree, 1, type_hint).asValue(tree, this.method);
  17015. if (type_hint === torch.AnyType.get() && out_val.type() !== torch.AnyType.get()) {
  17016. out_val = this.graph.insertUncheckedCast(out_val, type_hint);
  17017. }
  17018. return out_val;
  17019. }
  17020. emitSugaredExpr(tree, n_binders, type_hint) {
  17021. if (tree instanceof ast.Name) { // TK_VAR
  17022. return this.environment_stack.getSugaredVar(tree.id);
  17023. } else if (tree instanceof ast.Attribute) {
  17024. const sv = this.emitSugaredExpr(tree.value, 1);
  17025. return sv.attr(tree.range(), this.method, tree.attr);
  17026. } else if (tree instanceof ast.Call) { // TK_APPLY
  17027. return this.emitApplyExpr(tree, n_binders, type_hint);
  17028. } if (tree instanceof ast.Subscript) {
  17029. return this.emitSubscript(tree, type_hint);
  17030. }
  17031. return new torch._C.SimpleValue(this.emitSimpleExpr(tree, type_hint));
  17032. }
  17033. emitApplyExpr(apply, n_binders, type_hint) {
  17034. type_hint = type_hint || null;
  17035. const sv = this.emitSugaredExpr(apply.func, 1);
  17036. const loc = apply.func.range();
  17037. if (sv instanceof torch._C.SpecialFormValue) {
  17038. return this.emitApplySpecialForm(sv.form(), apply, sv, type_hint);
  17039. }
  17040. const args = this.getNamedValues(apply.args, true);
  17041. const kwargs = this.emitAttributes(apply.keywords);
  17042. return sv.call(loc, this.method, args, kwargs, n_binders);
  17043. }
  17044. emitAttributes(attributes) {
  17045. return attributes.map((attr) => new torch._C.NamedValue(attr.range(), attr.arg, this.emitExpr(attr.value)));
  17046. }
  17047. emitApplySpecialForm(form, apply, sv, type_hint) {
  17048. switch (form) {
  17049. case 'prim::fork': {
  17050. throw new python.Error('Not implemented.');
  17051. }
  17052. case 'prim::awaitable': {
  17053. throw new python.Error('Not implemented.');
  17054. }
  17055. case 'prim::annotate': {
  17056. this.checkApplyNumInputs(apply, 2);
  17057. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  17058. let expr = torch._C.tryConvertToType(apply.range(), this.graph, type, this.emitExpr(apply.args[1], type), /*allow_conversions=*/true);
  17059. if (!expr.type().isSubtypeOf(type)) {
  17060. throw new python.Error('Invalid expression type.');
  17061. }
  17062. if ((type instanceof torch.OptionalType || (type instanceof torch.UnionType && type.expect(torch.UnionType).canHoldType(torch.NoneType.get()))) && expr.type().isSubtypeOf(torch.NoneType.get())) {
  17063. const none = this.graph.createNone();
  17064. none.output().setType(type);
  17065. this.graph.insertNode(none);
  17066. expr = none.output();
  17067. }
  17068. return new torch._C.SimpleValue(expr);
  17069. }
  17070. case 'prim::unchecked_cast': {
  17071. this.checkApplyNumInputs(apply, 2);
  17072. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  17073. let v = this.emitExpr(apply.args[1]);
  17074. if (v.node().kind() !== 'prim::unchecked_cast' || v.type() !== type) {
  17075. v = this.graph.insertUncheckedCast(v, type);
  17076. }
  17077. return new torch._C.SimpleValue(v);
  17078. }
  17079. case 'prim::GetAttr': {
  17080. this.checkApplyNumInputsRange(apply, 2, 3);
  17081. const obj = this.emitSugaredExpr(apply.args[0], 1);
  17082. if (apply.args[1] instanceof ast.Constant === false || typeof apply.args[1].value !== 'string') {
  17083. throw new python.Error('Invalid argument.');
  17084. }
  17085. const name = apply.args[1].value;
  17086. if (apply.args.length === 2) {
  17087. return obj.attr(apply, this.method, name);
  17088. } else if (obj.hasAttr(apply, this.method, name)) {
  17089. return obj.attr(apply, this.method, name);
  17090. }
  17091. return this.emitSugaredExpr(apply.inputs()[2], 1);
  17092. }
  17093. case 'prim::Uninitialized': {
  17094. this.checkApplyNumInputs(apply, 1);
  17095. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  17096. const out = this.graph.insertNode(this.graph.createUninitialized(type)).setSourceRange(apply.range());
  17097. return new torch._C.SimpleValue(out.output());
  17098. }
  17099. case 'prim::TupleConstruct': {
  17100. throw new python.Error('Not implemented.');
  17101. }
  17102. case 'prim::isinstance': {
  17103. this.checkApplyNumInputs(apply, 2);
  17104. const result = this.emitIsInstance(apply.args[0], apply.args[1]);
  17105. return new torch._C.SimpleValue(result.value());
  17106. }
  17107. case 'prim::tolist': {
  17108. const value = apply.func.value;
  17109. const operand = this.emitSugaredExpr(value, 1);
  17110. if (!type_hint) {
  17111. throw new python.Error('Expected type hint for result of tolist().');
  17112. }
  17113. return new torch._C.SimpleValue(this.graph.insertToList(operand.asValue(value.range(), this.method), type_hint));
  17114. }
  17115. case 'prim::HasAttr': {
  17116. throw new python.Error('Not implemented.');
  17117. }
  17118. case 'prim::CreateObject': {
  17119. if (apply.args.length !== 1) {
  17120. throw python.Error('Only one argument to __new__ allowed.');
  17121. }
  17122. const arg = this.emitSugaredExpr(apply.args[0], 1);
  17123. if (arg instanceof torch._C.ClassValue === false) {
  17124. throw python.Error('Expected class value as argument to __new__.');
  17125. }
  17126. const class_arg = arg;
  17127. const createNode = this.graph.insertNode(this.graph.createObject(class_arg._type));
  17128. createNode.setSourceRange(apply.range());
  17129. return new torch._C.SimpleValue(createNode.output());
  17130. }
  17131. case 'prim::range': {
  17132. const input_vals = this.getValues(apply.args, true);
  17133. return new torch._C.RangeValue(apply.range(), this.method, input_vals);
  17134. }
  17135. case 'prim::enumerate': {
  17136. throw new python.Error('Not implemented.');
  17137. }
  17138. case 'prim::zip': {
  17139. throw new python.Error('Not implemented.');
  17140. }
  17141. case 'prim::list': {
  17142. throw new python.Error('Not implemented.');
  17143. }
  17144. case 'prim::dict': {
  17145. throw new python.Error('Not implemented.');
  17146. }
  17147. case 'aten::index': {
  17148. throw new python.Error('Not implemented.');
  17149. }
  17150. default: {
  17151. throw new python.Error(`Unsupported special form '${sv.from()}'.`);
  17152. }
  17153. }
  17154. }
  17155. emitSimpleExpr(tree, type_hint) {
  17156. if (tree instanceof ast.Constant) {
  17157. if (tree.value === true) {
  17158. return this.graph.insertConstant(new torch._C.IValue(true, 'Bool'), tree.range());
  17159. } else if (tree.value === false) {
  17160. return this.graph.insertConstant(new torch._C.IValue(false, 'Bool'), tree.range());
  17161. } else if (tree.value === null) {
  17162. return this.graph.insertConstant(new torch._C.IValue(), tree.range());
  17163. } else if (typeof tree.value === 'string') {
  17164. return this.emitStringLiteral(tree);
  17165. }
  17166. return this.emitConst(tree);
  17167. } else if (tree instanceof ast.List) {
  17168. return this.emitListLiteral(tree, type_hint);
  17169. } else if (tree instanceof ast.UnaryOp && tree.op instanceof ast.USub && tree.operand instanceof ast.Name && tree.operand.id === 'inf') {
  17170. return this.emitConst(new ast.Constant(-Infinity, 'float'));
  17171. } else if (tree instanceof ast.UnaryOp && tree.op instanceof ast.USub && tree.operand instanceof ast.Constant) {
  17172. const c = tree.operand;
  17173. if (c.type === 'complex') {
  17174. return this.emitConst(new ast.Constant(new builtins.complex(-c.value.real, -c.value.imag), 'complex'));
  17175. }
  17176. return this.emitConst(new ast.Constant(-c.value, c.type));
  17177. } else if (tree instanceof ast.UnaryOp && tree.op instanceof ast.USub) {
  17178. return this.emitUnaryOp(tree, '__neg__', 'aten::neg');
  17179. } else if (tree instanceof ast.BinOp) {
  17180. return this.emitBinaryOp(tree);
  17181. } else if (tree instanceof ast.Dict) {
  17182. return this.emitDictLiteral(tree, type_hint);
  17183. } else if (tree instanceof ast.Tuple) {
  17184. const values = this.getValues(tree.elts, /*maybe_unpack=*/true);
  17185. return this.graph.insertNode(this.graph.createTuple(values)).output();
  17186. }
  17187. throw new python.Error(`Simple expression '${tree.__class__.__name__}' not implemented.`);
  17188. }
  17189. getNodeKind(kind /*, ninputs */) {
  17190. if (kind instanceof ast.Add) {
  17191. return 'aten::add';
  17192. } else if (kind instanceof ast.Sub) {
  17193. return 'aten::sub';
  17194. } else if (kind instanceof ast.Mult) {
  17195. return 'aten::mul';
  17196. }
  17197. /*
  17198. case TK_UNARY_MINUS: return 'aten::neg';
  17199. case TK_POW: return 'aten::pow';
  17200. case '@': return 'aten::matmul';
  17201. case TK_STARRED: return 'prim::Starred';
  17202. case '/': return 'aten::div';
  17203. case '%': return 'aten::remainder';
  17204. case TK_NE: return 'aten::ne';
  17205. case TK_EQ: return 'aten::eq';
  17206. case '<': return 'aten::lt';
  17207. case '>': return 'aten::gt';
  17208. case TK_LE: return 'aten::le';
  17209. case TK_GE: return 'aten::ge';
  17210. case TK_AND: return 'aten::__and__';
  17211. case TK_OR: return 'aten::__or__';
  17212. case TK_IS: return 'aten::__is__';
  17213. case TK_ISNOT: return 'aten::__isnot__';
  17214. case TK_NOT: return 'aten::__not__';
  17215. case TK_FLOOR_DIV: return 'aten::floordiv';
  17216. case TK_LSHIFT: return 'aten::__lshift__';
  17217. case TK_RSHIFT: return 'aten::__rshift__';
  17218. case '&': return 'aten::__and__';
  17219. case '|': return 'aten::__or__';
  17220. case '^': return 'aten::__xor__';
  17221. case TK_IN: return 'aten::__contains__';
  17222. */
  17223. throw new python.Error(`Unknown kind '${kind.__class__.__name__}'.`);
  17224. }
  17225. getOperatorOverload(kind /*, ninputs */) {
  17226. if (kind instanceof ast.Add) {
  17227. return '__add__';
  17228. } else if (kind instanceof ast.Sub) {
  17229. return '__sub__';
  17230. } else if (kind instanceof ast.Mult) {
  17231. return '__mul__';
  17232. }
  17233. /*
  17234. case TK_UNARY_MINUS: return "__neg__";
  17235. case '~': return "__invert__";
  17236. case TK_POW: return "__pow__";
  17237. case '/': return "__truediv__";
  17238. case '%': return "__mod__";
  17239. case TK_NE: return "__ne__";
  17240. case TK_EQ: return "__eq__";
  17241. case '<': return "__lt__";
  17242. case '>': return "__gt__";
  17243. case TK_LE: return "__le__";
  17244. case TK_GE: return "__ge__";
  17245. case '&': return "__and__";
  17246. case '|': return "__or__";
  17247. case '^': return "__xor__";
  17248. case TK_IN: return "__contains__";
  17249. case TK_LSHIFT: return "__lshift__";
  17250. case TK_RSHIFT: return "__rshift__";
  17251. */
  17252. throw new python.Error(`Unknown kind '${kind.__class__.__name__}'.`);
  17253. }
  17254. emitBinaryOp(tree) {
  17255. const inputs = [tree.left, tree.right];
  17256. const kind = this.getNodeKind(tree.op, inputs.length);
  17257. const overload = this.getOperatorOverload(tree.op, inputs.length);
  17258. const named_values = this.getNamedValues(inputs, /*maybe_unpack=*/false);
  17259. if (tree.op instanceof ast.In) {
  17260. // std::iter_swap(named_values.begin() + 0, named_values.begin() + 1);
  17261. throw new python.Error('Not implemented.');
  17262. }
  17263. if (named_values[0].type() instanceof torch.TupleType &&
  17264. named_values[1].type() instanceof torch.TupleType &&
  17265. kind === 'aten::add') {
  17266. const first_tuple = torch._C.createTupleUnpack(named_values[0].value(this.graph)).vec();
  17267. const second_tuple = torch._C.createTupleUnpack(named_values[1].value(this.graph)).vec();
  17268. first_tuple.insert(first_tuple.end(), second_tuple.begin(), second_tuple.end());
  17269. return this.graph.insertNode(this.graph.createTuple(first_tuple)).output();
  17270. }
  17271. return torch._C.asSimple(torch._C.makeMagic(overload, new torch._C.BuiltinFunction(kind, null)).call(tree.range(), this.method, named_values, [], 0));
  17272. }
  17273. emitDictLiteral(dl, type_hint) {
  17274. const key_trees = dl.keys;
  17275. const value_trees = dl.values;
  17276. torch._C.AT_ASSERT(key_trees.length === value_trees.length);
  17277. const keys = [];
  17278. const values = [];
  17279. let rhs_value_type = null;
  17280. for (let i = 0; i < key_trees.length; i++) {
  17281. keys.push(this.emitExpr(key_trees[i]));
  17282. values.push(this.emitExpr(value_trees[i]));
  17283. if (i === 0) {
  17284. rhs_value_type = values[i].type();
  17285. } else {
  17286. if (keys[i - 1].type().kind() !== keys[i].type().kind()) {
  17287. throw new python.Error('Dict keys must contain only a single type.');
  17288. }
  17289. rhs_value_type = torch._C.unifyTypes(rhs_value_type, values[i].type(), /*default_to_union=*/true);
  17290. }
  17291. }
  17292. const refined_type_hint = { _: type_hint };
  17293. const annotated_union_type = type_hint && type_hint.isUnionType() ? type_hint : null;
  17294. const all_candidates = { _: [] };
  17295. const default_refined_type_hint_setter = () => {
  17296. if (keys.length === 0) {
  17297. refined_type_hint._ = torch.DictType.create(torch.StringType.get(), torch.TensorType.get());
  17298. } else {
  17299. refined_type_hint._ = torch.DictType.create(keys[0].type(), rhs_value_type);
  17300. if (rhs_value_type instanceof torch.UnionType) {
  17301. throw new python.Error('Dict values consist of heterogeneous types.');
  17302. }
  17303. }
  17304. };
  17305. if (type_hint) {
  17306. const type_match = (t) => t instanceof torch.DictType;
  17307. this.refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint, all_candidates, 'Dict', dl, type_match, () => [], default_refined_type_hint_setter);
  17308. if (all_candidates._.length > 0 && values.length === 0) {
  17309. throw new python.Error('Cannot assign an empty dict.');
  17310. }
  17311. } else {
  17312. default_refined_type_hint_setter();
  17313. }
  17314. torch._C.TORCH_INTERNAL_ASSERT(all_candidates._.length > 0 || refined_type_hint._);
  17315. if (values.length > 0) {
  17316. if (all_candidates._.length > 0) {
  17317. this.refineAndSetDictTypeHintFromCandidatesVector(all_candidates, type_hint, refined_type_hint, keys[0].type(), rhs_value_type, dl);
  17318. }
  17319. if (refined_type_hint._.getKeyType() !== keys[0].type()) {
  17320. throw new python.Error('Type annotation does not match key type.');
  17321. }
  17322. if (!rhs_value_type.isSubtypeOf(refined_type_hint._.getValueType())) {
  17323. throw new python.Error('Type annotation does not match value type.');
  17324. }
  17325. }
  17326. let result = this.graph.insertNode(this.graph.createDict(refined_type_hint._.getKeyType(), refined_type_hint._.getValueType(), keys, values));
  17327. if (annotated_union_type) {
  17328. const n = this.graph.insertNode(this.graph.create('prim::unchecked_cast', [result.output()]));
  17329. n.output().setType(annotated_union_type);
  17330. result = n;
  17331. }
  17332. return result.output();
  17333. }
  17334. emitStringLiteral(c) {
  17335. return torch._C.insertConstant(this.graph, c.value, c.range());
  17336. }
  17337. emitConst(c) {
  17338. if (c.type === 'int') {
  17339. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Int'), this.graph, c.range(), this.integral_constants);
  17340. } else if (c.type === 'complex') {
  17341. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Complex'), this.graph, c.range(), this.complex_constants);
  17342. } else if (c.type === 'float') {
  17343. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Double'), this.graph, c.range(), this.fp_constants);
  17344. }
  17345. throw new python.Error(`Unsupported constant type.`);
  17346. }
  17347. emitListLiteral(ll, type_hint) {
  17348. type_hint = type_hint || null;
  17349. const values = this.getValues(ll.elts, true);
  17350. if (values.length === 0 && type_hint === null) {
  17351. throw new python.Error('Not implemented.');
  17352. }
  17353. let inferred_elem_type = torch.TensorType.get();
  17354. const refined_type_hint = { _: type_hint };
  17355. const annotated_union_type = refined_type_hint._ && refined_type_hint._.isUnionType() ? refined_type_hint._ : null;
  17356. const all_candidates = { _: [] };
  17357. if (refined_type_hint._) {
  17358. const do_if_type_match = () => {
  17359. inferred_elem_type = refined_type_hint._.expect(torch.ListType).getElementType();
  17360. };
  17361. const type_match = (t) => t.isSubtypeOf(torch.Type.get('AnyListType'));
  17362. this.refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint, all_candidates, 'List', ll, type_match, do_if_type_match, do_if_type_match);
  17363. if (all_candidates._.length > 0 && values.len === 0) {
  17364. throw new python.Error('Cannot assign an empty list.');
  17365. }
  17366. }
  17367. if (values.length !== 0) {
  17368. const types = values.map((v) => v.type());
  17369. const elem_type_hint = refined_type_hint._ && refined_type_hint._.kind() === 'ListType' ? refined_type_hint._.getElementType() : null;
  17370. const unified_elem_type = torch._C.unifyTypeList(types, null /*nowhere*/, /*default_to_union=*/true, elem_type_hint);
  17371. if (!refined_type_hint._ && unified_elem_type.kind() === 'UnionType') {
  17372. throw new python.Error('Not implemented.');
  17373. }
  17374. if (all_candidates._.length === 0 && refined_type_hint._ && !unified_elem_type.isSubtypeOf(inferred_elem_type)) {
  17375. throw new python.Error('Not implemented.');
  17376. }
  17377. if (all_candidates._.length !== 0) {
  17378. this.refineAndSetListTypeHintFromCandidatesVector(all_candidates, type_hint, refined_type_hint._, unified_elem_type, ll);
  17379. inferred_elem_type = refined_type_hint._.expect(torch.ListType).getElementType();
  17380. }
  17381. if (!refined_type_hint._) {
  17382. inferred_elem_type = unified_elem_type;
  17383. }
  17384. }
  17385. let result = this.graph.insertNode(this.graph.createList(inferred_elem_type, values));
  17386. if (annotated_union_type) {
  17387. const n = this.graph.insertNode(this.graph.create('prim::unchecked_cast', [result.output()]));
  17388. n.output().setType(annotated_union_type);
  17389. result = n;
  17390. }
  17391. return result.output();
  17392. }
  17393. insertRefinements(loc, ref) {
  17394. for (const r of ref.activeRefinements()) {
  17395. const v = this.environment_stack.getVar(r.identifier(), loc);
  17396. const new_v = this.graph.insertUncheckedCast(v, r.type());
  17397. this.environment_stack.setVar(loc, r.identifier(), new_v);
  17398. }
  17399. }
  17400. shouldDeriveSetStateType(def, schema) {
  17401. const noTypeAnnotations = schema.arguments.every((arg) => arg.is_inferred_type());
  17402. const shouldInfer = def.name === '__setstate__' && noTypeAnnotations;
  17403. if (!shouldInfer) {
  17404. return false;
  17405. }
  17406. if (def.name !== '__setstate__' && def.args.args.length !== 2) {
  17407. throw new python.Error(`Invalid '__setstate' method.`);
  17408. }
  17409. return true;
  17410. }
  17411. checkApplyNumInputs(apply, expected_inputs) {
  17412. if (apply.args.length !== expected_inputs) {
  17413. throw new python.Error('Invalid number of arguments.');
  17414. }
  17415. if (apply.keywords.length > 0) {
  17416. throw new python.Error('Invalid number of keyword arguments.');
  17417. }
  17418. }
  17419. checkApplyNumInputsRange(apply, min_expected_inputs, max_expected_inputs) {
  17420. const position_arg_size = apply.args.length;
  17421. if (position_arg_size < min_expected_inputs || position_arg_size > max_expected_inputs) {
  17422. throw new python.Error('Invalid number of arguments.');
  17423. }
  17424. if (apply.keywords.length > 0) {
  17425. throw new python.Error('Invalid number of keyword arguments.');
  17426. }
  17427. }
  17428. validateAssignLhsExpr(lhs /*, r */) {
  17429. let num_normal_assign = 0;
  17430. let num_starred = 0;
  17431. for (const assignee of lhs) {
  17432. if (assignee instanceof ast.Name || assignee instanceof ast.Subscript || assignee instanceof ast.Tuple || assignee instanceof ast.Attribute) {
  17433. num_normal_assign++;
  17434. } else if (assignee instanceof ast.Starred) {
  17435. num_starred++;
  17436. } else {
  17437. throw new python.Error('Assignment must be a variable, subscript, or starred expression.');
  17438. }
  17439. }
  17440. if (num_starred > 1) {
  17441. throw new python.Error('Only one starred expression is allowed.');
  17442. }
  17443. if (num_starred > 0 && num_normal_assign === 0) {
  17444. throw new python.Error('Invalid starred expression.');
  17445. }
  17446. return num_starred;
  17447. }
  17448. createTempName(prefix) {
  17449. return `${prefix}${this._temp_name_count++}`;
  17450. }
  17451. handleMaybeNoReturn(def, block) {
  17452. const decl_ret = this._def_stack[this._def_stack.length - 1]._declared_return_type;
  17453. if (this.exit_blocks.size === 0) {
  17454. if (decl_ret && decl_ret !== torch.NoneType.get()) {
  17455. throw new python.Error('Function was not annotated as having type None, but does not return along all paths.');
  17456. }
  17457. const b = new torch._C.WithInsertPoint(block.nodes().end());
  17458. // this.emitReturn(Return::create(def.range(), Expr(Compound::create(TK_NONE, def.range(), {}))));
  17459. b.dispose();
  17460. throw new python.Error("'torch._C.to_ir.handleMaybeNoReturn' not implemented.");
  17461. } else if (this._def_stack[this._def_stack.length - 1]._merged_return_type === null) {
  17462. this._def_stack[this._def_stack.length - 1]._merged_return_type = decl_ret === null ? torch.NoneType.get() : decl_ret;
  17463. }
  17464. }
  17465. getAdjTupleIndex(loc, tuple_type, input_index, allow_out_of_bounds) {
  17466. let adj_index = input_index;
  17467. const tuple_len = tuple_type.elements().length;
  17468. if (input_index < 0) {
  17469. adj_index = tuple_len + input_index;
  17470. }
  17471. if (!allow_out_of_bounds && (adj_index >= tuple_len || adj_index < 0)) {
  17472. throw new python.Error(`Tuple index out of range at ${loc}.`);
  17473. }
  17474. return adj_index;
  17475. }
  17476. emitTupleIndex(loc, tuple_val, idx_val) {
  17477. const tuple_typ = tuple_val.type();
  17478. const elems = tuple_typ.elements();
  17479. let output_type = null;
  17480. if (idx_val.type() !== torch.IntType.get()) {
  17481. throw new python.Error('Tuple index must be an integer.');
  17482. }
  17483. const idx = torch._C.toIValue(idx_val);
  17484. if (idx) {
  17485. const adj_index = this.getAdjTupleIndex(loc, tuple_typ, idx.toInt(), /*allow_out_of_bounds*/ false);
  17486. output_type = elems[adj_index];
  17487. } else {
  17488. if (elems.length === 0 || !torch._C.convertibleToList(tuple_typ, torch.ListType.create(elems[0]))) {
  17489. throw new python.Error('Cannot index into a tuple with a non-integer literal.');
  17490. }
  17491. [output_type] = elems;
  17492. }
  17493. return this.graph.insertNode(this.graph.createTupleIndex(tuple_val, idx_val, output_type)).output();
  17494. }
  17495. getSliceInd(idx_val, loc) {
  17496. const ivalue = torch._C.toIValue(idx_val);
  17497. if (ivalue && ivalue.isInt()) {
  17498. return ivalue.toInt();
  17499. }
  17500. throw new python.Error(`Tuple slice indices must be integer constants at '${loc}'.`);
  17501. }
  17502. emitTupleSlice(loc, tuple_val, tuple_args) {
  17503. const tuple_type = tuple_val.value(this.graph).type().expect(torch.TupleType);
  17504. const tuple_len = tuple_type.elements().length;
  17505. const [beg_val, end_val, step] = tuple_args;
  17506. let step_size = 1;
  17507. if (step) {
  17508. const val = torch._C.toIValue(step.value(this.graph));
  17509. torch._C.TORCH_CHECK(val.isInt());
  17510. step_size = val.toInt();
  17511. }
  17512. let beg = { _: Number.MAX_SAFE_INTEGER }; // std::numeric_limits<int64_t>::max();
  17513. if (beg_val) {
  17514. beg = { _: this.getAdjTupleIndex(loc, tuple_type, this.getSliceInd(beg_val.value(this.graph), loc), true) };
  17515. }
  17516. let end = { _: Number.MAX_SAFE_INTEGER }; // std::numeric_limits<int64_t>::max();
  17517. if (end_val) {
  17518. end = { _: this.getAdjTupleIndex(loc, tuple_type, this.getSliceInd(end_val.value(this.graph), loc), true) };
  17519. }
  17520. const num_values = torch._C.slice_indices_adjust(tuple_len, beg, end, step_size);
  17521. return this.graph.insertNode(this.graph.createTupleSlice(tuple_val.value(this.graph), beg._, step_size, num_values)).output();
  17522. }
  17523. emitSliceOp(loc, sliceable, dim, start, end, step) {
  17524. const args = [];
  17525. args.push(new torch._C.NamedValue(loc, 'self', sliceable));
  17526. if (dim) {
  17527. torch._C.AT_ASSERT(sliceable.type().isSubtypeOf(torch.TensorType.get()));
  17528. args.emplace_back(new torch._C.NamedValue(dim));
  17529. } else {
  17530. torch._C.AT_ASSERT(!sliceable.type().isSubtypeOf(torch.TensorType.get()));
  17531. }
  17532. if (sliceable.type() instanceof torch.TupleType) {
  17533. const tuple_args = [];
  17534. tuple_args.push(start ? new torch._C.NamedValue(start) : null);
  17535. tuple_args.push(end ? new torch._C.NamedValue(end) : null);
  17536. tuple_args.push(step ? new torch._C.NamedValue(step) : null);
  17537. return this.emitTupleSlice(loc, args[0], tuple_args);
  17538. }
  17539. if (!step) {
  17540. step = this.graph.insertConstant(1, loc);
  17541. }
  17542. args.push(new torch._C.NamedValue(loc, 'start', start));
  17543. args.push(new torch._C.NamedValue(loc, 'end', end));
  17544. args.push(new torch._C.NamedValue(loc, 'step', step));
  17545. return this.emitBuiltinCall(loc, this.graph, 'aten::slice', args, []);
  17546. }
  17547. emitSlice(loc, input, dim, slice) {
  17548. let start = null;
  17549. let end = null;
  17550. let step = null;
  17551. if (slice.lower) {
  17552. start = this.emitExpr(slice.lower);
  17553. }
  17554. if (slice.upper) {
  17555. end = this.emitExpr(slice.upper);
  17556. }
  17557. if (slice.step) {
  17558. step = this.emitExpr(slice.step);
  17559. }
  17560. return this.emitSliceOp(loc, input, dim, start, end, step);
  17561. }
  17562. emitBasicSlice(loc, sliceable, subscript_exprs) {
  17563. torch._C.AT_ASSERT(subscript_exprs instanceof ast.Slice);
  17564. const slice_exp = subscript_exprs;
  17565. let maybe_dim = null;
  17566. if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  17567. maybe_dim = this.graph.insertConstant(0, loc);
  17568. }
  17569. return this.emitSlice(loc, sliceable, maybe_dim, slice_exp);
  17570. }
  17571. emitSubscript(subscript, type_hint) {
  17572. type_hint = type_hint === undefined ? null : type_hint;
  17573. const sv = this.emitSugaredExpr(subscript.value, 1);
  17574. const subscript_exprs = subscript.slice;
  17575. const range = subscript.range();
  17576. const val_range = subscript.value;
  17577. if (subscript_exprs instanceof ast.Tuple) {
  17578. return new torch._C.SimpleValue(this.emitMultidimSlicing(range, sv.asValue(val_range, this.method), subscript_exprs));
  17579. }
  17580. if (subscript_exprs instanceof ast.Slice) {
  17581. if (sv.kind() === 'module') {
  17582. const s_tuple_val = sv.asTupleValue(val_range, this.method).asValue(val_range, this.method);
  17583. const [slice] = subscript_exprs;
  17584. const tuple_args = [];
  17585. if (slice.start().present()) {
  17586. const begin = new torch._C.NamedValue(val_range, 'begin', this.emitExpr(slice.start().get()));
  17587. tuple_args.push(begin);
  17588. } else {
  17589. tuple_args.push(null);
  17590. }
  17591. if (slice.end().present()) {
  17592. const end = new torch._C.NamedValue(val_range, 'end', this.emitExpr(slice.end().get()));
  17593. tuple_args.push(end);
  17594. } else {
  17595. tuple_args.push(null);
  17596. }
  17597. if (slice.step().present()) {
  17598. const step = new torch._C.NamedValue(val_range, 'step', this.emitExpr(slice.step().get()));
  17599. tuple_args.push(step);
  17600. } else {
  17601. tuple_args.push(null);
  17602. }
  17603. const tupleSliceValue = this.emitTupleSlice(val_range, s_tuple_val, tuple_args);
  17604. return new torch._C.SimpleValue(tupleSliceValue);
  17605. }
  17606. return new torch._C.SimpleValue(this.emitBasicSlice(range, sv.asValue(val_range, this.method), subscript_exprs));
  17607. }
  17608. const sliceable = sv.asValue(val_range, this.method);
  17609. const subscript_sv = this.emitSugaredExpr(subscript_exprs, 1);
  17610. if (subscript_sv instanceof torch._C.SliceValue) {
  17611. const slice_value = subscript_sv;
  17612. let dim = null;
  17613. if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  17614. dim = this.method.graph().insertConstant(0, val_range);
  17615. }
  17616. const sliced = this.emitSliceOp(val_range, sliceable, dim, slice_value.start(), slice_value.stop(), slice_value.step());
  17617. return new torch._C.SimpleValue(sliced);
  17618. }
  17619. const idx = subscript_sv.asValue(val_range, this.method);
  17620. if (sliceable.type() instanceof torch.TupleType) {
  17621. return new torch._C.SimpleValue(this.emitTupleIndex(range, sv.asValue(val_range, this.method), idx));
  17622. } else if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  17623. return new torch._C.SimpleValue(this.emitMultidimSlicing(range, sliceable, subscript_exprs));
  17624. }
  17625. return sv.getitem(range, this.method, idx, type_hint);
  17626. }
  17627. });
  17628. this.registerType('torch.jit.CompilationUnit', class {
  17629. constructor() {
  17630. this._functions = new Map();
  17631. this._classes = new Map();
  17632. }
  17633. register_type(namedType) {
  17634. this._classes.set(namedType.annotation_str, namedType);
  17635. }
  17636. register_function(fn) {
  17637. const name = fn.qualname().qualifiedName();
  17638. torch._C.TORCH_CHECK(!this._functions.has(name));
  17639. this._functions.set(name, fn);
  17640. return fn;
  17641. }
  17642. define(...args) {
  17643. if (Array.isArray(args[1])) {
  17644. const [prefix, properties, propResolvers, definitions, defResolvers, self, shouldMangle, operator_set_version] = args;
  17645. torch._C.TORCH_INTERNAL_ASSERT(definitions.length === defResolvers.length);
  17646. torch._C.TORCH_INTERNAL_ASSERT(properties.length === propResolvers.length);
  17647. const functions = [];
  17648. const function_table = new Map();
  17649. const record_function = (fn) => {
  17650. function_table.set(fn.name(), fn);
  17651. functions.push(fn);
  17652. this.register_function(fn);
  17653. };
  17654. for (let i = 0; i < properties.length; i++) {
  17655. const property_fns = this.define_property(prefix, properties[i], propResolvers[i], self, function_table, shouldMangle);
  17656. const getter_fn = property_fns.getGetter();
  17657. const setter_fn = property_fns.getSetter();
  17658. record_function(getter_fn);
  17659. if (setter_fn) {
  17660. record_function(setter_fn);
  17661. }
  17662. }
  17663. for (let i = 0; i < definitions.length; i++) {
  17664. const fn = this.define(prefix, definitions[i], defResolvers[i], self, function_table, shouldMangle, 'Method', operator_set_version);
  17665. record_function(fn);
  17666. }
  17667. for (const [name, fn] of function_table) {
  17668. if (name === '__init__') {
  17669. fn.ensure_defined();
  17670. }
  17671. }
  17672. for (const fn of functions) {
  17673. fn.ensure_defined();
  17674. }
  17675. return functions;
  17676. } else if (args[1] instanceof ast.FunctionDef) {
  17677. const [prefix, def, resolver, self, function_table, shouldMangle, type, operator_set_version] = args;
  17678. const _resolver = self ? resolver : new torch._C.FunctionResolver(resolver, function_table);
  17679. const creator = (method) => {
  17680. return new torch._C.to_ir(def, _resolver, self, method);
  17681. };
  17682. let name = prefix ? new torch._C.QualifiedName(prefix, def.name) : new torch._C.QualifiedName(def.name);
  17683. if (shouldMangle && this.find_function(name)) {
  17684. name = this.mangle(name);
  17685. }
  17686. const graph = new torch.Graph();
  17687. graph.set_op_version(operator_set_version);
  17688. const fn = new torch._C.GraphFunction(name, graph, creator);
  17689. fn.__ast__ = def; // remove
  17690. if (self) {
  17691. if (type === 'hook') {
  17692. self.getClassType().addForwardHook(fn);
  17693. } else if (type === 'prehook') {
  17694. self.getClassType().addPreHook(fn);
  17695. } else {
  17696. self.getClassType().addMethod(fn);
  17697. }
  17698. }
  17699. return fn;
  17700. }
  17701. throw new python.Error('Invalid arguments.');
  17702. }
  17703. get_type(name) {
  17704. return this._classes.get(name.qualifiedName());
  17705. }
  17706. get_class(name) {
  17707. return this.get_type(name);
  17708. }
  17709. find_function(name) {
  17710. const key = name.qualifiedName();
  17711. return this._functions.get(key);
  17712. }
  17713. });
  17714. this.registerFunction('torch._C.ConvertToSSA', (graph) => {
  17715. const ctrl = new torch._C.ControlFlowLoadStores();
  17716. ctrl.run(graph);
  17717. const exit_vars = new torch._C.LoopContinuations();
  17718. exit_vars.run(graph);
  17719. torch._C.InlineLoopCondition(graph);
  17720. const erase_loads_stores = new torch._C.EraseLoadStores();
  17721. erase_loads_stores.run(graph);
  17722. torch._C.TransformExits(graph);
  17723. });
  17724. this.registerFunction('torch._C.canonicalizeModifiedLoop', (/* n */) => {
  17725. /*
  17726. LoopView loop(n);
  17727. if (loop.loopType() != LoopView::ModifiedLoop) {
  17728. return;
  17729. }
  17730. const g = n.owningGraph();
  17731. WithInsertPoint node_insert(n);
  17732. const zero = g.insertConstant(0);
  17733. const one = g.insertConstant(1);
  17734. const max_trip_count = loop.maxTripCount();
  17735. const condition = g.insert(aten::gt, {max_trip_count, zero});
  17736. loop.replaceMaxTripCount(g.insertConstant(std::numeric_limits<int64_t>::max()));
  17737. const inp_condition = toIValue(loop.inputCond());
  17738. if (inp_condition == null || inp_condition.toBool() == false) {
  17739. condition = g.insert(aten::__and__, {condition, loop.inputCond()});
  17740. }
  17741. loop.replaceInputCondition(condition);
  17742. n.addOutput().setType(IntType::get());
  17743. WithInsertPoint loop_insert(loop.bodyBlock());
  17744. n.addInput(zero);
  17745. const new_iter = loop.bodyBlock().addInput().setType(IntType::get());
  17746. // unset unique name for jitter, its replacement does not have a name
  17747. loop.currentTripCount().setDebugName('').replaceAllUsesWith(new_iter);
  17748. const inc_iter = g.insert(aten::add, {new_iter, one});
  17749. loop.bodyBlock().registerOutput(inc_iter);
  17750. const less_than_max_trip = g.insert(aten::lt, {inc_iter, max_trip_count});
  17751. const loop_continue = loop.nextCond();
  17752. const new_condition =
  17753. g.insert(aten::__and__, {less_than_max_trip, loop_continue});
  17754. loop.bodyBlock().eraseOutput(0);
  17755. loop.bodyBlock().insertOutput(0, new_condition);
  17756. */
  17757. });
  17758. this.registerFunction('torch._C.canonicalizeModifiedLoops', (block) => {
  17759. for (const n of block.nodes()) {
  17760. for (const b of n.blocks()) {
  17761. torch._C.canonicalizeModifiedLoops(b);
  17762. }
  17763. if (n.kind() === 'prim::Loop') {
  17764. torch._C.canonicalizeModifiedLoop(n);
  17765. }
  17766. }
  17767. });
  17768. this.registerFunction('torch._C.CanonicalizeModifiedLoops', (graph) => {
  17769. torch._C.canonicalizeModifiedLoops(graph.block());
  17770. });
  17771. this.registerType('torch._C.MiniEnvironment', class {
  17772. constructor(b, next) {
  17773. this.next = next || null;
  17774. this.table = new Map();
  17775. }
  17776. setVar(name, value) {
  17777. this.table.set(name, value);
  17778. }
  17779. definedVariables() {
  17780. const result = Array.from(this.table.keys());
  17781. return result.sort();
  17782. }
  17783. findInThisFrame(name) {
  17784. if (this.table.has(name)) {
  17785. return this.table.get(name);
  17786. }
  17787. return null;
  17788. }
  17789. findInAnyFrame(name) {
  17790. /* eslint-disable consistent-this */
  17791. const self = this;
  17792. /* eslint-enable consistent-this */
  17793. for (let runner = self; runner; runner = runner.next) {
  17794. const r = runner.findInThisFrame(name);
  17795. if (r) {
  17796. return r;
  17797. }
  17798. }
  17799. return null;
  17800. }
  17801. });
  17802. this.registerType('torch._C.ValueEnvironment', class extends torch._C.MiniEnvironment {
  17803. });
  17804. this.registerType('torch._C.TypeEnvironment', class extends torch._C.MiniEnvironment {
  17805. });
  17806. this.registerType('torch._C.ControlFlowLoadStores', class {
  17807. constructor() {
  17808. this.environment_stack = null;
  17809. }
  17810. pushFrame(b) {
  17811. this.environment_stack = new torch._C.TypeEnvironment(b, this.environment_stack);
  17812. }
  17813. popFrame() {
  17814. const old_frame = this.environment_stack;
  17815. this.environment_stack = this.environment_stack.next;
  17816. return old_frame;
  17817. }
  17818. addBlockInput(b, type, name) {
  17819. const g = b.owningGraph();
  17820. g.createStore(name, b.addInput(name).setType(type)).insertAfter(b.param_node());
  17821. }
  17822. addBlockOutput(exit_block, type, name) {
  17823. const insert = new torch._C.WithInsertPoint(exit_block);
  17824. const g = exit_block.owningGraph();
  17825. const block_exit = g.insertNode(g.createLoad(name, type)).output();
  17826. exit_block.registerOutput(block_exit);
  17827. insert.dispose();
  17828. }
  17829. addNodeOutput(n, type, name) {
  17830. const out = n.addOutput().setType(type);
  17831. if (torch._C.meaningfulName(name)) {
  17832. out.setDebugName(name);
  17833. }
  17834. const g = n.owningGraph();
  17835. g.createStore(name, out).insertAfter(n);
  17836. }
  17837. addNodeInput(n, type, name) {
  17838. const g = n.owningGraph();
  17839. const inp = g.createLoad(name, type).insertBefore(n).output();
  17840. n.addInput(inp);
  17841. }
  17842. addIfLoadStores(n) {
  17843. const [true_block, false_block] = n.blocks();
  17844. const true_vars = this.addControlFlowLoadStores(true_block);
  17845. const false_vars = this.addControlFlowLoadStores(false_block);
  17846. const mutated_variables = new Set();
  17847. for (const v of true_vars.definedVariables()) {
  17848. if (false_vars.findInAnyFrame(v)) {
  17849. mutated_variables.add(v);
  17850. }
  17851. }
  17852. for (const v of false_vars.definedVariables()) {
  17853. if (true_vars.findInAnyFrame(v)) {
  17854. mutated_variables.add(v);
  17855. }
  17856. }
  17857. for (const x of mutated_variables) {
  17858. const true_type = true_vars.findInAnyFrame(x);
  17859. const false_type = false_vars.findInAnyFrame(x);
  17860. const unified = torch._C.unifyTypes(true_type, false_type, /*default_to_union=*/true);
  17861. this.addBlockOutput(true_block, true_type, x);
  17862. this.addBlockOutput(false_block, false_type, x);
  17863. this.addNodeOutput(n, unified, x);
  17864. }
  17865. }
  17866. addLoopLoadStores(n) {
  17867. const [body_block] = n.blocks();
  17868. const loop_vars = this.addControlFlowLoadStores(body_block);
  17869. for (const name of loop_vars.definedVariables()) {
  17870. const parent_type = this.environment_stack.findInAnyFrame(name);
  17871. if (!parent_type) {
  17872. continue;
  17873. }
  17874. const block_type = loop_vars.findInThisFrame(name);
  17875. const unified_type = torch._C.unifyTypes(parent_type, block_type);
  17876. this.addNodeInput(n, parent_type, name);
  17877. this.addBlockInput(body_block, unified_type, name);
  17878. this.addBlockOutput(body_block, block_type, name);
  17879. this.addNodeOutput(n, unified_type, name);
  17880. }
  17881. }
  17882. addControlFlowLoadStores(block) {
  17883. this.pushFrame(block);
  17884. for (const n of block.nodes()) {
  17885. switch (n.kind()) {
  17886. case 'prim::If': {
  17887. this.addIfLoadStores(n);
  17888. break;
  17889. }
  17890. case 'prim::Loop': {
  17891. this.addLoopLoadStores(n);
  17892. break;
  17893. }
  17894. case 'prim::Closure': {
  17895. for (const b of n.blocks()) {
  17896. this.addControlFlowLoadStores(b);
  17897. }
  17898. break;
  17899. }
  17900. case 'prim::Store': {
  17901. this.environment_stack.setVar(n.s('name'), n.input().type());
  17902. break;
  17903. }
  17904. case 'prim::ComprehensionScope': {
  17905. this.addControlFlowLoadStores(n.blocks().at(0));
  17906. break;
  17907. }
  17908. default: {
  17909. break;
  17910. }
  17911. }
  17912. }
  17913. return this.popFrame();
  17914. }
  17915. run(graph) {
  17916. this.addControlFlowLoadStores(graph.block());
  17917. }
  17918. });
  17919. this.registerType('torch._C.LoopContinuations', class {
  17920. constructor() {
  17921. this._graph = null;
  17922. this._false_val = null;
  17923. this._curr_loop = null;
  17924. }
  17925. assignExitContinuations(block) {
  17926. for (const n of block.nodes()) {
  17927. switch (n.kind()) {
  17928. case 'prim::If': {
  17929. this.assignExitContinuations(n.blocks().at(0));
  17930. this.assignExitContinuations(n.blocks().at(1));
  17931. break;
  17932. }
  17933. case 'prim::Closure': {
  17934. const closure_block = new torch._C.LoopContinuations();
  17935. closure_block.run(n.blocks().at(0));
  17936. break;
  17937. }
  17938. case 'prim::Loop': {
  17939. const prev_loop = this._curr_loop;
  17940. this._curr_loop = n;
  17941. this.assignExitContinuations(n.blocks().at(0));
  17942. this._curr_loop = prev_loop;
  17943. break;
  17944. }
  17945. case 'prim::ContinueStmt': {
  17946. const loop_continuation = this._graph.create('prim::LoopContinuation', 0).insertAfter(n);
  17947. const header_block = loop_continuation.addBlock();
  17948. const [, pre_header] = this._curr_loop.blocks();
  17949. header_block.cloneFrom(pre_header, (v) => v);
  17950. this.InlineBlockBeforeNode(n, header_block);
  17951. loop_continuation.addInput(header_block.outputs()[0]);
  17952. loop_continuation.eraseBlock(0);
  17953. this.addLoopCarriedOutputs(loop_continuation);
  17954. n.destroy();
  17955. break;
  17956. }
  17957. case 'prim::BreakStmt': {
  17958. const loop_exit = this._graph.create('prim::LoopContinuation', 0).insertAfter(n);
  17959. loop_exit.addInput(this._false_val);
  17960. this.addLoopCarriedOutputs(loop_exit);
  17961. n.destroy();
  17962. break;
  17963. }
  17964. default: {
  17965. break;
  17966. }
  17967. }
  17968. }
  17969. }
  17970. run(...args) {
  17971. if (args.length === 1 && args[0] instanceof torch.Graph) {
  17972. const [graph] = args;
  17973. this.run(graph.block());
  17974. } else if (args.length === 1 && args[0] instanceof torch.Block) {
  17975. const [b] = args;
  17976. {
  17977. this._graph = b.owningGraph();
  17978. const guard = new torch._C.WithInsertPoint(b.nodes().front());
  17979. this._false_val = this._graph.insertConstant(false);
  17980. guard.dispose();
  17981. }
  17982. this.assignExitContinuations(b);
  17983. } else {
  17984. throw new python.Error('Not implemented.');
  17985. }
  17986. }
  17987. });
  17988. this.registerType('torch._C.LoopView', class {
  17989. constructor(node) {
  17990. torch._C.AT_ASSERT(node.kind() === 'prim::Loop' || node.kind() === 'onnx::Loop');
  17991. this._node = node;
  17992. }
  17993. bodyBlock() {
  17994. return this._node.blocks().at(0);
  17995. }
  17996. nextCond() {
  17997. return this.bodyBlock().outputs()[0];
  17998. }
  17999. carriedOutputs() {
  18000. return this._node.outputs();
  18001. }
  18002. bodyCarriedInputs() {
  18003. return this.bodyBlock().inputs().slice(1);
  18004. }
  18005. bodyCarriedOutputs() {
  18006. return this.bodyBlock().outputs().slice(1);
  18007. }
  18008. });
  18009. this.registerType('torch._C.WithLoopStatus', class {
  18010. constructor(to_ir, new_status) {
  18011. this._to_ir = to_ir;
  18012. this._prev = this._to_ir._loop_status;
  18013. this._to_ir._loop_status = new_status;
  18014. }
  18015. dispose() {
  18016. this._to_ir._loop_status = this._prev;
  18017. }
  18018. });
  18019. this.registerFunction('torch._C.InlineBlockBeforeNode', (before_node, block) => {
  18020. for (const block_node of block.nodes()) {
  18021. block_node.moveBefore(before_node);
  18022. }
  18023. });
  18024. this.registerFunction('torch._C.inlineLoopCondition', (...args) => {
  18025. if (args.length === 1 && args[0] instanceof torch.Block) {
  18026. const [block] = args;
  18027. for (const n of block.nodes()) {
  18028. for (const b of n.blocks()) {
  18029. torch._C.inlineLoopCondition(b);
  18030. }
  18031. if (n.kind() === 'prim::Loop') {
  18032. torch._C.inlineLoopCondition(n);
  18033. }
  18034. }
  18035. } else if (args.length === 1 && args[0] instanceof torch.Node) {
  18036. const [n] = args;
  18037. const [body_block, pre_header] = n.blocks();
  18038. const temp_block = n.addBlock();
  18039. temp_block.cloneFrom(pre_header, (v) => v);
  18040. torch._C.InlineBlockBeforeNode(n, temp_block);
  18041. n.insertInput(1, temp_block.outputs()[0]);
  18042. n.eraseBlock(2);
  18043. torch._C.InlineBlockBeforeNode(body_block.return_node(), pre_header);
  18044. body_block.return_node().insertInput(0, pre_header.outputs()[0]);
  18045. n.eraseBlock(1);
  18046. } else {
  18047. throw new python.Error('Not implemented.');
  18048. }
  18049. });
  18050. this.registerFunction('torch._C.InlineLoopCondition', (graph) => {
  18051. torch._C.inlineLoopCondition(graph.block());
  18052. });
  18053. this.registerType('torch._C.EraseLoadStores', class {
  18054. pushFrame(b) {
  18055. this.environment_stack = new torch._C.ValueEnvironment(b, this.environment_stack);
  18056. }
  18057. popFrame() {
  18058. const old_frame = this.environment_stack;
  18059. this.environment_stack = this.environment_stack.next;
  18060. return old_frame;
  18061. }
  18062. eraseBlockLoadStores(block) {
  18063. this.pushFrame(block);
  18064. for (const n of block.nodes()) {
  18065. switch (n.kind()) {
  18066. case 'prim::Store': {
  18067. this.environment_stack.setVar(n.s('name'), n.input());
  18068. n.destroy();
  18069. break;
  18070. }
  18071. case 'prim::Load': {
  18072. const name = n.s('name');
  18073. const value = this.environment_stack.findInAnyFrame(name);
  18074. torch._C.TORCH_INTERNAL_ASSERT(value);
  18075. n.output().replaceAllUsesWith(value);
  18076. n.destroy();
  18077. break;
  18078. }
  18079. case 'prim::ComprehensionScope': {
  18080. const [body] = n.blocks();
  18081. this.eraseBlockLoadStores(body);
  18082. for (const body_node of body.nodes()) {
  18083. body_node.moveBefore(n);
  18084. }
  18085. n.destroy();
  18086. break;
  18087. }
  18088. default: {
  18089. for (const b of n.blocks()) {
  18090. this.eraseBlockLoadStores(b);
  18091. }
  18092. break;
  18093. }
  18094. }
  18095. }
  18096. this.popFrame();
  18097. }
  18098. run(graph) {
  18099. this.eraseBlockLoadStores(graph.block());
  18100. }
  18101. });
  18102. this.registerFunction('torch._C.convertEnterExitNodesToWithBlocks', (/* graph */) => {
  18103. });
  18104. this.registerFunction('torch._C.inlineConsecutiveIfs', (/* graph */) => {
  18105. });
  18106. this.registerType('torch._C.ExitPair', class {
  18107. constructor(exit_v, exit_val_ref) {
  18108. const exit_vals = [];
  18109. for (const v of exit_val_ref) {
  18110. exit_vals.push(v);
  18111. }
  18112. if (exit_v.type() !== torch.BoolType.get()) {
  18113. throw new python.Error('Invalid exit value type.');
  18114. }
  18115. this.first = exit_v;
  18116. this.second = exit_vals;
  18117. }
  18118. hasExited() {
  18119. return this.first;
  18120. }
  18121. exitValues() {
  18122. return this.second;
  18123. }
  18124. });
  18125. this.registerType('torch._C.ExitTransformer', class {
  18126. constructor(graph) {
  18127. this._graph = graph;
  18128. this._target_block = null;
  18129. this._unit_values = new Map();
  18130. const guard = new torch._C.WithInsertPoint(this._graph.block().nodes().front());
  18131. this._true_val = this._graph.insertConstant(true);
  18132. this._false_val = this._graph.insertConstant(false);
  18133. this._throws_val = this.getUnitValue(torch.BoolType.get());
  18134. guard.dispose();
  18135. }
  18136. getUnitValue(type) {
  18137. const maybe_val = this._unit_values.get(type);
  18138. if (maybe_val) {
  18139. return maybe_val;
  18140. }
  18141. const unit = this._graph.createUninitialized(type).insertAfter(this._graph.param_node()).output();
  18142. this._unit_values.set(type, unit);
  18143. return unit;
  18144. }
  18145. transformReturnStmts() {
  18146. this._current_exit_kind = 'prim::ReturnStmt';
  18147. this.transformExits(this._graph.block());
  18148. }
  18149. transformLoopContinuations() {
  18150. this._current_exit_kind = 'prim::LoopContinuation';
  18151. this.transformExits(this._graph.block());
  18152. }
  18153. destroyNodeAfterExit(n) {
  18154. for (const output of n.outputs()) {
  18155. if (output.uses().length > 0) {
  18156. output.replaceAllUsesWith(this.getUnitValue(output.type()));
  18157. }
  18158. }
  18159. n.destroy();
  18160. }
  18161. deleteAfterExitNodes(block, iter) {
  18162. const nodes = block.nodes();
  18163. if (iter === nodes.end()) {
  18164. return;
  18165. }
  18166. const insert = new torch._C.WithInsertPoint(block.nodes().front());
  18167. for (const it of Array.from(nodes).reverse()) {
  18168. if (it === iter) {
  18169. break;
  18170. }
  18171. if (it !== block.return_node()) {
  18172. this.destroyNodeAfterExit(it);
  18173. }
  18174. }
  18175. this.destroyNodeAfterExit(iter);
  18176. insert.dispose();
  18177. }
  18178. updateTargetBlock(block) {
  18179. if (torch._C.ExitTransformer.owningNodeKind(block) === 'prim::Loop' && this._current_exit_kind === 'prim::LoopContinuation') {
  18180. this._target_block = block;
  18181. } else if (torch._C.ExitTransformer.isGraphOrClosureBlock(block) && this._current_exit_kind === 'prim::ReturnStmt') {
  18182. this._target_block = block;
  18183. }
  18184. }
  18185. transformLoop(node) {
  18186. const loop = new torch._C.LoopView(node);
  18187. const body = loop.bodyBlock();
  18188. const exit_pair = this.transformExits(body);
  18189. if (this.getExitStatus(exit_pair) === 'WONT' || this.getExitStatus(exit_pair) === 'THROWS') {
  18190. return this.constructWontExitPair();
  18191. }
  18192. const insert = new torch._C.WithInsertPoint(body);
  18193. const new_if = this._graph.insertNode(this._graph.create('prim::If', 0));
  18194. new_if.addInput(exit_pair.hasExited());
  18195. new_if.addBlock().registerOutput(this._false_val);
  18196. new_if.addBlock().registerOutput(loop.nextCond());
  18197. const new_condition = new_if.addOutput().setType(torch.BoolType.get());
  18198. loop.bodyBlock().eraseOutput(0);
  18199. loop.bodyBlock().insertOutput(0, new_condition);
  18200. node.addInput(this._false_val);
  18201. body.addInput().setType(torch.BoolType.get());
  18202. body.registerOutput(exit_pair.hasExited());
  18203. const new_has_exited = node.addOutput().setType(torch.BoolType.get());
  18204. for (const exit_value of exit_pair.exitValues()) {
  18205. const typ = exit_value.type();
  18206. node.addInput(this.getUnitValue(typ));
  18207. node.addOutput().setType(typ);
  18208. body.addInput().setType(typ);
  18209. body.registerOutput(exit_value);
  18210. }
  18211. const exit_vals = node.outputs().slice(node.outputs().length - exit_pair.exitValues().size());
  18212. const result = new torch._C.ExitPair(new_has_exited, exit_vals);
  18213. insert.dispose();
  18214. return result;
  18215. }
  18216. calcIfExitStatus(then_status, else_status) {
  18217. if (then_status === 'THROWS') {
  18218. return else_status;
  18219. } else if (else_status === 'THROWS') {
  18220. return then_status;
  18221. }
  18222. if (then_status === 'WONT' && else_status === 'WONT') {
  18223. return 'WONT';
  18224. }
  18225. if (then_status === 'WILL' && else_status === 'WILL') {
  18226. return 'WILL';
  18227. }
  18228. return 'MIGHT';
  18229. }
  18230. transformIf(node) {
  18231. const [then_block, else_block] = node.blocks();
  18232. let then_pair = this.transformExits(then_block);
  18233. let else_pair = this.transformExits(else_block);
  18234. const then_status = this.getExitStatus(then_pair);
  18235. const else_status = this.getExitStatus(else_pair);
  18236. const if_status = this.calcIfExitStatus(then_status, else_status);
  18237. if (if_status === 'THROWS') {
  18238. return this.constructThrowsExitPair();
  18239. }
  18240. if (if_status === 'WONT') {
  18241. return this.constructWontExitPair();
  18242. }
  18243. if (then_status === 'WONT' || then_status === 'THROWS') {
  18244. const exit_vals = this.matchValuesWithUnitialized(else_pair.exitValues());
  18245. then_pair = new torch._C.ExitPair(then_pair.hasExited(), exit_vals);
  18246. } else if (else_status === 'WONT' || else_status === 'THROWS') {
  18247. const exit_vals = this.matchValuesWithUnitialized(then_pair.exitValues());
  18248. else_pair = new torch._C.ExitPair(else_pair.hasExited(), exit_vals);
  18249. }
  18250. let has_exited = null;
  18251. if (if_status === 'WILL') {
  18252. has_exited = this._true_val;
  18253. } else {
  18254. this.addIfOutputs(node, [then_pair.hasExited()], [else_pair.hasExited()]);
  18255. has_exited = node.outputs().at(node.outputs().length - 1);
  18256. }
  18257. this.addIfOutputs(node, then_pair.exitValues(), else_pair.exitValues());
  18258. const num_exit_vals = then_pair.exitValues().size();
  18259. const exit_vals = node.outputs().slice(node.outputs().length - num_exit_vals);
  18260. return new torch._C.ExitPair(has_exited, exit_vals);
  18261. }
  18262. transformExits(block) {
  18263. const prev_target_block = this._target_block;
  18264. this.updateTargetBlock(block);
  18265. let exit_pair = this.constructWontExitPair();
  18266. for (const node of block.nodes()) {
  18267. const it = node.next;
  18268. switch (node.kind()) {
  18269. case 'prim::RaiseException': {
  18270. exit_pair = this.constructThrowsExitPair();
  18271. break;
  18272. }
  18273. case 'prim::ReturnStmt':
  18274. case 'prim::LoopContinuation': {
  18275. if (node.kind() === this._current_exit_kind) {
  18276. exit_pair = this.constructWillExitPair(node.inputs());
  18277. node.destroy();
  18278. }
  18279. break;
  18280. }
  18281. case 'prim::If': {
  18282. exit_pair = this.transformIf(node);
  18283. break;
  18284. }
  18285. case 'prim::With': {
  18286. exit_pair = this.transformWith(node);
  18287. break;
  18288. }
  18289. case 'prim::Closure': {
  18290. this.transformExits(node.blocks().at(0));
  18291. break;
  18292. }
  18293. case 'prim::Loop': {
  18294. exit_pair = this.transformLoop(node);
  18295. break;
  18296. }
  18297. default: {
  18298. break;
  18299. }
  18300. }
  18301. const status = this.getExitStatus(exit_pair);
  18302. if (status === 'WILL' || status === 'THROWS') {
  18303. this.deleteAfterExitNodes(block, it);
  18304. break;
  18305. }
  18306. if (status === 'MIGHT') {
  18307. throw new python.Error('Not implemented.');
  18308. // const nodes = block.nodes();
  18309. // if (node === nodes[nodes.length - 1]) {
  18310. // exit_pair = this.guardBlockNodes(block, exit_pair, it);
  18311. // }
  18312. // break;
  18313. }
  18314. }
  18315. if (this._target_block === block) {
  18316. if (this.getExitStatus(exit_pair) === 'MIGHT') {
  18317. const new_if = this._graph.create('prim::If', 0).insertBefore(block.return_node());
  18318. new_if.addBlock();
  18319. new_if.addBlock();
  18320. new_if.addInput(exit_pair.hasExited());
  18321. torch._C.ExistTransformer.addIfOutputs(new_if, exit_pair.exitValues(), block.outputs());
  18322. torch._C.ExistTransformer.replaceBlockOutputs(block, new_if.soutputs());
  18323. } else if (this.getExitStatus(exit_pair) === 'WILL') {
  18324. torch._C.ExitTransformer.replaceBlockOutputs(block, exit_pair.exitValues());
  18325. }
  18326. exit_pair = this.constructWontExitPair();
  18327. }
  18328. this._target_block = prev_target_block;
  18329. return exit_pair;
  18330. }
  18331. constructThrowsExitPair() {
  18332. return new torch._C.ExitPair(this._throws_val, []);
  18333. }
  18334. constructWontExitPair() {
  18335. return new torch._C.ExitPair(this._false_val, []);
  18336. }
  18337. constructWillExitPair(exit_val_ref) {
  18338. return new torch._C.ExitPair(this._true_val, exit_val_ref);
  18339. }
  18340. getExitStatus(exit_pair) {
  18341. const exit_v = exit_pair.hasExited();
  18342. if (exit_v === this._true_val) {
  18343. return 'WILL';
  18344. } else if (exit_v === this._false_val) {
  18345. return 'WONT';
  18346. } else if (exit_v === this._throws_val) {
  18347. return 'THROWS';
  18348. }
  18349. return 'MIGHT';
  18350. }
  18351. static owningNodeKind(block) {
  18352. if (block.owningNode()) {
  18353. return block.owningNode().kind();
  18354. }
  18355. return null;
  18356. }
  18357. static isGraphOrClosureBlock(block) {
  18358. return block.owningNode() === null || torch._C.ExitTransformer.owningNodeKind(block) === 'prim::Closure';
  18359. }
  18360. static removeOutputs(b) {
  18361. while (b.outputs().length > 0) {
  18362. b.eraseOutput(0);
  18363. }
  18364. }
  18365. static registerBlockOutputs(b, outs) {
  18366. for (const out of outs) {
  18367. b.registerOutput(out);
  18368. }
  18369. }
  18370. static replaceBlockOutputs(b, outs) {
  18371. torch._C.ExitTransformer.removeOutputs(b);
  18372. torch._C.ExitTransformer.registerBlockOutputs(b, outs);
  18373. }
  18374. });
  18375. this.registerFunction('torch._C.convertWithBlocksToEnterExitNodes', (/* graph */) => {
  18376. });
  18377. this.registerFunction('torch._C.TransformExits', (graph) => {
  18378. torch._C.convertEnterExitNodesToWithBlocks(graph);
  18379. const e_loop = new torch._C.ExitTransformer(graph);
  18380. e_loop.transformLoopContinuations();
  18381. const e_ret = new torch._C.ExitTransformer(graph);
  18382. e_ret.transformReturnStmts();
  18383. torch._C.inlineConsecutiveIfs(graph.block());
  18384. torch._C.convertWithBlocksToEnterExitNodes(graph);
  18385. });
  18386. this.registerFunction('torch._C.normalizeRSub', (iter) => {
  18387. if (iter.kind() === 'aten::rsub' && iter.schema() && iter.schema().overload === 'Tensor') {
  18388. const args = iter.inputs();
  18389. const newSub = iter.replaceWithNewSymbol('aten::sub');
  18390. newSub.replaceInput(0, args[1]);
  18391. newSub.replaceInput(1, args[0]);
  18392. iter.destroyCurrent();
  18393. return true;
  18394. }
  18395. return false;
  18396. });
  18397. this.registerFunction('torch._C.normalizeOpAliases', (/* iter */) => {
  18398. });
  18399. this.registerFunction('torch._C.normalizeIsBool', (iter) => {
  18400. const args = iter.inputs();
  18401. if (args.length === 2 && args[0].type() === torch.BoolType.get() && args[1].type() === torch.BoolType.get()) {
  18402. if (iter.kind() === 'aten::__is__') {
  18403. iter.replaceWithNewSymbol('aten::eq');
  18404. iter.destroyCurrent();
  18405. return true;
  18406. }
  18407. if (iter.kind() === 'aten::__isnot__') {
  18408. iter.replaceWithNewSymbol('aten::ne');
  18409. iter.destroyCurrent();
  18410. return true;
  18411. }
  18412. }
  18413. return false;
  18414. });
  18415. this.registerFunction('torch._C.NormalizeOps', (block) => {
  18416. for (const it of block.nodes()) {
  18417. for (const sub of it.blocks()) {
  18418. torch._C.NormalizeOps(sub);
  18419. }
  18420. if (torch._C.normalizeRSub(it)) {
  18421. continue;
  18422. }
  18423. if (torch._C.normalizeOpAliases(it)) {
  18424. continue;
  18425. }
  18426. if (torch._C.normalizeIsBool(it)) {
  18427. continue;
  18428. }
  18429. }
  18430. });
  18431. this.registerFunction('torch._C.getInlineEverythingMode', () => {
  18432. return false;
  18433. });
  18434. this.registerFunction('torch._C.runCleanupPasses', (to_clean) => {
  18435. /*
  18436. torch._C.liftClosures(to_clean);
  18437. torch._C.inlineForkedClosures(to_clean);
  18438. */
  18439. if (torch._C.getInlineEverythingMode()) {
  18440. torch._C.Inline(to_clean);
  18441. }
  18442. /*
  18443. torch._C.eraseListLiterals(to_clean);
  18444. */
  18445. torch._C.LowerSimpleTuples(to_clean);
  18446. torch._C.ConstantPropagationImmutableTypes(to_clean);
  18447. torch._C.ConstantPooling(to_clean);
  18448. /*
  18449. torch._C.CanonicalizeOutputs(to_clean);
  18450. torch._C.AnnotateWarns(to_clean);
  18451. */
  18452. });
  18453. this.registerType('torch.jit._script.ScriptModule', class extends torch.nn.modules.module.Module {});
  18454. this.registerType('torch.jit._trace.TracedModule', class extends torch.jit._script.ScriptModule {});
  18455. this.registerType('torch.jit._trace.TopLevelTracedModule', class extends torch.jit._trace.TracedModule {});
  18456. this.registerType('torch.jit._script.RecursiveScriptModule', class extends torch.jit._script.ScriptModule {
  18457. constructor(cpp_module) {
  18458. super();
  18459. this._initializing = true;
  18460. this._c = cpp_module;
  18461. }
  18462. static _construct(cpp_module, init_fn) {
  18463. const script_module = new torch.jit._script.RecursiveScriptModule(cpp_module);
  18464. init_fn(script_module);
  18465. torch.jit._script.RecursiveScriptModule._finalize_scriptmodule(script_module);
  18466. return script_module;
  18467. }
  18468. static _finalize_scriptmodule(script_module) {
  18469. script_module._parameters = new torch.ParameterDict(script_module._c).items();
  18470. script_module._buffers = new torch.BufferDict(script_module._c).items();
  18471. // script_module._modules = OrderedModuleDict(script_module._c, script_module._modules)
  18472. script_module._initializing = false;
  18473. }
  18474. get graph() {
  18475. // return this._c._get_method('forward').graph;
  18476. return this._c.graph;
  18477. }
  18478. get code_with_constants() {
  18479. // return this.forward.code_with_constants;
  18480. return this._c.code_with_constants;
  18481. }
  18482. __setattr__(name, value) {
  18483. if (this._initializing) {
  18484. super.__setattr__(name, value);
  18485. } else if (this._modules.has(name)) {
  18486. this._modules.set(name, value);
  18487. } else if (this._c.hasattr(name)) {
  18488. this._c.setattr(name, value);
  18489. } else {
  18490. //
  18491. }
  18492. }
  18493. __getattr__(name) {
  18494. if (this._initializing) {
  18495. return super.__getattr__(name);
  18496. }
  18497. if (this._modules.has(name)) {
  18498. return this._modules.get(name);
  18499. }
  18500. if (this._c.hasattr(name)) {
  18501. return this._c.getattr(name);
  18502. }
  18503. if (this._c._has_method(name)) {
  18504. //
  18505. }
  18506. return super.__getattr__(name);
  18507. }
  18508. });
  18509. torch.jit.ScriptModule = torch.jit._script.ScriptModule;
  18510. torch.jit.RecursiveScriptModule = torch.jit._script.RecursiveScriptModule;
  18511. torch.jit.TopLevelTracedModule = torch.jit._trace.TopLevelTracedModule;
  18512. torch.CompilationUnit = torch.jit.CompilationUnit;
  18513. torch._C.CompilationUnit = torch.jit.CompilationUnit;
  18514. torch._C.ScriptModule = torch.ScriptModule;
  18515. torch._C.ClassType = torch.ClassType;
  18516. this.registerType('torch._C.FlatBuffersLoader', class {
  18517. constructor(cu) {
  18518. this._cu = cu;
  18519. const torch = cu.execution.__import__('torch');
  18520. this._torch = torch;
  18521. const dtypes = Array.from(new Set(Object.values(torch).filter((obj) => obj instanceof torch.dtype)));
  18522. this._dtypes = new Map(dtypes.map((dtype) => [dtype.scalar_type(), dtype]));
  18523. this._ivalue_parsers = new Map();
  18524. this._ivalue_parsers.set(torch.mobile.serialization.Int, (ivalue) => ivalue.val.int_val);
  18525. this._ivalue_parsers.set(torch.mobile.serialization.Bool, (ivalue) => ivalue.val.bool_val);
  18526. this._ivalue_parsers.set(torch.mobile.serialization.Double, (ivalue) => ivalue.val.double_val);
  18527. this._ivalue_parsers.set(torch.mobile.serialization.TensorMetadata, (ivalue) => this.parseTensor(ivalue));
  18528. this._ivalue_parsers.set(torch.mobile.serialization.Object, (ivalue) => this.parseObject(ivalue));
  18529. }
  18530. parseModule(module) {
  18531. this._module = module;
  18532. this._all_functions = new Map();
  18533. this._all_ivalues = new Array(module.ivalues.length);
  18534. this._all_types = new Array(module.object_types.length);
  18535. const mobile_ivalue_size = module.mobile_ivalue_size ? module.mobile_ivalue_size : module.ivalues.length;
  18536. for (let i = 0; i < mobile_ivalue_size; i++) {
  18537. this.parseAndPopulate(i, module.ivalues[i]);
  18538. }
  18539. const m = this._all_ivalues[module.state_obj];
  18540. for (const [name, value] of this._all_functions) {
  18541. const class_index = module.ivalues[name].val.class_type;
  18542. const class_type = this._all_types[class_index];
  18543. if (value) {
  18544. class_type.addMethod(value);
  18545. }
  18546. }
  18547. m._min_operator_version = module.operator_version;
  18548. m._bytecode_version = module.bytecode_version;
  18549. return m;
  18550. }
  18551. parseAndPopulate(i, ivalue) {
  18552. if (ivalue.val instanceof torch.mobile.serialization.Function) {
  18553. this._all_functions.set(i, this.parseFunction(ivalue.val));
  18554. } else {
  18555. this._all_ivalues[i] = this.parseIValue(ivalue);
  18556. }
  18557. }
  18558. parseFunction(/* val */) {
  18559. return null;
  18560. }
  18561. parseIValue(ivalue) {
  18562. if (ivalue.val) {
  18563. const callback = this._ivalue_parsers.get(ivalue.val.constructor);
  18564. return callback(ivalue);
  18565. }
  18566. return null;
  18567. }
  18568. parseTensor(ivalue) {
  18569. return this.parseTensorFromMetadata(ivalue.val);
  18570. }
  18571. parseTensorFromMetadata(metadata) {
  18572. if (metadata.quantized_schema) {
  18573. throw new torch.Error('Quantized schema not implemented.');
  18574. }
  18575. const index = metadata.storage_location_index;
  18576. const data = this._module.storage_data[index].data;
  18577. const dtype = this._dtypes.get(metadata.scalar_type);
  18578. const size = data.length / dtype.itemsize();
  18579. const storage = new torch.storage.TypedStorage(size, dtype);
  18580. storage._set_cdata(data);
  18581. const tensor = new torch.Tensor();
  18582. const shape = Array.from(metadata.sizes);
  18583. const stride = Array.from(metadata.strides);
  18584. tensor.__setstate__([storage, metadata.storage_offset, shape, stride]);
  18585. return tensor;
  18586. }
  18587. parseObject(ivalue) {
  18588. const object = ivalue.val;
  18589. const obj_type = this._module.object_types[object.type_index];
  18590. const cls = this.getOrCreateClassTypeForObject(object);
  18591. switch (obj_type.type) {
  18592. case torch.mobile.serialization.TypeType.CLASS_WITH_FIELD: {
  18593. const torch = this._torch;
  18594. const obj = torch.ScriptObject.create(cls);
  18595. for (let i = 0; i < object.attrs.length; i++) {
  18596. const attr_name = obj_type.attr_names[i];
  18597. const val = this._all_ivalues[object.attrs[i]];
  18598. obj.__setattr__(attr_name, val);
  18599. }
  18600. return obj;
  18601. }
  18602. case torch.mobile.serialization.TypeType.CUSTOM_CLASS:
  18603. case torch.mobile.serialization.TypeType.CLASS_WITH_SETSTATE:
  18604. default: {
  18605. throw new python.Error(`Unknown object type type '${obj_type.type}'.`);
  18606. }
  18607. }
  18608. }
  18609. getOrCreateClassTypeForObject(object) {
  18610. let cls = this._all_types[object.type_index];
  18611. const obj_type = this._module.object_types[object.type_index];
  18612. if (!cls) {
  18613. const name = obj_type.type_name;
  18614. if (name.startsWith('__torch__') || name.startsWith('torch.jit')) {
  18615. cls = this._cu.get_class(new torch._C.QualifiedName(name));
  18616. if (!cls) {
  18617. const torch = this._torch;
  18618. cls = torch.ClassType.create(name, this._cu, true);
  18619. this._cu.register_type(cls);
  18620. }
  18621. } else {
  18622. // cls = c10::parseType(qn_str).cast<ClassType>();
  18623. }
  18624. this._all_types[object.type_index] = cls;
  18625. if (obj_type.type === torch.mobile.serialization.TypeType.CLASS_WITH_FIELD) {
  18626. for (let i = 0; i < object.attrs.length; i++) {
  18627. // const val = this._all_ivalues[object.attrs[i]];
  18628. cls.addAttribute(obj_type.attr_names[i] /*, null val.type(c10::DynamicType) */);
  18629. }
  18630. }
  18631. }
  18632. return cls;
  18633. }
  18634. });
  18635. this.registerType('torch.export.UnflattenedModule', class extends torch.nn.modules.module.Module {
  18636. constructor(export_module, flat_args_adapter) {
  18637. super();
  18638. const export_graph = copy.deepcopy(export_module.graph);
  18639. self.graph_signature = copy.deepcopy(export_module.graph_signature);
  18640. this.graph = torch.fx.Graph();
  18641. this.graph.owning_module = this;
  18642. this.module_call_graph = copy.deepcopy(export_module.module_call_graph);
  18643. this.flat_args_adapter = flat_args_adapter;
  18644. this.adapted = false;
  18645. // this._run_with_interpreter = RUN_WITH_INTERPRETER
  18646. this._inplace_buffer_mutations(export_graph, this.graph_signature);
  18647. }
  18648. });
  18649. this.registerType('torch.export.graph_signature.ExportGraphSignature', class {
  18650. constructor(input_specs, output_specs) {
  18651. this.input_specs = input_specs;
  18652. this.output_specs = output_specs;
  18653. }
  18654. get user_inputs() {
  18655. const user_inputs = [];
  18656. for (const s of this.input_specs) {
  18657. if (s.kind !== torch.export.graph_signature.InputKind.USER_INPUT) {
  18658. continue;
  18659. }
  18660. if (s.arg instanceof torch.export.graph_signature.TensorArgument ||
  18661. s.arg instanceof torch.export.graph_signature.SymIntArgument ||
  18662. s.arg instanceof torch.export.graph_signature.CustomObjArgument) {
  18663. user_inputs.push(s.arg.name);
  18664. } else if (s.arg instanceof torch.export.graph_signature.ConstantArgument) {
  18665. user_inputs.push(s.arg.value);
  18666. } else {
  18667. throw new python.Error(`Unsupported user input '${s.arg}'.`);
  18668. }
  18669. }
  18670. return user_inputs;
  18671. }
  18672. get user_outputs() {
  18673. const user_outputs = [];
  18674. for (const s of this.output_specs) {
  18675. if (s.kind !== torch.export.graph_signature.OutputKind.USER_OUTPUT) {
  18676. continue;
  18677. }
  18678. if (s.arg instanceof torch.export.graph_signature.TensorArgument ||
  18679. s.arg instanceof torch.export.graph_signature.SymIntArgument ||
  18680. s.arg instanceof torch.export.graph_signature.CustomObjArgument) {
  18681. user_outputs.push(s.arg.name);
  18682. } else if (s.arg instanceof torch.export.graph_signature.ConstantArgument) {
  18683. user_outputs.push(s.arg.value);
  18684. } else {
  18685. throw new python.Error(`Unsupported user output '${s.arg}'.`);
  18686. }
  18687. }
  18688. return user_outputs;
  18689. }
  18690. get inputs_to_parameters() {
  18691. return new Map(this.input_specs
  18692. .filter((s) => s.kind === torch.export.graph_signature.InputKind.PARAMETER && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  18693. .map((s) => [s.arg.name, s.target]));
  18694. }
  18695. get inputs_to_buffers() {
  18696. return new Map(this.input_specs
  18697. .filter((s) => s.kind === torch.export.graph_signature.InputKind.BUFFER && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  18698. .map((s) => [s.arg.name, s.target]));
  18699. }
  18700. get inputs_to_lifted_tensor_constants() {
  18701. return new Map(this.input_specs
  18702. .filter((s) => s.kind === torch.export.graph_signature.InputKind.CONSTANT_TENSOR && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  18703. .map((s) => [s.arg.name, s.target]));
  18704. }
  18705. });
  18706. torch.export.graph_signature.InputKind = {
  18707. USER_INPUT: 0,
  18708. PARAMETER: 1,
  18709. BUFFER: 2,
  18710. CONSTANT_TENSOR: 3,
  18711. CUSTOM_OBJ: 4,
  18712. TOKEN: 5
  18713. };
  18714. this.registerType('torch.export.graph_signature.InputSpec', class {
  18715. constructor(kind, arg, target, persistent) {
  18716. this.kind = kind;
  18717. this.arg = arg;
  18718. this.target = target;
  18719. this.persistent = persistent || null;
  18720. }
  18721. });
  18722. torch.export.graph_signature.OutputKind = {
  18723. USER_OUTPUT: 0,
  18724. LOSS_OUTPUT: 1,
  18725. BUFFER_MUTATION: 2,
  18726. GRADIENT_TO_PARAMETER: 3,
  18727. GRADIENT_TO_USER_INPUT: 4,
  18728. USER_INPUT_MUTATION: 5,
  18729. TOKEN: 6
  18730. };
  18731. this.registerType('torch.export.graph_signature.OutputSpec', class {
  18732. constructor(kind, arg, target) {
  18733. this.kind = kind;
  18734. this.arg = arg;
  18735. this.target = target;
  18736. }
  18737. });
  18738. this.registerType('torch.export.graph_signature.ConstantArgument', class {
  18739. constructor(name, value) {
  18740. this.name = name;
  18741. this.value = value; // Union[int, float, bool, str, None]
  18742. }
  18743. });
  18744. this.registerType('torch.export.graph_signature.TensorArgument', class {
  18745. constructor(name) {
  18746. this.name = name;
  18747. }
  18748. });
  18749. this.registerType('torch.export.graph_signature.SymIntArgument', class {
  18750. constructor(name) {
  18751. this.name = name;
  18752. }
  18753. });
  18754. this.registerType('torch.export.graph_signature.CustomObjArgument', class {
  18755. constructor(name, class_fqn, fake_val) {
  18756. this.name = name;
  18757. this.class_fqn = class_fqn;
  18758. this.fake_val = fake_val;
  18759. }
  18760. });
  18761. this.registerType('torch.export.exported_program.ExportedProgram', class {
  18762. constructor(root, graph, graph_signature, state_dict, range_constraints, module_call_graph, example_inputs, verifier, tensor_constants, constants) {
  18763. // graph._codegen = torch.fx.graph.CodeGen()
  18764. this._graph_module = this._create_graph_module_for_export(root, graph);
  18765. if (root instanceof torch.fx.GraphModule) {
  18766. // this._graph_module.meta.update(root.meta);
  18767. }
  18768. this._graph_signature = graph_signature;
  18769. this._state_dict = state_dict;
  18770. this._range_constraints = range_constraints;
  18771. this._module_call_graph = module_call_graph;
  18772. this._example_inputs = example_inputs;
  18773. this._constants = tensor_constants || constants || {};
  18774. }
  18775. _create_graph_module_for_export(root, graph) {
  18776. let gm = null;
  18777. try {
  18778. gm = new torch.fx.GraphModule(root, graph);
  18779. } catch {
  18780. const gm = new torch.fx.GraphModule(root, torch.fx.Graph());
  18781. gm._graph = graph;
  18782. }
  18783. return gm;
  18784. }
  18785. get graph_module() {
  18786. return this._graph_module;
  18787. }
  18788. get graph() {
  18789. return this._graph_module.graph;
  18790. }
  18791. get graph_signature() {
  18792. return this._graph_signature;
  18793. }
  18794. get state_dict() {
  18795. return this._state_dict;
  18796. }
  18797. get constants() {
  18798. return this._constants;
  18799. }
  18800. });
  18801. this.registerType('torch.export.exported_program.ModuleCallEntry', class {});
  18802. this.registerType('torch.export.exported_program.ModuleCallSignature', class {});
  18803. this.registerFunction('torch.export.exported_program._create_graph_module_for_export', (root, graph) => {
  18804. return new torch.fx.graph_module.GraphModule(root, graph);
  18805. });
  18806. this.registerFunction('torch.export.unflatten', (module, flat_args_adapter) => {
  18807. module = torch.export._remove_effect_tokens(module);
  18808. return new torch.export.UnflattenedModule(module, flat_args_adapter);
  18809. });
  18810. this.registerFunction('torch._export.exported_program._create_graph_module_for_export', (root, graph) => {
  18811. return new torch.fx.graph_module.GraphModule(root, graph);
  18812. });
  18813. this.registerType('torch._export.serde.serialize.SerializedArtifact', class {
  18814. constructor(exported_program, state_dict, constants, example_inputs) {
  18815. this.exported_program = exported_program;
  18816. this.state_dict = state_dict;
  18817. this.constants = constants;
  18818. this.example_inputs = example_inputs;
  18819. }
  18820. });
  18821. torch._export.serde.serialize._SYM_OPS = new Set([
  18822. operator.eq, operator.ne, operator.le, operator.ge, operator.lt, operator.gt,
  18823. operator.neg, operator.pos, operator.and_, operator.or_,
  18824. math.trunc, torch.sym_not,
  18825. operator.mul, operator.add, operator.sub, operator.floordiv, operator.mod, operator.pow,
  18826. torch.sym_int, torch.sym_float, torch.sym_ite, torch.sym_max, torch.sym_min, torch.sym_sqrt,
  18827. operator.truediv, operator.and_
  18828. ]);
  18829. this.registerType('torch._export.serde.union._Union', class {
  18830. constructor(obj) {
  18831. if (obj.$type) {
  18832. this.type = obj.$type;
  18833. this[obj.$type] = obj.$value;
  18834. delete obj.$type;
  18835. delete obj.$value;
  18836. } else if (obj.type) {
  18837. this.type = obj.type;
  18838. const entries = Object.entries(obj).filter(([key]) => key !== 'type');
  18839. this[obj.type] = Object.fromEntries(entries);
  18840. } else {
  18841. let entries = Object.entries(obj);
  18842. if (entries.length > 1) {
  18843. entries = entries.filter(([, value]) => value !== null);
  18844. }
  18845. if (entries.length !== 1) {
  18846. throw new python.Error(`Invalid union type '${entries.map(([key]) => key).join(',')}'.`);
  18847. }
  18848. const [entry] = entries;
  18849. const [type, value] = entry;
  18850. this.type = type;
  18851. this[type] = value;
  18852. }
  18853. }
  18854. get value() {
  18855. return this[this.type];
  18856. }
  18857. });
  18858. this.registerType('torch._export.serde.schema.NamedArgument', class {
  18859. constructor(obj) {
  18860. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  18861. this.name = obj.name;
  18862. }
  18863. });
  18864. this.registerType('torch._export.serde.schema.Argument', class extends torch._export.serde.union._Union {
  18865. constructor(obj) {
  18866. super(obj);
  18867. switch (this.type) {
  18868. case 'as_int':
  18869. case 'as_ints':
  18870. case 'as_float':
  18871. case 'as_floats':
  18872. case 'as_bool':
  18873. case 'as_bools':
  18874. case 'as_string':
  18875. case 'as_strings':
  18876. case 'as_scalar_type':
  18877. case 'as_device':
  18878. case 'as_memory_format':
  18879. case 'as_layout':
  18880. break;
  18881. case 'as_none':
  18882. this.as_none = null;
  18883. break;
  18884. case 'as_tensor':
  18885. this.as_tensor = new torch._export.serde.schema.TensorArgument(this.as_tensor);
  18886. break;
  18887. case 'as_tensors':
  18888. this.as_tensors = this.as_tensors.map((item) => new torch._export.serde.schema.TensorArgument(item));
  18889. break;
  18890. case 'as_graph':
  18891. this.as_graph = new torch._export.serde.schema.GraphArgument(this.as_graph);
  18892. break;
  18893. case 'as_sym_int':
  18894. this.as_sym_int = new torch._export.serde.schema.SymIntArgument(this.as_sym_int);
  18895. break;
  18896. case 'as_sym_ints':
  18897. this.as_sym_ints = this.as_sym_ints.map((item) => new torch._export.serde.schema.SymIntArgument(item));
  18898. break;
  18899. case 'as_sym_bool':
  18900. this.as_sym_bool = new torch._export.serde.schema.SymBoolArgument(this.as_sym_bool);
  18901. break;
  18902. case 'as_sym_bools':
  18903. this.as_sym_bools = this.as_sym_bools.map((item) => new torch._export.serde.schema.SymBoolArgument(item));
  18904. break;
  18905. case 'as_sym_float':
  18906. this.as_sym_float = new torch._export.serde.schema.SymFloatArgument(this.as_sym_float);
  18907. break;
  18908. case 'as_sym_floats':
  18909. this.as_sym_floats = this.as_sym_float.map((item) => new torch._export.serde.schema.SymFloatArgument(item));
  18910. break;
  18911. case 'as_optional_tensors':
  18912. this.as_optional_tensors = this.as_optional_tensors.map((item) => new torch._export.serde.schema.OptionalTensorArgument(item));
  18913. break;
  18914. case 'as_custom_obj':
  18915. this.as_custom_obj = new torch._export.serde.schema.CustomObjArgument(this.as_custom_obj);
  18916. break;
  18917. // case 'as_graph': GraphArgument
  18918. default:
  18919. throw new python.Error(`Unsupported argument '${this.type}'.`);
  18920. }
  18921. }
  18922. });
  18923. this.registerType('torch._export.serde.schema.Node', class {
  18924. constructor(obj) {
  18925. this.target = obj.target;
  18926. this.inputs = obj.inputs.map((input) => new torch._export.serde.schema.NamedArgument(input));
  18927. this.outputs = obj.outputs.map((output) => new torch._export.serde.schema.Argument(output));
  18928. this.metadata = new Map(Object.entries(obj.metadata));
  18929. }
  18930. });
  18931. torch._export.serde.schema.ScalarType = {
  18932. UNKNOWN: 0,
  18933. BYTE: 1,
  18934. CHAR: 2,
  18935. SHORT: 3,
  18936. INT: 4,
  18937. LONG: 5,
  18938. HALF: 6,
  18939. FLOAT: 7,
  18940. DOUBLE: 8,
  18941. COMPLEXHALF: 9,
  18942. COMPLEXFLOAT: 10,
  18943. COMPLEXDOUBLE: 11,
  18944. BOOL: 12,
  18945. BFLOAT16: 13,
  18946. UINT16: 28,
  18947. FLOAT8E4M3FN: 29,
  18948. FLOAT8E5M2: 30,
  18949. FLOAT8E4M3FNUZ: 31,
  18950. FLOAT8E5M2FNUZ: 32,
  18951. };
  18952. torch._export.serde.schema.Layout = {
  18953. Unknown: 0,
  18954. SparseCoo: 1,
  18955. SparseCsr: 2,
  18956. SparseCsc: 3,
  18957. SparseBsr: 4,
  18958. SparseBsc: 5,
  18959. _mkldnn: 6,
  18960. Strided: 7
  18961. };
  18962. torch._export.serde.schema.MemoryFormat = {
  18963. Unknown: 0,
  18964. ContiguousFormat: 1,
  18965. ChannelsLast: 2,
  18966. ChannelsLast3d: 3,
  18967. PreserveFormat: 4,
  18968. };
  18969. this.registerType('torch._export.serde.schema.Device', class {
  18970. constructor(obj) {
  18971. Object.assign(this, { ...obj });
  18972. }
  18973. });
  18974. this.registerType('torch._export.serde.schema.TensorMeta', class {
  18975. constructor(obj) {
  18976. obj = obj.meta || obj;
  18977. this.dtype = obj.dtype;
  18978. this.sizes = obj.sizes.map((size) => new torch._export.serde.schema.SymInt(size));
  18979. this.requires_grad = obj.requires_grad;
  18980. this.device = obj.device;
  18981. this.strides = obj.strides.map((stride) => new torch._export.serde.schema.SymInt(stride));
  18982. this.storage_offset = new torch._export.serde.schema.SymInt(Number.isInteger(obj.storage_offset) ? { as_int: obj.storage_offset } : obj.storage_offset);
  18983. this.layout = obj.layout;
  18984. }
  18985. });
  18986. this.registerType('torch._export.serde.schema.Graph', class {
  18987. constructor(obj) {
  18988. this.inputs = obj.inputs.map((input) => new torch._export.serde.schema.Argument(input));
  18989. this.outputs = obj.outputs.map((output) => new torch._export.serde.schema.Argument(output));
  18990. this.nodes = obj.nodes.map((node) => new torch._export.serde.schema.Node(node));
  18991. this.tensor_values = new Map(Object.entries(obj.tensor_values).map(([key, value]) => [key, new torch._export.serde.schema.TensorMeta(value)]));
  18992. this.sym_int_values = new Map(Object.entries(obj.sym_int_values).map(([key, value]) => [key, new torch._export.serde.schema.SymInt(value)]));
  18993. this.sym_bool_values = new Map(Object.entries(obj.sym_bool_values).map(([key, value]) => [key, new torch._export.serde.schema.SymBool(value)]));
  18994. this.is_single_tensor_return = obj.is_single_tensor_return;
  18995. this.custom_obj_values = new Map(Object.entries(obj.custom_obj_values || {}).map(([key, value]) => [key, new torch._export.serde.schema.CustomObjArgument(value)]));
  18996. if (obj.contants) {
  18997. // this.constants = new Map(Object.entries(serialized_graph.constants).map(([k, v]) => [k, torch.load(v)]));
  18998. // graph_signature -> input_specs -> tensor_constant
  18999. }
  19000. }
  19001. });
  19002. this.registerType('torch._export.serde.schema.ModuleCallSignature', class {
  19003. constructor(obj) {
  19004. Object.assign(this, { ...obj });
  19005. this.inputs = this.inputs.map((item) => new torch._export.serde.schema.Argument(item));
  19006. this.outputs = this.outputs.map((item) => new torch._export.serde.schema.Argument(item));
  19007. }
  19008. });
  19009. this.registerType('torch._export.serde.schema.ModuleCallEntry', class {
  19010. constructor(obj) {
  19011. Object.assign(this, { ...obj });
  19012. this.signature = this.signature ? new torch._export.serde.schema.ModuleCallSignature(this.signature) : null;
  19013. }
  19014. });
  19015. this.registerType('torch._export.serde.schema.GraphModule', class {
  19016. constructor(obj) {
  19017. this.graph = new torch._export.serde.schema.Graph(obj.graph);
  19018. this.signature = new torch._export.serde.schema.GraphSignature(obj.signature);
  19019. this.module_call_graph = obj.module_call_graph.map((item) => new torch._export.serde.schema.ModuleCallEntry(item));
  19020. this.metadata = new Map(Object.entries(obj.metadata || {}));
  19021. }
  19022. });
  19023. this.registerType('torch._export.serde.schema.ExportedProgram', class {
  19024. constructor(obj) {
  19025. Object.assign(this, { ...obj });
  19026. this.graph_module = new torch._export.serde.schema.GraphModule(obj.graph_module);
  19027. }
  19028. });
  19029. this.registerType('torch._export.serde.schema.SymExprHint', class extends torch._export.serde.union._Union {});
  19030. this.registerType('torch._export.serde.schema.SymExpr', class {
  19031. constructor(obj) {
  19032. this.expr_str = obj.expr_str;
  19033. this.hint = obj.hint ? new torch._export.serde.schema.SymExprHint(obj.hint) : null;
  19034. }
  19035. });
  19036. this.registerType('torch._export.serde.schema.SymInt', class extends torch._export.serde.union._Union {
  19037. constructor(obj) {
  19038. super(obj);
  19039. if (this.type === 'as_int') {
  19040. // continue
  19041. } else if (this.type === 'as_expr') {
  19042. this.as_expr = new torch._export.serde.schema.SymExpr(this.as_expr);
  19043. } else {
  19044. throw new python.Error(`Unsupported symbolic int '${this.type}'.`);
  19045. }
  19046. }
  19047. });
  19048. this.registerType('torch._export.serde.schema.SymBool', class extends torch._export.serde.union._Union {
  19049. constructor(obj) {
  19050. super(obj);
  19051. if (this.type === 'as_bool') {
  19052. // continue
  19053. } else if (this.type === 'as_expr') {
  19054. this.as_expr = new torch._export.serde.schema.SymExpr(this.as_expr);
  19055. } else {
  19056. throw new python.Error(`Unsupported symbolic bool '${this.type}'.`);
  19057. }
  19058. }
  19059. });
  19060. this.registerType('torch._export.serde.schema.SymIntArgument', class extends torch._export.serde.union._Union {
  19061. constructor(obj) {
  19062. super(obj);
  19063. Object.assign(this, { ...obj });
  19064. }
  19065. });
  19066. this.registerType('torch._export.serde.schema.SymFloatArgument', class extends torch._export.serde.union._Union {
  19067. constructor(obj) {
  19068. super(obj);
  19069. Object.assign(this, { ...obj });
  19070. }
  19071. });
  19072. this.registerType('torch._export.serde.schema.SymBoolArgument', class extends torch._export.serde.union._Union {
  19073. constructor(obj) {
  19074. super(obj);
  19075. Object.assign(this, { ...obj });
  19076. }
  19077. });
  19078. this.registerType('torch._export.serde.schema.CustomObjArgument', class {
  19079. constructor(obj) {
  19080. Object.assign(this, { ...obj });
  19081. }
  19082. });
  19083. this.registerType('torch._export.serde.schema.GraphSignature', class {
  19084. constructor(obj) {
  19085. this.input_specs = [];
  19086. if (Array.isArray(obj.input_specs)) {
  19087. this.input_specs = obj.input_specs.map((input_spec) => new torch._export.serde.schema.InputSpec(input_spec));
  19088. }
  19089. if (Array.isArray(obj.user_inputs)) {
  19090. for (const user_input of obj.user_inputs) {
  19091. this.input_specs.push(new torch._export.serde.schema.InputSpec({ user_input: { arg: { as_string: user_input } } }));
  19092. }
  19093. }
  19094. if (obj.inputs_to_parameters) {
  19095. for (const [input, parameter_name] of Object.entries(obj.inputs_to_parameters)) {
  19096. this.input_specs.push(new torch._export.serde.schema.InputSpec({ parameter: { arg: { name: input }, parameter_name } }));
  19097. }
  19098. }
  19099. this.output_specs = [];
  19100. if (Array.isArray(obj.output_specs)) {
  19101. this.output_specs = obj.output_specs.map((output_spec) => new torch._export.serde.schema.OutputSpec(output_spec));
  19102. }
  19103. }
  19104. });
  19105. this.registerType('torch._export.serde.schema.UserInputSpec', class {
  19106. constructor(obj) {
  19107. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  19108. }
  19109. });
  19110. this.registerType('torch._export.serde.schema.InputToParameterSpec', class {
  19111. constructor(obj) {
  19112. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  19113. this.parameter_name = obj.parameter_name;
  19114. }
  19115. });
  19116. this.registerType('torch._export.serde.schema.InputToBufferSpec', class {
  19117. constructor(obj) {
  19118. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  19119. this.buffer_name = obj.buffer_name;
  19120. }
  19121. });
  19122. this.registerType('torch._export.serde.schema.InputToTensorConstantSpec', class {
  19123. constructor(obj) {
  19124. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  19125. this.tensor_constant_name = obj.tensor_constant_name;
  19126. }
  19127. });
  19128. this.registerType('torch._export.serde.schema.InputToConstantInputSpec', class {
  19129. constructor(obj) {
  19130. this.name = obj.name;
  19131. this.value = new torch._export.serde.schema.ConstantValue(obj.value);
  19132. }
  19133. });
  19134. this.registerType('torch._export.serde.schema.ConstantValue', class extends torch._export.serde.union._Union {
  19135. constructor(obj) {
  19136. super(obj);
  19137. if (this.type === 'as_int' || this.type === 'as_float' || this.type === 'as_bool' || this.type === 'as_string' || this.type === 'as_strings') {
  19138. // continue
  19139. } else if (this.type === 'as_none') {
  19140. this.as_none = null;
  19141. } else {
  19142. throw new python.Error(`Unsupported constant value type '${this.type}'.`);
  19143. }
  19144. }
  19145. });
  19146. this.registerType('torch._export.serde.schema.InputSpec', class extends torch._export.serde.union._Union {
  19147. constructor(obj) {
  19148. super(obj);
  19149. if (this.type === 'user_input') {
  19150. this.user_input = new torch._export.serde.schema.UserInputSpec(this.user_input);
  19151. } else if (this.type === 'parameter') {
  19152. this.parameter = new torch._export.serde.schema.InputToParameterSpec(this.parameter);
  19153. } else if (this.type === 'buffer') {
  19154. this.buffer = new torch._export.serde.schema.InputToBufferSpec(this.buffer);
  19155. } else if (this.type === 'tensor_constant') {
  19156. this.tensor_constant = new torch._export.serde.schema.InputToTensorConstantSpec(this.tensor_constant);
  19157. } else if (this.type === 'constant_input') {
  19158. this.constant_input = new torch._export.serde.schema.InputToConstantInputSpec(this.constant_input);
  19159. } else {
  19160. throw new python.Error(`Unsupported input spec type '${this.type}'.`);
  19161. }
  19162. /*
  19163. custom_obj: InputToCustomObjSpec
  19164. token: InputTokenSpec
  19165. */
  19166. }
  19167. });
  19168. this.registerType('torch._export.serde.schema.UserOutputSpec', class {
  19169. constructor(obj) {
  19170. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  19171. }
  19172. });
  19173. this.registerType('torch._export.serde.schema.BufferMutationSpec', class {
  19174. constructor(obj) {
  19175. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  19176. this.buffer_name = obj.buffer_name;
  19177. }
  19178. });
  19179. this.registerType('torch._export.serde.schema.GradientToParameterSpec', class {
  19180. constructor(obj) {
  19181. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  19182. this.parameter_name = obj.parameter_name;
  19183. }
  19184. });
  19185. this.registerType('torch._export.serde.schema.GradientToUserInputSpec', class {
  19186. constructor(obj) {
  19187. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  19188. this.user_input_name = obj.user_input_name;
  19189. }
  19190. });
  19191. this.registerType('torch._export.serde.schema.UserInputMutationSpec', class {
  19192. constructor(obj) {
  19193. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  19194. this.user_input_name = obj.user_input_name;
  19195. }
  19196. });
  19197. this.registerType('torch._export.serde.schema.OutputTokenSpec', class {
  19198. constructor(obj) {
  19199. this.arg = new torch._export.serde.schema.TokenArgument(obj.arg);
  19200. }
  19201. });
  19202. this.registerType('torch._export.serde.schema.OutputSpec', class extends torch._export.serde.union._Union {
  19203. constructor(obj) {
  19204. super(obj);
  19205. if (this.type === 'user_output') {
  19206. this.user_output = new torch._export.serde.schema.UserOutputSpec(this.user_output);
  19207. } else if (this.type === 'loss_output') {
  19208. this.loss_output = new torch._export.serde.schema.LossOutputSpec(this.loss_output);
  19209. } else if (this.type === 'buffer_mutation') {
  19210. this.buffer_mutation = new torch._export.serde.schema.BufferMutationSpec(this.buffer_mutation);
  19211. } else if (this.type === 'gradient_to_parameter') {
  19212. this.gradient_to_parameter = new torch._export.serde.schema.GradientToParameterSpec(this.gradient_to_parameter);
  19213. } else if (this.type === 'gradient_to_user_input') {
  19214. this.gradient_to_user_input = new torch._export.serde.schema.GradientToUserInputSpec(this.gradient_to_user_input);
  19215. } else if (this.type === 'user_input_mutation') {
  19216. this.user_input_mutation = new torch._export.serde.schema.UserInputMutationSpec(this.user_input_mutation);
  19217. } else if (this.type === 'token') {
  19218. this.token = new torch._export.serde.schema.OutputTokenSpec(this.token);
  19219. }
  19220. }
  19221. });
  19222. this.registerType('torch._export.serde.schema.TensorArgument', class {
  19223. constructor(obj) {
  19224. this.name = obj.name;
  19225. }
  19226. });
  19227. this.registerType('torch._export.serde.schema.TokenArgument', class {
  19228. constructor(obj) {
  19229. this.name = obj.name;
  19230. }
  19231. });
  19232. this.registerType('torch._export.serde.schema.GraphArgument', class {
  19233. constructor(obj) {
  19234. this.name = obj.name;
  19235. this.graph = new torch._export.serde.schema.Graph(obj.graph);
  19236. }
  19237. });
  19238. this.registerType('torch._export.serde.schema.OptionalTensorArgument', class extends torch._export.serde.union._Union {
  19239. constructor(obj) {
  19240. super(obj);
  19241. if (this.type === 'as_tensor') {
  19242. this.as_tensor = new torch._export.serde.schema.TensorArgument({ name: this.as_tensor });
  19243. } else if (this.type === 'as_none') {
  19244. this.as_none = null;
  19245. } else {
  19246. throw new python.Error(`Unsupported optional tensor argument '${this.type}'.`);
  19247. }
  19248. }
  19249. });
  19250. this.registerFunction('torch.export.pt2_archive._package._load_state_dict', (f, model_name) => {
  19251. const legacy_file = `data/weights/${model_name}.pt`;
  19252. if (f.has(legacy_file)) {
  19253. return f.get(legacy_file);
  19254. }
  19255. const weights_config_file = `data/weights/${model_name}_weights_config.json`;
  19256. if (!f.has(weights_config_file)) {
  19257. return null;
  19258. }
  19259. const weights_config = f.get(weights_config_file);
  19260. const state_dict_file_map = torch.export.pt2_archive._package._build_file_map(f, weights_config, 'data/weights/');
  19261. const state_dict = new builtins.dict();
  19262. for (const [weight_fqn, payload_meta] of Object.entries(weights_config.config)) {
  19263. if (payload_meta.use_pickle) {
  19264. const weight_bytes = f.get(`data/weights/${payload_meta.path_name}`);
  19265. const weight_tensor = torch.load(weight_bytes);
  19266. state_dict.set(weight_fqn, weight_tensor);
  19267. } else {
  19268. const tensor_meta = payload_meta.tensor_meta;
  19269. const tensor = state_dict_file_map.get(payload_meta.path_name);
  19270. const sizes = tensor_meta.sizes.map((s) => s.as_int);
  19271. const strides = tensor_meta.strides.map((s) => s.as_int);
  19272. const storage_offset = tensor_meta.storage_offset.as_int;
  19273. const weight_tensor = new torch.Tensor();
  19274. weight_tensor.__setstate__([tensor.storage(), storage_offset, sizes, strides]);
  19275. weight_tensor.requires_grad = tensor_meta.requires_grad || false;
  19276. if (payload_meta.is_param) {
  19277. state_dict.set(weight_fqn, new torch.nn.parameter.Parameter(weight_tensor, tensor_meta.requires_grad));
  19278. } else {
  19279. state_dict.set(weight_fqn, weight_tensor);
  19280. }
  19281. }
  19282. }
  19283. return state_dict;
  19284. });
  19285. this.registerFunction('torch.export.pt2_archive._package._load_constants', (f, model_name) => {
  19286. const legacy_file = `data/constants/${model_name}.pt`;
  19287. if (f.has(legacy_file)) {
  19288. const entries = f.get(legacy_file);
  19289. return new builtins.dict(entries);
  19290. }
  19291. const constants_config_file = `data/constants/${model_name}_constants_config.json`;
  19292. if (!f.has(constants_config_file)) {
  19293. return null;
  19294. }
  19295. const constants_config = f.get(constants_config_file);
  19296. const constant_file_map = torch.export.pt2_archive._package._build_file_map(f, constants_config, 'data/constants/');
  19297. const constants = new builtins.dict();
  19298. for (const [constant_fqn, payload_meta] of Object.entries(constants_config.config)) {
  19299. const path_name = payload_meta.path_name;
  19300. if (path_name.startsWith('tensor_')) {
  19301. if (payload_meta.use_pickle) {
  19302. const constant_bytes = f.get(`data/constants/${payload_meta.path_name}`);
  19303. const constant_tensor = torch.load(constant_bytes);
  19304. constants.set(constant_fqn, constant_tensor);
  19305. } else {
  19306. const tensor_meta = payload_meta.tensor_meta;
  19307. const tensor = constant_file_map.get(payload_meta.path_name);
  19308. const sizes = tensor_meta.sizes.map((s) => s.as_int);
  19309. const strides = tensor_meta.strides.map((s) => s.as_int);
  19310. const storage_offset = tensor_meta.storage_offset.as_int;
  19311. const constant_tensor = new torch.Tensor();
  19312. constant_tensor.__setstate__([tensor.storage(), storage_offset, sizes, strides]);
  19313. constants.set(constant_fqn, constant_tensor);
  19314. }
  19315. } else if (payload_meta.path_name.startsWith('custom_obj_')) {
  19316. const custom_obj_bytes = f.get(`data/constants/${payload_meta.path_name}`);
  19317. const custom_obj = torch._C._pickle_load_obj(custom_obj_bytes);
  19318. constants.set(constant_fqn, custom_obj);
  19319. }
  19320. }
  19321. return constants;
  19322. });
  19323. this.registerFunction('torch._export.serde.serialize.deserialize_scalar_type', (st) => {
  19324. if (!torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE.has(st)) {
  19325. throw new python.Error(`Unsupported scalar type '${st}'.`);
  19326. }
  19327. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE.get(st);
  19328. });
  19329. this.registerFunction('torch.export.pt2_archive._package._build_file_map', (archive_reader, config, base_dir) => {
  19330. const file_map = new builtins.dict();
  19331. for (const payload_meta of Object.values(config.config)) {
  19332. if (payload_meta.use_pickle) {
  19333. continue;
  19334. }
  19335. if (file_map.has(payload_meta.path_name)) {
  19336. continue;
  19337. }
  19338. const tensor_bytes = archive_reader.get(`${base_dir}${payload_meta.path_name}`);
  19339. const tensor = torch.export.pt2_archive._package._create_flat_tensor_from_bytes(tensor_bytes, payload_meta.tensor_meta);
  19340. file_map.set(payload_meta.path_name, tensor);
  19341. }
  19342. return file_map;
  19343. });
  19344. this.registerFunction('torch.export.pt2_archive._package._create_flat_tensor_from_bytes', (tensor_bytes, tensor_meta) => {
  19345. const dtype = torch._export.serde.serialize.deserialize_scalar_type(tensor_meta.dtype);
  19346. const itemsize = dtype.itemsize();
  19347. const num_elements = tensor_bytes.length / itemsize;
  19348. const storage = new torch.storage.TypedStorage(num_elements, dtype);
  19349. storage._set_cdata(tensor_bytes);
  19350. const tensor = new torch.Tensor();
  19351. tensor.__setstate__([storage, 0, [num_elements], [1]]);
  19352. tensor.requires_grad = tensor_meta.requires_grad || false;
  19353. return tensor;
  19354. });
  19355. this.registerFunction('torch.export.pt2_archive._package.load_pt2', (f, expected_opset_version) => {
  19356. const exported_programs = new Map();
  19357. for (const name of f.keys()) {
  19358. const match = name.match(/^models\/([^/]+)\.json$/);
  19359. if (match) {
  19360. const [, model_name] = match;
  19361. const serialized_exported_program = f.get(`models/${model_name}.json`);
  19362. const serialized_state_dict = torch.export.pt2_archive._package._load_state_dict(f, model_name);
  19363. const serialized_constants = torch.export.pt2_archive._package._load_constants(f, model_name);
  19364. const serialized_example_inputs = f.get(`data/sample_inputs/${model_name}.pt`, 'zip');
  19365. const artifact = new torch._export.serde.serialize.SerializedArtifact(serialized_exported_program, serialized_state_dict, serialized_constants, serialized_example_inputs);
  19366. const exported_program = torch._export.serde.serialize.deserialize(artifact, expected_opset_version);
  19367. exported_programs.set(model_name, exported_program);
  19368. }
  19369. }
  19370. return { exported_programs };
  19371. });
  19372. this.registerFunction('torch._export.serde.serialize._dict_to_dataclass', (cls, data) => {
  19373. if (data === null) {
  19374. return data;
  19375. }
  19376. if (cls) {
  19377. return new cls(data);
  19378. }
  19379. throw new python.Error(`Unsupported data class '${cls.__name__}'.`);
  19380. });
  19381. this.registerFunction('torch._export.serde.serialize.deserialize', (artifact, expected_opset_version) => {
  19382. const serialized_exported_program = torch._export.serde.serialize._dict_to_dataclass(torch._export.serde.schema.ExportedProgram, artifact.exported_program);
  19383. return new torch._export.serde.serialize.ExportedProgramDeserializer(expected_opset_version).deserialize(serialized_exported_program, artifact.state_dict, artifact.constants, artifact.example_inputs);
  19384. });
  19385. this.registerType('torch._export.serde.serialize.ExportedProgramDeserializer', class {
  19386. constructor(expected_opset_version) {
  19387. this.expected_opset_version = expected_opset_version;
  19388. }
  19389. deserialize(exported_program, state_dict, constants, example_inputs) {
  19390. const symbol_name_to_range = new Map(Object.entries(exported_program.range_constraints));
  19391. /*
  19392. symbol_name_to_range = {
  19393. k: symbolic_shapes.ValueRanges(_int_to_sympy_int(v.min_val), _int_to_sympy_int(v.max_val))
  19394. for k, v in exported_program.range_constraints.items()
  19395. }
  19396. */
  19397. const deserializer = new torch._export.serde.serialize.GraphModuleDeserializer();
  19398. const res = deserializer.deserialize(
  19399. exported_program.graph_module,
  19400. state_dict,
  19401. constants,
  19402. example_inputs,
  19403. symbol_name_to_range);
  19404. const range_constraints = null;
  19405. /*
  19406. range_constraints = self.deserialize_range_constraints(
  19407. symbol_name_to_range, res.names_to_symbols,
  19408. )
  19409. model_opset_version: Optional[Dict[str, int]] = serialized_artifact.exported_program.opset_version
  19410. self._validate_model_opset_version(model_opset_version)
  19411. upgrader = GraphModuleOpUpgrader(self.expected_opset_version, model_opset_version)
  19412. */
  19413. return new torch.export.exported_program.ExportedProgram(
  19414. res.graph_module, res.graph_module.graph, res.signature,
  19415. res.state_dict, range_constraints, res.module_call_graph, res.example_inputs,
  19416. null, // verifier=load_verifier(serialized_artifact.exported_program.dialect),
  19417. res.constants);
  19418. // return upgrader.upgrade(exported_program)
  19419. }
  19420. });
  19421. this.registerFunction('torch._export.serde.serialize.deserialize_torch_artifact', (serialized) => {
  19422. if (serialized instanceof builtins.dict || serialized instanceof builtins.tuple) {
  19423. return serialized;
  19424. }
  19425. if (serialized === null || serialized.length === 0) {
  19426. return new builtins.dict();
  19427. }
  19428. const artifact = torch.load(serialized);
  19429. return artifact;
  19430. });
  19431. this.registerType('torch._export.serde.serialize.GraphModuleDeserializer', class {
  19432. constructor() {
  19433. this.serialized_name_to_node = new builtins.dict();
  19434. this.serialized_name_to_meta = new builtins.dict(); // torch._export.serde.serialize.LazyMap
  19435. this.graph = new torch.fx.Graph();
  19436. this.module = new torch.nn.Module();
  19437. }
  19438. save_graph_module() {
  19439. const Context = class {
  19440. constructor(self) {
  19441. this.self = self;
  19442. }
  19443. __enter__() {
  19444. this.saved = [
  19445. this.self.graph,
  19446. this.self.module,
  19447. this.self.serialized_name_to_node,
  19448. this.self.serialized_name_to_meta,
  19449. this.self.unbacked_symbols,
  19450. ];
  19451. this.self.graph = new torch.fx.graph.Graph();
  19452. this.self.module = new torch.nn.modules.module.Module();
  19453. this.self.serialized_name_to_node = new builtins.dict();
  19454. this.self.serialized_name_to_meta = new builtins.dict(); // torch._export.serde.serialize.LazyMap
  19455. this.self.unbacked_symbols = new Set();
  19456. }
  19457. __exit__(/* exc_type, exc_value, traceback */) {
  19458. const self = this.self;
  19459. [self.graph, self.module, self.serialized_name_to_node, self.serialized_name_to_meta, self.unbacked_symbols] = this.saved;
  19460. }
  19461. };
  19462. return new Context(this);
  19463. }
  19464. deserialize_graph_output(output) {
  19465. if (output.type === 'as_tensor') {
  19466. return this.serialized_name_to_node.get(output.as_tensor.name);
  19467. } else if (output.type === 'as_sym_int') {
  19468. return this.serialized_name_to_node.get(output.as_sym_int.as_name);
  19469. } else if (output.type === 'as_sym_bool') {
  19470. return this.serialized_name_to_node.get(output.as_sym_bool.as_name);
  19471. } else if (output.type === 'as_int') {
  19472. return this.serialized_name_to_node.get(output.as_int.as_name);
  19473. } else if (output.type === 'as_none') {
  19474. return this.serialized_name_to_node.get(output.as_sym_bool.as_name);
  19475. }
  19476. throw new python.Error(`Unsupported graph node ${output.type}.`);
  19477. }
  19478. deserialize_graph(serialized_graph) {
  19479. for (const [name, tensor_value] of serialized_graph.tensor_values) {
  19480. const meta_val = this.deserialize_tensor_meta(tensor_value.meta || tensor_value, this.fake_tensor_mode);
  19481. this.serialized_name_to_meta.set(name, meta_val);
  19482. }
  19483. for (const [name, sym_int_value] of serialized_graph.sym_int_values) {
  19484. this.serialized_name_to_meta.set(name, this.deserialize_sym_int(sym_int_value));
  19485. }
  19486. for (const [name, sym_bool_value] of serialized_graph.sym_bool_values) {
  19487. this.serialized_name_to_meta.set(name, this.deserialize_sym_bool(sym_bool_value));
  19488. }
  19489. for (const [name, script_obj_meta] of serialized_graph.custom_obj_values) {
  19490. this.serialized_name_to_meta.set(name, this.deserialize_script_obj_meta(script_obj_meta));
  19491. }
  19492. for (let i = 0; i < serialized_graph.inputs.length; i++) {
  19493. const input = serialized_graph.inputs[i];
  19494. if (input.type === 'as_tensor' || input.type === 'as_sym_int' || input.type === 'as_custom_obj') {
  19495. const node_name = input.value.name;
  19496. const placeholder_node = this.graph.placeholder(node_name);
  19497. placeholder_node.name = node_name;
  19498. this.sync_fx_node(node_name, placeholder_node);
  19499. } else if (input.type === 'as_int' || input.type === 'as_float' || input.type === 'as_bool' || input.type === 'as_none' || input.type === 'as_string') {
  19500. const node_name = this.signature.input_specs[i].arg.name;
  19501. const placeholder_node = this.graph.placeholder(node_name);
  19502. placeholder_node.meta.set('val', this.deserialize_input(input));
  19503. } else {
  19504. throw new python.Error(`Invalid input ${input.type}.`);
  19505. }
  19506. }
  19507. for (const serialized_node of serialized_graph.nodes) {
  19508. const target = this.deserialize_operator(serialized_node.target);
  19509. this.deserialize_node(serialized_node, target);
  19510. }
  19511. let outputs = [];
  19512. for (const output of serialized_graph.outputs) {
  19513. outputs.push(this.deserialize_graph_output(output));
  19514. }
  19515. if (serialized_graph.is_single_tensor_return) {
  19516. [outputs] = outputs;
  19517. } else {
  19518. outputs = new builtins.tuple(outputs);
  19519. }
  19520. const output_node = this.graph.output(outputs);
  19521. if (serialized_graph.is_single_tensor_return) {
  19522. output_node.meta.set('val', output_node.args[0].meta.get('val'));
  19523. } else {
  19524. /* output_node.meta['val'] = tuple(
  19525. arg.meta['val'] if isinstance(arg, torch.fx.Node) else arg
  19526. for arg in output_node.args[0]
  19527. ) */
  19528. }
  19529. return self.graph;
  19530. }
  19531. deserialize_operator(serialized_target) {
  19532. let module = null;
  19533. let serialized_target_names = null;
  19534. if (serialized_target.startsWith('_operator')) {
  19535. module = operator;
  19536. serialized_target_names = serialized_target.split('.').slice(1);
  19537. } else if (serialized_target.startsWith('torch')) {
  19538. module = torch;
  19539. serialized_target_names = serialized_target.split('.').slice(1);
  19540. } else if (serialized_target.startsWith('#')) {
  19541. return self.deserialize_extension_operator(serialized_target);
  19542. } else {
  19543. return serialized_target;
  19544. }
  19545. let target = module;
  19546. for (const name of serialized_target_names) {
  19547. target = builtins.getattr(target, name);
  19548. if (!target) {
  19549. return serialized_target;
  19550. }
  19551. }
  19552. return target;
  19553. }
  19554. deserialize_node(serialized_node, target) {
  19555. let fx_node = null;
  19556. if (torch._export.serde.serialize._SYM_OPS.has(target)) {
  19557. const name = serialized_node.outputs[0].value.as_name;
  19558. const args = this.deserialize_sym_op_inputs(serialized_node.inputs);
  19559. fx_node = this.graph.create_node('call_function', target, args, null, name);
  19560. this.deserialize_sym_op_outputs(serialized_node, fx_node);
  19561. } else if (builtins.isinstance(target, torch._ops.HigherOrderOperator)) {
  19562. const [args, kwargs] = this.deserialize_hoo_inputs(serialized_node.inputs);
  19563. const metadata = this.deserialize_metadata(serialized_node.metadata);
  19564. for (const x of [...args, ...kwargs.values()]) {
  19565. if (builtins.isinstance(x, torch.fx.Node) && x.op === 'get_attr') {
  19566. x.meta.update(metadata);
  19567. }
  19568. }
  19569. const name = serialized_node.outputs.length === 1 &&
  19570. builtins.hasattr(serialized_node.outputs[0], 'as_tensor') &&
  19571. builtins.getattr(serialized_node, 'is_hop_single_tensor_return', true) ?
  19572. serialized_node.outputs[0].as_tensor.name : null;
  19573. fx_node = this.graph.create_node('call_function', target, args, kwargs, name);
  19574. this.deserialize_outputs(serialized_node, fx_node);
  19575. fx_node.meta.update(metadata);
  19576. } else if (builtins.isinstance(target, torch._ops.OpOverload)) {
  19577. const name = this._is_single_tensor_return(target) ? serialized_node.outputs[0].as_tensor.name : null;
  19578. const [args, kwargs] = this.deserialize_inputs(target, serialized_node);
  19579. fx_node = this.graph.create_node('call_function', target, args, kwargs, name);
  19580. this.deserialize_outputs(serialized_node, fx_node);
  19581. } else if (typeof target === 'string') {
  19582. // Handle unresolved operators
  19583. execution.emit('resolve', target);
  19584. if (target.match(/^torch\.ops\.(aten|prim|quantized)\./)) {
  19585. throw new python.Error(`Unsupported node target type '${target}'.`);
  19586. }
  19587. const [args, kwargs] = this.deserialize_hoo_inputs(serialized_node.inputs);
  19588. const name = serialized_node.outputs.length === 1 && builtins.hasattr(serialized_node.outputs[0], 'as_tensor') ? serialized_node.outputs[0].as_tensor.name : null;
  19589. fx_node = this.graph.create_node('call_function', target, args, kwargs, name);
  19590. this.deserialize_outputs(serialized_node, fx_node);
  19591. } else {
  19592. throw new python.Error(`Unsupported node target type '${target}'.`);
  19593. }
  19594. fx_node.meta.update(this.deserialize_metadata(serialized_node.metadata));
  19595. if (fx_node.op !== 'placeholder' && fx_node.op !== 'output' && !fx_node.meta.has('nn_module_stack')) {
  19596. fx_node.meta.set('nn_module_stack', new builtins.dict());
  19597. }
  19598. }
  19599. deserialize_input_spec(i) {
  19600. if (i.type === 'user_input') {
  19601. return new torch.export.graph_signature.InputSpec(
  19602. torch.export.graph_signature.InputKind.USER_INPUT,
  19603. this.deserialize_argument_spec(i.user_input.arg),
  19604. null);
  19605. } else if (i.type === 'parameter') {
  19606. return new torch.export.graph_signature.InputSpec(
  19607. torch.export.graph_signature.InputKind.PARAMETER,
  19608. new torch.export.graph_signature.TensorArgument(i.parameter.arg.name),
  19609. i.parameter.parameter_name,
  19610. );
  19611. } else if (i.type === 'buffer') {
  19612. return new torch.export.graph_signature.InputSpec(
  19613. torch.export.graph_signature.InputKind.BUFFER,
  19614. new torch.export.graph_signature.TensorArgument(i.buffer.arg.name),
  19615. i.buffer.buffer_name,
  19616. i.buffer.persistent,
  19617. );
  19618. } else if (i.type === 'tensor_constant') {
  19619. return new torch.export.graph_signature.InputSpec(
  19620. torch.export.graph_signature.InputKind.CONSTANT_TENSOR,
  19621. new torch.export.graph_signature.TensorArgument(i.tensor_constant.arg.name),
  19622. i.tensor_constant.tensor_constant_name);
  19623. } else if (i.type === 'custom_obj') {
  19624. return new torch.export.graph_signature.InputSpec(
  19625. torch.export.graph_signature.InputKind.CUSTOM_OBJ,
  19626. new torch.export.graph_signature.CustomObjArgument(i.custom_obj.arg.name, i.custom_obj.arg.class_fqn),
  19627. i.custom_obj.custom_obj_name);
  19628. } else if (i.type === 'token') {
  19629. return new torch.export.graph_signature.InputSpec(
  19630. torch.export.graph_signature.InputKind.TOKEN,
  19631. new torch.export.graph_signature.TokenArgument(i.token.arg.name),
  19632. null);
  19633. } else if (i.type === 'constant_input') {
  19634. return new torch.export.graph_signature.InputSpec(
  19635. torch.export.graph_signature.InputKind.USER_INPUT,
  19636. new torch.export.graph_signature.ConstantArgument(i.constant_input.name, this.deserialize_constant_input(i.constant_input.value)),
  19637. null);
  19638. }
  19639. throw new python.Error(`Unknown input spec ${i}`);
  19640. }
  19641. deserialize_constant_input(inp) {
  19642. if (inp.type === 'as_int') {
  19643. return inp.as_int;
  19644. } else if (inp.type === 'as_float') {
  19645. return inp.as_float;
  19646. } else if (inp.type === 'as_string') {
  19647. return inp.as_string;
  19648. } else if (inp.type === 'as_bool') {
  19649. return inp.as_bool;
  19650. } else if (inp.type === 'as_none') {
  19651. return null;
  19652. }
  19653. throw new python.Error(`Unhandled constant argument ${inp} to deserialize.`);
  19654. }
  19655. deserialize_output_spec(o) {
  19656. if (o.type === 'user_output') {
  19657. return new torch.export.graph_signature.OutputSpec(
  19658. torch.export.graph_signature.OutputKind.USER_OUTPUT,
  19659. this.deserialize_argument_spec(o.user_output.arg),
  19660. null);
  19661. } else if (o.type === 'loss_output') {
  19662. return new torch.export.graph_signature.OutputSpec(
  19663. torch.export.graph_signature.OutputKind.LOSS_OUTPUT,
  19664. new torch.export.graph_signature.TensorArgument(o.loss_output.arg.name),
  19665. null);
  19666. } else if (o.type === 'buffer_mutation') {
  19667. return new torch.export.graph_signature.OutputSpec(
  19668. torch.export.graph_signature.OutputKind.BUFFER_MUTATION,
  19669. new torch.export.graph_signature.TensorArgument(o.buffer_mutation.arg.name),
  19670. o.buffer_mutation.buffer_name);
  19671. } else if (o.type === 'gradient_to_parameter') {
  19672. return new torch.export.graph_signature.OutputSpec(
  19673. torch.export.graph_signature.OutputKind.GRADIENT_TO_PARAMETER,
  19674. new torch.export.graph_signature.TensorArgument(o.gradient_to_parameter.arg.name),
  19675. o.gradient_to_parameter.parameter_name);
  19676. } else if (o.type === 'gradient_to_user_input') {
  19677. return new torch.export.graph_signature.OutputSpec(
  19678. torch.export.graph_signature.OutputKind.GRADIENT_TO_USER_INPUT,
  19679. new torch.export.graph_signature.TensorArgument(o.gradient_to_user_input.arg.name),
  19680. o.gradient_to_user_input.user_input_name);
  19681. } else if (o.type === 'user_input_mutation') {
  19682. return new torch.export.graph_signature.OutputSpec(
  19683. torch.export.graph_signature.OutputKind.USER_INPUT_MUTATION,
  19684. new torch.export.graph_signature.TensorArgument(o.user_input_mutation.arg.name),
  19685. o.user_input_mutation.user_input_name);
  19686. } else if (o.type === 'token') {
  19687. return new torch.export.graph_signature.OutputSpec(
  19688. torch.export.graph_signature.OutputKind.TOKEN,
  19689. new torch.export.graph_signature.TokenArgument(o.token.arg.name),
  19690. null);
  19691. }
  19692. throw new python.Error(`Unknown output spec ${o}.`);
  19693. }
  19694. deserialize_signature(sig) {
  19695. return new torch.export.graph_signature.ExportGraphSignature(
  19696. sig.input_specs.map((i) => this.deserialize_input_spec(i)),
  19697. sig.output_specs.map((o) => this.deserialize_output_spec(o)));
  19698. }
  19699. deserialize(serialized_graph_module, serialized_state_dict, constants, example_inputs, symbol_name_to_range) {
  19700. this.shape_env = new torch.fx.experimental.symbolic_shapes.ShapeEnv(/* assume_static_by_default = True */);
  19701. this.fake_tensor_mode = new torch._subclasses.fake_tensor.FakeTensorMode(false, true, this.shape_env);
  19702. this.sympy_functions = new Map([
  19703. ['FloorDiv', torch.utils._sympy.functions.FloorDiv],
  19704. ['ModularIndexing', torch.utils._sympy.functions.ModularIndexing],
  19705. ['Where', torch.utils._sympy.functions.Where],
  19706. ['PythonMod', torch.utils._sympy.functions.PythonMod],
  19707. ['Mod', torch.utils._sympy.functions.Mod],
  19708. ['CleanDiv', torch.utils._sympy.functions.CleanDiv],
  19709. ['CeilToInt', torch.utils._sympy.functions.CeilToInt],
  19710. ['FloorToInt', torch.utils._sympy.functions.FloorToInt],
  19711. ['CeilDiv', torch.utils._sympy.functions.CeilDiv],
  19712. ['LShift', torch.utils._sympy.functions.LShift],
  19713. ['RShift', torch.utils._sympy.functions.RShift],
  19714. ['PowByNatural', torch.utils._sympy.functions.PowByNatural],
  19715. ['FloatPow', torch.utils._sympy.functions.FloatPow],
  19716. ['FloatTrueDiv', torch.utils._sympy.functions.FloatTrueDiv],
  19717. ['IntTrueDiv', torch.utils._sympy.functions.IntTrueDiv],
  19718. ['IsNonOverlappingAndDenseIndicator', torch.utils._sympy.functions.IsNonOverlappingAndDenseIndicator],
  19719. ['TruncToFloat', torch.utils._sympy.functions.TruncToFloat],
  19720. ['TruncToInt', torch.utils._sympy.functions.TruncToInt],
  19721. ['RoundToInt', torch.utils._sympy.functions.RoundToInt],
  19722. ['RoundDecimal', torch.utils._sympy.functions.RoundDecimal],
  19723. ['ToFloat', torch.utils._sympy.functions.ToFloat],
  19724. ['Identity', torch.utils._sympy.functions.Identity],
  19725. ]);
  19726. this.symbol_name_to_symbol = new Map();
  19727. this.constants = torch._export.serde.serialize.deserialize_torch_artifact(constants);
  19728. this.signature = this.deserialize_signature(serialized_graph_module.signature);
  19729. this.symbol_name_to_range = symbol_name_to_range || new Map();
  19730. /*
  19731. if symbol_name_to_range:
  19732. for k, vr in symbol_name_to_range.items():
  19733. lower = int(vr.lower)
  19734. if vr.upper >= 2: # max is >= 2, not sym bool range
  19735. lower = max(2, lower)
  19736. this.symbol_name_to_range[k] = symbolic_shapes.ValueRanges(_int_to_sympy_int(lower), vr.upper)
  19737. */
  19738. this.example_inputs = null;
  19739. if (example_inputs) {
  19740. this.example_inputs = torch._export.serde.serialize.deserialize_torch_artifact(example_inputs);
  19741. }
  19742. this.deserialize_graph(serialized_graph_module.graph);
  19743. const module_call_graph = null; // this.deserialize_module_call_graph(serialized_graph_module.module_call_graph)
  19744. return {
  19745. graph_module: torch._export.exported_program._create_graph_module_for_export(this.module, this.graph),
  19746. signature: this.signature,
  19747. module_call_graph,
  19748. names_to_symbols: this.symbol_name_to_symbol,
  19749. state_dict: torch._export.serde.serialize.deserialize_torch_artifact(serialized_state_dict),
  19750. constants: this.constants,
  19751. example_inputs: this.example_inputs,
  19752. };
  19753. }
  19754. sync_fx_node(name, fx_node) {
  19755. if (this.serialized_name_to_node.has(name)) {
  19756. throw new python.Error(`Node ${name} has already been deserialized before.`);
  19757. }
  19758. this.serialized_name_to_node.set(name, fx_node);
  19759. fx_node.meta.set('val', this.serialized_name_to_meta.get(name));
  19760. }
  19761. deserialize_sym_op_inputs(inputs) {
  19762. return inputs.map((input) => this.deserialize_input(input.arg));
  19763. }
  19764. deserialize_inputs(target, serialized_node) {
  19765. const schema_args = this._get_schema_from_target(target).arguments;
  19766. const actual_args = new Map(serialized_node.inputs.map((input) => [input.name, this.deserialize_input(input.arg)]));
  19767. const args = new builtins.list();
  19768. const kwargs = new builtins.dict();
  19769. for (const schema_arg of schema_args) {
  19770. const is_positional = !schema_arg.has_default_value() && !schema_arg.kwarg_only;
  19771. if (is_positional) {
  19772. args.push(actual_args.get(schema_arg.name));
  19773. } else if (actual_args.has(schema_arg.name)) {
  19774. kwargs.set(schema_arg.name, actual_args.get(schema_arg.name));
  19775. }
  19776. }
  19777. return [args, kwargs];
  19778. }
  19779. deserialize_hoo_inputs(inputs) {
  19780. const args = [];
  19781. const kwargs = new builtins.dict();
  19782. for (const input_ of inputs) {
  19783. if (input_.name === '') {
  19784. args.push(this.deserialize_input(input_.arg));
  19785. } else {
  19786. kwargs.set(input_.name, this.deserialize_input(input_.arg));
  19787. }
  19788. }
  19789. return [new builtins.tuple(args), kwargs];
  19790. }
  19791. deserialize_input(inp) {
  19792. const value = inp.value;
  19793. const typ_ = inp.type;
  19794. if (typ_ === 'as_none') {
  19795. return null;
  19796. } else if (typ_ === 'as_tensor') {
  19797. return this.serialized_name_to_node.get(inp.as_tensor.name);
  19798. } else if (typ_ === 'as_scalar_type') {
  19799. return torch._export.serde.serialize.deserialize_scalar_type(inp.as_scalar_type);
  19800. } else if (typ_ === 'as_memory_format') {
  19801. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_MEMORY_FORMAT[inp.as_memory_format];
  19802. } else if (typ_ === 'as_layout') {
  19803. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_LAYOUT[inp.as_layout];
  19804. } else if (typ_ === 'as_graph') {
  19805. const context = this.save_graph_module();
  19806. context.__enter__();
  19807. this.deserialize_graph(value.graph);
  19808. const submodule = torch.export.exported_program._create_graph_module_for_export(this.module, this.graph);
  19809. context.__exit__(null, null, null);
  19810. this.module.register_module(value.name, submodule);
  19811. return this.graph.create_node('get_attr', value.name, null, null, value.name);
  19812. } else if (typ_ === 'as_device') {
  19813. return this.deserialize_device(inp.as_device);
  19814. } else if (typ_ === 'as_int') {
  19815. return inp.as_int;
  19816. } else if (typ_ === 'as_float') {
  19817. return inp.as_float;
  19818. } else if (typ_ === 'as_bool') {
  19819. return inp.as_bool;
  19820. } else if (typ_ === 'as_string') {
  19821. return inp.as_string;
  19822. } else if (typ_ === 'as_sym_int') {
  19823. return this.deserialize_sym_argument(inp.as_sym_int);
  19824. } else if (typ_ === 'as_sym_float') {
  19825. return this.deserialize_sym_argument(inp.as_sym_float);
  19826. } else if (typ_ === 'as_sym_bool') {
  19827. return this.deserialize_sym_argument(inp.as_sym_bool);
  19828. } else if (Array.isArray(value)) {
  19829. if (value.length === 0) {
  19830. return [];
  19831. } else if (typ_ === 'as_tensors') {
  19832. const result = [];
  19833. for (const arg of value) {
  19834. result.push(this.serialized_name_to_node.get(arg.name));
  19835. }
  19836. return result;
  19837. } else if (typ_ === 'as_ints' || typ_ === 'as_floats' || typ_ === 'as_bools' || typ_ === 'as_strings') {
  19838. return Array.from(value);
  19839. } else if (typ_ === 'as_sym_ints' || typ_ === 'as_sym_bools') {
  19840. return value.map((arg) => this.deserialize_sym_argument(arg));
  19841. } else if (typ_ === 'as_optional_tensors') {
  19842. const deserialize_optional_tensor_args = (a) => {
  19843. if (a.type === 'as_none') {
  19844. return null;
  19845. } else if (a.type === 'as_tensor') {
  19846. return this.serialized_name_to_node.get(a.value.name);
  19847. }
  19848. throw new python.Error(`Unsupported argument '${typ_}'.`);
  19849. };
  19850. return value.map((item) => deserialize_optional_tensor_args(item));
  19851. }
  19852. throw new python.Error(`Unsupported argument '${typ_}'.`);
  19853. } else if (typ_ === 'as_custom_obj') {
  19854. if (this.serialized_name_to_node.has(inp.as_custom_obj.name)) {
  19855. return this.serialized_name_to_node.get(inp.as_custom_obj.name);
  19856. }
  19857. return this.constants[inp.as_custom_obj.name];
  19858. } else if (typ_ === 'as_operator') {
  19859. return this.deserialize_operator(inp.as_operator);
  19860. }
  19861. throw new python.Error(`Unsupported argument '${typ_}'.`);
  19862. }
  19863. deserialize_sym_argument(sym_arg) {
  19864. if (sym_arg instanceof torch._export.serde.schema.SymIntArgument) {
  19865. if (sym_arg.type === 'as_int') {
  19866. return sym_arg.as_int;
  19867. } else if (sym_arg.type === 'as_name') {
  19868. return this.serialized_name_to_node.get(sym_arg.as_name);
  19869. }
  19870. } else if (sym_arg instanceof torch._export.serde.schema.SymFloatArgument) {
  19871. if (sym_arg.type === 'as_float') {
  19872. return sym_arg.as_float;
  19873. } else if (sym_arg.type === 'as_name') {
  19874. return this.serialized_name_to_node.get(sym_arg.as_name);
  19875. }
  19876. } else if (sym_arg instanceof torch._export.serde.schema.SymBoolArgument) {
  19877. if (sym_arg.type === 'as_bool') {
  19878. return sym_arg.as_bool;
  19879. } else if (sym_arg.type === 'as_name') {
  19880. return this.serialized_name_to_node.get(sym_arg.as_name);
  19881. }
  19882. }
  19883. throw new python.Error(`Unsupported symbolic argument type '${sym_arg.type}`);
  19884. }
  19885. deserialize_sym_op_outputs(serialized_node, fx_node) {
  19886. this.sync_fx_node(serialized_node.outputs[0].value.as_name, fx_node);
  19887. }
  19888. deserialize_outputs(serialized_node, fx_node) {
  19889. if (serialized_node.outputs.length === 0) {
  19890. return;
  19891. }
  19892. if (serialized_node.outputs.length === 1 &&
  19893. serialized_node.outputs[0].type === 'as_tensor') {
  19894. this.sync_fx_node(serialized_node.outputs[0].as_tensor.name, fx_node);
  19895. return;
  19896. } else if (serialized_node.outputs.length === 1 &&
  19897. (serialized_node.outputs[0].value instanceof torch._export.serde.schema.SymIntArgument ||
  19898. serialized_node.outputs[0].value instanceof torch._export.serde.schema.SymBoolArgument)) {
  19899. this.sync_fx_node(serialized_node.outputs[0].value.as_name, fx_node);
  19900. return;
  19901. }
  19902. this.deserialize_multiple_outputs(serialized_node, fx_node);
  19903. }
  19904. deserialize_multiple_outputs(serialized_node, fx_node) {
  19905. const deserialized_metadata = this.deserialize_metadata(serialized_node.metadata);
  19906. const generate_getitem = (meta_val, fx_node, arg, idx) => {
  19907. let name = '';
  19908. if (arg instanceof torch._export.serde.schema.TensorArgument) {
  19909. name = arg.name;
  19910. } else if (arg instanceof torch._export.serde.schema.SymIntArgument) {
  19911. name = arg.as_name;
  19912. } else {
  19913. throw new python.Error(`Unsupported argument type '${arg}'.`);
  19914. }
  19915. const individual_output = this.graph.create_node(
  19916. 'call_function',
  19917. operator.getitem,
  19918. new builtins.tuple([fx_node, idx]),
  19919. null,
  19920. name,
  19921. );
  19922. this.sync_fx_node(name, individual_output);
  19923. meta_val.push(this.serialized_name_to_meta.get(name));
  19924. individual_output.meta.update(deserialized_metadata);
  19925. };
  19926. const generate_getitems = (meta_val, fx_node, args) => {
  19927. for (let idx = 0; idx < args.length; idx++) {
  19928. let arg = args[idx];
  19929. if (arg instanceof torch._export.serde.schema.Argument) {
  19930. arg = arg.value;
  19931. }
  19932. if (arg instanceof torch._export.serde.schema.TensorArgument || arg instanceof torch._export.serde.schema.SymIntArgument) {
  19933. generate_getitem(meta_val, fx_node, arg, idx);
  19934. } else if (Array.isArray(arg)) { // arg instanceof (list, tuple))
  19935. const list_output = this.graph.create_node(
  19936. 'call_function',
  19937. operator.getitem,
  19938. (fx_node, idx),
  19939. );
  19940. meta_val.push([]);
  19941. generate_getitems(meta_val[meta_val.length - 1], list_output, arg);
  19942. list_output.meta.update(deserialized_metadata);
  19943. list_output.meta.set('val', meta_val[meta_val.length - 1]);
  19944. } else {
  19945. throw new python.Error(`Unsupported node output type: '${arg}'.`);
  19946. }
  19947. }
  19948. };
  19949. const meta_val = [];
  19950. if (serialized_node.outputs.length === 1) {
  19951. // assert isinstance(serialized_node.outputs[0].value, list)
  19952. // assert isinstance(serialized_node.outputs[0].value[0], TensorArgument)
  19953. generate_getitems(meta_val, fx_node, serialized_node.outputs[0].as_tensors);
  19954. } else {
  19955. generate_getitems(meta_val, fx_node, serialized_node.outputs);
  19956. }
  19957. fx_node.meta.set('val', new builtins.tuple(meta_val));
  19958. this.serialized_name_to_node.set(fx_node.name, fx_node);
  19959. }
  19960. deserialize_metadata(metadata) {
  19961. const ret = new builtins.dict();
  19962. const stack_trace = metadata.get('stack_trace');
  19963. if (stack_trace) {
  19964. ret.set('stack_trace', stack_trace);
  19965. }
  19966. const deserialize_meta_func = (serialized_target) => {
  19967. let module = null;
  19968. let serialized_target_names = [];
  19969. if (serialized_target.startsWith('torch.nn')) {
  19970. module = torch.nn;
  19971. serialized_target_names = serialized_target.split('.').slice(1);
  19972. } else if (serialized_target.startsWith('torch')) {
  19973. module = torch;
  19974. serialized_target_names = serialized_target.split('.').slice(1);
  19975. } else {
  19976. return this.deserialize_operator(serialized_target);
  19977. }
  19978. let target = module;
  19979. for (const name of serialized_target_names) {
  19980. if (!builtins.hasattr(target, name)) {
  19981. return serialized_target;
  19982. }
  19983. target = builtins.getattr(target, name);
  19984. }
  19985. return target;
  19986. };
  19987. const nn_module_stack_str = metadata.get('nn_module_stack');
  19988. if (nn_module_stack_str) {
  19989. const import_nn_module_stack = (key, path, ty) => {
  19990. return [key, [path, ty]];
  19991. };
  19992. const nn_module_stack = new Map(nn_module_stack_str.split(';').map((item) => import_nn_module_stack(...item.split(','))));
  19993. ret.set('nn_module_stack', nn_module_stack);
  19994. }
  19995. const source_fn_st_str = metadata.get('source_fn_stack');
  19996. if (source_fn_st_str) {
  19997. const source_fn_st = [];
  19998. for (const source_fn_str of source_fn_st_str.split(';')) {
  19999. const [name, target_str] = source_fn_str.split(',');
  20000. source_fn_st.push([name, deserialize_meta_func(target_str)]);
  20001. }
  20002. ret.set('source_fn_stack', source_fn_st);
  20003. }
  20004. const torch_fn = metadata.get('torch_fn');
  20005. if (torch_fn) {
  20006. ret.set('torch_fn', new builtins.tuple(torch_fn.split(';')));
  20007. }
  20008. const custom_str = metadata.get('custom');
  20009. if (custom_str) {
  20010. ret.set('custom', JSON.parse(custom_str));
  20011. }
  20012. return ret;
  20013. }
  20014. deserialize_argument_spec(x) {
  20015. if (x.type === 'as_tensor') {
  20016. return new torch.export.graph_signature.TensorArgument(x.as_tensor.name);
  20017. } else if (x.type === 'as_sym_int') {
  20018. return new torch.export.graph_signature.SymIntArgument(x.as_sym_int.as_name);
  20019. } else if (x.type === 'as_custom_obj') {
  20020. return new torch.export.graph_signature.ConstantArgument(x.as_custom_obj.name, this.deserialize_input(x));
  20021. }
  20022. return new torch.export.graph_signature.ConstantArgument('', this.deserialize_input(x));
  20023. }
  20024. deserialize_tensor_meta(tensor_meta) {
  20025. try {
  20026. this.fake_tensor_mode.__enter__();
  20027. const sizes = tensor_meta.sizes.map((val) => this.deserialize_sym_int(val));
  20028. const strides = tensor_meta.strides.map((val) => this.deserialize_sym_int(val));
  20029. const device = this.deserialize_device(tensor_meta.device);
  20030. const dtype = torch._export.serde.serialize.deserialize_scalar_type(tensor_meta.dtype);
  20031. return torch.empty_strided(sizes, strides, dtype, null, device);
  20032. } finally {
  20033. this.fake_tensor_mode.__exit__(null, null, null);
  20034. }
  20035. }
  20036. deserialize_script_obj_meta(script_obj_meta) {
  20037. return new torch.export.graph_signature.CustomObjArgument(script_obj_meta.name, script_obj_meta.class_fqn);
  20038. }
  20039. _parse_sym_expr(expr_str, hint) {
  20040. const _process_sym_expr = (sym, hint) => {
  20041. if (sym.is_Integer || sym.is_Float || sym.is_Boolean) {
  20042. return sym;
  20043. }
  20044. expr_str = sym.__str__();
  20045. for (const arg of sym.args) {
  20046. this._parse_sym_expr(arg);
  20047. }
  20048. if (this.symbol_name_to_symbol.has(expr_str)) {
  20049. sym = this.symbol_name_to_symbol.get(expr_str);
  20050. } else {
  20051. this.symbol_name_to_symbol.set(expr_str, sym);
  20052. 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])) {
  20053. this.unbacked_symbols.add(sym);
  20054. }
  20055. }
  20056. if (hint !== null && !this.shape_env.var_to_val.has(sym)) {
  20057. this.shape_env.add_var_to_val(sym, hint);
  20058. }
  20059. const vr = this.symbol_name_to_range.get(expr_str);
  20060. if (vr) {
  20061. this.shape_env.constrain_symbol_range(sym, vr.lower, vr.upper);
  20062. }
  20063. if (builtins.isinstance(sym, sympy.core.symbol.Symbol)) {
  20064. this.shape_env.var_to_stack.set(sym, torch.utils._traceback.CapturedTraceback.extract(false, false, 1));
  20065. }
  20066. return sym;
  20067. };
  20068. const locals = new Map([...this.sympy_functions, ...this.symbol_name_to_symbol]);
  20069. const expr = sympy.core.sympify.sympify(expr_str, locals);
  20070. return _process_sym_expr(expr, hint);
  20071. }
  20072. deserialize_sym_int(s) {
  20073. const val = s.value;
  20074. let hint = null;
  20075. if (s.type === 'as_expr') {
  20076. if (val.hint === null) {
  20077. hint = null;
  20078. } else {
  20079. // assert val.hint.type == "as_int"
  20080. hint = val.hint.value;
  20081. }
  20082. const sym = this._parse_sym_expr(val.expr_str, hint);
  20083. return this.shape_env.create_symintnode(sym, hint);
  20084. } else if (s.type === 'as_int') {
  20085. // assert type(val) is int
  20086. return val;
  20087. }
  20088. throw new python.Error(`SymInt has invalid field type ${s.type} with value ${s.value}.`);
  20089. }
  20090. deserialize_sym_bool(s) {
  20091. const val = s.value;
  20092. let hint = null;
  20093. if (s.type === 'as_expr') {
  20094. if (val.hint === null) {
  20095. hint = null;
  20096. } else {
  20097. // assert val.hint.type == "as_bool"
  20098. hint = val.hint.value;
  20099. }
  20100. const sym = this._parse_sym_expr(val.expr_str, hint);
  20101. return this.shape_env.create_symboolnode(sym, hint);
  20102. } else if (s.type === 'as_bool') {
  20103. // assert type(val) is bool
  20104. return val;
  20105. }
  20106. throw new python.Error(`SymBool has invalid field type ${s.type} with value ${s.value}.`);
  20107. }
  20108. deserialize_device(d) {
  20109. if (d.index === null) {
  20110. return new torch.device(d.type);
  20111. }
  20112. return new torch.device(d.type, d.index);
  20113. }
  20114. _get_schema_from_target(target) {
  20115. if (target instanceof torch._ops.OpOverload) {
  20116. return target._schema;
  20117. }
  20118. throw new python.Error(`Unsupported schema '${target.name}'.`);
  20119. }
  20120. _is_single_tensor_return(target) {
  20121. const schema = this._get_schema_from_target(target);
  20122. const returns = schema.returns;
  20123. return returns.length === 1 && returns[0].real_type instanceof torch.TensorType;
  20124. }
  20125. });
  20126. this.registerType('torch._export.verifier.Verifier', class {});
  20127. this.registerType('torch._dynamo.convert_frame.CatchErrorsWrapper', class {});
  20128. this.registerType('torch._dynamo.convert_frame.ConvertFrameAssert', class {});
  20129. this.registerType('torch._dynamo.convert_frame.ConvertFrame', class {});
  20130. this.registerType('torch._dynamo.convert_frame.ConvertFrameBox', class {});
  20131. this.registerType('torch._dynamo.eval_frame._TorchDynamoContext', class {});
  20132. this.registerType('torch._dynamo.eval_frame.OptimizedModule', class extends torch.nn.modules.module.Module {
  20133. constructor(mod, dynamo_ctx) {
  20134. builtins.object.__setattr__(self, '_orig_mod', mod);
  20135. // this._super_module_initialized = false;
  20136. super();
  20137. // this._super_module_initialized = true;
  20138. this._orig_mod = mod;
  20139. this.dynamo_ctx = dynamo_ctx;
  20140. // this._initialize();
  20141. this.training = this._orig_mod.training;
  20142. }
  20143. });
  20144. this.registerType('torch._dynamo.eval_frame.OptimizeContext', class extends torch._dynamo.eval_frame._TorchDynamoContext {});
  20145. this.registerType('torch._dynamo.hooks.Hooks', class {});
  20146. this.registerType('torch._dynamo.output_graph.GraphCompileReason', class {});
  20147. this.registerType('torch._dynamo.repro.after_dynamo.WrapBackendDebug', class {});
  20148. this.registerType('torch._TorchCompileInductorWrapper', class {});
  20149. this.registerFunction('torch._inductor.compile_fx.compile_fx');
  20150. this.registerFunction('torch_utils.persistence._reconstruct_persistent_obj', (meta) => {
  20151. const name = `_imported_module_${Math.floor(Math.random() * 10000)}`;
  20152. const module = new types.ModuleType(name);
  20153. execution.register('sys').modules.set(name, module);
  20154. const context = new python.Execution.Context(module, null);
  20155. execution.exec(meta.get('module_src'), context);
  20156. const obj = execution.invoke(`${name}.${meta.get('class_name')}`, []);
  20157. const state = meta.get('state');
  20158. if (state) {
  20159. if (obj.__setstate__) {
  20160. obj.__setstate__(state);
  20161. } else {
  20162. for (const [key, value] of state) {
  20163. obj[key] = value;
  20164. }
  20165. }
  20166. }
  20167. return obj;
  20168. });
  20169. this.registerFunction('torch_utils.misc.assert_shape', (/* tensor, ref_shape */) => {});
  20170. this.registerFunction('torch_utils.ops.conv2d_resample.conv2d_resample', (/* x, w, f, up, down, padding, groups, flip_weight, flip_filter */) => {});
  20171. this.registerFunction('torch_utils.ops.upfirdn2d.setup_filter', (/* x, f, up, down, padding, flip_filter, gain, impl */) => {});
  20172. this.registerFunction('torch_utils.ops.bias_act', (/* x, b, dim, act, alpha, gain, clamp, impl */) => {});
  20173. this.registerFunction('torch_utils.ops.fma.fma', (/* a, b, c */) => {});
  20174. this.registerType('torch.device', class {
  20175. constructor(type, index) {
  20176. this.type = type;
  20177. this.index = index ? index : null;
  20178. }
  20179. __str__() {
  20180. return this.index === null ? this.type : `${this.type}:${this.index}`;
  20181. }
  20182. toString() {
  20183. const index = this.index === null ? '' : `, index=${this.index}`;
  20184. return `device(type='${this.type}'${index})`;
  20185. }
  20186. });
  20187. this.registerType('torch.memory_format', class {
  20188. constructor(name) {
  20189. this.name = name;
  20190. }
  20191. __str__() {
  20192. return `torch.${this.name}`;
  20193. }
  20194. toString() {
  20195. return this.__str__();
  20196. }
  20197. });
  20198. this.registerType('torch.dtype', class {
  20199. constructor(scalar_type, name, itemsize) {
  20200. this._scalar_type = scalar_type;
  20201. this._name = name;
  20202. this._itemsize = itemsize;
  20203. }
  20204. scalar_type() {
  20205. return this._scalar_type;
  20206. }
  20207. itemsize() {
  20208. return this._itemsize;
  20209. }
  20210. __reduce__() {
  20211. return this._name;
  20212. }
  20213. __str__() {
  20214. return `torch.${this._name}`;
  20215. }
  20216. toString() {
  20217. return this.__str__();
  20218. }
  20219. });
  20220. this.registerType('torch.layout', class {
  20221. constructor(name) {
  20222. this._name = name;
  20223. }
  20224. __str__() {
  20225. return `torch.${this._name}`;
  20226. }
  20227. toString() {
  20228. return this.__str__();
  20229. }
  20230. });
  20231. this.registerType('torch.qscheme', class {
  20232. constructor(name) {
  20233. this._name = name;
  20234. }
  20235. __str__() {
  20236. return this._name;
  20237. }
  20238. toString() {
  20239. return this.__str__();
  20240. }
  20241. });
  20242. this.registerType('torch.utils.hooks.RemovableHandle', class {
  20243. __setstate__(state) {
  20244. [this.hooks_dict_ref, this.id] = state;
  20245. this.hooks_dict_ref = this.hooks_dict_ref || new Map();
  20246. }
  20247. });
  20248. this.registerType('torch.storage._StorageBase', class {
  20249. constructor(size, dtype) {
  20250. this._size = size;
  20251. this._dtype = dtype;
  20252. this._device = null;
  20253. }
  20254. get device() {
  20255. return this._device;
  20256. }
  20257. get dtype() {
  20258. return this._dtype;
  20259. }
  20260. element_size() {
  20261. return this._dtype.element_size;
  20262. }
  20263. size() {
  20264. return this._size;
  20265. }
  20266. get data() {
  20267. return this._cdata;
  20268. }
  20269. _set_cdata(data) {
  20270. const length = this.size() * this.dtype.itemsize();
  20271. if (length !== data.length) {
  20272. throw new python.Error('Typed storage data size mismatch.');
  20273. }
  20274. this._cdata = data;
  20275. }
  20276. _set_from_file(unpickler) {
  20277. const buffer = unpickler.read(8);
  20278. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20279. if (size !== this.size()) {
  20280. throw new python.Error('Typed storage size mismatch.');
  20281. }
  20282. const itemsize = this.dtype.itemsize();
  20283. const data = unpickler.stream(itemsize * size);
  20284. this._set_cdata(data);
  20285. }
  20286. static _new_with_file(unpickler) {
  20287. const buffer = unpickler.read(8);
  20288. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20289. const storage = new this(size);
  20290. const itemsize = storage.dtype.itemsize();
  20291. const data = unpickler.stream(itemsize * size);
  20292. storage._set_cdata(data);
  20293. return storage;
  20294. }
  20295. });
  20296. this.registerType('torch.storage.UntypedStorage', class {
  20297. constructor(size) {
  20298. this._size = size;
  20299. }
  20300. _set_cdata(data) {
  20301. if (this._size !== data.length) {
  20302. throw new python.Error('Untyped storage data size mismatch.');
  20303. }
  20304. this._cdata = data;
  20305. }
  20306. });
  20307. this.registerType('torch.storage.TypedStorage', class {
  20308. constructor(...args) {
  20309. if (args.length === 0) {
  20310. this._size = 0;
  20311. } else if (args.length === 1 && Number.isInteger(args[0])) {
  20312. [this._size] = args;
  20313. } else if (args.length >= 2 && Number.isInteger(args[0]) && args[1] instanceof torch.dtype) {
  20314. if (args[3] instanceof torch.device) {
  20315. [this._size, this.dtype, , this._device] = args;
  20316. } else {
  20317. [this._size, this.dtype] = args;
  20318. }
  20319. } else {
  20320. throw new python.Error(`Unsupported TypedStorage arguments '${JSON.stringify(args)}'.`);
  20321. }
  20322. }
  20323. get device() {
  20324. return this._device;
  20325. }
  20326. get dtype() {
  20327. return this._dtype;
  20328. }
  20329. set dtype(value) {
  20330. this._dtype = value;
  20331. }
  20332. element_size() {
  20333. return this._dtype.element_size;
  20334. }
  20335. size() {
  20336. return this._size;
  20337. }
  20338. get data() {
  20339. return this._cdata;
  20340. }
  20341. _set_cdata(data) {
  20342. const length = this.size() * this.dtype.itemsize();
  20343. if (length !== data.length) {
  20344. throw new python.Error('Storage data size mismatch.');
  20345. }
  20346. this._cdata = data;
  20347. }
  20348. _set_from_file(unpickler) {
  20349. const buffer = unpickler.read(8);
  20350. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20351. if (size !== this.size()) {
  20352. throw new python.Error('Storage size mismatch.');
  20353. }
  20354. const itemsize = this.dtype.itemsize();
  20355. const data = unpickler.stream(itemsize * size);
  20356. this._set_cdata(data);
  20357. }
  20358. static _new_with_file(unpickler) {
  20359. const buffer = unpickler.read(8);
  20360. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20361. const storage = new this(size);
  20362. const itemsize = storage.dtype.itemsize();
  20363. const data = unpickler.stream(itemsize * size);
  20364. storage._set_cdata(data);
  20365. return storage;
  20366. }
  20367. });
  20368. this.registerType('torch.storage._LegacyStorage', class extends torch.storage.TypedStorage {
  20369. });
  20370. this.registerType('torch.BoolStorage', class extends torch.storage._LegacyStorage {
  20371. constructor(...args) {
  20372. // eslint-disable-next-line no-constructor-return
  20373. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.BoolStorage.dtype);
  20374. }
  20375. });
  20376. this.registerType('torch.ByteStorage', class extends torch.storage._LegacyStorage {
  20377. constructor(...args) {
  20378. // eslint-disable-next-line no-constructor-return
  20379. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ByteStorage.dtype);
  20380. }
  20381. });
  20382. this.registerType('torch.CharStorage', class extends torch.storage._LegacyStorage {
  20383. constructor(...args) {
  20384. // eslint-disable-next-line no-constructor-return
  20385. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.CharStorage.dtype);
  20386. }
  20387. });
  20388. this.registerType('torch.ShortStorage', class extends torch.storage._LegacyStorage {
  20389. constructor(...args) {
  20390. // eslint-disable-next-line no-constructor-return
  20391. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ShortStorage.dtype);
  20392. }
  20393. });
  20394. this.registerType('torch.IntStorage', class extends torch.storage._LegacyStorage {
  20395. constructor(...args) {
  20396. // eslint-disable-next-line no-constructor-return
  20397. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.IntStorage.dtype);
  20398. }
  20399. });
  20400. this.registerType('torch.LongStorage', class extends torch.storage._LegacyStorage {
  20401. constructor(...args) {
  20402. // eslint-disable-next-line no-constructor-return
  20403. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.LongStorage.dtype);
  20404. }
  20405. });
  20406. this.registerType('torch.HalfStorage', class extends torch.storage._LegacyStorage {
  20407. constructor(...args) {
  20408. // eslint-disable-next-line no-constructor-return
  20409. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.HalfStorage.dtype);
  20410. }
  20411. });
  20412. this.registerType('torch.FloatStorage', class extends torch.storage._LegacyStorage {
  20413. constructor(...args) {
  20414. // eslint-disable-next-line no-constructor-return
  20415. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.FloatStorage.dtype);
  20416. }
  20417. });
  20418. this.registerType('torch.DoubleStorage', class extends torch.storage._LegacyStorage {
  20419. constructor(...args) {
  20420. // eslint-disable-next-line no-constructor-return
  20421. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.DoubleStorage.dtype);
  20422. }
  20423. });
  20424. this.registerType('torch.ComplexHalfStorage', class extends torch.storage._LegacyStorage {
  20425. constructor(...args) {
  20426. // eslint-disable-next-line no-constructor-return
  20427. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ComplexHalfStorage.dtype);
  20428. }
  20429. });
  20430. this.registerType('torch.ComplexFloatStorage', class extends torch.storage._LegacyStorage {
  20431. constructor(...args) {
  20432. // eslint-disable-next-line no-constructor-return
  20433. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ComplexFloatStorage.dtype);
  20434. }
  20435. });
  20436. this.registerType('torch.ComplexDoubleStorage', class extends torch.storage._LegacyStorage {
  20437. constructor(...args) {
  20438. // eslint-disable-next-line no-constructor-return
  20439. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ComplexDoubleStorage.dtype);
  20440. }
  20441. });
  20442. this.registerType('torch.QInt8Storage', class extends torch.storage._LegacyStorage {
  20443. constructor(...args) {
  20444. // eslint-disable-next-line no-constructor-return
  20445. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt8Storage.dtype);
  20446. }
  20447. });
  20448. this.registerType('torch.QUInt8Storage', class extends torch.storage._LegacyStorage {
  20449. constructor(...args) {
  20450. // eslint-disable-next-line no-constructor-return
  20451. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt8Storage.dtype);
  20452. }
  20453. });
  20454. this.registerType('torch.QInt32Storage', class extends torch.storage._LegacyStorage {
  20455. constructor(...args) {
  20456. // eslint-disable-next-line no-constructor-return
  20457. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QInt32Storage.dtype);
  20458. }
  20459. });
  20460. this.registerType('torch.BFloat16Storage', class extends torch.storage._LegacyStorage {
  20461. constructor(...args) {
  20462. // eslint-disable-next-line no-constructor-return
  20463. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.BFloat16Storage.dtype);
  20464. }
  20465. });
  20466. this.registerType('torch.QUInt4x2Storage', class extends torch.storage._LegacyStorage {
  20467. constructor(...args) {
  20468. // eslint-disable-next-line no-constructor-return
  20469. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt4x2Storage.dtype);
  20470. }
  20471. });
  20472. this.registerType('torch.QUInt2x4Storage', class extends torch.storage._LegacyStorage {
  20473. constructor(...args) {
  20474. // eslint-disable-next-line no-constructor-return
  20475. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt2x4Storage.dtype);
  20476. }
  20477. });
  20478. this.registerType('torch.UInt16Storage', class extends torch.storage._LegacyStorage {
  20479. constructor(...args) {
  20480. // eslint-disable-next-line
  20481. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.UInt16Storage.dtype);
  20482. }
  20483. });
  20484. this.registerType('torch.UInt32Storage', class extends torch.storage._LegacyStorage {
  20485. constructor(...args) {
  20486. // eslint-disable-next-line no-constructor-return
  20487. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.UInt32Storage.dtype);
  20488. }
  20489. });
  20490. this.registerType('torch.UInt64Storage', class extends torch.storage._LegacyStorage {
  20491. constructor(...args) {
  20492. // eslint-disable-next-line no-constructor-return
  20493. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.UInt64Storage.dtype);
  20494. }
  20495. });
  20496. this.registerType('torch.Size', class extends Array {
  20497. constructor(size) {
  20498. super(size.length);
  20499. for (let i = 0; i < size.length; i++) {
  20500. this[i] = size[i];
  20501. }
  20502. }
  20503. __len__() {
  20504. return this.length;
  20505. }
  20506. });
  20507. this.registerType('torch._C.TensorMeta', class {
  20508. });
  20509. this.registerType('torch._C.TensorBase', class extends torch._C.TensorMeta {
  20510. });
  20511. this.registerType('torch.Tensor', class extends torch._C.TensorBase {
  20512. constructor(storage, shape, dtype, layout, device, requires_grad) {
  20513. super();
  20514. if (storage) {
  20515. this._storage = storage;
  20516. }
  20517. if (shape !== null && shape !== undefined) {
  20518. this._shape = shape;
  20519. }
  20520. if (dtype) {
  20521. this._dtype = dtype;
  20522. }
  20523. this._layout = layout || torch.strided;
  20524. if (device) {
  20525. this._device = device;
  20526. }
  20527. if (requires_grad !== undefined) {
  20528. this.requires_grad = requires_grad;
  20529. }
  20530. }
  20531. clone() {
  20532. const tensor = new torch.Tensor(this._storage, this._shape, this._dtype, this._layout, this._device, this.requires_grad);
  20533. tensor._storage_offset = this._storage_offset;
  20534. tensor._stride = this._stride;
  20535. tensor._values = this._values;
  20536. tensor._indices = this._indices;
  20537. tensor.__quantized__ = this.__quantized__;
  20538. tensor.__nested__ = this.__nested__;
  20539. tensor.data = this.data;
  20540. tensor._backward_hooks = this._backward_hooks;
  20541. return tensor;
  20542. }
  20543. get device() {
  20544. if (this._device !== undefined) {
  20545. return this._device;
  20546. }
  20547. return this.storage().device;
  20548. }
  20549. get dtype() {
  20550. if (this._dtype !== undefined) {
  20551. return this._dtype;
  20552. }
  20553. if (this._layout === torch.sparse_coo) {
  20554. return this._values.dtype;
  20555. }
  20556. return this.storage().dtype;
  20557. }
  20558. get shape() {
  20559. return this._shape;
  20560. }
  20561. get layout() {
  20562. return this._layout;
  20563. }
  20564. get values() {
  20565. if (this._layout === torch.sparse_coo) {
  20566. return this._values;
  20567. }
  20568. throw new python.Error(`Unsupported values in layout'${this._layout.__str__()}'.`);
  20569. }
  20570. get indices() {
  20571. if (this._layout === torch.sparse_coo) {
  20572. return this._indices;
  20573. }
  20574. throw new python.Error(`Unsupported indices in layout'${this._indices.__str__()}'.`);
  20575. }
  20576. get is_quantized() {
  20577. return this.__quantized__ === true;
  20578. }
  20579. get is_nested() {
  20580. return this.__nested__ === true;
  20581. }
  20582. get is_sparse() {
  20583. return this.layout !== torch.strided;
  20584. }
  20585. size() {
  20586. return this._shape;
  20587. }
  20588. storage() {
  20589. return this._storage;
  20590. }
  20591. storage_offset() {
  20592. return this._storage_offset;
  20593. }
  20594. stride() {
  20595. return this._stride;
  20596. }
  20597. resize_(shape) {
  20598. this._shape = shape;
  20599. }
  20600. __len__() {
  20601. return this._shape[0];
  20602. }
  20603. __setstate__(state) {
  20604. switch (state.length) {
  20605. case 3:
  20606. break;
  20607. case 4:
  20608. [this._storage, this._storage_offset, this._shape, this._stride] = state;
  20609. break;
  20610. case 5:
  20611. [this.data, ,this._backward_hooks, this.requires_grad] = state;
  20612. break;
  20613. default:
  20614. throw new python.Error(`Unsupported tensor state length '${state.length}'.`);
  20615. }
  20616. }
  20617. set_(source, storage_offset, size, stride) {
  20618. this._storage = source;
  20619. this._storage_offset = storage_offset;
  20620. this._shape = size;
  20621. this._stride = stride;
  20622. }
  20623. __bool__() {
  20624. return true;
  20625. }
  20626. __int__() {
  20627. const storage = this.storage();
  20628. if (storage && storage.dtype.__reduce__() === 'int64' && storage.data.length === 8) {
  20629. const buffer = storage.data.peek ? storage.data.peek() : storage.data;
  20630. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  20631. return view.getBigInt64(0, true);
  20632. }
  20633. return NaN;
  20634. }
  20635. __float__() {
  20636. const storage = this.storage();
  20637. if (storage && storage.dtype.__reduce__() === 'float32') {
  20638. if (storage.size() !== undefined && storage.data.length === 4) {
  20639. const buffer = storage.data.peek ? storage.data.peek() : storage.data;
  20640. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  20641. return view.getFloat32(0, true);
  20642. }
  20643. }
  20644. return NaN;
  20645. }
  20646. __str__() {
  20647. return 'tensor(...)';
  20648. }
  20649. static _make_wrapper_subclass(cls, size, stride, dtype, storage_offset, layout, device, requires_grad) {
  20650. const t = new torch.Tensor(null, size, dtype, layout, device, requires_grad);
  20651. t.__setstate__([null, storage_offset, size, stride]);
  20652. return t;
  20653. }
  20654. });
  20655. this.registerType('torch.nn.parameter.Parameter', class extends torch.Tensor {
  20656. constructor(data, requires_grad) {
  20657. super();
  20658. this.data = data || new torch.Tensor([]);
  20659. this.requires_grad = requires_grad === undefined ? true : requires_grad;
  20660. }
  20661. });
  20662. this.registerType('torch._subclasses.fake_tensor.FakeTensor', class extends torch.Tensor {
  20663. });
  20664. this.registerType('torch._subclasses.fake_tensor.FakeTensorMode', class extends torch.utils._python_dispatch.TorchDispatchMode {
  20665. constructor(allow_fallback_kernels, allow_non_fake_inputs, shape_env) {
  20666. super();
  20667. this.allow_fallback_kernels = allow_fallback_kernels;
  20668. this.allow_non_fake_inputs = allow_non_fake_inputs;
  20669. this.shape_env = shape_env;
  20670. this.enter_stack = [];
  20671. this._mode_key = 0; // torch._C._TorchDispatchModeKey.FAKE
  20672. }
  20673. __enter__() {
  20674. const prev_only_lift_cpu_tensors = null;
  20675. const maybe_prev_fake_mode = torch._C._unset_dispatch_mode(this._mode_key);
  20676. if (this === maybe_prev_fake_mode) {
  20677. torch._C._set_dispatch_mode(this);
  20678. this.enter_stack.push([false, null, prev_only_lift_cpu_tensors]);
  20679. } else {
  20680. this.enter_stack.push([true, maybe_prev_fake_mode, prev_only_lift_cpu_tensors]);
  20681. return super.__enter__();
  20682. }
  20683. return this;
  20684. }
  20685. __exit__(exc_type, exc_value, traceback) {
  20686. const [live, maybe_prev_fake_mode, maybe_prev_only_lift_cpu_tensors] = this.enter_stack.pop();
  20687. if (live) {
  20688. super.__exit__(exc_type, exc_value, traceback);
  20689. if (maybe_prev_fake_mode !== null) {
  20690. torch._C._set_dispatch_mode(maybe_prev_fake_mode);
  20691. }
  20692. if (maybe_prev_only_lift_cpu_tensors !== null) {
  20693. torch._C._set_only_lift_cpu_tensors(maybe_prev_only_lift_cpu_tensors);
  20694. }
  20695. torch._C._set_dispatch_mode(maybe_prev_fake_mode);
  20696. }
  20697. }
  20698. });
  20699. this.registerType('torch.nn.parameter.UninitializedParameter', class extends torch.nn.parameter.Parameter {
  20700. constructor(requires_grad /*, device, dtype */) {
  20701. super(undefined, requires_grad);
  20702. }
  20703. });
  20704. this.registerType('torch.nn.parameter.UninitializedBuffer', class extends torch.Tensor {});
  20705. this.registerType('torch.BoolTensor', class extends torch.Tensor {
  20706. constructor(...args) {
  20707. // eslint-disable-next-line no-constructor-return
  20708. return new torch.Tensor(...args);
  20709. }
  20710. });
  20711. this.registerType('torch.ByteTensor', class extends torch.Tensor {
  20712. constructor(...args) {
  20713. // eslint-disable-next-line no-constructor-return
  20714. return new torch.Tensor(...args);
  20715. }
  20716. });
  20717. this.registerType('torch.CharTensor', class extends torch.Tensor {
  20718. constructor(...args) {
  20719. // eslint-disable-next-line no-constructor-return
  20720. return new torch.Tensor(...args);
  20721. }
  20722. });
  20723. this.registerType('torch.ShortTensor', class extends torch.Tensor {
  20724. constructor(...args) {
  20725. // eslint-disable-next-line no-constructor-return
  20726. return new torch.Tensor(...args);
  20727. }
  20728. });
  20729. this.registerType('torch.IntTensor', class extends torch.Tensor {
  20730. constructor(...args) {
  20731. // eslint-disable-next-line no-constructor-return
  20732. return new torch.Tensor(...args);
  20733. }
  20734. });
  20735. this.registerType('torch.LongTensor', class extends torch.Tensor {
  20736. constructor(...args) {
  20737. // eslint-disable-next-line no-constructor-return
  20738. return new torch.Tensor(...args);
  20739. }
  20740. });
  20741. this.registerType('torch.HalfTensor', class extends torch.Tensor {
  20742. constructor(...args) {
  20743. // eslint-disable-next-line no-constructor-return
  20744. return new torch.Tensor(...args);
  20745. }
  20746. });
  20747. this.registerType('torch.FloatTensor', class extends torch.Tensor {
  20748. constructor(...args) {
  20749. // eslint-disable-next-line no-constructor-return
  20750. return new torch.Tensor(...args);
  20751. }
  20752. });
  20753. this.registerType('torch.DoubleTensor', class extends torch.Tensor {
  20754. constructor(...args) {
  20755. // eslint-disable-next-line no-constructor-return
  20756. return new torch.Tensor(...args);
  20757. }
  20758. });
  20759. this.registerType('torch.ComplexFloatTensor', class extends torch.Tensor {
  20760. constructor(...args) {
  20761. // eslint-disable-next-line no-constructor-return
  20762. return new torch.Tensor(...args);
  20763. }
  20764. });
  20765. this.registerType('torch.ComplexDoubleTensor', class extends torch.Tensor {
  20766. constructor(...args) {
  20767. // eslint-disable-next-line no-constructor-return
  20768. return new torch.Tensor(...args);
  20769. }
  20770. });
  20771. this.registerType('torch.QInt8Tensor', class extends torch.Tensor {
  20772. constructor(...args) {
  20773. // eslint-disable-next-line no-constructor-return
  20774. return new torch.Tensor(...args);
  20775. }
  20776. });
  20777. this.registerType('torch.QUInt8Tensor', class extends torch.Tensor {
  20778. constructor(...args) {
  20779. // eslint-disable-next-line no-constructor-return
  20780. return new torch.Tensor(...args);
  20781. }
  20782. });
  20783. this.registerType('torch.QInt32Tensor', class extends torch.Tensor {
  20784. constructor(...args) {
  20785. // eslint-disable-next-line no-constructor-return
  20786. return new torch.Tensor(...args);
  20787. }
  20788. });
  20789. this.registerType('torch.BFloat16Tensor', class extends torch.Tensor {
  20790. constructor(...args) {
  20791. // eslint-disable-next-line no-constructor-return
  20792. return new torch.Tensor(...args);
  20793. }
  20794. });
  20795. this.registerType('torch.cuda._CudaLegacyStorage', class extends torch.storage._LegacyStorage {});
  20796. this.registerType('torch.cuda.FloatStorage', class extends torch.cuda._CudaLegacyStorage {});
  20797. this.registerType('torch.cuda.FloatTensor', class extends torch.Tensor {
  20798. constructor(...args) {
  20799. // eslint-disable-next-line no-constructor-return
  20800. return new torch.Tensor(...args);
  20801. }
  20802. });
  20803. this.registerType('torch.cuda.DoubleStorage', class extends torch.cuda._CudaLegacyStorage {});
  20804. this.registerType('torch.cuda.DoubleTensor', class extends torch.Tensor {
  20805. constructor(...args) {
  20806. // eslint-disable-next-line no-constructor-return
  20807. return new torch.Tensor(...args);
  20808. }
  20809. });
  20810. this.registerType('torch.cuda.amp.grad_scaler.GradScaler', class {});
  20811. this.registerType('torchao.utils.TorchAOBaseTensor', class extends torch.Tensor {
  20812. constructor(...args) {
  20813. // eslint-disable-next-line no-constructor-return
  20814. return new torch.Tensor(...args);
  20815. }
  20816. });
  20817. this.registerType('torchao.dtypes.affine_quantized_tensor.AffineQuantizedTensor', class extends torchao.utils.TorchAOBaseTensor {});
  20818. this.registerType('torchao.dtypes.utils.Layout', class {});
  20819. this.registerType('torchao.dtypes.uintx.plain_layout.PlainAQTTensorImpl', class {});
  20820. this.registerType('torchao.dtypes.floatx.float8_layout.Float8Layout', class extends torchao.dtypes.utils.Layout {});
  20821. this.registerType('torchao.dtypes.utils.AQTTensorImpl', class extends torchao.utils.TorchAOBaseTensor {});
  20822. this.registerType('torchao.dtypes.utils.PlainLayout', class extends torchao.dtypes.utils.Layout {});
  20823. this.registerType('torchao.dtypes.floatx.float8_layout.Float8AQTTensorImpl', class extends torchao.dtypes.utils.AQTTensorImpl {});
  20824. this.registerType('torchao.quantization.quant_primitives.ZeroPointDomain', class extends this.enum.Enum {});
  20825. this.registerFunction('torch.cuda.amp.grad_scaler._refresh_per_optimizer_state');
  20826. this.registerType('torch.SymBool', class {
  20827. constructor(node) {
  20828. this.node = node;
  20829. }
  20830. });
  20831. this.registerType('torch.SymInt', class {
  20832. constructor(node) {
  20833. this.node = node;
  20834. }
  20835. toString() {
  20836. return this.node.__str__();
  20837. }
  20838. });
  20839. this.register('torch.nn').Module = this.register('torch.nn.modules.module').Module;
  20840. this.register('torch.optim').Adam = this.register('torch.optim.adam').Adam;
  20841. this.register('torch.nn').ReLU = this.register('torch.nn.modules.activation').ReLU;
  20842. this.register('sklearn.utils').Bunch = this.register('sklearn.utils._bunch').Bunch;
  20843. /* eslint-disable no-multi-assign */
  20844. // https://github.com/pytorch/pytorch/blob/main/c10/core/ScalarType.h
  20845. torch.uint8 = torch.ByteStorage.dtype = new torch.dtype(0, 'uint8', 1);
  20846. torch.int8 = torch.CharStorage.dtype = new torch.dtype(1, 'int8', 1);
  20847. torch.int16 = torch.ShortStorage.dtype = new torch.dtype(2, 'int16', 2);
  20848. torch.int32 = torch.IntStorage.dtype = new torch.dtype(3, 'int32', 4);
  20849. torch.int64 = torch.LongStorage.dtype = new torch.dtype(4, 'int64', 8);
  20850. torch.float16 = torch.HalfStorage.dtype = new torch.dtype(5, 'float16', 2);
  20851. torch.float32 = torch.FloatStorage.dtype = new torch.dtype(6, 'float32', 4);
  20852. torch.float64 = torch.DoubleStorage.dtype = new torch.dtype(7, 'float64', 8);
  20853. torch.complex32 = torch.ComplexHalfStorage.dtype = new torch.dtype(8, 'complex<float16>', 4);
  20854. torch.complex64 = torch.ComplexFloatStorage.dtype = new torch.dtype(9, 'complex<float32>', 8);
  20855. torch.complex128 = torch.ComplexDoubleStorage.dtype = new torch.dtype(10, 'complex<float64>', 16);
  20856. torch.bool = torch.BoolStorage.dtype = new torch.dtype(11, 'boolean', 1);
  20857. torch.qint8 = torch.QInt8Storage.dtype = new torch.dtype(12, 'qint8', 1);
  20858. torch.quint8 = torch.QUInt8Storage.dtype = new torch.dtype(13, 'quint8', 1);
  20859. torch.qint32 = torch.QInt32Storage.dtype = new torch.dtype(14, 'qint32', 4);
  20860. torch.bfloat16 = torch.BFloat16Storage.dtype = new torch.dtype(15, 'bfloat16', 2);
  20861. torch.quint4x2 = torch.QUInt4x2Storage.dtype = new torch.dtype(16, 'quint4x2', 1);
  20862. torch.quint2x4 = torch.QUInt2x4Storage.dtype = new torch.dtype(17, 'quint2x4');
  20863. torch.bits1x8 = new torch.dtype(18, 'bits1x8');
  20864. torch.bits2x4 = new torch.dtype(19, 'bits2x4');
  20865. torch.bits4x2 = new torch.dtype(20, 'bits4x2');
  20866. torch.bits8 = new torch.dtype(21, 'bits8');
  20867. torch.bits16 = new torch.dtype(22, 'bits16');
  20868. torch.float8_e5m2 = new torch.dtype(23, 'float8_e5m2', 1);
  20869. torch.float8_e5m2fnuz = new torch.dtype(24, 'float8_e5m2fnuz', 1);
  20870. torch.float8_e4m3fn = new torch.dtype(25, 'float8_e4m3fn', 1);
  20871. torch.float8_e4m3fnuz = new torch.dtype(26, 'float8_e4m3fnuz', 1);
  20872. torch.uint16 = torch.UInt16Storage.dtype = new torch.dtype(27, 'uint16', 2);
  20873. torch.uint32 = torch.UInt32Storage.dtype = new torch.dtype(28, 'uint32', 4);
  20874. torch.uint64 = torch.UInt64Storage.dtype = new torch.dtype(29, 'uint64', 8);
  20875. torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE = new Map([
  20876. ['uint8', 'BYTE'],
  20877. ['int8', 'CHAR'], ['int16', 'SHORT'], ['int32', 'INT'], ['int64', 'LONG'],
  20878. ['float16', 'HALF'], ['float32', 'FLOAT'], ['float64', 'DOUBLE'],
  20879. ['complex32', 'COMPLEXHALF'], ['complex64', 'COMPLEXFLOAT'], ['complex128', 'COMPLEXDOUBLE'],
  20880. ['bool', 'BOOL'], ['bfloat16', 'BFLOAT16'], ['uint16', 'UINT16'],
  20881. ['float8_e4m3fn','FLOAT8E4M3FN'], ['float8_e5m2','FLOAT8E5M2'], ['float8_e4m3fnuz','FLOAT8E4M3FNUZ'], ['float8_e5m2fnuz','FLOAT8E5M2FNUZ']
  20882. ].map(([key, value]) => [torch._export.serde.schema.ScalarType[value], torch[key]]));
  20883. torch.contiguous_format = new torch.memory_format('contiguous_format');
  20884. torch.channels_last = new torch.memory_format('channels_last');
  20885. torch.channels_last_3d = new torch.memory_format('channels_last_3d');
  20886. torch.preserve_format = new torch.memory_format('preserve_format');
  20887. torch._export.serde.serialize._SERIALIZE_TO_TORCH_MEMORY_FORMAT = Object.fromEntries([
  20888. ['contiguous_format', 'ContiguousFormat'],
  20889. ['channels_last', 'ChannelsLast'],
  20890. ['channels_last_3d', 'ChannelsLast3d'],
  20891. ['preserve_format', 'PreserveFormat']
  20892. ].map(([key, value]) => [torch._export.serde.schema.MemoryFormat[value], torch[key]]));
  20893. /* eslint-enable no-multi-assign */
  20894. torch.strided = new torch.layout('strided');
  20895. torch.sparse_coo = new torch.layout('sparse_coo');
  20896. torch.sparse_csr = new torch.layout('sparse_csr');
  20897. torch.sparse_csc = new torch.layout('sparse_csc');
  20898. torch.sparse_bsr = new torch.layout('sparse_bsr');
  20899. torch.sparse_bsc = new torch.layout('sparse_bsc');
  20900. torch._mkldnn = new torch.layout('_mkldnn');
  20901. torch._export.serde.serialize._SERIALIZE_TO_TORCH_LAYOUT = Object.fromEntries([
  20902. ['sparse_coo', 'SparseCoo'],
  20903. ['sparse_csr', 'SparseCsr'],
  20904. ['sparse_csc', 'SparseCsc'],
  20905. ['sparse_bsr', 'SparseBsr'],
  20906. ['sparse_bsc', 'SparseBsc'],
  20907. ['_mkldnn', '_mkldnn'],
  20908. ['strided', 'Strided'],
  20909. ].map(([key, value]) => [torch._export.serde.schema.Layout[value], torch[key]]));
  20910. torch.per_tensor_affine = new torch.qscheme('torch.per_tensor_affine');
  20911. torch.per_channel_affine = new torch.qscheme('torch.per_channel_affine');
  20912. torch.per_tensor_symmetric = new torch.qscheme('torch.per_tensor_symmetric');
  20913. torch.per_channel_symmetric = new torch.qscheme('torch.per_channel_symmetric');
  20914. torch.per_channel_affine_float_qparams = new torch.qscheme('torch.per_channel_affine_float_qparams');
  20915. torch.inf = this.register('math').inf;
  20916. this.registerFunction('fastcore.basics._using_attr');
  20917. this.registerFunction('fastcore.imports.noop');
  20918. this.registerType('fastcore.basics.fastuple', class {});
  20919. this.registerType('fastcore.basics.GetAttr', class {});
  20920. this.registerType('fastcore.dispatch._TypeDict', class {});
  20921. this.registerType('fastcore.dispatch.TypeDispatch', class {});
  20922. this.registerType('fastcore.foundation.L', class {});
  20923. this.registerType('fastcore.transform.Pipeline', class extends builtins.object {});
  20924. this.registerType('fastcore.transform.Transform', class extends builtins.object {});
  20925. this.registerType('fastcore.transform.DisplayedTransform', class extends fastcore.transform.Transform {});
  20926. this.registerType('fastcore.transform.ItemTransform', class extends fastcore.transform.Transform {});
  20927. this.registerType('fastai.basic_train.Learner', class {});
  20928. this.registerType('fastai.basic_train.Recorder', class {});
  20929. this.registerFunction('fastai.torch_core._fa_rebuild_tensor', (cls, ...args) => {
  20930. const tensor = torch._utils._rebuild_tensor_v2(...args);
  20931. return self.invoke(cls, [tensor]);
  20932. });
  20933. this.registerFunction('fastai.torch_core.trainable_params');
  20934. this.registerFunction('fastai.torch_core._rebuild_from_type', (func, type, args, dict) => {
  20935. const tensor = self.invoke(type, [func(...args)]);
  20936. Object.assign(tensor, dict);
  20937. return tensor;
  20938. });
  20939. this.registerType('fastai.torch_core.Module', class extends torch.nn.modules.module.Module {});
  20940. this.registerType('fastai.torch_core.TensorBase', class extends torch.Tensor {
  20941. constructor(x) {
  20942. super();
  20943. Object.assign(this, x);
  20944. }
  20945. });
  20946. this.registerType('fastai.torch_core.TensorCategory', class extends fastai.torch_core.TensorBase {});
  20947. this.registerType('fastai.torch_core.TensorImageBase', class extends fastai.torch_core.TensorBase {});
  20948. this.registerType('fastai.torch_core.TensorImage', class extends fastai.torch_core.TensorImageBase {});
  20949. this.registerType('fastai.torch_core.TensorMask', class extends fastai.torch_core.TensorImageBase {});
  20950. this.registerType('fastai.torch_core.TensorMultiCategory', class extends fastai.torch_core.TensorCategory {});
  20951. this.registerFunction('fastai.torch_core.uniform');
  20952. this.registerType('fastai.callback.core.Callback', class extends fastcore.basics.GetAttr {});
  20953. this.registerType('fastai.callback.core.TrainEvalCallback', class extends fastai.callback.core.Callback {});
  20954. this.registerType('fastai.callback.fp16.AMPMode', class extends this.enum.Enum {});
  20955. this.registerType('fastai.callback.fp16.MixedPrecision', class {});
  20956. this.registerFunction('fastai.callback.hook._hook_inner');
  20957. this.registerType('fastai.callback.hook.Hook', class extends builtins.object {});
  20958. this.registerType('fastai.callback.hook.Hooks', class extends builtins.object {});
  20959. this.registerType('fastai.callback.mixup.MixHandler', class extends fastai.callback.core.Callback {});
  20960. this.registerType('fastai.callback.mixup.CutMix', class extends fastai.callback.mixup.MixHandler {});
  20961. this.registerType('fastai.callback.progress.ProgressCallback', class {});
  20962. this.registerType('fastai.callback.progress.ShowGraphCallback', class {});
  20963. this.registerType('fastai.callback.tracker.EarlyStoppingCallback', class {});
  20964. this.registerType('fastai.callback.tracker.TrackerCallback', class {});
  20965. this.registerType('fastai.callback.tracker.SaveModelCallback', class extends fastai.callback.tracker.TrackerCallback {});
  20966. this.registerType('fastai.data.core.DataLoaders', class extends fastcore.basics.GetAttr {});
  20967. this.registerType('fastai.data.core.Datasets', class {});
  20968. this.registerType('fastai.data.load.DataLoader', class extends fastcore.basics.GetAttr {});
  20969. this.registerType('fastai.data.core.FilteredBase', class {});
  20970. this.registerType('fastai.data.core.TfmdDL', class extends fastai.data.load.DataLoader {});
  20971. this.registerType('fastai.data.core.TfmdLists', class {});
  20972. this.registerType('fastai.data.load._FakeLoader', class {});
  20973. this.registerFunction('fastai.data.load._wif');
  20974. this.registerType('fastai.data.transforms.Categorize', class {});
  20975. this.registerType('fastai.data.transforms.Category', class {});
  20976. this.registerType('fastai.data.transforms.CategoryMap', class {});
  20977. this.registerType('fastai.data.transforms.ColReader', class {});
  20978. this.registerType('fastai.data.transforms.IntToFloatTensor', class {});
  20979. this.registerType('fastai.data.transforms.MultiCategorize', class {});
  20980. this.registerType('fastai.data.transforms.Normalize', class {});
  20981. this.registerType('fastai.data.transforms.parent_label', class {});
  20982. this.registerType('fastai.data.transforms.OneHotEncode', class {});
  20983. this.registerType('fastai.data.transforms.RegressionSetup', class {});
  20984. this.registerType('fastai.data.transforms.ToTensor', class {});
  20985. this.registerType('fastai.data_block.CategoryList', class {});
  20986. this.registerType('fastai.data_block.CategoryProcessor', class {});
  20987. this.registerType('fastai.imports.noop', class {});
  20988. this.registerType('fastai.layers.AdaptiveConcatPool2d', class {});
  20989. this.registerType('fastai.layers.ConvLayer', class {});
  20990. this.registerType('fastai.layers.Embedding', class {});
  20991. this.registerType('fastai.layers.Flatten', class {});
  20992. this.registerType('fastai.layers.FlattenedLoss', class {});
  20993. this.registerType('fastai.layers.LinBnDrop', class {});
  20994. this.registerType('fastai.layers.MergeLayer', class {});
  20995. this.registerType('fastai.layers.PixelShuffle_ICNR', class {});
  20996. this.registerType('fastai.layers.ResBlock', class {});
  20997. this.registerType('fastai.layers.SelfAttention', class {});
  20998. this.registerType('fastai.layers.SigmoidRange', class {});
  20999. this.registerType('fastai.layers.TimeDistributed', class {});
  21000. this.registerType('fastai.layers.ToTensorBase', class {});
  21001. this.registerType('fastai.learner._ConstantFunc', class {});
  21002. this.registerType('fastai.learner.Metric', class {});
  21003. this.registerType('fastai.learner.AvgLoss', class extends fastai.learner.Metric {});
  21004. this.registerType('fastai.learner.AvgMetric', class extends fastai.learner.Metric {});
  21005. this.registerType('fastai.learner.AvgSmoothLoss', class extends fastai.learner.Metric {});
  21006. this.registerType('fastai.learner.CastToTensor', class extends fastai.callback.core.Callback {});
  21007. this.registerType('fastai.learner.Dice', class extends fastai.learner.Metric {});
  21008. this.registerType('fastai.learner.Learner', class extends fastcore.basics.GetAttr {});
  21009. this.registerType('fastai.learner.Recorder', class {});
  21010. this.registerType('fastai.losses.BaseLoss', class {});
  21011. this.registerType('fastai.losses.BCEWithLogitsLossFlat', class {});
  21012. this.registerType('fastai.losses.CrossEntropyLossFlat', class extends fastai.losses.BaseLoss {});
  21013. this.registerType('fastai.losses.FocalLoss', class extends fastai.torch_core.Module {});
  21014. this.registerType('fastai.losses.FocalLossFlat', class extends fastai.losses.BaseLoss {});
  21015. this.registerType('fastai.losses.LabelSmoothingCrossEntropy', class extends fastai.torch_core.Module {});
  21016. this.registerType('fastai.metrics.AccumMetric', class extends fastai.learner.Metric {});
  21017. this.registerType('fastai.metrics.Dice', class {});
  21018. this.registerType('fastai.metrics.JaccardCoeff', class {});
  21019. this.registerFunction('fastai.metrics._rmse');
  21020. this.registerFunction('fastai.metrics.accuracy');
  21021. this.registerFunction('fastai.metrics.accuracy_multi');
  21022. this.registerFunction('fastai.metrics.foreground_acc');
  21023. this.registerFunction('fastai.metrics.mse');
  21024. this.registerFunction('fastai.metrics.error_rate');
  21025. this.registerType('fastai.optimizer._BaseOptimizer', class {});
  21026. this.registerType('fastai.optimizer.Optimizer', class extends fastai.optimizer._BaseOptimizer {});
  21027. this.registerFunction('fastai.optimizer.Adam');
  21028. this.registerFunction('fastai.optimizer.adam_step');
  21029. this.registerFunction('fastai.optimizer.average_grad');
  21030. this.registerFunction('fastai.optimizer.average_sqr_grad');
  21031. this.registerFunction('fastai.optimizer.RAdam');
  21032. this.registerFunction('fastai.optimizer.step_stat');
  21033. this.registerFunction('fastai.optimizer.weight_decay');
  21034. this.registerType('fastai.tabular.core.Categorify', class {});
  21035. this.registerType('fastai.tabular.core.FillMissing', class {});
  21036. this.registerType('fastai.tabular.core.FillStrategy', class {});
  21037. this.registerType('fastai.tabular.core.ReadTabBatch', class extends fastcore.transform.ItemTransform {});
  21038. this.registerType('fastai.tabular.core.TabDataLoader', class extends fastai.data.core.TfmdDL {});
  21039. this.registerType('fastai.tabular.data.TabularDataLoaders', class extends fastai.data.core.DataLoaders {});
  21040. this.registerType('fastai.tabular.core.Tabular', class {});
  21041. this.registerType('fastai.tabular.core.TabularPandas', class extends fastai.tabular.core.Tabular {});
  21042. this.registerType('fastai.tabular.core.TabWeightedDL', class {});
  21043. this.registerType('fastai.tabular.learner.TabularLearner', class extends fastai.learner.Learner {});
  21044. this.registerType('fastai.tabular.model.TabularModel', class {});
  21045. this.registerFunction('fastai.vision.augment.aug_transforms');
  21046. this.registerFunction('fastai.vision.augment.dihedral_mat');
  21047. this.registerType('fastai.vision.augment._BrightnessLogit', class {});
  21048. this.registerType('fastai.vision.augment._ContrastLogit', class {});
  21049. this.registerType('fastai.vision.augment._WarpCoord', class {});
  21050. this.registerType('fastai.vision.augment.RandTransform', class extends fastcore.transform.DisplayedTransform {});
  21051. this.registerType('fastai.vision.augment.AffineCoordTfm', class extends fastai.vision.augment.RandTransform {});
  21052. this.registerType('fastai.vision.augment.Brightness', class {});
  21053. this.registerType('fastai.vision.augment.flip_mat', class {});
  21054. this.registerType('fastai.vision.augment.Flip', class {});
  21055. this.registerType('fastai.vision.augment.RandomResizedCrop', class {});
  21056. this.registerType('fastai.vision.augment.RandomResizedCropGPU', class {});
  21057. this.registerType('fastai.vision.augment.Resize', class {});
  21058. this.registerType('fastai.vision.augment.rotate_mat', class {});
  21059. this.registerFunction('fastai.vision.augment.TensorImage.lighting');
  21060. this.registerType('fastai.vision.augment.Warp', class extends fastai.vision.augment.AffineCoordTfm {});
  21061. this.registerType('fastai.vision.augment.zoom_mat', class {});
  21062. this.registerType('fastai.vision.core.PILImage', class {});
  21063. this.registerType('fastai.vision.core.PILMask', class {});
  21064. this.registerType('fastai.vision.core.AddMaskCodes', class {});
  21065. this.registerType('fastai.vision.data.ImageList', class {});
  21066. this.registerType('fastai.vision.data.ImageItemList', class {});
  21067. this.registerType('fastai.vision.image.Image', class {});
  21068. this.registerType('fastai.vision.image.RandTransform', class {});
  21069. this.registerType('fastai.vision.image.TfmCrop', class {});
  21070. this.registerFunction('fastai.vision.learner._resnet_split');
  21071. this.registerFunction('fastai.vision.learner.default_split');
  21072. this.registerFunction('fastai.vision.learner.default_split');
  21073. this.registerType('fastai.vision.learner.TimmBody', class {});
  21074. this.registerType('fastai.vision.models.unet.DynamicUnet', class {});
  21075. this.registerType('fastai.vision.models.unet.ResizeToOrig', class {});
  21076. this.registerType('fastai.vision.models.unet.UnetBlock', class {});
  21077. this.registerType('fastai.vision.models.xresnet.XResNet', class {});
  21078. this.registerFunction('fastai.vision.transform._crop_pad');
  21079. }
  21080. exec(code , context) {
  21081. const ast = this.ast;
  21082. const program = ast.parse(code, '', null, null);
  21083. if (!program) {
  21084. throw new python.Error("Module '?' parse error.");
  21085. }
  21086. this.block(program.body, context);
  21087. }
  21088. debug(/* file */) {
  21089. }
  21090. source(file) {
  21091. if (this._sources.has(file)) {
  21092. return this._sources.get(file);
  21093. }
  21094. return null;
  21095. }
  21096. read(file) {
  21097. const buffer = this.source(file);
  21098. if (buffer) {
  21099. const debug = this.debug(file);
  21100. return this.parse(file, buffer, debug);
  21101. }
  21102. return null;
  21103. }
  21104. parse(filename, buffer, debug) {
  21105. const ast = this.ast;
  21106. const source = this._utf8Decoder.decode(buffer);
  21107. const program = ast.parse(source, filename, null, debug);
  21108. if (!program) {
  21109. throw new python.Error(`Module '${filename}' parse error.`);
  21110. }
  21111. return program;
  21112. }
  21113. import(name, current, level) {
  21114. if (level) {
  21115. let bits = current.split('.');
  21116. if (bits.length < level) {
  21117. throw new python.Error('Invalid relative import beyond top-level package.');
  21118. }
  21119. bits = bits.slice(0, bits.length - level);
  21120. const base = bits.join('.');
  21121. name = name ? [base, name].join('.') : base;
  21122. }
  21123. const index = name.lastIndexOf('.');
  21124. let parent = null;
  21125. let child = null;
  21126. if (index > 0) {
  21127. parent = name.substring(0, index);
  21128. child = name.substring(index + 1);
  21129. this.import(parent);
  21130. }
  21131. if (!this._modules.has(name)) {
  21132. const module = this._registry.get(name) || new this.builtins.module(name);
  21133. module.__package__ = name;
  21134. this._modules.set(name, module);
  21135. const path = name.split('.').join('/');
  21136. module.__path__ = [path];
  21137. const file = `${path}.py`;
  21138. const program = this.read(file);
  21139. if (program) {
  21140. module.__file__ = file;
  21141. for (const [name, value] of Object.entries(this.builtins)) {
  21142. switch (name) {
  21143. case '__class__':
  21144. case '__package__':
  21145. case '__module__':
  21146. case '__name__':
  21147. case '__path__':
  21148. case '__file__':
  21149. break;
  21150. default:
  21151. module[name] = value;
  21152. break;
  21153. }
  21154. }
  21155. const context = new python.Execution.Context(module, null);
  21156. if (name !== 'builtins') {
  21157. context.set('__builtins__', this._modules.get('builtins'));
  21158. }
  21159. this.block(program.body, context);
  21160. }
  21161. if (parent) {
  21162. const parent_module = this._modules.get(parent);
  21163. parent_module[child] = module;
  21164. }
  21165. }
  21166. return this._modules.get(name);
  21167. }
  21168. __import__(name, globals, locals, fromlist, level) {
  21169. let module = null;
  21170. level = level || 0;
  21171. if (level === 0) {
  21172. module = this.import(name);
  21173. } else {
  21174. globals = globals || {};
  21175. let current = globals.__package__;
  21176. if (!current) {
  21177. const spec = globals.__spec__;
  21178. if (spec) {
  21179. current = spec.parent;
  21180. } else {
  21181. const name = globals.__name__;
  21182. const bits = name.split('.');
  21183. bits.pop();
  21184. current = bits.join('.');
  21185. }
  21186. }
  21187. module = this.import(name, current, level);
  21188. }
  21189. if (!fromlist) {
  21190. if (level === 0) {
  21191. return this.import(name.split('.')[0]);
  21192. } else if (name) {
  21193. throw new python.Error(`Unsupported relative import '${name}'.`);
  21194. // cut_off = len(name) - len(name.partition('.')[0])
  21195. // return sys.modules[module.__name__[:len(module.__name__)-cut_off]]
  21196. }
  21197. } else if (module.__path__) {
  21198. const handle_fromlist = (module, fromlist, recursive) => {
  21199. for (const name of fromlist) {
  21200. if (name === '*') {
  21201. if (!recursive && module.__all__) {
  21202. handle_fromlist(module, module.__all__, true);
  21203. }
  21204. } else if (!module[name]) {
  21205. this.import(`${module.__name__}.${name}`);
  21206. }
  21207. }
  21208. return module;
  21209. };
  21210. handle_fromlist(module, fromlist);
  21211. }
  21212. return module;
  21213. }
  21214. module(name) {
  21215. return this._modules.get(name);
  21216. }
  21217. resolve(name) {
  21218. const index = name.lastIndexOf('.');
  21219. const memberName = index === -1 ? name : name.substring(index + 1, name.length);
  21220. const moduleName = index === -1 ? '' : name.substring(0, index);
  21221. const module = this.import(moduleName);
  21222. let type = module ? module[memberName] : null;
  21223. if (!type) {
  21224. if (!this._unresolved.has(name)) {
  21225. const moduleName = name.split('.').shift();
  21226. if (this._registry.has(moduleName) && moduleName !== '__main__' && moduleName !== '__torch__') {
  21227. this.emit('resolve', name);
  21228. }
  21229. const type = this._createType(name, class {});
  21230. this._unresolved.set(name, type);
  21231. }
  21232. type = this._unresolved.get(name);
  21233. }
  21234. return type;
  21235. }
  21236. invoke(target, args) {
  21237. const builtins = this.builtins;
  21238. if (typeof target === 'string') {
  21239. target = this.resolve(target);
  21240. }
  21241. if (target) {
  21242. if (target.__class__ === builtins.type) {
  21243. if (target.prototype && target.prototype.__class__ === target) {
  21244. return Reflect.construct(target, args);
  21245. }
  21246. const obj = Object.create(target);
  21247. if (obj.__init__ && typeof obj.__init__ === 'function') {
  21248. obj.__init__(...args);
  21249. }
  21250. return obj;
  21251. } else if (target.__class__ === builtins.function) {
  21252. if (target.__call__) {
  21253. return target.__call__(args);
  21254. }
  21255. return target(...args);
  21256. }
  21257. }
  21258. throw new python.Error('Unsupported invoke target.');
  21259. }
  21260. call(target, name, args, keywords, context) {
  21261. const builtins = this.builtins;
  21262. const callTarget = this.target(target, context);
  21263. const callArguments = args.map((arg) => this.expression(arg, context));
  21264. if (!callTarget || (name !== null && !callTarget[name])) {
  21265. if (name === '__new__' && callArguments.length === 1 && callArguments[0] === callTarget) {
  21266. name = null;
  21267. callArguments.shift();
  21268. } else {
  21269. const targetName = `${this.identifier(target)}.${name}`;
  21270. throw new python.Error(`Unknown function '${targetName}'.`);
  21271. }
  21272. }
  21273. const func = name ? callTarget[name] : callTarget;
  21274. if (func.__class__ === builtins.type) {
  21275. if (func.prototype && func.prototype.__class__ === func) {
  21276. return Reflect.construct(func, callArguments);
  21277. }
  21278. const obj = Object.create(func);
  21279. obj.__class__ = func;
  21280. if (obj.__init__ && typeof obj.__init__ === 'function') {
  21281. obj.__init__(...args);
  21282. }
  21283. return obj;
  21284. }
  21285. if (func.__class__ === builtins.function) {
  21286. if (func.__call__) {
  21287. return func.__call__(callArguments);
  21288. }
  21289. }
  21290. if (func.__class__ === builtins.method) {
  21291. if (func.__call__) {
  21292. return func.__call__([callTarget].concat(callArguments));
  21293. }
  21294. }
  21295. if (typeof func === 'function') {
  21296. return func.apply(callTarget, callArguments);
  21297. }
  21298. throw new python.Error('Unsupported call expression.');
  21299. }
  21300. apply(method, args, context) {
  21301. const locals = Array.prototype.slice.call(args);
  21302. context = new python.Execution.Context(context.globals, {});
  21303. args = method.args.posonlyargs.concat(method.args.args);
  21304. const default_pos = args.length - method.args.defaults.length;
  21305. for (let i = 0; i < method.args.args.length; i++) {
  21306. const arg = method.args.args[i];
  21307. let value = null;
  21308. if (locals.length > 0) {
  21309. value = locals.shift();
  21310. } else if (i >= default_pos) {
  21311. value = this.expression(method.args.defaults[i - default_pos], context);
  21312. } else {
  21313. throw new python.Error('Missing required positional argument.');
  21314. }
  21315. context.set(arg.arg, value);
  21316. }
  21317. return this.block(method.body, context);
  21318. }
  21319. block(statements, context) {
  21320. statements = Array.prototype.slice.call(statements);
  21321. while (statements.length > 0) {
  21322. const stmt = statements.shift();
  21323. const value = this.statement(stmt, context);
  21324. if (value !== undefined) {
  21325. return value;
  21326. }
  21327. }
  21328. return undefined;
  21329. }
  21330. statement(stmt, context) {
  21331. const ast = this.ast;
  21332. const builtins = this.builtins;
  21333. if (stmt instanceof ast.Pass) {
  21334. // pass
  21335. } else if (stmt instanceof ast.Constant) {
  21336. // pass
  21337. } else if (stmt instanceof ast.Return) {
  21338. return this.expression(stmt.value, context);
  21339. } else if (stmt instanceof ast.FunctionDef) {
  21340. const module = context.get('__name__');
  21341. /* eslint-disable consistent-this */
  21342. const self = this;
  21343. /* eslint-enable consistent-this */
  21344. const parent = context.get('__class__');
  21345. const type = (parent === builtins.module) ? builtins.function : builtins.method;
  21346. const func = {
  21347. __class__: type,
  21348. __globals__: context,
  21349. __module__: module,
  21350. __name__: stmt.name,
  21351. __code__: stmt,
  21352. __call__(args) {
  21353. return self.apply(this.__code__, args, this.__globals__);
  21354. }
  21355. };
  21356. context.set(stmt.name, func);
  21357. } else if (stmt instanceof ast.ClassDef) {
  21358. const bases = stmt.bases.map((base) => this.base(base, context));
  21359. if (bases.length > 1) {
  21360. throw new python.Error(`Unsupported multiple bases for class '${stmt.name}'.`);
  21361. }
  21362. const base = bases.length === 1 ? bases[0] : null;
  21363. const name = `${context.get('__name__')}.${stmt.name}`;
  21364. const value = this._createType(name, base ? class extends base {} : class {});
  21365. value.__bases__ = bases;
  21366. context.set(stmt.name, value);
  21367. this.block(stmt.body, new python.Execution.Context(context.globals, value.prototype));
  21368. } else if (stmt instanceof ast.AnnAssign) {
  21369. const target = this.identifier(stmt.target, context);
  21370. context.set(target, stmt.value ? this.expression(stmt.value, context) : undefined);
  21371. } else if (stmt instanceof ast.Assign) {
  21372. this.expression(stmt, context);
  21373. } else if (stmt instanceof ast.If) {
  21374. const test = this.expression(stmt.test, context);
  21375. if (test === true || test) {
  21376. const value = this.block(stmt.body, context);
  21377. if (value !== undefined) {
  21378. return value;
  21379. }
  21380. } else if (test === false) {
  21381. if (stmt.orelse) {
  21382. const value = this.block(stmt.orelse, context);
  21383. if (value !== undefined) {
  21384. return value;
  21385. }
  21386. }
  21387. } else {
  21388. throw new python.Error('Unsupported condition.');
  21389. }
  21390. } else if (stmt instanceof ast.For) {
  21391. if (stmt.target instanceof ast.Name && stmt.iter instanceof ast.Tuple === false) {
  21392. const range = this.expression(stmt.iter, context);
  21393. const variable = stmt.target;
  21394. for (const current of range) {
  21395. this.statement({ type: '=', target: variable, expression: { type: 'number', value: current } }, context);
  21396. const value = this.block(stmt.body.statements, context);
  21397. if (value !== undefined) {
  21398. return value;
  21399. }
  21400. }
  21401. } else {
  21402. throw new python.Error("Unsupported 'for' statement.");
  21403. }
  21404. } else if (stmt instanceof ast.While) {
  21405. const test = this.expression(stmt.test, context);
  21406. if (test) {
  21407. const value = this.block(stmt.body.statements, context);
  21408. if (value !== undefined) {
  21409. return value;
  21410. }
  21411. }
  21412. } else if (stmt instanceof ast.With) {
  21413. const items = [];
  21414. for (const item of stmt.items) {
  21415. items.push(this.expression(item.context_expr, context));
  21416. }
  21417. for (const item of items) {
  21418. if (item.__enter__ && item.__enter__.__call__) {
  21419. item.__enter__.__call__([item]);
  21420. }
  21421. }
  21422. const value = this.block(stmt.body, context);
  21423. for (const item of items) {
  21424. if (item.__exit__ && item.__exit__.__call__) {
  21425. item.__exit__.__call__([item]);
  21426. }
  21427. }
  21428. if (value !== undefined) {
  21429. return value;
  21430. }
  21431. } else if (stmt instanceof ast.Expr) {
  21432. this.expression(stmt.value, context);
  21433. } else if (stmt instanceof ast.Import) {
  21434. for (const alias of stmt.names) {
  21435. let module = this.__import__(alias.name, context);
  21436. if (alias.asname) {
  21437. const bits = alias.name.split('.').reverse();
  21438. bits.pop();
  21439. while (bits.length > 0) {
  21440. module = module[bits.pop()];
  21441. }
  21442. context.set(alias.asname, module);
  21443. } else {
  21444. context.set(alias.name.split('.')[0], module);
  21445. }
  21446. }
  21447. } else if (stmt instanceof ast.ImportFrom) {
  21448. const fromlist = stmt.names.map((name) => name.name);
  21449. const module = this.__import__(stmt.module, context.globals, context.locals, fromlist, stmt.level);
  21450. for (const entry of stmt.names) {
  21451. const name = entry.name;
  21452. const asname = entry.asname ? entry.asname : null;
  21453. if (!module[name]) {
  21454. throw new python.Error(`Cannot import '${name}' from '${stmt.module}'.`);
  21455. }
  21456. context.set(asname ? asname : name, module[name]);
  21457. }
  21458. } else {
  21459. throw new python.Error(`Unsupported statement '${stmt.__class__.__name__}'.`);
  21460. }
  21461. return undefined;
  21462. }
  21463. expression(expr, context) {
  21464. const ast = this.ast;
  21465. const builtins = this.builtins;
  21466. const typing = this.typing;
  21467. const self = context.get('self');
  21468. switch (expr.__class__.__name__) {
  21469. case 'Assign': {
  21470. const [target] = expr.targets;
  21471. if (target instanceof ast.Name) {
  21472. const value = this.expression(expr.value, context);
  21473. context.set(target.id, value);
  21474. return undefined;
  21475. } else if (target instanceof ast.Subscript) {
  21476. if (target.value instanceof ast.Name &&
  21477. target.slice instanceof ast.List &&
  21478. target.slice.elts.length === 1) {
  21479. const index = this.expression(target.slice.elts[0], context);
  21480. const id = target.value.id;
  21481. if (id === '__annotations__') {
  21482. context.set(id, context.get(id) || {});
  21483. }
  21484. const obj = context.get(id);
  21485. const value = this.expression(expr.value, context);
  21486. if (obj instanceof Map) {
  21487. obj.set(index, value);
  21488. } else {
  21489. obj[index] = value;
  21490. }
  21491. return undefined;
  21492. }
  21493. } else if (target instanceof ast.Attribute) {
  21494. const obj = this.expression(target.value, context);
  21495. const value = this.expression(expr.value, context);
  21496. obj[target.attr] = value;
  21497. return undefined;
  21498. } else if (target instanceof ast.Tuple) {
  21499. context.target.push(target.elts);
  21500. const value = this.expression(expr.value, context);
  21501. context.target.pop();
  21502. if (target.elts.every((elt) => elt instanceof ast.Name)) {
  21503. if (target.elts.length < value.length) {
  21504. throw new python.Error(`ValueError: too many values to unpack (expected ${target.value.length}, actual ${value.length}).`);
  21505. }
  21506. if (target.elts.length > value.length) {
  21507. throw new python.Error(`ValueError: not enough values to unpack (expected ${target.value.length}, actual ${value.length}).`);
  21508. }
  21509. for (let i = 0; i < value.length; i++) {
  21510. context.set(target.elts[i].id, value[i]);
  21511. }
  21512. return undefined;
  21513. }
  21514. }
  21515. break;
  21516. }
  21517. case 'List': {
  21518. return expr.elts.map((expr) => this.expression(expr, context));
  21519. }
  21520. case 'Constant': {
  21521. return expr.value;
  21522. }
  21523. case 'Subscript': {
  21524. if (expr.value instanceof ast.Name && expr.slice instanceof ast.Tuple === false) {
  21525. const id = expr.value.id;
  21526. if (context.get(id)) {
  21527. const index = this.expression(expr.slice, context);
  21528. const target = context.get(id);
  21529. if (target instanceof Map) {
  21530. return target.get(index);
  21531. }
  21532. return target[index < 0 ? target.length + index : index];
  21533. }
  21534. }
  21535. const value = this.expression(expr.value, context);
  21536. if (value && expr.slice instanceof ast.List &&
  21537. (value.__class__ === typing._TupleType ||
  21538. value.__class__ === typing._SpecialGenericAlias ||
  21539. value.__class__ === typing._SpecialForm)) {
  21540. const type = { ...value };
  21541. type.__args__ = expr.slice.elts.map((arg) => this.expression(arg, context));
  21542. return type;
  21543. }
  21544. if (expr.slice instanceof ast.List && expr.slice.elts.length === 1) {
  21545. const index = this.expression(expr.slice.elts[0], context);
  21546. if (value instanceof Map) {
  21547. return value.get(index);
  21548. }
  21549. return value[index < 0 ? value.length + index : index];
  21550. }
  21551. break;
  21552. }
  21553. case 'Attribute': {
  21554. const value = this.target(expr.value, context);
  21555. return value[expr.attr];
  21556. }
  21557. case 'Call': {
  21558. const func = expr.func;
  21559. if (func instanceof ast.Attribute) {
  21560. return this.call(func.value, func.attr, expr.args, expr.keywords, context, expr.range ? expr.range() : null);
  21561. }
  21562. return this.call(func, null, expr.args, expr.keywords, context, expr.range ? expr.range() : null);
  21563. }
  21564. case 'Name': {
  21565. const id = expr.id;
  21566. if (id === 'self') {
  21567. return self;
  21568. }
  21569. const type = (value) => {
  21570. return value &&
  21571. (value.__class__ === builtins.type ||
  21572. value.__class__ === typing._TupleType ||
  21573. value.__class__ === typing._SpecialGenericAlias ||
  21574. value.__class__ === typing._SpecialForm);
  21575. };
  21576. const builtin = builtins[id];
  21577. if (type(builtin)) {
  21578. return builtin;
  21579. }
  21580. const value = context.get(id);
  21581. if (value === undefined) {
  21582. const value = typing[id];
  21583. if (type(value)) {
  21584. return value;
  21585. }
  21586. }
  21587. return value;
  21588. }
  21589. case 'Tuple': {
  21590. return expr.elts.map((expr) => this.expression(expr, context));
  21591. }
  21592. case 'Dict': {
  21593. const dict = {};
  21594. for (let i = 0; i < expr.keys.length; i++) {
  21595. const key = this.expression(expr.keys[i], context);
  21596. const value = this.expression(expr.values[i], context);
  21597. dict[key] = value;
  21598. }
  21599. return dict;
  21600. }
  21601. case 'UnaryOp': {
  21602. if (expr.op instanceof ast.USub) {
  21603. return -this.expression(expr.operand, context);
  21604. }
  21605. throw new python.Error(`Unsupported unary expression '${expr.op}'.`);
  21606. }
  21607. case 'binary': {
  21608. switch (expr.op) {
  21609. case '==': {
  21610. return this.expression(expr.left, context) === this.expression(expr.right, context);
  21611. }
  21612. default: {
  21613. throw new python.Error(`Unsupported binary expression '${expr.op}'.`);
  21614. }
  21615. }
  21616. }
  21617. default: {
  21618. throw new python.Error(`Unsupported expression '${expr.type}'.`);
  21619. }
  21620. }
  21621. return undefined;
  21622. }
  21623. base(expr, context) {
  21624. return this.expression(expr, context);
  21625. }
  21626. identifier(expr) {
  21627. const ast = this.ast;
  21628. if (expr instanceof ast.Name) {
  21629. return expr.id;
  21630. }
  21631. if (expr instanceof ast.Attribute) {
  21632. return `${this.identifier(expr.value)}.${expr.attr}`;
  21633. }
  21634. return null;
  21635. }
  21636. target(expr, context) {
  21637. const ast = this.ast;
  21638. let current = expr;
  21639. let path = [];
  21640. for (;;) {
  21641. if (current instanceof ast.Attribute) {
  21642. path.push(current.attr);
  21643. current = current.value;
  21644. } else if (current instanceof ast.Name && current.id !== 'self' && current.id !== 'CONSTANTS') {
  21645. path.push(current.id);
  21646. break;
  21647. } else {
  21648. path = null;
  21649. break;
  21650. }
  21651. }
  21652. if (path) {
  21653. let target = null;
  21654. for (let i = path.length - 1; i >= 0; i--) {
  21655. const name = path[i];
  21656. if (target) {
  21657. target = target.__getattr__ ? target.__getattr__(name) : target[name];
  21658. } else {
  21659. target = context.get(name);
  21660. }
  21661. if (!target) {
  21662. break;
  21663. }
  21664. }
  21665. if (!target) {
  21666. path.reverse();
  21667. const name = path.join('.');
  21668. const file = `${path.join('/')}.py`;
  21669. if (this._sources.has(file)) {
  21670. target = this.import(name);
  21671. } else {
  21672. target = this.resolve(name);
  21673. }
  21674. }
  21675. return target;
  21676. }
  21677. return this.expression(expr, context);
  21678. }
  21679. add(name, source) {
  21680. this._sources.set(name, source);
  21681. }
  21682. on(event, listener) {
  21683. const value = this._events.get(event) || [];
  21684. value.push(listener);
  21685. this._events.set(event, value);
  21686. }
  21687. emit(event, ...args) {
  21688. if (this._events.has(event)) {
  21689. for (const callback of this._events.get(event)) {
  21690. callback(this, ...args);
  21691. }
  21692. }
  21693. }
  21694. register(name, value) {
  21695. if (!this._registry.has(name)) {
  21696. value = value || new (this._registry.get('builtins').module)(name);
  21697. this._registry.set(name, value);
  21698. let current = name;
  21699. for (;;) {
  21700. const index = current.lastIndexOf('.');
  21701. if (index === -1) {
  21702. break;
  21703. }
  21704. const child = current.substring(index + 1);
  21705. current = current.substring(0, index);
  21706. if (!value.__module__) {
  21707. value.__module__ = current;
  21708. }
  21709. const parent = this.register(current);
  21710. parent[child] = value;
  21711. value = parent;
  21712. }
  21713. }
  21714. return this._registry.get(name);
  21715. }
  21716. registerFunction(name, value) {
  21717. const builtins = this.builtins;
  21718. const index = name.lastIndexOf('.');
  21719. if (!value) {
  21720. value = () => {
  21721. throw new python.Error(`'${name}' is not implemented.`);
  21722. };
  21723. }
  21724. value.__class__ = builtins.function;
  21725. value.__name__ = index === -1 ? name : name.substring(index + 1);
  21726. value.__module__ = index === -1 ? '' : name.substring(0, index);
  21727. const module = this.register(value.__module__);
  21728. if (module[name]) {
  21729. throw new python.Error(`Function '${name}' is already registered.`);
  21730. }
  21731. module[value.__name__] = value;
  21732. return value;
  21733. }
  21734. registerOperator(name, value) {
  21735. this._operators.set(name, value);
  21736. }
  21737. _createType(name, value) {
  21738. const builtins = this.builtins;
  21739. const index = name.lastIndexOf('.');
  21740. value.__class__ = builtins.type;
  21741. value.__name__ = index === -1 ? name : name.substring(index + 1);
  21742. value.__module__ = index === -1 ? '' : name.substring(0, index);
  21743. value.prototype.__class__ = value;
  21744. return value;
  21745. }
  21746. registerType(name, value) {
  21747. value = this._createType(name, value);
  21748. const parts = name.split('.');
  21749. const memberName = parts.pop();
  21750. const moduleName = parts.join('.');
  21751. const module = this.register(moduleName);
  21752. if (module[memberName]) {
  21753. throw new python.Error(`Class '${memberName}' is already registered.`);
  21754. }
  21755. module[memberName] = value;
  21756. return value;
  21757. }
  21758. };
  21759. python.Execution.Context = class {
  21760. constructor(globals, locals) {
  21761. this.globals = globals;
  21762. this.locals = locals;
  21763. }
  21764. set(name, value) {
  21765. if (this.locals) {
  21766. this.locals[name] = value;
  21767. } else {
  21768. this.globals[name] = value;
  21769. }
  21770. }
  21771. get(name) {
  21772. if (this.locals && name in this.locals) {
  21773. return this.locals[name];
  21774. }
  21775. if (name in this.globals) {
  21776. return this.globals[name];
  21777. }
  21778. return undefined;
  21779. }
  21780. get target() {
  21781. this._target = this._target || [];
  21782. return this._target;
  21783. }
  21784. };
  21785. python.BinaryReader = class {
  21786. constructor(buffer) {
  21787. this._buffer = buffer;
  21788. this._length = buffer.length;
  21789. this._position = 0;
  21790. this._view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  21791. this._utf8Decoder = new TextDecoder('utf-8');
  21792. this._asciiDecoder = new TextDecoder('ascii');
  21793. }
  21794. get position() {
  21795. return this._position;
  21796. }
  21797. get length() {
  21798. return this._length;
  21799. }
  21800. seek(position) {
  21801. this._position = position >= 0 ? position : this._length + position;
  21802. if (this._position > this._buffer.length) {
  21803. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21804. }
  21805. }
  21806. skip(offset) {
  21807. this._position += offset;
  21808. if (this._position > this._buffer.length) {
  21809. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21810. }
  21811. }
  21812. stream(length) {
  21813. const buffer = this.read(length);
  21814. return new python.BinaryReader(buffer);
  21815. }
  21816. peek(length) {
  21817. const position = this._position;
  21818. length = length === undefined ? this._length - this._position : length;
  21819. this.skip(length);
  21820. const end = this._position;
  21821. this.skip(-length);
  21822. if (position === 0 && length === this._length) {
  21823. return this._buffer;
  21824. }
  21825. return this._buffer.subarray(position, end);
  21826. }
  21827. read(length) {
  21828. const position = this._position;
  21829. length = length === undefined ? this._length - this._position : length;
  21830. this.skip(length);
  21831. if (position === 0 && length === this._length) {
  21832. return this._buffer;
  21833. }
  21834. return this._buffer.subarray(position, this._position);
  21835. }
  21836. byte() {
  21837. const position = this._position;
  21838. this.skip(1);
  21839. return this._view.getUint8(position);
  21840. }
  21841. uint16() {
  21842. const position = this._position;
  21843. this.skip(2);
  21844. return this._view.getUint16(position, true);
  21845. }
  21846. int32() {
  21847. const position = this._position;
  21848. this.skip(4);
  21849. return this._view.getInt32(position, true);
  21850. }
  21851. uint32() {
  21852. const position = this._position;
  21853. this.skip(4);
  21854. return this._view.getUint32(position, true);
  21855. }
  21856. int64() {
  21857. const position = this._position;
  21858. this.skip(8);
  21859. return this._view.getBigInt64(position, true);
  21860. }
  21861. float64() {
  21862. const position = this._position;
  21863. this.skip(8);
  21864. return this._view.getFloat64(position, false);
  21865. }
  21866. string(size, encoding) {
  21867. const data = this.read(size);
  21868. return (encoding === 'utf-8') ?
  21869. this._utf8Decoder.decode(data) :
  21870. this._asciiDecoder.decode(data);
  21871. }
  21872. line() {
  21873. const index = this._buffer.indexOf(0x0A, this._position);
  21874. if (index === -1) {
  21875. throw new python.Error('Could not find end of line.');
  21876. }
  21877. const size = index - this._position;
  21878. const text = this.string(size, 'ascii');
  21879. this.skip(1);
  21880. return text;
  21881. }
  21882. };
  21883. python.StreamReader = class {
  21884. constructor(stream) {
  21885. this._stream = stream;
  21886. this._length = stream.length;
  21887. this._position = 0;
  21888. this._utf8Decoder = new TextDecoder('utf-8');
  21889. this._asciiDecoder = new TextDecoder('ascii');
  21890. }
  21891. get position() {
  21892. return this._position;
  21893. }
  21894. get length() {
  21895. return this._length;
  21896. }
  21897. seek(position) {
  21898. this._stream.seek(position);
  21899. this._position = this._stream.position;
  21900. }
  21901. skip(offset) {
  21902. this._position += offset;
  21903. if (this._position > this._length) {
  21904. throw new python.Error(`Expected ${this._position - this._length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21905. }
  21906. }
  21907. stream(length) {
  21908. this._stream.seek(this._position);
  21909. this.skip(length);
  21910. return this._stream.stream(length);
  21911. }
  21912. peek(length) {
  21913. this._stream.seek(this._position);
  21914. return this._stream.peek(length);
  21915. }
  21916. read(length) {
  21917. this._stream.seek(this._position);
  21918. this.skip(length);
  21919. return this._stream.read(length);
  21920. }
  21921. byte() {
  21922. const position = this._fill(1);
  21923. return this._view.getUint8(position);
  21924. }
  21925. uint16() {
  21926. const position = this._fill(2);
  21927. return this._view.getUint16(position, true);
  21928. }
  21929. int32() {
  21930. const position = this._fill(4);
  21931. return this._view.getInt32(position, true);
  21932. }
  21933. uint32() {
  21934. const position = this._fill(4);
  21935. return this._view.getUint32(position, true);
  21936. }
  21937. int64() {
  21938. const position = this._fill(8);
  21939. return this._view.getBigInt64(position, true);
  21940. }
  21941. float64() {
  21942. const position = this._fill(8);
  21943. return this._view.getFloat64(position, false);
  21944. }
  21945. string(size, encoding) {
  21946. const data = this.read(size);
  21947. return (encoding === 'utf-8') ?
  21948. this._utf8Decoder.decode(data) :
  21949. this._asciiDecoder.decode(data);
  21950. }
  21951. line() {
  21952. let position = this._fill(0);
  21953. let index = this._buffer.indexOf(0x0A, position);
  21954. if (index === -1) {
  21955. const size = Math.min(0x20000000, this._stream.length - this._position);
  21956. this._fill(size);
  21957. this.skip(-size);
  21958. position = this._fill(0);
  21959. index = this._buffer.indexOf(0x0A, position);
  21960. if (index === -1) {
  21961. throw new python.Error('Could not find end of line.');
  21962. }
  21963. }
  21964. const size = index - position;
  21965. const text = this.string(size, 'ascii');
  21966. this.skip(1);
  21967. return text;
  21968. }
  21969. _fill(length) {
  21970. if (this._position + length > this._length) {
  21971. throw new Error(`Expected ${this._position + length - this._length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21972. }
  21973. if (!this._buffer || this._position < this._offset || this._position + length > this._offset + this._buffer.length) {
  21974. this._offset = this._position;
  21975. this._stream.seek(this._offset);
  21976. const size = Math.max(length, Math.min(0x10000000, this._length - this._offset));
  21977. this._buffer = this._stream.read(size);
  21978. this._view = new DataView(this._buffer.buffer, this._buffer.byteOffset, this._buffer.byteLength);
  21979. }
  21980. const position = this._position;
  21981. this._position += length;
  21982. return position - this._offset;
  21983. }
  21984. };
  21985. python.Error = class extends Error {
  21986. constructor(message) {
  21987. super(message);
  21988. this.name = 'Python Error';
  21989. }
  21990. };
  21991. export const Execution = python.Execution;