python.js 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301
  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.Generator', class {});
  5706. this.registerType('torch._C._TensorBase', class extends builtins.object {});
  5707. this.registerType('torch._C._TensorMeta', class extends builtins.type {});
  5708. this.registerType('torch._C._VariableFunctionsClass', class extends builtins.object {});
  5709. this.registerType('torch._C.SchemaParser', class {
  5710. constructor(str, allow_typevars) {
  5711. this.L = new torch._C.Lexer(str);
  5712. this.type_parser = new torch._C.SchemaTypeParser(this.L, false, allow_typevars);
  5713. }
  5714. parseName() {
  5715. const L = this.L;
  5716. let name = L.expect('id').text();
  5717. if (L.nextIf(':')) {
  5718. L.expect(':');
  5719. name = `${name}::${L.expect('ident').text()}`;
  5720. }
  5721. let overload_name = '';
  5722. if (L.nextIf('.')) {
  5723. overload_name = L.expect('ident').text();
  5724. }
  5725. // const is_a_valid_overload_name = !((overload_name === "default") || (overload_name.rfind("__", 0) == 0));
  5726. // TORCH_CHECK(is_a_valid_overload_name, overload_name, " is not a legal overload name for aten operators");
  5727. return new torch._C.OperatorName(name, overload_name);
  5728. }
  5729. parseDeclaration() {
  5730. const L = this.L;
  5731. const name = this.parseName();
  5732. if (L.cur().kind !== '(') {
  5733. return name;
  5734. }
  5735. throw new python.Error('Not implemented.');
  5736. }
  5737. parseExactlyOneDeclaration() {
  5738. // const L = this.L;
  5739. const result = this.parseDeclaration();
  5740. // L.nextIf(TK_NEWLINE);
  5741. // L.expect(TK_EOF);
  5742. return result;
  5743. }
  5744. parseArgument(idx, is_return, kwarg_only) {
  5745. const L = this.L;
  5746. const type_parser = this.type_parser;
  5747. let [fake_type, real_type, alias_info] = type_parser.parseFakeAndRealType();
  5748. let N = null;
  5749. if (L.nextIf('[')) {
  5750. fake_type = torch.ListType.create(fake_type);
  5751. real_type = torch.ListType.create(real_type);
  5752. if (L.cur().kind === '#') {
  5753. N = Number(L.cur().text());
  5754. L.next();
  5755. }
  5756. L.expect(']');
  5757. let container = type_parser.parseAliasAnnotation();
  5758. if (alias_info) {
  5759. if (!container) {
  5760. container = new torch._C.AliasInfo();
  5761. container.is_write = alias_info.is_write;
  5762. }
  5763. container.addContainedType(alias_info);
  5764. }
  5765. alias_info = container;
  5766. if (L.nextIf('?')) {
  5767. fake_type = torch.OptionalType.create(fake_type);
  5768. real_type = torch.OptionalType.create(real_type);
  5769. }
  5770. }
  5771. let name = null;
  5772. /* eslint-disable no-undef-init */
  5773. let default_value = undefined;
  5774. /* eslint-enable no-undef-init */
  5775. if (is_return) {
  5776. kwarg_only = false;
  5777. if (L.cur().kind === 'id') {
  5778. name = L.next().text();
  5779. } else {
  5780. name = '';
  5781. }
  5782. } else {
  5783. name = L.expect('id').text();
  5784. if (L.nextIf('=')) {
  5785. default_value = this.parseDefaultValue(fake_type, fake_type.kind(), real_type, N);
  5786. }
  5787. }
  5788. return new torch.Argument(name, fake_type, real_type, N, default_value, kwarg_only, alias_info);
  5789. }
  5790. parseDefaultValue(arg_type, kind, real_type, arg_N) {
  5791. // auto range = L.cur().range;
  5792. const L = this.L;
  5793. const range = null;
  5794. switch (kind) {
  5795. case torch._C.TypeKind.StringType:
  5796. case torch._C.TypeKind.OptionalType:
  5797. case torch._C.TypeKind.NumberType:
  5798. case torch._C.TypeKind.IntType:
  5799. case torch._C.TypeKind.BoolType:
  5800. case torch._C.TypeKind.FloatType:
  5801. case torch._C.TypeKind.ComplexType:
  5802. return this.parseSingleConstant(arg_type, kind, real_type);
  5803. case torch._C.TypeKind.ListType: {
  5804. const elem_type = arg_type.containedType(0);
  5805. const real_elem_type = real_type.containedType(0);
  5806. if (L.cur().kind === 'id') {
  5807. return this.parseTensorDefault(range);
  5808. } else if (arg_N && L.cur().kind !== '[') {
  5809. const v = this.parseSingleConstant(elem_type, elem_type.kind(), real_elem_type);
  5810. const repeated = Array(arg_N).fill(v);
  5811. // std::vector<IValue> repeated(arg_N, v);
  5812. return this.convertToList(elem_type, elem_type.kind(), range, repeated);
  5813. }
  5814. return this.parseConstantList(elem_type, elem_type.kind(), real_elem_type);
  5815. }
  5816. case torch._C.TypeKind.DynamicType:
  5817. return this.parseDefaultValue(arg_type, arg_type.dynamicKind(), real_type, arg_N);
  5818. default:
  5819. throw new python.Error(`Unsupported default value kind '${kind}'.`);
  5820. }
  5821. }
  5822. parseSingleConstant(type, kind, real_type) {
  5823. const L = this.L;
  5824. if (kind === torch._C.TypeKind.DynamicType) {
  5825. return this.parseSingleConstant(type, type.dynamicKind(), real_type);
  5826. }
  5827. // const auto& str2dtype = c10::getStringToDtypeMap();
  5828. if (L.cur().kind === 'id') {
  5829. if (L.cur().text() === 'True') {
  5830. L.next();
  5831. return new torch._C.IValue(true);
  5832. }
  5833. if (L.cur().text() === 'False') {
  5834. L.next();
  5835. return new torch._C.IValue(false);
  5836. }
  5837. if (L.cur().text() === 'None') {
  5838. L.next();
  5839. return new torch._C.IValue();
  5840. }
  5841. } else if (L.cur().kind === 'string') {
  5842. const token = L.next();
  5843. return new torch._C.IValue(torch._C.parseStringLiteral(null, token.text()));
  5844. } else if (L.cur().kind === '#') {
  5845. let n = '';
  5846. if (L.nextIf('-')) {
  5847. n = `-${L.expect('#').text()}`; // # .text();
  5848. } else {
  5849. n = L.expect('#').text(); // # .text();
  5850. }
  5851. if (kind === torch._C.TypeKind.ComplexType || n.indexOf('j') !== -1) {
  5852. throw new Error("Complex type not implemented.");
  5853. /*
  5854. const imag = std::stod(n.substr(0, n.size() - 1));
  5855. return c10::complex<double>(0, imag);
  5856. */
  5857. } else if (kind === torch._C.TypeKind.FloatType || n.indexOf('.') !== -1 || n.indexOf('e') !== -1) {
  5858. const v = parseFloat(n);
  5859. return new torch._C.IValue(v, 'Double');
  5860. } else {
  5861. const v = parseInt(n, 10);
  5862. return new torch._C.IValue(v, 'Int');
  5863. }
  5864. }
  5865. throw new python.Error('Not implemented.');
  5866. /*
  5867. switch (L.cur().kind) {
  5868. case TK_TRUE:
  5869. L.next();
  5870. return true;
  5871. case TK_FALSE:
  5872. L.next();
  5873. return false;
  5874. case TK_NONE:
  5875. L.next();
  5876. return IValue();
  5877. case TK_STRINGLITERAL: {
  5878. const token = L.next();
  5879. return parseStringLiteral(token.range, token.text());
  5880. }
  5881. case TK_IDENT: {
  5882. const tok = L.next();
  5883. const text_view = tok.text_view();
  5884. // NB: float/complex/long are here for BC purposes. Other dtypes
  5885. // are handled via str2dtype.
  5886. // Please don't add more cases to this if-else block.
  5887. if ("float" == text_view) {
  5888. return static_cast<int64_t>("at::kFloat");
  5889. } else if ("complex" == text_view) {
  5890. return static_cast<int64_t>("at::kComplexFloat");
  5891. } else if ("long" == text_view) {
  5892. return static_cast<int64_t>("at::kLong");
  5893. } else if ("strided" == text_view) {
  5894. return static_cast<int64_t>("at::kStrided");
  5895. } else if ("Mean" == text_view) {
  5896. return static_cast<int64_t>("at::Reduction::Mean");
  5897. } else if ("contiguous_format" == text_view) {
  5898. return static_cast<int64_t>("c10::MemoryFormat::Contiguous");
  5899. } else {
  5900. const text = tok.text();
  5901. if (isPossiblyOptionalScalarType(real_type) &&
  5902. str2dtype.count(text) > 0) {
  5903. return static_cast<int64_t>(str2dtype.at(text));
  5904. } else {
  5905. throw(ErrorReport(L.cur().range) << "invalid numeric default value");
  5906. }
  5907. }
  5908. }
  5909. default: {
  5910. let n;
  5911. if (L.nextIf('-')) {
  5912. n = "-" + L.expect(TK_NUMBER).text();
  5913. }
  5914. else {
  5915. n = L.expect(TK_NUMBER).text();
  5916. }
  5917. if (kind == torch._C.TypeKind.ComplexType || n.find('j') != "std::string::npos") {
  5918. throw new python.Error('Complex type not implemented.');
  5919. const imag = std::stod(n.substr(0, n.size() - 1));
  5920. return c10::complex<double>(0, imag);
  5921. } else if (kind == torch._C.TypeKind.FloatType || n.find('.') != "std::string::npos" || n.find('e') != "std::string::npos") {
  5922. throw new python.Error('Float type not implemented.');
  5923. return std::stod(n);
  5924. } else {
  5925. throw new python.Error("'torch._C.SchemaParser.parseSingleConstant' not implemented.");
  5926. int64_t v = std::stoll(n);
  5927. return v;
  5928. }
  5929. }
  5930. }
  5931. */
  5932. }
  5933. parseConstantList(type, kind, real_type) {
  5934. const L = this.L;
  5935. const tok = L.expect('[');
  5936. const vs = [];
  5937. if (L.cur().kind !== ']') {
  5938. do {
  5939. vs.push(this.parseSingleConstant(type, kind, real_type));
  5940. } while (L.nextIf(','));
  5941. }
  5942. L.expect(']');
  5943. return this.convertToList(type, kind, tok.range, vs);
  5944. }
  5945. convertToList(type, kind, range, vs) {
  5946. switch (kind) {
  5947. case torch._C.TypeKind.ComplexType:
  5948. return new torch._C.IValue(new torch._C.List(torch.ComplexType.get(), vs.map((v) => v)));
  5949. case torch._C.TypeKind.FloatType:
  5950. return new torch._C.IValue(new torch._C.List(torch.FloatType.get(), vs.map((v) => v)));
  5951. case torch._C.TypeKind.IntType:
  5952. return new torch._C.IValue(new torch._C.List(torch.IntType.get(), vs.map((v) => v)));
  5953. case torch._C.TypeKind.BoolType:
  5954. return new torch._C.IValue(new torch._C.List(torch.BoolType.get(), vs.map((v) => v)));
  5955. case torch._C.TypeKindDynamicType:
  5956. return this.convertToList(type.dynamicKind(), range, vs);
  5957. default:
  5958. // throw(ErrorReport(range) << "lists are only supported for float, int and complex types");
  5959. throw new python.Error('lists are only supported for float, int and complex types');
  5960. }
  5961. }
  5962. });
  5963. this.registerType('torch.FunctionSchema', class {
  5964. constructor(name, overload_name, args, returns, is_vararg, is_varret) {
  5965. const index = name.indexOf('(');
  5966. if (index === -1) {
  5967. this._name = name;
  5968. this._overload_name = overload_name || '';
  5969. this._arguments = args || [];
  5970. this._returns = returns || [];
  5971. this._is_vararg = is_vararg || false;
  5972. this._is_varret = is_varret || false;
  5973. } else {
  5974. const value = name.substring(0, index).trim();
  5975. const dot = value.indexOf('.');
  5976. if (dot === -1) {
  5977. this._name = value;
  5978. this._overload_name = '';
  5979. } else {
  5980. this._name = value.substring(0, dot);
  5981. this._overload_name = value.substring(dot + 1, value.length);
  5982. }
  5983. this._buffer = name.substring(index, name.length);
  5984. }
  5985. }
  5986. static parse(schema) {
  5987. return new torch.FunctionSchema(schema);
  5988. }
  5989. get name() {
  5990. return this._name;
  5991. }
  5992. get overload_name() {
  5993. return this._overload_name;
  5994. }
  5995. get arguments() {
  5996. this._parse();
  5997. return this._arguments;
  5998. }
  5999. get returns() {
  6000. this._parse();
  6001. return this._returns;
  6002. }
  6003. get is_vararg() {
  6004. this._parse();
  6005. return this._is_vararg;
  6006. }
  6007. get is_varret() {
  6008. this._parse();
  6009. return this._is_varret;
  6010. }
  6011. argumentIndexWithName(name) {
  6012. const index = this.arguments.findIndex((arg) => arg.name === name);
  6013. return index === -1 ? null : index;
  6014. }
  6015. _parse() {
  6016. if (this._buffer) {
  6017. const parser = new torch._C.SchemaParser(this._buffer, true /* parseSchemaOrName */);
  6018. const L = parser.L;
  6019. this._arguments = [];
  6020. this._is_vararg = false;
  6021. this._kwarg_only = false;
  6022. let idx = 0;
  6023. L.expect('(');
  6024. if (!L.nextIf(')')) {
  6025. while (true) {
  6026. if (this._is_vararg) {
  6027. throw new python.Error("Unexpected 'torch.FunctionSchema._is_vararg'.");
  6028. }
  6029. if (L.nextIf('*')) {
  6030. this._kwarg_only = true;
  6031. } else if (L.nextIf('...')) {
  6032. this._is_vararg = true;
  6033. } else {
  6034. const argument = parser.parseArgument(idx++, false, this._kwarg_only);
  6035. this._arguments.push(argument);
  6036. }
  6037. if (!L.nextIf(',')) {
  6038. break;
  6039. }
  6040. }
  6041. L.expect(')');
  6042. }
  6043. L.expect('->');
  6044. this._returns = [];
  6045. this._is_varret = false;
  6046. if (L.nextIf('...')) {
  6047. this._is_varret = true;
  6048. } else if (L.nextIf('(')) {
  6049. if (!L.nextIf(')')) {
  6050. while (true) {
  6051. if (this._is_varret) {
  6052. throw new python.Error("Unexpected 'torch.FunctionSchema._is_varret'.");
  6053. }
  6054. if (L.nextIf('...')) {
  6055. this._is_varret = true;
  6056. } else {
  6057. const argument = parser.parseArgument(idx++, true, false);
  6058. this._returns.push(argument);
  6059. }
  6060. if (!L.nextIf(',')) {
  6061. break;
  6062. }
  6063. }
  6064. L.expect(')');
  6065. }
  6066. } else {
  6067. this._returns.push(parser.parseArgument(0, true, false));
  6068. }
  6069. delete this._buffer;
  6070. }
  6071. }
  6072. __str__() {
  6073. const list = [this.name];
  6074. const overload_name = this.overload_name;
  6075. if (overload_name !== '' && overload_name !== 'default') {
  6076. list.push(`.${this.overload_name}`);
  6077. }
  6078. list.push('(');
  6079. let first = true;
  6080. let kwarg_only = false;
  6081. for (const argument of this.arguments) {
  6082. if (!first) {
  6083. list.push(', ');
  6084. }
  6085. if (argument.kwarg_only && !kwarg_only) {
  6086. list.push('*, ');
  6087. kwarg_only = true;
  6088. }
  6089. first = false;
  6090. list.push(argument.str());
  6091. }
  6092. if (this.is_vararg) {
  6093. if (!first) {
  6094. list.push(', ');
  6095. }
  6096. first = true;
  6097. list.push('...');
  6098. }
  6099. list.push(') -> ');
  6100. const returns = this.returns;
  6101. const braces = !this.is_varret &&
  6102. (returns.length !== 1 ||
  6103. returns[0].name ||
  6104. returns[0].real_type instanceof torch.TupleType ||
  6105. returns[0].real_type instanceof torch.ListType && returns[0].real_type.getElementType() instanceof torch.TupleType);
  6106. if (braces) {
  6107. list.push('(');
  6108. }
  6109. first = true;
  6110. for (const argument of this.returns) {
  6111. if (!first) {
  6112. list.push(', ');
  6113. }
  6114. first = false;
  6115. list.push(argument.str());
  6116. }
  6117. if (this.is_varret) {
  6118. if (!first) {
  6119. list.push(', ');
  6120. }
  6121. first = true;
  6122. list.push('...');
  6123. }
  6124. if (braces) {
  6125. list.push(')');
  6126. }
  6127. return list.join('');
  6128. }
  6129. aliasAnalysis() {
  6130. return this._alias_kind || 'CONSERVATIVE';
  6131. }
  6132. setAliasAnalysis(v) {
  6133. this._alias_kind = v;
  6134. }
  6135. hasAnyAliasInfo() {
  6136. for (const arg of this.arguments) {
  6137. if (arg.alias_info !== null) {
  6138. return true;
  6139. }
  6140. }
  6141. for (const ret of this.returns) {
  6142. if (ret.alias_info !== null) {
  6143. return true;
  6144. }
  6145. }
  6146. return false;
  6147. }
  6148. is_mutable() {
  6149. return this.arguments.some((arg) => {
  6150. const aliasInfo = arg.alias_info;
  6151. return aliasInfo && aliasInfo.is_write;
  6152. });
  6153. }
  6154. });
  6155. this.registerType('torch._C.SchemaInfo', class {
  6156. constructor(schema) {
  6157. this._schema = schema;
  6158. this._alias_maps_current = false;
  6159. this._has_init = false;
  6160. }
  6161. is_nondeterministic() {
  6162. if (this._schema.name === 'aten::dropout' && this._schema.overload === '') {
  6163. //
  6164. }
  6165. torch._C.nondeterministic_op_strings = torch._C.nondeterministic_op_strings || new Set([
  6166. 'aten::dropout(Tensor input, float p, bool train) -> Tensor',
  6167. 'aten::_fused_dropout(Tensor self, float p, Generator? generator) -> (Tensor, Tensor)',
  6168. 'aten::_standard_gamma(Tensor self, Generator? generator) -> Tensor',
  6169. 'aten::bernoulli(Tensor self, *, Generator? generator) -> Tensor',
  6170. 'aten::bernoulli(Tensor self, float p, *, Generator? generator) -> Tensor',
  6171. 'aten::multinomial(Tensor self, int num_samples, bool replacement, *, Generator? generator) -> Tensor',
  6172. 'aten::native_dropout(Tensor input, float p, bool? train) -> (Tensor, Tensor)',
  6173. 'aten::normal(Tensor mean, Tensor std, *, Generator? generator) -> Tensor',
  6174. 'aten::normal(float mean, Tensor std, *, Generator? generator) -> Tensor',
  6175. 'aten::normal(Tensor mean, float std, *, Generator? generator) -> Tensor',
  6176. 'aten::poisson(Tensor self, Generator? generator) -> Tensor',
  6177. 'aten::binomial(Tensor count, Tensor prob, Generator? generator=None) -> Tensor',
  6178. 'aten::rrelu(Tensor self, Scalar lower, Scalar upper, bool training, Generator? generator) -> Tensor',
  6179. 'aten::rrelu_with_noise(Tensor self, Tensor noise, Scalar lower, Scalar upper, bool training, Generator? generator) -> Tensor',
  6180. 'aten::rand(int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6181. 'aten::rand_like(Tensor self, *, int? dtype=None, int? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor',
  6182. 'aten::randint(int high, int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6183. 'aten::randint(int low, int high, int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6184. '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',
  6185. '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',
  6186. 'aten::randn(int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6187. 'aten::randn_like(Tensor self, *, int? dtype=None, int? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor',
  6188. 'aten::randperm(int n, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor'
  6189. ]);
  6190. if (torch._C.nondeterministic_op_strings.has(this._schema.__str__())) {
  6191. return true;
  6192. }
  6193. /*
  6194. const auto& op = c10::Dispatcher::singleton().findOp(
  6195. c10::OperatorName(schema_.name(), schema_.overload_name()));
  6196. return op && op->hasTag(at::Tag::nondeterministic_seeded);
  6197. */
  6198. return false;
  6199. }
  6200. });
  6201. this.registerType('torch._C.OperatorRegistry', class {
  6202. constructor() {
  6203. this.to_register = [];
  6204. this.operators = new Map();
  6205. }
  6206. registerPendingOperators() {
  6207. for (const op of this.to_register) {
  6208. const sym = op.schema().name;
  6209. if (!this.operators.has(sym)) {
  6210. this.operators.set(sym, []);
  6211. }
  6212. this.operators.get(sym).push(op);
  6213. }
  6214. this.to_register = [];
  6215. }
  6216. registerOperator(op) {
  6217. this.to_register.push(op);
  6218. }
  6219. getOperators(name) {
  6220. this.registerPendingOperators();
  6221. if (this.operators.has(name)) {
  6222. return this.operators.get(name);
  6223. }
  6224. return [];
  6225. }
  6226. });
  6227. this.registerFunction('torch._C.getAllOperatorsFor', (name) => {
  6228. return torch._C.getRegistry().getOperators(name);
  6229. });
  6230. this.registerType('torch._C.Operator', class {
  6231. constructor(schema) {
  6232. this._schema = schema;
  6233. }
  6234. schema() {
  6235. return this._schema;
  6236. }
  6237. getOperation(/* node */) {
  6238. return null;
  6239. }
  6240. aliasAnalysisKind() {
  6241. const schemaRef = this.schema();
  6242. const alias_analysis = schemaRef.aliasAnalysis();
  6243. torch._C.TORCH_CHECK(alias_analysis === 'FROM_SCHEMA' || !schemaRef.hasAnyAliasInfo());
  6244. return alias_analysis;
  6245. }
  6246. });
  6247. this.registerFunction('torch._C.getRegistry', () => {
  6248. torch._C.r = torch._C.r || new torch._C.OperatorRegistry();
  6249. return torch._C.r;
  6250. });
  6251. this.registerFunction('torch._C._get_schema', (op_name, overload_name) => {
  6252. const operations = torch._C.getAllOperatorsFor(op_name);
  6253. for (const op of operations) {
  6254. if (op.schema().overload_name === overload_name) {
  6255. return op.schema();
  6256. }
  6257. }
  6258. throw new python.Error(`Schema '${op_name}.${overload_name}' not found.`);
  6259. });
  6260. this.registerFunction('torch._C._jit_get_schemas_for_operator', (op_name) => {
  6261. return torch._C.getAllOperatorsFor(op_name).map((op) => op.schema());
  6262. });
  6263. this.registerFunction('torch._C._jit_get_operation', (op_name) => {
  6264. const sortedOps = torch._C.getAllOperatorsFor(op_name);
  6265. if (sortedOps.length === 0) {
  6266. return [null, null];
  6267. }
  6268. const overload_names = sortedOps.map((op) => op.schema().overload_name);
  6269. return [{}, overload_names];
  6270. });
  6271. this.registerFunction('torch._C._get_operation_overload', (op_name, overload_name) => {
  6272. const operations = torch._C.getAllOperatorsFor(op_name);
  6273. for (const op of operations) {
  6274. if (op.schema().overload_name === overload_name) {
  6275. return [{}, {}, null];
  6276. }
  6277. }
  6278. return null;
  6279. });
  6280. this.registerFunction('torch._C._unset_dispatch_mode', () => {
  6281. return null;
  6282. });
  6283. this.registerFunction('torch._C._set_dispatch_mode', () => {
  6284. });
  6285. this.registerType('torch._C.MatchedSchema', class {
  6286. constructor(inputs, return_types, return_field_names, schema_name) {
  6287. this.inputs = inputs;
  6288. this.return_types = return_types;
  6289. this.register_field_names = return_field_names;
  6290. this.schema_name = schema_name;
  6291. }
  6292. });
  6293. this.registerType('torch._C.Self', class {
  6294. });
  6295. this.registerFunction('torch._C.toValues', (g, nvs) => {
  6296. return nvs.map((v) => v.value(g));
  6297. });
  6298. this.registerType('torch._C.SimpleSelf', class extends torch._C.Self {
  6299. constructor(classType) {
  6300. super();
  6301. this._classType = classType;
  6302. }
  6303. makeSugared(v) {
  6304. v.setType(this._classType);
  6305. return new torch._C.SimpleValue(v);
  6306. }
  6307. getClassType() {
  6308. return this._classType;
  6309. }
  6310. });
  6311. this.registerType('torch._C.Function', class {
  6312. isGraphFunction() {
  6313. return false;
  6314. }
  6315. name() {
  6316. return this.qualname().name();
  6317. }
  6318. });
  6319. this.registerType('torch._C.BuiltinOpFunction', class extends torch._C.Function {
  6320. constructor(qualname, schema) {
  6321. super();
  6322. this._name = qualname;
  6323. this._schema = schema;
  6324. }
  6325. qualname() {
  6326. return this._name;
  6327. }
  6328. getSchema() {
  6329. return this._schema;
  6330. }
  6331. ensure_defined() {
  6332. }
  6333. });
  6334. this.registerType('torch._C.DeadCodeEliminator', class {
  6335. constructor(...args) {
  6336. this._aliasDb = null;
  6337. this._useAliasDb = false;
  6338. this._memo = new Map();
  6339. this._marked = new Set();
  6340. this._liveValues = new Set();
  6341. this._deleteCallback = () => {};
  6342. if (args.length > 0 && args[0] instanceof torch.Graph) {
  6343. [this._graph, this._sideEffectPolicy] = args;
  6344. this._useAliasDb = true;
  6345. } else {
  6346. [this._sideEffectPolicy] = args;
  6347. }
  6348. }
  6349. run(block, recurse) {
  6350. this.eliminateDeadForkInputs(block, recurse);
  6351. this.mark(block.return_node());
  6352. this.mark(block);
  6353. this._deleteCallback(this._liveValues);
  6354. this.sweep(block, recurse);
  6355. }
  6356. setDeleteCallback(deleteCallback) {
  6357. this._deleteCallback = deleteCallback;
  6358. }
  6359. eliminateDeadForkInputs(block, recurse) {
  6360. for (const node of block.nodes()) {
  6361. if (recurse) {
  6362. for (const sb of node.blocks()) {
  6363. this.eliminateDeadForkInputs(sb, recurse);
  6364. }
  6365. }
  6366. if (node.kind() !== 'prim::fork') {
  6367. continue;
  6368. }
  6369. const g = node.g("Subgraph");
  6370. for (let i = 0; i < g.inputs().length; i++) {
  6371. if (!g.inputs()[i].hasUses()) {
  6372. g.eraseInput(i);
  6373. node.removeInput(i);
  6374. }
  6375. }
  6376. }
  6377. }
  6378. markReturnNode(node) {
  6379. if (this._marked.has(node)) {
  6380. return false;
  6381. }
  6382. torch._C.AT_ASSERT(node.owningBlock().return_node() === node);
  6383. const outerNode = node.owningBlock().owningNode();
  6384. if (outerNode === null || outerNode.kind() === 'prim::Reverse') {
  6385. return this.mark(node);
  6386. }
  6387. if (outerNode.kind() === 'prim::Loop' || outerNode.kind() === 'c10::onnx::Loop') {
  6388. const loop = new torch._C.LoopView(outerNode);
  6389. for (let i = 0; i < loop.carriedOutputs().length; i++) {
  6390. if (outerNode.kind() === 'onnx::Loop') {
  6391. this._liveValues.add(loop.bodyCarriedOutputs()[i]);
  6392. continue;
  6393. }
  6394. const innerInput = loop.bodyCarriedInputs()[i];
  6395. const innerOutput = loop.bodyCarriedOutputs()[i];
  6396. const outerOutput = loop.carriedOutputs()[i];
  6397. if (this._liveValues.has(outerOutput) || innerInput.hasUses()) {
  6398. this._liveValues.add(innerOutput);
  6399. }
  6400. }
  6401. this._liveValues.add(loop.nextCond());
  6402. } else {
  6403. torch._C.AT_ASSERT(outerNode.outputs().length === node.inputs().length);
  6404. for (let i = 0; i < outerNode.outputs().length; i++) {
  6405. const innerOutput = node.inputs()[i];
  6406. const outerOutput = outerNode.outputs()[i];
  6407. if (!this._liveValues.has(outerOutput)) {
  6408. this._liveValues.add(innerOutput);
  6409. }
  6410. }
  6411. }
  6412. this._marked.add(node);
  6413. return true;
  6414. }
  6415. markLoop(node) {
  6416. torch._C.TORCH_INTERNAL_ASSERT(node.kind() === 'prim::Loop');
  6417. let marked = false;
  6418. let anyMarked = false;
  6419. do {
  6420. marked = this.mark(node.blocks().at(0));
  6421. anyMarked = anyMarked || marked;
  6422. } while (marked);
  6423. return anyMarked;
  6424. }
  6425. mark(...args) {
  6426. if (args.length === 1 && args[0] instanceof torch.Block) {
  6427. const [block] = args;
  6428. let anyMarked = false;
  6429. for (const node of block.nodes()) {
  6430. if (this._sideEffectPolicy === 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS' && this.hasSideEffects(node)) {
  6431. const marked = this.mark(node);
  6432. anyMarked = anyMarked || marked;
  6433. }
  6434. }
  6435. const marked = this.markReturnNode(block.return_node());
  6436. anyMarked = anyMarked || marked;
  6437. for (const node of block.nodes()) {
  6438. if (node.kind() === 'prim::Loop') {
  6439. const marked = this.markLoop(node);
  6440. anyMarked = anyMarked || marked;
  6441. } else {
  6442. for (const subBlock of node.blocks()) {
  6443. const marked = this.mark(subBlock);
  6444. anyMarked = anyMarked || marked;
  6445. }
  6446. }
  6447. const marked = this.markIfLive(node);
  6448. anyMarked = anyMarked || marked;
  6449. }
  6450. return anyMarked;
  6451. }
  6452. if (args.length === 1 && args[0] instanceof torch.Node) {
  6453. const [node] = args;
  6454. if (this._marked.has(node)) {
  6455. return false;
  6456. }
  6457. this._marked.add(node);
  6458. let curNode = node;
  6459. while (curNode && curNode.owningBlock()) {
  6460. this.mark(curNode);
  6461. curNode = curNode.owningBlock().owningNode();
  6462. }
  6463. for (const input of node.inputs()) {
  6464. if (!this._liveValues.has(input)) {
  6465. this._liveValues.add(input);
  6466. }
  6467. }
  6468. return true;
  6469. }
  6470. throw new python.Error('Not implemented.');
  6471. }
  6472. markIfLive(node) {
  6473. for (const output of node.outputs()) {
  6474. if (this._liveValues.has(output)) {
  6475. return this.mark(node);
  6476. }
  6477. }
  6478. if (this._useAliasDb) {
  6479. if (this.getOrCreateAliasDb().writesToAlias(node, this._liveValues)) {
  6480. return this.mark(node);
  6481. }
  6482. }
  6483. return false;
  6484. }
  6485. sweep(block, recurse) {
  6486. const nodes = Array.from(block.nodes()).reverse();
  6487. for (const node of nodes) {
  6488. this.removeDeadBlockOutputs(node);
  6489. this.removeDeadLoopOutputs(node);
  6490. if (recurse) {
  6491. for (const block of node.blocks()) {
  6492. this.sweep(block, true);
  6493. }
  6494. }
  6495. if (!this._marked.has(node) && !node.hasUses()) {
  6496. node.destroy();
  6497. }
  6498. }
  6499. }
  6500. hasUntrackedMutation(node) {
  6501. if (!this._useAliasDb) {
  6502. if (node.kind() === 'prim::SetAttr') {
  6503. return true;
  6504. }
  6505. const schema = node.maybeSchema();
  6506. return schema && schema.is_mutable();
  6507. }
  6508. return this.getOrCreateAliasDb().writesToWildcard(node);
  6509. }
  6510. hasSideEffects(node) {
  6511. const it = this._memo.get(node);
  6512. if (it) {
  6513. return it;
  6514. }
  6515. const has_side_effects = node.hasSideEffects() ||
  6516. node.blocks().some((b) => Array.from(b.nodes()).some((n) => this.hasSideEffects(n))) ||
  6517. this.hasUntrackedMutation(node);
  6518. this._memo.set(node, has_side_effects);
  6519. return has_side_effects;
  6520. }
  6521. removeDeadBlockOutputs(node) {
  6522. if (node.kind() !== 'prim::If' && node.kind() !== 'prim::GradOf') {
  6523. return;
  6524. }
  6525. for (let i_1 = node.outputs().length; i_1 > 0; i_1--) {
  6526. const i = i_1 - 1;
  6527. if (!node.outputs()[i].hasUses()) {
  6528. node.eraseOutput(i);
  6529. for (const b of node.blocks()) {
  6530. b.eraseOutput(i);
  6531. }
  6532. }
  6533. }
  6534. }
  6535. removeDeadLoopOutputs() {
  6536. }
  6537. getOrCreateAliasDb() {
  6538. if (!this._aliasDb) {
  6539. this._aliasDb = new torch._C.AliasDb(this._graph);
  6540. }
  6541. return this._aliasDb;
  6542. }
  6543. });
  6544. this.registerFunction('torch._C.EliminateDeadCode', (...args) => {
  6545. if (args.length === 1 && args[0] instanceof torch.Graph) {
  6546. const [graph] = args;
  6547. const sideEffectPolicy = 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS';
  6548. const worker = new torch._C.DeadCodeEliminator(graph, sideEffectPolicy);
  6549. worker.run(graph.block(), /*recurse=*/true);
  6550. } else if (args.length > 0 && args[0] instanceof torch.Block) {
  6551. const [block] = args;
  6552. const recurse = false;
  6553. const sideEffectPolicy = 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS';
  6554. const worker = new torch._C.DeadCodeEliminator(sideEffectPolicy);
  6555. worker.run(block, recurse);
  6556. } else {
  6557. throw new python.Error('Not implemented.');
  6558. }
  6559. });
  6560. this.registerFunction('torch._C.removeTupleNodes', () => {
  6561. });
  6562. this.registerFunction('torch._C.LowerSimpleTuples', (...args) => {
  6563. if (args.length === 1 && args[0] instanceof torch.Graph) {
  6564. const [graph] = args;
  6565. torch._C.LowerSimpleTuples(graph.block());
  6566. torch._C.EliminateDeadCode(graph);
  6567. } else if (args.length === 1 && args[0] instanceof torch.Block) {
  6568. const [block] = args;
  6569. for (const n of block.nodes()) {
  6570. torch._C.removeTupleNodes(n, false);
  6571. for (const b of n.blocks()) {
  6572. torch._C.LowerSimpleTuples(b);
  6573. }
  6574. }
  6575. } else {
  6576. throw new python.Error('Not implemented.');
  6577. }
  6578. });
  6579. this.registerFunction('torch._C.attributesEqualCSE', (lhs, rhs) => {
  6580. torch._C.AT_ASSERT(lhs !== null);
  6581. torch._C.AT_ASSERT(rhs !== null);
  6582. if (lhs.hasAttributes() !== rhs.hasAttributes()) {
  6583. return false;
  6584. }
  6585. if (!lhs.hasAttributes() && !rhs.hasAttributes()) {
  6586. return true;
  6587. }
  6588. const lnames = lhs.attributeNames();
  6589. const rnames = rhs.attributeNames();
  6590. lnames.sort();
  6591. rnames.sort();
  6592. if (lnames.length !== rnames.length && !lnames.every((v, i) => v !== rnames[i])) {
  6593. return false;
  6594. }
  6595. for (const name of lnames) {
  6596. if (lhs.kindOf(name) !== rhs.kindOf(name)) {
  6597. return false;
  6598. }
  6599. const kind = lhs.kindOf(name);
  6600. switch (kind) {
  6601. case 'i':
  6602. case 'f':
  6603. case 's':
  6604. case 't': {
  6605. if (lhs[kind](name) !== rhs[kind](name)) {
  6606. return false;
  6607. }
  6608. break;
  6609. }
  6610. case 'c': {
  6611. const lc = lhs.c(name);
  6612. const rc = rhs.c(name);
  6613. if (lc.real !== rc.real || lc.imag !== rc.imag) {
  6614. return false;
  6615. }
  6616. break;
  6617. }
  6618. case 'ival': {
  6619. if (lhs[kind](name) !== rhs[kind](name)) {
  6620. return false;
  6621. }
  6622. break;
  6623. }
  6624. default: {
  6625. throw new python.Error('Not implemented.');
  6626. }
  6627. }
  6628. }
  6629. return true;
  6630. });
  6631. this.registerFunction('torch._C.get_hash', (...args) => {
  6632. let hash = 0;
  6633. for (const value of args) {
  6634. if (typeof value === 'number') {
  6635. hash += (value | 0);
  6636. } else if (typeof value === 'string') {
  6637. hash += (value.length | 0);
  6638. } else if (Array.isArray(value)) {
  6639. for (const item of value) {
  6640. hash += torch._C.get_hash(item);
  6641. }
  6642. } else if (value instanceof builtins.complex) {
  6643. hash += (value.real | 0) + (value.imag | 0);
  6644. }
  6645. }
  6646. return hash;
  6647. });
  6648. this.registerFunction('torch._C.HashNode', (k) => {
  6649. torch._C.AT_ASSERT(k !== null);
  6650. let constant_hash = 0;
  6651. if (k.kind() === 'prim::Constant') {
  6652. const type = k.output().type();
  6653. if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'i') {
  6654. constant_hash = k.i('value');
  6655. } else if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'f') {
  6656. constant_hash = k.f('value');
  6657. } else if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'c') {
  6658. constant_hash = k.c('value');
  6659. } else if (type.isSubtypeOf(torch.BoolType.get())) {
  6660. constant_hash = k.i('value');
  6661. }
  6662. }
  6663. return torch._C.get_hash(k.kind(), k.outputs().map((v) => v.type().kind()), k.inputs().map((v) => v.unique()), constant_hash);
  6664. });
  6665. this.registerFunction('torch._C.EqualNode', (lhs, rhs) => {
  6666. if (lhs === null && rhs === null) {
  6667. return true;
  6668. }
  6669. if (lhs === null || rhs === null) {
  6670. return false;
  6671. }
  6672. if (lhs.kind() !== rhs.kind()) {
  6673. return false;
  6674. }
  6675. const lhs_outputs = lhs.outputs();
  6676. const rhs_outputs = rhs.outputs();
  6677. if (lhs_outputs.length !== rhs_outputs.length) {
  6678. return false;
  6679. }
  6680. for (let i = 0; i < lhs_outputs.length; i++) {
  6681. const lt = lhs_outputs[i].type();
  6682. const rt = rhs_outputs[i].type();
  6683. if (!lt.equals(rt)) {
  6684. return false;
  6685. }
  6686. }
  6687. const lhs_inputs = lhs.inputs();
  6688. const rhs_inputs = rhs.inputs();
  6689. if (lhs_inputs.length !== rhs_inputs.length) {
  6690. return false;
  6691. }
  6692. if (!lhs_inputs.every((v, i) => v === rhs_inputs[i])) {
  6693. return false;
  6694. }
  6695. if (!torch._C.attributesEqualCSE(lhs, rhs)) {
  6696. return false;
  6697. }
  6698. if (lhs.blocks().length !== rhs.blocks().length) {
  6699. return false;
  6700. }
  6701. for (let i = 0; i < lhs.blocks().length; i++) {
  6702. if (lhs.blocks().at(i) !== rhs.blocks().at(i)) {
  6703. return false;
  6704. }
  6705. }
  6706. return true;
  6707. });
  6708. this.registerType('torch._C.NodeSet', class {
  6709. constructor() {
  6710. this._nodes = new Map();
  6711. }
  6712. insert(n) {
  6713. const key = torch._C.HashNode(n);
  6714. if (this._nodes.has(key)) {
  6715. this._nodes.get(key).push(n);
  6716. } else {
  6717. this._nodes.set(key, [n]);
  6718. }
  6719. }
  6720. get(n) {
  6721. const key = torch._C.HashNode(n);
  6722. if (this._nodes.has(key)) {
  6723. const nodes = this._nodes.get(key);
  6724. for (const node of nodes) {
  6725. if (torch._C.EqualNode(node, n)) {
  6726. return node;
  6727. }
  6728. }
  6729. }
  6730. return null;
  6731. }
  6732. has(n) {
  6733. return this.get(n) !== null;
  6734. }
  6735. });
  6736. this.registerFunction('torch._C.isinstance', (stack, types) => {
  6737. const ty = stack.pop().type();
  6738. for (const candidate of types) {
  6739. if (ty.isSubtypeOf(candidate)) {
  6740. stack.push(new torch._C.IValue(true, 'Bool'));
  6741. stack.push(true);
  6742. return;
  6743. }
  6744. }
  6745. stack.push(new torch._C.IValue(false, 'Bool'));
  6746. });
  6747. this.registerType('torch._C.Tuple', class {
  6748. constructor(elements) {
  6749. this._elements = elements;
  6750. }
  6751. static create(elements) {
  6752. return new torch._C.Tuple(elements);
  6753. }
  6754. elements() {
  6755. return this._elements;
  6756. }
  6757. });
  6758. this.registerFunction('torch._C.tupleConstruct', (stack, num_inputs) => {
  6759. torch._C.TORCH_CHECK(num_inputs <= stack.length);
  6760. const elems = stack.splice(stack.length - num_inputs, num_inputs);
  6761. const tuple = torch._C.Tuple.create(elems.reverse());
  6762. stack.push(new torch._C.IValue(tuple));
  6763. });
  6764. this.registerFunction('torch._C.runNodeIfInputsAreConstant', (n, ignore_custom_classes, db) => {
  6765. let stack = [];
  6766. for (const input of n.inputs()) {
  6767. const ival = torch._C.toIValue(input);
  6768. if (ival) {
  6769. stack.push(ival);
  6770. } else {
  6771. return null;
  6772. }
  6773. }
  6774. switch (n.kind()) {
  6775. case 'prim::ListUnpack': {
  6776. if (stack.back().toList().size() !== n.outputs().length) {
  6777. return null;
  6778. }
  6779. torch._C.listUnpack(stack, n.outputs().length);
  6780. break;
  6781. }
  6782. case 'prim::TupleConstruct': {
  6783. const tt = n.output().type().expect(torch.TupleType);
  6784. if (tt.name()) {
  6785. torch._C.namedTupleConstruct(stack, tt, n.inputs().length);
  6786. } else {
  6787. torch._C.tupleConstruct(stack, n.inputs().length);
  6788. }
  6789. break;
  6790. }
  6791. case 'prim::ListConstruct': {
  6792. torch._C.listConstruct(stack, n.output().type().expect(torch.ListType), n.inputs().length);
  6793. break;
  6794. }
  6795. case 'prim::DictConstruct': {
  6796. torch._C.dictConstruct(stack, n.output().type().expect(torch.DictType), n.inputs().length);
  6797. break;
  6798. }
  6799. case 'prim::CreateObject': {
  6800. torch._C.createObject(stack, n.output().type().expect(torch.ClassType), /*use_weak_ref*/ true);
  6801. break;
  6802. }
  6803. case 'prim::GetAttr': {
  6804. const attr = torch._C.pop(stack).toObject().getAttr(n.s('name'));
  6805. torch._C.push(stack, attr);
  6806. break;
  6807. }
  6808. case 'prim::isinstance': {
  6809. torch._C.isinstance(stack, n.tys('types'));
  6810. break;
  6811. }
  6812. default: {
  6813. const maybe_schema = n.maybeSchema();
  6814. if (maybe_schema && maybe_schema.is_vararg) {
  6815. return null;
  6816. }
  6817. // try
  6818. // {
  6819. // const op = n.getOperation();
  6820. // op(stack);
  6821. const [module, name] = n.kind().split('::');
  6822. const obj = torch.ops[module];
  6823. if (!obj) {
  6824. throw new python.Error(`Unknown constant module 'torch.ops.${module}'.`);
  6825. }
  6826. const fn = torch.ops[module].__getattr__(name);
  6827. if (!fn || !fn.__call__) {
  6828. throw new python.Error(`Unknown constant function 'torch.ops.${module}.${name}'.`);
  6829. }
  6830. const args = stack.map((v) => v.value);
  6831. const result = fn.__call__(...args);
  6832. if (result === undefined) {
  6833. stack = [];
  6834. } else if (result instanceof torch._C.IValue) {
  6835. stack = [result];
  6836. } else if (Array.isArray(result) && result.every((v) => v instanceof torch._C.IValue)) {
  6837. stack = result;
  6838. } else {
  6839. stack = [new torch._C.IValue(result)];
  6840. }
  6841. // } catch {
  6842. // stack = [];
  6843. // return null;
  6844. // }
  6845. break;
  6846. }
  6847. }
  6848. for (const v of stack) {
  6849. if (v.isTensor()) {
  6850. const t = v.toTensor();
  6851. if (t.defined() && t.requires_grad()) {
  6852. return null;
  6853. }
  6854. }
  6855. if (ignore_custom_classes) {
  6856. if (v.isCustomClass()) {
  6857. return null;
  6858. }
  6859. }
  6860. if (v.isCustomClass()) {
  6861. if (v.toObject().is_weak_compilation_ref()) {
  6862. continue;
  6863. }
  6864. if (!db) {
  6865. continue;
  6866. }
  6867. const n_non_const = n;
  6868. if (db.mayContainAlias(n_non_const.inputs(), [n_non_const.outputs()])) {
  6869. continue;
  6870. }
  6871. const obj = v.toObject();
  6872. obj.unsafe_make_weak_compilation_ref();
  6873. }
  6874. if (v.isObject()) {
  6875. if (!v.toObject().is_weak_compilation_ref()) {
  6876. return null;
  6877. }
  6878. }
  6879. }
  6880. return stack;
  6881. });
  6882. this.registerType('torch._C.ConstantPropagator', class {
  6883. constructor(graph, aliasing_types, ignore_custom_classes) {
  6884. this._made_change = false;
  6885. this._graph = graph;
  6886. this._aliasing_types = aliasing_types;
  6887. this._ignore_custom_classes = ignore_custom_classes;
  6888. }
  6889. static NoAliasDb(graph) {
  6890. return new torch._C.ConstantPropagator(graph, false, false);
  6891. }
  6892. run() {
  6893. this.ConstantPropagation(this._graph.block());
  6894. return this._made_change;
  6895. }
  6896. propagateNode(n) {
  6897. let outputs = [];
  6898. const outputs_opt = torch._C.runNodeIfInputsAreConstant(n, this._ignore_custom_classes);
  6899. if (outputs_opt) {
  6900. outputs = outputs_opt;
  6901. const graph = n.owningGraph();
  6902. const guard = new torch._C.WithInsertPoint(n);
  6903. for (let i = 0; i < outputs.length; i++) {
  6904. const new_output = torch._C.tryInsertConstant(graph, outputs[i]);
  6905. if (new_output) {
  6906. this._made_change = true;
  6907. if (outputs[i].isNone()) {
  6908. new_output.setType(n.outputs()[i].type());
  6909. }
  6910. n.outputs()[i].replaceAllUsesWith(new_output);
  6911. }
  6912. }
  6913. guard.dispose();
  6914. }
  6915. }
  6916. removeLoopNode(n) {
  6917. const loop_input_offset = 2;
  6918. for (let i = 0; i < n.outputs().length; i++) {
  6919. n.outputs()[i].replaceAllUsesWith(n.inputs()[i + loop_input_offset]);
  6920. }
  6921. this._made_change = true;
  6922. n.destroy();
  6923. }
  6924. loopWillNotRun(node) {
  6925. const [trip_count, start_cond] = node.inputs();
  6926. const iter_len = torch._C.constant_as(trip_count, 'toInt', 1);
  6927. const cond_val = torch._C.constant_as(start_cond, 'toBool', true);
  6928. const loop_might_run = cond_val && iter_len > 0;
  6929. return !loop_might_run;
  6930. }
  6931. inlineIfBody(body) {
  6932. const n = body.owningNode();
  6933. for (const body_node of body.nodes()) {
  6934. body_node.moveBefore(n);
  6935. }
  6936. for (let i = 0; i < n.outputs().length; i++) {
  6937. n.outputs()[i].replaceAllUsesWith(body.outputs()[i]);
  6938. }
  6939. n.destroy();
  6940. }
  6941. inlineIf(n) {
  6942. const input_bool = torch._C.constant_as(n.input(), 'toBool');
  6943. torch._C.AT_ASSERT(input_bool !== null);
  6944. const block_index = input_bool ? 0 : 1;
  6945. this.ConstantPropagation(n.blocks().at(block_index));
  6946. this.inlineIfBody(n.blocks().at(block_index));
  6947. this._made_change = true;
  6948. }
  6949. replaceAndRemoveIfOutput(n, i, replacement) {
  6950. n.outputs()[i].replaceAllUsesWith(replacement);
  6951. n.eraseOutput(i);
  6952. n.blocks().at(0).eraseOutput(i);
  6953. n.blocks().at(1).eraseOutput(i);
  6954. }
  6955. removeExtraIfOutputs(n) {
  6956. torch._C.TORCH_CHECK(n.kind() === 'prim::If');
  6957. const [true_block, false_block] = n.blocks();
  6958. const graph = n.owningGraph();
  6959. const initial_outputs = true_block.outputs().length;
  6960. const guard = new torch._C.WithInsertPoint(n);
  6961. for (let i = 0; i < true_block.outputs().length;) {
  6962. const t_out = true_block.outputs()[i];
  6963. const f_out = false_block.outputs()[i];
  6964. if (true_block.outputs()[i] === false_block.outputs()[i]) {
  6965. this.replaceAndRemoveIfOutput(n, i, true_block.outputs()[i]);
  6966. continue;
  6967. }
  6968. const maybe_const = torch._C.toIValue(t_out);
  6969. if (maybe_const && torch._C.EqualNode(t_out.node(), f_out.node())) {
  6970. const new_const = graph.insertConstant(maybe_const);
  6971. this.replaceAndRemoveIfOutput(n, i, new_const);
  6972. continue;
  6973. }
  6974. i++;
  6975. }
  6976. this._made_change = this._made_change || (initial_outputs !== true_block.outputs().length);
  6977. guard.dispose();
  6978. }
  6979. removeExtraLoopOutputs(node) {
  6980. const initial_outputs = node.outputs().length;
  6981. const [loop_body] = node.blocks();
  6982. const loop_input_offset = 2;
  6983. const loop_body_offset = 1;
  6984. for (let i_1 = node.outputs().length; i_1 > 0; i_1--) {
  6985. const i = i_1 - 1;
  6986. if (loop_body.inputs()[loop_body_offset + i] === loop_body.outputs()[loop_body_offset + i]) {
  6987. const node_input = node.inputs()[loop_input_offset + i];
  6988. node.outputs().at(i).replaceAllUsesWith(node_input);
  6989. loop_body.inputs()[loop_body_offset + i].replaceAllUsesWith(node_input);
  6990. node.eraseOutput(i);
  6991. node.removeInput(loop_input_offset + i);
  6992. loop_body.eraseInput(loop_body_offset + i);
  6993. loop_body.eraseOutput(loop_body_offset + i);
  6994. }
  6995. }
  6996. this._made_change = this._made_change || (initial_outputs !== node.outputs().length);
  6997. }
  6998. noMutableValues(values) {
  6999. return values.every((v) => !torch._C.AliasDb.isMutableType(v));
  7000. }
  7001. getOrCreateAliasDb() {
  7002. if (!this._aliasDb) {
  7003. this._aliasDb = new torch._C.AliasDb(this._graph);
  7004. }
  7005. return this._aliasDb;
  7006. }
  7007. supportedNode(n) {
  7008. torch._C.skip_list = torch._C.skip_list || new Set([
  7009. 'prim::If',
  7010. 'prim::Loop',
  7011. 'prim::Closure',
  7012. 'prim::Constant',
  7013. 'prim::AutogradZero',
  7014. 'prim::Uninitialized',
  7015. 'prim::Guard',
  7016. 'prim::profile',
  7017. 'prim::profile_ivalue',
  7018. 'prim::unchecked_unwrap_optional',
  7019. 'prim::awaitable',
  7020. 'aten::dequantize'
  7021. ]);
  7022. let no_mutation = false;
  7023. if (this._aliasing_types) {
  7024. no_mutation = !this.getOrCreateAliasDb().hasWriters(n);
  7025. } else {
  7026. no_mutation = this.noMutableValues(n.inputs()) && this.noMutableValues(n.outputs());
  7027. }
  7028. return no_mutation && !n.kind().startsWith('onnx::') && !torch._C.skip_list.has(n.kind()) && !n.isNondeterministic() && !n.hasSideEffects() && n.blocks().length === 0;
  7029. }
  7030. ConstantPropagation(...args) {
  7031. if (args[0] instanceof torch.Graph) {
  7032. throw new python.Error('Not implemented.');
  7033. } else if (args[0] instanceof torch.Block) {
  7034. const [block] = args;
  7035. for (const n of block.nodes()) {
  7036. this.ConstantPropagation(n);
  7037. }
  7038. } else if (args[0] instanceof torch.Node) {
  7039. const [n] = args;
  7040. const constant_inputs = n.inputs().every((v) => v.node().kind() === 'prim::Constant');
  7041. if (n.kind() === 'prim::If') {
  7042. if (constant_inputs) {
  7043. this.inlineIf(n);
  7044. } else {
  7045. this.ConstantPropagation(n.blocks());
  7046. this.removeExtraIfOutputs(n);
  7047. }
  7048. } else if (n.kind() === 'prim::Loop') {
  7049. if (this.loopWillNotRun(n)) {
  7050. this.removeLoopNode(n);
  7051. } else {
  7052. this.ConstantPropagation(n.blocks());
  7053. this.removeExtraLoopOutputs(n);
  7054. }
  7055. } else if (constant_inputs && this.supportedNode(n)) {
  7056. this.propagateNode(n);
  7057. } else {
  7058. this.ConstantPropagation(n.blocks()); // not implemented
  7059. }
  7060. } else if (args.length === 1 && Array.isArray(args[0]) && args[0].every((b) => b instanceof torch.Block)) {
  7061. const [blocks] = args;
  7062. for (const block of blocks) {
  7063. this.ConstantPropagation(block);
  7064. }
  7065. } else {
  7066. throw new python.Error('Not implemented.');
  7067. }
  7068. }
  7069. });
  7070. this.registerFunction('torch._C.ConstantPropagationImmutableTypes', (graph) => {
  7071. const cp = torch._C.ConstantPropagator.NoAliasDb(graph);
  7072. const made_change = cp.run();
  7073. if (made_change) {
  7074. torch._C.EliminateDeadCode(graph);
  7075. }
  7076. return made_change;
  7077. });
  7078. this.registerType('torch._C.MutableTypePtrHelper', class {
  7079. constructor(mutable_type_cache) {
  7080. this._mutable_type_cache = mutable_type_cache;
  7081. }
  7082. mapTypeToAliasTypeSet(type) {
  7083. if (this._mutable_type_cache) {
  7084. const result = this.mapTypeToBorrowedAliasTypeSet(type);
  7085. if (result) {
  7086. return result;
  7087. }
  7088. }
  7089. return this.mapTypeToAliasTypeSetImpl(type);
  7090. }
  7091. mapTypeToAliasTypeSetImpl(type) {
  7092. if (type instanceof torch.ListType ||
  7093. type instanceof torch.DictType ||
  7094. type instanceof torch.ClassType ||
  7095. type instanceof torch.TensorType) {
  7096. return [torch._C.unshapedType(type)];
  7097. }
  7098. if (type instanceof torch.UnionType) {
  7099. const mutable_types = [];
  7100. for (const inner of type.expect(torch.UnionType).containedTypes()) {
  7101. const maybe_inner_types = this.mapTypeToAliasTypeSet(inner);
  7102. if (maybe_inner_types) {
  7103. mutable_types.push(...maybe_inner_types);
  7104. }
  7105. }
  7106. if (mutable_types.length === 0) {
  7107. return null;
  7108. }
  7109. return mutable_types;
  7110. }
  7111. if (type instanceof torch.OptionalType) {
  7112. const inner = type.getElementType();
  7113. return this.mapTypeToAliasTypeSet(inner);
  7114. }
  7115. if (type instanceof torch.AnyType) {
  7116. return [torch._C.AliasTypeSet([type])];
  7117. }
  7118. if (type instanceof torch.FutureType) {
  7119. const maybe_mut_types = this.mapTypeToAliasTypeSet(type.getElementType());
  7120. if (maybe_mut_types) {
  7121. return [torch._C.AliasTypeSet([torch.FutureType.create(torch._C.toSingleType(maybe_mut_types))])];
  7122. }
  7123. return null;
  7124. }
  7125. if (type instanceof torch.AwaitType) {
  7126. const maybe_mut_types = this.mapTypeToAliasTypeSet(type.getElementType());
  7127. if (maybe_mut_types) {
  7128. return [torch._C.AliasTypeSet([torch.AwaitType.create(torch._C.toSingleType(maybe_mut_types))])];
  7129. }
  7130. return null;
  7131. }
  7132. if (type instanceof torch.TupleType) {
  7133. const mutable_types = [];
  7134. for (const inner of type.elements()) {
  7135. const maybe_inner_types = this.mapTypeToAliasTypeSet(inner);
  7136. if (maybe_inner_types) {
  7137. mutable_types.push(...maybe_inner_types);
  7138. }
  7139. }
  7140. if (mutable_types.length === 0) {
  7141. return null;
  7142. }
  7143. return [[torch.TupleType.create(mutable_types)]];
  7144. }
  7145. return null;
  7146. }
  7147. });
  7148. this.registerFunction('torch._C.isMutableTypeImpl', (type, mutable_type_cache) => {
  7149. if (type instanceof torch.TensorType || type instanceof torch.ListType ||
  7150. type instanceof torch.ClassType || type instanceof torch.DictType) {
  7151. return true;
  7152. }
  7153. const helper = new torch._C.MutableTypePtrHelper(mutable_type_cache);
  7154. if (mutable_type_cache) {
  7155. return helper.mapTypeToBorrowedAliasTypeSet(type) !== null;
  7156. }
  7157. return helper.mapTypeToAliasTypeSet(type) !== null;
  7158. });
  7159. this.registerType('torch._C.AliasDb', class {
  7160. constructor() {
  7161. this._writeIndex = new Map();
  7162. }
  7163. static isMutableType(...args) {
  7164. if (args[0] instanceof torch.Type) {
  7165. const [type] = args;
  7166. return torch._C.isMutableTypeImpl(type, null);
  7167. }
  7168. if (args[0] instanceof torch.Value) {
  7169. const [value] = args;
  7170. return torch._C.AliasDb.isMutableType(value.type());
  7171. }
  7172. throw new python.Error('Not implemented.');
  7173. }
  7174. writesToAlias(/* n, vs */) {
  7175. /*
  7176. const writtenTo = this.getWrites(n);
  7177. if (writtenTo.length === 0) {
  7178. return false;
  7179. }
  7180. MemoryLocations locs;
  7181. for (const v of vs) {
  7182. const it = elementMap_.find(v);
  7183. if (it != elementMap_.end()) {
  7184. const auto& vlocs = memoryDAG_->getMemoryLocations(it->second);
  7185. if (writtenTo.intersects(vlocs)) {
  7186. return true;
  7187. }
  7188. }
  7189. }
  7190. */
  7191. return false;
  7192. }
  7193. writesToWildcard(n) {
  7194. if (!this._writeIndex.has(n)) {
  7195. return false;
  7196. }
  7197. const writes = this._writeIndex.get(n);
  7198. for (const pr of this._wildcardIndex) {
  7199. const [, wildcardElement] = pr;
  7200. if (writes.test(wildcardElement.index)) {
  7201. return true;
  7202. }
  7203. }
  7204. return false;
  7205. }
  7206. safeToChangeAliasingRelationship(a, b) {
  7207. if (torch._C.hasWriters(a) || torch._C.hasWriters(b)) {
  7208. return false;
  7209. }
  7210. return !(torch._C.escapesScope(a) && torch._C.escapesScope(b));
  7211. }
  7212. });
  7213. this.registerFunction('torch._C.hasWriters', () => {
  7214. });
  7215. this.registerFunction('torch._C.escapesScope', () => {
  7216. });
  7217. this.registerType('torch._C.DepthFirstGraphNodeIterator', class {
  7218. constructor(graph) {
  7219. this._current = graph.block().nodes().front();
  7220. }
  7221. next() {
  7222. return null;
  7223. }
  7224. });
  7225. this.registerType('torch._C.ConcatCombiner', class {
  7226. constructor(graph) {
  7227. this._graph = graph;
  7228. this._aliasDb = new torch._C.AliasDb(graph);
  7229. this._combinable_concats = [];
  7230. }
  7231. collectOptimizableConcats() {
  7232. const graph_it = new torch._C.DepthFirstGraphNodeIterator(this._graph);
  7233. for (let node = graph_it.next(); node !== null; node = graph_it.next()) {
  7234. if (node.kind() === 'aten::cat') {
  7235. this.handleConcat(node);
  7236. }
  7237. }
  7238. }
  7239. combineConcats() {
  7240. if (this._combinable_concats.length === 0) {
  7241. return false;
  7242. }
  7243. const list_construct_inputs = this.getListConstructInputs();
  7244. for (const node_and_new_list of list_construct_inputs) {
  7245. const [node, inputs] = node_and_new_list;
  7246. const new_list_construct = this.createListConstruct(inputs);
  7247. const old_list_construct = node.input(0).node();
  7248. new_list_construct.output().setType(old_list_construct.output().type());
  7249. new_list_construct.insertBefore(node);
  7250. old_list_construct.replaceAllUsesWith(new_list_construct);
  7251. }
  7252. return true;
  7253. }
  7254. run() {
  7255. this.collectOptimizableConcats();
  7256. const changed = this.combineConcats();
  7257. if (changed) {
  7258. torch._C.EliminateDeadCode(this._graph);
  7259. }
  7260. return changed;
  7261. }
  7262. });
  7263. this.registerFunction('torch._C.CombineConcats', (graph) => {
  7264. const changed = new torch._C.ConcatCombiner(graph).run();
  7265. return changed;
  7266. });
  7267. this.registerType('torch._C.PeepholeOptimizeImpl', class {
  7268. constructor(graph, disable_shape_peepholes) {
  7269. this._graph = graph;
  7270. this._shape_peepholes = !disable_shape_peepholes;
  7271. }
  7272. run() {
  7273. let changed = this.optimizeBlock(this._graph.block());
  7274. /* changed |= torch._C.PeepholeOptimizeListIdioms(this._graph);
  7275. changed |= torch._C.PeepholeOptimizeDictIdioms(this._graph);
  7276. changed |= torch._C.PeepholeOptimizeAliasSensitive(this._graph, this._shape_peepholes);
  7277. changed |= torch._C.PeepholeOptimizeNonTensor(this._graph); */
  7278. changed = changed || torch._C.CombineConcats(this._graph);
  7279. return changed;
  7280. }
  7281. optimizeBlock(block) {
  7282. let changed = false;
  7283. for (const node of block.nodes()) {
  7284. for (const sub_block of node.blocks()) {
  7285. changed = changed || this.optimizeBlock(sub_block);
  7286. }
  7287. if (node.kind() !== 'prim::Constant') {
  7288. const guard = new torch._C.WithInsertPoint(node);
  7289. for (const output of node.outputs()) {
  7290. if (output.type() instanceof torch.NoneType) {
  7291. output.replaceAllUsesWith(this._graph.insertConstant(new torch._C.IValue()));
  7292. changed = true;
  7293. }
  7294. }
  7295. guard.dispose();
  7296. }
  7297. if (node.kind() === 'prim::If') {
  7298. // throw new python.Error('Not implemented.');
  7299. /*
  7300. const n = new torch._C.IfView(node);
  7301. // this handles redundant short circuits like "x and True" or "x or
  7302. // False"
  7303. for (const auto i : c10::irange(n.outputs().length)) {
  7304. if (n.outputs().at(i).type() != torch.BoolType.get()) {
  7305. continue;
  7306. }
  7307. const true_val = constant_as<bool>(n.thenOutputs().at(i)).value_or(false);
  7308. const false_val = constant_as<bool>(n.elseOutputs().at(i)).value_or(true);
  7309. if (true_val && !false_val) {
  7310. n.outputs().at(i).replaceAllUsesWith(n.cond());
  7311. changed = true;
  7312. }
  7313. }
  7314. for (let i = 0; i < n.outputs().length; ++i) {
  7315. const inputs_non_optional = !n.thenOutputs().at(i).type().cast<OptionalType>() && !n.elseOutputs().at(i).type().cast<OptionalType>();
  7316. const output_optional = n.outputs()[i].type();
  7317. if (inputs_non_optional && output_optional instanceof torch.OptionalType) {
  7318. const unif = torch._c.unifyTypes(n.thenOutputs().at(i).type(), n.elseOutputs().at(i).type())
  7319. if (unif) {
  7320. n.outputs()[i].setType(unif);
  7321. changed = true;
  7322. }
  7323. }
  7324. }
  7325. */
  7326. } else if (node.kind() === 'aten::__is__' || node.kind() === 'aten::__isnot__') {
  7327. torch._C.AT_ASSERT(node.inputs().length === 2);
  7328. for (const check_none_index of [0, 1]) {
  7329. const input_must_be_none = node.inputs()[check_none_index].mustBeNone();
  7330. const other_must_not_be_none = node.inputs().at(1 - check_none_index).mustNotBeNone();
  7331. if (input_must_be_none && other_must_not_be_none) {
  7332. const guard = new torch._C.WithInsertPoint(node);
  7333. const output = node.owningGraph().insertConstant(node.kind() === 'aten::__isnot__');
  7334. node.output().replaceAllUsesWith(output);
  7335. changed = true;
  7336. guard.dispose();
  7337. }
  7338. }
  7339. } else if (node.kind() === 'prim::unchecked_unwrap_optional' || node.kind() === 'aten::_unwrap_optional') {
  7340. throw new python.Error('Not implemented.');
  7341. /*
  7342. // we are unwrapping an input that can't be None, remove the unwrap
  7343. const input = node.input();
  7344. if (input.mustNotBeNone()) {
  7345. node.output().replaceAllUsesWith(node.input());
  7346. changed = true;
  7347. }
  7348. */
  7349. } else if (node.kind() === 'prim::unchecked_cast') {
  7350. const input_type = torch._C.unshapedType(node.input().type());
  7351. const output_type = torch._C.unshapedType(node.output().type());
  7352. if (input_type.isSubtypeOf(output_type)) {
  7353. node.output().replaceAllUsesWith(node.input());
  7354. changed = true;
  7355. }
  7356. } else if ((node.kind() === 'aten::Int' || node.kind() === 'aten::ceil') && node.inputs().length === 1 && node.input().type() instanceof torch.IntType) {
  7357. node.output().replaceAllUsesWith(node.input());
  7358. changed = true;
  7359. } else if (node.kind() === 'aten::ne' || node.kind() === 'aten::eq') {
  7360. if (node.inputs().length !== 2 || node.inputs()[0] !== node.inputs()[1]) {
  7361. continue;
  7362. }
  7363. const inp_type = node.inputs()[0].type();
  7364. const immut_type = (type) => {
  7365. const kind = type.kind();
  7366. const handled_immutable_types = new Set('BoolType', 'IntType', 'FloatType', 'NoneType');
  7367. return handled_immutable_types.has(kind);
  7368. };
  7369. let non_throwing_type = false;
  7370. if (inp_type instanceof torch.ListType) {
  7371. non_throwing_type = immut_type(inp_type.getElementType());
  7372. } else if (inp_type instanceof torch.DictType) {
  7373. non_throwing_type = immut_type(inp_type.getKeyType()) && immut_type(inp_type.getValueType());
  7374. } else {
  7375. non_throwing_type = immut_type(inp_type);
  7376. }
  7377. if (non_throwing_type) {
  7378. const guard = new torch._C.WithInsertPoint(node);
  7379. node.output().replaceAllUsesWith(this._graph.insertConstant(node.kind() === 'aten::eq'));
  7380. changed = true;
  7381. guard.dispose();
  7382. }
  7383. } else if (node.kind() === 'aten::mul' || node.kind() === 'aten::floordiv' || node.kind() === 'aten::div') {
  7384. // changed = changed || torch._C.trySimplifyMulOrDiv(node);
  7385. } else if (node.kind() === 'aten::add' || node.kind() === 'aten::sub') {
  7386. // changed = changed || torch._C.trySimplifyAddOrSub(node);
  7387. }
  7388. }
  7389. return changed;
  7390. }
  7391. });
  7392. this.registerFunction('torch._C.PeepholeOptimize', (graph, addmm_fusion_enabled) => {
  7393. const peephole = new torch._C.PeepholeOptimizeImpl(graph, addmm_fusion_enabled);
  7394. const changed = peephole.run();
  7395. if (changed) {
  7396. torch._C.EliminateDeadCode(graph.block());
  7397. }
  7398. return changed;
  7399. });
  7400. this.registerFunction('torch._C.TORCH_INTERNAL_ASSERT', (cond) => {
  7401. if (!cond) {
  7402. throw new python.Error('Assertion failed.');
  7403. }
  7404. });
  7405. this.registerFunction('torch._C.TORCH_CHECK', (cond) => {
  7406. if (!cond) {
  7407. throw new python.Error('Assertion failed.');
  7408. }
  7409. });
  7410. this.registerFunction('torch._C.AT_ASSERT', (cond) => {
  7411. if (!cond) {
  7412. throw new python.Error('Assertion failed.');
  7413. }
  7414. });
  7415. this.registerFunction('torch._C.eraseListLiterals', (graph) => {
  7416. const it = new torch._C.DepthFirstGraphNodeIterator(graph);
  7417. for (let next_node = it.next(); next_node !== null;) {
  7418. const node = next_node;
  7419. next_node = it.next();
  7420. if (node.kind() === 'prim::EmptyListLiteral') {
  7421. if (node.hasUses()) {
  7422. torch._C.TORCH_INTERNAL_ASSERT(node.output().type().isSubtypeOf(torch.ListType.ofTensors()));
  7423. }
  7424. const li = graph.createList(torch.TensorType.get(), []);
  7425. li.insertBefore(node);
  7426. node.replaceAllUsesWith(li);
  7427. }
  7428. node.destroy();
  7429. }
  7430. });
  7431. this.registerFunction('torch._C.ConstantPooling', (...args) => {
  7432. if (args.length === 1 && args[0] instanceof torch.Graph) {
  7433. const [graph] = args;
  7434. const aliasDb = new torch._C.AliasDb(graph);
  7435. const constants = new torch._C.NodeSet();
  7436. torch._C.ConstantPooling(graph.block(), constants, aliasDb);
  7437. } else if (args.length === 3 && args[0] instanceof torch.Block) {
  7438. const [block, constants, aliasDb] = args;
  7439. for (const node of block.nodes()) {
  7440. if (node.blocks().length > 0) {
  7441. for (const block of node.blocks()) {
  7442. torch._C.ConstantPooling(block, constants, aliasDb);
  7443. }
  7444. continue;
  7445. }
  7446. if (node.kind() !== 'prim::Constant') {
  7447. continue;
  7448. }
  7449. if (constants.has(node)) {
  7450. const existing = constants.get(node);
  7451. const old_ivalue = torch._C.toIValue(existing.output());
  7452. const new_ivalue = torch._C.toIValue(node.output());
  7453. const same_identity = (old_ivalue && new_ivalue && (old_ivalue.is(new_ivalue)));
  7454. if (!same_identity && !aliasDb.safeToChangeAliasingRelationship(node.outputs(), existing.outputs())) {
  7455. continue;
  7456. }
  7457. node.replaceAllUsesWith(existing);
  7458. node.destroy();
  7459. continue;
  7460. } else {
  7461. constants.insert(node);
  7462. }
  7463. const [first_node] = node.owningGraph().block().nodes();
  7464. if (node !== first_node) {
  7465. node.moveBefore(first_node);
  7466. }
  7467. }
  7468. } else {
  7469. throw new python.Error('Not implemented.');
  7470. }
  7471. });
  7472. this.registerFunction('torch._C.handleBlock', (/* block, initial_state */) =>{
  7473. /*
  7474. const autocast_stack = [];
  7475. let incompatible_amp = null;
  7476. const current_state = () => autocast_stack.length === 0 ? initial_state : autocast_stack.top().context;
  7477. for (const node of block.nodes()) {
  7478. switch (node.kind()) {
  7479. case 'prim::CallFunction':
  7480. if (current_state() === initial_state) {
  7481. if (current_state()) {
  7482. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7483. }
  7484. break;
  7485. }
  7486. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || incompatible_amp.value(), "Calls are not expected with AMP & JIT");
  7487. incompatible_amp = true;
  7488. break;
  7489. case 'prim::CallMethod':
  7490. if (current_state() === initial_state) {
  7491. if (current_state()) {
  7492. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7493. }
  7494. break;
  7495. }
  7496. if (node.input(0).type() instanceof torch.ClassType) {
  7497. const class_type = node.input(0).type();
  7498. const name = node.s('name');
  7499. const fn = class_type.getMethod(name);
  7500. if (!fn.isGraphFunction()) {
  7501. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || incompatible_amp.value());
  7502. incompatible_amp = true;
  7503. }
  7504. } else {
  7505. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || incompatible_amp.value());
  7506. incompatible_amp = true;
  7507. }
  7508. break;
  7509. case 'prim::Enter': {
  7510. const autocast_scope = torch._C.parseAutocast(node.input(), current_state());
  7511. if (autocast_scope) {
  7512. if (node.hasUses()) {
  7513. torch._C.TORCH_CHECK(false, "`with autocast() as ...` is not supported");
  7514. }
  7515. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || !incompatible_amp.value());
  7516. incompatible_amp = false;
  7517. autocast_stack.push(autocast_scope);
  7518. }
  7519. break;
  7520. }
  7521. case 'prim::Exit': {
  7522. if (torch._C.isAutocastNode(node.input(0))) {
  7523. torch._C.TORCH_INTERNAL_ASSERT(!autocast_stack.empty());
  7524. torch._C.TORCH_INTERNAL_ASSERT(autocast_stack.top().instance === node.input());
  7525. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || !incompatible_amp.value());
  7526. incompatible_amp = false;
  7527. autocast_stack.pop();
  7528. }
  7529. break;
  7530. }
  7531. case 'aten::is_autocast_enabled': {
  7532. torch._C.updateAutocastEnabledCheck(node, current_state().gpu_enabled);
  7533. break;
  7534. }
  7535. case 'aten::is_autocast_cpu_enabled': {
  7536. torch._C.updateAutocastEnabledCheck(node, current_state().cpu_enabled);
  7537. break;
  7538. }
  7539. case 'aten::_convolution':
  7540. case 'aten::conv1d':
  7541. case 'aten::conv2d':
  7542. case 'aten::conv3d':
  7543. case 'aten::conv_tbc':
  7544. case 'aten::conv_transpose1d':
  7545. case 'aten::convolution':
  7546. case 'aten::cudnn_convolution':
  7547. case 'aten::cudnn_convolution_transpose':
  7548. case 'aten::prelu':
  7549. case 'aten::addmm':
  7550. case 'aten::addmv':
  7551. case 'aten::addr':
  7552. case 'aten::matmul':
  7553. case 'aten::mm':
  7554. case 'aten::mv':
  7555. case 'aten::linear':
  7556. case 'aten::addbmm':
  7557. case 'aten::baddbmm':
  7558. case 'aten::bmm':
  7559. case 'aten::chain_matmul':
  7560. case 'aten::_thnn_fused_lstm_cell':
  7561. case 'aten::_thnn_fused_gru_cell':
  7562. case 'aten::lstm_cell':
  7563. case 'aten::gru_cell':
  7564. case 'aten::rnn_tanh_cell':
  7565. case 'aten::rnn_relu_cell': {
  7566. if (!node.schema().is_mutable()) {
  7567. torch._C.castTensorInputs(node, 'aten::_autocast_to_reduced_precision', current_state());
  7568. }
  7569. break;
  7570. }
  7571. case 'aten::native_layer_norm':
  7572. case 'aten::acos':
  7573. case 'aten::asin':
  7574. case 'aten::cosh':
  7575. case 'aten::erfinv':
  7576. case 'aten::exp':
  7577. case 'aten::expm1':
  7578. case 'aten::log':
  7579. case 'aten::log10':
  7580. case 'aten::log2':
  7581. case 'aten::log1p':
  7582. case 'aten::reciprocal':
  7583. case 'aten::rsqrt':
  7584. case 'aten::sinh':
  7585. case 'aten::tan':
  7586. case 'aten::pow':
  7587. case 'aten::softplus':
  7588. case 'aten::gelu':
  7589. case 'aten::layer_norm':
  7590. case 'aten::group_norm':
  7591. case 'aten::frobenius_norm':
  7592. case 'aten::nuclear_norm':
  7593. case 'aten::cosine_similarity':
  7594. case 'aten::cosine_embedding_loss':
  7595. case 'aten::nll_loss':
  7596. case 'aten::nll_loss2d':
  7597. case 'aten::hinge_embedding_loss':
  7598. case 'aten::kl_div':
  7599. case 'aten::l1_loss':
  7600. case 'aten::smooth_l1_loss':
  7601. case 'aten::mse_loss':
  7602. case 'aten::margin_ranking_loss':
  7603. case 'aten::multilabel_margin_loss':
  7604. case 'aten::soft_margin_loss':
  7605. case 'aten::triplet_margin_loss':
  7606. case 'aten::multi_margin_loss':
  7607. case 'aten::binary_cross_entropy_with_logits':
  7608. case 'aten::dist':
  7609. case 'aten::pdist':
  7610. case 'aten::cdist':
  7611. case 'aten::renorm':
  7612. case 'aten::logsumexp': {
  7613. if (!node.schema().is_mutable()) {
  7614. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7615. }
  7616. break;
  7617. }
  7618. case 'aten::prod':
  7619. case 'aten::log_softmax':
  7620. case 'aten::cumprod':
  7621. case 'aten::cumsum':
  7622. case 'aten::sum': {
  7623. if (!node.schema().is_mutable() && !torch._C.hasExplicitDtypeArgument(node)) {
  7624. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7625. }
  7626. break;
  7627. }
  7628. case 'aten::softmax': {
  7629. if (!node.schema().is_mutable() && !torch._C.hasExplicitDtypeArgument(node)) {
  7630. const context = current_state();
  7631. context.cpu_enabled = false;
  7632. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', context);
  7633. }
  7634. break;
  7635. }
  7636. case 'aten::addcdiv':
  7637. case 'aten::addcmul':
  7638. case 'aten::atan2':
  7639. case 'aten::bilinear':
  7640. case 'aten::cat':
  7641. case 'aten::cross':
  7642. case 'aten::dot':
  7643. case 'aten::equal':
  7644. case 'aten::index_put':
  7645. case 'aten::stack':
  7646. case 'aten::tensordot':
  7647. case 'aten::add':
  7648. case 'aten::sub':
  7649. case 'aten::mul':
  7650. case 'aten::div': {
  7651. if (!node.schema().is_mutable()) {
  7652. torch._C.castInputsToWidestType(node, current_state());
  7653. }
  7654. break;
  7655. }
  7656. case 'aten::binary_cross_entropy': {
  7657. if (current_state()) {
  7658. torch._C.TORCH_CHECK(false, "Unsafe to autocast");
  7659. }
  7660. break;
  7661. }
  7662. default: {
  7663. break;
  7664. }
  7665. }
  7666. for (const sub_block of node.blocks()) {
  7667. torch._C.handleBlock(sub_block, current_state());
  7668. }
  7669. }
  7670. torch._C.TORCH_INTERNAL_ASSERT(autocast_stack.length === 0);
  7671. */
  7672. });
  7673. this.registerFunction('torch._C.autocastEnabled', () => {
  7674. return true;
  7675. });
  7676. this.registerFunction('torch._C.Autocast', (graph) => {
  7677. if (torch._C.autocastEnabled()) {
  7678. const init = null;
  7679. /* AutocastContext init = {
  7680. at::autocast::is_autocast_enabled(at::kCUDA),
  7681. at::autocast::is_autocast_enabled(at::kCPU),
  7682. at::autocast::get_autocast_dtype(at::kCUDA),
  7683. at::autocast::get_autocast_dtype(at::kCPU)}; */
  7684. torch._C.handleBlock(graph.block(), init);
  7685. }
  7686. });
  7687. this.registerFunction('torch._C.preoptimizeGraph', (graph, disable_autocast) => {
  7688. disable_autocast = disable_autocast || false;
  7689. torch._C.Inline(graph);
  7690. torch._C.PeepholeOptimize(graph, true);
  7691. torch._C.ConstantPropagationImmutableTypes(graph);
  7692. if (!disable_autocast) {
  7693. torch._C.Autocast(graph);
  7694. }
  7695. torch._C.ConstantPooling(graph);
  7696. });
  7697. this.registerType('torch._C.GraphFunction', class extends torch._C.Function {
  7698. constructor(name, graph, function_creator, executor_execution_mode) {
  7699. super();
  7700. this._name = name;
  7701. this._graph = graph;
  7702. this._executor_execution_mode = executor_execution_mode || null;
  7703. this._function_creator = function_creator;
  7704. this._force_no_amp = false;
  7705. }
  7706. isGraphFunction() {
  7707. return true;
  7708. }
  7709. qualname() {
  7710. return this._name;
  7711. }
  7712. graph() {
  7713. return this._graph;
  7714. }
  7715. optimized_graph() {
  7716. const graph_ref = this._graph.copy();
  7717. torch._C.preoptimizeGraph(graph_ref, this._force_no_amp);
  7718. return graph_ref;
  7719. }
  7720. ensure_defined() {
  7721. if (this._function_creator) {
  7722. const creator = this._function_creator;
  7723. this._function_creator = () => {
  7724. throw new python.Error('Recursive method call.');
  7725. };
  7726. creator(this);
  7727. this._function_creator = null;
  7728. }
  7729. this.check_single_output();
  7730. }
  7731. check_single_output() {
  7732. if (this.graph().outputs().length !== 1) {
  7733. throw new python.Error('Graph must have a single output.');
  7734. }
  7735. }
  7736. getSchema() {
  7737. this._schema = this._schema || this.defaultSchemaFor(this);
  7738. return this._schema;
  7739. }
  7740. setSchema(schema) {
  7741. this._schema = schema;
  7742. }
  7743. num_inputs() {
  7744. return this.graph().inputs().length;
  7745. }
  7746. unshapedType(type) {
  7747. if (type.isSubtypeOf(torch.TensorType.get())) {
  7748. return torch.TensorType.get();
  7749. }
  7750. const contained = type.containedTypes();
  7751. if (contained.length === 0) {
  7752. return type;
  7753. }
  7754. return type.withContained(type.containedTypes((type) => this.unshapedType(type)));
  7755. }
  7756. defaultSchemaFor(fn) {
  7757. const args = [];
  7758. const returns = [];
  7759. const g = fn.graph();
  7760. const num_inputs = fn.num_inputs();
  7761. for (let i = 0; i < num_inputs; i++) {
  7762. const v = g.inputs()[i];
  7763. const name = v.hasDebugName() ? v.debugNameBase() : `argument_${i}`;
  7764. const argument = new torch.Argument(name, this.unshapedType(g.inputs()[i].type()));
  7765. args.push(argument);
  7766. }
  7767. const num_outputs = g.outputs().length;
  7768. for (let i = 0; i < num_outputs; i++) {
  7769. const argument = new torch.Argument('', this.unshapedType(g.outputs()[i].type()));
  7770. returns.push(argument);
  7771. }
  7772. return new torch.FunctionSchema(fn.name(), '', args, returns);
  7773. }
  7774. });
  7775. this.registerType('torch.utils._contextlib._DecoratorContextManager', class {});
  7776. this.registerType('torch.utils._contextlib._NoParamDecoratorContextManager', class extends torch.utils._contextlib._DecoratorContextManager {});
  7777. this.registerType('torch.utils._sympy.symbol.SymT', class extends this.enum.Enum {});
  7778. this.registerType('torch.utils._sympy.functions.FloorDiv', class extends sympy.core.function.Function {
  7779. __str__() {
  7780. return this._args.map((a) => a.__str__()).join('//');
  7781. }
  7782. });
  7783. this.registerType('torch.utils._sympy.functions.ModularIndexing', class {});
  7784. this.registerType('torch.utils._sympy.functions.Where', class {});
  7785. this.registerType('torch.utils._sympy.functions.PythonMod', class {});
  7786. this.registerType('torch.utils._sympy.functions.Mod', class {});
  7787. this.registerType('torch.utils._sympy.functions.CleanDiv', class {});
  7788. this.registerType('torch.utils._sympy.functions.CeilToInt', class {});
  7789. this.registerType('torch.utils._sympy.functions.FloorToInt', class {});
  7790. this.registerType('torch.utils._sympy.functions.CeilDiv', class {});
  7791. this.registerType('torch.utils._sympy.functions.LShift', class {});
  7792. this.registerType('torch.utils._sympy.functions.RShift', class {});
  7793. this.registerType('torch.utils._sympy.functions.PowByNatural', class {});
  7794. this.registerType('torch.utils._sympy.functions.FloatPow', class {});
  7795. this.registerType('torch.utils._sympy.functions.FloatTrueDiv', class {});
  7796. this.registerType('torch.utils._sympy.functions.IntTrueDiv', class {});
  7797. this.registerType('torch.utils._sympy.functions.IsNonOverlappingAndDenseIndicator', class {});
  7798. this.registerType('torch.utils._sympy.functions.TruncToFloat', class {});
  7799. this.registerType('torch.utils._sympy.functions.TruncToInt', class {});
  7800. this.registerType('torch.utils._sympy.functions.RoundToInt', class {});
  7801. this.registerType('torch.utils._sympy.functions.RoundDecimal', class {});
  7802. this.registerType('torch.utils._sympy.functions.ToFloat', class {});
  7803. this.registerType('torch.utils._sympy.functions.Identity', class {});
  7804. this.registerType('torch.utils._traceback.CapturedTraceback', class {
  7805. static extract() {
  7806. }
  7807. });
  7808. this.registerFunction('torch.utils.checkpoint.checkpoint');
  7809. this.registerType('torch.utils.data.dataloader._MultiProcessingDataLoaderIter', class {});
  7810. this.registerType('torch.utils.data.dataloader.DataLoader', class {});
  7811. this.registerFunction('torch.utils.data._utils.collate.default_collate');
  7812. torch.utils.data.dataloader.default_collate = torch.utils.data._utils.collate.default_collate;
  7813. this.registerType('torch.utils.data.dataset.Subset', class {});
  7814. this.registerType('torch.utils.data.dataset.Dataset', class {});
  7815. this.registerType('torch.utils.data.dataset.ConcatDataset', class {});
  7816. this.registerType('torch.utils.data.dataset.TensorDataset', class {});
  7817. this.registerType('torch.utils.data.sampler.BatchSampler', class {});
  7818. this.registerType('torch.utils.data.sampler.RandomSampler', class {});
  7819. this.registerType('torch.utils.data.sampler.SequentialSampler', class {});
  7820. this.registerType('torch.utils.data.sampler.SubsetRandomSampler', class {});
  7821. this.registerType('torch.ao.quantization.fake_quantize.FakeQuantize', class {});
  7822. this.registerType('torch.ao.quantization.fake_quantize.FusedMovingAvgObsFakeQuantize', class {});
  7823. this.registerType('torch.ao.quantization.observer._PartialWrapper', class {});
  7824. this.registerType('torch.ao.quantization.observer.HistogramObserver', class {});
  7825. this.registerType('torch.ao.quantization.observer.MovingAverageMinMaxObserver', class {});
  7826. this.registerType('torch.ao.quantization.observer.MovingAveragePerChannelMinMaxObserver', class {});
  7827. this.registerType('torch.ao.quantization.observer.MinMaxObserver', class {});
  7828. this.registerType('torch.ao.quantization.observer.PerChannelMinMaxObserver', class {});
  7829. this.registerType('torch.ao.quantization.observer.PlaceholderObserver', class {});
  7830. this.registerType('torch.ao.quantization.qconfig.QConfig', class {});
  7831. this.registerType('torch.ao.quantization.qconfig.QConfigDynamic', class {});
  7832. this.registerType('torch.ao.quantization.stubs.DeQuantStub', class {});
  7833. this.registerType('torch.ao.quantization.stubs.QuantStub', class {});
  7834. this.registerType('torch.ao.quantization.stubs.QuantWrapper', class {});
  7835. this.registerFunction('torch.ao.quantization.qconfig._activation_is_memoryless');
  7836. this.registerFunction('torch.ao.quantization.qconfig._add_module_to_qconfig_obs_ctr');
  7837. this.registerFunction('torch.ao.quantization.fx.graph_module._save_packed_weight');
  7838. this.registerFunction('torch.ao.quantization.fx._lower_to_native_backend._load_packed_weight');
  7839. this.registerFunction('torch.ao.quantization.fx._lower_to_native_backend._save_packed_weight');
  7840. this.registerFunction('torch.ao.quantization.observer._is_activation_post_process');
  7841. this.registerFunction('torch.ao.quantization.quantize._observer_forward_hook');
  7842. this.registerFunction('torch.ao.quantization.quantization_mappings._get_special_act_post_process');
  7843. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_dynamic_quant_module_mappings');
  7844. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_qat_module_mappings');
  7845. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_qconfig_propagation_list');
  7846. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_static_quant_module_mappings');
  7847. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_static_quant_reference_module_mappings');
  7848. this.registerFunction('torch.ao.quantization.quantization_mappings.no_observer_set');
  7849. this.registerFunction('torch.ao.quantization.quantization_mappings._has_special_act_post_process');
  7850. this.registerFunction('torch.ao.quantization.utils.get_qparam_dict');
  7851. this.registerFunction('torch.ao.quantization.utils.has_no_children_ignoring_parametrizations');
  7852. this.registerFunction('torch.amp.grad_scaler._refresh_per_optimizer_state');
  7853. this.registerType('torch.amp.grad_scaler.GradScaler', class {});
  7854. this.registerType('torch._C._LegacyVariableBase', class {});
  7855. this.registerType('torch.autograd.grad_mode.no_grad', class extends torch.utils._contextlib._NoParamDecoratorContextManager {});
  7856. this.registerType('torch.autograd.variable.Variable', class extends torch._C._LegacyVariableBase {});
  7857. this.registerType('torch.autograd.function._SingleLevelFunction', class {});
  7858. this.registerType('torch.autograd.function.Function', class extends torch.autograd.function._SingleLevelFunction {});
  7859. this.registerType('torch.backends.cudnn.rnn.Unserializable', class {});
  7860. this.registerFunction('torch.distributed._shard.sharded_tensor.pre_load_state_dict_hook');
  7861. this.registerFunction('torch.distributed._shard.sharded_tensor.state_dict_hook');
  7862. this.registerFunction('torch.distributed._sharded_tensor.state_dict_hook');
  7863. this.registerFunction('torch.distributed._sharded_tensor.pre_load_state_dict_hook');
  7864. this.registerType('torch.distributed.algorithms.join._JoinConfig', class {});
  7865. this.registerType('torch.distributed.remote_device._remote_device', class {});
  7866. this.registerType('torch.distributed._shard.metadata.ShardMetadata', class {});
  7867. this.registerType('torch.distributed._shard.sharded_tensor.api.ShardedTensor', class {});
  7868. this.registerType('torch.distributed._shard.sharded_tensor.metadata.ShardedTensorMetadata', class {});
  7869. this.registerType('torch.distributed._shard.sharded_tensor.metadata.TensorProperties', class {});
  7870. this.registerType('torch.distributed._shard.sharded_tensor.shard.Shard', class {});
  7871. this.registerType('torch.distributed._tensor.api.DTensor', class extends torch._C._TensorMeta {});
  7872. this.registerType('torch.distributed._tensor.placement_types.DTensorSpec', class {});
  7873. this.registerType('torch.distributed._tensor.placement_types.Shard', class {});
  7874. this.registerType('torch.distributed._tensor.placement_types.TensorMeta', class {});
  7875. this.registerType('torch.distributed.device_mesh.DeviceMesh', class {});
  7876. this.registerType('torch.distributions.bernoulli.Bernoulli', class {});
  7877. this.registerType('torch.distributions.beta.Beta', class {});
  7878. this.registerType('torch.distributions.binomial.Binomial', class {});
  7879. this.registerType('torch.distributions.categorical.Categorical', class {});
  7880. this.registerType('torch.distributions.constraints._GreaterThan', class {});
  7881. this.registerType('torch.distributions.constraints._Interval', class {});
  7882. this.registerType('torch.distributions.constraints._LowerCholesky', class {});
  7883. this.registerType('torch.distributions.constraints._Real', class {});
  7884. this.registerType('torch.distributions.dirichlet.Dirichlet', class {});
  7885. this.registerType('torch.distributions.mixture_same_family.MixtureSameFamily', class {});
  7886. this.registerType('torch.distributions.multivariate_normal.MultivariateNormal', class {});
  7887. this.registerType('torch.distributions.normal.Normal', class {});
  7888. this.registerType('torch.distributions.transforms._InverseTransform', class {});
  7889. this.registerType('torch.distributions.transforms.AffineTransform', class {});
  7890. this.registerType('torch.distributions.transforms.ComposeTransform', class {});
  7891. this.registerType('torch.distributions.transforms.ExpTransform', class {});
  7892. this.registerType('torch.distributions.transforms.LowerCholeskyTransform', class {});
  7893. this.registerType('torch.distributions.uniform.Uniform', class {});
  7894. this.registerType('torch.nn.backends.thnn._get_thnn_function_backend', class {});
  7895. this.registerType('torch.nn.intrinsic.modules.fused._FusedModule', class {});
  7896. this.registerType('torch.nn.intrinsic.modules.fused.ConvBnReLU2d', class {});
  7897. this.registerType('torch.nn.intrinsic.modules.fused.ConvReLU2d', class {});
  7898. this.registerType('torch.nn.intrinsic.modules.fused.BNReLU2d', class {});
  7899. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvBn2d', class {});
  7900. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU2d', class {});
  7901. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvReLU2d', class {});
  7902. this.registerType('torch.nn.intrinsic.quantized.modules.bn_relu.BNReLU2d', class {});
  7903. this.registerType('torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU1d', class {});
  7904. this.registerType('torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', class {});
  7905. this.registerType('torch.nn.intrinsic.quantized.modules.linear_relu.LinearReLU', class {});
  7906. this.registerType('torch.nn.modules.activation.CELU', class extends torch.nn.modules.module.Module {});
  7907. this.registerType('torch.nn.modules.activation.ELU', class extends torch.nn.modules.module.Module {});
  7908. this.registerType('torch.nn.modules.activation.GELU', class extends torch.nn.modules.module.Module {});
  7909. this.registerType('torch.nn.modules.activation.GLU', class extends torch.nn.modules.module.Module {});
  7910. this.registerType('torch.nn.modules.activation.Hardtanh', class extends torch.nn.modules.module.Module {});
  7911. this.registerType('torch.nn.modules.activation.Hardshrink', class extends torch.nn.modules.module.Module {});
  7912. this.registerType('torch.nn.modules.activation.Hardsigmoid', class extends torch.nn.modules.module.Module {});
  7913. this.registerType('torch.nn.modules.activation.Hardswish', class extends torch.nn.modules.module.Module {});
  7914. this.registerType('torch.nn.modules.activation.LeakyReLU', class extends torch.nn.modules.module.Module {});
  7915. this.registerType('torch.nn.modules.activation.LogSigmoid', class extends torch.nn.modules.module.Module {});
  7916. this.registerType('torch.nn.modules.activation.LogSoftmax', class extends torch.nn.modules.module.Module {});
  7917. this.registerType('torch.nn.modules.activation.Mish', class extends torch.nn.modules.module.Module {});
  7918. this.registerType('torch.nn.modules.activation.MultiheadAttention', class extends torch.nn.modules.module.Module {});
  7919. this.registerType('torch.nn.modules.activation.ReLU', class extends torch.nn.modules.module.Module {});
  7920. this.registerType('torch.nn.modules.activation.ReLU6', class extends torch.nn.modules.module.Module {});
  7921. this.registerType('torch.nn.modules.activation.PReLU', class extends torch.nn.modules.module.Module {});
  7922. this.registerType('torch.nn.modules.activation.RReLU', class extends torch.nn.modules.module.Module {});
  7923. this.registerType('torch.nn.modules.activation.SELU', class extends torch.nn.modules.module.Module {});
  7924. this.registerType('torch.nn.modules.activation.Sigmoid', class extends torch.nn.modules.module.Module {});
  7925. this.registerType('torch.nn.modules.activation.SiLU', class extends torch.nn.modules.module.Module {});
  7926. this.registerType('torch.nn.modules.activation.Softmax', class extends torch.nn.modules.module.Module {});
  7927. this.registerType('torch.nn.modules.activation.Softmax2d', class extends torch.nn.modules.module.Module {});
  7928. this.registerType('torch.nn.modules.activation.Softmin', class extends torch.nn.modules.module.Module {});
  7929. this.registerType('torch.nn.modules.activation.Softplus', class extends torch.nn.modules.module.Module {});
  7930. this.registerType('torch.nn.modules.activation.Softshrink', class extends torch.nn.modules.module.Module {});
  7931. this.registerType('torch.nn.modules.activation.Softsign', class extends torch.nn.modules.module.Module {});
  7932. this.registerType('torch.nn.modules.activation.Tanh', class extends torch.nn.modules.module.Module {});
  7933. this.registerType('torch.nn.modules.activation.Tanhshrink', class extends torch.nn.modules.module.Module {});
  7934. this.registerType('torch.nn.modules.activation.Threshold', class extends torch.nn.modules.module.Module {});
  7935. this.registerType('torch.nn.modules.adaptive.AdaptiveLogSoftmaxWithLoss', class {});
  7936. this.registerType('torch.nn.modules.batchnorm._NormBase', class extends torch.nn.modules.module.Module {});
  7937. this.registerType('torch.nn.modules.batchnorm._BatchNorm', class extends torch.nn.modules.batchnorm._NormBase {});
  7938. this.registerType('torch.nn.modules.batchnorm.BatchNorm1d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  7939. this.registerType('torch.nn.modules.batchnorm.BatchNorm2d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  7940. this.registerType('torch.nn.modules.batchnorm.BatchNorm3d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  7941. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm1d', class {});
  7942. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm2d', class {});
  7943. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm3d', class {});
  7944. this.registerType('torch.nn.modules.batchnorm.SyncBatchNorm', class {});
  7945. this.registerType('torch.nn.modules.byted_batchnorm.BytedBatchNorm2d', class {});
  7946. this.registerType('torch.nn.modules.channelshuffle.ChannelShuffle', class {});
  7947. this.registerType('torch.nn.modules.container.ModuleDict', class extends torch.nn.modules.module.Module {});
  7948. this.registerType('torch.nn.modules.container.ModuleList', class extends torch.nn.modules.module.Module {});
  7949. this.registerType('torch.nn.modules.container.ParameterDict', class extends torch.nn.modules.module.Module {});
  7950. this.registerType('torch.nn.modules.container.ParameterList', class extends torch.nn.modules.module.Module {});
  7951. this.registerType('torch.nn.modules.container.Sequential', class extends torch.nn.modules.module.Module {});
  7952. this.registerType('torch.nn.modules.conv._ConvNd', class extends torch.nn.modules.module.Module {});
  7953. this.registerType('torch.nn.modules.conv.Conv1d', class extends torch.nn.modules.conv._ConvNd {});
  7954. this.registerType('torch.nn.modules.conv.Conv2d', class extends torch.nn.modules.conv._ConvNd {});
  7955. this.registerType('torch.nn.modules.conv.Conv3d', class extends torch.nn.modules.conv._ConvNd {});
  7956. this.registerType('torch.nn.modules.conv._ConvTransposeNd', class extends torch.nn.modules.module.Module {});
  7957. this.registerType('torch.nn.modules.conv.ConvTranspose1d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  7958. this.registerType('torch.nn.modules.conv.ConvTranspose2d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  7959. this.registerType('torch.nn.modules.conv.ConvTranspose3d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  7960. this.registerType('torch.nn.modules.conv.LazyConv1d', class {});
  7961. this.registerType('torch.nn.modules.conv.LazyConv2d', class {});
  7962. this.registerType('torch.nn.modules.conv.LazyConv3d', class {});
  7963. this.registerType('torch.nn.modules.conv.LazyConvTranspose2d', class {});
  7964. this.registerType('torch.nn.modules.conv.LazyConvTranspose3d', class {});
  7965. this.registerType('torch.nn.modules.distance.CosineSimilarity', class extends torch.nn.modules.module.Module {});
  7966. this.registerType('torch.nn.modules.distance.PairwiseDistance', class extends torch.nn.modules.module.Module {});
  7967. this.registerType('torch.nn.modules.dropout._DropoutNd', class extends torch.nn.modules.module.Module {});
  7968. this.registerType('torch.nn.modules.dropout.AlphaDropout', class extends torch.nn.modules.dropout._DropoutNd {});
  7969. this.registerType('torch.nn.modules.dropout.Dropout', class extends torch.nn.modules.dropout._DropoutNd {});
  7970. this.registerType('torch.nn.modules.dropout.Dropout1d', class extends torch.nn.modules.dropout._DropoutNd {});
  7971. this.registerType('torch.nn.modules.dropout.Dropout2d', class extends torch.nn.modules.dropout._DropoutNd {});
  7972. this.registerType('torch.nn.modules.dropout.Dropout3d', class extends torch.nn.modules.dropout._DropoutNd {});
  7973. this.registerType('torch.nn.modules.dropout.FeatureAlphaDropout', class extends torch.nn.modules.dropout._DropoutNd {});
  7974. this.registerType('torch.nn.modules.fold.Fold', class extends torch.nn.modules.module.Module {});
  7975. this.registerType('torch.nn.modules.fold.Unfold', class extends torch.nn.modules.module.Module {});
  7976. this.registerType('torch.nn.modules.flatten.Flatten', class extends torch.nn.modules.module.Module {});
  7977. this.registerType('torch.nn.modules.flatten.Unflatten', class extends torch.nn.modules.module.Module {});
  7978. this.registerType('torch.nn.modules.instancenorm.InstanceNorm1d', class {});
  7979. this.registerType('torch.nn.modules.instancenorm.InstanceNorm2d', class {});
  7980. this.registerType('torch.nn.modules.instancenorm.InstanceNorm3d', class {});
  7981. this.registerType('torch.nn.modules.instancenorm.LazyInstanceNorm2d', class {});
  7982. this.registerType('torch.nn.modules.instancenorm.LazyInstanceNorm3d', class {});
  7983. this.registerType('torch.nn.modules.linear._LinearWithBias', class {});
  7984. this.registerType('torch.nn.modules.linear.Bilinear', class extends torch.nn.modules.module.Module {});
  7985. this.registerType('torch.nn.modules.linear.Identity', class extends torch.nn.modules.module.Module {});
  7986. this.registerType('torch.nn.modules.linear.LazyLinear', class extends torch.nn.modules.module.Module {});
  7987. this.registerType('torch.nn.modules.linear.Linear', class extends torch.nn.modules.module.Module {});
  7988. this.registerType('torch.nn.modules.linear.NonDynamicallyQuantizableLinear', class extends torch.nn.modules.linear.Linear {});
  7989. this.registerType('torch.nn.modules.loss._Loss', class extends torch.nn.modules.module.Module {});
  7990. this.registerType('torch.nn.modules.loss._WeightedLoss', class extends torch.nn.modules.loss._Loss {});
  7991. this.registerType('torch.nn.modules.loss.BCELoss', class extends torch.nn.modules.loss._WeightedLoss {});
  7992. this.registerType('torch.nn.modules.loss.BCEWithLogitsLoss', class extends torch.nn.modules.loss._Loss {});
  7993. this.registerType('torch.nn.modules.loss.CrossEntropyLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  7994. this.registerType('torch.nn.modules.loss.CosineEmbeddingLoss', class extends torch.nn.modules.loss._Loss {});
  7995. this.registerType('torch.nn.modules.loss.CTCLoss', class extends torch.nn.modules.loss._Loss {});
  7996. this.registerType('torch.nn.modules.loss.GaussianNLLLoss', class extends torch.nn.modules.loss._Loss {});
  7997. this.registerType('torch.nn.modules.loss.HuberLoss', class extends torch.nn.modules.loss._Loss {});
  7998. this.registerType('torch.nn.modules.loss.HingeEmbeddingLoss', class extends torch.nn.modules.loss._Loss {});
  7999. this.registerType('torch.nn.modules.loss.KLDivLoss', class extends torch.nn.modules.loss._Loss {});
  8000. this.registerType('torch.nn.modules.loss.L1Loss', class extends torch.nn.modules.loss._Loss {});
  8001. this.registerType('torch.nn.modules.loss.MarginRankingLoss', class extends torch.nn.modules.loss._Loss {});
  8002. this.registerType('torch.nn.modules.loss.MultiLabelMarginLoss', class extends torch.nn.modules.loss._Loss {});
  8003. this.registerType('torch.nn.modules.loss.MultiLabelSoftMarginLoss', class extends torch.nn.modules.loss._Loss {});
  8004. this.registerType('torch.nn.modules.loss.MultiMarginLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  8005. this.registerType('torch.nn.modules.loss.MSELoss', class extends torch.nn.modules.loss._Loss {});
  8006. this.registerType('torch.nn.modules.loss.NLLLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  8007. this.registerType('torch.nn.modules.loss.NLLLoss2d', class extends torch.nn.modules.loss.NLLLoss {});
  8008. this.registerType('torch.nn.modules.loss.PoissonNLLLoss', class {});
  8009. this.registerType('torch.nn.modules.loss.SmoothL1Loss', class {});
  8010. this.registerType('torch.nn.modules.loss.SoftMarginLoss', class {});
  8011. this.registerType('torch.nn.modules.loss.TripletMarginLoss', class {});
  8012. this.registerType('torch.nn.modules.loss.TripletMarginWithDistanceLoss', class {});
  8013. this.registerType('torch.nn.modules.module._IncompatibleKeys', class {});
  8014. this.registerType('torch.nn.modules.module._WrappedHook', class {});
  8015. this.registerType('torch.nn.modules.module.PatchForward', class {});
  8016. this.registerType('torch.nn.modules.normalization.CrossMapLRN2d', class {});
  8017. this.registerType('torch.nn.modules.normalization.GroupNorm', class extends torch.nn.modules.module.Module {});
  8018. this.registerType('torch.nn.modules.normalization.LayerNorm', class extends torch.nn.modules.module.Module {});
  8019. this.registerType('torch.nn.modules.normalization.LocalResponseNorm', class {});
  8020. this.registerType('torch.nn.modules.normalization.RMSNorm', class {});
  8021. this.registerType('torch.nn.modules.padding._ReflectionPadNd', class extends torch.nn.modules.module.Module {});
  8022. this.registerType('torch.nn.modules.padding.ReflectionPad1d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  8023. this.registerType('torch.nn.modules.padding.ReflectionPad2d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  8024. this.registerType('torch.nn.modules.padding.ReflectionPad3d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  8025. this.registerType('torch.nn.modules.padding._ReplicationPadNd', class extends torch.nn.modules.module.Module {});
  8026. this.registerType('torch.nn.modules.padding.ReplicationPad1d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  8027. this.registerType('torch.nn.modules.padding.ReplicationPad2d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  8028. this.registerType('torch.nn.modules.padding.ReplicationPad3d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  8029. this.registerType('torch.nn.modules.padding.ZeroPad1d', class {});
  8030. this.registerType('torch.nn.modules.padding.ZeroPad2d', class {});
  8031. this.registerType('torch.nn.modules.padding.ZeroPad3d', class {});
  8032. this.registerType('torch.nn.modules.padding.ConstantPad1d', class {});
  8033. this.registerType('torch.nn.modules.padding.ConstantPad2d', class {});
  8034. this.registerType('torch.nn.modules.padding.ConstantPad3d', class {});
  8035. this.registerType('torch.nn.modules.padding.CircularPad3d', class {});
  8036. this.registerType('torch.nn.modules.pixelshuffle.PixelShuffle', class {});
  8037. this.registerType('torch.nn.modules.pixelshuffle.PixelUnshuffle', class {});
  8038. this.registerType('torch.nn.modules.pooling._AdaptiveAvgPoolNd', class extends torch.nn.modules.module.Module {});
  8039. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool1d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  8040. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool2d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  8041. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool3d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  8042. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool1d', class {});
  8043. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool2d', class {});
  8044. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool3d', class {});
  8045. this.registerType('torch.nn.modules.pooling.AvgPool1d', class {});
  8046. this.registerType('torch.nn.modules.pooling.AvgPool2d', class {});
  8047. this.registerType('torch.nn.modules.pooling.AvgPool3d', class {});
  8048. this.registerType('torch.nn.modules.pooling.FractionalMaxPool2d', class {});
  8049. this.registerType('torch.nn.modules.pooling.FractionalMaxPool3d', class {});
  8050. this.registerType('torch.nn.modules.pooling.LPPool1d', class {});
  8051. this.registerType('torch.nn.modules.pooling.LPPool2d', class {});
  8052. this.registerType('torch.nn.modules.pooling.LPPool3d', class {});
  8053. this.registerType('torch.nn.modules.pooling._MaxPoolNd', class extends torch.nn.modules.module.Module {});
  8054. this.registerType('torch.nn.modules.pooling.MaxPool1d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  8055. this.registerType('torch.nn.modules.pooling.MaxPool2d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  8056. this.registerType('torch.nn.modules.pooling.MaxPool3d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  8057. this.registerType('torch.nn.modules.pooling._MaxUnpoolNd', class extends torch.nn.modules.module.Module {});
  8058. this.registerType('torch.nn.modules.pooling.MaxUnpool1d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  8059. this.registerType('torch.nn.modules.pooling.MaxUnpool2d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  8060. this.registerType('torch.nn.modules.pooling.MaxUnpool3d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  8061. this.registerType('torch.nn.modules.rnn.GRU', class {});
  8062. this.registerType('torch.nn.modules.rnn.GRUCell', class {});
  8063. this.registerType('torch.nn.modules.rnn.LSTM', class {});
  8064. this.registerType('torch.nn.modules.rnn.LSTMCell', class {});
  8065. this.registerType('torch.nn.modules.rnn.RNNBase', class extends torch.nn.modules.module.Module {});
  8066. this.registerType('torch.nn.modules.rnn.RNN', class extends torch.nn.modules.rnn.RNNBase {});
  8067. this.registerType('torch.nn.modules.rnn.RNNCellBase', class extends torch.nn.modules.module.Module {});
  8068. this.registerType('torch.nn.modules.rnn.RNNCell', class extends torch.nn.modules.rnn.RNNCellBase {});
  8069. this.registerType('torch.nn.modules.sparse.Embedding', class {});
  8070. this.registerType('torch.nn.modules.sparse.EmbeddingBag', class {});
  8071. this.registerType('torch.nn.modules.transformer.Transformer', class {});
  8072. this.registerType('torch.nn.modules.transformer.TransformerDecoder', class {});
  8073. this.registerType('torch.nn.modules.transformer.TransformerDecoderLayer', class {});
  8074. this.registerType('torch.nn.modules.transformer.TransformerEncoder', class {});
  8075. this.registerType('torch.nn.modules.transformer.TransformerEncoderLayer', class {});
  8076. this.registerType('torch.nn.modules.upsampling.Upsample', class {});
  8077. this.registerType('torch.nn.modules.upsampling.UpsamplingBilinear2d', class {});
  8078. this.registerType('torch.nn.modules.upsampling.UpsamplingNearest2d', class {});
  8079. this.registerType('torch.nn.parallel.data_parallel.DataParallel', class {});
  8080. this.registerType('torch.nn.parallel.distributed._DDPUnevenInputsConfig', class {});
  8081. this.registerType('torch.nn.parallel.distributed.DistributedDataParallel', class {});
  8082. this.registerType('torch.nn.qat.modules.conv.Conv2d', class {});
  8083. this.registerType('torch.nn.qat.modules.linear.Linear', class {});
  8084. this.registerType('torch.nn.quantized.modules.activation.ReLU', class {});
  8085. this.registerType('torch.nn.quantized.modules.activation.LeakyReLU', class {});
  8086. this.registerType('torch.nn.quantized.modules.activation.Softmax', class {});
  8087. this.registerType('torch.nn.quantized.dynamic.modules.linear.Linear', class {});
  8088. this.registerType('torch.nn.quantized.dynamic.modules.rnn.GRU', class {});
  8089. this.registerType('torch.nn.quantized.dynamic.modules.rnn.LSTM', class {});
  8090. this.registerType('torch.nn.quantized.dynamic.modules.rnn.LSTMCell', class {});
  8091. this.registerType('torch.nn.quantized.dynamic.modules.rnn.PackedParameter', class {});
  8092. this.registerType('torch.nn.quantized.modules.activation.ReLU6', class {});
  8093. this.registerType('torch.nn.quantized.modules.batchnorm.BatchNorm2d', class {});
  8094. this.registerType('torch.nn.quantized.modules.conv.Conv1d', class {});
  8095. this.registerType('torch.nn.quantized.modules.conv.Conv2d', class {});
  8096. this.registerType('torch.nn.quantized.modules.conv.ConvTranspose2d', class {});
  8097. this.registerType('torch.nn.quantized.modules.DeQuantize', class {});
  8098. this.registerType('torch.nn.quantized.modules.dropout.Dropout', class {});
  8099. this.registerType('torch.nn.quantized.modules.embedding_ops.Embedding', class {});
  8100. this.registerType('torch.nn.quantized.modules.embedding_ops.EmbeddingPackedParams', class {});
  8101. this.registerType('torch.nn.quantized.modules.functional_modules.FloatFunctional', class {});
  8102. this.registerType('torch.nn.quantized.modules.functional_modules.QFunctional', class {});
  8103. this.registerType('torch.nn.quantized.modules.linear.Linear', class {});
  8104. this.registerType('torch.nn.quantized.modules.linear.LinearPackedParams', class {});
  8105. this.registerType('torch.nn.quantized.modules.normalization.InstanceNorm2d', class {});
  8106. this.registerType('torch.nn.quantized.modules.normalization.GroupNorm', class extends torch.nn.modules.normalization.GroupNorm {});
  8107. this.registerType('torch.nn.quantized.modules.normalization.LayerNorm', class extends torch.nn.modules.normalization.LayerNorm {});
  8108. this.registerType('torch.nn.quantized.modules.Quantize', class {});
  8109. this.registerType('torch.ao.nn.quantizable.modules.activation.MultiheadAttention', class extends torch.nn.modules.activation.MultiheadAttention {});
  8110. this.registerType('torch.ao.nn.quantizable.modules.rnn._LSTMLayer', class {});
  8111. this.registerType('torch.ao.nn.quantizable.modules.rnn._LSTMSingleLayer', class {});
  8112. this.registerType('torch.ao.nn.quantizable.modules.rnn.LSTM', class {});
  8113. this.registerType('torch.ao.nn.quantizable.modules.rnn.LSTMCell', class {});
  8114. this.registerType('torch.ao.nn.quantized.modules.activation.ELU', class extends torch.nn.modules.activation.ELU {});
  8115. this.registerType('torch.ao.nn.quantized.modules.activation.Hardswish', class extends torch.nn.modules.activation.Hardswish {});
  8116. this.registerType('torch.ao.nn.quantized.modules.activation.MultiheadAttention', class extends torch.ao.nn.quantizable.modules.activation.MultiheadAttention {});
  8117. this.registerType('torch.ao.nn.quantized.modules.activation.PReLU', class extends torch.nn.modules.module.Module {});
  8118. this.registerType('torch.ao.nn.quantized.modules.activation.ReLU6', class extends torch.nn.modules.activation.ReLU {});
  8119. this.registerType('torch.ao.nn.quantized.modules.activation.LeakyReLU', class extends torch.nn.modules.activation.LeakyReLU {});
  8120. this.registerType('torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule', class extends torch.nn.modules.module.Module {});
  8121. this.registerType('torch.ao.nn.quantized.modules.batchnorm._BatchNorm', class extends torch.nn.modules.batchnorm._BatchNorm {});
  8122. this.registerType('torch.ao.nn.quantized.modules.batchnorm.BatchNorm2d', class extends torch.ao.nn.quantized.modules.batchnorm._BatchNorm {});
  8123. this.registerType('torch.ao.nn.quantized.modules.conv.Conv1d', class extends torch.nn.modules.module.Module {});
  8124. this.registerType('torch.ao.nn.quantized.modules.conv.Conv2d', class extends torch.nn.modules.module.Module {});
  8125. this.registerType('torch.ao.nn.quantized.modules.conv._ConvNd', class extends torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule {});
  8126. this.registerType('torch.ao.nn.quantized.modules.conv._ConvTransposeNd', class extends torch.ao.nn.quantized.modules.conv._ConvNd {});
  8127. this.registerType('torch.ao.nn.quantized.modules.conv.ConvTranspose1d', class extends torch.ao.nn.quantized.modules.conv._ConvTransposeNd {});
  8128. this.registerType('torch.ao.nn.quantized.modules.conv.ConvTranspose2d', class extends torch.ao.nn.quantized.modules.conv._ConvTransposeNd {});
  8129. this.registerType('torch.ao.nn.quantized.modules.Quantize', class extends torch.nn.modules.module.Module {});
  8130. this.registerType('torch.ao.nn.quantized.modules.DeQuantize', class extends torch.nn.modules.module.Module {});
  8131. this.registerType('torch.ao.nn.quantized.modules.dropout.Dropout', class extends torch.nn.modules.dropout.Dropout {});
  8132. this.registerType('torch.ao.nn.quantized.modules.embedding_ops.Embedding', class extends torch.nn.modules.module.Module {});
  8133. this.registerType('torch.ao.nn.quantized.modules.embedding_ops.EmbeddingPackedParams', class extends torch.nn.modules.module.Module {});
  8134. this.registerType('torch.ao.nn.quantized.modules.functional_modules.FloatFunctional', class extends torch.nn.modules.module.Module {});
  8135. this.registerType('torch.ao.nn.quantized.modules.functional_modules.QFunctional', class extends torch.nn.modules.module.Module {});
  8136. this.registerType('torch.ao.nn.quantized.modules.functional_modules.FXFloatFunctional', class extends torch.nn.modules.module.Module {});
  8137. this.registerType('torch.ao.nn.quantized.modules.linear.Linear', class extends torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule {});
  8138. this.registerType('torch.ao.nn.quantized.modules.linear.LinearPackedParams', class extends torch.nn.modules.module.Module {});
  8139. this.registerType('torch.ao.nn.quantized.modules.normalization.LayerNorm', class extends torch.nn.modules.normalization.LayerNorm {});
  8140. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm1d', class extends torch.nn.modules.instancenorm.InstanceNorm1d {});
  8141. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm2d', class extends torch.nn.modules.instancenorm.InstanceNorm2d {});
  8142. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm3d', class extends torch.nn.modules.instancenorm.InstanceNorm3d {});
  8143. this.registerType('torch.ao.nn.quantized.modules.rnn.LSTM', class {});
  8144. this.registerType('torch.ao.nn.quantized.dynamic.modules.linear.Linear', class extends torch.ao.nn.quantized.modules.linear.Linear {});
  8145. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.PackedParameter', class extends torch.nn.modules.module.Module {});
  8146. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase', class extends torch.nn.modules.module.Module {});
  8147. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.GRU', class extends torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase {});
  8148. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.LSTM', class extends torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase {});
  8149. this.registerType('torch.ao.nn.quantized.reference.modules.conv.Conv1d', class {});
  8150. this.registerType('torch.ao.nn.quantized.reference.modules.conv.Conv2d', class {});
  8151. this.registerType('torch.ao.nn.quantized.reference.modules.linear.Linear', class {});
  8152. this.registerType('torch.ao.nn.qat.modules.conv.Conv2d', class {});
  8153. this.registerType('torch.ao.nn.qat.modules.linear.Linear', class {});
  8154. this.registerType('torch.ao.nn.intrinsic.quantized.modules.conv_relu.ConvReLU1d', class extends torch.ao.nn.quantized.modules.conv.Conv1d {});
  8155. this.registerType('torch.ao.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', class extends torch.ao.nn.quantized.modules.conv.Conv2d {});
  8156. this.registerType('torch.ao.nn.intrinsic.quantized.modules.linear_relu.LinearReLU', class extends torch.ao.nn.quantized.modules.linear.Linear {});
  8157. this.registerType('torch.ao.nn.intrinsic.quantized.modules.bn_relu.BNReLU2d', class extends torch.ao.nn.quantized.modules.batchnorm.BatchNorm2d {});
  8158. this.registerType('torch.ao.nn.intrinsic.modules.fused._FusedModule', class extends torch.nn.modules.container.Sequential {});
  8159. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvBn2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8160. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvReLU1d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8161. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvReLU2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8162. this.registerType('torch.ao.nn.intrinsic.modules.fused.LinearReLU', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8163. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvBnReLU2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8164. this.registerType('torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU2d', class {});
  8165. this.registerType('torch.nn.utils.prune.CustomFromMask', class {});
  8166. this.registerType('torch.nn.utils.prune.Identity', class {});
  8167. this.registerType('torch.nn.utils.prune.L1Unstructured', class {});
  8168. this.registerType('torch.nn.utils.prune.LnStructured', class {});
  8169. this.registerType('torch.nn.utils.prune.PruningContainer', class {});
  8170. this.registerType('torch.nn.utils.prune.RandomUnstructured', class {});
  8171. this.registerType('torch.nn.utils.spectral_norm.SpectralNorm', class {});
  8172. this.registerType('torch.nn.utils.spectral_norm.SpectralNormStateDictHook', class {});
  8173. this.registerType('torch.nn.utils.spectral_norm.SpectralNormLoadStateDictPreHook', class {});
  8174. this.registerType('torch.nn.utils.weight_norm.WeightNorm', class {});
  8175. this.registerFunction('torch.nn.utils.parametrize.type_before_parametrizations');
  8176. this.registerType('torch.nn.utils.parametrize.ParametrizationList', class extends torch.nn.modules.container.ModuleList {});
  8177. this.registerType('torch.torch_version.TorchVersion', class extends String {});
  8178. this.registerType('torch.optim.optimizer.Optimizer', class {});
  8179. this.registerType('torch.optim.adam.Adam', class extends torch.optim.optimizer.Optimizer {});
  8180. this.registerType('torch.optim.adamw.AdamW', class {});
  8181. this.registerType('torch.optim.adagrad.Adagrad', class {});
  8182. this.registerType('torch.optim.adadelta.Adadelta', class {});
  8183. this.registerType('torch.optim.lbfgs.LBFGS', class {});
  8184. this.registerType('torch.optim.lr_scheduler.CosineAnnealingLR', class {});
  8185. this.registerType('torch.optim.lr_scheduler.CosineAnnealingWarmRestarts', class {});
  8186. this.registerType('torch.optim.lr_scheduler.CyclicLR', class {});
  8187. this.registerType('torch.optim.lr_scheduler.ExponentialLR', class {});
  8188. this.registerType('torch.optim.lr_scheduler.LambdaLR', class {});
  8189. this.registerType('torch.optim.lr_scheduler.LinearLR', class {});
  8190. this.registerType('torch.optim.lr_scheduler.MultiStepLR', class {});
  8191. this.registerType('torch.optim.lr_scheduler.OneCycleLR', class {});
  8192. this.registerType('torch.optim.lr_scheduler.ReduceLROnPlateau', class {});
  8193. this.registerType('torch.optim.lr_scheduler.StepLR', class {});
  8194. this.registerType('torch.optim.optimizer._RequiredParameter', class {});
  8195. this.registerType('torch.optim.radam.RAdam', class extends torch.optim.optimizer.Optimizer {});
  8196. this.registerType('torch.optim.rmsprop.RMSprop', class {});
  8197. this.registerType('torch.optim.sgd.SGD', class {});
  8198. this.registerType('torch.optim.sparse_adam.SparseAdam', class {});
  8199. this.registerType('torch.optim.swa_utils.SWALR', class {});
  8200. torch.optim.RAdam = torch.optim.radam.RAdam;
  8201. this.registerType('torch.quantization.fake_quantize.FakeQuantize', class {});
  8202. this.registerFunction('torch.quantization.fx.graph_module._save_packed_weight');
  8203. this.registerType('torch.quantization.observer._PartialWrapper', class {});
  8204. this.registerType('torch.quantization.observer.HistogramObserver', class {});
  8205. this.registerType('torch.quantization.observer.MinMaxObserver', class {});
  8206. this.registerType('torch.quantization.observer.MovingAverageMinMaxObserver', class {});
  8207. this.registerType('torch.quantization.observer.MovingAveragePerChannelMinMaxObserver', class {});
  8208. this.registerFunction('torch.quantization.observer._with_args');
  8209. this.registerType('torch.quantization.qconfig.QConfig', class {});
  8210. this.registerType('torch.quantization.stubs.DeQuantStub', class {});
  8211. this.registerType('torch.quantization.stubs.QuantStub', class {});
  8212. this.registerType('torch.utils._pytree.LeafSpec', class {});
  8213. this.registerType('torch.utils._pytree.TreeSpec', class {});
  8214. this.registerType('torch.utils._python_dispatch.TorchDispatchMode', class {
  8215. __enter__() {
  8216. return this;
  8217. }
  8218. __exit__(/* exc_type, exc_value, traceback */) {
  8219. }
  8220. });
  8221. this.registerFunction('torch.utils._pytree.tree_map');
  8222. torch.nn.Sequential = torch.nn.modules.container.Sequential;
  8223. this.registerFunction('torch.fx.experimental.sym_node.SymNode', class {
  8224. constructor(expr, shape_env, pytype, hint, constant, fx_node, optimized_summation) {
  8225. this._expr = expr;
  8226. this.shape_env = shape_env;
  8227. this.pytype = pytype;
  8228. this._optimized_summation = optimized_summation;
  8229. this._hint = hint;
  8230. this.constant = constant;
  8231. const tx_validation_en = this.shape_env && this.shape_env._translation_validation_enabled ? true : false;
  8232. this.fx_node = tx_validation_en && fx_node ? fx_node : null;
  8233. }
  8234. __str__() {
  8235. return this._expr.__str__();
  8236. }
  8237. });
  8238. this.registerType('torch.fx.experimental.symbolic_shapes.ShapeEnv', class {
  8239. constructor() {
  8240. this.var_to_val = new Map();
  8241. this.var_to_stack = new Map();
  8242. }
  8243. add_var_to_val(expr, val) {
  8244. this.var_to_val.set(expr, new sympy.core.numbers.Integer(val));
  8245. }
  8246. constrain_symbol_range(/* s, compiler_min, compiler_max */) {
  8247. }
  8248. create_symintnode(sym, hint, source) {
  8249. let out = null;
  8250. let fx_node = null;
  8251. if (this._translation_validation_enabled && source !== null) {
  8252. throw new python.Error('Not implemented.');
  8253. } else {
  8254. fx_node = null;
  8255. }
  8256. if (builtins.isinstance(sym, sympy.core.numbers.Integer)) {
  8257. out = builtins.int(sym);
  8258. if (hint !== null && out !== hint) {
  8259. throw new python.Error(`Symbolic integer has value '${out}' but expected '${hint}'.`);
  8260. }
  8261. } else {
  8262. // if free_unbacked_symbols(sym):
  8263. // hint = None
  8264. out = new torch.SymInt(new torch.fx.experimental.sym_node.SymNode(sym, this, builtins.int, hint, null, fx_node));
  8265. }
  8266. return out;
  8267. }
  8268. create_symboolnode(sym) {
  8269. return new torch.SymBool(new torch.fx.experimental.sym_node.SymNode(sym, this, builtins.bool, null));
  8270. }
  8271. });
  8272. this.registerFunction('torch.fx.experimental.symbolic_shapes.symbol_is_type', (/* sym, prefix */) => {
  8273. /*
  8274. assert isinstance(sym, sympy.Symbol)
  8275. const name_str = sym.name.toLowerCase();
  8276. if (builtins.isinstance(prefix, torch.utils._sympy.symbol.SymT)) {
  8277. return name_str.startsWith(prefix_str[prefix])
  8278. }
  8279. return name_str.startswith(tuple(prefix_str[p] for p in prefix));
  8280. */
  8281. return false;
  8282. });
  8283. this.registerType('torch.fx.proxy.TracerBase', class {
  8284. constructor() {
  8285. this.traced_func_name = 'forward';
  8286. }
  8287. });
  8288. this.registerType('torch.fx._symbolic_trace.Tracer', class extends torch.fx.proxy.TracerBase {
  8289. trace(root /*, concrete_args */) {
  8290. let fn = null;
  8291. if (root instanceof torch.nn.Module) {
  8292. // torch.fx._lazy_graph_module._LazyGraphModule.force_recompile(root)
  8293. this.root = root;
  8294. fn = builtins.getattr(new builtins.type(root), this.traced_func_name);
  8295. this.root_module_name = root._get_name();
  8296. this.submodule_paths = new builtins.dict(root.named_modules());
  8297. } else {
  8298. this.root = new torch.nn.Module();
  8299. fn = root;
  8300. }
  8301. const tracer_cls = builtins.getattr(this, '__class__', null);
  8302. this.graph = new torch.fx.graph.Graph(null, tracer_cls);
  8303. if (builtins.hasattr(this, '__code__')) {
  8304. const code = fn.__code__;
  8305. this.graph._co_fields = {
  8306. co_name: code.co_name,
  8307. co_filename: code.co_filename,
  8308. co_firstlineno: code.co_firstlineno,
  8309. };
  8310. }
  8311. return this.graph;
  8312. }
  8313. is_leaf_module(m /*, module_qualified_name */) {
  8314. return (m.__module__.startsWith('torch.nn') || m.__module__.startsWith('torch.ao.nn')) && m instanceof torch.nn.Sequential === false;
  8315. }
  8316. });
  8317. this.registerType('torch.fx.experimental.proxy_tensor.PythonKeyTracer', class extends torch.fx._symbolic_trace.Tracer {});
  8318. this.registerType('torch.fx.experimental.proxy_tensor._ModuleStackTracer', class extends torch.fx.experimental.proxy_tensor.PythonKeyTracer {});
  8319. this.registerFunction('torch.fx._lazy_graph_module._make_graph_module', (...args) => {
  8320. const graph_module_cls = args.pop() || torch.fx.graph_module.GraphModule;
  8321. return new graph_module_cls(...args);
  8322. });
  8323. this.registerFunction('torch.fx.graph_module._deserialize_graph_module', (forward, body, graph_module_cls) => {
  8324. let tracer_cls = body.get('_tracer_cls');
  8325. if (!tracer_cls) {
  8326. tracer_cls = torch.fx._symbolic_trace.Tracer;
  8327. }
  8328. const graphmodule_cls_name = body.get('_graphmodule_cls_name', 'GraphModule');
  8329. const cls_tracer = tracer_cls;
  8330. const KeepModules = class extends cls_tracer {
  8331. is_leaf_module() {
  8332. return true;
  8333. }
  8334. };
  8335. const com = new torch.fx.graph_module._CodeOnlyModule(body);
  8336. const tracer_extras = body.get('_tracer_extras', new builtins.dict());
  8337. const graph = new KeepModules().trace(com, tracer_extras);
  8338. graph._tracer_cls = tracer_cls;
  8339. const gm = torch.fx._lazy_graph_module._make_graph_module(com, graph, graphmodule_cls_name, graph_module_cls);
  8340. for (const [k, v] of body.items()) {
  8341. if (!builtins.hasattr(gm, k)) {
  8342. builtins.setattr(gm, k, v);
  8343. }
  8344. }
  8345. return gm;
  8346. });
  8347. this.registerFunction('torch.fx.graph_module._forward_from_src', (src, globals /*, co_fields */) => {
  8348. globals = { ...globals };
  8349. const context = new python.Execution.Context(globals, null);
  8350. execution.exec(src, context);
  8351. const forward_fn = globals.forward;
  8352. delete globals.forward;
  8353. return forward_fn;
  8354. });
  8355. this.registerFunction('torch.fx.graph_module.reduce_graph_module', (body, import_block) => {
  8356. // https://github.com/pytorch/pytorch/blob/master/torch/fx/graph_module.py
  8357. let fn_src = null;
  8358. if (body.has('_code')) {
  8359. fn_src = body.get('_code');
  8360. } else if (body.has('code')) {
  8361. fn_src = body.get('code');
  8362. } else {
  8363. fn_src = body._code || body.code;
  8364. }
  8365. const forward = torch.fx.graph_module._forward_from_src(import_block + fn_src, {});
  8366. return torch.fx.graph_module._deserialize_graph_module(forward, body);
  8367. });
  8368. this.registerFunction('torch.fx.graph_module.reduce_package_graph_module', (importer, body, generated_module_name) => {
  8369. const forward = importer.import_module(generated_module_name).forward;
  8370. return torch.fx.graph_module._deserialize_graph_module(forward, body);
  8371. });
  8372. this.registerType('torch.fx.graph.CodeGen', class {});
  8373. this.registerType('torch.fx.graph._PyTreeInfo', class {
  8374. constructor(orig_args, in_spec, out_spec) {
  8375. this.orig_args = orig_args;
  8376. this.in_spec = in_spec;
  8377. this.out_spec = out_spec;
  8378. }
  8379. });
  8380. this.registerType('torch.fx.graph._Namespace', class {
  8381. constructor() {
  8382. this._obj_to_name = new Map();
  8383. this._unassociated_names = new Set();
  8384. this._used_names = new Set();
  8385. this._base_count = {};
  8386. }
  8387. create_name(candidate, obj) {
  8388. if (obj && this._obj_to_name.has(obj)) {
  8389. return self._obj_to_name.get(obj);
  8390. }
  8391. candidate = candidate || '_unnamed';
  8392. candidate = /^\d+$/.test(candidate) ? `_${candidate}` : candidate;
  8393. candidate = candidate.replace(/[^0-9a-zA-Z_]+/, '_');
  8394. const match = candidate.match(/(.*)_(\d+)$"/);
  8395. let base = candidate;
  8396. let num = null;
  8397. if (match) {
  8398. [, base] = match;
  8399. num = parseInt(match[2], 10);
  8400. }
  8401. candidate = num ? `${base}_${num}` : base;
  8402. if (!num) {
  8403. num = this._base_count[base] || 0;
  8404. }
  8405. while (this._used_names.has(candidate) || this._is_illegal_name(candidate, obj)) {
  8406. num += 1;
  8407. candidate = `${base}_${num}`;
  8408. }
  8409. this._used_names.add(candidate);
  8410. this._base_count[base] = num;
  8411. if (obj) {
  8412. this._obj_to_name[obj] = candidate;
  8413. } else {
  8414. this._unassociated_names.add(candidate);
  8415. }
  8416. return candidate;
  8417. }
  8418. _is_illegal_name(/* name, obj */) {
  8419. /*
  8420. if name in keyword.kwlist:
  8421. return True
  8422. if name in builtins.__dict__:
  8423. return obj is not builtins.__dict__[name]
  8424. if name in _custom_builtins:
  8425. return obj is not _custom_builtins[name].obj
  8426. */
  8427. return false;
  8428. }
  8429. associate_name_with_obj() {
  8430. }
  8431. });
  8432. this.registerType('torch.fx.node.Node', class {
  8433. constructor(graph, name, op, target, args, kwargs, return_type) {
  8434. this.graph = graph;
  8435. this.name = name;
  8436. this.op = op;
  8437. this.target = target;
  8438. this._input_nodes = new builtins.dict();
  8439. this.__update_args_kwargs(args, kwargs);
  8440. this.users = new builtins.dict();
  8441. this.type = return_type;
  8442. this._prev = this;
  8443. this._next = this;
  8444. this._erased = false;
  8445. this._repr_fn = null;
  8446. this.meta = new builtins.dict();
  8447. }
  8448. get args() {
  8449. return this._args;
  8450. }
  8451. get kwargs() {
  8452. return this._kwargs;
  8453. }
  8454. get next() {
  8455. return this._next;
  8456. }
  8457. prepend(x) {
  8458. x._remove_from_list();
  8459. const p = this._prev;
  8460. [p._next, x._prev] = [x, p];
  8461. [x._next, this._prev] = [this, x];
  8462. }
  8463. _remove_from_list() {
  8464. const [p, n] = [this._prev, this._next];
  8465. [p._next, n._prev] = [n, p];
  8466. }
  8467. __update_args_kwargs(new_args, new_kwargs) {
  8468. const update_users_and_input_nodes = (n) => {
  8469. if (n instanceof torch.fx.node.Node) {
  8470. this._input_nodes.setdefault(n);
  8471. n.users.setdefault(this);
  8472. }
  8473. return n;
  8474. };
  8475. const map_aggregate = (a, fn) => {
  8476. if (a instanceof builtins.tuple) {
  8477. const t = new builtins.tuple(a.map((elem) => map_aggregate(elem, fn)));
  8478. if (!builtins.hasattr(a, '_fields')) {
  8479. return t;
  8480. }
  8481. throw new python.Error('Not implemented.');
  8482. // return type(a)(*t);
  8483. } else if (Array.isArray(a)) {
  8484. return a.map((elem) => map_aggregate(elem, fn));
  8485. } else if (a instanceof builtins.dict) {
  8486. const rv = new builtins.dict();
  8487. for (const [k, v] of a) {
  8488. rv.__setitem__(k, map_aggregate(v, fn));
  8489. }
  8490. return rv;
  8491. } else if (a instanceof builtins.slice) {
  8492. throw new python.Error('Not implemented.');
  8493. // return slice(map_aggregate(a.start, fn), map_aggregate(a.stop, fn), map_aggregate(a.step, fn))
  8494. }
  8495. return fn(a);
  8496. };
  8497. for (const old_use of this._input_nodes.keys()) {
  8498. old_use.users.pop(this);
  8499. }
  8500. // object.__setattr__(self, "_input_nodes", {})
  8501. this._input_nodes = new builtins.dict();
  8502. // object.__setattr__(self, "_args", map_aggregate(new_args, update_users_and_input_nodes))
  8503. this._args = map_aggregate(new_args, update_users_and_input_nodes);
  8504. // object.__setattr__(self, "_kwargs", map_aggregate(new_kwargs, update_users_and_input_nodes))
  8505. this._kwargs = map_aggregate(new_kwargs, update_users_and_input_nodes);
  8506. }
  8507. });
  8508. torch.fx.Node = torch.fx.node.Node;
  8509. torch.fx.graph.Node = torch.fx.node.Node;
  8510. this.registerType('torch.fx.graph.Graph', class {
  8511. constructor(owning_module, tracer_cls, tracer_extras) {
  8512. this._root = new torch.fx.node.Node(self, '', 'root', '', new builtins.list(), new builtins.dict());
  8513. this._used_names = new Map();
  8514. this._len = 0;
  8515. this._graph_namespace = new torch.fx.graph._Namespace();
  8516. this._owning_module = owning_module;
  8517. this._tracer_cls = tracer_cls;
  8518. this._tracer_extras = tracer_extras;
  8519. // this._codegen = CodeGen()
  8520. // this._co_fields = {}
  8521. }
  8522. get nodes() {
  8523. const array = new Array(this._len);
  8524. let node = this._root.next;
  8525. for (let i = 0; node !== this._root; i++) {
  8526. array[i] = node;
  8527. node = node.next;
  8528. }
  8529. return array;
  8530. }
  8531. placeholder(name, type_expr /*, default_value */) {
  8532. const args = []; // () if default_value is inspect.Signature.empty else (default_value,)
  8533. const kwargs = new builtins.dict();
  8534. return this.create_node('placeholder', name, args, kwargs, type_expr);
  8535. }
  8536. create_node(op, target, args, kwargs, name, type_expr) {
  8537. args = args || new builtins.tuple();
  8538. kwargs = kwargs || new builtins.dict();
  8539. const candidate = name || this._target_to_str(target);
  8540. name = this._graph_namespace.create_name(candidate, null);
  8541. const n = new torch.fx.node.Node(this, name, op, target, args, kwargs, type_expr);
  8542. this._graph_namespace.associate_name_with_obj(name, n);
  8543. this._insert(n);
  8544. this._len += 1;
  8545. return n;
  8546. }
  8547. _insert(n) {
  8548. this._root.prepend(n);
  8549. }
  8550. output(result, type_expr) {
  8551. return this.create_node('output', 'output', new builtins.tuple(result), null, type_expr);
  8552. }
  8553. _target_to_str(target) {
  8554. if (typeof target === 'string') {
  8555. if (target.startsWith('__') && target.endsWith('__')) {
  8556. target = target.substring(2, target.length - 2);
  8557. }
  8558. } else {
  8559. target = target.__name__;
  8560. }
  8561. return this._snake_case(target);
  8562. }
  8563. _snake_case(s) {
  8564. const chars = [];
  8565. let prev_lower = false;
  8566. for (const c of s) {
  8567. const x = c.toLowerCase();
  8568. if (prev_lower && x !== c) {
  8569. chars.push('_');
  8570. } else {
  8571. prev_lower = true;
  8572. }
  8573. chars.push(x);
  8574. }
  8575. return chars.join('');
  8576. }
  8577. });
  8578. this.registerType('torch.fx.graph_module._CodeOnlyModule', class extends torch.nn.modules.module.Module {
  8579. constructor(body) {
  8580. super();
  8581. for (const [k, v] of body.items()) {
  8582. builtins.setattr(this, k, v);
  8583. }
  8584. }
  8585. });
  8586. this.registerFunction('torch.fx.graph_module._copy_attr', (from_module, to_module, target) => {
  8587. const parts = target.split('.');
  8588. const field = parts.pop();
  8589. for (const item of parts) {
  8590. const f = builtins.getattr(from_module, item);
  8591. let t = builtins.getattr(to_module, item, null);
  8592. if (f === t) {
  8593. return;
  8594. }
  8595. if (t === null) {
  8596. t = new torch.nn.modules.module.Module();
  8597. builtins.setattr(to_module, item, t);
  8598. }
  8599. from_module = f;
  8600. to_module = t;
  8601. }
  8602. const orig = builtins.getattr(from_module, field);
  8603. builtins.setattr(to_module, field, orig);
  8604. });
  8605. this.registerType('torch.fx.graph_module.GraphModule', class extends torch.nn.modules.module.Module {
  8606. constructor(root, graph, class_name) {
  8607. super();
  8608. this.__class__.__name__ = class_name || 'GraphModule';
  8609. this.graph = graph;
  8610. if (root instanceof torch.nn.modules.module.Module && graph && graph.nodes) {
  8611. for (const node of graph.nodes) {
  8612. if (node.op === 'get_attr' || node.op === 'call_module') {
  8613. torch.fx.graph_module._copy_attr(root, this, node.target);
  8614. }
  8615. }
  8616. }
  8617. }
  8618. });
  8619. torch.fx.Graph = torch.fx.graph.Graph;
  8620. torch.fx.GraphModule = torch.fx.graph_module.GraphModule;
  8621. this.registerType('torch.fx.immutable_collections.immutable_dict', class extends builtins.dict {});
  8622. this.registerType('torch.fx.immutable_collections.immutable_list', class extends builtins.list {});
  8623. this.registerFunction('torch.fx._symbolic_trace.wrap', (fn_or_name) => {
  8624. return fn_or_name;
  8625. });
  8626. this.registerFunction('torch.fx._symbolic_trace._assert_is_none');
  8627. this.registerFunction('torchvision.datasets.folder.default_loader');
  8628. this.registerType('torchvision.datasets.folder.ImageFolder', class {});
  8629. this.registerType('torchvision.datasets.mnist.FashionMNIST', class {});
  8630. this.registerType('torchvision.datasets.mnist.MNIST', class {});
  8631. this.registerType('torchvision.datasets.video_utils.VideoClips', class {});
  8632. this.registerType('torchvision.datasets.vision.StandardTransform', class {});
  8633. this.registerType('torchvision.ops.deform_conv.DeformConv2d', class {});
  8634. this.registerType('torchvision.ops.feature_pyramid_network.FeaturePyramidNetwork', class {});
  8635. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelMaxPool', class {});
  8636. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelP6P7', class {});
  8637. this.registerType('torchvision.ops.misc.Conv2dNormActivation', class {});
  8638. this.registerType('torchvision.ops.misc.ConvNormActivation', class {});
  8639. this.registerType('torchvision.ops.misc.MLP', class extends torch.nn.modules.container.Sequential {});
  8640. this.registerType('torchvision.ops.misc.ConvTranspose2d', class {});
  8641. this.registerType('torchvision.ops.misc.FrozenBatchNorm2d', class {});
  8642. this.registerType('torchvision.ops.misc.Permute', class {});
  8643. this.registerType('torchvision.ops.misc.SqueezeExcitation', class {});
  8644. this.registerType('torchvision.ops.poolers.LevelMapper', class {});
  8645. this.registerType('torchvision.ops.poolers.MultiScaleRoIAlign', class {});
  8646. this.registerType('torchvision.ops.roi_align.RoIAlign', class {});
  8647. this.registerType('torchvision.ops.stochastic_depth.StochasticDepth', class {});
  8648. this.registerType('torchvision.models._api.Weights', class {});
  8649. this.registerType('torchvision.models.alexnet.AlexNet', class {});
  8650. this.registerType('torchvision.models.convnext.ConvNeXt', class {});
  8651. this.registerType('torchvision.models.convnext.CNBlock', class {});
  8652. this.registerType('torchvision.models.convnext.LayerNorm2d', class {});
  8653. this.registerType('torchvision.models.densenet.DenseNet', class extends torch.nn.modules.module.Module {});
  8654. this.registerType('torchvision.models.densenet._DenseBlock', class extends torch.nn.modules.container.ModuleDict {});
  8655. this.registerType('torchvision.models.densenet._DenseLayer', class extends torch.nn.modules.module.Module {});
  8656. this.registerType('torchvision.models.densenet._Transition', class extends torch.nn.modules.container.Sequential {});
  8657. this.registerType('torchvision.models.detection._utils.BalancedPositiveNegativeSampler', class {});
  8658. this.registerType('torchvision.models.detection._utils.BoxCoder', class {});
  8659. this.registerType('torchvision.models.detection._utils.Matcher', class {});
  8660. this.registerType('torchvision.models.detection._utils.SSDMatcher', class {});
  8661. this.registerType('torchvision.models.detection.anchor_utils.AnchorGenerator', class {});
  8662. this.registerType('torchvision.models.detection.anchor_utils.DefaultBoxGenerator', class {});
  8663. this.registerType('torchvision.models.detection.backbone_utils.BackboneWithFPN', class {});
  8664. this.registerType('torchvision.models.detection.faster_rcnn.FasterRCNN', class {});
  8665. this.registerType('torchvision.models.detection.faster_rcnn.FastRCNNConvFCHead', class {});
  8666. this.registerType('torchvision.models.detection.faster_rcnn.FastRCNNPredictor', class {});
  8667. this.registerType('torchvision.models.detection.faster_rcnn.TwoMLPHead', class {});
  8668. this.registerType('torchvision.models.detection.fcos.FCOS', class {});
  8669. this.registerType('torchvision.models.detection.fcos.FCOSHead', class {});
  8670. this.registerType('torchvision.models.detection.fcos.FCOSClassificationHead', class {});
  8671. this.registerType('torchvision.models.detection.fcos.FCOSRegressionHead', class {});
  8672. this.registerType('torchvision.models.detection._utils.BoxLinearCoder', class {});
  8673. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNN', class {});
  8674. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNHeads', class {});
  8675. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNPredictor', class {});
  8676. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNN', class {});
  8677. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNHeads', class {});
  8678. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNPredictor', class {});
  8679. this.registerType('torchvision.models.detection.retinanet.RetinaNet', class {});
  8680. this.registerType('torchvision.models.detection.retinanet.RetinaNetClassificationHead', class {});
  8681. this.registerType('torchvision.models.detection.retinanet.RetinaNetHead', class {});
  8682. this.registerType('torchvision.models.detection.retinanet.RetinaNetRegressionHead', class {});
  8683. this.registerType('torchvision.models.detection.roi_heads.RoIHeads', class {});
  8684. this.registerType('torchvision.models.detection.rpn.AnchorGenerator', class {});
  8685. this.registerType('torchvision.models.detection.rpn.RegionProposalNetwork', class {});
  8686. this.registerType('torchvision.models.detection.rpn.RPNHead', class {});
  8687. this.registerType('torchvision.models.detection.ssd.SSD', class {});
  8688. this.registerType('torchvision.models.detection.ssd.SSDClassificationHead', class {});
  8689. this.registerType('torchvision.models.detection.ssd.SSDHead', class {});
  8690. this.registerType('torchvision.models.detection.ssd.SSDFeatureExtractorVGG', class {});
  8691. this.registerType('torchvision.models.detection.ssd.SSDRegressionHead', class {});
  8692. this.registerType('torchvision.models.detection.ssdlite.SSDLiteClassificationHead', class {});
  8693. this.registerType('torchvision.models.detection.ssdlite.SSDLiteFeatureExtractorMobileNet', class {});
  8694. this.registerType('torchvision.models.detection.ssdlite.SSDLiteHead', class {});
  8695. this.registerType('torchvision.models.detection.ssdlite.SSDLiteRegressionHead', class {});
  8696. this.registerType('torchvision.models.detection.transform.GeneralizedRCNNTransform', class {});
  8697. this.registerType('torchvision.models.efficientnet.EfficientNet', class {});
  8698. this.registerType('torchvision.models.efficientnet.EfficientNet_B3_Weights', class {});
  8699. this.registerType('torchvision.models.efficientnet.FusedMBConv', class {});
  8700. this.registerType('torchvision.models.efficientnet.MBConv', class {});
  8701. this.registerType('torchvision.models.feature_extraction.LeafModuleAwareTracer', class extends torch.fx._symbolic_trace.Tracer {});
  8702. this.registerType('torchvision.models.feature_extraction.NodePathTracer', class extends torchvision.models.feature_extraction.LeafModuleAwareTracer {});
  8703. this.registerType('torchvision.models.googlenet.BasicConv2d', class {});
  8704. this.registerType('torchvision.models.googlenet.GoogLeNet', class {});
  8705. this.registerType('torchvision.models.googlenet.Inception', class {});
  8706. this.registerType('torchvision.models.googlenet.InceptionAux', class {});
  8707. this.registerType('torchvision.models.inception.BasicConv2d', class {});
  8708. this.registerType('torchvision.models.inception.Inception3', class {});
  8709. this.registerType('torchvision.models.inception.InceptionAux', class {});
  8710. this.registerType('torchvision.models.inception.InceptionA', class {});
  8711. this.registerType('torchvision.models.inception.InceptionB', class {});
  8712. this.registerType('torchvision.models.inception.InceptionC', class {});
  8713. this.registerType('torchvision.models.inception.InceptionD', class {});
  8714. this.registerType('torchvision.models.inception.InceptionE', class {});
  8715. this.registerFunction('torchvision.models.inception.inception_v3');
  8716. this.registerType('torchvision.models.mnasnet._InvertedResidual', class {});
  8717. this.registerType('torchvision.models.mnasnet.MNASNet', class {});
  8718. this.registerType('torchvision.models.maxvit.MaxVit', class {});
  8719. this.registerType('torchvision.models.maxvit.MaxVitBlock', class {});
  8720. this.registerType('torchvision.models.maxvit.MaxVitLayer', class {});
  8721. this.registerType('torchvision.models.maxvit.MBConv', class {});
  8722. this.registerType('torchvision.models.maxvit.PartitionAttentionLayer', class {});
  8723. this.registerType('torchvision.models.maxvit.RelativePositionalMultiHeadAttention', class {});
  8724. this.registerType('torchvision.models.maxvit.SwapAxes', class {});
  8725. this.registerType('torchvision.models.maxvit.WindowDepartition', class {});
  8726. this.registerType('torchvision.models.mobilenet.ConvBNReLU', class {});
  8727. this.registerType('torchvision.models.mobilenet.MobileNetV2', class {});
  8728. this.registerType('torchvision.models.mobilenet.InvertedResidual', class {});
  8729. this.registerType('torchvision.models.mobilenetv2.ConvBNActivation', class {});
  8730. this.registerType('torchvision.models.mobilenetv2.InvertedResidual', class {});
  8731. this.registerType('torchvision.models.mobilenetv2.MobileNetV2', class {});
  8732. this.registerType('torchvision.models.mobilenetv3.InvertedResidual', class {});
  8733. this.registerType('torchvision.models.mobilenetv3.MobileNetV3', class {});
  8734. this.registerType('torchvision.models.mobilenetv3.SqueezeExcitation', class {});
  8735. this.registerType('torchvision.models.regnet.AnyStage', class extends torch.nn.modules.container.Sequential {});
  8736. this.registerType('torchvision.models.regnet.BottleneckTransform', class {});
  8737. this.registerType('torchvision.models.regnet.ResBottleneckBlock', class {});
  8738. this.registerType('torchvision.models.regnet.RegNet', class {});
  8739. this.registerType('torchvision.models.regnet.SimpleStemIN', class {});
  8740. this.registerType('torchvision.models.resnet.Bottleneck', class {});
  8741. this.registerType('torchvision.models.resnet.BasicBlock', class {});
  8742. this.registerType('torchvision.models.quantization.mobilenet.QuantizableInvertedResidual', class {});
  8743. this.registerType('torchvision.models.quantization.mobilenet.QuantizableMobileNetV2', class {});
  8744. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableInvertedResidual', class {});
  8745. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableMobileNetV2', class {});
  8746. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableMobileNetV3', class {});
  8747. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableInvertedResidual', class {});
  8748. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableSqueezeExcitation', class {});
  8749. this.registerType('torchvision.models.quantization.resnet.QuantizableBasicBlock', class {});
  8750. this.registerType('torchvision.models.quantization.resnet.QuantizableBottleneck', class {});
  8751. this.registerType('torchvision.models.quantization.resnet.QuantizableResNet', class {});
  8752. this.registerType('torchvision.models.segmentation.deeplabv3.ASPP', class {});
  8753. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPConv', class {});
  8754. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPPooling', class {});
  8755. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabHead', class {});
  8756. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabV3', class {});
  8757. this.registerType('torchvision.models.segmentation.fcn.FCN', class {});
  8758. this.registerType('torchvision.models.segmentation.fcn.FCNHead', class {});
  8759. this.registerType('torchvision.models.segmentation.lraspp.LRASPP', class {});
  8760. this.registerType('torchvision.models.segmentation.lraspp.LRASPPHead', class {});
  8761. this.registerType('torchvision.models.shufflenetv2.ShuffleNetV2', class {});
  8762. this.registerType('torchvision.models.shufflenetv2.InvertedResidual', class {});
  8763. this.registerType('torchvision.models.squeezenet.Fire', class {});
  8764. this.registerType('torchvision.models.squeezenet.SqueezeNet', class {});
  8765. this.registerType('torchvision.models.swin_transformer.PatchMerging', class {});
  8766. this.registerType('torchvision.models.swin_transformer.PatchMergingV2', class {});
  8767. this.registerType('torchvision.models.swin_transformer.ShiftedWindowAttention', class {});
  8768. this.registerType('torchvision.models.swin_transformer.ShiftedWindowAttentionV2', class {});
  8769. this.registerType('torchvision.models.swin_transformer.SwinTransformer', class {});
  8770. this.registerType('torchvision.models.swin_transformer.SwinTransformerBlock', class {});
  8771. this.registerType('torchvision.models.swin_transformer.SwinTransformerBlockV2', class {});
  8772. this.registerType('torchvision.models.resnet.ResNet', class {});
  8773. this.registerType('torchvision.models.vgg.VGG', class {});
  8774. this.registerType('torchvision.models.video.resnet.BasicBlock', class {});
  8775. this.registerType('torchvision.models.video.resnet.BasicStem', class {});
  8776. this.registerType('torchvision.models.video.resnet.Conv2Plus1D', class {});
  8777. this.registerType('torchvision.models.video.resnet.Conv3DNoTemporal', class {});
  8778. this.registerType('torchvision.models.video.resnet.Conv3DSimple', class {});
  8779. this.registerType('torchvision.models.video.resnet.R2Plus1dStem', class {});
  8780. this.registerType('torchvision.models.video.resnet.VideoResNet', class {});
  8781. this.registerType('torchvision.models.vision_transformer.Encoder', class extends torch.nn.modules.module.Module {});
  8782. this.registerType('torchvision.models.vision_transformer.EncoderBlock', class extends torch.nn.modules.module.Module {});
  8783. this.registerType('torchvision.models.vision_transformer.MLPBlock', class extends torchvision.ops.misc.MLP {});
  8784. this.registerType('torchvision.models.vision_transformer.VisionTransformer', class extends torch.nn.modules.module.Module {});
  8785. this.registerType('torchvision.models._utils.IntermediateLayerGetter', class {});
  8786. this.registerType('torchvision.transforms._presets.ImageClassification', class extends torch.nn.modules.module.Module {});
  8787. this.registerType('torchvision.transforms.autoaugment.AutoAugment', class {});
  8788. this.registerType('torchvision.transforms.autoaugment.AutoAugmentPolicy', class {});
  8789. this.registerType('torchvision.transforms.autoaugment.AugMix', class {});
  8790. this.registerType('torchvision.transforms.functional.InterpolationMode', class {});
  8791. this.registerFunction('torchvision.transforms.functional.adjust_brightness');
  8792. this.registerFunction('torchvision.transforms.functional.adjust_contrast');
  8793. this.registerFunction('torchvision.transforms.functional.adjust_brightness');
  8794. this.registerFunction('torchvision.transforms.functional.adjust_contrast');
  8795. this.registerFunction('torchvision.transforms.functional.adjust_gamma');
  8796. this.registerFunction('torchvision.transforms.functional.adjust_hue');
  8797. this.registerFunction('torchvision.transforms.functional.adjust_saturation');
  8798. this.registerType('torchvision.transforms.transforms.ColorJitter', class extends torch.nn.modules.module.Module {});
  8799. this.registerType('torchvision.transforms.transforms.Compose', class {});
  8800. this.registerType('torchvision.transforms.transforms.ConvertImageDtype', class {});
  8801. this.registerType('torchvision.transforms.transforms.CenterCrop', class extends torch.nn.modules.module.Module {});
  8802. this.registerType('torchvision.transforms.transforms.GaussianBlur', class extends torch.nn.modules.module.Module {});
  8803. this.registerType('torchvision.transforms.transforms.Grayscale', class extends torch.nn.modules.module.Module {});
  8804. this.registerType('torchvision.transforms.transforms.Lambda', class {});
  8805. this.registerType('torchvision.transforms.transforms.Normalize', class extends torch.nn.modules.module.Module {});
  8806. this.registerType('torchvision.transforms.transforms.PILToTensor', class {});
  8807. this.registerType('torchvision.transforms.transforms.RandomAffine', class extends torch.nn.modules.module.Module {});
  8808. this.registerType('torchvision.transforms.transforms.RandomApply', class extends torch.nn.modules.module.Module {});
  8809. this.registerType('torchvision.transforms.transforms.RandomCrop', class extends torch.nn.modules.module.Module {});
  8810. this.registerType('torchvision.transforms.transforms.RandomChoice', class {});
  8811. this.registerType('torchvision.transforms.transforms.RandomErasing', class {});
  8812. this.registerType('torchvision.transforms.transforms.RandomInvert', class {});
  8813. this.registerType('torchvision.transforms.transforms.RandomPerspective', class {});
  8814. this.registerType('torchvision.transforms.transforms.RandomHorizontalFlip', class extends torch.nn.modules.module.Module {});
  8815. this.registerType('torchvision.transforms.transforms.RandomVerticalFlip', class extends torch.nn.modules.module.Module {});
  8816. this.registerType('torchvision.transforms.transforms.RandomResizedCrop', class extends torch.nn.modules.module.Module {});
  8817. this.registerType('torchvision.transforms.transforms.RandomRotation', class extends torch.nn.modules.module.Module {});
  8818. this.registerType('torchvision.transforms.transforms.Resize', class extends torch.nn.modules.module.Module {});
  8819. this.registerType('torchvision.transforms.transforms.Scale', class extends torch.nn.modules.module.Module {});
  8820. this.registerType('torchvision.transforms.transforms.ToPILImage', class {});
  8821. this.registerType('torchvision.transforms.transforms.ToTensor', class {});
  8822. this.registerType('torchvision.transforms.v2._color.Grayscale', class {});
  8823. this.registerType('torchvision.transforms.v2._color.RandomGrayscale', class {});
  8824. this.registerType('torchvision.transforms.v2._container.Compose', class {});
  8825. this.registerType('torchvision.transforms.v2._deprecated.ToTensor', class {});
  8826. this.registerType('torchvision.transforms.v2._misc.ConvertImageDtype', class {});
  8827. this.registerType('torchvision.transforms.v2._misc.Normalize', class {});
  8828. this.registerType('torchvision.transforms.v2._misc.ToDtype', class {});
  8829. this.registerType('torchvision.transforms.v2._geometry.CenterCrop', class {});
  8830. this.registerType('torchvision.transforms.v2._geometry.Resize', class {});
  8831. this.registerType('torchvision.transforms.v2._geometry.Pad', class {});
  8832. this.registerType('torchvision.transforms.v2._geometry.RandomCrop', class {});
  8833. this.registerType('torchvision.transforms.v2._transform.Transform', class extends torch.nn.modules.module.Module {});
  8834. this.registerType('torchvision.transforms.v2._type_conversion.ToImage', class extends torchvision.transforms.v2._transform.Transform {});
  8835. this.registerType('torchvision.transforms.v2._type_conversion.PILToTensor', class {});
  8836. this.registerFunction('torchvision.models.resnet.resnet18', () => {});
  8837. this.registerFunction('torchvision.models.resnet.resnet34', () => {});
  8838. this.registerFunction('torchvision.models.resnet.resnet50', () => {});
  8839. this.registerFunction('torchvision.models.resnet.resnet101', () => {});
  8840. this.registerFunction('torchvision.models.resnet.resnet152', () => {});
  8841. this.registerFunction('torchvision.models.vision_transformer.vit_h_14', () => {});
  8842. this.registerFunction('torchvision.ops.boxes.box_iou');
  8843. this.registerFunction('torchvision.ops.focal_loss.sigmoid_focal_loss');
  8844. this.registerType('ultralytics.models.utils.loss.DETRLoss', class extends torch.nn.modules.module.Module {});
  8845. this.registerType('ultralytics.models.utils.loss.RTDETRDetectionLoss', class {});
  8846. this.registerType('ultralytics.models.utils.ops.HungarianMatcher', class extends torch.nn.modules.module.Module {});
  8847. this.registerType('ultralytics.nn.Addmodules.Dysample.Dy_Sample', class extends torch.nn.modules.module.Module {});
  8848. this.registerType('ultralytics.nn.Addmodules.MSCB.Bottleneck', class extends torch.nn.modules.module.Module {});
  8849. this.registerType('ultralytics.nn.Addmodules.MSCB.C3k', class extends torch.nn.modules.module.Module {});
  8850. this.registerType('ultralytics.nn.Addmodules.MSCB.C3k2_MSCB1', class extends torch.nn.modules.module.Module {});
  8851. this.registerType('ultralytics.nn.Addmodules.MSCB.Conv', class extends torch.nn.modules.module.Module {});
  8852. this.registerType('ultralytics.nn.Addmodules.MSCB.MSCB', class extends torch.nn.modules.module.Module {});
  8853. this.registerType('ultralytics.nn.Addmodules.MSCB.MSDC', class extends torch.nn.modules.module.Module {});
  8854. this.registerType('ultralytics.nn.Addmodules.ShuffleNetV2.InvertedResidual', class extends torch.nn.modules.module.Module {});
  8855. this.registerType('ultralytics.nn.Addmodules.ShuffleNetV2.ShuffleNetV2', class extends torch.nn.modules.module.Module {});
  8856. this.registerType('ultralytics.nn.attention.MSCA.MSCAAttention', class extends torch.nn.modules.module.Module {});
  8857. this.registerType('ultralytics.nn.extra_modules.attention.EMA', class extends torch.nn.modules.module.Module {});
  8858. this.registerType('ultralytics.nn.extra_modules.attention.SimAM', class extends torch.nn.modules.module.Module {});
  8859. this.registerType('ultralytics.nn.extra_modules.block.C2f_DWR_DRB', class extends torch.nn.modules.module.Module {});
  8860. this.registerType('ultralytics.nn.extra_modules.block.Conv', class extends torch.nn.modules.module.Module {});
  8861. this.registerType('ultralytics.nn.extra_modules.block.DWR_DRB', class extends torch.nn.modules.module.Module {});
  8862. this.registerType('ultralytics.nn.extra_modules.block.DilatedReparamBlock', class extends torch.nn.modules.module.Module {});
  8863. this.registerType('ultralytics.nn.extra_modules.block.DySample', class extends torch.nn.modules.module.Module {});
  8864. this.registerType('ultralytics.nn.extra_modules.block.GSBottleneckC', class extends torch.nn.modules.module.Module {});
  8865. this.registerType('ultralytics.nn.extra_modules.block.GSConv', class extends torch.nn.modules.module.Module {});
  8866. this.registerType('ultralytics.nn.extra_modules.block.VoVGSCSPC', class extends torch.nn.modules.module.Module {});
  8867. this.registerType('ultralytics.nn.extra_modules.head.Detect_Efficient', class extends torch.nn.modules.module.Module {});
  8868. this.registerType('ultralytics.nn.jirui_seg.FuseModule', class extends torch.nn.modules.module.Module {});
  8869. this.registerType('ultralytics.nn.jirui_seg.JiRuiSegHR', class extends torch.nn.modules.module.Module {});
  8870. this.registerType('ultralytics.nn.modules.activation.AGLU', class extends torch.nn.modules.module.Module {});
  8871. this.registerType('ultralytics.nn.modules.block.A2C2f', class extends torch.nn.modules.module.Module {});
  8872. this.registerType('ultralytics.nn.modules.block.AAttn', class extends torch.nn.modules.module.Module {});
  8873. this.registerType('ultralytics.nn.modules.block.ABlock', class extends torch.nn.modules.module.Module {});
  8874. this.registerType('ultralytics.nn.modules.block.AConv', class extends torch.nn.modules.module.Module {});
  8875. this.registerType('ultralytics.nn.modules.block.ADown', class extends torch.nn.modules.module.Module {});
  8876. this.registerType('ultralytics.nn.modules.block.AdaHGComputation', class extends torch.nn.modules.module.Module {});
  8877. this.registerType('ultralytics.nn.modules.block.AdaHGConv', class extends torch.nn.modules.module.Module {});
  8878. this.registerType('ultralytics.nn.modules.block.AdaHyperedgeGen', class extends torch.nn.modules.module.Module {});
  8879. this.registerType('ultralytics.nn.modules.block.Attention', class extends torch.nn.modules.module.Module {});
  8880. this.registerType('ultralytics.nn.modules.block.BNContrastiveHead', class extends torch.nn.modules.module.Module {});
  8881. this.registerType('ultralytics.nn.modules.block.BlockSplitAttention', class extends torch.nn.modules.module.Module {});
  8882. this.registerType('ultralytics.nn.modules.block.Bottleneck', class extends torch.nn.modules.module.Module {});
  8883. this.registerType('ultralytics.nn.modules.block.BottleneckCSP', class extends torch.nn.modules.module.Module {});
  8884. this.registerType('ultralytics.nn.modules.block.Bottleneck_PConv_Impl', class extends torch.nn.modules.module.Module {});
  8885. this.registerType('ultralytics.nn.modules.block.Bottleneck_Rep', class extends torch.nn.modules.module.Module {});
  8886. this.registerType('ultralytics.nn.modules.block.Bottleneck_ScConv', class extends torch.nn.modules.module.Module {});
  8887. this.registerType('ultralytics.nn.modules.block.C1', class extends torch.nn.modules.module.Module {});
  8888. this.registerType('ultralytics.nn.modules.block.C2', class extends torch.nn.modules.module.Module {});
  8889. this.registerType('ultralytics.nn.modules.block.C2f', class extends torch.nn.modules.module.Module {});
  8890. this.registerType('ultralytics.nn.modules.block.C2fAttn', class extends torch.nn.modules.module.Module {});
  8891. this.registerType('ultralytics.nn.modules.block.C2fCIB', class extends torch.nn.modules.module.Module {});
  8892. this.registerType('ultralytics.nn.modules.block.C2fPSA', class extends torch.nn.modules.module.Module {});
  8893. this.registerType('ultralytics.nn.modules.block.C2f_CA_PConv', class extends torch.nn.modules.module.Module {});
  8894. this.registerType('ultralytics.nn.modules.block.C2f_ScConv', class extends torch.nn.modules.module.Module {});
  8895. this.registerType('ultralytics.nn.modules.block.C2PSA', class extends torch.nn.modules.module.Module {});
  8896. this.registerType('ultralytics.nn.modules.block.C3', class extends torch.nn.modules.module.Module {});
  8897. this.registerType('ultralytics.nn.modules.block.C3f', class extends torch.nn.modules.module.Module {});
  8898. this.registerType('ultralytics.nn.modules.block.C3Ghost', class extends torch.nn.modules.module.Module {});
  8899. this.registerType('ultralytics.nn.modules.block.C3k', class extends torch.nn.modules.module.Module {});
  8900. this.registerType('ultralytics.nn.modules.block.C3k2', class extends torch.nn.modules.module.Module {});
  8901. this.registerType('ultralytics.nn.modules.block.C3k2_v2', class extends torch.nn.modules.module.Module {});
  8902. this.registerType('ultralytics.nn.modules.block.C3TR', class extends torch.nn.modules.module.Module {});
  8903. this.registerType('ultralytics.nn.modules.block.C3x', class extends torch.nn.modules.module.Module {});
  8904. this.registerType('ultralytics.nn.modules.block.C2tf', class extends torch.nn.modules.module.Module {});
  8905. this.registerType('ultralytics.nn.modules.block.CBFuse', class extends torch.nn.modules.module.Module {});
  8906. this.registerType('ultralytics.nn.modules.block.CBLinear', class extends torch.nn.modules.module.Module {});
  8907. this.registerType('ultralytics.nn.modules.block.CIB', class extends torch.nn.modules.module.Module {});
  8908. this.registerType('ultralytics.nn.modules.block.Channels', class extends torch.nn.modules.module.Module {});
  8909. this.registerType('ultralytics.nn.modules.block.ContrastiveHead', class extends torch.nn.modules.module.Module {});
  8910. this.registerType('ultralytics.nn.modules.block.Conv', class extends torch.nn.modules.module.Module {});
  8911. this.registerType('ultralytics.nn.modules.block.CoordAtt', class extends torch.nn.modules.module.Module {});
  8912. this.registerType('ultralytics.nn.modules.block.DFL', class extends torch.nn.modules.module.Module {});
  8913. this.registerType('ultralytics.nn.modules.block.DiffISP', class extends torch.nn.modules.module.Module {});
  8914. this.registerType('ultralytics.nn.modules.block.DSBottleneck', class extends torch.nn.modules.module.Module {});
  8915. this.registerType('ultralytics.nn.modules.block.DSC3k', class extends torch.nn.modules.module.Module {});
  8916. this.registerType('ultralytics.nn.modules.block.DSC3k2', class extends torch.nn.modules.module.Module {});
  8917. this.registerType('ultralytics.nn.modules.block.ELAN1', class extends torch.nn.modules.module.Module {});
  8918. this.registerType('ultralytics.nn.modules.block.GhostBottleneck', class extends torch.nn.modules.module.Module {});
  8919. this.registerType('ultralytics.nn.modules.block.HGBlock', class extends torch.nn.modules.module.Module {});
  8920. this.registerType('ultralytics.nn.modules.block.HGStem', class extends torch.nn.modules.module.Module {});
  8921. this.registerType('ultralytics.nn.modules.block.ImagePoolingAttn', class extends torch.nn.modules.module.Module {});
  8922. this.registerType('ultralytics.nn.modules.block.MaxSigmoidAttnBlock', class extends torch.nn.modules.module.Module {});
  8923. this.registerType('ultralytics.nn.modules.block.MobileNetV3_BLOCK', class extends torch.nn.modules.module.Module {});
  8924. this.registerType('ultralytics.nn.modules.block.PConv', class extends torch.nn.modules.module.Module {});
  8925. this.registerType('ultralytics.nn.modules.block.Proto', class extends torch.nn.modules.module.Module {});
  8926. this.registerType('ultralytics.nn.modules.block.Proto26', class extends torch.nn.modules.module.Module {});
  8927. this.registerType('ultralytics.nn.modules.block.PSA', class extends torch.nn.modules.module.Module {});
  8928. this.registerType('ultralytics.nn.modules.block.PSABlock', class extends torch.nn.modules.module.Module {});
  8929. this.registerType('ultralytics.nn.modules.block.RealNVP', class extends torch.nn.modules.module.Module {});
  8930. this.registerType('ultralytics.nn.modules.block.RepMLP_blockv4', class extends torch.nn.modules.module.Module {});
  8931. this.registerType('ultralytics.nn.modules.block.RepNMLPv4', class extends torch.nn.modules.module.Module {});
  8932. this.registerType('ultralytics.nn.modules.block.RepBottleneck', class extends torch.nn.modules.module.Module {});
  8933. this.registerType('ultralytics.nn.modules.block.RepC3', class extends torch.nn.modules.module.Module {});
  8934. this.registerType('ultralytics.nn.modules.block.RepCSP', class extends torch.nn.modules.module.Module {});
  8935. this.registerType('ultralytics.nn.modules.block.RepNCSPELAN4', class extends torch.nn.modules.module.Module {});
  8936. this.registerType('ultralytics.nn.modules.block.RepVGGDW', class extends torch.nn.modules.module.Module {});
  8937. this.registerType('ultralytics.nn.modules.block.Residual', class extends torch.nn.modules.module.Module {});
  8938. this.registerType('ultralytics.nn.modules.block.ResNetBlock', class extends torch.nn.modules.module.Module {});
  8939. this.registerType('ultralytics.nn.modules.block.ResNetLayer', class extends torch.nn.modules.module.Module {});
  8940. this.registerType('ultralytics.nn.modules.block.SAVPE', class extends torch.nn.modules.module.Module {});
  8941. this.registerType('ultralytics.nn.modules.block.SCDown', class extends torch.nn.modules.module.Module {});
  8942. this.registerType('ultralytics.nn.modules.block.SPP', class extends torch.nn.modules.module.Module {});
  8943. this.registerType('ultralytics.nn.modules.block.SPPELAN', class extends torch.nn.modules.module.Module {});
  8944. this.registerType('ultralytics.nn.modules.block.SPPF', class extends torch.nn.modules.module.Module {});
  8945. this.registerType('ultralytics.nn.modules.block.SwiGLUFFN', class extends torch.nn.modules.module.Module {});
  8946. this.registerType('ultralytics.nn.modules.block.TorchVision', class extends torch.nn.modules.module.Module {});
  8947. this.registerType('ultralytics.nn.modules.conv.CBAM', class extends torch.nn.modules.module.Module {});
  8948. this.registerType('ultralytics.nn.modules.conv.CRU', class extends torch.nn.modules.module.Module {});
  8949. this.registerType('ultralytics.nn.modules.conv.ChannelAttention', class extends torch.nn.modules.module.Module {});
  8950. this.registerType('ultralytics.nn.modules.conv.Concat', class extends torch.nn.modules.module.Module {});
  8951. this.registerType('ultralytics.nn.modules.conv.Conv', class extends torch.nn.modules.module.Module {});
  8952. this.registerType('ultralytics.nn.modules.conv.Conv2', class extends torch.nn.modules.module.Module {});
  8953. this.registerType('ultralytics.nn.modules.conv.ConvTranspose', class extends torch.nn.modules.module.Module {});
  8954. this.registerType('ultralytics.nn.modules.conv.DWConv', class extends torch.nn.modules.module.Module {});
  8955. this.registerType('ultralytics.nn.modules.conv.DWConvTranspose2d', class extends torch.nn.modules.module.Module {});
  8956. this.registerType('ultralytics.nn.modules.conv.Focus', class extends torch.nn.modules.module.Module {});
  8957. this.registerType('ultralytics.nn.modules.conv.GhostConv', class extends torch.nn.modules.module.Module {});
  8958. this.registerType('ultralytics.nn.modules.conv.GroupBatchnorm2d', class extends torch.nn.modules.module.Module {});
  8959. this.registerType('ultralytics.nn.modules.conv.Index', class extends torch.nn.modules.module.Module {});
  8960. this.registerType('ultralytics.nn.modules.conv.LightConv', class extends torch.nn.modules.module.Module {});
  8961. this.registerType('ultralytics.nn.modules.conv.CoordAtt', class extends torch.nn.modules.module.Module {});
  8962. this.registerType('ultralytics.nn.modules.conv.h_sigmoid', class extends torch.nn.modules.module.Module {});
  8963. this.registerType('ultralytics.nn.modules.conv.h_swish', class extends torch.nn.modules.module.Module {});
  8964. this.registerType('ultralytics.nn.modules.conv.RepConv', class extends torch.nn.modules.module.Module {});
  8965. this.registerType('ultralytics.nn.modules.conv.SRU', class extends torch.nn.modules.module.Module {});
  8966. this.registerType('ultralytics.nn.modules.conv.ScConv', class extends torch.nn.modules.module.Module {});
  8967. this.registerType('ultralytics.nn.modules.conv.SpatialAttention', class extends torch.nn.modules.module.Module {});
  8968. this.registerType('ultralytics.nn.modules.conv.mn_conv', class extends torch.nn.modules.module.Module {});
  8969. this.registerType('ultralytics.nn.modules.DAttention.DAttentionBaseline', class extends torch.nn.modules.module.Module {});
  8970. this.registerType('ultralytics.nn.modules.DAttention.LayerNormProxy', class extends torch.nn.modules.module.Module {});
  8971. this.registerType('ultralytics.nn.modules.DSConv.Bottleneck_DySnakeConv', class extends torch.nn.modules.module.Module {});
  8972. this.registerType('ultralytics.nn.modules.DSConv.C2f_DSConv', class extends torch.nn.modules.module.Module {});
  8973. this.registerType('ultralytics.nn.modules.DSConv.DSConv', class extends torch.nn.modules.module.Module {});
  8974. this.registerType('ultralytics.nn.modules.DSConv.DySnakeConv', class extends torch.nn.modules.module.Module {});
  8975. this.registerType('ultralytics.nn.modules.dysample.DySample', class extends torch.nn.modules.module.Module {});
  8976. this.registerType('ultralytics.nn.modules.head.Classify', class extends torch.nn.modules.module.Module {});
  8977. this.registerType('ultralytics.nn.modules.head.Detect', class extends torch.nn.modules.module.Module {});
  8978. this.registerType('ultralytics.nn.modules.head.LRPCHead', class extends torch.nn.modules.module.Module {});
  8979. this.registerType('ultralytics.nn.modules.head.MultiTask', class extends torch.nn.modules.module.Module {});
  8980. this.registerType('ultralytics.nn.modules.head.OBB', class extends torch.nn.modules.module.Module {});
  8981. this.registerType('ultralytics.nn.modules.head.OBB26', class extends torch.nn.modules.module.Module {});
  8982. this.registerType('ultralytics.nn.modules.head.Pose', class extends torch.nn.modules.module.Module {});
  8983. this.registerType('ultralytics.nn.modules.head.Pose26', class extends torch.nn.modules.module.Module {});
  8984. this.registerType('ultralytics.nn.modules.head.RealNVP', class extends torch.nn.modules.module.Module {});
  8985. this.registerType('ultralytics.nn.modules.head.RTDETRDecoder', class extends torch.nn.modules.module.Module {});
  8986. this.registerType('ultralytics.nn.modules.head.SAVPE', class extends torch.nn.modules.module.Module {});
  8987. this.registerType('ultralytics.nn.modules.head.Segment', class extends torch.nn.modules.module.Module {});
  8988. this.registerType('ultralytics.nn.modules.head.Segment26', class extends torch.nn.modules.module.Module {});
  8989. this.registerType('ultralytics.nn.modules.head.WorldDetect', class extends torch.nn.modules.module.Module {});
  8990. this.registerType('ultralytics.nn.modules.head.YOLOEDetect', class extends torch.nn.modules.module.Module {});
  8991. this.registerType('ultralytics.nn.modules.head.YOLOESegment', class extends torch.nn.modules.module.Module {});
  8992. this.registerType('ultralytics.nn.modules.head.YOLOESegment26', class extends torch.nn.modules.module.Module {});
  8993. this.registerType('ultralytics.nn.modules.head.v10Detect', class extends torch.nn.modules.module.Module {});
  8994. this.registerType('ultralytics.nn.modules.model_ajl.BottleneckCA', class extends torch.nn.modules.module.Module {});
  8995. this.registerType('ultralytics.nn.modules.model_ajl.C2fCA', class extends torch.nn.modules.module.Module {});
  8996. this.registerType('ultralytics.nn.modules.model_ajl.CA_Block', class extends torch.nn.modules.module.Module {});
  8997. this.registerType('ultralytics.nn.modules.moe.EfficientSpatialRouter', class extends torch.nn.modules.module.Module {});
  8998. this.registerType('ultralytics.nn.modules.moe.OptimizedMOEImproved', class extends torch.nn.modules.module.Module {});
  8999. this.registerType('ultralytics.nn.modules.moe.SimpleExpert', class extends torch.nn.modules.module.Module {});
  9000. this.registerType('ultralytics.nn.modules.moe.experts.SimpleExpert', class extends torch.nn.modules.module.Module {});
  9001. this.registerType('ultralytics.nn.modules.moe.loss.MoELoss', class {});
  9002. this.registerType('ultralytics.nn.modules.moe.modules.OptimizedMOEImproved', class extends torch.nn.modules.module.Module {});
  9003. this.registerType('ultralytics.nn.modules.moe.routers.EfficientSpatialRouter', class extends torch.nn.modules.module.Module {});
  9004. this.registerType('ultralytics.nn.modules.my_modules.FDConv_initialversion.FDConv', class extends torch.nn.modules.module.Module {});
  9005. this.registerType('ultralytics.nn.modules.my_modules.GGCA.GGCA_Std', class extends torch.nn.modules.module.Module {});
  9006. this.registerType('ultralytics.nn.modules.my_modules.my_modules.ADown', class extends torch.nn.modules.module.Module {});
  9007. this.registerType('ultralytics.nn.modules.my_modules.my_modules.Bottleneck_PFDConv', class extends torch.nn.modules.module.Module {});
  9008. this.registerType('ultralytics.nn.modules.my_modules.my_modules.C3k2_PFDConv', class extends torch.nn.modules.module.Module {});
  9009. this.registerType('ultralytics.nn.modules.my_modules.my_modules.C3k_PFDConv', class extends torch.nn.modules.module.Module {});
  9010. this.registerType('ultralytics.nn.modules.my_modules.my_modules.Partial_FDConv', class extends torch.nn.modules.module.Module {});
  9011. this.registerType('ultralytics.nn.modules.new.RepBlock', class extends torch.nn.modules.module.Module {});
  9012. this.registerType('ultralytics.nn.modules.new.RFConv', class extends torch.nn.modules.module.Module {});
  9013. this.registerType('ultralytics.nn.modules.new.SPDConv', class extends torch.nn.modules.module.Module {});
  9014. this.registerType('ultralytics.nn.modules.new.StandardConv', class extends torch.nn.modules.module.Module {});
  9015. this.registerType('ultralytics.nn.modules.transformer.AIFI', class extends torch.nn.modules.module.Module {});
  9016. this.registerType('ultralytics.nn.modules.transformer.DeformableTransformerDecoder', class extends torch.nn.modules.module.Module {});
  9017. this.registerType('ultralytics.nn.modules.transformer.DeformableTransformerDecoderLayer', class extends torch.nn.modules.module.Module {});
  9018. this.registerType('ultralytics.nn.modules.transformer.LayerNorm2d', class extends torch.nn.modules.module.Module {});
  9019. this.registerType('ultralytics.nn.modules.transformer.MLP', class extends torch.nn.modules.module.Module {});
  9020. this.registerType('ultralytics.nn.modules.transformer.MLPBlock', class extends torch.nn.modules.module.Module {});
  9021. this.registerType('ultralytics.nn.modules.transformer.MSDeformAttn', class extends torch.nn.modules.module.Module {});
  9022. this.registerType('ultralytics.nn.modules.transformer.TransformerBlock', class extends torch.nn.modules.module.Module {});
  9023. this.registerType('ultralytics.nn.modules.transformer.TransformerEncoderLayer', class extends torch.nn.modules.module.Module {});
  9024. this.registerType('ultralytics.nn.modules.transformer.TransformerLayer', class extends torch.nn.modules.module.Module {});
  9025. this.registerType('ultralytics.nn.modules.Bottleneck', class extends torch.nn.modules.module.Module {});
  9026. this.registerType('ultralytics.nn.modules.C2f', class extends torch.nn.modules.module.Module {});
  9027. this.registerType('ultralytics.nn.modules.Concat', class extends torch.nn.modules.module.Module {});
  9028. this.registerType('ultralytics.nn.modules.Conv', class extends torch.nn.modules.module.Module {});
  9029. this.registerType('ultralytics.nn.modules.DFL', class extends torch.nn.modules.module.Module {});
  9030. this.registerType('ultralytics.nn.modules.Detect', class extends torch.nn.modules.module.Module {});
  9031. this.registerType('ultralytics.nn.modules.Pose', class extends torch.nn.modules.module.Module {});
  9032. this.registerType('ultralytics.nn.modules.Proto', class extends torch.nn.modules.module.Module {});
  9033. this.registerType('ultralytics.nn.modules.SPPF', class extends torch.nn.modules.module.Module {});
  9034. this.registerType('ultralytics.nn.modules.Segment', class extends torch.nn.modules.module.Module {});
  9035. this.registerType('ultralytics.nn.modules.CA.CoordAtt', class extends torch.nn.modules.module.Module {});
  9036. this.registerType('ultralytics.nn.modules.CA.h_sigmoid', class extends torch.nn.modules.module.Module {});
  9037. this.registerType('ultralytics.nn.modules.CA.h_swish', class extends torch.nn.modules.module.Module {});
  9038. this.registerType('ultralytics.nn.modules.CoordConv.AddCoords', class extends torch.nn.modules.module.Module {});
  9039. this.registerType('ultralytics.nn.modules.CoordConv.CoordConv', class extends torch.nn.modules.module.Module {});
  9040. this.registerType('ultralytics.nn.modules.ECA.ECA', class extends torch.nn.modules.module.Module {});
  9041. this.registerType('ultralytics.nn.extra_modules.Down_WT.Down_wt', class extends torch.nn.modules.module.Module {});
  9042. this.registerType('ultralytics.nn.extra_modules.prune_module.C3k2_v2', class extends torch.nn.modules.module.Module {});
  9043. this.registerType('ultralytics.nn.tasks.BaseModel', class extends torch.nn.modules.module.Module {});
  9044. this.registerType('ultralytics.nn.tasks.ClassificationModel', class extends torch.nn.modules.module.Module {});
  9045. this.registerType('ultralytics.nn.tasks.DetectionModel', class extends torch.nn.modules.module.Module {});
  9046. this.registerType('ultralytics.nn.tasks.Ensemble', class extends torch.nn.modules.module.Module {});
  9047. this.registerType('ultralytics.nn.tasks.MultiTaskModel', class extends torch.nn.modules.module.Module {});
  9048. this.registerType('ultralytics.nn.tasks.OBBModel', class extends torch.nn.modules.module.Module {});
  9049. this.registerType('ultralytics.nn.tasks.PoseModel', class extends torch.nn.modules.module.Module {});
  9050. this.registerType('ultralytics.nn.tasks.RTDETRDetectionModel', class extends torch.nn.modules.module.Module {});
  9051. this.registerType('ultralytics.nn.tasks.SegmentationModel', class extends torch.nn.modules.module.Module {});
  9052. this.registerType('ultralytics.nn.tasks.SemanticSegmentationModel', class extends torch.nn.modules.module.Module {});
  9053. this.registerType('ultralytics.nn.tasks.WorldModel', class extends torch.nn.modules.module.Module {});
  9054. this.registerType('ultralytics.nn.tasks.YOLOEModel', class extends torch.nn.modules.module.Module {});
  9055. this.registerType('ultralytics.nn.tasks.YOLOESegModel', class extends torch.nn.modules.module.Module {});
  9056. this.registerType('ultralytics.nn.tasks.YOLOv10DetectionModel', class extends torch.nn.modules.module.Module {});
  9057. this.registerType('ultralytics.utils.IterableSimpleNamespace', class {});
  9058. this.registerType('ultralytics.utils.loss.BCEDiceLoss', class extends torch.nn.modules.module.Module {});
  9059. this.registerType('ultralytics.utils.loss.BboxLoss', class extends torch.nn.modules.module.Module {});
  9060. this.registerType('ultralytics.utils.loss.DFLoss', class extends torch.nn.modules.module.Module {});
  9061. this.registerType('ultralytics.utils.loss.E2EDetectLoss', class {});
  9062. this.registerType('ultralytics.utils.loss.E2ELoss', class {});
  9063. this.registerType('ultralytics.utils.loss.FocalLoss', class extends torch.nn.modules.module.Module {});
  9064. this.registerType('ultralytics.utils.loss.KeypointLoss', class extends torch.nn.modules.module.Module {});
  9065. this.registerType('ultralytics.utils.loss.MultiChannelDiceLoss', class extends torch.nn.modules.module.Module {});
  9066. this.registerType('ultralytics.utils.loss.PoseLoss26', class extends torch.nn.modules.module.Module {});
  9067. this.registerType('ultralytics.utils.loss.RLELoss', class extends torch.nn.modules.module.Module {});
  9068. this.registerType('ultralytics.utils.loss.RotatedBboxLoss', class extends torch.nn.modules.module.Module {});
  9069. this.registerType('ultralytics.utils.loss.SlideLoss', class extends torch.nn.modules.module.Module {});
  9070. this.registerType('ultralytics.utils.loss.TVPDetectLoss', class {});
  9071. this.registerType('ultralytics.utils.loss.TVPSegmentLoss', class {});
  9072. this.registerType('ultralytics.utils.loss.VarifocalLoss', class extends torch.nn.modules.module.Module {});
  9073. this.registerType('ultralytics.utils.loss.v8ClassificationLoss', class {});
  9074. this.registerType('ultralytics.utils.loss.v8DetectionLoss', class {});
  9075. this.registerType('ultralytics.utils.loss.v8OBBLoss', class {});
  9076. this.registerType('ultralytics.utils.loss.v8PoseLoss', class {});
  9077. this.registerType('ultralytics.utils.loss.v8SegmentationLoss', class {});
  9078. this.registerType('ultralytics.utils.loss.v10DetectLoss', class {});
  9079. this.registerType('ultralytics.utils.tal.RotatedTaskAlignedAssigner', class extends torch.nn.modules.module.Module {});
  9080. this.registerType('ultralytics.utils.tal.TaskAlignedAssigner', class extends torch.nn.modules.module.Module {});
  9081. this.registerType('ultralytics.utils.torch_utils.EarlyStopping', class {});
  9082. this.registerType('ultralytics.utils.torch_utils.ModelEMA', class {});
  9083. this.registerType('ultralytics.yolo.utils.IterableSimpleNamespace', class {});
  9084. this.registerType('ultralytics.yolo.utils.loss.BboxLoss', class extends torch.nn.modules.module.Module {});
  9085. this.registerType('ultralytics.yolo.utils.loss.v8DetectionLoss', class {});
  9086. this.registerType('ultralytics.yolo.utils.tal.TaskAlignedAssigner', class extends torch.nn.modules.module.Module {});
  9087. this.registerFunction('builtins.annotate', (type, value) => {
  9088. if (type === builtins.int) {
  9089. return Number.isInteger(value) ? value : NaN;
  9090. }
  9091. if (type === builtins.float) {
  9092. return typeof value === 'number' ? value : NaN;
  9093. }
  9094. if (type === builtins.number) {
  9095. // if (pytorch.Utility.isTensor(value)) {
  9096. // value.resize_([]);
  9097. // }
  9098. }
  9099. return value;
  9100. });
  9101. this.registerFunction('builtins.uninitialized', (/* type */) => {
  9102. return undefined;
  9103. });
  9104. this.registerFunction('builtins.range', (start, stop, step) => {
  9105. if (stop === undefined && step === undefined) {
  9106. if (Number.isInteger(start)) {
  9107. return Array(start).keys();
  9108. }
  9109. if (isNaN(start)) {
  9110. return [];
  9111. }
  9112. }
  9113. if (Number.isInteger(start) && Number.isInteger(stop) && (step === undefined || Number.isInteger(step))) {
  9114. step = step === undefined ? 1 : step;
  9115. const result = [];
  9116. if (step > 0) {
  9117. for (let i = start; i < stop; i += step) {
  9118. result.push(i);
  9119. }
  9120. } else if (step < 0) {
  9121. for (let i = start; i > stop; i += step) {
  9122. result.push(i);
  9123. }
  9124. }
  9125. return result;
  9126. }
  9127. throw new python.Error(`Unsupported range(${JSON.stringify(start)}, ${JSON.stringify(stop)}, ${JSON.stringify(step)})`);
  9128. });
  9129. this.registerFunction('math.trunc');
  9130. builtins.xrange = builtins.range;
  9131. this.registerFunction('torch._C._nn.gelu');
  9132. this.registerFunction('torch._C._nn.avg_pool2d');
  9133. this.registerFunction('torch._C._nn.avg_pool3d');
  9134. this.registerFunction('torch._C._nn.scaled_dot_product_attention');
  9135. this.registerFunction('torch._C._nn.softplus');
  9136. this.registerFunction('torch._native_multi_head_attention');
  9137. this.registerFunction('torch._utils._rebuild_sparse_tensor', (layout, data) => {
  9138. if (layout === torch.sparse_coo) {
  9139. return self.invoke('torch._sparse_coo_tensor_unsafe', data);
  9140. }
  9141. throw new python.Error(`Unsupported sparse tensor layout '${layout ? layout.__str__() : ''}'.`);
  9142. });
  9143. this.registerFunction('torch._utils._get_restore_location', (device) => {
  9144. return device;
  9145. });
  9146. this.registerFunction('torch._utils._rebuild_wrapper_subclass', (cls, dtype, size, stride, storage_offset, layout, device, requires_grad) => {
  9147. device = torch._utils._get_restore_location(device);
  9148. return torch.Tensor._make_wrapper_subclass(cls, size, stride, dtype, storage_offset, layout, device, requires_grad);
  9149. });
  9150. this.registerFunction('torch.from_numpy', (obj) => {
  9151. const dtypes = new Map([
  9152. ['<f2', torch.float16],
  9153. ['<f4', torch.float32],
  9154. ['<f8', torch.float64],
  9155. ['<i2', torch.int16],
  9156. ['<i4', torch.int32],
  9157. ['<i8', torch.int64],
  9158. ]);
  9159. if (!dtypes.has(obj.dtype.str)) {
  9160. throw new python.Error(`Unsupported numpy.ndarray type '${obj.dtype.str}'.`);
  9161. }
  9162. const dtype = dtypes.get(obj.dtype.str);
  9163. const strides = obj.strides.map((stride) => stride / obj.itemsize);
  9164. const storage = new torch.storage.TypedStorage(obj.size, dtype);
  9165. storage._set_cdata(obj.data);
  9166. const tensor = new torch.Tensor();
  9167. tensor.__setstate__([storage, 0, obj.shape, strides]);
  9168. return tensor;
  9169. });
  9170. this.registerFunction('torch._utils._rebuild_device_tensor_from_numpy', (data, dtype, device, requires_grad) => {
  9171. const tensor = torch.from_numpy(data);
  9172. // tensor = tensor.to(dtype, device)
  9173. tensor.requires_grad = requires_grad;
  9174. return tensor;
  9175. });
  9176. this.registerFunction('torch._utils._rebuild_device_tensor_from_cpu_tensor', (data, dtype, device, requires_grad) => {
  9177. data = data.clone();
  9178. data.requires_grad = requires_grad;
  9179. return data;
  9180. });
  9181. this.registerFunction('torch._sparse_coo_tensor_unsafe', (indices, values, size) => {
  9182. const tensor = self.invoke('torch.Tensor', []);
  9183. tensor._layout = torch.sparse_coo;
  9184. tensor._indices = indices;
  9185. tensor._values = values;
  9186. tensor._shape = size;
  9187. return tensor;
  9188. });
  9189. this.registerFunction('torch._utils.set_tensor_metadata', (tensor, metadata) => {
  9190. torch._C._set_tensor_metadata(tensor, metadata);
  9191. });
  9192. this.registerFunction('torch._utils._restore_device_fake_mode', (tensor) => {
  9193. return tensor;
  9194. });
  9195. this.registerFunction('torch._utils._rebuild_meta_tensor_no_storage', (dtype, size, stride, requires_grad) => {
  9196. return torch.empty_strided(size, stride, dtype, null, 'meta', false, requires_grad);
  9197. });
  9198. this.registerFunction('torch._utils._rebuild_tensor', (storage, storage_offset, size, stride) => {
  9199. if (Array.isArray(storage) && storage.length === 5 && storage[0] === 'storage') {
  9200. const [, storage_type, , ,size] = storage;
  9201. storage = new storage_type(size);
  9202. }
  9203. const tensor = new torch.Tensor();
  9204. tensor.__setstate__([storage, storage_offset, size, stride]);
  9205. return tensor;
  9206. });
  9207. this.registerFunction('torch._utils._rebuild_tensor_v2', (storage, storage_offset, size, stride, requires_grad, backward_hooks, metadata) => {
  9208. const tensor = torch._utils._rebuild_tensor(storage, storage_offset, size, stride);
  9209. tensor.requires_grad = requires_grad;
  9210. if (metadata) {
  9211. torch._utils.set_tensor_metadata(tensor, metadata);
  9212. }
  9213. tensor.backward_hooks = backward_hooks;
  9214. return tensor;
  9215. });
  9216. this.registerFunction('torch._utils._rebuild_tensor_v3', (storage, storage_offset, size, stride, requires_grad, backward_hooks, dtype, metadata) => {
  9217. const t = new torch.Tensor(null, null, dtype);
  9218. t.set_(storage, storage_offset, size, stride);
  9219. if (metadata) {
  9220. torch._utils.set_tensor_metadata(t, metadata);
  9221. }
  9222. t._backward_hooks = backward_hooks;
  9223. return torch._utils._restore_device_fake_mode(t);
  9224. });
  9225. this.registerFunction('torch._utils._rebuild_parameter', (data, requires_grad, backward_hooks) => {
  9226. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  9227. param.backward_hooks = backward_hooks;
  9228. return param;
  9229. });
  9230. this.registerFunction('torch._utils._rebuild_parameter_v2', (data, requires_grad, backward_hooks, state) => {
  9231. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  9232. param.backward_hooks = backward_hooks;
  9233. torch._utils._set_obj_state(param, state);
  9234. return param;
  9235. });
  9236. this.registerFunction('torch._utils._rebuild_parameter_with_state', (data, requires_grad, backward_hooks, state) => {
  9237. const _set_obj_state = (obj, state) => {
  9238. const [dict_state, slots_state] = Array.isArray(state) ? state : [state, null];
  9239. if (dict_state) {
  9240. for (const [k, v] of Object.entries(dict_state)) {
  9241. builtins.setattr(obj, k, v);
  9242. }
  9243. }
  9244. if (slots_state) {
  9245. for (const [k, v] of Object.entries(slots_state)) {
  9246. builtins.setattr(obj, k, v);
  9247. }
  9248. }
  9249. };
  9250. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  9251. param._backward_hooks = backward_hooks;
  9252. _set_obj_state(param, state);
  9253. return param;
  9254. });
  9255. this.registerFunction('torch._utils._rebuild_qtensor', (storage, storage_offset, size, stride, quantizer_params, requires_grad, backward_hooks) => {
  9256. const tensor = torch._utils._rebuild_tensor_v2(storage, storage_offset, size, stride, requires_grad, backward_hooks);
  9257. tensor.quantizer_params = quantizer_params;
  9258. return tensor;
  9259. });
  9260. this.registerFunction('torch._utils._set_obj_state', (obj, state) => {
  9261. let dict_state = state;
  9262. let slots_state = null;
  9263. if (state instanceof self.builtins.tuple) {
  9264. if (state.length !== 2) {
  9265. throw new python.Error(`Invalid serialized state: '${state}'.`);
  9266. }
  9267. [dict_state, slots_state] = state;
  9268. }
  9269. if (dict_state) {
  9270. const entries = dict_state instanceof Map ? dict_state : Object.entries(dict_state);
  9271. for (const [name, value] of entries) {
  9272. builtins.setattr(obj, name, value);
  9273. }
  9274. }
  9275. if (slots_state) {
  9276. const entries = slots_state instanceof Map ? slots_state : Object.entries(slots_state);
  9277. for (const [name, value] of entries) {
  9278. builtins.setattr(obj, name, value);
  9279. }
  9280. }
  9281. return obj;
  9282. });
  9283. this.registerFunction('torch._set_item', (dict, key, value) => {
  9284. dict[key] = value;
  9285. });
  9286. this.registerFunction('torch._tensor._rebuild_from_type_v2', (func, new_type, args, state) => {
  9287. let ret = func(...args);
  9288. if (ret.__class__ !== new_type) {
  9289. ret.__class__ = new_type;
  9290. }
  9291. const setstate = builtins.getattr(ret.__class__, '__setstate__', torch.Tensor.__setstate__);
  9292. if (setstate === torch.Tensor.__setstate__) {
  9293. ret = torch._utils._set_obj_state(ret, state);
  9294. } else {
  9295. ret.__setstate__(state);
  9296. }
  9297. return ret;
  9298. });
  9299. this.registerFunction('torch.__range_length', (lo, hi, step) => {
  9300. if (step === 0) {
  9301. throw new python.Error('range() arg 3 must not be zero');
  9302. }
  9303. if (step > 0 && lo < hi) {
  9304. return 1 + (hi - 1 - lo) / step;
  9305. } else if (step < 0 && lo > hi) {
  9306. return 1 + (lo - 1 - hi) / (0 - step);
  9307. }
  9308. return 0;
  9309. });
  9310. this.registerFunction('torch._nested_tensor_from_mask_left_aligned');
  9311. this.registerOperator('aten::_unwrap_optional', (value) => {
  9312. return value;
  9313. });
  9314. this.registerFunction('torch.get_default_dtype', () => {
  9315. torch._default_type = torch._default_type || torch.float32;
  9316. return torch._default_type;
  9317. });
  9318. this.registerFunction('torch.set_default_dtype', (value) => {
  9319. torch._default_type = value;
  9320. });
  9321. this.registerFunction('torch._prims_common.dtype_or_default', (value) => {
  9322. return value || torch.get_default_dtype();
  9323. });
  9324. this.registerFunction('torch.empty_strided', (size, stride, dtype, layout, device, pin_memory, requires_grad) => {
  9325. const shape = size;
  9326. dtype = torch._prims_common.dtype_or_default(dtype);
  9327. let storage = null;
  9328. if (size.every((d) => d instanceof torch.SymInt === false)) {
  9329. const size = shape.reduce((a, b) => a * b, 1);
  9330. storage = new torch.storage.TypedStorage(size, dtype);
  9331. }
  9332. const tensor = new torch.Tensor(storage, shape, dtype, layout, device, requires_grad);
  9333. tensor.__setstate__([storage, 0, shape, stride]);
  9334. return tensor;
  9335. });
  9336. this.registerFunction('torch.all', (input) => {
  9337. if (Array.isArray(input) && input.length === 0) {
  9338. return true;
  9339. }
  9340. throw new python.Error(`Unsupported 'torch.all' expression type.`);
  9341. });
  9342. this.registerFunction('torch.append', (list, value) => {
  9343. list.push(value);
  9344. return value;
  9345. });
  9346. this.registerFunction('torch.clear', (value) => {
  9347. if (value instanceof torch.Value) {
  9348. throw new python.Error('Invalid value.');
  9349. }
  9350. if (Object(value) === value) {
  9351. for (const key of Object.keys(value)) {
  9352. delete value[key];
  9353. }
  9354. }
  9355. });
  9356. this.registerFunction('torch.dict', (args) => {
  9357. const obj = {};
  9358. if (args) {
  9359. if (Array.isArray(args)) {
  9360. for (const [key, value] of args) {
  9361. obj[key] = value;
  9362. }
  9363. } else {
  9364. throw new python.Error("'torch.dict' arguments not supported.");
  9365. }
  9366. }
  9367. return obj;
  9368. });
  9369. this.registerOperator('aten::cosine_similarity', () => {
  9370. throw new python.Error(`'aten::cosine_similarity' not implemented.`);
  9371. });
  9372. this.registerOperator('aten::extend', (list, value) => {
  9373. list.push(...value);
  9374. });
  9375. this.registerOperator('aten::insert', (list, index, value) => {
  9376. list.splice(index, 0, value);
  9377. return value;
  9378. });
  9379. this.registerOperator('aten::replace', (value, oldvalue, newvalue /*, max */) => {
  9380. return value.replace(oldvalue, newvalue);
  9381. });
  9382. this.registerOperator('aten::add', (a, b) => {
  9383. if ((typeof a === 'number' || a instanceof Number) && (typeof b === 'number' || b instanceof Number)) {
  9384. return a + b;
  9385. }
  9386. if (typeof a === 'number' && b instanceof builtins.complex) {
  9387. return new builtins.complex(a + b.real, b.imag);
  9388. }
  9389. if (a instanceof builtins.complex && typeof b === 'number') {
  9390. return new builtins.complex(a.real + b, a.imag);
  9391. }
  9392. if (a instanceof builtins.complex && b instanceof builtins.complex) {
  9393. return new builtins.complex(a.real + b.real, a.imag + b.imag);
  9394. }
  9395. if (Array.isArray(a) && Array.isArray(b)) {
  9396. return a.concat(b);
  9397. }
  9398. if (typeof a === 'string' && typeof b === 'string') {
  9399. return a + b;
  9400. }
  9401. throw new python.Error('Unsupported aten::add expression type.');
  9402. });
  9403. this.registerOperator('aten::log', (x) => {
  9404. if (typeof x === 'number' || x instanceof Number) {
  9405. return Math.log(x);
  9406. }
  9407. throw new python.Error('Unsupported aten::log expression type.');
  9408. });
  9409. this.registerOperator('aten::dim', (tensor) => {
  9410. if (tensor && tensor.size) {
  9411. const size = tensor.size();
  9412. if (size) {
  9413. return size.length;
  9414. }
  9415. }
  9416. return NaN;
  9417. });
  9418. this.registerOperator('aten::numel', (tensor) => {
  9419. if (tensor && tensor.size) {
  9420. const size = tensor.size();
  9421. if (size) {
  9422. return size.reduce((a, b) => a * b, 1);
  9423. }
  9424. }
  9425. return NaN;
  9426. });
  9427. this.registerOperator('aten::eq', (left, right) => {
  9428. if (typeof left === 'string' && typeof right === 'string') {
  9429. return left === right;
  9430. }
  9431. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9432. if (isNaN(left) && isNaN(right)) {
  9433. return true;
  9434. }
  9435. return left === right;
  9436. }
  9437. if (left === undefined || right === undefined) {
  9438. return true;
  9439. }
  9440. if (Array.isArray(left) && Array.isArray(right)) {
  9441. return left.length === right.length && left.every((item, index) => item === right[index]);
  9442. }
  9443. throw new python.Error("Unsupported 'torch.eq' expression type.");
  9444. });
  9445. this.registerOperator('aten::floor', (value) => {
  9446. return Math.floor(value);
  9447. });
  9448. this.registerOperator('aten::ceil', (value) => {
  9449. return Math.ceil(value);
  9450. });
  9451. this.registerOperator('aten::floordiv', (left, right) => {
  9452. return Math.floor(left / right);
  9453. });
  9454. this.registerOperator('aten::format', (...args) => {
  9455. const list = args.shift().split(/({}D?)/);
  9456. return list.map((text) => {
  9457. if (text === '{}' || text === '{}D') {
  9458. const arg = args.shift();
  9459. if (Array.isArray(arg)) {
  9460. return `[${arg.map((item) => item.toString()).join(', ')}]`;
  9461. }
  9462. return arg ? arg.toString() : '?';
  9463. }
  9464. return text;
  9465. }).join('');
  9466. });
  9467. this.registerOperator('aten::strip', (self, chars) => {
  9468. chars = chars || '\\n\\t\\f\\v';
  9469. const regex = new RegExp(`[${chars}]`, 'g');
  9470. return self.replace(regex, '');
  9471. });
  9472. this.registerOperator('aten::gt', (left, right) => {
  9473. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9474. if (!isNaN(left) && !isNaN(right)) {
  9475. return left > right;
  9476. }
  9477. }
  9478. if (isNaN(left) && !isNaN(right)) {
  9479. return true;
  9480. }
  9481. throw new python.Error("Unsupported 'ops.aten.gt' expression type.");
  9482. });
  9483. this.registerOperator('aten::ge', (left, right) => {
  9484. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9485. if (!isNaN(left) && !isNaN(right)) {
  9486. return left > right;
  9487. }
  9488. }
  9489. if (isNaN(left) && !isNaN(right)) {
  9490. return true;
  9491. }
  9492. throw new python.Error("Unsupported 'ops.aten.ge' expression type.");
  9493. });
  9494. this.registerOperator('aten::is_floating_point', (tensor) => {
  9495. const type = tensor.dtype.scalar_type();
  9496. return (type === 5 || type === 6 || type === 7);
  9497. });
  9498. this.registerOperator('aten::is_grad_enabled', () => {
  9499. return false;
  9500. });
  9501. this.registerOperator('aten::is_autocast_enabled', () => {
  9502. return false;
  9503. });
  9504. this.registerOperator('aten::isfinite');
  9505. this.registerOperator('aten::set_grad_enabled', (/* value */) => {
  9506. });
  9507. this.registerFunction('torch.serialization._get_layout', (name) => {
  9508. const value = name.startsWith('torch.') ? torch[name.split('.')[1]] : null;
  9509. return value instanceof torch.layout ? value : null;
  9510. });
  9511. this.registerFunction('torch.storage._load_from_bytes', (b) => {
  9512. return torch.load(b);
  9513. });
  9514. this.registerFunction('torch.jit._pickle.build_boollist', (data) => {
  9515. return data;
  9516. });
  9517. this.registerFunction('torch.jit._pickle.build_doublelist', (data) => {
  9518. return data;
  9519. });
  9520. this.registerFunction('torch.jit._pickle.build_intlist', (data) => {
  9521. return data;
  9522. });
  9523. this.registerFunction('torch.jit._pickle.build_tensorlist', (data) => {
  9524. return data;
  9525. });
  9526. this.registerFunction('torch.jit._pickle.build_tensor_from_id', (data) => {
  9527. return self.builtins.CONSTANTS[`c${data}`];
  9528. });
  9529. this.registerFunction('torch.jit._pickle.restore_type_tag', (value /*, type_str */) => {
  9530. return value;
  9531. });
  9532. this.registerOperator('aten::keys', (dict) => {
  9533. return Object.keys(dict);
  9534. });
  9535. this.registerOperator('aten::len', (value) => {
  9536. if (Array.isArray(value)) {
  9537. return value.length;
  9538. }
  9539. if (value && value.shape && value.__len__) {
  9540. return value.__len__();
  9541. }
  9542. return NaN;
  9543. });
  9544. this.registerOperator('aten::le', (left, right) => {
  9545. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9546. if (isNaN(left) || isNaN(right)) {
  9547. return false;
  9548. }
  9549. return left <= right;
  9550. }
  9551. if (left === undefined || right === undefined) {
  9552. return true;
  9553. }
  9554. throw new python.Error("Unsupported 'torch.le' expression type.");
  9555. });
  9556. this.registerOperator('aten::list', (args) => {
  9557. return args;
  9558. });
  9559. this.registerOperator('aten::list_with_default', (size /*, defaults */) => {
  9560. return size;
  9561. });
  9562. this.registerType('torch.PyTorchFileReader', class {
  9563. constructor(entries) {
  9564. let prefix = 0;
  9565. const paths = Array.from(entries.keys()).map((path) => path.replace(/\\/g, '/').split('/').reverse());
  9566. for (let set = new Set(); set && paths.length > 0;) {
  9567. set = new Set(paths.map((path) => path.length > 1 ? path.pop() : null));
  9568. set = set.size > 1 || set.keys().next().value === null ? null : set;
  9569. prefix += set ? set.keys().next().value.length + 1 : 0;
  9570. }
  9571. this._records = new Map(Array.from(entries).map(([name, value]) => [name.substring(prefix), value]));
  9572. this._version = 0;
  9573. this.init();
  9574. }
  9575. init() {
  9576. let stream = null;
  9577. if (this.has_record('.data/version')) {
  9578. stream = this.get_record('.data/version');
  9579. } else if (this.has_record('version')) {
  9580. stream = this.get_record('version');
  9581. }
  9582. if (stream) {
  9583. const decoder = new TextDecoder('utf-8');
  9584. const buffer = stream.peek();
  9585. const text = decoder.decode(buffer);
  9586. this._version = Number(text.split('\n').shift().trim());
  9587. }
  9588. }
  9589. has_record(name) {
  9590. return this._records.has(name);
  9591. }
  9592. get_record(name) {
  9593. if (!this.has_record(name)) {
  9594. throw new python.Error(`Record '${name}' not found.`);
  9595. }
  9596. return this._records.get(name);
  9597. }
  9598. get_all_records() {
  9599. return Array.from(this._records.keys());
  9600. }
  9601. version() {
  9602. return this._version;
  9603. }
  9604. });
  9605. this.registerFunction('torch.load', (f) => {
  9606. const legacy_load = (entries) => {
  9607. const deserialized_objects = {};
  9608. if (entries.has('storages')) {
  9609. const data = entries.get('storages');
  9610. const unpickler = new pickle.Unpickler(data);
  9611. const num_storages = unpickler.load();
  9612. for (let i = 0; i < num_storages; i++) {
  9613. const args = unpickler.load();
  9614. const [key, , storage_type] = args;
  9615. const obj = storage_type._new_with_file(unpickler);
  9616. deserialized_objects[key] = obj;
  9617. }
  9618. /*
  9619. let storage_views = unpickler.load();
  9620. for target_cdata, root_cdata, offset, size in storage_views:
  9621. root = deserialized_objects[root_cdata]
  9622. deserialized_objects[target_cdata] = root[offset:offset + size]
  9623. */
  9624. }
  9625. if (entries.has('tensors')) {
  9626. const data = entries.get('tensors');
  9627. const unpickler = new pickle.Unpickler(data);
  9628. const num_tensors = unpickler.load();
  9629. const int32 = (unpickler) => {
  9630. const buffer = unpickler.read(4);
  9631. return buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24);
  9632. };
  9633. const int64 = (unpickler) => {
  9634. const buffer = unpickler.read(8);
  9635. if (buffer[6] !== 0 && buffer[7] !== 0) {
  9636. throw new python.Error('Unsigned 64-bit value exceeds 32-bit range.');
  9637. }
  9638. return buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24) + (buffer[4] * 4294967296) + (buffer[5] * 1099511627776);
  9639. };
  9640. for (let i = 0; i < num_tensors; i++) {
  9641. const args = unpickler.load();
  9642. const [key, storage_id] = args;
  9643. const storage = deserialized_objects[storage_id];
  9644. const ndim = int32(unpickler);
  9645. unpickler.read(4);
  9646. const shape = Array.from(new Array(ndim)).map(() => int64(unpickler));
  9647. const stride = Array.from(new Array(ndim)).map(() => int64(unpickler));
  9648. const storage_offset = int64(unpickler);
  9649. const tensor = torch._utils._rebuild_tensor(storage, storage_offset, shape, stride);
  9650. deserialized_objects[key] = tensor;
  9651. }
  9652. }
  9653. const data = entries.get('pickle');
  9654. const unpickler = new pickle.Unpickler(data);
  9655. unpickler.persistent_load = (saved_id) => deserialized_objects[saved_id];
  9656. return unpickler.load();
  9657. };
  9658. const _legacy_load = () => {
  9659. const unpickler = new pickle.Unpickler(f);
  9660. unpickler.load(); // magic_number
  9661. const protocol_version = unpickler.load();
  9662. if (protocol_version !== 1001) {
  9663. throw new python.Error(`Unsupported protocol version '${protocol_version}'.`);
  9664. }
  9665. const sys_info = unpickler.load();
  9666. if (sys_info.get('protocol_version') !== 1001) {
  9667. throw new python.Error(`Unsupported protocol version '${sys_info.protocol_version}'.`);
  9668. }
  9669. if (sys_info.get('little_endian') === false) {
  9670. throw new python.Error("Unsupported big-endian storage data.");
  9671. }
  9672. const module_source_map = new Map();
  9673. const deserialized_objects = new Map();
  9674. unpickler.persistent_load = (saved_id) => {
  9675. switch (saved_id[0]) {
  9676. case 'module': {
  9677. const [, module, ,source] = saved_id;
  9678. module_source_map.set(module, source);
  9679. return saved_id[1];
  9680. }
  9681. case 'storage': {
  9682. const [, storage_type, key, , size, view_metadata] = saved_id;
  9683. if (!deserialized_objects.has(key)) {
  9684. const obj = new storage_type(size);
  9685. deserialized_objects.set(key, obj);
  9686. }
  9687. if (view_metadata) {
  9688. const view_key = view_metadata.shift();
  9689. view_metadata.shift(); // view_offset
  9690. view_metadata.shift(); // view_size
  9691. if (!deserialized_objects.has(view_key)) {
  9692. const view = null; // storage.slice(view_offset, view_offset + view_size);
  9693. deserialized_objects.set(view_key, view);
  9694. }
  9695. return deserialized_objects.get(view_key);
  9696. }
  9697. return deserialized_objects.get(key);
  9698. }
  9699. default: {
  9700. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  9701. }
  9702. }
  9703. };
  9704. const obj = unpickler.load();
  9705. const deserialized_storage_keys = unpickler.load();
  9706. for (const deserialized_storage_key of deserialized_storage_keys) {
  9707. const storage = deserialized_objects.get(deserialized_storage_key);
  9708. storage._set_from_file(unpickler);
  9709. }
  9710. if (!obj) {
  9711. throw new python.Error('File format is not PyTorch.');
  9712. }
  9713. if (obj === 'None') {
  9714. throw new python.Error("File contains 'None' root object.");
  9715. }
  9716. return obj;
  9717. };
  9718. const _load = (entries) => {
  9719. if (f.has('constant.pkl')) {
  9720. throw python.Error("TorchScript 'torch.load' not supported.");
  9721. }
  9722. const loaded_storages = new Map();
  9723. const persistent_load = (saved_id) => {
  9724. switch (saved_id[0]) {
  9725. case 'storage': {
  9726. const [, storage_type, key, , numel] = saved_id;
  9727. if (!loaded_storages.has(key)) {
  9728. const storage = new storage_type(numel);
  9729. if (!storage._set_cdata) {
  9730. throw new python.Error(`'${storage_type.__name__}._set_cdata' is not a function.`);
  9731. }
  9732. const name = `data/${key}`;
  9733. const stream = entries.get(name);
  9734. if (!stream) {
  9735. throw new python.Error(`Record '${name}' not found.`);
  9736. }
  9737. storage._set_cdata(stream);
  9738. loaded_storages.set(key, storage);
  9739. }
  9740. return loaded_storages.get(key);
  9741. }
  9742. default: {
  9743. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  9744. }
  9745. }
  9746. };
  9747. const data_file = entries.get('data.pkl');
  9748. const unpickler = new pickle.Unpickler(data_file);
  9749. unpickler.persistent_load = persistent_load;
  9750. const result = unpickler.load();
  9751. return result;
  9752. };
  9753. if (f instanceof Map) {
  9754. const reader = new torch.PyTorchFileReader(f);
  9755. const records = reader.get_all_records().map((name) => [name, reader.get_record(name)]);
  9756. f = new Map(records);
  9757. if (f.has('pickle')) {
  9758. return legacy_load(f);
  9759. }
  9760. if (f.has('data.pkl')) {
  9761. return _load(f);
  9762. }
  9763. throw new python.Error(`Unsupported 'torch.load' input '${JSON.stringify(Array.from(f.keys()))}'.`);
  9764. }
  9765. return _legacy_load(f);
  9766. });
  9767. this.registerOperator('prim::abs', (a) => {
  9768. if (typeof a === 'number' || a instanceof Number) {
  9769. return Math.abs(a);
  9770. }
  9771. if (a instanceof builtins.complex) {
  9772. return Math.hypot(a.real, a.imag);
  9773. }
  9774. throw new python.Error('Unsupported prim::abs expression type.');
  9775. });
  9776. this.registerOperator('prim::unchecked_cast', (type, value) => {
  9777. return value;
  9778. });
  9779. this.registerOperator('prim::data', (tensor) => {
  9780. return tensor;
  9781. });
  9782. this.registerOperator('prim::device', (tensor) => {
  9783. return tensor.device;
  9784. });
  9785. this.registerOperator('prim::dtype', (tensor) => {
  9786. return tensor.dtype.scalar_type();
  9787. });
  9788. this.registerOperator('prim::is_quantized', (tensor) => {
  9789. return tensor.is_quantized;
  9790. });
  9791. this.registerOperator('prim::is_cuda', (/* tensor */) => {
  9792. return false;
  9793. });
  9794. this.registerOperator('prim::is_nested', (tensor) => {
  9795. return tensor.is_nested;
  9796. });
  9797. this.registerOperator('prim::is_sparse', (tensor) => {
  9798. return tensor.is_sparse;
  9799. });
  9800. this.registerOperator('prim::unchecked_unwrap_optional', (value) => {
  9801. return value;
  9802. });
  9803. this.registerOperator('prim::NumToTensor', (value) => {
  9804. const tensor = self.invoke('torch.Tensor', []);
  9805. tensor.value = value;
  9806. return tensor;
  9807. });
  9808. this.registerOperator('prim::min', (...args) => {
  9809. if (Array.isArray(args[0])) {
  9810. return Math.min.apply(null, args[0]);
  9811. }
  9812. return Math.min.apply(null, args);
  9813. });
  9814. this.registerOperator('prim::max', (...args) => {
  9815. if (Array.isArray(args[0])) {
  9816. return Math.max.apply(null, args[0]);
  9817. }
  9818. return Math.max.apply(null, args);
  9819. });
  9820. this.registerOperator('prim::shape', (tensor) => {
  9821. return tensor && tensor.size ? tensor.size() : undefined;
  9822. });
  9823. this.registerOperator('quantized::conv_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9824. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9825. params.weight = weight;
  9826. params.bias = bias;
  9827. params.stride = stride;
  9828. params.padding = padding;
  9829. params.dilation = dilation;
  9830. params.groups = groups;
  9831. return params;
  9832. });
  9833. this.registerOperator('quantized::conv1d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9834. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9835. params.weight = weight;
  9836. params.bias = bias;
  9837. params.stride = stride;
  9838. params.padding = padding;
  9839. params.dilation = dilation;
  9840. params.groups = groups;
  9841. return params;
  9842. });
  9843. this.registerOperator('quantized::conv2d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9844. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9845. params.weight = weight;
  9846. params.bias = bias;
  9847. params.stride = stride;
  9848. params.padding = padding;
  9849. params.dilation = dilation;
  9850. params.groups = groups;
  9851. return params;
  9852. });
  9853. this.registerOperator('quantized::conv3d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9854. const params = self.invoke('__torch__.torch.classes.quantized.Conv3dPackedParamsBase', []);
  9855. params.weight = weight;
  9856. params.bias = bias;
  9857. params.stride = stride;
  9858. params.padding = padding;
  9859. params.dilation = dilation;
  9860. params.groups = groups;
  9861. return params;
  9862. });
  9863. this.registerOperator('quantized::conv_transpose1d_prepack', (weight, bias, stride, padding, output_padding, dilation, groups) => {
  9864. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9865. params.weight = weight;
  9866. params.bias = bias;
  9867. params.stride = stride;
  9868. params.padding = padding;
  9869. params.output_padding = output_padding;
  9870. params.dilation = dilation;
  9871. params.groups = groups;
  9872. return params;
  9873. });
  9874. this.registerOperator('quantized::conv_transpose2d_prepack', (weight, bias, stride, padding, output_padding, dilation, groups) => {
  9875. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9876. params.weight = weight;
  9877. params.bias = bias;
  9878. params.stride = stride;
  9879. params.padding = padding;
  9880. params.output_padding = output_padding;
  9881. params.dilation = dilation;
  9882. params.groups = groups;
  9883. return params;
  9884. });
  9885. this.registerOperator('quantized::linear_prepack', (weight, bias) => {
  9886. const params = self.invoke('__torch__.torch.classes.quantized.LinearPackedParamsBase', []);
  9887. params.weight = weight;
  9888. params.bias = bias;
  9889. return params;
  9890. });
  9891. this.registerOperator('prim::RaiseException', (message) => {
  9892. throw new python.Error(message);
  9893. });
  9894. this.registerOperator('prim::TupleIndex', (t, i) => {
  9895. return t.elements()[i];
  9896. });
  9897. this.registerOperator('prim::TupleUnpack', (t) => {
  9898. return t.elements();
  9899. });
  9900. this.registerOperator('aten::is_scripting', () => {
  9901. return true;
  9902. });
  9903. this.registerOperator('aten::__and__', (left, right) => {
  9904. return left && right;
  9905. });
  9906. this.registerOperator('aten::__contains__', (dict, key) => {
  9907. return builtins.hasattr(dict, key);
  9908. });
  9909. this.registerFunction('torch.__derive_index', (index, start, step) => {
  9910. return start + index * step;
  9911. });
  9912. this.registerOperator('aten::__is__', (left, right) => {
  9913. return left === right;
  9914. });
  9915. this.registerOperator('aten::__isnot__', (left, right) => {
  9916. return left !== right;
  9917. });
  9918. this.registerOperator('aten::__not__', (value) => {
  9919. if (Number.isInteger(value)) {
  9920. value = Boolean(value);
  9921. }
  9922. if (typeof value === 'boolean') {
  9923. return !value;
  9924. }
  9925. throw new python.Error("Unsupported 'ops.aten.__not__' expression type.");
  9926. });
  9927. this.registerOperator('aten::log10', (value) => {
  9928. return Math.log10(value);
  9929. });
  9930. this.registerOperator('aten::device', (type, index) => {
  9931. return new torch.device(type, index);
  9932. });
  9933. this.registerOperator('aten::lt', (left, right) => {
  9934. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9935. return left < right;
  9936. }
  9937. throw new python.Error("Unsupported 'ops.aten.lt' expression type.");
  9938. });
  9939. this.registerOperator('aten::mul', (left, right) => {
  9940. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9941. return left * right;
  9942. }
  9943. if (isNaN(left) || isNaN(right)) {
  9944. return NaN;
  9945. }
  9946. if (Array.isArray(left) && left.every((value) => typeof value === 'number' || value instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9947. return left.map((value) => value * right);
  9948. }
  9949. throw new python.Error("Unsupported 'ops.aten.mul' expression type.");
  9950. });
  9951. this.registerOperator('aten::div', (left, right) => {
  9952. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9953. return left / right;
  9954. }
  9955. if (isNaN(left) || isNaN(right)) {
  9956. return NaN;
  9957. }
  9958. throw new python.Error("Unsupported 'ops.aten.div' expression type.");
  9959. });
  9960. this.registerFunction('torch.round', (value) => {
  9961. if (typeof value === 'number' || value instanceof Number) {
  9962. return Math.round(value);
  9963. }
  9964. if (isNaN(value)) {
  9965. return value;
  9966. }
  9967. throw new python.Error("Unsupported 'torch.round' expression type.");
  9968. });
  9969. this.registerOperator('aten::remainder', (left, right) => {
  9970. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9971. return left % right;
  9972. }
  9973. if (isNaN(left) || isNaN(right)) {
  9974. return NaN;
  9975. }
  9976. throw new python.Error("Unsupported 'ops.aten.remainder' expression type.");
  9977. });
  9978. this.registerOperator('aten::ne', (left, right) => {
  9979. if (typeof left === 'boolean' && typeof right === 'boolean') {
  9980. return left !== right;
  9981. }
  9982. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9983. if (isNaN(left) || isNaN(right)) {
  9984. return false;
  9985. }
  9986. return left !== right;
  9987. }
  9988. if (Array.isArray(left) && Array.isArray(right) && left.length === right.length) {
  9989. return false;
  9990. }
  9991. if (typeof left === 'string' && typeof right === 'string') {
  9992. return left !== right;
  9993. }
  9994. if (left === undefined || right === undefined) {
  9995. return true;
  9996. }
  9997. throw new python.Error("Unsupported 'ops.aten.ne' expression type.");
  9998. });
  9999. this.registerOperator('aten::neg', (value) => {
  10000. if (typeof value === 'number') {
  10001. return -value;
  10002. }
  10003. throw new python.Error("Unsupported 'ops.aten.neg' expression type.");
  10004. });
  10005. this.registerOperator('aten::pow', (left, right) => {
  10006. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  10007. return Math.pow(left, right);
  10008. }
  10009. throw new python.Error("Unsupported 'ops.aten.pow' expression type.");
  10010. });
  10011. this.registerFunction('torch.q_scale', (/* tensor */) => {
  10012. return -1;
  10013. });
  10014. this.registerFunction('torch.t', (tensor) => {
  10015. return tensor;
  10016. });
  10017. this.registerOperator('aten::size', (tensor, dim) => {
  10018. if (tensor && tensor.size) {
  10019. const size = tensor.size();
  10020. if (Array.isArray(size)) {
  10021. if (dim === undefined) {
  10022. return size;
  10023. }
  10024. if (Number.isInteger(dim)) {
  10025. if (dim >= 0 && dim < size.length) {
  10026. return size[dim];
  10027. }
  10028. if (dim < 0 && -dim < size.length) {
  10029. return size[size.length + dim];
  10030. }
  10031. }
  10032. throw new python.Error(`Dimension out of range (expected to be in range of ${JSON.stringify(size)}, but got ${JSON.stringify(dim)}).`);
  10033. }
  10034. }
  10035. if (Number.isInteger(dim)) {
  10036. return NaN;
  10037. }
  10038. return [];
  10039. });
  10040. this.registerFunction('aten::sqrt', (x) => {
  10041. return Math.sqrt(x);
  10042. });
  10043. this.registerOperator('aten::slice', (l, start, end, step) => {
  10044. if (!Array.isArray(l)) {
  10045. throw new python.Error('Slicing expected array');
  10046. }
  10047. step = step || 1;
  10048. if (step !== 1) {
  10049. throw new python.Error('Slicing only supports step=1');
  10050. }
  10051. start = Math.max(0, start >= 0 ? start : l.length + start);
  10052. end = Math.min(l.length, end || Number.MAX_SAFE_INTEGER);
  10053. return l.slice(start, end);
  10054. });
  10055. this.registerOperator('aten::sub', (left, right) => {
  10056. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  10057. return left - right;
  10058. }
  10059. if (typeof left === 'number' && right instanceof builtins.complex) {
  10060. return new builtins.complex(left - right.real, right.imag);
  10061. }
  10062. if (left instanceof builtins.complex && typeof right === 'number') {
  10063. return new builtins.complex(left.real - right, left.imag);
  10064. }
  10065. if (left instanceof builtins.complex && right instanceof builtins.complex) {
  10066. return new builtins.complex(left.real - right.real, left.imag - right.imag);
  10067. }
  10068. throw new python.Error("Unsupported 'torch.sub' expression type.");
  10069. });
  10070. this.registerFunction('torch.sym_int');
  10071. this.registerFunction('torch.sym_float');
  10072. this.registerFunction('torch.sym_ite');
  10073. this.registerFunction('torch.sym_max');
  10074. this.registerFunction('torch.sym_min');
  10075. this.registerFunction('torch.sym_not');
  10076. this.registerFunction('torch.sym_sqrt');
  10077. this.registerFunction('torch.sym_sqrt');
  10078. this.registerFunction('torch.functional.einsum');
  10079. this.registerFunction('torch.functional.norm');
  10080. this.registerFunction('torch.functional.split');
  10081. this.registerFunction('torch.nn.init.constant_');
  10082. this.registerFunction('torch.nn.init.normal_');
  10083. this.registerFunction('torch.nn.init.xavier_uniform_');
  10084. this.registerFunction('torch.nn.functional.adaptive_avg_pool2d');
  10085. this.registerFunction('torch.nn.functional.binary_cross_entropy');
  10086. this.registerFunction('torch.nn.functional.binary_cross_entropy_with_logits');
  10087. this.registerFunction('torch.nn.functional.cross_entropy');
  10088. this.registerFunction('torch.nn.functional.elu');
  10089. this.registerFunction('torch.nn.functional.gelu');
  10090. this.registerFunction('torch.nn.functional.hardsigmoid');
  10091. this.registerFunction('torch.nn.functional.hardswish');
  10092. this.registerFunction('torch.nn.functional.hardtanh');
  10093. this.registerFunction('torch.nn.functional.interpolate');
  10094. this.registerFunction('torch.nn.functional.leaky_relu');
  10095. this.registerFunction('torch.nn.functional.l1_loss');
  10096. this.registerFunction('torch.nn.functional.linear');
  10097. this.registerFunction('torch.nn.functional.log_softmax');
  10098. this.registerFunction('torch.nn.functional._max_pool2d');
  10099. this.registerFunction('torch.nn.functional.max_pool2d_with_indices');
  10100. this.registerFunction('torch.nn.functional.mse_loss');
  10101. this.registerFunction('torch.nn.functional.pad');
  10102. this.registerFunction('torch.nn.functional.relu');
  10103. this.registerFunction('torch.nn.functional.relu6');
  10104. this.registerFunction('torch.nn.functional.sigmoid');
  10105. this.registerFunction('torch.nn.functional.silu');
  10106. this.registerFunction('torch.nn.functional.softmax');
  10107. this.registerFunction('torch.nn.functional.tanh');
  10108. this.registerFunction('torch.values', (dict) => {
  10109. return Object.values(dict);
  10110. });
  10111. this.registerFunction('torch.warn', () => {
  10112. });
  10113. this.registerType('torch._ops.OperatorBase', class {
  10114. constructor() {
  10115. this.functorch_table = {};
  10116. }
  10117. });
  10118. this.registerType('torch._ops.HigherOrderOperator', class extends torch._ops.OperatorBase {
  10119. constructor(name, cacheable) {
  10120. super();
  10121. this._name = name;
  10122. this.__name__ = name;
  10123. this._ns = 'higher_order';
  10124. this.__module__ = 'torch.ops.higher_order';
  10125. this._cacheable = cacheable;
  10126. }
  10127. get namespace() {
  10128. return this._ns;
  10129. }
  10130. get name() {
  10131. return this._name;
  10132. }
  10133. });
  10134. this.registerType('torch._higher_order_ops.wrap.WrapWithAutocast', class extends torch._ops.HigherOrderOperator {
  10135. constructor(name) {
  10136. super(name, false);
  10137. this._schema = torch.FunctionSchema.parse('higher_order::wrap_with_autocast(str device_type, ScalarType? dtype, bool enabled, bool? cache_enabled, Any wrapped_func, ...) -> Tensor');
  10138. }
  10139. });
  10140. torch.ops.higher_order.wrap_with_autocast = new torch._higher_order_ops.wrap.WrapWithAutocast('wrap_with_autocast');
  10141. this.registerType('torch._higher_order_ops.wrap.WrapWithSetGradEnabled', class extends torch._ops.HigherOrderOperator {
  10142. constructor(name) {
  10143. super(name, false);
  10144. this._schema = torch.FunctionSchema.parse('higher_order::wrap_with_set_grad_enabled(bool enable_grad, Any wrapped_func) -> Tensor');
  10145. }
  10146. });
  10147. torch.ops.higher_order.wrap_with_set_grad_enabled = new torch._higher_order_ops.wrap.WrapWithSetGradEnabled('wrap_with_set_grad_enabled');
  10148. this.registerType('torch._higher_order_ops.wrap.Wrap', class extends torch._ops.HigherOrderOperator {
  10149. constructor(name) {
  10150. super(name, false);
  10151. this._schema = torch.FunctionSchema.parse('higher_order::wrap(Any func) -> Tensor');
  10152. }
  10153. });
  10154. torch.ops.higher_order.wrap = new torch._higher_order_ops.wrap.Wrap('wrap');
  10155. this.registerType('torch._higher_order_ops.wrap.WrapActivationCheckpoint', class extends torch._ops.HigherOrderOperator {
  10156. constructor(name) {
  10157. super(name, false);
  10158. }
  10159. });
  10160. torch.ops.higher_order.wrap_activation_checkpoint = new torch._higher_order_ops.wrap.WrapActivationCheckpoint('wrap_activation_checkpoint', false);
  10161. this.registerType('torch._higher_order_ops.wrap.TagActivationCheckpoint', class extends torch._ops.HigherOrderOperator {
  10162. constructor(name) {
  10163. super(name, false);
  10164. }
  10165. });
  10166. torch.ops.higher_order.tag_activation_checkpoint = new torch._higher_order_ops.wrap.TagActivationCheckpoint('tag_activation_checkpoint', false);
  10167. this.registerType('torch.Type', class {
  10168. constructor(kind, annotation_str) {
  10169. this._kind = kind;
  10170. if (annotation_str) {
  10171. this._annotation_str = annotation_str;
  10172. }
  10173. }
  10174. static get(kind, annotation_str) {
  10175. torch.Type.cache = torch.Type.cache || new Map();
  10176. if (!annotation_str) {
  10177. if (!torch.Type.cache.has(kind)) {
  10178. torch.Type.cache.set(kind, new torch.Type(kind));
  10179. }
  10180. return torch.Type.cache.get(kind);
  10181. }
  10182. return new torch.Type(kind, annotation_str);
  10183. }
  10184. kind() {
  10185. return this._kind;
  10186. }
  10187. get annotation_str() {
  10188. return this._annotation_str;
  10189. }
  10190. equals(rhs) {
  10191. return this.kind() === rhs.kind();
  10192. }
  10193. isSubtypeOf(rhs) {
  10194. if (rhs.kind() === 'AnyType' || this === rhs) {
  10195. return true;
  10196. }
  10197. if (rhs instanceof torch.OptionalType && this instanceof torch.OptionalType === false) {
  10198. return this.isSubtypeOf(rhs.getElementType());
  10199. }
  10200. if (rhs instanceof torch.UnionType) {
  10201. return rhs.containedTypes().some((inner) => this.isSubtypeOf(inner));
  10202. }
  10203. if (rhs instanceof torch._C.DynamicType) {
  10204. return torch._C.DynamicType.create(this).isSubtypeOf(rhs);
  10205. }
  10206. return this.equals(rhs);
  10207. }
  10208. containedTypes() {
  10209. return [];
  10210. }
  10211. containedType(i) {
  10212. return this.containedTypes()[i];
  10213. }
  10214. withContained(contained_types) {
  10215. const current_contained = this.containedTypes();
  10216. torch._C.TORCH_INTERNAL_ASSERT(current_contained.length > 0 && current_contained.length === contained_types.length);
  10217. if (current_contained.length === contained_types.length && current_contained.every((x, index) => x === contained_types[index])) {
  10218. return this;
  10219. }
  10220. return this.createWithContained(contained_types);
  10221. }
  10222. createWithContained(/* createWithContained */) {
  10223. throw new python.Error('Not implemented.');
  10224. }
  10225. isUnionType() {
  10226. return false;
  10227. }
  10228. hasFreeVariables() {
  10229. return false;
  10230. }
  10231. is_module() {
  10232. return false;
  10233. }
  10234. expect(type) {
  10235. torch._C.AT_ASSERT(this instanceof type);
  10236. return this;
  10237. }
  10238. str() {
  10239. if (this instanceof torch._C.VarType && this._annotation_str) {
  10240. return this._annotation_str;
  10241. } else if (this._kind === 'ScalarTypeType') {
  10242. return 'ScalarType';
  10243. } else if (this._kind === 'QSchemeType') {
  10244. return 'QScheme';
  10245. } else if (this._kind) {
  10246. return this._kind;
  10247. }
  10248. throw new python.Error(`Not implemented '${this.kind()}'.`);
  10249. }
  10250. __str__() {
  10251. return this.str();
  10252. }
  10253. toString() {
  10254. return this.__str__();
  10255. }
  10256. });
  10257. this.registerType('torch.ClassType', class extends torch.Type {
  10258. constructor(qualified_name, cu, is_module) {
  10259. super('ClassType', typeof qualified_name === 'string' ? qualified_name : qualified_name.qualifiedName());
  10260. this._name = typeof qualified_name === 'string' ? new torch._C.QualifiedName(qualified_name) : qualified_name;
  10261. this._is_module = is_module;
  10262. this._attributes = [];
  10263. this._attributeTypes = [];
  10264. this._methods = [];
  10265. this._staticmethods = new Map();
  10266. this._forward_hooks = [];
  10267. this._forward_pre_hooks = [];
  10268. this._properties = [];
  10269. this._constants = new Map();
  10270. }
  10271. static create(qualifiedName, cu, is_module /*, doc_string, unresolved_class_attributes */) {
  10272. return new torch.ClassType(qualifiedName, cu, is_module);
  10273. }
  10274. qualified_name() {
  10275. return this.annotation_str;
  10276. }
  10277. name() {
  10278. return this._name;
  10279. }
  10280. is_module() {
  10281. return this._is_module;
  10282. }
  10283. is_parameter(slot) {
  10284. return this._attributes[slot].is_parameter === true;
  10285. }
  10286. is_buffer(slot) {
  10287. return this._attributes[slot].is_buffer === true;
  10288. }
  10289. addMethod(method) {
  10290. torch._C.TORCH_CHECK(this.findMethod(method.name()) === null);
  10291. this._methods.push(method);
  10292. }
  10293. findMethod(name) {
  10294. for (const method of this._methods) {
  10295. if (name === method.name()) {
  10296. return method;
  10297. }
  10298. }
  10299. return null;
  10300. }
  10301. getMethod(name) {
  10302. const method = this.findMethod(name);
  10303. if (!method) {
  10304. throw new python.Error(`Method '${name}' not found on class '${this.str()}.`);
  10305. }
  10306. return method;
  10307. }
  10308. methods() {
  10309. return this._methods;
  10310. }
  10311. addStaticMethod(func) {
  10312. this._staticmethods.set(func.name, func);
  10313. }
  10314. findStaticMethod(name) {
  10315. return this._staticmethods.get(name);
  10316. }
  10317. findHook(name) {
  10318. let hook = this.findForwardHook(name);
  10319. if (hook === null) {
  10320. hook = this.findForwardPreHook(name);
  10321. }
  10322. return hook;
  10323. }
  10324. findForwardHook(name) {
  10325. for (const hook of this._forward_hooks) {
  10326. if (name === hook.name()) {
  10327. return hook;
  10328. }
  10329. }
  10330. return null;
  10331. }
  10332. findForwardPreHook(name) {
  10333. for (const pre_hook of this._forward_pre_hooks) {
  10334. if (name === pre_hook.name()) {
  10335. return pre_hook;
  10336. }
  10337. }
  10338. return null;
  10339. }
  10340. numAttributes() {
  10341. return this._attributes.length;
  10342. }
  10343. addAttribute(name, type, is_parameter, is_buffer) {
  10344. is_parameter = is_parameter || false;
  10345. is_buffer = is_buffer || false;
  10346. const slot = this._attributes.length;
  10347. this._attributes.push({ name, type, is_parameter, is_buffer });
  10348. this._attributeTypes.push(type);
  10349. return slot;
  10350. }
  10351. addOrCheckAttribute(name, ty, is_parameter, is_buffer) {
  10352. is_parameter = is_parameter || false;
  10353. is_buffer = is_buffer || false;
  10354. const slot_idx = this.findAttributeSlot(name);
  10355. if (slot_idx === null) {
  10356. return this.addAttribute(name, ty, is_parameter, is_buffer);
  10357. }
  10358. // TORCH_CHECK(is_parameter == this.is_parameter(*slot_idx), "Parameter field mismatch for the field '", name, "'");
  10359. // const TypePtr& atype = getAttribute(*slot_idx);
  10360. // TORCH_CHECK(ty.isSubtypeOf(*atype), ty.repr_str(), " is not compatible with the type ", atype.repr_str(), " for the field '", name, "'");
  10361. return slot_idx;
  10362. }
  10363. findAttributeSlot(name) {
  10364. for (let pos = 0; pos < this._attributes.length; pos++) {
  10365. if (name === this._attributes[pos].name) {
  10366. return pos;
  10367. }
  10368. }
  10369. return null;
  10370. }
  10371. findAttribute(name) {
  10372. const slot = this.findAttributeSlot(name);
  10373. if (slot !== null) {
  10374. return this._attributes[slot].type;
  10375. }
  10376. return null;
  10377. }
  10378. hasAttribute(name) {
  10379. return this._attributes.find((attr) => attr.name === name);
  10380. }
  10381. getAttribute(arg) {
  10382. const slot = Number.isInteger(arg) ? arg : this.findAttributeSlot(arg);
  10383. return this._attributes[slot].type;
  10384. }
  10385. getAttributeName(slot) {
  10386. return this._attributes[slot].name;
  10387. }
  10388. addConstant(name, value) {
  10389. this._constants.set(name, value);
  10390. }
  10391. hasConstant(name) {
  10392. return this._constants.has(name);
  10393. }
  10394. getProperty(name) {
  10395. for (const prop of this._properties) {
  10396. if (name === prop.name) {
  10397. return prop;
  10398. }
  10399. }
  10400. return null;
  10401. }
  10402. containedTypes() {
  10403. return this._attributeTypes;
  10404. }
  10405. createWithContained(contained_types) {
  10406. const ptr = torch.ClassType.create(this.name(), this._compilation_unit, this.is_module());
  10407. torch._C.AT_ASSERT(this.numAttributes() === contained_types.length);
  10408. for (let i = 0; i < this._attributes.length; i++) {
  10409. torch._C.AT_ASSERT(this._attributes[i].type.isSubtypeOf(contained_types[i]));
  10410. ptr.addAttribute(this._attributes[i].name, contained_types[i]);
  10411. }
  10412. for (const method of this.methods()) {
  10413. ptr.addMethod(method);
  10414. }
  10415. return ptr;
  10416. }
  10417. str() {
  10418. return this.qualified_name();
  10419. }
  10420. });
  10421. this.registerType('torch.EnumType', class extends torch.Type {
  10422. constructor(qualified_class_name, value_type, enum_names_values, cu) {
  10423. super('EnumType', qualified_class_name);
  10424. this._name = qualified_class_name;
  10425. this._value_type = value_type;
  10426. this._enum_names_values = enum_names_values;
  10427. this._cu = cu;
  10428. }
  10429. static create(qualified_class_name, value, enum_names_values, cu) {
  10430. if (value instanceof torch.IntType || value instanceof torch.FloatType || value instanceof torch.StringType) {
  10431. return new torch.EnumType(qualified_class_name, value, enum_names_values, cu);
  10432. }
  10433. torch._C.TORCH_CHECK(false);
  10434. return null;
  10435. }
  10436. name() {
  10437. return this._name;
  10438. }
  10439. get annotation_str() {
  10440. return this._name.qualifiedName();
  10441. }
  10442. enumNamesValues() {
  10443. return this._enum_names_values;
  10444. }
  10445. compilation_unit() {
  10446. return this._cu;
  10447. }
  10448. getValueType() {
  10449. return this._value_type;
  10450. }
  10451. equals(rhs) {
  10452. if (rhs instanceof torch.EnumType) {
  10453. return this.name() && this.name() === rhs.name() && this.getValueType() === rhs.getValueType() && this.compilation_unit() === rhs.compilation_unit();
  10454. }
  10455. return false;
  10456. }
  10457. isSubtypeOf(rhs) {
  10458. if (rhs instanceof torch.AnyType || rhs.kind() === 'AnyEnumType' || this === rhs) {
  10459. return true;
  10460. }
  10461. return super.isSubtypeOf(rhs);
  10462. }
  10463. });
  10464. this.registerFunction('torch._C.standardizeVectorForUnion', (...args) => {
  10465. if (args.length === 1) {
  10466. const [to_flatten] = args;
  10467. torch._C.TORCH_INTERNAL_ASSERT(to_flatten !== null);
  10468. const to_fill = [];
  10469. torch._C.standardizeVectorForUnion(to_flatten, to_fill);
  10470. to_flatten.splice(0, to_flatten.length);
  10471. to_flatten.push(...to_fill);
  10472. } else if (args.length === 2) {
  10473. const [reference, to_fill] = args;
  10474. for (const type of reference) {
  10475. torch._C.flattenUnion(type, to_fill);
  10476. }
  10477. torch._C.filterDuplicateSubtypes(to_fill);
  10478. torch._C.sortUnion(to_fill);
  10479. } else {
  10480. throw new python.Error('Not implemented.');
  10481. }
  10482. });
  10483. this.registerFunction('torch._C.flattenUnion', (type, to_fill) => {
  10484. if (type instanceof torch.UnionType) {
  10485. for (const inner of type.containedTypes()) {
  10486. torch._C.flattenUnion(inner, to_fill);
  10487. }
  10488. } else if (type instanceof torch.OptionalType) {
  10489. const inner = type.getElementType();
  10490. torch._C.flattenUnion(inner, to_fill);
  10491. to_fill.push(torch.NoneType.get());
  10492. } else if (type instanceof torch.NumberType) {
  10493. to_fill.push(torch.IntType.get());
  10494. to_fill.push(torch.FloatType.get());
  10495. to_fill.push(torch.ComplexType.get());
  10496. } else {
  10497. to_fill.push(type);
  10498. }
  10499. });
  10500. this.registerFunction('torch._C.filterDuplicateSubtypes', (types) => {
  10501. if (types.length === 0) {
  10502. // return;
  10503. }
  10504. /*
  10505. const get_supertype = [](const TypePtr& t1, const TypePtr& t2) -> std::optional<TypePtr> {
  10506. // We don't want nested Optionals. Also, prematurely unifying to
  10507. // `Optional` could prevent us from coalescing other types
  10508. if ((t1->isSubtypeOf(*NoneType::get()) && !t2->isSubtypeOf(*NoneType::get()))
  10509. || (!t1->isSubtypeOf(*NoneType::get()) && t2->isSubtypeOf(*NoneType::get()))) {
  10510. return null;
  10511. } else {
  10512. return unifyTypes(t1, t2, default_to_union=false);
  10513. }
  10514. };
  10515. size_t end_idx = types->size()-1;
  10516. for (size_t i = types->size()-1; i > 0; --i) {
  10517. for (size_t j = std::min(i-1, end_idx); ; --j) {
  10518. std::optional<TypePtr> unified;
  10519. unified = get_supertype((*types)[i], (*types)[j]);
  10520. if (unified) {
  10521. (*types)[j] = *unified;
  10522. (*types)[i] = (*types)[end_idx];
  10523. --end_idx;
  10524. break;
  10525. }
  10526. if (j == 0) {
  10527. break;
  10528. }
  10529. }
  10530. }
  10531. types.erase(types->begin() + static_cast<std::ptrdiff_t>(end_idx) + 1, types->end());
  10532. */
  10533. });
  10534. this.registerFunction('torch._C.sortUnion', (/* types */) => {
  10535. /*
  10536. std::sort(types->begin(), types->end(),
  10537. [](const TypePtr& a, const TypePtr& b) -> bool {
  10538. if (a->kind() != b->kind()) {
  10539. return a->kind() < b->kind();
  10540. }
  10541. return a->str() < b->str();
  10542. });
  10543. */
  10544. });
  10545. this.registerType('torch.UnionType', class extends torch.Type {
  10546. constructor(reference, kind) {
  10547. super(kind || 'UnionType');
  10548. torch._C.TORCH_INTERNAL_ASSERT(reference.length > 0);
  10549. this._types = [];
  10550. torch._C.standardizeVectorForUnion(reference, this._types);
  10551. if (this._types.length === 1) {
  10552. throw new python.Error('Invalid union type reference.');
  10553. }
  10554. this._can_hold_none = false;
  10555. this._has_free_variables = false;
  10556. for (const type of this._types) {
  10557. if (type instanceof torch.NoneType) {
  10558. this._can_hold_none = true;
  10559. }
  10560. if (type.hasFreeVariables()) {
  10561. this._has_free_variables = true;
  10562. }
  10563. }
  10564. }
  10565. static create(reference) {
  10566. const union_type = new torch.UnionType(reference);
  10567. /*
  10568. bool int_found = false;
  10569. bool float_found = false;
  10570. bool complex_found = false;
  10571. bool nonetype_found = false;
  10572. const update_is_opt_flags = [&](const TypePtr& t) {
  10573. if (t == IntType::get()) {
  10574. int_found = true;
  10575. } else if (t == FloatType::get()) {
  10576. float_found = true;
  10577. } else if (t == ComplexType::get()) {
  10578. complex_found = true;
  10579. } else if (t == NoneType::get()) {
  10580. nonetype_found = true;
  10581. }
  10582. };
  10583. for (const auto& t : union_type->containedTypes()) {
  10584. update_is_opt_flags(t);
  10585. }
  10586. bool numbertype_found = int_found && float_found && complex_found;
  10587. if (nonetype_found) {
  10588. if (union_type->containedTypes().size() == 4 && numbertype_found) {
  10589. return OptionalType::create(NumberType::get());
  10590. }
  10591. if (union_type->containedTypes().size() == 2) {
  10592. const not_none = union_type->containedTypes()[0] != NoneType::get()
  10593. ? union_type->containedTypes()[0]
  10594. : union_type->containedTypes()[1];
  10595. return OptionalType::create(not_none);
  10596. }
  10597. }
  10598. */
  10599. return union_type;
  10600. }
  10601. containedTypes() {
  10602. return this._types;
  10603. }
  10604. isUnionType() {
  10605. return true;
  10606. }
  10607. hasFreeVariables() {
  10608. return this._has_free_variables;
  10609. }
  10610. equals(rhs) {
  10611. if (rhs instanceof torch.UnionType) {
  10612. if (rhs.containedTypes().length !== this.containedTypes().length) {
  10613. return false;
  10614. }
  10615. return this.containedTypes().every((lhs_type) => rhs.containedTypes().some((rhs_type) => lhs_type === rhs_type));
  10616. } else if (rhs instanceof torch.OptionalType) {
  10617. if (rhs.getElementType() === torch.NumberType.get()) {
  10618. return this.containedTypes().length === 4 && this._can_hold_none && this.canHoldType(torch.NumberType.get());
  10619. }
  10620. const optional_lhs = this.toOptional();
  10621. return optional_lhs && rhs === optional_lhs.expect(torch.OptionalType);
  10622. } else if (rhs instanceof torch.NumberType) {
  10623. return this.containedTypes().length === 3 && this.canHoldType(torch.NumberType.get());
  10624. }
  10625. return false;
  10626. }
  10627. isSubtypeOf(rhs) {
  10628. const rhs_types = [];
  10629. if (rhs instanceof torch.UnionType) {
  10630. if (this.containedTypes() === rhs.containedTypes()) {
  10631. return true;
  10632. }
  10633. for (const typePtr of rhs.containedTypes()) {
  10634. rhs_types.push(typePtr);
  10635. }
  10636. } else if (rhs instanceof torch.OptionalType) {
  10637. rhs_types.push(torch.NoneType.get());
  10638. if (rhs.getElementType() === torch.NumberType.get()) {
  10639. const number_types = [torch.IntType.get(), torch.FloatType.get(), torch.ComplexType.get()];
  10640. rhs_types.push(...number_types);
  10641. } else {
  10642. rhs_types.push(rhs.getElementType());
  10643. }
  10644. } else if (rhs instanceof torch.NumberType) {
  10645. const number_types = [torch.IntType.get(), torch.FloatType.get(), torch.ComplexType.get()];
  10646. rhs_types.push(...number_types);
  10647. } else {
  10648. rhs_types.push(rhs);
  10649. }
  10650. return this.containedTypes().every((lhs_type) => rhs_types.some((rhs_type) => lhs_type.isSubtypeOf(rhs_type)));
  10651. }
  10652. });
  10653. this.registerType('torch.OptionalType', class extends torch.UnionType {
  10654. constructor(contained) {
  10655. super([contained, torch.NoneType.get()], 'OptionalType');
  10656. let is_numbertype = false;
  10657. if (contained instanceof torch.UnionType) {
  10658. is_numbertype = contained.containedTypes().length === 3 && contained.canHoldType(torch.NumberType.get());
  10659. }
  10660. if (super.containedTypes().length === 2) {
  10661. this._contained = super.containedTypes()[0] instanceof torch.NoneType ? super.containedTypes()[1] : super.containedTypes()[0];
  10662. } else if (contained === torch.NumberType.get() || is_numbertype) {
  10663. this._contained = torch.NumberType.get();
  10664. this._types.splice(0, this._types.length);
  10665. this._types.push(torch.NumberType.get());
  10666. this._types.push(torch.NoneType.get());
  10667. } else {
  10668. const to_subtract = [torch.NoneType.get()];
  10669. const without_none = this.subtractTypeSetFrom(to_subtract, this._types);
  10670. this._contained = torch.UnionType.create([without_none]);
  10671. }
  10672. this._has_free_variables = contained.hasFreeVariables();
  10673. }
  10674. static create(elem) {
  10675. return new torch.OptionalType(elem);
  10676. }
  10677. getElementType() {
  10678. return this._contained;
  10679. }
  10680. equals(rhs) {
  10681. return this.kind() === rhs.kind() && this.getElementType().equals(rhs.getElementType());
  10682. }
  10683. isSubtypeOf(rhs) {
  10684. if (rhs instanceof torch.OptionalType) {
  10685. return this.getElementType().isSubtypeOf(rhs.getElementType());
  10686. } else if (rhs instanceof torch.UnionType) {
  10687. throw new python.Error('Not implemented.');
  10688. }
  10689. // return super.isSubtypeOf(rhs);
  10690. return torch.Type.prototype.isSubtypeOf.call(this, rhs);
  10691. }
  10692. containedTypes() {
  10693. return [this._contained];
  10694. }
  10695. createWithContained(contained_types) {
  10696. torch._C.AT_ASSERT(contained_types.length === 1);
  10697. return torch.OptionalType.create(contained_types[0]);
  10698. }
  10699. subtractTypeSetFrom(to_subtract, from) {
  10700. const types = [];
  10701. const should_subtract = (lhs) => to_subtract.some((rhs) => lhs.isSubtypeOf(rhs));
  10702. for (const t of from) {
  10703. if (!should_subtract(t)) {
  10704. types.push(t);
  10705. }
  10706. }
  10707. if (types.length === 0) {
  10708. return null;
  10709. } else if (types.length === 1) {
  10710. return types[0];
  10711. }
  10712. return torch.UnionType.create(types);
  10713. }
  10714. str() {
  10715. return `${this.getElementType().str()}?`;
  10716. }
  10717. __str__() {
  10718. return `Optional[${this.getElementType().__str__()}]`;
  10719. }
  10720. });
  10721. this.registerType('torch.ListType', class extends torch.Type {
  10722. constructor(elem) {
  10723. super('ListType');
  10724. this._elem = elem;
  10725. }
  10726. static create(elem) {
  10727. return new torch.ListType(elem);
  10728. }
  10729. getElementType() {
  10730. return this._elem;
  10731. }
  10732. equals(rhs) {
  10733. if (rhs instanceof torch.ListType) {
  10734. return this.getElementType().equals(rhs.getElementType());
  10735. }
  10736. return false;
  10737. }
  10738. isSubtypeOf(rhs) {
  10739. if (super.isSubtypeOf(rhs)) {
  10740. return true;
  10741. }
  10742. if (rhs.kind() === 'AnyListType') {
  10743. return true;
  10744. }
  10745. return false;
  10746. }
  10747. containedTypes() {
  10748. return [this._elem];
  10749. }
  10750. createWithContained(contained_types) {
  10751. return new torch.ListType(contained_types[0]);
  10752. }
  10753. hasFreeVariables() {
  10754. return this.getElementType().hasFreeVariables();
  10755. }
  10756. str() {
  10757. return `${this.getElementType().str()}[]`;
  10758. }
  10759. __str__() {
  10760. return `List[${this.getElementType().__str__()}]`;
  10761. }
  10762. });
  10763. this.registerType('torch.FutureType', class extends torch.Type {
  10764. constructor(elem) {
  10765. super('FutureType');
  10766. this._elem = elem;
  10767. }
  10768. static create(elem) {
  10769. return new torch.FutureType(elem);
  10770. }
  10771. getElementType() {
  10772. return this._elem;
  10773. }
  10774. containedTypes() {
  10775. throw new python.Error('Not implemented.');
  10776. }
  10777. str() {
  10778. return `Future(${this.getElementType().str()})`;
  10779. }
  10780. __str__() {
  10781. return `Future[${this.getElementType().__str__()}]`;
  10782. }
  10783. });
  10784. this.registerType('torch.RRefType', class extends torch.Type {
  10785. constructor(elem) {
  10786. super('RRefType');
  10787. this._elem = elem;
  10788. }
  10789. static create(elem) {
  10790. return new torch.RRefType(elem);
  10791. }
  10792. getElementType() {
  10793. return this._elem;
  10794. }
  10795. containedTypes() {
  10796. throw new python.Error('Not implemented.');
  10797. }
  10798. str() {
  10799. return `RRef(${this.getElementType().str()})`;
  10800. }
  10801. __str__() {
  10802. return `RRef[${this.getElementType().__str__()}]`;
  10803. }
  10804. });
  10805. this.registerType('torch.AwaitType', class extends torch.Type {
  10806. constructor(elem) {
  10807. super('AwaitType');
  10808. this._elem = elem;
  10809. }
  10810. static get(elem) {
  10811. return new torch.AwaitType(elem);
  10812. }
  10813. getElementType() {
  10814. return this._elem;
  10815. }
  10816. containedTypes() {
  10817. throw new python.Error('Not implemented.');
  10818. }
  10819. str() {
  10820. return `Await(${this.getElementType().str()})`;
  10821. }
  10822. __str__() {
  10823. return `Await[${this.getElementType().__str__()}]`;
  10824. }
  10825. });
  10826. this.registerType('torch.TupleType', class extends torch.Type {
  10827. constructor(elements, annotation_str, schema) {
  10828. super('TupleType', annotation_str);
  10829. this._elements = elements;
  10830. this._has_free_variables = elements.some((v) => {
  10831. if (!v) {
  10832. throw new python.Error('Can not create tuple with None type');
  10833. }
  10834. return v.hasFreeVariables();
  10835. });
  10836. this._schema = schema;
  10837. }
  10838. static create(elements) {
  10839. return new torch.TupleType(elements, null, null);
  10840. }
  10841. static createNamed(qualified_name, field_names, field_types /*, field_defaults */) {
  10842. const args = [];
  10843. for (let i = 0; i < field_names.length; i++) {
  10844. const arg = new torch.Argument(field_names[i], field_types[i], field_types[i]);
  10845. args.push(arg);
  10846. }
  10847. const schema = new torch.FunctionSchema(qualified_name, '', args, []);
  10848. return new torch.TupleType(field_types, qualified_name, schema);
  10849. }
  10850. elements() {
  10851. return this._elements;
  10852. }
  10853. name() {
  10854. return this.annotation_str;
  10855. }
  10856. containedTypes() {
  10857. return this._elements;
  10858. }
  10859. createWithContained(createWithContained) {
  10860. return new torch.TupleType(createWithContained, this.name(), this.schema());
  10861. }
  10862. hasFreeVariables() {
  10863. return this._has_free_variables;
  10864. }
  10865. schema() {
  10866. return this._schema;
  10867. }
  10868. str() {
  10869. if (this._schema) {
  10870. return `NamedTuple(...)`;
  10871. }
  10872. return `(${this.elements().map((elem) => elem.str()).join(', ')})`;
  10873. }
  10874. __str__() {
  10875. if (this.annotation_str) {
  10876. return this.annotation_str;
  10877. }
  10878. return `Tuple[${this.elements().map((elem) => elem.__str__()).join(', ')}]`;
  10879. }
  10880. });
  10881. this.registerType('torch.AnyType', class extends torch.Type {
  10882. constructor() {
  10883. super('AnyType');
  10884. }
  10885. static get() {
  10886. torch.AnyType.value = torch.AnyType.value || new torch.AnyType();
  10887. return torch.AnyType.value;
  10888. }
  10889. str() {
  10890. return 'Any';
  10891. }
  10892. __str__() {
  10893. return 'Any';
  10894. }
  10895. });
  10896. this.registerType('torch.NoneType', class extends torch.Type {
  10897. constructor() {
  10898. super('NoneType');
  10899. }
  10900. static get() {
  10901. torch.NoneType.value = torch.NoneType.value || new torch.NoneType();
  10902. return torch.NoneType.value;
  10903. }
  10904. equals(rhs) {
  10905. return this.kind() === rhs.kind();
  10906. }
  10907. isSubtypeOf(rhs) {
  10908. if (rhs.kind() === 'OptionalType') {
  10909. return true;
  10910. }
  10911. return super.isSubtypeOf(rhs);
  10912. }
  10913. str() {
  10914. return 'NoneType';
  10915. }
  10916. __str__() {
  10917. return 'NoneType';
  10918. }
  10919. });
  10920. this.registerType('torch.TensorType', class extends torch.Type {
  10921. constructor() {
  10922. super('TensorType');
  10923. this._is_inferred = false;
  10924. }
  10925. static get() {
  10926. torch.TensorType.value = torch.TensorType.value || new torch.TensorType();
  10927. return torch.TensorType.value;
  10928. }
  10929. equals(rhs) {
  10930. return this.kind() === rhs.kind();
  10931. }
  10932. isInferredType() {
  10933. return this._is_inferred;
  10934. }
  10935. str() {
  10936. return 'Tensor';
  10937. }
  10938. __str__() {
  10939. return 'Tensor';
  10940. }
  10941. });
  10942. this.registerType('torch.NumberType', class extends torch.Type {
  10943. constructor() {
  10944. super('NumberType');
  10945. }
  10946. static get() {
  10947. torch.NumberType.value = torch.NumberType.value || new torch.NumberType();
  10948. return torch.NumberType.value;
  10949. }
  10950. str() {
  10951. return 'Scalar';
  10952. }
  10953. __str__() {
  10954. return 'number';
  10955. }
  10956. });
  10957. this.registerType('torch.BoolType', class extends torch.Type {
  10958. constructor() {
  10959. super('BoolType');
  10960. }
  10961. static get() {
  10962. torch.BoolType.value = torch.BoolType.value || new torch.BoolType();
  10963. return torch.BoolType.value;
  10964. }
  10965. equals(rhs) {
  10966. return this.kind() === rhs.kind();
  10967. }
  10968. str() {
  10969. return 'bool';
  10970. }
  10971. __str__() {
  10972. return 'bool';
  10973. }
  10974. });
  10975. this.registerType('torch.IntType', class extends torch.Type {
  10976. constructor() {
  10977. super('IntType');
  10978. }
  10979. static get() {
  10980. torch.IntType.value = torch.IntType.value || new torch.IntType();
  10981. return torch.IntType.value;
  10982. }
  10983. equals(rhs) {
  10984. return this.kind() === rhs.kind();
  10985. }
  10986. isSubtypeOf(rhs) {
  10987. return rhs instanceof torch.NumberType || rhs instanceof torch.FloatType || super.isSubtypeOf(rhs);
  10988. }
  10989. str() {
  10990. return 'int';
  10991. }
  10992. __str__() {
  10993. return 'int';
  10994. }
  10995. });
  10996. this.registerType('torch.SymIntType', class extends torch.Type {
  10997. constructor() {
  10998. super('SymIntType');
  10999. }
  11000. static get() {
  11001. torch.SymIntType.value = torch.SymIntType.value || new torch.SymIntType();
  11002. return torch.SymIntType.value;
  11003. }
  11004. equals(rhs) {
  11005. return this.kind() === rhs.kind();
  11006. }
  11007. str() {
  11008. return 'SymInt';
  11009. }
  11010. __str__() {
  11011. return 'int';
  11012. }
  11013. });
  11014. this.registerType('torch.FloatType', class extends torch.Type {
  11015. constructor() {
  11016. super('FloatType');
  11017. }
  11018. static get() {
  11019. torch.FloatType.value = torch.FloatType.value || new torch.FloatType();
  11020. return torch.FloatType.value;
  11021. }
  11022. equals(rhs) {
  11023. return this.kind() === rhs.kind();
  11024. }
  11025. isSubtypeOf(rhs) {
  11026. return rhs.kind() === 'NumberType' || super.isSubtypeOf(rhs);
  11027. }
  11028. str() {
  11029. return 'float';
  11030. }
  11031. __str__() {
  11032. return 'float';
  11033. }
  11034. });
  11035. this.registerType('torch.StringType', class extends torch.Type {
  11036. constructor() {
  11037. super('StringType');
  11038. }
  11039. static get() {
  11040. torch.StringType.value = torch.StringType.value || new torch.StringType();
  11041. return torch.StringType.value;
  11042. }
  11043. equals(rhs) {
  11044. return this.kind() === rhs.kind();
  11045. }
  11046. str() {
  11047. return 'str';
  11048. }
  11049. __str__() {
  11050. return 'str';
  11051. }
  11052. });
  11053. this.registerType('torch.ComplexType', class extends torch.Type {
  11054. constructor() {
  11055. super('ComplexType');
  11056. }
  11057. static get() {
  11058. torch.ComplexType.value = torch.ComplexType.value || new torch.ComplexType();
  11059. return torch.ComplexType.value;
  11060. }
  11061. equals(rhs) {
  11062. return this.kind() === rhs.kind();
  11063. }
  11064. isSubtypeOf(rhs) {
  11065. return rhs.kind() === 'NumberType' || super.isSubtypeOf(rhs);
  11066. }
  11067. str() {
  11068. return 'complex';
  11069. }
  11070. __str__() {
  11071. return 'complex';
  11072. }
  11073. });
  11074. this.registerType('torch.DictType', class extends torch.Type {
  11075. constructor(key, value) {
  11076. super('DictType');
  11077. this.types = [key, value];
  11078. }
  11079. static create(key, value) {
  11080. let kind = key.kind();
  11081. if (key instanceof torch._C.DynamicType) {
  11082. kind = key.dynamicKind();
  11083. }
  11084. switch (kind) {
  11085. case 'AnyType':
  11086. case 'IntType':
  11087. case 'BoolType':
  11088. case 'FloatType':
  11089. case 'ComplexType':
  11090. case 'StringType':
  11091. case 'TensorType':
  11092. case 'DeviceObjType':
  11093. return new torch.DictType(key, value);
  11094. default:
  11095. throw new python.Error(`Invalid dict key type '${kind}'.`);
  11096. }
  11097. }
  11098. createWithContained(contained_types) {
  11099. if (contained_types.length !== 2) {
  11100. throw new python.Error('Expected 2 contained types.');
  11101. }
  11102. return torch.DictType.create(contained_types[0], contained_types[1]);
  11103. }
  11104. getKeyType() {
  11105. return this.types[0];
  11106. }
  11107. getValueType() {
  11108. return this.types[1];
  11109. }
  11110. hasFreeVariables() {
  11111. return this.getKeyType().hasFreeVariables() || this.getValueType().hasFreeVariables();
  11112. }
  11113. containedTypes() {
  11114. return this.types;
  11115. }
  11116. equals(rhs) {
  11117. if (rhs instanceof torch.DictType) {
  11118. return this.getKeyType().equals(rhs.getKeyType()) && this.getValueType().equals(rhs.getValueType());
  11119. }
  11120. return false;
  11121. }
  11122. str() {
  11123. return `Dict(${this.getKeyType().str()}, ${this.getValueType().str()})`;
  11124. }
  11125. __str__() {
  11126. return `Dict(${this.getKeyType().__str__()}, ${this.getValueType().__str__()})`;
  11127. }
  11128. });
  11129. this.registerType('torch.DeviceObjType', class extends torch.Type {
  11130. constructor() {
  11131. super('DeviceObjType');
  11132. }
  11133. static get() {
  11134. torch.DeviceObjType.value ||= new torch.DeviceObjType();
  11135. return torch.DeviceObjType.value;
  11136. }
  11137. str() {
  11138. return 'Device';
  11139. }
  11140. __str__() {
  11141. return 'Device';
  11142. }
  11143. });
  11144. this.registerType('torch.StreamObjType', class extends torch.Type {
  11145. constructor() {
  11146. super('StreamObjType');
  11147. }
  11148. str() {
  11149. return 'Stream';
  11150. }
  11151. __str__() {
  11152. return 'Stream';
  11153. }
  11154. });
  11155. this.registerType('torch._C._GeneratorType', class extends torch.Type {
  11156. constructor() {
  11157. super('GeneratorType');
  11158. }
  11159. static get() {
  11160. torch._C._GeneratorType.value = torch._C._GeneratorType.value || new torch._C._GeneratorType();
  11161. return torch._C._GeneratorType.value;
  11162. }
  11163. str() {
  11164. return 'Generator';
  11165. }
  11166. __str__() {
  11167. return 'Generator';
  11168. }
  11169. });
  11170. this.registerType('torch.InterfaceType', class extends torch.Type {
  11171. constructor() {
  11172. super('InterfaceType');
  11173. }
  11174. });
  11175. this.registerType('torch._C.DynamicType', class extends torch.Type {
  11176. constructor() {
  11177. super('DynamicType');
  11178. }
  11179. });
  11180. this.registerType('torch._C.FunctionType', class extends torch.Type {
  11181. constructor(func) {
  11182. super('FunctionType');
  11183. this._func = func;
  11184. }
  11185. static create(func) {
  11186. return new torch._C.FunctionType(func);
  11187. }
  11188. function() {
  11189. return this._func;
  11190. }
  11191. });
  11192. this.registerType('torch._C.VarType', class extends torch.Type {
  11193. constructor(name) {
  11194. super('VarType', name);
  11195. }
  11196. static create(name) {
  11197. return new torch._C.VarType(name);
  11198. }
  11199. name() {
  11200. return this._annotation_str;
  11201. }
  11202. hasFreeVariables() {
  11203. return true;
  11204. }
  11205. });
  11206. this.registerType('torch._C.AliasInfo', class {
  11207. constructor() {
  11208. this.is_write = false;
  11209. this.before_set = [];
  11210. this.after_set = [];
  11211. this.containedTypes = [];
  11212. }
  11213. addBeforeSet(value) {
  11214. this.before_set.push(value);
  11215. }
  11216. addAfterSet(value) {
  11217. this.after_set.push(value);
  11218. }
  11219. addContainedType(alias_info) {
  11220. this.containedTypes.push(alias_info);
  11221. }
  11222. str() {
  11223. const list = ['('];
  11224. list.push(this.before_set.join('|'));
  11225. if (this.after_set.length > 0) {
  11226. list.push(' -> ');
  11227. list.push(this.after_set.join('|'));
  11228. }
  11229. if (this.is_write) {
  11230. list.push('!');
  11231. }
  11232. list.push(')');
  11233. return list.join('');
  11234. }
  11235. });
  11236. this.registerFunction('torch._C.parseStringLiteral', (range, str) => {
  11237. if (str.startsWith('"') && str.endsWith('"')) {
  11238. return str.slice(1, -1);
  11239. }
  11240. if (str.startsWith("'") && str.endsWith("'")) {
  11241. return str.slice(1, -1);
  11242. }
  11243. throw new python.Error(`Invalid string literal '${str}'.`);
  11244. // inline std::string parseStringLiteral(
  11245. });
  11246. this.registerType('torch._C.Token', class {
  11247. constructor() {
  11248. this.kind = '';
  11249. this.value = '';
  11250. }
  11251. text() {
  11252. return this.value;
  11253. }
  11254. });
  11255. this.registerType('torch._C.Lexer', class {
  11256. constructor(buffer) {
  11257. this.buffer = buffer;
  11258. this.position = 0;
  11259. this.next_tokens = [new torch._C.Token(), new torch._C.Token(), new torch._C.Token(), new torch._C.Token()];
  11260. this.next();
  11261. }
  11262. cur() {
  11263. return this.next_tokens[0];
  11264. }
  11265. lookahead() {
  11266. if (!this.next_tokens[1].kind) {
  11267. this.position += this.cur().text().length;
  11268. this.lex(this.next_tokens[1]);
  11269. }
  11270. return this.next_tokens[1];
  11271. }
  11272. next() {
  11273. const [cur] = this.next_tokens;
  11274. [, this.next_tokens[0], this.next_tokens[1], this.next_tokens[2]] = this.next_tokens;
  11275. this.next_tokens[1].kind = '';
  11276. this.next_tokens[3] = cur;
  11277. const [token] = this.next_tokens;
  11278. if (token.kind) {
  11279. return cur;
  11280. }
  11281. this.position += cur.text().length;
  11282. this.lex(token);
  11283. return cur;
  11284. }
  11285. nextIf(kind) {
  11286. if (this.cur().kind !== kind) {
  11287. return false;
  11288. }
  11289. this.next();
  11290. return true;
  11291. }
  11292. expect(kind) {
  11293. if (this.cur().kind !== kind) {
  11294. throw new python.Error(`Unexpected '${this.cur().kind}' instead of '${kind}'.`);
  11295. }
  11296. return this.next();
  11297. }
  11298. lex(token) {
  11299. while (this.buffer[this.position] === ' ') {
  11300. this.position += 1;
  11301. }
  11302. let i = this.position;
  11303. if (i >= this.buffer.length) {
  11304. token.kind = '\0';
  11305. token.value = '';
  11306. } else if (this.buffer[i] === '.' && this.buffer[i + 1] === '.' && this.buffer[i + 2] === '.') {
  11307. token.kind = '...';
  11308. token.value = '...';
  11309. /* } else if (this.buffer[i] === '[' && this.buffer[i + 1] === ']') {
  11310. this.kind = '[]';
  11311. this.value = '[]'; */
  11312. } 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] === '|') {
  11313. token.kind = this.buffer[i];
  11314. token.value = this.buffer[i];
  11315. } else if ((this.buffer[i] >= 'a' && this.buffer[i] <= 'z') || (this.buffer[i] >= 'A' && this.buffer[i] <= 'Z') || this.buffer[i] === '_') {
  11316. i += 1;
  11317. 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] === '_')) {
  11318. i += 1;
  11319. }
  11320. token.kind = 'id';
  11321. token.value = this.buffer.slice(this.position, i);
  11322. } else if (this.buffer[i] === '-' && this.buffer[i + 1] === '>') {
  11323. token.kind = '->';
  11324. token.value = '->';
  11325. } else if ((this.buffer[i] >= '0' && this.buffer[i] <= '9') || this.buffer[i] === '-') {
  11326. i += 1;
  11327. while (i < this.buffer.length && ((this.buffer[i] >= '0' && this.buffer[i] <= '9') || this.buffer[i] === '.' || this.buffer[i] === 'e' || this.buffer[i] === '-')) {
  11328. i += 1;
  11329. }
  11330. token.kind = '#';
  11331. token.value = this.buffer.slice(this.position, i);
  11332. } else if (this.buffer[i] === "'" || this.buffer[i] === '"') {
  11333. const quote = this.buffer[i];
  11334. i += 1;
  11335. while (i < this.buffer.length && this.buffer[i] !== quote) {
  11336. i += (this.buffer[i] === '\\' && (this.buffer[i + 1] === "'" || this.buffer[i + 1] === '"' || this.buffer[i + 1] === '\\')) ? 2 : 1;
  11337. }
  11338. i += 1;
  11339. token.kind = 'string';
  11340. token.value = this.buffer.slice(this.position, i);
  11341. } else {
  11342. throw new python.Error(`Unsupported token at '${this.position}'.`);
  11343. }
  11344. }
  11345. });
  11346. this.registerType('torch._C.SchemaTypeParser', class {
  11347. constructor(L, complete_tensor_types, allow_typevars) {
  11348. this.L = L;
  11349. this.complete_tensor_types = complete_tensor_types;
  11350. this._allow_typevars = allow_typevars;
  11351. }
  11352. parseType() {
  11353. const r = this.parseFakeAndRealType();
  11354. return { first: r[0], second: r[2] };
  11355. }
  11356. parseBaseType() {
  11357. const L = this.L;
  11358. const tok = L.cur();
  11359. const text = tok.text();
  11360. L.next();
  11361. switch (text) {
  11362. case 'Tensor': return torch.TensorType.get();
  11363. case 'bool': return torch.BoolType.get();
  11364. case 'int': return torch.IntType.get();
  11365. case 'float': return torch.FloatType.get();
  11366. case 'complex': return torch.ComplexType.get();
  11367. case 'str': return torch.StringType.get();
  11368. case 'SymInt': return torch.SymIntType.get();
  11369. case 'Scalar': return torch.NumberType.get();
  11370. case 'ScalarType': return torch.Type.get('ScalarTypeType');
  11371. case 'Device': return torch.DeviceObjType.get();
  11372. case 'Layout': return torch.Type.get('Layout');
  11373. case 'MemoryFormat': return torch.Type.get('MemoryFormat');
  11374. case 'Generator': return torch._C._GeneratorType.get();
  11375. case 't': case 't1': case 't2': case 'tVal': return torch._C.VarType.create(text);
  11376. case 'Any': return torch.AnyType.get();
  11377. case 'AnyEnumType': return torch.Type.get('AnyEnumType');
  11378. case 'Dimname': return torch.StringType.get();
  11379. case 'QScheme': return torch.Type.get('QSchemeType');
  11380. case 'Stream': return torch.StreamObjType.get();
  11381. case 'Storage': return torch.Type.get('Storage');
  11382. case 'AnyClassType': return torch.Type.get('AnyClassType');
  11383. case 'NoneType': return torch.NoneType.get();
  11384. default: throw new python.Error(`Unsupported type '${text}'.`);
  11385. }
  11386. }
  11387. parseFakeAndRealType() {
  11388. const L = this.L;
  11389. let fake_value = null;
  11390. let real_value = null;
  11391. let alias_info = null;
  11392. if (L.nextIf('(')) {
  11393. const types = [];
  11394. while (!L.nextIf(')')) {
  11395. const r = this.parseType();
  11396. types.push(r.first);
  11397. if (alias_info && r.second) {
  11398. alias_info.addContainedType(r.second);
  11399. }
  11400. L.nextIf(',');
  11401. }
  11402. real_value = torch.TupleType.create(types);
  11403. fake_value = real_value;
  11404. } else if (L.cur().text() === 'Future') {
  11405. L.next();
  11406. L.expect('(');
  11407. const p = this.parseType();
  11408. const subtype = p.first;
  11409. // const subalias = p.second;
  11410. L.expect(')');
  11411. real_value = torch.FutureType.create(subtype);
  11412. fake_value = real_value;
  11413. } else if (L.cur().text() === 'Await') {
  11414. L.next();
  11415. L.expect('(');
  11416. const p = this.parseType();
  11417. const subtype = p.first;
  11418. // const subalias = p.second;
  11419. L.expect(')');
  11420. real_value = torch.AwaitType.get(subtype);
  11421. fake_value = real_value;
  11422. } else if (L.cur().text() === 'RRef') {
  11423. L.next();
  11424. L.expect('(');
  11425. const p = this.parseType();
  11426. const subtype = p.first;
  11427. // const subalias = p.second;
  11428. L.expect(')');
  11429. real_value = torch.RRefType.create(subtype);
  11430. fake_value = real_value;
  11431. } else if (L.cur().text() === 'Tensor') {
  11432. L.next();
  11433. real_value = torch.TensorType.get();
  11434. fake_value = real_value;
  11435. alias_info = this.parseAliasAnnotation();
  11436. } else if (L.cur().text() === 'Dict') {
  11437. L.next();
  11438. L.expect('(');
  11439. const key_type = this.parseType().first;
  11440. L.expect(',');
  11441. const value_type = this.parseType().first;
  11442. L.expect(')');
  11443. alias_info = this.parseAliasAnnotation();
  11444. real_value = torch.DictType.create(key_type, value_type);
  11445. fake_value = real_value;
  11446. } else if (L.nextIf('Union')) {
  11447. L.next();
  11448. L.expect('(');
  11449. const types = [];
  11450. types.push(this.parseType().first);
  11451. while (L.cur().kind !== ')') {
  11452. L.expect(',');
  11453. types.push(this.parseType().first);
  11454. }
  11455. L.expect(')');
  11456. alias_info = this.parseAliasAnnotation();
  11457. real_value = new torch.UnionType(types);
  11458. fake_value = real_value;
  11459. /* } else if (complete_tensor_types && L.cur().kind == TK_IDENT && parseTensorDType(L.cur().text())) {
  11460. fake_value = real_value = parseRefinedTensor();
  11461. alias_info = parseAliasAnnotation(); */
  11462. } else if (L.cur().kind === 'id' && L.cur().text() === '__torch__') {
  11463. L.next();
  11464. L.expect('.');
  11465. const torch_tok = L.expect('id');
  11466. if (torch_tok.text() !== 'torch') {
  11467. throw new python.Error('Expected classes namespace.');
  11468. }
  11469. L.expect('.');
  11470. const classes_tok = L.expect('id');
  11471. if (classes_tok.text() !== 'classes') {
  11472. throw new python.Error('Expected classes namespace.');
  11473. }
  11474. L.expect('.');
  11475. const ns_tok = L.expect('id');
  11476. L.expect('.');
  11477. const class_tok = L.expect('id');
  11478. real_value = torch._C.getCustomClass(`__torch__.torch.classes.${ns_tok.text()}.${class_tok.text()}`);
  11479. fake_value = real_value;
  11480. if (!fake_value) {
  11481. throw new python.Error(`Unknown custom class type '${ns_tok.text()}.${class_tok.text()}'.`);
  11482. }
  11483. } else {
  11484. real_value = this.parseBaseType();
  11485. fake_value = real_value;
  11486. if (real_value.kind() === 'ScalarTypeType' ||
  11487. real_value.kind() === 'MemoryFormat' ||
  11488. real_value.kind() === 'Layout' ||
  11489. real_value.kind() === 'SymIntType') {
  11490. fake_value = torch.IntType.get();
  11491. }
  11492. alias_info = this.parseAliasAnnotation();
  11493. }
  11494. while (true) {
  11495. if (L.cur().kind === '[' && L.lookahead().kind === ']') {
  11496. L.expect('[');
  11497. L.expect(']');
  11498. fake_value = torch.ListType.create(fake_value);
  11499. real_value = torch.ListType.create(real_value);
  11500. let container = this.parseAliasAnnotation();
  11501. if (alias_info) {
  11502. if (!container) {
  11503. container = new torch._C.AliasInfo();
  11504. container.is_write = alias_info.is_write;
  11505. }
  11506. container.addContainedType(alias_info);
  11507. }
  11508. alias_info = container;
  11509. } else if (L.nextIf('?')) {
  11510. fake_value = torch.OptionalType.create(fake_value);
  11511. real_value = torch.OptionalType.create(real_value);
  11512. } else {
  11513. break;
  11514. }
  11515. }
  11516. return [fake_value, real_value, alias_info];
  11517. }
  11518. parseAliasAnnotation() {
  11519. const L = this.L;
  11520. let alias_info = null;
  11521. if (L.nextIf('(')) {
  11522. alias_info = new torch._C.AliasInfo();
  11523. do {
  11524. alias_info.addBeforeSet(L.cur().text());
  11525. L.next();
  11526. if (L.nextIf('!')) {
  11527. alias_info.is_write = true;
  11528. }
  11529. }
  11530. while (L.nextIf('|'));
  11531. if (L.nextIf('->')) {
  11532. do {
  11533. alias_info.addAfterSet(L.cur().text());
  11534. L.next();
  11535. }
  11536. while (L.nextIf('|'));
  11537. }
  11538. L.expect(')');
  11539. }
  11540. return alias_info;
  11541. }
  11542. });
  11543. this.registerType('torch.Argument', class {
  11544. constructor(...args) {
  11545. // torch/aten/src/ATen/core/function_schema.h
  11546. this.N = null;
  11547. this.default_value = null;
  11548. this.kwarg_only = false;
  11549. this.alias_info = null;
  11550. if (args.length === 2) {
  11551. [this.name, this.type] = args;
  11552. this.real_type = this.type;
  11553. } else if (args.length === 3 && args[1] instanceof torch.Type && args[2] instanceof torch.Type) {
  11554. [this.name, this.type, this.real_type] = args;
  11555. } else if (args.length === 6) {
  11556. [this.name, this.type, this.real_type, this.N, this.default_value, this.kwarg_only] = args;
  11557. } else if (args.length === 7) {
  11558. [this.name, this.type, this.real_type, this.N, this.default_value, this.kwarg_only, this.alias_info] = args;
  11559. } else {
  11560. throw new python.Error('Invalid arguments.');
  11561. }
  11562. const is_alias = this.alias_info && this.alias_info.is_write;
  11563. this.is_out = this.kwarg_only && is_alias;
  11564. }
  11565. has_default_value() {
  11566. return this.default_value !== undefined;
  11567. }
  11568. is_inferred_type() {
  11569. if (this.type instanceof torch.TensorType) {
  11570. return this.type.isInferredType();
  11571. }
  11572. return false;
  11573. }
  11574. str() {
  11575. const list = [];
  11576. const type = this.real_type;
  11577. const is_opt = type instanceof torch.OptionalType;
  11578. const unopt_type = is_opt ? type.getElementType() : type;
  11579. if (unopt_type instanceof torch.ListType) {
  11580. list.push(unopt_type.getElementType().str());
  11581. if (this.alias_info && this.alias_info.containedTypes.length > 0) {
  11582. list.push(this.alias_info.containedTypes[0].str());
  11583. }
  11584. list.push(this.N === null ? `[]` : `[${this.N}]`);
  11585. } else {
  11586. list.push(unopt_type.str());
  11587. }
  11588. if (this.alias_info && this.alias_info.before_set.length > 0) {
  11589. list.push(this.alias_info.str());
  11590. }
  11591. if (is_opt) {
  11592. list.push('?');
  11593. }
  11594. if (this.name) {
  11595. list.push(' ');
  11596. list.push(this.name);
  11597. }
  11598. if (this.default_value !== undefined) {
  11599. const value = this.default_value;
  11600. if (value === null) {
  11601. list.push('=None');
  11602. } else if (typeof value === 'boolean') {
  11603. list.push('=');
  11604. list.push(value ? 'True' : 'False');
  11605. } else if (typeof value === 'string') {
  11606. list.push(`="${value}"`);
  11607. } else if (typeof value === 'number') {
  11608. list.push(`=${value}`);
  11609. if (Number.isInteger(value) && this.real_type instanceof torch.FloatType) {
  11610. list.push(`.`);
  11611. }
  11612. } else if (Array.isArray(value)) {
  11613. list.push(`=[${value.join(', ')}]`);
  11614. }
  11615. }
  11616. return list.join('');
  11617. }
  11618. });
  11619. torch._C.TypeKind = {
  11620. StringType: 'StringType',
  11621. NumberType: 'NumberType',
  11622. IntType: 'IntType',
  11623. BoolType: 'BoolType',
  11624. DynamicType: 'DynamicType',
  11625. OptionalType: 'OptionalType',
  11626. FloatType: 'FloatType',
  11627. ComplexType: 'ComplexType',
  11628. ListType: 'ListType',
  11629. };
  11630. this.registerType('torch._C.List', class extends Array {
  11631. constructor(type, elements) {
  11632. super(elements ? elements.length : 0);
  11633. if (Array.isArray(elements)) {
  11634. for (let i = 0; i < elements.length; i++) {
  11635. this[i] = elements[i];
  11636. }
  11637. }
  11638. this.type = type;
  11639. }
  11640. elementType() {
  11641. return this.type;
  11642. }
  11643. });
  11644. this.registerFunction('torch._C.builtin_cast_method_to_scalar_type', () => {
  11645. return new Map();
  11646. });
  11647. this.registerFunction('torch._C.string_to_type_lut', () => {
  11648. if (!torch._C.string_to_type_lut.basePythonTypes) {
  11649. const map = new Map();
  11650. map.set('Tensor', torch.TensorType.get());
  11651. map.set('int', torch.IntType.get());
  11652. map.set('float', torch.FloatType.get());
  11653. map.set('bool', torch.BoolType.get());
  11654. map.set('complex', torch.ComplexType.get());
  11655. map.set('str', torch.StringType.get());
  11656. map.set('Device', torch.DeviceObjType.get());
  11657. map.set('number', torch.NumberType.get());
  11658. map.set('None', torch.NoneType.get());
  11659. map.set('NoneType', torch.NoneType.get());
  11660. map.set('Any', torch.AnyType.get());
  11661. map.set('list', torch.Type.get('AnyListType'));
  11662. map.set('tuple', torch.Type.get('AnyTupleType'));
  11663. torch._C.string_to_type_lut.basePythonTypes = map;
  11664. }
  11665. return torch._C.string_to_type_lut.basePythonTypes;
  11666. });
  11667. this.registerType('torch._C.ScriptTypeParser', class {
  11668. constructor(resolver) {
  11669. this._resolver = resolver;
  11670. }
  11671. parseSchemaFromDef(def, skip_self) {
  11672. const name = def.name;
  11673. const args = this.parseArgsFromDecl(def, skip_self);
  11674. const returns = this.parseReturnFromDecl(def);
  11675. return new torch.FunctionSchema(name, '', args, returns, false, false);
  11676. }
  11677. parseArgsFromDecl(decl, skip_self) {
  11678. const retval = [];
  11679. if (decl.args.posonlyargs.length > 0 || decl.args.kwonlyargs.length > 0) {
  11680. throw new python.Error('Unsupported function argument.');
  11681. }
  11682. const params = decl.args.args.slice();
  11683. const kwonlyargs = new Set(Array.from(decl.args.kwonlyargs));
  11684. const start = skip_self ? 1 : 0;
  11685. for (let i = start; i < params.length; i++) {
  11686. const decl_arg = params[i];
  11687. const N = null;
  11688. const default_value = undefined;
  11689. const type = decl_arg.annotation ? this.parseTypeFromExpr(decl_arg.annotation) : null;
  11690. const arg = new torch.Argument(decl_arg.arg, type, type, N, default_value, kwonlyargs.has(decl_arg), null);
  11691. retval.push(arg);
  11692. }
  11693. return retval;
  11694. }
  11695. parseReturnFromDecl(decl) {
  11696. if (!decl.returns) {
  11697. return [];
  11698. }
  11699. if (this.parseBroadcastList(decl.returns)) {
  11700. throw new python.Error('Broadcastable lists cannot appear as a return type.');
  11701. }
  11702. const parsed_type = this.parseTypeFromExpr(decl.returns);
  11703. return [new torch.Argument('', parsed_type, parsed_type, null, undefined, false)];
  11704. }
  11705. parseTypeFromExpr(expr) {
  11706. if (this._resolver) {
  11707. if (expr instanceof ast.Name) {
  11708. const type = this._resolver.resolveType(expr.id);
  11709. if (type) {
  11710. return type;
  11711. }
  11712. }
  11713. }
  11714. return this.parseTypeFromExprImpl(expr);
  11715. }
  11716. parseTypeFromExprImpl(expr) {
  11717. if (expr instanceof ast.Subscript) {
  11718. const value_name = this.parseBaseTypeName(expr.value);
  11719. if (!value_name) {
  11720. throw new python.Error('Subscripted type must be a type identifier.');
  11721. }
  11722. return this.subscriptToType(value_name, expr);
  11723. }
  11724. const name = this.parseBaseTypeName(expr);
  11725. if (name) {
  11726. const itr = torch._C.string_to_type_lut().get(name);
  11727. if (itr) {
  11728. return itr;
  11729. }
  11730. if (this._resolver) {
  11731. const typePtr = this._resolver.resolveType(name, expr);
  11732. if (typePtr) {
  11733. return typePtr;
  11734. }
  11735. }
  11736. }
  11737. throw new python.Error(`Unknown type name '${name}'.`);
  11738. }
  11739. parseBaseTypeName(expr) {
  11740. if (expr instanceof ast.Name) {
  11741. return expr.id;
  11742. } else if (expr instanceof ast.Constant && expr.value === null) {
  11743. return 'None';
  11744. } else if (expr instanceof ast.Attribute) {
  11745. const name = expr.attr;
  11746. const tensor_subtypes = new Set(['Tensor', 'LongTensor', 'FloatTensor', 'DoubleTensor', 'IntTensor', 'ShortTensor', 'HalfTensor', 'CharTensor', 'ByteTensor', 'BoolTensor']);
  11747. if (torch._C.isTorch(expr.value) && tensor_subtypes.has(name)) {
  11748. return name;
  11749. }
  11750. return torch._C.collectQualname(expr);
  11751. }
  11752. throw new python.Error(`Unsupported type '${expr.__class__.__name__}'.`);
  11753. }
  11754. parseBroadcastList(/* expr */) {
  11755. return null;
  11756. }
  11757. parseType(str) {
  11758. const expr = ast.parse(str);
  11759. return this.parseTypeFromExpr(expr.body[0].value);
  11760. }
  11761. subscriptToType(typeName, subscript) {
  11762. if (typeName === 'Tuple' || typeName === 'tuple') {
  11763. const subscript_expr_types = [];
  11764. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11765. for (const expr of elts) {
  11766. subscript_expr_types.push(this.parseTypeFromExprImpl(expr));
  11767. }
  11768. return torch.TupleType.create(subscript_expr_types);
  11769. } else if (typeName === 'List' || typeName === 'list') {
  11770. if (subscript.slice instanceof ast.Slice || subscript.slice instanceof ast.Tuple) {
  11771. throw new python.Error('List type must have exactly one element type.');
  11772. }
  11773. const elem_type = this.parseTypeFromExprImpl(subscript.slice);
  11774. return torch.ListType.create(elem_type);
  11775. } else if (typeName === 'Optional') {
  11776. if (subscript.slice instanceof ast.Slice || subscript.slice instanceof ast.Tuple) {
  11777. throw new python.Error('Optional type must have exactly one element type.');
  11778. }
  11779. const elem_type = this.parseTypeFromExprImpl(subscript.slice);
  11780. return torch.OptionalType.create(elem_type);
  11781. } else if (typeName === 'Union') {
  11782. const subscript_expr_types = [];
  11783. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11784. for (const expr of elts) {
  11785. subscript_expr_types.push(this.parseTypeFromExprImpl(expr));
  11786. }
  11787. return torch.UnionType.create(subscript_expr_types);
  11788. } else if (typeName === 'Future' || typeName === 'torch.jit.Future') {
  11789. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11790. if (elts.length !== 1) {
  11791. throw new python.Error('Future type must have exactly one element type.');
  11792. }
  11793. const elem_type = this.parseTypeFromExprImpl(elts[0]);
  11794. return torch.FutureType.create(elem_type);
  11795. } else if (typeName === 'Await' || typeName === 'torch.jit._Await') {
  11796. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11797. if (elts.length !== 1) {
  11798. throw new python.Error('Await type must have exactly one element type.');
  11799. }
  11800. const elem_type = this.parseTypeFromExprImpl(elts[0]);
  11801. return torch.AwaitType.create(elem_type);
  11802. } else if (typeName === 'RRef') {
  11803. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11804. if (elts.length !== 1) {
  11805. throw new python.Error('RRef type must have exactly one element type.');
  11806. }
  11807. const elem_type = this.parseTypeFromExprImpl(elts[0]);
  11808. return torch.RRefType.create(elem_type);
  11809. } else if (typeName === 'Dict' || typeName === 'dict') {
  11810. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11811. if (elts.length !== 2) {
  11812. throw new python.Error('Dict type must have exactly two element types.');
  11813. }
  11814. const key_type = this.parseTypeFromExprImpl(elts[0]);
  11815. const value_type = this.parseTypeFromExprImpl(elts[1]);
  11816. return torch.DictType.create(key_type, value_type);
  11817. }
  11818. throw new python.Error(`Unknown type constructor '${typeName}'.`);
  11819. }
  11820. });
  11821. this.registerFunction('torch._C.isTorch', (expr) => {
  11822. return expr instanceof ast.Name && expr.id === 'torch';
  11823. });
  11824. this.registerFunction('torch._C.collectQualname', (select) => {
  11825. const base = select.value;
  11826. if (base instanceof ast.Name) {
  11827. return `${base.id}.${select.attr}`;
  11828. }
  11829. const basename = torch._C.collectQualname(base);
  11830. return `${basename}.${select.attr}`;
  11831. });
  11832. this.registerType('torch._ops.OpOverload', class extends torch._ops.OperatorBase {
  11833. constructor(overloadpacket, op, op_dk, schema, tags) {
  11834. super();
  11835. this._op = op;
  11836. this._op_dk = op_dk;
  11837. this._schema = schema;
  11838. this._overloadpacket = overloadpacket;
  11839. this._tags = tags;
  11840. this._overloadname = schema.overload_name === '' ? 'default' : schema.overload_name;
  11841. this._name = this._schema.name;
  11842. this._name = schema.overload_name ? `${this._name}.${schema.overload_name}` : this._name;
  11843. this.__name__ = `${this._schema.name.split('::')[1]}.${this._overloadname}`;
  11844. this.__module__ = overloadpacket.__module__;
  11845. op.__module__ = overloadpacket.__module__;
  11846. this.__qualname__ = self._name;
  11847. this.__annotations__ = {};
  11848. // this._defined_in_python = this.__qualname__ in torch.library._defs
  11849. let is_write = null;
  11850. for (const a of this._schema.arguments) {
  11851. if (a.alias_info) {
  11852. is_write = is_write === null ? a.alias_info.is_write : a.alias_info.is_write || is_write;
  11853. }
  11854. }
  11855. this.is_view = is_write !== null && !is_write;
  11856. }
  11857. name() {
  11858. return this._name;
  11859. }
  11860. });
  11861. this.registerType('torch._ops.OpOverloadPacket', class {
  11862. constructor(qualified_op_name, op_name, op, overload_names) {
  11863. this._qualified_op_name = qualified_op_name;
  11864. this.__name__ = op_name;
  11865. this._op = op;
  11866. this._overload_names = overload_names;
  11867. this._dir = [];
  11868. this._has_torchbind_op_overload = this._schemas.some((schema) => this._has_script_object_arg(schema));
  11869. }
  11870. get _schemas() {
  11871. return this._overload_names.map((overload_name) => torch._C._get_schema(this._qualified_op_name, overload_name));
  11872. }
  11873. __getattr__(key) {
  11874. key = key === 'default' ? '' : key;
  11875. const op_dk_tags = torch._C._get_operation_overload(this._qualified_op_name, key);
  11876. const [op_, op_dk_, tags] = op_dk_tags;
  11877. const schema = torch._C._get_schema(this._qualified_op_name, key);
  11878. const overload = this._has_script_object_arg(schema) ?
  11879. new torch._ops.TorchBindOpOverload(this, op_, op_dk_, schema, tags) :
  11880. new torch._ops.OpOverload(this, op_, op_dk_, schema, tags);
  11881. builtins.setattr(self, key, overload);
  11882. this._dir.push(key);
  11883. return overload;
  11884. }
  11885. _has_script_object_arg(schema) {
  11886. return schema.arguments.some((arg) => arg.type instanceof torch.ClassType);
  11887. }
  11888. __call__(...args) {
  11889. const fn = execution._operators.get(this._qualified_op_name);
  11890. if (!fn) {
  11891. throw new python.Error(`Operator call '${this._qualified_op_name}' is not registered.`);
  11892. }
  11893. return fn(...args);
  11894. }
  11895. });
  11896. this.registerType('torch._ops._OpNamespace', class extends types.ModuleType {
  11897. constructor(name) {
  11898. super(`torch.ops.${name}`);
  11899. this.name = name;
  11900. this._dir = [];
  11901. }
  11902. __getattr__(op_name) {
  11903. const namespace_name = this.name;
  11904. const qualified_op_name = `${namespace_name}::${op_name}`;
  11905. const module_name = `${this.__module__}.${namespace_name}`;
  11906. let op = null;
  11907. let overload_names = null;
  11908. try {
  11909. [op, overload_names] = this._get_packet(qualified_op_name, module_name);
  11910. } catch {
  11911. // continue regardless of error
  11912. }
  11913. if (!op) {
  11914. throw new python.Error(`Unknown operator type '${qualified_op_name}'.`);
  11915. }
  11916. op.__module__ = module_name;
  11917. const opoverloadpacket = new torch._ops.OpOverloadPacket(qualified_op_name, op_name, op, overload_names);
  11918. opoverloadpacket.__module__ = `${this.__module__}.${namespace_name}`;
  11919. builtins.setattr(this, op_name, opoverloadpacket);
  11920. this._dir.push(op_name);
  11921. return opoverloadpacket;
  11922. }
  11923. _get_packet(qualname, op_module) {
  11924. const [op, overload_names] = torch._C._jit_get_operation(qualname);
  11925. if (op) {
  11926. // torch.jit._builtins._register_builtin(op, qualname);
  11927. }
  11928. op.__module__ = op_module;
  11929. return [op, overload_names];
  11930. }
  11931. });
  11932. this.registerType('torch._C.graph_node_list', class {
  11933. constructor(head) {
  11934. this.head = head;
  11935. }
  11936. front() {
  11937. return this.head.next;
  11938. }
  11939. end() {
  11940. return this.head.prev;
  11941. }
  11942. [Symbol.iterator]() {
  11943. let current = this.head.next;
  11944. const prev = this.head.prev;
  11945. return {
  11946. next() {
  11947. if (current !== prev) {
  11948. const value = current;
  11949. current = current.next;
  11950. return { value, done: false };
  11951. }
  11952. return { done: true };
  11953. }
  11954. };
  11955. }
  11956. });
  11957. this.registerType('torch.Graph', class {
  11958. constructor() {
  11959. this._next_unique = 0;
  11960. this._unique_names = new Map();
  11961. this._name_base_suffix = new Map();
  11962. this.all_nodes = new Set();
  11963. this.all_values = new Set();
  11964. this.all_blocks = new Set();
  11965. this._block = new torch.Block(this, null);
  11966. this._insert_before = this.return_node();
  11967. }
  11968. insert(opname, args, kwargs, range) {
  11969. return torch._C.emitBuiltinCall(range, this, opname, args, kwargs);
  11970. }
  11971. create(kind, ...args) {
  11972. let inputs = null;
  11973. let num_outputs = 1;
  11974. if (args.length === 2 && Array.isArray(args[0]) && typeof args[1] === 'number') {
  11975. [inputs, num_outputs] = args;
  11976. } else if (args.length === 1) {
  11977. if (typeof args[0] === 'number') {
  11978. [num_outputs] = args;
  11979. } else if (Array.isArray(args[0])) {
  11980. [inputs] = args;
  11981. }
  11982. }
  11983. const n = new torch.Node(this, kind);
  11984. if (inputs) {
  11985. for (const i of inputs) {
  11986. n.addInput(i);
  11987. }
  11988. }
  11989. for (let i = 0; i < num_outputs; i++) {
  11990. n.addOutput();
  11991. }
  11992. return n;
  11993. }
  11994. createClone(n, value_map, copy_blocks) {
  11995. copy_blocks = copy_blocks === undefined ? true : copy_blocks;
  11996. const r = n.allocNewInstance(this);
  11997. for (const o of n.outputs()) {
  11998. r.addOutput().copyMetadata(o);
  11999. }
  12000. r.cloneFrom(n);
  12001. for (const i of n.inputs()) {
  12002. r.addInput(value_map(i));
  12003. }
  12004. if (copy_blocks) {
  12005. for (const b of n.blocks()) {
  12006. r.addBlock().cloneFrom(b, value_map);
  12007. }
  12008. }
  12009. return r;
  12010. }
  12011. createNone() {
  12012. const n = this.create('prim::Constant');
  12013. n.output().setType(torch.NoneType.get());
  12014. return n;
  12015. }
  12016. createUninitialized(typ) {
  12017. const n = this.create('prim::Uninitialized');
  12018. n.output().setType(typ);
  12019. return n;
  12020. }
  12021. createEnumValue(e) {
  12022. const enum_type = e.type().expect(torch.EnumType);
  12023. const n = this.create('prim::EnumValue', [e]);
  12024. n.output().setType(enum_type.getValueType());
  12025. return n;
  12026. }
  12027. createList(contained_type, values) {
  12028. const n = this.create('prim::ListConstruct', values);
  12029. for (const v of values) {
  12030. if (!v.type().isSubtypeOf(contained_type)) {
  12031. throw new python.Error('Invalid list item.');
  12032. }
  12033. }
  12034. n.output().setType(torch.ListType.create(contained_type));
  12035. return n;
  12036. }
  12037. createListUnpack(v, size) {
  12038. const list_type = v.type().expect(torch.ListType);
  12039. const elem_type = list_type.getElementType();
  12040. const n = this.create('prim::ListUnpack', [v], 0);
  12041. for (let i = 0; i < size; i++) {
  12042. n.addOutput().setType(elem_type);
  12043. }
  12044. return n;
  12045. }
  12046. createTuple(values, tuple_type) {
  12047. if (!tuple_type) {
  12048. const types = values.map((v) => v.type());
  12049. tuple_type = torch.TupleType.create(types);
  12050. }
  12051. const n = this.create('prim::TupleConstruct', values);
  12052. n.output().setType(tuple_type);
  12053. return n;
  12054. }
  12055. createTupleUnpack(v) {
  12056. const tt = v.type().expect(torch.TupleType);
  12057. const n = this.create('prim::TupleUnpack', [v], 0);
  12058. for (const element of tt.elements()) {
  12059. n.addOutput().setType(element);
  12060. }
  12061. return n;
  12062. }
  12063. createTupleIndex(tup, idx, output_type) {
  12064. const n = this.create('prim::TupleIndex', [tup, idx]);
  12065. n.output().setType(output_type);
  12066. return n;
  12067. }
  12068. createTupleSlice(tup, beg, step_size, num_values) {
  12069. const new_vals = [];
  12070. const tt = tup.type().expect(torch.TupleType);
  12071. let i = beg;
  12072. for (let j = 0; j < num_values; j++) {
  12073. const idx = this.insertConstant(new torch._C.IValue(i, 'Int'));
  12074. const tupleIndex = this.insertNode(this.createTupleIndex(tup, idx, tt.elements()[i]));
  12075. new_vals.push(tupleIndex.output());
  12076. i += step_size;
  12077. }
  12078. const n = this.createTuple(new_vals);
  12079. return n;
  12080. }
  12081. createDict(key_type, value_type, keys, values) {
  12082. if (keys.length !== values.length) {
  12083. throw new python.Error('Invalid dictionary size.');
  12084. }
  12085. const n = this.create('prim::DictConstruct');
  12086. const length = keys.length;
  12087. for (let i = 0; i < length; i++) {
  12088. if (!keys[i].type().isSubtypeOf(key_type)) {
  12089. throw new python.Error('Invalid key.');
  12090. }
  12091. if (!values[i].type().isSubtypeOf(value_type)) {
  12092. throw new python.Error('Invalid value.');
  12093. }
  12094. n.addInput(keys[i]);
  12095. n.addInput(values[i]);
  12096. }
  12097. n.output().setType(torch.DictType.create(key_type, value_type));
  12098. return n;
  12099. }
  12100. createObject(type) {
  12101. const node = this.create('prim::CreateObject');
  12102. node.output().setType(type);
  12103. return node;
  12104. }
  12105. createIsInstance(v, types) {
  12106. const n = this.create('prim::isinstance', [v], 1);
  12107. n.tys_('types', types);
  12108. n.output().setType(torch.BoolType.get());
  12109. return n;
  12110. }
  12111. createSetAttr(obj, field, newValue) {
  12112. const n = this.create('prim::SetAttr', [obj, newValue], 0);
  12113. n.s_('name', field);
  12114. return n;
  12115. }
  12116. createGetAttr(obj, field) {
  12117. const n = this.create('prim::GetAttr', [obj]);
  12118. n.s_('name', field);
  12119. const classType = obj.type();
  12120. const outputType = classType.getAttribute(field);
  12121. n.output().setType(outputType);
  12122. n.output().setDebugName(torch._C.normalizeAttrName(field));
  12123. return n;
  12124. }
  12125. createLoad(name, type) {
  12126. const n = this.create('prim::Load', [], 1);
  12127. n.s_('name', name);
  12128. n.output().setType(type);
  12129. return n;
  12130. }
  12131. createStore(name, v) {
  12132. const n = this.create('prim::Store', [v], 0);
  12133. n.s_('name', name);
  12134. return n;
  12135. }
  12136. inputs() {
  12137. return this._block.inputs();
  12138. }
  12139. outputs() {
  12140. return this._block.outputs();
  12141. }
  12142. nodes() {
  12143. return this._block.nodes();
  12144. }
  12145. param_node() {
  12146. return this._block.param_node();
  12147. }
  12148. return_node() {
  12149. return this._block.return_node();
  12150. }
  12151. block() {
  12152. return this._block;
  12153. }
  12154. addInput(name) {
  12155. return this._block.addInput(name);
  12156. }
  12157. insertNode(node) {
  12158. torch._C.AT_ASSERT(this._insert_before.inBlockList());
  12159. return node.insertBefore(this._insert_before);
  12160. }
  12161. insertConstant(val, loc, scope) {
  12162. return torch._C.insertConstant(this, val, loc, scope);
  12163. }
  12164. insertMethodCall(method_name, matched) {
  12165. const result = this.insertNode(this.create('prim::CallMethod', matched.inputs))
  12166. .s_('name', method_name)
  12167. .output().setType(matched.return_types[0]);
  12168. return result;
  12169. }
  12170. insertUncheckedCast(v, type) {
  12171. const n = this.create('prim::unchecked_cast', [v]);
  12172. this.insertNode(n);
  12173. n.output().setType(type);
  12174. return n.output();
  12175. }
  12176. insertToList(v, type) {
  12177. let dim = 0;
  12178. let ptr = type;
  12179. while (ptr instanceof torch.ListType) {
  12180. ptr = ptr.getElementType();
  12181. dim += 1;
  12182. }
  12183. let elem_ty = 0;
  12184. if (ptr instanceof torch.IntType) {
  12185. elem_ty = 0;
  12186. } else if (ptr instanceof torch.FloatType) {
  12187. elem_ty = 1;
  12188. } else if (ptr instanceof torch.BoolType) {
  12189. elem_ty = 2;
  12190. } else if (ptr instanceof torch.ComplexType) {
  12191. elem_ty = 3;
  12192. } else {
  12193. throw new python.Error(`Unsupported list type '${type.kind()}'.`);
  12194. }
  12195. const dim_val = this.insertConstant(dim);
  12196. const elem_ty_val = this.insertConstant(elem_ty);
  12197. const n = this.insertNode(this.create('prim::tolist', [v, dim_val, elem_ty_val]));
  12198. n.output().setType(type);
  12199. return n.output();
  12200. }
  12201. insertFunctionCall(callee, matched) {
  12202. const func_name = callee.name();
  12203. const fn_constant = this.insertNode(this.create('prim::Constant')).s_('name', func_name).output().setType(torch._C.FunctionType.create(callee));
  12204. const inputs = [fn_constant, ...matched.inputs];
  12205. const result = this.insertNode(this.create('prim::CallFunction', inputs)).output().setType(matched.return_types[0]);
  12206. return result;
  12207. }
  12208. insertPoint() {
  12209. return this._insert_before;
  12210. }
  12211. setInsertPoint(node) {
  12212. if (node instanceof torch.Block) {
  12213. node = node.return_node();
  12214. }
  12215. this._insert_before = node;
  12216. }
  12217. freeNode(n) {
  12218. this.all_nodes.delete(n);
  12219. }
  12220. freeValue(v) {
  12221. v.setDebugName('');
  12222. this.all_values.delete(v);
  12223. }
  12224. freeBlock(b) {
  12225. this.all_blocks.delete(b);
  12226. }
  12227. copy() {
  12228. const new_g = new torch.Graph();
  12229. new_g.cloneFrom(this);
  12230. return new_g;
  12231. }
  12232. cloneFrom(src) {
  12233. const env = (v) => {
  12234. throw new python.Error(`Use of value '${v.debugName()}' not in scope.`);
  12235. };
  12236. this.block().cloneFrom(src.block(), env);
  12237. }
  12238. set_op_version(version) {
  12239. this._op_version = version;
  12240. }
  12241. get_op_version() {
  12242. return this._op_version;
  12243. }
  12244. print(out, print_source_locations) {
  12245. out.write('graph(');
  12246. torch._C.const_value_list_with_types(out, this.inputs(), ',\n ');
  12247. out.write('):\n');
  12248. const groups = [];
  12249. for (const node of this.nodes()) {
  12250. node.print(out, 1, groups, print_source_locations);
  12251. }
  12252. out.write(' return (');
  12253. torch._C.printValueRefs(out, this.outputs());
  12254. out.write(')\n');
  12255. for (let i = 0; i < groups.length; i++) {
  12256. const fg = groups[i];
  12257. out.write('with ');
  12258. out.write(fg.kind());
  12259. out.write(`_${i} = `);
  12260. out.write(fg.g('Subgraph'));
  12261. }
  12262. return out;
  12263. }
  12264. toString() {
  12265. const out = new io.StringIO();
  12266. this.print(out, true);
  12267. return out.toString();
  12268. }
  12269. });
  12270. this.registerType('torch.Block', class {
  12271. constructor(graph, node) {
  12272. this._graph = graph;
  12273. this._input = graph.create('prim::Param', 0);
  12274. this._output = graph.create('prim::Return', 0);
  12275. this._owning_node = node;
  12276. this._input.next = this._output;
  12277. this._input.prev = this._output;
  12278. this._output.next = this._input;
  12279. this._output.prev = this._input;
  12280. this._graph.all_blocks.add(this);
  12281. this._output._owning_block = this;
  12282. // output_.topo_position_ = kUpperBound;
  12283. this._input._owning_block = this;
  12284. // input_.topo_position_ = kLowerBound;
  12285. }
  12286. inputs() {
  12287. return this._input.outputs();
  12288. }
  12289. outputs() {
  12290. return this._output.inputs();
  12291. }
  12292. nodes() {
  12293. return new torch._C.graph_node_list(this._input);
  12294. }
  12295. return_node() {
  12296. return this._output;
  12297. }
  12298. param_node() {
  12299. return this._input;
  12300. }
  12301. owningNode() {
  12302. return this._owning_node;
  12303. }
  12304. owningGraph() {
  12305. return this._graph;
  12306. }
  12307. addInput(name) {
  12308. const value = this._input.addOutput();
  12309. value.setDebugName(name || '');
  12310. return value;
  12311. }
  12312. registerOutput(value) {
  12313. this._output.addInput(value);
  12314. return this.outputs().length - 1;
  12315. }
  12316. appendNode(n) {
  12317. if (n._graph !== this._graph || n.inBlockList()) {
  12318. throw new python.Error('Node not in graph.');
  12319. }
  12320. n.insertBefore(this._output);
  12321. return n;
  12322. }
  12323. cloneFrom(src, value_map) {
  12324. const local_map = new Map();
  12325. const env = (v) => {
  12326. if (local_map.has(v)) {
  12327. return local_map.get(v);
  12328. }
  12329. return value_map(v);
  12330. };
  12331. const graph = this.owningGraph();
  12332. for (const input of src.inputs()) {
  12333. local_map.set(input, this.addInput().copyMetadata(input));
  12334. }
  12335. for (const node of src.nodes()) {
  12336. const new_node = this.appendNode(graph.createClone(node, env));
  12337. for (let i = 0; i < node.outputs().length; i++) {
  12338. const oo = node.outputs()[i];
  12339. const no = new_node.outputs()[i];
  12340. local_map.set(oo, no);
  12341. no.copyMetadata(oo);
  12342. }
  12343. }
  12344. for (const output of src.outputs()) {
  12345. this.registerOutput(env(output));
  12346. }
  12347. }
  12348. eraseOutput(i) {
  12349. this._output.removeInput(i);
  12350. }
  12351. destroy() {
  12352. this._output.removeAllInputs();
  12353. for (const n of this.nodes()) {
  12354. n.destroy();
  12355. }
  12356. this._output.destroy();
  12357. this._input.destroy();
  12358. this._graph.freeBlock(this);
  12359. }
  12360. });
  12361. this.registerType('torch.Node', class {
  12362. constructor(graph, kind) {
  12363. this._kind = kind;
  12364. this._graph = graph;
  12365. this._owning_block = null;
  12366. this._values = new Map();
  12367. this._inputs = [];
  12368. this._outputs = [];
  12369. this._blocks = [];
  12370. this._graph.all_nodes.add(this);
  12371. this._prev = null;
  12372. this._next = null;
  12373. this._source_range = null;
  12374. this._op = null;
  12375. }
  12376. owningGraph() {
  12377. return this._graph;
  12378. }
  12379. owningBlock() {
  12380. return this._owning_block;
  12381. }
  12382. kind() {
  12383. return this._kind;
  12384. }
  12385. schema() {
  12386. if (this._op) {
  12387. return this._op.schema();
  12388. }
  12389. // Node::schema() throws while torch.Node.schema() does not.
  12390. const op = this.maybeOperator();
  12391. if (op) {
  12392. return op.schema();
  12393. }
  12394. return null;
  12395. // return this.getOperator().schema();
  12396. }
  12397. hasNamedInput(name) {
  12398. for (const argument of this.schema().arguments) {
  12399. if (argument.name === name) {
  12400. return true;
  12401. }
  12402. }
  12403. return false;
  12404. }
  12405. matches(schema) {
  12406. if (torch._C.isBlockListedSchema(schema)) {
  12407. return false;
  12408. }
  12409. if (this.kind() !== schema.name) {
  12410. return false;
  12411. }
  12412. const actuals = this.inputs();
  12413. const formals = schema.arguments;
  12414. if (actuals.length < formals.length) {
  12415. return false;
  12416. }
  12417. const type_env = new Map();
  12418. for (let i = 0; i < formals.length; i++) {
  12419. let formal = formals[i].type;
  12420. const matched_type = torch._C.matchTypeVariables(formal, actuals[i].type(), type_env);
  12421. if (!matched_type.success()) {
  12422. return false;
  12423. }
  12424. const resolved = torch._C.tryEvalTypeVariables(formal, type_env);
  12425. if (resolved) {
  12426. formal = resolved;
  12427. }
  12428. if (!actuals[i].type().isSubtypeOf(formal)) {
  12429. return false;
  12430. }
  12431. }
  12432. if (!schema.is_vararg && actuals.length !== formals.length) {
  12433. return false;
  12434. }
  12435. return true;
  12436. }
  12437. mustBeNone() {
  12438. return this._kind === 'prim::AutogradZero' ||
  12439. (this.outputs().length === 1 && this.output().type() === torch.NoneType.get()) ||
  12440. (this._kind === 'prim::Constant' && !this.hasAttributes() && this.output().type() instanceof torch.OptionalType);
  12441. }
  12442. maybeSchema() {
  12443. const op = this.maybeOperator();
  12444. if (op) {
  12445. return op.schema();
  12446. }
  12447. return null;
  12448. }
  12449. maybeOperator() {
  12450. if (!this._op) {
  12451. const candidates = torch._C.getAllOperatorsFor(this.kind());
  12452. for (const candidate of candidates) {
  12453. if (this.matches(candidate.schema())) {
  12454. this._op = candidate;
  12455. break;
  12456. }
  12457. }
  12458. }
  12459. return this._op;
  12460. }
  12461. getOperator() {
  12462. const maybe = this.maybeOperator();
  12463. if (maybe) {
  12464. return maybe;
  12465. }
  12466. throw new python.Error(`Schema not found for node '${this.kind()}'.`);
  12467. }
  12468. getOperation() {
  12469. return this.getOperator().getOperation(this);
  12470. }
  12471. isNondeterministic() {
  12472. const schema = this.maybeSchema();
  12473. if (!this.kind().startsWith('aten::')) {
  12474. return false;
  12475. }
  12476. if (!schema) {
  12477. return false;
  12478. }
  12479. const schema_info = new torch._C.SchemaInfo(schema);
  12480. if (this.hasNamedInput('train')) {
  12481. throw new python.Error('Not Implemented.');
  12482. // const value = constant_as<bool>(this.namedInput("train"));
  12483. // if (value) {
  12484. // schema_info.addArgumentValue('train', value);
  12485. // }
  12486. }
  12487. return schema_info.is_nondeterministic();
  12488. }
  12489. hasSideEffects() {
  12490. switch (this._kind) {
  12491. case 'prim::PythonOp':
  12492. case 'prim::IgnoredPythonOp':
  12493. case 'prim::Print':
  12494. case 'prim::RaiseException':
  12495. case 'aten::warn':
  12496. case 'aten::save':
  12497. case 'aten::manual_seed':
  12498. case 'prim::AddStatValue':
  12499. case 'prim::TimePoint':
  12500. case 'prim::CallFunction':
  12501. case 'prim::CallMethod':
  12502. case 'prim::BailoutTemplate':
  12503. case 'prim::BailOut':
  12504. case 'prim::rpc_async':
  12505. case 'prim::rpc_sync':
  12506. case 'prim::rpc_remote':
  12507. case 'aten::wait':
  12508. case 'cuda::set_stream':
  12509. case 'cuda::_set_device':
  12510. case 'cuda::_current_device':
  12511. case 'cuda::synchronize':
  12512. case 'prim::Enter':
  12513. case 'prim::Exit':
  12514. return true;
  12515. default:
  12516. break;
  12517. }
  12518. const op = this.maybeOperator();
  12519. if (!op) {
  12520. torch._C.TORCH_INTERNAL_ASSERT(this._kind.startsWith('prim::'));
  12521. return false;
  12522. }
  12523. if (this._kind.startsWith('prim::') || this._kind.startsWith('aten::') || this._kind.startsWith('cuda::')) {
  12524. torch._C.TORCH_INTERNAL_ASSERT(
  12525. op.aliasAnalysisKind() === 'INTERNAL_SPECIAL_CASE' ||
  12526. op.aliasAnalysisKind() === 'FROM_SCHEMA' ||
  12527. op.aliasAnalysisKind() === 'CONSERVATIVE');
  12528. }
  12529. switch (op.aliasAnalysisKind()) {
  12530. case 'PURE_FUNCTION':
  12531. case 'FROM_SCHEMA':
  12532. case 'INTERNAL_SPECIAL_CASE':
  12533. return false;
  12534. case 'CONSERVATIVE':
  12535. return true;
  12536. default:
  12537. break;
  12538. }
  12539. torch._C.TORCH_INTERNAL_ASSERT(false);
  12540. return false;
  12541. }
  12542. inputs() {
  12543. return this._inputs;
  12544. }
  12545. outputs() {
  12546. return this._outputs;
  12547. }
  12548. input(i) {
  12549. if (i === undefined) {
  12550. torch._C.AT_ASSERT(this._inputs.length === 1);
  12551. return this._inputs[0];
  12552. }
  12553. return this._inputs[i];
  12554. }
  12555. output(i) {
  12556. if (i === undefined) {
  12557. torch._C.AT_ASSERT(this._outputs.length === 1);
  12558. return this._outputs[0];
  12559. }
  12560. return this._outputs[i];
  12561. }
  12562. hasUses() {
  12563. for (const o of this.outputs()) {
  12564. if (o.uses().length > 0) {
  12565. return true;
  12566. }
  12567. }
  12568. return false;
  12569. }
  12570. blocks() {
  12571. return this._blocks;
  12572. }
  12573. insertInput(i, value) {
  12574. torch._C.AT_ASSERT(this._graph === value.owningGraph());
  12575. this._op = null;
  12576. for (let use_itr = i; use_itr < this._inputs.length; use_itr++) {
  12577. const use = this.findUseForInput(use_itr);
  12578. use.offset += 1;
  12579. }
  12580. this._inputs.splice(i, 0, value);
  12581. value._uses.push(new torch.Use(this, i));
  12582. return value;
  12583. }
  12584. addInput(value) {
  12585. torch._C.AT_ASSERT(this._graph === value.owningGraph());
  12586. this._op = null;
  12587. const use = new torch.Use(this, this._inputs.length);
  12588. value.uses().push(use);
  12589. this._inputs.push(value);
  12590. return value;
  12591. }
  12592. addOutput() {
  12593. const value = new torch.Value(this, this._outputs.length);
  12594. this._outputs.push(value);
  12595. return value;
  12596. }
  12597. addBlock() {
  12598. this._op = null;
  12599. this._blocks.push(new torch.Block(this.owningGraph(), this));
  12600. return this._blocks[this._blocks.length - 1];
  12601. }
  12602. get prev() {
  12603. return this._prev;
  12604. }
  12605. set prev(value) {
  12606. this._prev = value;
  12607. }
  12608. get next() {
  12609. return this._next;
  12610. }
  12611. set next(value) {
  12612. this._next = value;
  12613. }
  12614. insertBefore(n) {
  12615. if (!n.inBlockList()) {
  12616. throw new python.Error('Node not in block.');
  12617. }
  12618. this.insertAfter(n.prev);
  12619. return this;
  12620. }
  12621. insertAfter(n) {
  12622. torch._C.AT_ASSERT(!this.inBlockList() || n.inBlockList());
  12623. torch._C.AT_ASSERT(n.owningBlock());
  12624. torch._C.TORCH_INTERNAL_ASSERT(n.kind() !== 'prim::Return');
  12625. this._owning_block = n.owningBlock();
  12626. const next = n.next;
  12627. n.next = this;
  12628. this.prev = n;
  12629. this.next = next;
  12630. next.prev = this;
  12631. // this.assignTopoPosition();
  12632. return this;
  12633. }
  12634. allocNewInstance(g) {
  12635. return new torch.Node(g, this.kind());
  12636. }
  12637. cloneFrom(s) {
  12638. this._source_range = s._source_range;
  12639. if (s._scope && !s._scope.isBlank()) {
  12640. this._scope = s._scope;
  12641. }
  12642. this.copyAttributes(s);
  12643. this._callstack = s._callstack;
  12644. }
  12645. copyAttributes(rhs) {
  12646. this._values = new Map(rhs._values);
  12647. return this;
  12648. }
  12649. dropInput(i) {
  12650. torch._C.AT_ASSERT(i < this._inputs.length);
  12651. const input_node = this._inputs[i];
  12652. const use_it = this.findUseForInput(i);
  12653. input_node._uses = input_node._uses.filter((use) => use !== use_it);
  12654. this._inputs[i] = null;
  12655. return input_node;
  12656. }
  12657. eraseOutput(i) {
  12658. torch._C.AT_ASSERT(i < this._outputs.length);
  12659. // torch._C.AT_ASSERT(this._outputs[i].uses().length === 0);
  12660. this._op = null;
  12661. const n = this._outputs[i];
  12662. this._outputs.splice(i, 1);
  12663. this.owningGraph().freeValue(n);
  12664. for (let j = i; j < this._outputs.length; j++) {
  12665. this._outputs[j]._offset--;
  12666. }
  12667. }
  12668. eraseBlock(i) {
  12669. this._op = null;
  12670. const n = this._blocks[i];
  12671. this._blocks.splice(i, 1);
  12672. n.destroy();
  12673. }
  12674. findUseForInput(i) {
  12675. const input_uses = this._inputs[i]._uses;
  12676. for (const use_it of input_uses) {
  12677. if (use_it.user === this && use_it.offset === i) {
  12678. return use_it;
  12679. }
  12680. }
  12681. throw new python.Error('Input use not found.');
  12682. }
  12683. moveBefore(n) {
  12684. this.removeFromList();
  12685. this.insertBefore(n);
  12686. }
  12687. removeInput(i) {
  12688. this._op = null;
  12689. this.dropInput(i);
  12690. for (let j = i + 1; j < this._inputs.length; j++) {
  12691. const it = this.findUseForInput(j);
  12692. it.offset--;
  12693. }
  12694. this._inputs.splice(i, 1);
  12695. }
  12696. removeAllInputs() {
  12697. this._op = null;
  12698. for (let i = 0; i < this._inputs.length; i++) {
  12699. this.dropInput(i);
  12700. }
  12701. this._inputs = [];
  12702. }
  12703. inBlockList() {
  12704. return this.next !== null;
  12705. }
  12706. removeFromList() {
  12707. this._owning_block = null;
  12708. const next = this.next;
  12709. const prev = this.prev;
  12710. prev.next = next;
  12711. next.prev = prev;
  12712. this.next = null;
  12713. this.prev = null;
  12714. }
  12715. destroy() {
  12716. while (this.outputs().length > 0) {
  12717. this.eraseOutput(this.outputs().length - 1);
  12718. }
  12719. while (this.blocks().length > 0) {
  12720. this.eraseBlock(this.blocks().length - 1);
  12721. }
  12722. this.removeAllInputs();
  12723. if (this.inBlockList()) {
  12724. this.removeFromList();
  12725. }
  12726. this._graph.freeNode(this);
  12727. }
  12728. replaceAllUsesWith(n) {
  12729. torch._C.AT_ASSERT(this.outputs().length === n.outputs().length);
  12730. const nOutputs = this.outputs().length;
  12731. for (let i = 0; i < nOutputs; i++) {
  12732. this.outputs()[i].replaceAllUsesWith(n.outputs()[i]);
  12733. }
  12734. }
  12735. s_(name, value) {
  12736. this._values.set(name, [value, 's']);
  12737. return this;
  12738. }
  12739. s(name) {
  12740. return this._values.get(name)[0];
  12741. }
  12742. ss_(name, value) {
  12743. this._values.set(name, [value, 'ss']);
  12744. return this;
  12745. }
  12746. ss(name) {
  12747. return this._values.get(name)[0];
  12748. }
  12749. i_(name, value) {
  12750. this._values.set(name, [value, 'i']);
  12751. return this;
  12752. }
  12753. i(name) {
  12754. return this._values.get(name)[0];
  12755. }
  12756. f_(name, value) {
  12757. this._values.set(name, [value, 'f']);
  12758. return this;
  12759. }
  12760. f(name) {
  12761. return this._values.get(name)[0];
  12762. }
  12763. c_(name, value) {
  12764. this._values.set(name, [value, 'c']);
  12765. return this;
  12766. }
  12767. c(name) {
  12768. return this._values.get(name)[0];
  12769. }
  12770. t_(name, value) {
  12771. this._values.set(name, [value, 't']);
  12772. return this;
  12773. }
  12774. t(name) {
  12775. return this._values.get(name)[0];
  12776. }
  12777. tys_(name, value) {
  12778. this._values.set(name, [value, 'tys']);
  12779. return this;
  12780. }
  12781. tys(name) {
  12782. return this._values.get(name)[0];
  12783. }
  12784. ival_(name, value) {
  12785. this._values.set(name, [value, 'ival']);
  12786. return this;
  12787. }
  12788. ival(name) {
  12789. return this._values.get(name)[0];
  12790. }
  12791. hasAttribute(name) {
  12792. return this._values.has(name);
  12793. }
  12794. hasAttributes() {
  12795. return this._values.size > 0;
  12796. }
  12797. attributeNames() {
  12798. return Array.from(this._values.keys());
  12799. }
  12800. kindOf(name) {
  12801. return this._values.get(name)[1];
  12802. }
  12803. setSourceRange(r) {
  12804. torch._C.AT_ASSERT(r instanceof torch._C.SourceRange);
  12805. this._source_range = r;
  12806. return this;
  12807. }
  12808. sourceRange() {
  12809. if (this._source_range) {
  12810. return this._source_range;
  12811. }
  12812. return new torch._C.SourceRange();
  12813. }
  12814. print_attributes(out, ignore_subgraph) {
  12815. ignore_subgraph = ignore_subgraph || false;
  12816. out.write('[');
  12817. const names = this.attributeNames();
  12818. for (let i = 0; i < names.length; i++) {
  12819. const name = names[i];
  12820. if (ignore_subgraph && name === 'Subgraph') {
  12821. continue;
  12822. }
  12823. if (i > 0) {
  12824. out.write(', ');
  12825. }
  12826. out.write(`${name}=`);
  12827. this.printAttrValue(out, name);
  12828. }
  12829. out.write(']');
  12830. }
  12831. printTypeList(out, items) {
  12832. out.write('[');
  12833. for (let i = 0; i < items.length; i++) {
  12834. const item = items[i];
  12835. if (i++ > 0) {
  12836. out.write(', ');
  12837. }
  12838. out.write(item.str());
  12839. }
  12840. out.write(']');
  12841. }
  12842. printAttrValue(out, name) {
  12843. const kind = this.kindOf(name);
  12844. switch (kind) {
  12845. case 'c': case 'cs': case 'f': case 'fs': case 'i': case 'is':
  12846. case 'ss': case 'ival': case 'ty':
  12847. out.write(this[kind](name));
  12848. break;
  12849. case 's':
  12850. out.write(`"${this.s(name)}"`);
  12851. break;
  12852. case 't':
  12853. out.write(`"{}"`);
  12854. break;
  12855. case 'ts': out.write('[<Tensors>]'); break;
  12856. case 'g': out.write('[<Graph>]'); break;
  12857. case 'gs': out.write('[<Graphs>]'); break;
  12858. case 'tys': this.printTypeList(out, this.tys(name)); break;
  12859. default: throw new python.Error(`Unknown attribute kind '${kind}'.`);
  12860. }
  12861. }
  12862. print(out, level, groups, print_source_locations, print_attributes, print_scopes, print_body) {
  12863. print_source_locations = print_source_locations === false ? false : true;
  12864. print_attributes = print_attributes === false ? false : true;
  12865. print_scopes = print_scopes === false ? false : true;
  12866. print_body = print_body === false ? false : true;
  12867. const outs = this.outputs();
  12868. torch._C.indent(out, level);
  12869. torch._C.const_value_list_with_types(out, outs, ', ');
  12870. out.write(' = ');
  12871. if (this.kind() === 'prim::PythonOp') {
  12872. throw new python.Error('Not implemented.');
  12873. } else if (this.hasAttribute('Subgraph') && groups) {
  12874. throw new python.Error('Not implemented.');
  12875. } else {
  12876. out.write(this.kind());
  12877. if (print_attributes && this.hasAttributes()) {
  12878. this.print_attributes(out);
  12879. }
  12880. }
  12881. out.write('(');
  12882. torch._C.printValueRefs(out, this.inputs());
  12883. out.write(')');
  12884. if (print_scopes) {
  12885. //
  12886. }
  12887. if (print_source_locations) {
  12888. let r = this.sourceRange();
  12889. if (r.source()) {
  12890. const orig = this.sourceRange().source().findSourceRangeThatGenerated(r);
  12891. if (orig) {
  12892. r = orig;
  12893. }
  12894. }
  12895. const file_line_col = r.file_line_col();
  12896. if (file_line_col !== null) {
  12897. const [filename, line, col] = file_line_col;
  12898. out.write(` # ${filename}:${line}:${col}`);
  12899. }
  12900. }
  12901. if (!print_body) {
  12902. return out;
  12903. }
  12904. out.write('\n');
  12905. for (let i = 0; i < this.blocks().length; i++) {
  12906. const b = this.blocks().at(i);
  12907. torch._C.indent(out, level + 1);
  12908. out.write(`block${i}(`);
  12909. torch._C.const_value_list_with_types(out, b.inputs());
  12910. out.write('):\n');
  12911. for (const nested of b.nodes()) {
  12912. nested.print(out, level + 2, groups);
  12913. }
  12914. torch._C.indent(out, level + 2);
  12915. out.write('-> (');
  12916. torch._C.printValueRefs(out, b.outputs());
  12917. out.write(')\n');
  12918. }
  12919. return out;
  12920. }
  12921. toString() {
  12922. const out = new io.StringIO();
  12923. this.print(out, 0, true);
  12924. return out.toString();
  12925. }
  12926. });
  12927. this.registerType('torch.Value', class {
  12928. constructor(node, offset) {
  12929. this._node = node;
  12930. this._offset = offset;
  12931. this._unique = node._graph._next_unique++;
  12932. this._uses = [];
  12933. this._node._graph.all_values.add(this);
  12934. }
  12935. unique() {
  12936. return this._unique;
  12937. }
  12938. node() {
  12939. return this._node;
  12940. }
  12941. owningGraph() {
  12942. return this._node.owningGraph();
  12943. }
  12944. uses() {
  12945. return this._uses;
  12946. }
  12947. hasUses() {
  12948. return this._uses.length > 0;
  12949. }
  12950. mustBeNone() {
  12951. return this.type() instanceof torch.NoneType || this._node.mustBeNone();
  12952. }
  12953. mustNotBeNone() {
  12954. return this._node.kind() !== 'prim::AutogradAdd' &&
  12955. this.type() !== torch.NoneType.get() &&
  12956. !(this.type() instanceof torch.OptionalType) &&
  12957. !(this.type() instanceof torch.UnionType && this.type().expect(torch.UnionType).canHoldType(torch.NoneType.get()));
  12958. }
  12959. isValidName(name) {
  12960. if (name.length === 0) {
  12961. return true;
  12962. }
  12963. if (torch._C.isNumber(name)) {
  12964. return false;
  12965. }
  12966. return true;
  12967. }
  12968. hasDebugName() {
  12969. return this._unique_name && this._unique_name.length > 0;
  12970. }
  12971. setDebugName(name) {
  12972. if (!this.isValidName(name)) {
  12973. throw new python.Error(`Invalid name '${name}'.`);
  12974. }
  12975. const names = this.node().owningGraph()._unique_names;
  12976. if (this.hasDebugName()) {
  12977. names.delete(this._unique_name);
  12978. this._unique_name = '';
  12979. }
  12980. if (!name) {
  12981. return this;
  12982. }
  12983. const old_owner_of_name = names.get(name);
  12984. if (old_owner_of_name) {
  12985. let suffix = 1;
  12986. let name_base = name;
  12987. const last_dot_pos = name.lastIndexOf('.');
  12988. if (last_dot_pos !== -1) {
  12989. if (/^\d+$/.test(name.substring(last_dot_pos + 1))) {
  12990. suffix = Number(name.substring(last_dot_pos + 1));
  12991. name_base = name.substring(0, last_dot_pos);
  12992. }
  12993. }
  12994. const names_suffixes = this.node().owningGraph()._name_base_suffix;
  12995. if (names_suffixes.has(name_base)) {
  12996. suffix = Math.max(suffix, names_suffixes.get(name_base));
  12997. }
  12998. let replacement_name = null;
  12999. do {
  13000. replacement_name = `${name_base}.${suffix++}`;
  13001. } while (names.has(replacement_name));
  13002. names_suffixes.set(name_base, suffix);
  13003. old_owner_of_name.setDebugName(replacement_name);
  13004. }
  13005. names.set(name, this);
  13006. this._unique_name = name;
  13007. return this;
  13008. }
  13009. debugName() {
  13010. if (this.hasDebugName()) {
  13011. return this._unique_name;
  13012. }
  13013. return this.unique().toString();
  13014. }
  13015. type() {
  13016. return this._type;
  13017. }
  13018. setType(type) {
  13019. // torch._C.AT_ASSERT(type instanceof torch.Type);
  13020. if (type instanceof torch._C.DynamicType) {
  13021. type = type.fallback();
  13022. }
  13023. this._type = type;
  13024. for (const use of this._uses) {
  13025. use.user._op = null;
  13026. }
  13027. return this;
  13028. }
  13029. set value(value) { // remove
  13030. if (value instanceof torch.Value) {
  13031. throw new python.Error('Value cannot be a value.');
  13032. }
  13033. this._value = value;
  13034. }
  13035. get value() { // remove
  13036. return this._value;
  13037. }
  13038. replaceFirstUseWith(newValue) {
  13039. torch._C.AT_ASSERT(this.owningGraph() === newValue.owningGraph());
  13040. const [u] = this.uses();
  13041. u.user._inputs[u.offset] = newValue;
  13042. newValue._uses.push(u);
  13043. this._uses.shift();
  13044. }
  13045. replaceAllUsesWith(newValue) {
  13046. while (this.uses().length > 0) {
  13047. this.replaceFirstUseWith(newValue);
  13048. }
  13049. }
  13050. copyMetadata(from) {
  13051. this.setType(from.type());
  13052. if (from.hasDebugName()) {
  13053. this.setDebugName(from.debugName());
  13054. }
  13055. return this;
  13056. }
  13057. toString() {
  13058. return `${this.debugName()} : ${this.type().toString()}`;
  13059. }
  13060. });
  13061. this.registerType('torch.Use', class {
  13062. constructor(user, offset) {
  13063. this.user = user;
  13064. this.offset = offset;
  13065. }
  13066. });
  13067. this.registerType('torch._C.IValue', class {
  13068. constructor(value, tag) {
  13069. this.value = value;
  13070. if (tag) {
  13071. this.tag = tag;
  13072. } else if (value === undefined) {
  13073. this.tag = 'None';
  13074. this.value = null;
  13075. } else if (typeof value === 'boolean') {
  13076. this.tag = 'Bool';
  13077. } else if (typeof value === 'string') {
  13078. this.tag = 'String';
  13079. } else if (value instanceof torch.Tensor) {
  13080. this.tag = 'Tensor';
  13081. } else if (value instanceof torch.ScriptObject) {
  13082. this.tag = 'Object';
  13083. } else if (Array.isArray(value)) {
  13084. this.tag = 'GenericList';
  13085. } else if (value instanceof torch._C.Tuple) {
  13086. this.tag = 'Tuple';
  13087. } else if (value instanceof torch.device) {
  13088. this.tag = 'Device';
  13089. } else if (Number.isInteger(value)) {
  13090. this.tag = 'Int';
  13091. } else if (typeof value === 'number') {
  13092. this.tag = 'Double';
  13093. } else if (value instanceof builtins.complex) {
  13094. this.tag = 'ComplexDouble';
  13095. } else if (value instanceof torch._C.EnumHolder) {
  13096. this.tag = 'Enum';
  13097. } else {
  13098. throw new python.Error('Unsupported type.');
  13099. }
  13100. }
  13101. isNone() {
  13102. return this.tag === 'None';
  13103. }
  13104. isBool() {
  13105. return this.tag === 'Bool';
  13106. }
  13107. toBool() {
  13108. return this.value;
  13109. }
  13110. isObject() {
  13111. return this.tag === 'Object';
  13112. }
  13113. toObject() {
  13114. return this.value;
  13115. }
  13116. isTensor() {
  13117. return this.tag === 'Tensor';
  13118. }
  13119. toTensor() {
  13120. return this.value;
  13121. }
  13122. isDouble() {
  13123. return this.tag === 'Double';
  13124. }
  13125. toDouble() {
  13126. return this.value;
  13127. }
  13128. isComplexDouble() {
  13129. return this.tag === 'ComplexDouble' || this.tag === 'Complex';
  13130. }
  13131. toComplexDouble() {
  13132. return this.value;
  13133. }
  13134. isInt() {
  13135. return this.tag === 'Int';
  13136. }
  13137. toInt() {
  13138. if (this.isInt()) {
  13139. return this.value;
  13140. } else if (this.isSymInt()) {
  13141. return this.toSymInt().guard_int(/* __FILE__, __LINE__ */);
  13142. }
  13143. throw new python.Error('Expected int.');
  13144. }
  13145. isString() {
  13146. return this.tag === 'String';
  13147. }
  13148. toStringRef() {
  13149. return this.value;
  13150. }
  13151. isList() {
  13152. return this.tag === 'GenericList';
  13153. }
  13154. toList() {
  13155. return this.value;
  13156. }
  13157. toListRef() {
  13158. return this.value;
  13159. }
  13160. isBoolList() {
  13161. return this.value instanceof torch._C.List && this.value.elementType() instanceof torch.BoolType;
  13162. }
  13163. isIntList() {
  13164. return this.value instanceof torch._C.List && this.value.elementType() instanceof torch.IntType;
  13165. }
  13166. isDoubleList() {
  13167. return this.value instanceof torch._C.List && this.value.elementType() instanceof torch.FloatType;
  13168. }
  13169. isDevice() {
  13170. return this.tag === 'Device';
  13171. }
  13172. toDevice() {
  13173. return this.value;
  13174. }
  13175. isGenerator() {
  13176. return this.tag === 'Generator';
  13177. }
  13178. isStream() {
  13179. return this.tag === 'Stream';
  13180. }
  13181. isGenericDict() {
  13182. return this.tag === 'GenericDict';
  13183. }
  13184. isEnum() {
  13185. return this.tag === 'Enum';
  13186. }
  13187. toEnumHolder() {
  13188. return this.value;
  13189. }
  13190. isTuple() {
  13191. return this.tag === 'Tuple';
  13192. }
  13193. toTupleRef() {
  13194. return this.value;
  13195. }
  13196. isCustomClass() {
  13197. return torch._C.isCustomClass(this);
  13198. }
  13199. equals(rhs) {
  13200. switch (this.tag) {
  13201. case 'None': return rhs.isNone();
  13202. case 'Bool': return rhs.isBool() && this.toBool() === rhs.toBool();
  13203. case 'Int': return rhs.isInt() && this.toInt() === rhs.toInt();
  13204. case 'Double': return rhs.isDouble() && this.toDouble() === rhs.toDouble();
  13205. case 'String': return rhs.isString() && this.toString() === rhs.toString();
  13206. case 'Tensor': return rhs.isTensor() && this.toTensor() === rhs.toTensor();
  13207. case 'Object': return rhs.isObject() && this.toObject() === rhs.toObject();
  13208. case 'Device': return rhs.isObject() && this.toDevice() === rhs.toDevice();
  13209. case 'GenericList': {
  13210. if (rhs.isList()) {
  13211. const a = this.toList();
  13212. const b = rhs.toList();
  13213. return (a.length === b.length) && a.every((v, i) => v === b[i]);
  13214. }
  13215. return false;
  13216. }
  13217. default: throw new python.Error(`IValue.equals() not implemented for '${this.tag}.`);
  13218. }
  13219. }
  13220. is(rhs) {
  13221. return this.equals(rhs);
  13222. }
  13223. type() {
  13224. switch (this.tag) {
  13225. case 'None': return torch.NoneType.get();
  13226. case 'Bool': return torch.BoolType.get();
  13227. case 'Int': return torch.IntType.get();
  13228. case 'Double': return torch.FloatType.get();
  13229. case 'String': return torch.StringType.get();
  13230. case 'Device': return torch.DeviceObjType.get();
  13231. case 'Tuple': return torch.TupleType.create(this.value.elements().map((ivalue) => ivalue.type()));
  13232. case 'Enum': return this.toEnumHolder().type();
  13233. case 'GenericList': return torch.ListType.create(this.toList().elementType());
  13234. default: throw new python.Error(`IValue.type('${this.tag}') not implemented.`);
  13235. }
  13236. }
  13237. });
  13238. this.registerFunction('torch._C.indent', (out, level) => {
  13239. for (let i = 0; i < level; i++) {
  13240. out.write(' ');
  13241. }
  13242. return out;
  13243. });
  13244. this.registerFunction('torch._C.printValueRef', (out, n) => {
  13245. out.write(`%${n.debugName()}`);
  13246. });
  13247. this.registerFunction('torch._C.printValueRefs', (out, nodes) => {
  13248. for (let i = 0; i < nodes.length; i++) {
  13249. const n = nodes[i];
  13250. if (i > 0) {
  13251. out.write(', ');
  13252. }
  13253. torch._C.printValueRef(out, n);
  13254. }
  13255. return out;
  13256. });
  13257. this.registerFunction('torch._C.const_value_list_with_types', (out, values, delim) => {
  13258. for (let i = 0; i < values.length; i++) {
  13259. const n = values[i];
  13260. if (i > 0) {
  13261. out.write(delim);
  13262. }
  13263. torch._C.printValueRef(out, n);
  13264. out.write(' : ');
  13265. out.write(n.type().str());
  13266. }
  13267. });
  13268. this.register('torch.jit._script');
  13269. this.register('torch.jit._trace');
  13270. this.registerType('torch._C.Parser', class {
  13271. constructor(source) {
  13272. this.L = source;
  13273. }
  13274. parse() {
  13275. const p = ast.parse(this.L.text_str(), this.L.filename());
  13276. return p;
  13277. }
  13278. parseExp() {
  13279. const expr = ast.parse(this.L.text_str());
  13280. return expr.body[0].value;
  13281. }
  13282. });
  13283. this.registerType('torch._C.StringCordView', class {
  13284. });
  13285. this.registerType('torch._C.Source', class {
  13286. constructor(text_view, filename, starting_line_no, gen_ranges /*, copies_str */) {
  13287. if (text_view instanceof Uint8Array) {
  13288. const decoder = new TextDecoder('utf-8');
  13289. this._text_view = decoder.decode(text_view);
  13290. } else if (typeof text_view === 'string') {
  13291. this._text_view = text_view;
  13292. } else {
  13293. throw new python.Error('Invalid text view.');
  13294. }
  13295. this._filename = filename;
  13296. this._starting_line_no = starting_line_no;
  13297. this._gen_ranges = gen_ranges;
  13298. this.calc_line_start_offsets();
  13299. }
  13300. text_str() {
  13301. return this._text_view;
  13302. }
  13303. size() {
  13304. return this._text_view.length;
  13305. }
  13306. filename() {
  13307. return this._filename;
  13308. }
  13309. calc_line_start_offsets() {
  13310. let pos = 0;
  13311. this._line_starting_offsets = [0];
  13312. while ((pos = this._text_view.indexOf('\n', pos)) !== -1) {
  13313. pos += 1;
  13314. this._line_starting_offsets.push(pos);
  13315. }
  13316. }
  13317. offset_for_line(line) {
  13318. return this._line_starting_offsets[line];
  13319. }
  13320. lineno_for_offset(offset) {
  13321. const iter = this._line_starting_offsets.findIndex((value) => value > offset);
  13322. return (iter === -1 ? this._line_starting_offsets.length : iter) - 1;
  13323. }
  13324. lineno_to_source_lineno(lineno) {
  13325. if (this._filename) {
  13326. return lineno + this._starting_line_no;
  13327. }
  13328. return lineno;
  13329. }
  13330. findSourceRangeThatGenerated(range) {
  13331. if (!this._gen_ranges) {
  13332. return null;
  13333. }
  13334. return this._gen_ranges.findSourceRangeThatGenerated(range);
  13335. }
  13336. });
  13337. this.registerType('torch._C.SourceRange', class {
  13338. constructor(...args) {
  13339. if (args.length === 0) {
  13340. this._source_view = null;
  13341. } else if (args.length === 2) {
  13342. let node = null;
  13343. [this._source_view, node] = args;
  13344. this._start = this._source_view.offset_for_line(node.lineno - 1) + (node.col_offset - 1);
  13345. this._end = this._source_view.offset_for_line(node.end_lineno - 1) + (node.end_col_offset - 1);
  13346. } else if (args.length === 3) {
  13347. [this._source_view, this._start, this._end] = args;
  13348. } else {
  13349. throw new python.Error('Not implemented.');
  13350. }
  13351. }
  13352. source() {
  13353. return this._source_view;
  13354. }
  13355. file_line_col() {
  13356. if (!this._source_view || this.source().filename() === null) {
  13357. return null;
  13358. }
  13359. const lineno = this._source_view.lineno_for_offset(this._start);
  13360. const col_offset = this._start - this._source_view.offset_for_line(lineno);
  13361. return [this._source_view.filename(), this._source_view.lineno_to_source_lineno(lineno), col_offset];
  13362. }
  13363. start() {
  13364. return this._start;
  13365. }
  13366. toString() {
  13367. const loc = this.file_line_col();
  13368. return loc ? `${loc[0]}:${loc[1]}:${loc[2]}` : '';
  13369. }
  13370. });
  13371. this.registerType('torch._C.QualifiedName', class {
  13372. constructor(...args) {
  13373. let name = null;
  13374. if (args.length === 1 && typeof args[0] === 'string') {
  13375. [name] = args;
  13376. } else if (args.length === 1 && Array.isArray(args[0]) && args[0].every((arg) => typeof arg === 'string')) {
  13377. name = args[0].join('.');
  13378. } else {
  13379. name = `${args[0].qualifiedName()}.${args[1]}`;
  13380. }
  13381. const index = name.lastIndexOf('.');
  13382. this._qualifiedName = name;
  13383. this._prefix = index === -1 ? '' : name.substring(0, index);
  13384. this._name = index === -1 ? name : name.substring(index + 1);
  13385. }
  13386. qualifiedName() {
  13387. return this._qualifiedName; // "foo.bar.baz"
  13388. }
  13389. prefix() {
  13390. return this._prefix; // "foo.bar"
  13391. }
  13392. name() {
  13393. return this._name; // "baz"
  13394. }
  13395. atoms() {
  13396. return this._qualifiedName.split('.');
  13397. }
  13398. });
  13399. this.registerType('torch._C.Resolver', class {
  13400. resolveValue() {
  13401. throw new python.Error('Not implemented.');
  13402. }
  13403. resolveType() {
  13404. throw new python.Error('Not implemented.');
  13405. }
  13406. });
  13407. this.registerFunction('torch._C.registerCustomClass', (class_type) => {
  13408. torch._C.customClasses = torch._C.customClasses || new Map();
  13409. torch._C.TORCH_INTERNAL_ASSERT(class_type.name());
  13410. const name = class_type.name().qualifiedName();
  13411. torch._C.TORCH_CHECK(!torch._C.customClasses.has(name));
  13412. torch._C.customClasses.set(name, class_type);
  13413. });
  13414. this.registerFunction('torch._C.getCustomClass', (class_name) => {
  13415. torch._C.customClasses = torch._C.customClasses || new Map();
  13416. const ret = torch._C.customClasses.has(class_name) ? torch._C.customClasses.get(class_name) : null;
  13417. return ret;
  13418. });
  13419. this.registerFunction('torch._C.isCustomClass', (v) => {
  13420. return v.isObject() && v.toObject().type().name() && torch._C.getCustomClass(v.toObject().type().name().qualifiedName());
  13421. });
  13422. this.registerType('torch._C.SourceImporter', class extends torch._C.Resolver {
  13423. constructor(cu, constant_table, source_loader, version) {
  13424. super();
  13425. this._cu = cu;
  13426. this._constant_table = constant_table;
  13427. this._source_loader = source_loader;
  13428. this._version = version;
  13429. this._loaded_sources = new Set();
  13430. this._sources = new Map();
  13431. const sources = this._sources;
  13432. ast.AST.prototype.range = function() {
  13433. if (!this._range) {
  13434. if (sources.has(this.filename)) {
  13435. const source_view = sources.get(this.filename);
  13436. this._range = new torch._C.SourceRange(source_view, this);
  13437. } else {
  13438. this._range = new torch._C.SourceRange();
  13439. }
  13440. }
  13441. return this._range;
  13442. };
  13443. this._to_be_defined = new Map();
  13444. this._env = new Map([
  13445. ['torch', new torch._C.BuiltinModule('aten', version)],
  13446. ['ops', new torch._C.OpsValue(version)],
  13447. ['CONSTANTS', new torch._C.ConstantTableValue(constant_table)],
  13448. ['fork', torch._C.SpecialFormValue.create('prim::fork')],
  13449. ['awaitable', torch._C.SpecialFormValue.create('prim::awaitable')],
  13450. ['annotate', torch._C.SpecialFormValue.create('prim::annotate')],
  13451. ['unchecked_cast', torch._C.SpecialFormValue.create('prim::unchecked_cast')],
  13452. ['uninitialized', torch._C.SpecialFormValue.create('prim::Uninitialized')],
  13453. ]);
  13454. }
  13455. loadType(name) {
  13456. const type_parser = new torch._C.ScriptTypeParser(this);
  13457. return type_parser.parseType(name.qualifiedName());
  13458. }
  13459. resolveType(name) {
  13460. name = new torch._C.QualifiedName(name);
  13461. return this.findNamedType(name);
  13462. }
  13463. resolveValue(name, m, loc) {
  13464. if (this._env.has(name)) {
  13465. return this._env.get(name);
  13466. }
  13467. const graph = m.graph();
  13468. switch (name) {
  13469. case 'inf': return new torch._C.SimpleValue(graph.insertConstant(Infinity /* 'std::numeric_limits<double>::infinity()' */, loc));
  13470. case 'nan': return new torch._C.SimpleValue(graph.insertConstant(NaN /* 'std::numeric_limits<double>::quiet_NaN()' */, loc));
  13471. case 'infj': return new torch._C.SimpleValue(graph.insertConstant('c10::complex<double>(0, std::numeric_limits<double>::infinity())', loc));
  13472. case 'nanj': return new torch._C.SimpleValue(graph.insertConstant('c10::complex<double>(0, std::numeric_limits<double>::quiet_NaN()', loc));
  13473. case '__torch__': return new torch._C.ClassNamespaceValue(new torch._C.QualifiedName(name), this);
  13474. default: return null;
  13475. }
  13476. }
  13477. findNamedType(name) {
  13478. const custom_class = torch._C.getCustomClass(name.qualifiedName());
  13479. if (custom_class) {
  13480. return custom_class;
  13481. }
  13482. this.parseSourceIfNeeded(name.prefix());
  13483. const key = name.qualifiedName();
  13484. const it = this._to_be_defined.get(key);
  13485. if (it && it instanceof ast.ClassDef) {
  13486. this._to_be_defined.delete(key);
  13487. this.importNamedType(name.prefix(), it);
  13488. }
  13489. return this._cu.get_type(name);
  13490. }
  13491. importNamedType(qualifier, class_def) {
  13492. const qualified_name = new torch._C.QualifiedName(`${qualifier}.${class_def.name}`);
  13493. if (class_def.bases.length === 0) {
  13494. this.importClass(qualified_name, class_def, false);
  13495. return;
  13496. }
  13497. const superclass_name = class_def.bases[0].id;
  13498. if (superclass_name === 'Module') {
  13499. this.importClass(qualified_name, class_def, true);
  13500. } else if (superclass_name === 'NamedTuple') {
  13501. this.importNamedTuple(qualified_name, class_def);
  13502. } else if (superclass_name === 'Interface') {
  13503. // this._cu.define_interface(qualified_name, class_def, shared_from_this(), is_module=false);
  13504. } else if (superclass_name === 'ModuleInterface') {
  13505. // this._cu.define_interface(qualified_name, class_def, shared_from_this(), is_module=true);
  13506. } else if (superclass_name === 'Enum') {
  13507. this.importEnum(qualified_name, class_def);
  13508. } else {
  13509. throw new python.Error('TorchScript does not support class inheritance.');
  13510. }
  13511. }
  13512. importClass(qualified_classname, class_def, is_module) {
  13513. if (qualified_classname.prefix().startsWith('__torch__.torch.classes')) {
  13514. return;
  13515. }
  13516. const parameter_names = new Set();
  13517. const buffer_names = new Set();
  13518. const methods = [];
  13519. const method_resolvers = [];
  13520. const attributes = [];
  13521. const constants = [];
  13522. const pre_hook_names = new Set();
  13523. const pre_hook_def_map = new Map();
  13524. const hook_names = new Set();
  13525. const hook_def_map = new Map();
  13526. const class_type = torch.ClassType.create(qualified_classname.qualifiedName(), this._cu, is_module);
  13527. for (const stmt of class_def.body) {
  13528. if (stmt instanceof ast.Assign || stmt instanceof ast.AnnAssign) {
  13529. let target = null;
  13530. let annotation = null;
  13531. let value = null;
  13532. if (stmt instanceof ast.Assign) {
  13533. [target] = stmt.targets;
  13534. value = stmt.value;
  13535. } else {
  13536. target = stmt.target;
  13537. annotation = stmt.annotation;
  13538. value = stmt.value;
  13539. }
  13540. if (target instanceof ast.Name) {
  13541. const name = this._cu.execution.identifier(target);
  13542. switch (name) {
  13543. case '__annotations__': {
  13544. continue;
  13545. }
  13546. case '__parameters__': {
  13547. for (const elt of value.elts) {
  13548. parameter_names.add(elt.value);
  13549. }
  13550. break;
  13551. }
  13552. case '__buffers__': {
  13553. for (const elt of value.elts) {
  13554. buffer_names.add(elt.value);
  13555. }
  13556. break;
  13557. }
  13558. case '__forward_pre_hooks__': {
  13559. for (const elt of value.elts) {
  13560. pre_hook_names.add(elt.value);
  13561. }
  13562. break;
  13563. }
  13564. case '__forward_hooks__': {
  13565. for (const elt of value.elts) {
  13566. hook_names.add(elt.value);
  13567. }
  13568. break;
  13569. }
  13570. default: {
  13571. const fixed_up = this.attributeAssignmentSpecialHandlingHack(qualified_classname, stmt);
  13572. if (fixed_up) {
  13573. attributes.push({ name: fixed_up.target.id, value: fixed_up.value, annotation: fixed_up.annotation });
  13574. } else if (value) {
  13575. constants.push({ name, value, annotation });
  13576. } else {
  13577. attributes.push({ name, value, annotation });
  13578. }
  13579. break;
  13580. }
  13581. }
  13582. } else if (target instanceof ast.Subscript && target.value instanceof ast.Name && target.value.id === '__annotations__') {
  13583. const name = target.slice.value;
  13584. attributes.push({ name, value, annotation: stmt.value });
  13585. continue;
  13586. } else {
  13587. throw new python.Error('Unexpected statement kind in module metadata.');
  13588. }
  13589. } else if (stmt instanceof ast.FunctionDef) {
  13590. const def = stmt;
  13591. const def_name = def.name;
  13592. if (pre_hook_names.has(def_name)) {
  13593. pre_hook_def_map.set(def_name, def);
  13594. } else if (hook_names.has(def_name)) {
  13595. hook_def_map.set(def_name, def);
  13596. } else {
  13597. methods.push(def);
  13598. method_resolvers.push(this);
  13599. }
  13600. } else {
  13601. throw new python.Error('Unexpected statement kind in class body.');
  13602. }
  13603. }
  13604. const type_parser = new torch._C.ScriptTypeParser(this);
  13605. for (const assign of attributes) {
  13606. const name = assign.name;
  13607. const annotation = type_parser.parseTypeFromExpr(assign.annotation);
  13608. const is_parameter = parameter_names.has(name);
  13609. const is_buffer = buffer_names.has(name);
  13610. class_type.addAttribute(name, annotation, is_parameter, is_buffer);
  13611. }
  13612. for (const constant of constants) {
  13613. class_type.addConstant(constant.name, constant.value);
  13614. }
  13615. this._cu.register_type(class_type);
  13616. const self = new torch._C.SimpleSelf(class_type);
  13617. this._cu.define(qualified_classname, [], [], methods, method_resolvers, self, false, this._version);
  13618. }
  13619. importEnum(qualified_name, enum_def) {
  13620. const names_values = [];
  13621. let value_type = null;
  13622. const set_or_check_type = (t) => {
  13623. if (!value_type) {
  13624. value_type = t;
  13625. } else if (value_type !== t) {
  13626. throw new python.Error('Enum class with varying value types are not supported.');
  13627. }
  13628. };
  13629. for (const stmt of enum_def.body) {
  13630. if (stmt instanceof ast.Assign === false) {
  13631. throw new python.Error('Unexpected statement in Enum class body.');
  13632. }
  13633. const assign = stmt;
  13634. const name = assign.targets[0].id;
  13635. let ivalue = null;
  13636. const rhs = assign.value;
  13637. switch (rhs.type) {
  13638. case 'str':
  13639. ivalue = new torch._C.IValue(rhs.value, 'String');
  13640. set_or_check_type(torch.StringType.get());
  13641. break;
  13642. case 'int':
  13643. ivalue = new torch._C.IValue(rhs.value, 'Int');
  13644. set_or_check_type(torch.IntType.get());
  13645. break;
  13646. case 'float':
  13647. ivalue = new torch._C.IValue(rhs.value, 'Double');
  13648. set_or_check_type(torch.FloatType.get());
  13649. break;
  13650. default:
  13651. throw new python.Error(`Unsupported enum value type '${rhs.type}'.`);
  13652. }
  13653. names_values.push([name, ivalue]);
  13654. }
  13655. if (!value_type) {
  13656. throw new python.Error('No enum values defined.');
  13657. }
  13658. const enum_type = torch.EnumType.create(qualified_name, value_type, names_values, this._cu);
  13659. this._cu.register_type(enum_type);
  13660. }
  13661. importNamedTuple(qualified_name, named_tuple_def) {
  13662. const type_parser = new torch._C.ScriptTypeParser(this);
  13663. const field_names = [];
  13664. const field_types = [];
  13665. const field_defaults = [];
  13666. for (const stmt of named_tuple_def.body) {
  13667. if (stmt instanceof ast.AnnAssign === false) {
  13668. throw new python.Error('Unexpected statement in NamedTuple body.');
  13669. }
  13670. const assign = stmt;
  13671. const target = this._cu.execution.identifier(stmt.target);
  13672. // const annotation = this._cu.execution.type(stmt.annotation);
  13673. const type = type_parser.parseTypeFromExpr(assign.annotation);
  13674. field_names.push(target);
  13675. // field_types.push(annotation);
  13676. field_types.push(type);
  13677. }
  13678. const tt = torch.TupleType.createNamed(qualified_name.qualifiedName(), field_names, field_types, field_defaults);
  13679. this._cu.register_type(tt);
  13680. }
  13681. importFunction(qualifier, def) {
  13682. const definitions = [def];
  13683. const resolvers = [this];
  13684. this._cu.define(new torch._C.QualifiedName(qualifier), /*properties=*/[], /*propResolvers=*/[], definitions, resolvers, null);
  13685. }
  13686. parseSourceIfNeeded(qualifier) {
  13687. if (!qualifier || this._loaded_sources.has(qualifier)) {
  13688. return;
  13689. }
  13690. this._loaded_sources.add(qualifier);
  13691. const src = this._source_loader(qualifier);
  13692. if (!src) {
  13693. return;
  13694. }
  13695. this._sources.set(src.filename(), src);
  13696. const p = new torch._C.Parser(src);
  13697. const L = p.parse();
  13698. this.parsePossibleVersionNumber(p);
  13699. for (const stmt of L.body) {
  13700. if (stmt instanceof ast.ClassDef) {
  13701. const name = `${qualifier}.${stmt.name}`;
  13702. this._to_be_defined.set(name, stmt);
  13703. } else if (stmt instanceof ast.FunctionDef) {
  13704. const name = `${qualifier}.${stmt.name}`;
  13705. this._to_be_defined.set(name, stmt);
  13706. }
  13707. }
  13708. }
  13709. parsePossibleVersionNumber(/* p */) {
  13710. }
  13711. parseImports(/* p */) {
  13712. }
  13713. attributeAssignmentSpecialHandlingHack(qualified_classname, assign) {
  13714. const replacements = new Map([
  13715. ['__torch__.torch.ao.nn.quantized.modules.linear.LinearPackedParams', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  13716. ['__torch__.torch.ao.nn.quantized.modules.linear.Linear', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  13717. ['__torch__.torch.ao.nn.quantized.dynamic.modules.linear.Linear', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  13718. ['__torch__.torch.ao.nn.quantized.modules.conv.Conv2d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv2dPackedParamsBase']],
  13719. ['__torch__.torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv2dPackedParamsBase']],
  13720. ['__torch__.torch.ao.nn.quantized.modules.conv.Conv3d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv3dPackedParamsBase']],
  13721. ['__torch__.torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU3d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv3dPackedParamsBase']],
  13722. ['__torch__.torch.nn.quantized.modules.linear.LinearPackedParams', ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]],
  13723. ["__torch__.torch.nn.quantized.modules.linear.Linear", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]],
  13724. ["__torch__.torch.nn.quantized.modules.conv.Conv2d", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.Conv2dPackedParamsBase"]],
  13725. ["__torch__.torch.nn.quantized.modules.conv.Conv3d", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.Conv3dPackedParamsBase"]],
  13726. ["__torch__.torch.nn.quantized.dynamic.modules.linear.Linear", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]]
  13727. ]);
  13728. const mangleRe = /\.___torch_mangle_\d+/g;
  13729. const demangled_classname = qualified_classname.qualifiedName().replace(mangleRe, '');
  13730. if (replacements.has(demangled_classname)) {
  13731. const lhs = assign.target;
  13732. if (!assign.annotation || assign.annotation instanceof ast.Name === false) {
  13733. return null;
  13734. }
  13735. const type = assign.annotation.id;
  13736. const [attr_name, expected_type, replacement_type] = replacements.get(demangled_classname);
  13737. if (lhs.id === attr_name && type === expected_type) {
  13738. const p = new torch._C.Parser(new torch._C.Source(replacement_type));
  13739. const typename_expr = p.parseExp();
  13740. return new ast.AnnAssign(lhs, typename_expr, assign.value, lhs instanceof ast.Name);
  13741. }
  13742. }
  13743. return null;
  13744. }
  13745. LEGACY_import_methods(mod, src) {
  13746. const self = new torch._C.SimpleSelf(mod.type());
  13747. const prefix = mod.type().name();
  13748. const p = new torch._C.Parser(src);
  13749. const L = p.parse();
  13750. this.parsePossibleVersionNumber(L);
  13751. this.parseImports(L);
  13752. const definitions = [];
  13753. const resolvers = [];
  13754. for (const def of L.body) {
  13755. if (def instanceof ast.FunctionDef) {
  13756. definitions.push(def);
  13757. resolvers.push(this);
  13758. }
  13759. }
  13760. this._cu.define(prefix, /*properties=*/[], /*propResolvers=*/[], definitions, resolvers, self);
  13761. }
  13762. findFunction(name) {
  13763. this.parseSourceIfNeeded(name.prefix());
  13764. const key = name.qualifiedName();
  13765. const it = this._to_be_defined.get(key);
  13766. if (it && it instanceof ast.FunctionDef) {
  13767. this._to_be_defined.delete(key);
  13768. this.importFunction(name.prefix(), it);
  13769. }
  13770. return this._cu.find_function(name);
  13771. }
  13772. });
  13773. this.registerType('torch._C.FunctionResolver', class extends torch._C.Resolver {
  13774. constructor(otherResolver, functionTable) {
  13775. super();
  13776. this._otherResolver = otherResolver;
  13777. this._functionTable = functionTable;
  13778. }
  13779. resolveValue(name, m, loc) {
  13780. const it = this._functionTable.get(name);
  13781. if (it) {
  13782. return new torch._C.FunctionValue(it);
  13783. }
  13784. return this._otherResolver.resolveValue(name, m, loc);
  13785. }
  13786. resolveType(name, loc) {
  13787. return this._otherResolver.resolveType(name, loc);
  13788. }
  13789. });
  13790. this.registerType('torch._C.SourceRangeDeserializer', class {
  13791. constructor(text_table) {
  13792. this.cached_sources = new Map();
  13793. this._text_table = text_table || [];
  13794. }
  13795. deserialize(iv) {
  13796. torch._C.TORCH_INTERNAL_ASSERT(iv.length === 3);
  13797. const [file, start, end] = iv;
  13798. const source = this.deserialize_source(file);
  13799. return new torch._C.SourceRange(source, start, end);
  13800. }
  13801. deserialize_source(iv) {
  13802. const tup = iv;
  13803. if (this.cached_sources.has(tup)) {
  13804. return this.cached_sources.get(tup);
  13805. }
  13806. let source = null;
  13807. const tup_elems = tup;
  13808. torch._C.TORCH_INTERNAL_ASSERT(tup_elems.length === 3);
  13809. if (this._text_table.length > 0) {
  13810. const [textIndex, fnameIndex, starting_line_no] = tup_elems;
  13811. torch._C.TORCH_CHECK(fnameIndex < this._text_table.length);
  13812. const filename = this._text_table[fnameIndex];
  13813. const pieces = [];
  13814. const strs = [];
  13815. for (const i of textIndex) {
  13816. pieces.push(this._text_table[i]);
  13817. strs.push(this._text_table[i]);
  13818. }
  13819. // const str_cord = new torch._C.StringCordView(pieces, strs);
  13820. source = new torch._C.Source(pieces.join(''), filename, starting_line_no);
  13821. } else {
  13822. const [text, filename, starting_line_no] = tup_elems;
  13823. source = new torch._C.Source(text, filename, starting_line_no);
  13824. }
  13825. this.cached_sources.set(tup, source);
  13826. return source;
  13827. }
  13828. });
  13829. this.registerType('torch._C.SourceRangeUnpickler', class {
  13830. });
  13831. this.registerType('torch._C.ConcreteSourceRangeUnpickler', class extends torch._C.SourceRangeUnpickler {
  13832. constructor (data) {
  13833. super();
  13834. this.data = data;
  13835. this.deserializer = null;
  13836. this.unpickled_records = null;
  13837. }
  13838. unpickle() {
  13839. if (this.unpickled_records) {
  13840. return;
  13841. }
  13842. const unpickler = new pickle.Unpickler(this.data);
  13843. const ivalues = unpickler.load();
  13844. torch._C.TORCH_CHECK(ivalues.length > 0);
  13845. this.unpickled_records = [];
  13846. let lines = null;
  13847. if (ivalues[0] === 'FORMAT_WITH_STRING_TABLE') {
  13848. this.deserializer = new torch._C.SourceRangeDeserializer(ivalues[1]);
  13849. lines = ivalues[2];
  13850. } else {
  13851. this.deserializer = new torch._C.SourceRangeDeserializer();
  13852. lines = ivalues;
  13853. }
  13854. for (const tup_elems of lines) {
  13855. const [offset, range] = tup_elems;
  13856. const source_range = this.deserializer.deserialize(range);
  13857. this.unpickled_records.push([offset, source_range]);
  13858. }
  13859. }
  13860. findSourceRangeThatGenerated(range) {
  13861. this.unpickle();
  13862. const start = range.start();
  13863. const records = this.unpickled_records;
  13864. for (let i = 0; i < records.length; i++) {
  13865. const [offset, target] = records[i];
  13866. const next = i < records.length - 1 ? records[i + 1][0] : range.source().size();
  13867. if (start >= offset && start < next) {
  13868. return target;
  13869. }
  13870. }
  13871. return null;
  13872. }
  13873. });
  13874. this.registerFunction('torch._C.qualifierToArchivePath', (qualifier, export_prefix) => {
  13875. return `${export_prefix}${qualifier.replace(/\./g, '/')}.py`;
  13876. });
  13877. this.registerFunction('torch._C.findSourceInArchiveFromQualifier', (reader, export_prefix, qualifier) =>{
  13878. const path = torch._C.qualifierToArchivePath(qualifier, export_prefix);
  13879. if (!reader.has_record(path)) {
  13880. return null;
  13881. }
  13882. const stream = reader.get_record(path);
  13883. let gen_ranges = null;
  13884. const debug_file = `${path}.debug_pkl`;
  13885. if (reader.has_record(debug_file)) {
  13886. const debug_stream = reader.get_record(debug_file);
  13887. gen_ranges = new torch._C.ConcreteSourceRangeUnpickler(debug_stream.peek());
  13888. }
  13889. return new torch._C.Source(stream.peek(), path, 1, gen_ranges);
  13890. });
  13891. this.registerType('torch._C.ScriptModuleDeserializer', class {
  13892. constructor(cu, reader, pickle_dir_prefix, tensor_dir_prefix, storage_context) {
  13893. this._compilation_unit = cu;
  13894. this._reader = reader;
  13895. this._storage_context = storage_context;
  13896. this._code_prefix = !pickle_dir_prefix && !tensor_dir_prefix ? 'code/' : '.data/ts_code/code/';
  13897. this._pickle_dir_prefix = pickle_dir_prefix || '';
  13898. this._tensor_dir_prefix = tensor_dir_prefix || '';
  13899. this._constant_table = [];
  13900. const SourceLoader = (qualifier) => {
  13901. return torch._C.findSourceInArchiveFromQualifier(this._reader, this._code_prefix, qualifier);
  13902. };
  13903. this._source_importer = new torch._C.SourceImporter(this._compilation_unit, this._constant_table, SourceLoader, reader.version());
  13904. }
  13905. deserialize() {
  13906. const execution = this._compilation_unit.execution;
  13907. const code_prefix = this._code_prefix;
  13908. for (const name of this._reader.get_all_records()) {
  13909. if (name.startsWith(code_prefix) && name.endsWith('.py')) {
  13910. const file = name.substring(code_prefix.length);
  13911. const stream = this._reader.get_record(name);
  13912. const buffer = stream.peek();
  13913. execution.add(file, buffer);
  13914. }
  13915. }
  13916. const torch = execution.import('torch');
  13917. execution.builtins.torch = torch;
  13918. execution.builtins.Tensor = torch.Tensor;
  13919. execution.builtins.ops = torch.ops;
  13920. execution.builtins.inf = torch.inf;
  13921. execution.builtins.CONSTANTS = {};
  13922. execution._resolver = this._source_importer;
  13923. if (this._reader.has_record('model.json')) {
  13924. return this.LEGACY_deserialize();
  13925. }
  13926. const constants = this.readArchive('constants');
  13927. for (let i = 0; i < constants.length; i++) {
  13928. let val = constants[i];
  13929. if (val && val.__class__ && val.__class__.__module__.startsWith('__torch__.torch.classes.')) {
  13930. const type = this._source_importer.resolveType(`${val.__class__.__module__}.${val.__class__.__name__}`);
  13931. const obj = torch.ScriptObject.create(type);
  13932. obj._ivalue = val;
  13933. val = obj;
  13934. }
  13935. execution.builtins.CONSTANTS[`c${i}`] = val;
  13936. this._constant_table.push(val);
  13937. }
  13938. const obj = this.readArchive('data');
  13939. const convertObject = (obj) => {
  13940. if (obj.__class__) {
  13941. const name = `${obj.__class__.__module__}.${obj.__class__.__name__}`;
  13942. const type = this._source_importer.loadType(new torch._C.QualifiedName(name));
  13943. const module = type.is_module() ? new torch.ScriptModule(type, this._compilation_unit) : new torch.ScriptObject(type);
  13944. for (let i = 0; i < type.numAttributes(); i++) {
  13945. const k = type.getAttributeName(i);
  13946. const t = type.getAttribute(i);
  13947. const v = obj[k];
  13948. if (t instanceof torch.ClassType) {
  13949. module.__setattr__(k, convertObject(v));
  13950. } else {
  13951. if (t instanceof torch.TensorType && v && v.__class__ && v instanceof torch.Tensor === false && v.__class__.__module__ === '__torch__.torch.classes.quantized') {
  13952. const name = `${v.__class__.__module__}.${v.__class__.__name__}`;
  13953. type._attributes[i].type = this._source_importer.resolveType(name);
  13954. }
  13955. module.__setattr__(k, obj[k]);
  13956. }
  13957. }
  13958. for (const [key, value] of Object.entries(Object.getPrototypeOf(obj))) {
  13959. if (value && value.__class__ === builtins.method) {
  13960. module[key] = value;
  13961. }
  13962. }
  13963. return module;
  13964. }
  13965. throw new python.Error('Module class not found.');
  13966. };
  13967. return convertObject(obj);
  13968. }
  13969. LEGACY_deserialize() {
  13970. // https://github.com/pytorch/pytorch/blob/5e69e11d098a2cfccc8a59377c431e9c71cab9a8/torch/csrc/jit/serialization/import_legacy.cpp#L88
  13971. const execution = this._compilation_unit.execution;
  13972. const caffe2 = execution.proto.caffe2;
  13973. const torch = execution.import('torch');
  13974. const stream = this._reader.get_record('model.json');
  13975. const buffer = stream.peek();
  13976. const decoder = new TextDecoder('utf-8');
  13977. const content = decoder.decode(buffer);
  13978. const obj = JSON.parse(content);
  13979. const model = execution.proto.torch.ModelDef.decodeJson(obj);
  13980. const tensorTypeMap = new Map([
  13981. [caffe2.TensorProto.DataType.FLOAT, 'Float'],
  13982. [caffe2.TensorProto.DataType.FLOAT16, 'Half'],
  13983. [caffe2.TensorProto.DataType.DOUBLE, 'Double'],
  13984. [caffe2.TensorProto.DataType.INT8, 'Char'],
  13985. [caffe2.TensorProto.DataType.INT32, 'Int'],
  13986. [caffe2.TensorProto.DataType.INT64, 'Long']
  13987. ]);
  13988. const tensor_table = (model.tensors || []).map((constant) => {
  13989. const key = constant.data.key;
  13990. if (!tensorTypeMap.has(constant.data_type)) {
  13991. throw new python.Error(`Unsupported tensor data type '${constant.data_type}'.`);
  13992. }
  13993. const type = tensorTypeMap.get(constant.data_type);
  13994. const shape = constant.dims ? constant.dims.map((dim) => parseInt(dim, 10)) : null;
  13995. const strides = constant.strides ? constant.strides.map((dim) => parseInt(dim, 10)) : null;
  13996. const storage_type = execution.resolve(`torch.${type}Storage`);
  13997. const size = (shape || []).reduce((a, b) => a * b, 1);
  13998. const offset = parseInt(constant.offset, 10) || 0;
  13999. const storage = new storage_type(size);
  14000. const itemsize = storage.dtype.itemsize();
  14001. const stream = this._reader.get_record(key);
  14002. if (stream) {
  14003. const buffer = stream.peek();
  14004. const length = size * itemsize;
  14005. const data = buffer.slice(offset, offset + length);
  14006. storage._set_cdata(data);
  14007. }
  14008. const tensor = torch._utils._rebuild_tensor(storage, 0, shape, strides);
  14009. tensor.name = key;
  14010. return tensor;
  14011. });
  14012. execution.builtins.CONSTANTS = {};
  14013. for (let i = 0; i < tensor_table.length; i++) {
  14014. execution.builtins.CONSTANTS[`c${i}`] = tensor_table[i];
  14015. }
  14016. const attributes = [];
  14017. if (this._reader.has_record('attributes.pkl')) {
  14018. const stream = this._reader.get_record('attributes.pkl');
  14019. const buffer = stream.peek();
  14020. const unpickler = new pickle.Unpickler(buffer);
  14021. const obj = unpickler.load();
  14022. attributes.push(...obj);
  14023. }
  14024. this._LEGACY_moduleStack = ['__torch__'];
  14025. const module_def = model.main_module;
  14026. for (const tensor of tensor_table) {
  14027. this._constant_table.push(tensor);
  14028. }
  14029. return this.LEGACY_convertModule(module_def);
  14030. }
  14031. LEGACY_convertModule(module_def) {
  14032. const atoms = new torch._C.QualifiedName(module_def.name).atoms();
  14033. const numPushed = atoms.length;
  14034. for (const atom of atoms) {
  14035. const sanitized = /^\d+$/.test(atom) ? `_${atom}` : atom;
  14036. this._LEGACY_moduleStack.push(sanitized);
  14037. }
  14038. const qn = new torch._C.QualifiedName(this._LEGACY_moduleStack);
  14039. const module = new torch.ScriptModule(qn, this._compilation_unit);
  14040. for (const sub_def of module_def.submodules || []) {
  14041. const submodule = this.LEGACY_convertModule(sub_def);
  14042. module.register_module(sub_def.name, submodule);
  14043. }
  14044. for (const param_def of module_def.parameters || []) {
  14045. const tensor = this._constant_table[Number(param_def.tensor_id)];
  14046. if (param_def.isBuffer) {
  14047. module.register_buffer(param_def.name, tensor);
  14048. } else {
  14049. module.register_parameter(param_def.name, tensor, false);
  14050. }
  14051. }
  14052. // const typeParser = new torch._C.ScriptTypeParser(this._source_importer);
  14053. for (const attr_def of module_def.attributes || []) {
  14054. if (module.hasattr(attr_def.name)) {
  14055. continue;
  14056. }
  14057. throw new python.Error('Not implemented.');
  14058. // IValue ivalue;
  14059. // if (attr_def.id() >= 0) {
  14060. // ivalue = LEGACY_pickled_ivalues_.at(attr_def.id());
  14061. // }
  14062. // module.register_attribute(attr_def.name, typeParser.parseType(attr_def.type), ivalue);
  14063. }
  14064. if (module_def.torchscript_arena) {
  14065. const key = module_def.torchscript_arena.key;
  14066. const file = key.substring('code/'.length);
  14067. const name = file.replace(/\.py$/, '').split('/').join('.');
  14068. const code = execution.import(name);
  14069. if (code.forward.__class__ === execution.builtins.function) {
  14070. module.forward = code.forward;
  14071. }
  14072. }
  14073. // let gen_ranges = null;
  14074. if (module_def.torchscript_debug_arena) {
  14075. throw new python.Error('Not implemented.');
  14076. //const [data, size] = reader_->getRecord(module_def.torchscript_debug_arena().key());
  14077. //gen_ranges = std::make_shared<ConcreteSourceRangeUnpickler>(std::move(data), size);
  14078. }
  14079. if (module_def.torchscript_arena) {
  14080. const filename = module_def.torchscript_arena.key;
  14081. const stream = this._reader.get_record(filename);
  14082. const data = stream.peek();
  14083. const src = new torch._C.Source(data, filename);
  14084. this._source_importer.LEGACY_import_methods(module, src);
  14085. }
  14086. if (module_def.get_state_attribute_id) {
  14087. throw new python.Error('Not implemented.');
  14088. // LEGACY_moduleSetState(module, LEGACY_pickled_ivalues_.at(module_def.get_state_attribute_id()));
  14089. }
  14090. /*
  14091. const module_type = module._ivalue().type();
  14092. const N = module_type.numAttributes();
  14093. for (let i = 0; i < N; ++i) {
  14094. const v = module._ivalue().getSlot(i);
  14095. if (module_type.getAttribute(i) instanceof torch.OptionalType === false) {
  14096. torch._C.TORCH_CHECK(!v.isNone());
  14097. }
  14098. }
  14099. */
  14100. for (let i = 0; i < numPushed; i++) {
  14101. this._LEGACY_moduleStack.pop();
  14102. }
  14103. return module;
  14104. }
  14105. readArchive(archive_name) {
  14106. const type_resolver = (qn) => {
  14107. const cls = this._source_importer.loadType(qn);
  14108. return cls;
  14109. };
  14110. const ObjLoaderFunc = (/* type, ivalue */) => {
  14111. };
  14112. return this.readArchiveAndTensors(archive_name, this._pickle_dir_prefix, this._tensor_dir_prefix, type_resolver, ObjLoaderFunc, this._device, this._reader, null, this._storage_context);
  14113. }
  14114. readArchiveAndTensors(archive_name, pickle_prefix, tensor_prefix, type_resolver, obj_loader, device, stream_reader, type_parser, storage_context) {
  14115. const picklename = `${pickle_prefix + archive_name}.pkl`;
  14116. const stream = stream_reader.get_record(picklename);
  14117. if (!stream) {
  14118. throw new python.Error(`File '${picklename}' is not found.`);
  14119. }
  14120. const buffer = stream.peek();
  14121. const tensor_dir_path = tensor_prefix ? tensor_prefix : `${archive_name}/`;
  14122. const read_record = (name) => {
  14123. const stream = stream_reader.get_record(tensor_dir_path + name);
  14124. return stream.length <= 0x40000 ? stream.peek() : stream;
  14125. };
  14126. const execution = this._compilation_unit.execution;
  14127. const pickle = execution.__import__('pickle');
  14128. const Unpickler = class extends pickle.Unpickler {
  14129. find_class(module, name) {
  14130. return super.find_class(module, name);
  14131. }
  14132. };
  14133. const unpickler = new Unpickler(buffer);
  14134. unpickler.persistent_load = (saved_id) => {
  14135. if (saved_id[0] !== 'storage') {
  14136. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  14137. }
  14138. const [, storage_type, key, , size] = saved_id;
  14139. if (storage_context && storage_context.has_storage(key)) {
  14140. return storage_context.get_storage(key);
  14141. }
  14142. const storage = new storage_type(size);
  14143. if (!storage._set_cdata) {
  14144. throw new python.Error(`'${storage_type.__name__}._set_cdata' is not a function.`);
  14145. }
  14146. const storage_ptr = read_record(key);
  14147. storage._set_cdata(storage_ptr);
  14148. if (storage_context) {
  14149. storage_context.add_storage(key);
  14150. }
  14151. return storage;
  14152. };
  14153. return unpickler.load();
  14154. }
  14155. });
  14156. this.registerType('torch._C.WithInsertPoint', class {
  14157. constructor(...args) {
  14158. let n = null;
  14159. if (args.length === 1 && args[0] instanceof torch.Block) {
  14160. const [b] = args;
  14161. n = b.return_node();
  14162. } else if (args.length === 1 && args[0] instanceof torch.Node) {
  14163. [n] = args;
  14164. } else {
  14165. throw new python.Error('Invalid arguments.');
  14166. }
  14167. this._prev = n.owningGraph().insertPoint();
  14168. n.owningGraph().setInsertPoint(n);
  14169. }
  14170. dispose() {
  14171. this._prev.owningGraph().setInsertPoint(this._prev);
  14172. }
  14173. });
  14174. this.registerType('torch._C.Environment', class {
  14175. constructor(method, resolver, b, next) {
  14176. this.method = method;
  14177. this.resolver = resolver;
  14178. this.b = b;
  14179. this.next = next;
  14180. this.value_table = new Map();
  14181. this.type_table = new Map();
  14182. this.error_messages = new Map();
  14183. }
  14184. setVariableTypeError(name, msg) {
  14185. /* eslint-disable consistent-this */
  14186. let runner = this;
  14187. /* eslint-enable consistent-this */
  14188. while (runner.next) {
  14189. runner = runner.next;
  14190. }
  14191. runner.error_messages.set(name, msg);
  14192. }
  14193. insertLoad(name, type) {
  14194. const g = this.b.owningGraph();
  14195. const load = g.insertNode(g.createLoad(name, type));
  14196. if (torch._C.meaningfulName(name)) {
  14197. load.output().setDebugName(name);
  14198. }
  14199. return new torch._C.SimpleValue(load.output());
  14200. }
  14201. insertStore(name, loc, v, type) {
  14202. const g = this.b.owningGraph();
  14203. g.insertNode(g.createStore(name, v)).setSourceRange(loc);
  14204. this.type_table.set(name, type);
  14205. }
  14206. findInThisFrame(name) {
  14207. if (this.value_table.has(name)) {
  14208. return this.value_table.get(name);
  14209. }
  14210. if (this.type_table.has(name)) {
  14211. return this.insertLoad(name, this.type_table.get(name));
  14212. }
  14213. return null;
  14214. }
  14215. findInParentFrame(name) {
  14216. return this.next ? this.next.findInAnyFrame(name) : null;
  14217. }
  14218. setType(name, type) {
  14219. this.type_table.set(name, type);
  14220. }
  14221. findInAnyFrame(name) {
  14222. /* eslint-disable consistent-this */
  14223. const self = this;
  14224. /* eslint-enable consistent-this */
  14225. for (let runner = self; runner; runner = runner.next) {
  14226. const r = runner.findInThisFrame(name);
  14227. if (r) {
  14228. return r;
  14229. }
  14230. }
  14231. return null;
  14232. }
  14233. block() {
  14234. return this.b;
  14235. }
  14236. setVar(loc, name, value) {
  14237. this.setSugaredVar(loc, name, new torch._C.SimpleValue(value), null);
  14238. }
  14239. setSugaredVar(loc, name, value, annotated_type) {
  14240. let as_simple_value = torch._C.asSimple(value);
  14241. if (as_simple_value && !as_simple_value.hasDebugName() && torch._C.meaningfulName(name) && as_simple_value.node().owningBlock() === this.block()) {
  14242. as_simple_value.setDebugName(name);
  14243. }
  14244. const parent = this.findInParentFrame(name);
  14245. if (parent) {
  14246. if (annotated_type) {
  14247. throw new python.Error('Type already defined in an outer block.');
  14248. }
  14249. if (!as_simple_value) {
  14250. throw new python.Error('Only reassignments to first-class values are allowed.');
  14251. }
  14252. const simple_parent = torch._C.asSimple(parent);
  14253. if (!simple_parent) {
  14254. throw new python.Error('Only reassignments to first-class values are allowed.');
  14255. }
  14256. const parent_type = torch._C.unshapedType(simple_parent.type());
  14257. as_simple_value = torch._C.tryConvertToType(loc, this.b.owningGraph(), parent_type, as_simple_value, /*allow_conversions=*/true);
  14258. if (!as_simple_value.type().isSubtypeOf(parent_type)) {
  14259. throw new python.Error('Incompatible types.');
  14260. }
  14261. }
  14262. if (as_simple_value) {
  14263. if (annotated_type && !as_simple_value.type().isSubtypeOf(annotated_type)) {
  14264. throw new python.Error('Invalid type.');
  14265. }
  14266. const value_store_type = annotated_type ? annotated_type : as_simple_value.type();
  14267. this.insertStore(name, loc, as_simple_value, value_store_type);
  14268. } else {
  14269. this.value_table.set(name, value);
  14270. }
  14271. }
  14272. getSugaredVar(ident, range, required) {
  14273. required = required || true;
  14274. let retval = this.findInAnyFrame(ident);
  14275. if (!retval) {
  14276. torch._C.Environment.globals = torch._C.Environment.globals || new Map([
  14277. ['print', new torch._C.PrintValue()],
  14278. ['tuple', torch._C.SpecialFormValue.create('prim::TupleConstruct')],
  14279. ['float', new torch._C.MagicMethod('__float__', new torch._C.CastValue(torch.FloatType.get(), 'aten::Float'))],
  14280. ['int', new torch._C.MagicMethod('__int__', new torch._C.CastValue(torch.IntType.get(), 'aten::Int'))],
  14281. ['bool', new torch._C.MagicMethod('__bool__', new torch._C.CastValue(torch.BoolType.get(), 'aten::Bool'))],
  14282. ['str', new torch._C.MagicMethod('__str__', new torch._C.CastValue(torch.StringType.get(), 'aten::str'))],
  14283. ['getattr', torch._C.SpecialFormValue.create('prim::GetAttr')],
  14284. ['hasattr', torch._C.SpecialFormValue.create('prim::HasAttr')],
  14285. ['isinstance', torch._C.SpecialFormValue.create('prim::isinstance')],
  14286. ['range', torch._C.SpecialFormValue.create('prim::range')],
  14287. ['sorted', new torch._C.BuiltinFunction('aten::sorted', null)],
  14288. ]);
  14289. if (torch._C.Environment.globals.has(ident)) {
  14290. retval = torch._C.Environment.globals.get(ident);
  14291. }
  14292. }
  14293. if (!retval) {
  14294. const type = this.resolver.resolveType(ident, range);
  14295. if (type instanceof torch.TupleType) {
  14296. retval = new torch.jit.NamedTupleConstructor(type);
  14297. }
  14298. }
  14299. if (!retval) {
  14300. retval = this.resolver.resolveValue(ident, this.method, range);
  14301. }
  14302. if (!retval) {
  14303. const type = this.resolver.resolveType(ident, range);
  14304. if (type instanceof torch.ClassType) {
  14305. retval = new torch.jit.ClassValue(type);
  14306. }
  14307. }
  14308. if (!retval && required) {
  14309. throw new python.Error(`The name '${ident}' is not defined.`);
  14310. }
  14311. return retval;
  14312. }
  14313. getVar(ident, range) {
  14314. return this.getSugaredVar(ident, range).asValue(range, this.method);
  14315. }
  14316. definedVariables() {
  14317. return Array.from(this.type_table.keys());
  14318. }
  14319. });
  14320. this.registerType('torch._C.Refinement', class {
  14321. constructor(identifier, type) {
  14322. this._identifier = identifier;
  14323. this._type = type;
  14324. }
  14325. identifier() {
  14326. return this._identifier;
  14327. }
  14328. type() {
  14329. return this._type;
  14330. }
  14331. });
  14332. this.registerType('torch._C.RefinementSet', class {
  14333. constructor(...args) {
  14334. if (args.length === 1 && args[0] instanceof torch._C.Refinement) {
  14335. this._true_refinements = [args[0]];
  14336. this._false_refinements = [];
  14337. } else if (args.length === 2 && args[0] instanceof torch._C.Refinement && args[1] instanceof torch._C.Refinement) {
  14338. this._true_refinements = [args[0]];
  14339. this._false_refinements = [args[1]];
  14340. } else if (args.length === 2 && Array.isArray(args[0]) && Array.isArray(args[1])) {
  14341. [this._true_refinements, this._false_refinements] = args;
  14342. } else {
  14343. throw new python.Error('Not implemented.');
  14344. }
  14345. }
  14346. Not() {
  14347. return new torch._C.RefinementSet(this._false_refinements, this._true_refinements);
  14348. }
  14349. activeRefinements() {
  14350. return this._true_refinements;
  14351. }
  14352. });
  14353. this.registerFunction('torch._C.CondValue', class {
  14354. constructor(...args) {
  14355. if (args.length === 3) {
  14356. [this._value, this._refinements, this._static_if] = args;
  14357. } else if (args.length === 4) {
  14358. const [g, loc, static_value, refinements] = args;
  14359. this._value = g.insertConstant(static_value, loc);
  14360. this._refinements = refinements;
  14361. this._static_if = static_value;
  14362. } else {
  14363. throw new python.Error('Invalid number of arguments.');
  14364. }
  14365. }
  14366. value() {
  14367. return this._value;
  14368. }
  14369. staticIf() {
  14370. return this._static_if;
  14371. }
  14372. refinements() {
  14373. return this._refinements;
  14374. }
  14375. });
  14376. this.registerFunction('torch._C.asSimple', (value) => {
  14377. if (value instanceof torch._C.SimpleValue) {
  14378. return value.getValue();
  14379. }
  14380. return null;
  14381. });
  14382. this.registerFunction('torch._C.isNumber', (str) => {
  14383. return /^[0-9]+$/.test(str);
  14384. });
  14385. this.registerFunction('torch._C.normalizeAttrName', (field) => {
  14386. if (torch._C.isNumber(field)) {
  14387. return `_${field}`;
  14388. }
  14389. return field;
  14390. });
  14391. this.registerFunction('torch._C.meaningfulName', (name) => {
  14392. if (name.length === 0) {
  14393. return false;
  14394. }
  14395. if (name[0] === '$') {
  14396. return false;
  14397. }
  14398. if (name[0] !== '_') {
  14399. return true;
  14400. }
  14401. return !/\d+/.test(name.slice(1));
  14402. });
  14403. this.registerFunction('torch._C.materializeConstant', (val, graph, r, map) => {
  14404. const key = `${val.value}:${val.tag}`;
  14405. const existing_constant = map.get(key);
  14406. if (existing_constant) {
  14407. return existing_constant;
  14408. }
  14409. const guard = new torch._C.WithInsertPoint(graph.block().nodes().front());
  14410. const new_constant = graph.insertConstant(val, r);
  14411. map.set(key, new_constant);
  14412. guard.dispose();
  14413. return new_constant;
  14414. });
  14415. this.registerFunction('torch._C.getFullSchemaName', (schema) => {
  14416. if (schema.overload_name) {
  14417. return `${schema.name}.${schema.overload_name}`;
  14418. }
  14419. return schema.name;
  14420. });
  14421. this.registerFunction('torch._C.insertGraph', (g, callee, inputs, value_map) => {
  14422. const value_map_func = (v) => value_map.get(v);
  14423. torch._C.AT_ASSERT(callee.inputs().length === inputs.length);
  14424. for (let i = 0; i < inputs.length; i++) {
  14425. value_map.set(callee.inputs()[i], inputs[i]);
  14426. }
  14427. for (const node of callee.nodes()) {
  14428. const new_node = g.insertNode(g.createClone(node, value_map_func));
  14429. for (let i = 0; i < node.outputs().length; i++) {
  14430. value_map.set(node.outputs()[i], new_node.outputs()[i]);
  14431. }
  14432. }
  14433. const outputs = [];
  14434. for (const output of callee.outputs()) {
  14435. outputs.push(value_map_func(output));
  14436. }
  14437. return outputs;
  14438. });
  14439. this.registerType('TemplateEnv', class {
  14440. });
  14441. this.registerType('torch._C.BuiltinFunctionRegistry', class {
  14442. constructor() {
  14443. this.state = 'UNINITIALIZED';
  14444. this._builtins_by_name = new Map();
  14445. }
  14446. getAllBuiltinFunctionsFor(name) {
  14447. if (this.state === 'UNINITIALIZED') {
  14448. this.loadBuiltinFunctions();
  14449. this.state = 'INITIALIZED';
  14450. }
  14451. if (!this._builtins_by_name.has(name)) {
  14452. return [];
  14453. }
  14454. return this._builtins_by_name.get(name);
  14455. }
  14456. loadBuiltinFunctions() {
  14457. /*
  14458. for (const scalar of ['float', 'int', 'complex']) {
  14459. const env = new torch.C.TemplateEnv();
  14460. env.s('Scalar', scalar);
  14461. this.loadSource(scalar_operators_source.format(env), 'aten');
  14462. }
  14463. for (const scalar of ['float', 'int']) {
  14464. const env = new torch.C.TemplateEnv();
  14465. env.s('Scalar', scalar);
  14466. loadSource(scalar_operators_no_complex_source.format(env), 'aten');
  14467. }
  14468. using str_pair = std::pair<std::string, std::string>;
  14469. const std::vector<str_pair> name_len = {
  14470. str_pair('single', '1'),
  14471. str_pair('pair', '2'),
  14472. str_pair('triple', '3'),
  14473. str_pair('quadruple', '4'),
  14474. };
  14475. for (const auto scalar : {'float', 'int'}) {
  14476. for (const auto& pair : name_len) {
  14477. const env = new torch.C.TemplateEnv();
  14478. env.s('Scalar', scalar);
  14479. env.s('name', pair.first);
  14480. env.s('Length', pair.second);
  14481. this.loadSource(_ntuple_ops.format(env), 'aten');
  14482. }
  14483. }
  14484. for (auto rhs : {'number', 'Tensor'}) {
  14485. at::jit::TemplateEnv env;
  14486. env.s('Rhs_Type', rhs);
  14487. this.loadSource(floordiv.format(env), 'aten');
  14488. }
  14489. this.loadSource(aten_ops, 'aten');
  14490. this.loadSource(aten_ops_additional, 'aten');
  14491. this.loadSource(tensor_properties, 'prim');
  14492. */
  14493. }
  14494. loadSource(/* source, the_namespace */) {
  14495. }
  14496. });
  14497. this.registerFunction('torch._C.getAllBuiltinFunctionsFor', (name) => {
  14498. torch._C.registry = torch._C.registry || new torch._C.BuiltinFunctionRegistry();
  14499. return torch._C.registry.getAllBuiltinFunctionsFor(name);
  14500. });
  14501. this.registerFunction('torch._C.get_operator_version_map', () => {
  14502. return new Map();
  14503. });
  14504. this.registerFunction('torch._C.varargsCanBeUsedAsList', (schema, arg_index, arg) => {
  14505. const is_last_argument = arg_index + 1 === schema.arguments.length || schema.arguments[arg_index + 1].kwarg_only;
  14506. let arg_type = arg.type;
  14507. if (arg_type instanceof torch._C.DynamicType) {
  14508. arg_type = arg_type.fallback();
  14509. }
  14510. const argument_is_list = arg_type instanceof torch.ListType;
  14511. const typevar_list = argument_is_list && arg_type.getElementType() instanceof torch._C.VarType;
  14512. const arg_is_broadcasting_list = arg.N > 0;
  14513. return is_last_argument && argument_is_list && !arg_is_broadcasting_list && !typevar_list;
  14514. });
  14515. this.registerFunction('torch._C.isBlockListedSchema', (schema) => {
  14516. if ((schema.name === 'aten::view' && schema.overload_name === 'dtype') ||
  14517. (schema.name === 'aten::max' && schema.overload_name === 'unary_out') ||
  14518. (schema.name === 'aten::min' && schema.overload_name === 'unary_out')) {
  14519. return true;
  14520. }
  14521. return false;
  14522. });
  14523. this.registerFunction('torch._C.unwrapOptional', (opt_type) => {
  14524. if (opt_type instanceof torch._C.DynamicType) {
  14525. return torch._C.unwrapOptional(opt_type.fallback());
  14526. }
  14527. if (opt_type instanceof torch.OptionalType) {
  14528. return opt_type.getElementType();
  14529. }
  14530. return opt_type;
  14531. });
  14532. this.registerFunction('torch._C.loadPossibleHistoricOps', (name, version) => {
  14533. const possibleSchemas = [];
  14534. if (version === undefined) {
  14535. return possibleSchemas;
  14536. }
  14537. for (const entry of torch._C.get_operator_version_map()) {
  14538. const old_symbol_name = entry.first;
  14539. const base_name = old_symbol_name.substring(0, old_symbol_name.find('.'));
  14540. if (base_name === name) {
  14541. const possibleUpgrader = torch._C.findUpgrader(entry.second, version.value());
  14542. if (possibleUpgrader.has_value()) {
  14543. possibleSchemas.push_back(possibleUpgrader.value().old_schema);
  14544. }
  14545. }
  14546. }
  14547. return possibleSchemas;
  14548. });
  14549. this.registerFunction('torch._C.isOpCurrentBasedOnUpgraderEntries', (upgraders_for_schema, current_version) => {
  14550. const latest_update = upgraders_for_schema[upgraders_for_schema.length - 1].bumped_at_version;
  14551. return current_version < latest_update;
  14552. });
  14553. this.registerFunction('torch._C.isOpSymbolCurrent', (name, current_version) => {
  14554. const it = torch._C.get_operator_version_map().get(name);
  14555. if (it) {
  14556. return torch._C.isOpCurrentBasedOnUpgraderEntries(it, current_version);
  14557. }
  14558. return true;
  14559. });
  14560. this.registerFunction('torch._C.packOutputs', (g, values, field_names) => {
  14561. if (values.length === 1) {
  14562. return values[0];
  14563. }
  14564. let named_tuple = null;
  14565. if (field_names) {
  14566. const types = values.map((v) => v.type());
  14567. named_tuple = torch.TupleType.createNamed(null, field_names.value(), types);
  14568. }
  14569. return g.insertNode(g.createTuple(values, named_tuple)).output();
  14570. });
  14571. this.registerFunction('torch._C.isIntOrFloatUsedAsList', (value, arg) => {
  14572. const v_type = value.type();
  14573. if (v_type !== torch.FloatType.get() && v_type !== torch.IntType.get()) {
  14574. return false;
  14575. }
  14576. const arg_type = torch._C.unwrapOptional(arg.type);
  14577. return arg_type instanceof torch.ListType && arg_type.getElementType() === v_type && arg.N;
  14578. });
  14579. this.registerFunction('torch._C.convertibleToList', (type, list_type_) => {
  14580. const list_type = list_type_;
  14581. if (list_type instanceof torch.ListType === false) {
  14582. return false;
  14583. }
  14584. if (type.isSubtypeOf(list_type_)) {
  14585. return true;
  14586. }
  14587. if (type instanceof torch.TupleType) {
  14588. return type.elements().every((t) => t.isSubtypeOf(list_type.getElementType()));
  14589. }
  14590. return false;
  14591. });
  14592. this.registerFunction('torch._C.findInputWithName', (name, kwargs, is_aten) => {
  14593. for (let i = 0; i < kwargs.length; i++) {
  14594. if (is_aten && name === 'self' && kwargs[i].name() === 'input') {
  14595. return i;
  14596. }
  14597. if (kwargs[i].name() === name) {
  14598. return i;
  14599. }
  14600. }
  14601. return null;
  14602. });
  14603. this.registerFunction('torch._C.tryCreateList', (elem_type, graph, loc, varargs, failure_messages, err, convert_tensor_to_num, type_env) => {
  14604. const elem_arg = new torch.Argument('<varargs>', elem_type);
  14605. const list_elements = [];
  14606. for (const named_value of varargs) {
  14607. const matched_value = torch._C.tryMatchArgument(/*arg=*/elem_arg, graph, loc, named_value, failure_messages, err, /*allow_conversions=*/convert_tensor_to_num, type_env);
  14608. if (!matched_value) {
  14609. return null;
  14610. }
  14611. list_elements.push(matched_value);
  14612. }
  14613. return graph.insertNode(graph.createList(elem_type, list_elements)).output();
  14614. });
  14615. this.registerType('torch._C.MatchTypeReturn', class {
  14616. constructor(reason) {
  14617. this._reason = reason;
  14618. }
  14619. static Success() {
  14620. return new torch._C.MatchTypeReturn(null);
  14621. }
  14622. success() {
  14623. return this._reason === null;
  14624. }
  14625. });
  14626. this.registerFunction('torch._C.matchTypeVariables', (formal, actual, type_env) => {
  14627. if (!formal.hasFreeVariables()) {
  14628. if (formal instanceof torch._C.DynamicType) {
  14629. return torch._C.matchTypeVariables(formal.fallback(), actual, type_env);
  14630. }
  14631. return torch._C.MatchTypeReturn.Success();
  14632. }
  14633. if (formal instanceof torch._C.VarType) {
  14634. const it = type_env.has(formal.name()) ? type_env.get(formal.name()) : null;
  14635. if (it === null) {
  14636. type_env.set(formal.name(), actual);
  14637. return torch._C.MatchTypeReturn.Success();
  14638. } else if (torch._C.unifyTypes(it, actual)) {
  14639. return torch._C.MatchTypeReturn.Success();
  14640. }
  14641. return new torch._C.MatchTypeReturn('Cannot match var.');
  14642. } else if (formal instanceof torch.ListType) {
  14643. if (actual instanceof torch.ListType) {
  14644. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14645. if (!innerMatch.success()) {
  14646. return innerMatch;
  14647. }
  14648. return torch._C.MatchTypeReturn.Success();
  14649. } else if (actual instanceof torch.TupleType) {
  14650. const maybe_tuple_unified = torch._C.unifyTypeList(actual.elements(), '');
  14651. if (maybe_tuple_unified) {
  14652. return torch._C.matchTypeVariables(formal.getElementType(), maybe_tuple_unified, type_env);
  14653. }
  14654. }
  14655. return new torch._C.MatchTypeReturn('Cannot match list.');
  14656. } else if (formal instanceof torch.TupleType) {
  14657. if (actual instanceof torch.TupleType) {
  14658. if (formal.elements().length !== actual.elements().length) {
  14659. return torch._C.MatchTypeReturn('Cannot match tuples of mismatched size.');
  14660. }
  14661. for (let i = 0; i < formal.elements().length; i++) {
  14662. const result = torch._C.matchTypeVariables(formal.elements()[i], actual.elements()[i], type_env);
  14663. if (!result.success()) {
  14664. return result;
  14665. }
  14666. }
  14667. return torch._C.MatchTypeReturn.Success();
  14668. }
  14669. return new torch._C.MatchTypeReturn('Cannot match tuple.');
  14670. } else if (formal instanceof torch.FutureType) {
  14671. if (actual instanceof torch.FutureType) {
  14672. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14673. if (!innerMatch.success()) {
  14674. return innerMatch;
  14675. }
  14676. return torch._C.MatchTypeReturn.Success();
  14677. }
  14678. return new torch._C.MatchTypeReturn('Cannot match future.');
  14679. } else if (formal instanceof torch.AwaitType) {
  14680. if (actual instanceof torch.AwaitType) {
  14681. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14682. if (!innerMatch.success()) {
  14683. return innerMatch;
  14684. }
  14685. return torch._C.MatchTypeReturn.Success();
  14686. }
  14687. return new torch._C.MatchTypeReturn('Cannot match await.');
  14688. } else if (formal instanceof torch.RRefType) {
  14689. if (actual instanceof torch.RRefType) {
  14690. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14691. if (!innerMatch.success()) {
  14692. return innerMatch;
  14693. }
  14694. return torch._C.MatchTypeReturn.Success();
  14695. }
  14696. return new torch._C.MatchTypeReturn('Cannot match rref.');
  14697. } else if (formal instanceof torch.OptionalType) {
  14698. if (actual instanceof torch.OptionalType) {
  14699. const optionedMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14700. if (!optionedMatch.success()) {
  14701. return optionedMatch;
  14702. }
  14703. } else if (!actual.isSubtypeOf(torch.NoneType.get())) {
  14704. return torch._C.matchTypeVariables(formal.getElementType(), actual, type_env);
  14705. }
  14706. return torch._C.MatchTypeReturn.Success();
  14707. } else if (formal instanceof torch.DictType) {
  14708. if (actual instanceof torch.DictType) {
  14709. const key_match = torch._C.matchTypeVariables(formal.getKeyType(), actual.getKeyType(), type_env);
  14710. if (!key_match.success()) {
  14711. return key_match;
  14712. }
  14713. const value_match = torch._C.matchTypeVariables(formal.getValueType(), actual.getValueType(), type_env);
  14714. if (!value_match.success()) {
  14715. return value_match;
  14716. }
  14717. return torch._C.MatchTypeReturn.Success();
  14718. }
  14719. return new torch._C.MatchTypeReturn('Cannot match dict.');
  14720. }
  14721. throw new python.Error('Unhandled free variable container.');
  14722. });
  14723. this.registerFunction('torch._C.tryMatchArgument', (arg, graph, loc, named_value, failure_messages, err, allow_conversions, type_env) => {
  14724. let value = named_value.value(graph);
  14725. if (torch._C.isIntOrFloatUsedAsList(value, arg)) {
  14726. const repeated = Array(arg.N).fill(value);
  14727. value = graph.insertNode(graph.createList(value.type(), repeated)).output();
  14728. }
  14729. const matched = torch._C.matchTypeVariables(arg.type, value.type(), type_env);
  14730. if (!matched.success()) {
  14731. if (failure_messages) {
  14732. throw new python.Error(`Could not match type ${value.type().repr_str()} to ${arg.type().repr_str()} in argument '${arg.name()}'.`);
  14733. }
  14734. return null;
  14735. }
  14736. const concrete_type = torch._C.tryEvalTypeVariables(arg.type, type_env);
  14737. if (!concrete_type) {
  14738. if (failure_messages) {
  14739. throw new python.Error(`Could not infer type for argument '${arg.name}'.`);
  14740. }
  14741. return null;
  14742. }
  14743. value = torch._C.tryConvertToType(loc, graph, concrete_type, value, allow_conversions);
  14744. if (!value.type().isSubtypeOf(concrete_type)) {
  14745. if (failure_messages) {
  14746. throw new python.Error(`Could not match type in argument '${arg.name()}'.`);
  14747. }
  14748. return null;
  14749. }
  14750. return value;
  14751. });
  14752. this.registerFunction('torch._C.tryConvertToType', (loc, graph, concrete_type, value, allow_conversions) => {
  14753. if (concrete_type instanceof torch.OptionalType) {
  14754. const op = concrete_type;
  14755. if (value.type() instanceof torch.OptionalType === false && !value.type().isSubtypeOf(torch.NoneType.get())) {
  14756. return torch._C.tryConvertToType(loc, graph, op.getElementType(), value, allow_conversions);
  14757. }
  14758. }
  14759. if (value.node().kind() === 'prim::EmptyListLiteral' && concrete_type instanceof torch.ListType) {
  14760. value = graph.insertNode(graph.createList(concrete_type.getElementType(), [])).output();
  14761. }
  14762. if (value.type() instanceof torch.TupleType) {
  14763. const value_tuple = value.type();
  14764. if (torch._C.convertibleToList(value.type(), torch._C.unwrapOptional(concrete_type))) {
  14765. const unpacked = torch._C.createTupleUnpack(value);
  14766. const elem_type = torch._C.unwrapOptional(concrete_type).expect(torch.ListType).getElementType();
  14767. value = graph.insertNode(graph.createList(elem_type, unpacked)).output();
  14768. }
  14769. if (concrete_type instanceof torch.TupleType) {
  14770. const concrete_tuple = concrete_type;
  14771. if (!value_tuple.isSubtypeOf(concrete_tuple) &&
  14772. concrete_tuple.elements().length === value_tuple.elements().length) {
  14773. const unpacked = torch._C.createTupleUnpack(value);
  14774. const converted = [];
  14775. for (let i = 0; i < concrete_tuple.elements().length; i++) {
  14776. converted.push(torch._C.tryConvertToType(loc, graph, concrete_tuple.elements()[i], unpacked[i], allow_conversions));
  14777. }
  14778. value = graph.insertNode(graph.createTuple(converted)).output();
  14779. }
  14780. }
  14781. }
  14782. if (allow_conversions) {
  14783. const value_isa_tensor = value.type().isSubtypeOf(torch.TensorType.get());
  14784. const value_equals_number = value.type() === torch.NumberType.get();
  14785. const concrete_float = concrete_type === torch.FloatType.get();
  14786. const concrete_complex = concrete_type === torch.ComplexType.get();
  14787. const concrete_int = concrete_type === torch.IntType.get();
  14788. const concrete_number = concrete_type === torch.NumberType.get();
  14789. if (value_isa_tensor) {
  14790. if (concrete_float) {
  14791. value = graph.insert('aten::FloatImplicit', [new torch._C.NamedValue(value)], [], loc);
  14792. } else if (concrete_complex) {
  14793. value = graph.insert('aten::ComplexImplicit', [new torch._C.NamedValue(value)], [], loc);
  14794. } else if (concrete_int) {
  14795. value = graph.insert('aten::IntImplicit', [new torch._C.NamedValue(value)], [], loc);
  14796. } else if (concrete_number) {
  14797. value = graph.insert('aten::ScalarImplicit', [new torch._C.NamedValue(value)], [], loc);
  14798. }
  14799. } else if (value_equals_number) {
  14800. if (concrete_float) {
  14801. value = graph.insert('aten::Float', [new torch._C.NamedValue(value)], [], loc);
  14802. } else if (concrete_complex) {
  14803. value = graph.insert('aten::Complex', [new torch._C.NamedValue(value)], [], loc);
  14804. } else if (concrete_int) {
  14805. value = graph.insert('aten::Int', [new torch._C.NamedValue(value)], [], loc);
  14806. }
  14807. } else if (value.type() === torch.BoolType.get()) {
  14808. if (concrete_float) {
  14809. value = graph.insert('aten::Float', [new torch._C.NamedValue(value)], [], loc);
  14810. } else if (concrete_int || concrete_number) {
  14811. value = graph.insert('aten::Int', [new torch._C.NamedValue(value)], [], loc);
  14812. }
  14813. }
  14814. if (value.type().isSubtypeOf(torch.StringType.get()) && concrete_type.isSubtypeOf(torch.DeviceObjType.get())) {
  14815. return graph.insert('aten::device', [new torch._C.NamedValue(value)], [], loc);
  14816. }
  14817. }
  14818. return value;
  14819. });
  14820. this.registerFunction('torch._C.tryEvalTypeVariables', (type, type_env) => {
  14821. if (!type.hasFreeVariables()) {
  14822. if (type instanceof torch._C.DynamicType) {
  14823. return torch._C.tryEvalTypeVariables(type.fallback(), type_env);
  14824. }
  14825. return type;
  14826. }
  14827. if (type instanceof torch._C.VarType) {
  14828. return type_env.get(type.annotation_str);
  14829. }
  14830. const contained = type.containedTypes();
  14831. if (contained.length === 0) {
  14832. return type;
  14833. }
  14834. const new_contained = [];
  14835. for (const t of contained) {
  14836. const r = torch._C.tryEvalTypeVariables(t, type_env);
  14837. if (!r) {
  14838. return null;
  14839. }
  14840. new_contained.push(r);
  14841. }
  14842. return type.withContained(new_contained);
  14843. });
  14844. this.registerFunction('torch._C.tryMatchSchema', (schema, loc, graph, args, kwargs, self, failure_messages, allow_conversions) => {
  14845. if (torch._C.isBlockListedSchema(schema)) {
  14846. return null;
  14847. }
  14848. const err = null;
  14849. const type_env = new Map();
  14850. const positional_inputs = [];
  14851. const used_kwarg = kwargs.map(() => false);
  14852. const is_aten = schema.name.startsWith('aten::');
  14853. let used_args = 0;
  14854. for (let schema_i = 0; schema_i < schema.arguments.length; schema_i++) {
  14855. const arg = schema.arguments[schema_i];
  14856. let actual_named_value = null;
  14857. if (arg.name === 'self' && self) {
  14858. actual_named_value = self;
  14859. self = null;
  14860. } else if (!arg.kwarg_only && used_args < args.length) {
  14861. if (allow_conversions && torch._C.varargsCanBeUsedAsList(schema, schema_i, arg)) {
  14862. const value = args[used_args].value(graph);
  14863. const actual_type = value.type();
  14864. if (actual_type instanceof torch.ListType === false && !torch._C.convertibleToList(actual_type, torch._C.unwrapOptional(arg.type))) {
  14865. const formal_type = torch._C.unwrapOptional(arg.type).expect(torch.ListType).getElementType();
  14866. const list = torch._C.tryCreateList(formal_type, graph, loc, args.slice(used_args), failure_messages, err, allow_conversions, type_env);
  14867. if (!list) {
  14868. return null;
  14869. }
  14870. used_args = args.length;
  14871. positional_inputs.push(list);
  14872. continue;
  14873. }
  14874. }
  14875. actual_named_value = args[used_args];
  14876. used_args++;
  14877. } else {
  14878. const kwarg_idx = torch._C.findInputWithName(arg.name, kwargs, is_aten);
  14879. if (Number.isInteger(kwarg_idx)) {
  14880. const nv = kwargs[kwarg_idx];
  14881. if (used_kwarg[kwarg_idx]) {
  14882. if (failure_messages) {
  14883. throw new python.Error(`Argument '${nv.name()}' specified twice in schema.`);
  14884. }
  14885. return null;
  14886. }
  14887. used_kwarg[kwarg_idx] = true;
  14888. actual_named_value = nv;
  14889. } else if (arg.has_default_value()) {
  14890. actual_named_value = new torch._C.NamedValue(arg.default_value);
  14891. } else {
  14892. if (failure_messages) {
  14893. throw new python.Error(`Argument '${arg.name}' not provided.`);
  14894. }
  14895. return null;
  14896. }
  14897. }
  14898. const positional = torch._C.tryMatchArgument(arg, graph, loc, actual_named_value, failure_messages, err, allow_conversions, type_env);
  14899. if (!positional) {
  14900. return null;
  14901. }
  14902. positional_inputs.push(positional);
  14903. }
  14904. if (self !== null) {
  14905. if (failure_messages) {
  14906. throw new python.Error('Provided self argument not used in schema.');
  14907. }
  14908. return null;
  14909. }
  14910. if (schema.is_vararg) {
  14911. for (; used_args < args.length; used_args++) {
  14912. positional_inputs.push(args[used_args].value(graph));
  14913. }
  14914. }
  14915. if (used_args < args.length) {
  14916. if (failure_messages) {
  14917. throw new python.Error('Too many positional arguments.');
  14918. }
  14919. return null;
  14920. }
  14921. for (let i = 0; i < kwargs.length; i++) {
  14922. const nv = kwargs[i];
  14923. if (!used_kwarg[i]) {
  14924. if (failure_messages) {
  14925. if (schema.argumentIndexWithName(nv.name()) === null) {
  14926. throw new python.Error('Keyword argument unknown.');
  14927. } else {
  14928. throw new python.Error('Keyword argument specified twice.');
  14929. }
  14930. }
  14931. return null;
  14932. }
  14933. }
  14934. const returns = schema.returns;
  14935. const return_types = returns.map((r) => {
  14936. const result = torch._C.tryEvalTypeVariables(r.type, type_env);
  14937. if (!result) {
  14938. throw new python.Error('Unbound type variable.');
  14939. }
  14940. return result;
  14941. });
  14942. const return_has_field_names = returns.every((r) => !r.name);
  14943. let return_field_names = null;
  14944. if (return_has_field_names) {
  14945. return_field_names = returns.map((r) => r.name);
  14946. }
  14947. const schema_name = torch._C.getFullSchemaName(schema);
  14948. return new torch._C.MatchedSchema(positional_inputs, return_types, return_field_names, schema_name);
  14949. });
  14950. this.registerFunction('torch._C.matchSchema', (schema, loc, graph, args, kwargs, self) => {
  14951. self = self || null;
  14952. const result = torch._C.tryMatchSchema(schema, loc, graph, args, kwargs, self, null, true);
  14953. if (result) {
  14954. return result;
  14955. }
  14956. throw new python.Error(`No matching schema '${schema.name}' found.`);
  14957. });
  14958. this.registerFunction('torch._C.matchSchemas', (schemas, loc, graph, args, kwargs, self, render_errors) => {
  14959. self = self || null;
  14960. render_errors = render_errors || false;
  14961. torch._C.TORCH_INTERNAL_ASSERT(schemas.length > 0);
  14962. if (schemas.length === 1) {
  14963. return [0, torch._C.matchSchema(schemas[0], loc, graph, args, kwargs, self)];
  14964. }
  14965. for (const allow_conversions of [false, true]) {
  14966. for (let i = 0; i < schemas.length; i++) {
  14967. const matched_schema = torch._C.tryMatchSchema(schemas[i], loc, graph, args, kwargs, self, null, allow_conversions);
  14968. if (matched_schema) {
  14969. return [i, matched_schema];
  14970. }
  14971. }
  14972. }
  14973. if (!render_errors) {
  14974. return torch._C.matchSchemas(schemas, loc, graph, args, kwargs, self, /*render_errors=*/true);
  14975. }
  14976. throw new python.Error(`No matching schema '${schemas[0].name}' found.`);
  14977. });
  14978. this.registerFunction('torch._C.emitBuiltinCall', (loc, graph, name, args, kwargs, self) => {
  14979. const variants = torch._C.getAllOperatorsFor(name);
  14980. const builtin_functions = torch._C.getAllBuiltinFunctionsFor(name);
  14981. const graph_version = graph.get_op_version();
  14982. const schemas = [];
  14983. const upgrader_schemas = [];
  14984. for (const op of variants) {
  14985. let found_upgrader = false;
  14986. const op_name = torch._C.getFullSchemaName(op.schema());
  14987. if (Number.isInteger(graph_version)) {
  14988. const version_entry = torch._C.get_operator_version_map().get(op_name);
  14989. if (version_entry) {
  14990. const old_schema_entry = torch._C.findUpgrader(version_entry.second, graph_version.value());
  14991. if (old_schema_entry.has_value()) {
  14992. const old_schema = torch._C.parseSchema(old_schema_entry.value().old_schema);
  14993. upgrader_schemas.push(old_schema);
  14994. found_upgrader = true;
  14995. } else if (!torch._C.isOpCurrentBasedOnUpgraderEntries(version_entry.second, graph_version.value())) {
  14996. throw new python.Error('Valid upgrader must be present.');
  14997. }
  14998. }
  14999. }
  15000. if (!found_upgrader) {
  15001. schemas.push(op.schema());
  15002. }
  15003. }
  15004. if (variants.length === 0) {
  15005. const oldSchemas = torch._C.loadPossibleHistoricOps(name, graph_version);
  15006. for (const old_schema_entry of oldSchemas) {
  15007. const old_schema = torch._C.parseSchema(old_schema_entry);
  15008. upgrader_schemas.push(old_schema);
  15009. }
  15010. }
  15011. for (const schema of upgrader_schemas) {
  15012. schemas.push(schema);
  15013. }
  15014. for (const method of builtin_functions) {
  15015. method.ensure_defined();
  15016. schemas.push(method.getSchema());
  15017. }
  15018. if (schemas.length === 0) {
  15019. const inputs = args.map((arg) => arg.value(graph));
  15020. const n = graph.insertNode(graph.create(name, inputs, 0)).setSourceRange(loc);
  15021. n.addOutput().setType(torch.TensorType.get());
  15022. return n.output();
  15023. }
  15024. const matched = torch._C.matchSchemas(schemas, loc, graph, args, kwargs, self);
  15025. if (matched[0] < variants.length + upgrader_schemas.length) {
  15026. return torch._C.emitBuiltinNode(matched[1], loc, graph, name, graph_version);
  15027. }
  15028. const fn = builtin_functions[matched.first - variants.size()];
  15029. return torch._C.insertGraph(graph, torch._C.toGraphFunction(fn).graph(), matched.second.inputs, new Map())[0];
  15030. });
  15031. this.registerFunction('torch._C.emitBuiltinNode', (matched_schema, loc, graph, name, version) => {
  15032. const n = graph.insertNode(graph.create(name, matched_schema.inputs, 0)).setSourceRange(loc);
  15033. for (const ret of matched_schema.return_types) {
  15034. n.addOutput().setType(ret);
  15035. }
  15036. if (!Number.isInteger(version) || torch._C.isOpSymbolCurrent(matched_schema.schema_name, version)) {
  15037. n.getOperation();
  15038. } else {
  15039. n.setHistoricSchemaName(matched_schema.schema_name);
  15040. }
  15041. return torch._C.packOutputs(graph, n.outputs(), matched_schema.return_field_names);
  15042. });
  15043. this.registerFunction('torch._C.unshapedType', (type) => {
  15044. if (type.isSubtypeOf(torch.TensorType.get())) {
  15045. return torch.TensorType.get();
  15046. }
  15047. const contained = type.containedTypes();
  15048. if (contained.length === 0) {
  15049. return type;
  15050. }
  15051. return type.withContained(contained.map((t) => torch._C.unshapedType(t)));
  15052. });
  15053. this.registerFunction('torch._C.unifyTypesImpl', (t1, t2, default_to_union, type_hint) => {
  15054. default_to_union = default_to_union || false;
  15055. type_hint = type_hint || null;
  15056. if (t1.isSubtypeOf(t2)) {
  15057. return t2;
  15058. } else if (t2.isSubtypeOf(t1)) {
  15059. return t1;
  15060. }
  15061. if (t1.kind() === 'TensorType' && t2.kind() === 'TensorType') {
  15062. return t1.merge(t2);
  15063. }
  15064. if (t1.isSubtypeOf(torch.NoneType.get()) && !t2.isSubtypeOf(torch.NoneType.get())) {
  15065. return torch.OptionalType.create(t2);
  15066. } else if (t2.isSubtypeOf(torch.NoneType.get()) && !t1.isSubtypeOf(torch.NoneType.get())) {
  15067. return torch.OptionalType.create(t1);
  15068. }
  15069. if (t1 instanceof torch.OptionalType) {
  15070. const elem = torch._C.unifyTypes(t1.getElementType(), t2);
  15071. if (elem) {
  15072. return torch.OptionalType.create(elem);
  15073. }
  15074. } else if (t2 instanceof torch.OptionalType) {
  15075. const elem = torch._C.unifyTypes(t2.getElementType(), t1);
  15076. if (elem) {
  15077. return torch.OptionalType.create(elem);
  15078. }
  15079. }
  15080. if (t1 instanceof torch.TupleType && t2 instanceof torch.TupleType) {
  15081. if (t1.elements().size() !== t2.elements().size()) {
  15082. return null;
  15083. }
  15084. const elements = [];
  15085. for (let i = 0; i < t1.elements().length; i++) {
  15086. const elem = torch._C.unifyTypes(t1.elements()[i], t2.elements()[i], default_to_union);
  15087. if (elem) {
  15088. elements.push(elem);
  15089. } else {
  15090. return null;
  15091. }
  15092. }
  15093. return torch.TupleType.create(elements);
  15094. }
  15095. if (t1 instanceof torch.FutureType && t2 instanceof torch.FutureType) {
  15096. const elem = torch._C.unifyTypes(t1.getElementType(), t2.getElementType());
  15097. if (elem) {
  15098. return torch.FutureType.create(elem);
  15099. }
  15100. }
  15101. const t1_unshaped = torch._C.unshapedType(t1);
  15102. const t2_unshaped = torch._C.unshapedType(t2);
  15103. if (t1_unshaped.isSubtypeOf(t2_unshaped)) {
  15104. return t2_unshaped;
  15105. } else if (t2_unshaped.isSubtypeOf(t1_unshaped)) {
  15106. return t1_unshaped;
  15107. }
  15108. if (type_hint && t1.isSubtypeOf(type_hint) && t2.isSubtypeOf(type_hint)) {
  15109. return type_hint;
  15110. }
  15111. return null;
  15112. });
  15113. this.registerFunction('torch._C.unifyTypes', (t1, t2, default_to_union, type_hint) => {
  15114. const unified = torch._C.unifyTypesImpl(t1, t2, default_to_union, type_hint);
  15115. if (default_to_union && !unified) {
  15116. return torch.UnionType.create([t1, t2]);
  15117. }
  15118. return unified;
  15119. });
  15120. this.registerFunction('torch._C.unifyTypeList', (elements, why_not, default_to_union, type_hint) => {
  15121. if (elements.length === 0) {
  15122. return null;
  15123. }
  15124. let [ret_type] = elements;
  15125. for (let i = 1; i < elements.length && ret_type; i++) {
  15126. const maybe_unified = torch._C.unifyTypes(ret_type, elements[i], default_to_union, type_hint);
  15127. if (!maybe_unified) {
  15128. return null;
  15129. }
  15130. ret_type = maybe_unified;
  15131. }
  15132. return ret_type;
  15133. });
  15134. this.registerFunction('torch._C.insertableTensor', (ten) => {
  15135. return !ten.requires_grad() && ten.has_storage() && !ten.is_nested();
  15136. });
  15137. this.registerFunction('torch._C.insertableIValue', (ivalue) => {
  15138. if (ivalue.isInt() || ivalue.isNone() || ivalue.isBool() ||
  15139. ivalue.isDouble() || ivalue.isComplexDouble() || ivalue.isString() ||
  15140. ivalue.isDevice() || ivalue.isEnum()) {
  15141. return true;
  15142. }
  15143. if (ivalue.isTensor()) {
  15144. return torch._C.insertableTensor(ivalue.toTensor());
  15145. }
  15146. if (ivalue.isList() || ivalue.isTuple()) {
  15147. let elems = [];
  15148. if (ivalue.isTuple()) {
  15149. elems = ivalue.toTupleRef().elements();
  15150. } else {
  15151. elems = ivalue.toListRef();
  15152. }
  15153. return elems.every((tup_elem) => torch._C.insertableIValue(tup_elem));
  15154. }
  15155. if (ivalue.isGenericDict()) {
  15156. const dict = ivalue.toGenericDict();
  15157. return dict.every((entry) => torch._C.insertableIValue(entry.key()) && torch._C.insertableIValue(entry.value()));
  15158. }
  15159. return false;
  15160. });
  15161. this.registerFunction('torch._C.insertConstant', (g, val, loc, scope) => {
  15162. loc = loc || null;
  15163. scope = scope || null;
  15164. const value = torch._C.tryInsertConstant(g, val, loc, scope);
  15165. if (value !== undefined) {
  15166. return value;
  15167. }
  15168. throw new python.Error('Unsupported value kind.');
  15169. });
  15170. this.registerFunction('torch._C.tryInsertConstant', (g, val, loc, scope) => {
  15171. if (val instanceof torch._C.IValue) {
  15172. const n = g.create('prim::Constant');
  15173. if (val.isTensor()) {
  15174. const ref = val.toTensor();
  15175. if (!torch._C.insertableTensor(val.toTensor())) {
  15176. n.destroy();
  15177. return null;
  15178. }
  15179. if (!ref.defined()) {
  15180. n.destroy();
  15181. return g.insertNode(g.createNone()).output();
  15182. }
  15183. torch._C.TORCH_INTERNAL_ASSERT(!ref.requires_grad());
  15184. n.output().inferTypeFrom(ref); // note: before t_ because of std::move(ref)
  15185. n.t_('value', ref);
  15186. } else if (val.isInt()) {
  15187. n.i_('value', val.toInt());
  15188. n.output().setType(torch.IntType.get());
  15189. } else if (val.isDouble()) {
  15190. n.f_('value', val.toDouble());
  15191. n.output().setType(torch.FloatType.get());
  15192. } else if (val.isComplexDouble()) {
  15193. n.c_('value', val.toComplexDouble());
  15194. n.output().setType(torch.ComplexType.get());
  15195. } else if (val.isBool()) {
  15196. n.i_('value', val.toBool());
  15197. n.output().setType(torch.BoolType.get());
  15198. } else if (val.isList()) {
  15199. const fast_path_list = val.isBoolList() || val.isIntList() || val.isDoubleList();
  15200. if (fast_path_list || torch._C.insertableIValue(val)) {
  15201. n.ival_('value', val);
  15202. n.output().setType(val.type());
  15203. } else {
  15204. n.destroy();
  15205. return null;
  15206. }
  15207. } else if (val.isString()) {
  15208. n.s_('value', val.toStringRef());
  15209. n.output().setType(torch.StringType.get());
  15210. } else if (val.isDevice()) {
  15211. n.s_('value', val.toDevice().__str__());
  15212. n.output().setType(torch.DeviceObjType.get());
  15213. } else if (val.isGenerator()) {
  15214. n.ival_('value', val.toGenerator());
  15215. n.output().setType(torch._C_._GeneratorType.get());
  15216. } else if (val.isStream()) {
  15217. n.ival_('value', val);
  15218. n.output().setType(torch.StreamObjType.get());
  15219. } else if (val.isNone()) {
  15220. n.output().setType(torch.NoneType.get());
  15221. // n.ival_('value', null); // remove
  15222. } else if (val.isTuple()) {
  15223. if (torch._C.insertableIValue(val)) {
  15224. n.ival_('value', val);
  15225. n.output().setType(val.type());
  15226. } else {
  15227. n.destroy();
  15228. return null;
  15229. }
  15230. } else if (val.isObject()) {
  15231. const ref = val.toObjectRef();
  15232. // see: [Constant Object Weak CompilationUnit Reference]
  15233. if (!ref.type().is_module() && (ref.is_weak_compilation_ref() || ref.is_empty_strong_compilation_ref())) {
  15234. n.ival_('value', val);
  15235. n.output().setType(val.type());
  15236. } else {
  15237. n.destroy();
  15238. return null;
  15239. }
  15240. } else if ((val.isGenericDict() && torch._C.insertableIValue(val)) || (val.isEnum())) {
  15241. n.ival_('value', val);
  15242. n.output().setType(val.type());
  15243. } else {
  15244. n.destroy();
  15245. return null;
  15246. }
  15247. if (loc) {
  15248. n.setSourceRange(loc);
  15249. }
  15250. if (scope) {
  15251. n.setScope(scope);
  15252. }
  15253. return g.insertNode(n).output();
  15254. }
  15255. const n = g.create('prim::Constant');
  15256. let type = null;
  15257. if (val === null) {
  15258. n.ival_('value', val);
  15259. type = torch.NoneType.get();
  15260. } else if (typeof val === 'string') {
  15261. n.s_('value', val);
  15262. type = torch.StringType.get();
  15263. } else if (Array.isArray(val) && val.every((item) => typeof item === 'string')) {
  15264. n.ss_('value', val);
  15265. type = torch.ListType.create(torch.StringType.get());
  15266. } else if (typeof val === 'boolean') {
  15267. n.i_('value', val === true ? 1 : 0);
  15268. type = torch.BoolType.get();
  15269. } else if ((!val.type && Number.isInteger(val)) || val.type === 'int') {
  15270. n.i_('value', val);
  15271. type = torch.IntType.get();
  15272. } else if ((!val.type && typeof val === 'number') || val.type === 'float') {
  15273. n.f_('value', val);
  15274. type = torch.FloatType.get();
  15275. } else if (val instanceof torch.Tensor) {
  15276. n.t_('value', val);
  15277. type = torch.TensorType.get();
  15278. } else if (val instanceof torch.ScriptObject) {
  15279. n.ival_('value', val);
  15280. type = val.type();
  15281. } else if (Array.isArray(val) && val.every((item) => Number.isInteger(item))) {
  15282. n.ival_('value', val);
  15283. type = torch.ListType.create(torch.IntType.get());
  15284. } else {
  15285. throw new python.Error(`Unsupported value type '${typeof val}'.`);
  15286. }
  15287. if (type) {
  15288. n.output().setType(type);
  15289. }
  15290. if (loc) {
  15291. n.setSourceRange(loc);
  15292. }
  15293. if (scope) {
  15294. n.setScope(scope);
  15295. }
  15296. return g.insertNode(n).output();
  15297. });
  15298. this.registerFunction('torch._C.toIValue', (v) => {
  15299. if (v.node().kind() !== 'prim::Constant' || v.type() instanceof torch._C.FunctionType) {
  15300. return null;
  15301. }
  15302. const node = v.node();
  15303. const type = v.type();
  15304. if (type.isSubtypeOf(torch.TensorType.get())) {
  15305. return new torch._C.IValue(node.t('value'), 'Tensor');
  15306. } else if (type.isSubtypeOf(torch.BoolType.get())) {
  15307. return new torch._C.IValue(Boolean(node.i('value'), 'Bool'));
  15308. } else if (type.isSubtypeOf(torch.NumberType.get()) && node.kindOf('value') === 'i') {
  15309. return new torch._C.IValue(node.i('value'), 'Int');
  15310. } else if (type.isSubtypeOf(torch.NumberType.get()) && node.kindOf('value') === 'f') {
  15311. return new torch._C.IValue(node.f('value'), 'Double');
  15312. } else if (type.isSubtypeOf(torch.ComplexType.get()) && node.kindOf('value') === 'c') {
  15313. return new torch._C.IValue(node.c('value'), 'Complex');
  15314. } else if (type instanceof torch.ListType && node.kindOf('value') === 'ival') {
  15315. let list = node.ival('value');
  15316. list = list.isList ? list : new torch._C.IValue(list); // remove
  15317. torch._C.TORCH_INTERNAL_ASSERT(list.isList());
  15318. return list;
  15319. } else if (type instanceof torch.DictType && node.kindOf('value') === 'ival') {
  15320. const dict = node.ival('value');
  15321. torch._C.TORCH_INTERNAL_ASSERT(dict.isGenericDict());
  15322. return dict;
  15323. } else if (type instanceof torch.TupleType && node.kindOf('value') === 'ival') {
  15324. const tup = node.ival('value');
  15325. torch._C.TORCH_INTERNAL_ASSERT(tup.isTuple());
  15326. return tup;
  15327. } else if (type === torch.StringType.get()) {
  15328. const s = new torch._C.IValue(node.s('value'), 'String');
  15329. return s;
  15330. } else if (type === torch.DeviceObjType.get()) {
  15331. const d = new torch.device(node.s('value'));
  15332. return new torch._C.IValue(d);
  15333. } else if (type === torch._C._GeneratorType.get()) {
  15334. throw new python.Error('Not implemented.');
  15335. // const generator = node.ival('value').toGenerator();
  15336. // return generator;
  15337. } else if (type === torch.StreamObjType.get()) {
  15338. throw new python.Error('Not implemented.');
  15339. // const s = node.ival('value').toStream();
  15340. // return s;
  15341. } else if (node.mustBeNone()) {
  15342. return new torch._C.IValue();
  15343. } else if (type.kind() === 'EnumType') {
  15344. const enum_val = node.ival('value');
  15345. return enum_val;
  15346. } else if (type instanceof torch.ClassType && !type.is_module()) {
  15347. const class_val = node.ival('value');
  15348. return new torch._C.IValue(class_val, 'Object');
  15349. }
  15350. throw new python.Error('Unsupported constant literal.');
  15351. });
  15352. this.registerFunction('torch._C.constant_as', (v, target, default_value) => {
  15353. const ivalue = torch._C.toIValue(v);
  15354. if (ivalue) {
  15355. return ivalue[target]();
  15356. }
  15357. return default_value === undefined ? null : default_value;
  15358. });
  15359. this.registerType('torch._C.NamedValue', class {
  15360. constructor(...args) {
  15361. if (args.length === 1) {
  15362. if (args[0] instanceof torch.Value) {
  15363. [this._value] = args;
  15364. } else {
  15365. [this._ivalue] = args;
  15366. }
  15367. } else if (args.length === 3 && typeof args[1] === 'string' && args[2] instanceof torch.Value) {
  15368. [this._loc, this._name, this._value] = args;
  15369. } else {
  15370. throw new python.Error('Invalid argument.');
  15371. }
  15372. }
  15373. name() {
  15374. return this._name;
  15375. }
  15376. value(g) {
  15377. if (!this._value) {
  15378. return torch._C.insertConstant(g, this._ivalue);
  15379. }
  15380. return this._value;
  15381. }
  15382. type() {
  15383. if (this._value) {
  15384. return this._value.type();
  15385. }
  15386. return this._ivalue.type();
  15387. }
  15388. });
  15389. this.registerType('torch._C.SugaredValue', class {
  15390. kind() {
  15391. throw new python.Error('Not implemented.');
  15392. }
  15393. shouldEmitUnrolled() {
  15394. return this.staticLen() !== null;
  15395. }
  15396. });
  15397. this.registerType('torch._C.SimpleValue', class extends torch._C.SugaredValue {
  15398. constructor(value) {
  15399. super();
  15400. this._value = value;
  15401. }
  15402. kind() {
  15403. return `value of type '${this._value.type().annotation_str}'`;
  15404. }
  15405. asValue(/* range, m */) {
  15406. return this._value;
  15407. }
  15408. getValue() {
  15409. return this._value;
  15410. }
  15411. asTuple(loc, m, size_hint) {
  15412. const make_simple_value = (v) => new torch._C.SimpleValue(v);
  15413. if (this._value.type() instanceof torch.TupleType) {
  15414. const outputs = torch._C.createTupleUnpack(this._value);
  15415. return outputs.map((v) => make_simple_value(v));
  15416. } else if (this._value.type() instanceof torch.ListType) {
  15417. if (!size_hint) {
  15418. throw new python.Error('Cannot statically infer the expected size of a list in this context.');
  15419. }
  15420. const graph = this._value.owningGraph();
  15421. const unpack = graph.insertNode(graph.createListUnpack(this._value, size_hint));
  15422. return unpack.outputs().map((v) => make_simple_value(v));
  15423. } else if (this._value.type().kind() === 'AnyTupleType') {
  15424. throw new python.Error('Provided tuple is not fully defined including its element types.');
  15425. }
  15426. throw new python.Error(`Cannot use '${this._value.type().toString()}' as tuple.`);
  15427. }
  15428. attr(loc, m, field) {
  15429. if (this._value.type().isSubtypeOf(torch.TensorType.get())) {
  15430. if (torch._C.builtin_cast_method_to_scalar_type().has(field)) {
  15431. return new torch._C.TensorCastValue(torch._C.builtin_cast_method_to_scalar_type().get(field), new torch._C.NamedValue(loc, 'self', this._value));
  15432. }
  15433. }
  15434. if (this._value.type() instanceof torch.TupleType) {
  15435. throw new python.Error('Not implemented.');
  15436. }
  15437. if (this._value.type() instanceof torch.AwaitType) {
  15438. throw new python.Error('Not implemented.');
  15439. }
  15440. if (this._value.type() instanceof torch.ClassType) {
  15441. const classType = this._value.type();
  15442. if (classType.findMethod(field)) {
  15443. return new torch._C.MethodValue(this.getValue(), [field]);
  15444. }
  15445. if (classType.hasAttribute(field)) {
  15446. const g = m.graph();
  15447. const n = g.insertNode(g.createGetAttr(this._value, field));
  15448. return new torch._C.SimpleValue(n.output());
  15449. }
  15450. const prop = classType.getProperty(field);
  15451. if (prop) {
  15452. return new torch._C.MethodValue(this._value, [prop.getter.name()]).call(loc, m, {}, {}, /*n_binders=*/1);
  15453. }
  15454. } else if (this._value.type() instanceof torch.InterfaceType) {
  15455. throw new python.Error('Not implemented.');
  15456. } else if (this._value.type() instanceof torch.EnumType) {
  15457. const g = m.graph();
  15458. if (field === 'name') {
  15459. const n = g.insertNode(g.createEnumName(this._value));
  15460. return new torch._C.SimpleValue(n.output());
  15461. }
  15462. if (field === 'value') {
  15463. const n = g.insertNode(g.createEnumValue(this._value));
  15464. return new torch._C.SimpleValue(n.output());
  15465. }
  15466. }
  15467. if (field === 'type') {
  15468. const builtin = torch._C.BuiltinFunction.tryCreate('aten::to', new torch._C.NamedValue(loc, 'self', this._value));
  15469. if (builtin) {
  15470. return builtin;
  15471. }
  15472. }
  15473. const builtin = torch._C.BuiltinFunction.tryCreate(`aten::${field}`, new torch._C.NamedValue(loc, 'self', this._value));
  15474. if (builtin) {
  15475. return builtin;
  15476. }
  15477. if (this._value.type().isSubtypeOf(torch.TensorType.get()) && field === 'tolist') {
  15478. return torch._C.SpecialFormValue.create('prim::tolist');
  15479. }
  15480. if (this._value.type().isSubtypeOf(torch.TensorType.get()) && field === '__getitem__') {
  15481. return torch._C.SpecialFormValue.create('aten::index');
  15482. }
  15483. if (this._value.type() instanceof torch._C._GeneratorType && (field === 'manual_seed' || field === 'initial_seed' || field === 'seed')) {
  15484. const builtin = torch._C.BuiltinFunction.tryCreate(`aten::${field}`, new torch._C.NamedValue(loc, 'self', this._value));
  15485. if (builtin) {
  15486. return builtin;
  15487. }
  15488. }
  15489. throw new python.Error('Object has no attribute or method.');
  15490. }
  15491. setAttr(loc, m, field, newValue) {
  15492. const type = this._value.type();
  15493. if (type instanceof torch.ClassType === false) {
  15494. throw new python.Error('Cannot set attribute on non-class type.');
  15495. }
  15496. const classType = type;
  15497. let expectedType = classType.findAttribute(field);
  15498. if (!expectedType) {
  15499. const isInitializing = m.name() === '__init__' && m.graph().inputs().length > 0 && m.graph().inputs()[0].type() === classType;
  15500. if (isInitializing) {
  15501. if (this.isRecursive(classType, newValue.type())) {
  15502. throw new python.Error('Classes that recursively contain instances of themselves are not supported.');
  15503. }
  15504. classType.addAttribute(field, newValue.type());
  15505. expectedType = newValue.type();
  15506. const insertPoint = m.graph().insertPoint();
  15507. const topLevelBlock = m.graph().block();
  15508. if (insertPoint.owningBlock() !== topLevelBlock) {
  15509. throw new python.Error('First assignment cannot be in a control-flow block.');
  15510. }
  15511. } else {
  15512. const prop = classType.getProperty(field);
  15513. if (prop && prop.setter) {
  15514. new torch._C.MethodValue(this._value, prop.setter.name()).call(loc, m, [newValue], [], /*n_binders=*/1);
  15515. return;
  15516. }
  15517. if (prop && !prop.setter) {
  15518. throw new python.Error('Tried to set read-only attribute.');
  15519. }
  15520. throw new python.Error('Tried to set nonexistent attribute.');
  15521. }
  15522. }
  15523. torch._C.AT_ASSERT(expectedType);
  15524. const newType = newValue.type();
  15525. if (!newType.isSubtypeOf(expectedType)) {
  15526. throw new python.Error('Wrong type for attribute assignment.');
  15527. }
  15528. const g = m.graph();
  15529. g.insertNode(g.createSetAttr(this._value, field, newValue));
  15530. }
  15531. getitem(loc, m, idx, type_hint) {
  15532. const val = this.getValue();
  15533. const val_type = val.type();
  15534. const g = m.graph();
  15535. if (val_type instanceof torch.ListType || val_type instanceof torch.StringType) {
  15536. return new torch._C.SimpleValue(g.insert('aten::__getitem__', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc));
  15537. } else if (val_type instanceof torch.DictType) {
  15538. return new torch._C.SimpleValue(g.insert('aten::__getitem__', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc));
  15539. } else if (val_type.isSubtypeOf(torch.TensorType.get())) {
  15540. 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));
  15541. } else if (val_type instanceof torch.ClassType) {
  15542. const class_type = val_type;
  15543. if (class_type.is_module() && type_hint) {
  15544. const res = g.insert('prim::ModuleContainerIndex', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc);
  15545. res.setType(type_hint);
  15546. return new torch._C.SimpleValue(res);
  15547. }
  15548. return this.attr(loc, m, '__getitem__').call(loc, m, [new torch._C.NamedValue(idx)], [], 1);
  15549. }
  15550. throw new python.Error('Object is not subscriptable.');
  15551. }
  15552. });
  15553. this.registerType('torch._C.MethodValue', class extends torch._C.SugaredValue {
  15554. constructor(self, method_names) {
  15555. super();
  15556. this._self = self;
  15557. this._method_names = method_names;
  15558. }
  15559. call(loc, f, args, kwargs /*, n_binders */) {
  15560. const argsWithSelf = [new torch._C.NamedValue(this._self), ...args];
  15561. const schemas = [];
  15562. for (const method_name of this._method_names) {
  15563. const type = this._self.type();
  15564. if (type instanceof torch.ClassType) {
  15565. const class_type = type;
  15566. const method = class_type.getMethod(method_name);
  15567. method.ensure_defined();
  15568. schemas.push(method.getSchema());
  15569. } else if (type instanceof torch.InterfaceType) {
  15570. const interface_type = type;
  15571. schemas.push(interface_type.getMethod(method_name));
  15572. } else {
  15573. throw new python.Error('Method constructed that is not a class or interface.');
  15574. }
  15575. }
  15576. const match = torch._C.matchSchemas(schemas, loc, f.graph(), argsWithSelf, kwargs);
  15577. const output = f.graph().insertMethodCall(this._method_names[match[0]], match[1]);
  15578. output.node().setSourceRange(loc);
  15579. return new torch._C.SimpleValue(output);
  15580. }
  15581. });
  15582. this.registerType('torch._C.ClassValue', class extends torch._C.SugaredValue {
  15583. constructor(type) {
  15584. super();
  15585. this._type = type;
  15586. }
  15587. attr(loc, m, field) {
  15588. const hook = this._type.findHook(field);
  15589. if (hook) {
  15590. return new torch._C.FunctionValue(hook);
  15591. }
  15592. if (field !== '__new__') {
  15593. throw new python.Error('Tried to lookup unknown attribute on class.');
  15594. }
  15595. return torch._C.SpecialFormValue.create('prim::CreateObject');
  15596. }
  15597. });
  15598. this.registerType('torch._C.NamedTupleConstructor', class extends torch._C.SugaredValue {
  15599. constructor(type) {
  15600. super();
  15601. this._type = type;
  15602. }
  15603. call(loc, m, args, kwargs /*, n_binders */) {
  15604. const g = m.graph();
  15605. const schema = this._type.schema();
  15606. torch._C.TORCH_INTERNAL_ASSERT(schema);
  15607. const matched_schema = torch._C.matchSchema(schema, loc, g, args, kwargs);
  15608. const self = g.insertNode(g.createTuple(matched_schema.inputs, this._type).setSourceRange(loc)).output();
  15609. self.setType(this._type);
  15610. return new torch._C.SimpleValue(self);
  15611. }
  15612. });
  15613. this.registerType('torch._C.SugaredEnumClass', class extends torch._C.SugaredValue {
  15614. constructor(enum_type) {
  15615. super();
  15616. this._enum_type = enum_type;
  15617. }
  15618. attr(loc, m, field) {
  15619. const names_values = this._enum_type.enumNamesValues();
  15620. const it = names_values.find((nv) => nv[0] === field);
  15621. if (it === null) {
  15622. throw new python.Error(`Enum '${this._enum_type.name()}' has no attribute '${field}'.`);
  15623. }
  15624. const enum_holder = new torch._C.EnumHolder(this._enum_type, it[0], it[1]);
  15625. return new torch._C.SimpleValue(m.graph().insertConstant(new torch._C.IValue(enum_holder), loc));
  15626. }
  15627. });
  15628. this.registerType('torch._C.EnumHolder', class {
  15629. constructor(type, name, value) {
  15630. this._type = type;
  15631. this._name = name;
  15632. this._value = value;
  15633. }
  15634. name() {
  15635. return this._name;
  15636. }
  15637. type() {
  15638. return this._type;
  15639. }
  15640. });
  15641. this.registerType('torch._C.FunctionValue', class extends torch._C.SugaredValue {
  15642. constructor(...args) {
  15643. super();
  15644. if (args.length === 1 && args[0] instanceof torch._C.Function) {
  15645. this._callees = [args[0]];
  15646. } else {
  15647. throw new python.Error('Not implemented.');
  15648. }
  15649. }
  15650. call(loc, f, args, kwargs /*, n_binders */) {
  15651. const schemas = [];
  15652. for (const callee of this._callees) {
  15653. callee.ensure_defined();
  15654. schemas.push(callee.getSchema());
  15655. }
  15656. const match = torch._C.matchSchemas(schemas, loc, f.graph(), args, kwargs);
  15657. const output = f.graph().insertFunctionCall(this._callees[match[0]], match[1]);
  15658. output.node().setSourceRange(loc);
  15659. return new torch._C.SimpleValue(output);
  15660. }
  15661. });
  15662. this.registerType('torch._C.NoneValue', class extends torch._C.SugaredValue {
  15663. });
  15664. this.registerType('torch._C.PrintValue', class extends torch._C.SugaredValue {
  15665. call(loc, m, args, kwargs /*, n_binders */) {
  15666. const g = m.graph();
  15667. if (kwargs.length > 0) {
  15668. throw new python.Error(`Print doesn't accept any keyword arguments at ${loc}.`);
  15669. }
  15670. const lowered_inputs = torch._C.toValues(m.graph(), args);
  15671. g.insertNode(g.create('prim::Print', lowered_inputs, 0).setSourceRange(loc));
  15672. return new torch._C.NoneValue();
  15673. }
  15674. });
  15675. this.registerType('torch._C.SpecialFormValue', class extends torch._C.SugaredValue {
  15676. constructor(form) {
  15677. super();
  15678. this._form = form;
  15679. }
  15680. form() {
  15681. return this._form;
  15682. }
  15683. static create(form) {
  15684. return new torch._C.SpecialFormValue(form);
  15685. }
  15686. });
  15687. this.registerFunction('torch._C.makeMagic', (name, base) => {
  15688. return new torch._C.MagicMethod(name, base);
  15689. });
  15690. this.registerType('torch._C.BuiltinFunction', class extends torch._C.SugaredValue {
  15691. constructor(symbol, self) {
  15692. super();
  15693. this.symbol = symbol;
  15694. this.self = self;
  15695. }
  15696. call(loc, m, args, kwargs /*, n_binders */) {
  15697. return new torch._C.SimpleValue(torch._C.emitBuiltinCall(loc, m.graph(), this.symbol, args, kwargs, this.self));
  15698. }
  15699. static tryCreate(symbol, self) {
  15700. for (const op of torch._C.getAllOperatorsFor(symbol)) {
  15701. if (!self) {
  15702. return new torch._C.BuiltinFunction(symbol, null);
  15703. }
  15704. const index = op.schema().argumentIndexWithName('self');
  15705. if (index) {
  15706. const type_env = new Map();
  15707. const formal_type = op.schema().arguments()[index].type();
  15708. const matched = torch._C.matchTypeVariables(formal_type, self.type(), type_env);
  15709. if (!matched.success()) {
  15710. continue;
  15711. }
  15712. const concrete_type = torch._C.tryEvalTypeVariables(formal_type, type_env);
  15713. if (!concrete_type || !self.type().isSubtypeOf(concrete_type)) {
  15714. continue;
  15715. }
  15716. return new torch._C.BuiltinFunction(symbol, self);
  15717. }
  15718. }
  15719. return null;
  15720. }
  15721. });
  15722. this.registerType('torch._C.BuiltinModule', class extends torch._C.SugaredValue {
  15723. constructor(name, version) {
  15724. super();
  15725. this.name = name;
  15726. this.version = version || null;
  15727. }
  15728. attr(loc, m, field) {
  15729. if (field === 'autograd') {
  15730. return new torch._C.BuiltinModule('aten', this.version);
  15731. }
  15732. const sym = `${this.name}::${field}`;
  15733. return new torch._C.BuiltinFunction(sym, null);
  15734. }
  15735. });
  15736. this.registerType('torch._C.OpsValue', class extends torch._C.SugaredValue {
  15737. constructor(version) {
  15738. super();
  15739. this._version = version;
  15740. }
  15741. attr(loc, m, field) {
  15742. return new torch._C.BuiltinModule(field, this._version);
  15743. }
  15744. });
  15745. this.registerType('torch._C.ConstantTableValue', class extends torch._C.SugaredValue {
  15746. constructor(constants) {
  15747. super();
  15748. this._constants = constants;
  15749. this.non_holding_object_cache = new Map();
  15750. }
  15751. attr(loc, m, field) {
  15752. const offset = parseInt(field.substring(1), 10);
  15753. if (!Number.isInteger(offset)) {
  15754. throw new python.Error(`Invalid constant identifier '${field}.`);
  15755. }
  15756. if (offset < 0 || offset >= this._constants.length) {
  15757. throw new python.Error('Invalid constant index.');
  15758. }
  15759. const ivalue = new torch._C.IValue(this._constants[offset]); // remove IValue
  15760. let value = null;
  15761. if (ivalue.isObject() && !ivalue.toObject().is_weak_compilation_ref()) {
  15762. const obj = ivalue.toObject();
  15763. if (!this.non_holding_object_cache.has(obj)) {
  15764. this.non_holding_object_cache.set(obj, obj.copy_to_weak_compilation_ref());
  15765. }
  15766. value = m.graph().insertConstant(this.non_holding_object_cache[obj], loc);
  15767. } else {
  15768. value = m.graph().insertConstant(this._constants[offset], loc);
  15769. }
  15770. value.setType(torch._C.unshapedType(value.type()));
  15771. return new torch._C.SimpleValue(value);
  15772. }
  15773. });
  15774. this.registerType('torch._C.CastValue', class extends torch._C.BuiltinFunction {
  15775. constructor(type, method) {
  15776. super(method, null);
  15777. this._type = type;
  15778. }
  15779. call(loc, m, args, kwargs, n_binders) {
  15780. if (args.length === 1 && kwargs.length === 0) {
  15781. const len_op = new torch._C.BuiltinFunction('aten::len', null);
  15782. const gt_op = new torch._C.BuiltinFunction('aten::gt', null);
  15783. const zero = m.graph().insertConstant(new torch._C.IValue(0, 'Int'));
  15784. const v = args[0].value(m.graph());
  15785. if (v.type().isSubtypeOf(this._type)) {
  15786. return new torch._C.SimpleValue(v);
  15787. } 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)) {
  15788. const len = len_op.call(loc, m, [v], [], 1);
  15789. return gt_op.call(loc, m, [len.asValue(loc, m), zero], [], 1);
  15790. }
  15791. }
  15792. return super.call(loc, m, args, kwargs, n_binders);
  15793. }
  15794. });
  15795. this.registerType('torch._C.MagicMethod', class extends torch._C.SugaredValue {
  15796. constructor(desugared_name, base) {
  15797. super();
  15798. this._base_value = base;
  15799. this._desugared_name = desugared_name;
  15800. }
  15801. call(loc, m, args, kwargs, n_binders) {
  15802. if (args.length > 0) {
  15803. const self = args[0].value(m.graph());
  15804. if (self.type() instanceof torch.ClassType) {
  15805. return new torch._C.SimpleValue(self)
  15806. .attr(loc, m, this._desugared_name)
  15807. .call(loc, m, args.slice(1), kwargs, n_binders);
  15808. }
  15809. }
  15810. if (!this._base_value) {
  15811. throw new python.Error('Invalid magic method.');
  15812. }
  15813. return this._base_value.call(loc, m, args, kwargs, n_binders);
  15814. }
  15815. });
  15816. this.registerType('torch._C.RangeValue', class extends torch._C.SugaredValue {
  15817. constructor(loc, m, inputs, static_len) {
  15818. super();
  15819. static_len = static_len || null;
  15820. if (inputs.length === 0 || inputs.length > 3 || !inputs.every((value) => value.type() instanceof torch.IntType)) {
  15821. throw new python.Error('Invalid range inputs.');
  15822. }
  15823. const g = m.graph();
  15824. if (inputs.length === 1) {
  15825. [this._end] = inputs;
  15826. this._start = g.insertConstant(0, loc);
  15827. this._step = g.insertConstant(1, loc);
  15828. this._has_only_end = true;
  15829. } else {
  15830. [this._start, this._end] = inputs;
  15831. this._step = inputs.length === 3 ? inputs[2] : g.insertConstant(1, loc);
  15832. this._has_only_end = false;
  15833. }
  15834. this._static_len = static_len;
  15835. }
  15836. staticLen() {
  15837. return this._static_len;
  15838. }
  15839. iter() {
  15840. return this;
  15841. }
  15842. len(loc, m) {
  15843. if (this._static_len) {
  15844. return torch._C.insertConstant(m.graph(), this._static_len, loc);
  15845. }
  15846. if (this._has_only_end) {
  15847. return this._end;
  15848. }
  15849. const g = m.graph();
  15850. return g.insert('aten::__range_length', [this._start, this._end, this._step], [], loc);
  15851. }
  15852. getitem(loc, m, idx /*, type_hint */) {
  15853. if (this._has_only_end) {
  15854. return new torch._C.SimpleValue(idx);
  15855. }
  15856. const g = m.graph();
  15857. return new torch._C.SimpleValue(g.insert('aten::__derive_index', [idx, this._start, this._step], [], loc));
  15858. }
  15859. });
  15860. this.registerType('torch._C.SliceValue', class extends torch._C.SugaredValue {
  15861. });
  15862. this.registerType('torch._C.ClassNamespaceValue', class extends torch._C.SugaredValue {
  15863. constructor(name, si) {
  15864. super();
  15865. this._basename = name;
  15866. this._si = si;
  15867. }
  15868. attr(loc, m, name) {
  15869. const fullName = new torch._C.QualifiedName(this._basename, name);
  15870. const serializable_type = this._si.findNamedType(fullName);
  15871. if (serializable_type) {
  15872. if (serializable_type instanceof torch.ClassType) {
  15873. return new torch._C.ClassValue(serializable_type);
  15874. } else if (serializable_type instanceof torch.TupleType) {
  15875. return new torch._C.NamedTupleConstructor(serializable_type);
  15876. } else if (serializable_type instanceof torch.EnumType) {
  15877. return new torch._C.SugaredEnumClass(serializable_type);
  15878. }
  15879. }
  15880. const fn = this._si.findFunction(fullName);
  15881. if (fn) {
  15882. return new torch._C.FunctionValue(fn);
  15883. }
  15884. return new torch._C.ClassNamespaceValue(fullName, this._si);
  15885. }
  15886. });
  15887. this.registerType('torch.package.PackageImporter', class {
  15888. constructor(reader) {
  15889. this.zip_reader = reader;
  15890. }
  15891. load_pickle(module, resource) {
  15892. const name = `${module.replace(/\./, '/')}/${resource}`;
  15893. const stream = this.zip_reader.get_record(name);
  15894. const loaded_reduces = new Map();
  15895. this.storage_context = new torch._C.DeserializationStorageContext();
  15896. const unpickler = new pickle.Unpickler(stream);
  15897. unpickler.persistent_load = (saved_id) => {
  15898. switch (saved_id[0]) {
  15899. case 'storage': {
  15900. const [, storage_type, key, , size] = saved_id;
  15901. if (!this.storage_context.has_storage(key)) {
  15902. const storage = new storage_type(size);
  15903. if (!storage._set_cdata) {
  15904. throw new python.Error(`'${storage_type.__name__}._set_cdata' is not a function.`);
  15905. }
  15906. const stream = this.zip_reader.get_record(`.data/${key}.storage`);
  15907. const buffer = stream.peek();
  15908. storage._set_cdata(buffer);
  15909. this.storage_context.add_storage(key, storage);
  15910. }
  15911. return this.storage_context.get_storage(key);
  15912. }
  15913. case 'reduce_package': {
  15914. if (saved_id.length === 2) {
  15915. const [, func, args] = saved_id;
  15916. return execution.invoke(func, args);
  15917. }
  15918. const [, reduce_id, func, args] = saved_id;
  15919. if (!loaded_reduces.has(reduce_id)) {
  15920. const value = execution.invoke(func, [this].concat(args));
  15921. loaded_reduces.set(reduce_id, value);
  15922. }
  15923. return loaded_reduces.get(reduce_id);
  15924. }
  15925. default: {
  15926. throw new python.Error(`Unknown package typename '${saved_id[0]}'.`);
  15927. }
  15928. }
  15929. };
  15930. const obj = unpickler.load();
  15931. this.storage_context = null;
  15932. return obj;
  15933. }
  15934. import_module(name) {
  15935. return execution.import(name);
  15936. }
  15937. });
  15938. this.registerFunction('torch.jit.load', (file, map_location, extra_files) => {
  15939. const cu = new torch.jit.CompilationUnit();
  15940. cu.execution = execution;
  15941. const cpp_module = torch._C.import_ir_module(cu, file, map_location, extra_files);
  15942. const module = torch.jit._script.wrap_cpp_module(cpp_module);
  15943. module.forward = cpp_module.forward; // remove
  15944. return module;
  15945. });
  15946. this.registerFunction('torch._C.import_ir_module', function(cu, reader, ...args) {
  15947. switch (arguments.length) {
  15948. case 4: {
  15949. const [device, extra_files] = args;
  15950. const deserializer = new torch._C.ScriptModuleDeserializer(cu, reader);
  15951. return deserializer.deserialize(device, extra_files);
  15952. }
  15953. case 5: {
  15954. const [storage_context, device, ts_id] = args;
  15955. const deserializer = new torch._C.ScriptModuleDeserializer(cu, reader, `.data/ts_code/${ts_id}/`, '.data/', storage_context);
  15956. return deserializer.deserialize(device, null);
  15957. }
  15958. default: {
  15959. throw new python.Error("Invalid 'torch._C.import_ir_module' signature.");
  15960. }
  15961. }
  15962. });
  15963. this.registerFunction('torch._C._import_ir_module_from_package', (cu, reader, storage_context, map_location, ts_id) => {
  15964. return torch._C.import_ir_module(cu, reader, storage_context, null, ts_id);
  15965. });
  15966. this.registerFunction('torch._C.tryToGraphFunction', (value) => {
  15967. if (value instanceof torch.Node) {
  15968. const n = value;
  15969. if (n.kind() === 'prim::CallFunction') {
  15970. torch._C.AT_ASSERT(n.input(0).node().kind() === 'prim::Constant');
  15971. const function_constant = n.input(0).node();
  15972. const fun_type = function_constant.output().type().expect(torch._C.FunctionType);
  15973. return torch._C.tryToGraphFunction(fun_type.function());
  15974. }
  15975. if (n.kind() === 'prim::CallMethod') {
  15976. const name = n.s('name');
  15977. const class_type = n.input(0).type();
  15978. if (class_type instanceof torch.ClassType) {
  15979. const fn = class_type.getMethod(name);
  15980. return torch._C.tryToGraphFunction(fn);
  15981. }
  15982. }
  15983. return null;
  15984. } else if (value instanceof torch._C.Function) {
  15985. const fn = value;
  15986. if (!fn.isGraphFunction()) {
  15987. return null;
  15988. }
  15989. return fn;
  15990. }
  15991. throw new python.Error('Not implemented.');
  15992. });
  15993. this.registerType('torch._C.ModuleInstanceInfo', class {
  15994. constructor(module_type, instance_name) {
  15995. this._module_type = module_type;
  15996. this._instance_name = instance_name;
  15997. }
  15998. });
  15999. this.registerFunction('torch._C.slice_indices_adjust', (length, start, stop, step) => {
  16000. torch._C.TORCH_CHECK(step !== 0);
  16001. torch._C.TORCH_CHECK(step >= -Number.MAX_SAFE_INTEGER); // INT64_MAX
  16002. if (start._ === Number.MAX_SAFE_INTEGER) {
  16003. start._ = (step < 0) ? Number.MAX_SAFE_INTEGER : 0;
  16004. }
  16005. if (stop._ === Number.MAX_SAFE_INTEGER) {
  16006. stop._ = (step < 0) ? Number.MIN_SAFE_INTEGER : Number.MAX_SAFE_INTEGER;
  16007. }
  16008. if (start._ < 0) {
  16009. start._ += length;
  16010. if (start._ < 0) {
  16011. start._ = (step < 0) ? -1 : 0;
  16012. }
  16013. } else if (start._ >= length) {
  16014. start._ = (step < 0) ? length - 1 : length;
  16015. }
  16016. if (stop._ < 0) {
  16017. stop._ += length;
  16018. if (stop._ < 0) {
  16019. stop._ = (step < 0) ? -1 : 0;
  16020. }
  16021. } else if (stop._ >= length) {
  16022. stop._ = (step < 0) ? length - 1 : length;
  16023. }
  16024. if (step < 0) {
  16025. if (stop._ < start._) {
  16026. return Math.floor((start._ - stop._ - 1) / (-step) + 1);
  16027. }
  16028. } else if (start._ < stop._) {
  16029. return Math.floor((stop._ - start._ - 1) / step + 1);
  16030. }
  16031. return 0;
  16032. });
  16033. this.registerFunction('torch._C.createTupleUnpack', (v) => {
  16034. if (v.node().kind() === 'prim::TupleConstruct') {
  16035. return v.node().inputs();
  16036. }
  16037. const g = v.owningGraph();
  16038. return g.insertNode(g.createTupleUnpack(v)).outputs();
  16039. });
  16040. this.registerFunction('torch._C.inlineCallStackOfNode', (/* new_node, new_cs_entriesm, callee, to_replace, m_info */) => {
  16041. /*
  16042. const new_node_cs = new_node.callstack();
  16043. const raw_callstack_ptr = new_node_cs ? new_node_cs : nullptr;
  16044. if (!new_cs_entries.has(raw_callstack_ptr)) {
  16045. if (new_node_cs) {
  16046. new_cs_entries.set(raw_callstack_ptr, c10::make_intrusive<InlinedCallStack>(*new_node_cs, callee, to_replace.sourceRange(), m_info));
  16047. } else {
  16048. new_cs_entries.set(raw_callstack_ptr, c10::make_intrusive<InlinedCallStack>(callee, to_replace.sourceRange(), m_info);
  16049. }
  16050. }
  16051. new_node.setCallStack(new_cs_entries.at(raw_callstack_ptr));
  16052. for (const block of new_node.blocks()) {
  16053. torch._C.inlineCallStackOfBlock(block, new_cs_entries, callee, to_replace, m_info);
  16054. }
  16055. */
  16056. });
  16057. this.registerFunction('torch._C.inlineCallTo', (to_replace, callee, arg) => {
  16058. if (arg === undefined || typeof arg === 'boolean') {
  16059. const inline_optimized_graph = arg === undefined ? true : arg;
  16060. const graph = inline_optimized_graph ? callee.optimized_graph() : callee.graph();
  16061. return torch._C.inlineCallTo(to_replace, callee, graph);
  16062. }
  16063. if (arg instanceof torch.Graph === false) {
  16064. throw new python.Error('Invalid argument.');
  16065. }
  16066. const callee_graph = arg;
  16067. const guard = new torch._C.WithInsertPoint(to_replace);
  16068. const value_map = new Map();
  16069. const new_outputs = torch._C.insertGraph(to_replace.owningGraph(), callee_graph, to_replace.inputs(), value_map);
  16070. const new_callstack_entries = new Map();
  16071. let module_instance_info = null;
  16072. if (to_replace.kind() === 'prim::CallMethod') {
  16073. const class_type_ptr = to_replace.input(0).type();
  16074. if (to_replace.input(0).node().kind() === 'prim::GetAttr') {
  16075. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, to_replace.input(0).node().s('name'));
  16076. } else if (to_replace.owningGraph().inputs().length > 0 && to_replace.input(0) === to_replace.owningGraph().inputs()[0]) {
  16077. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, 'SELF');
  16078. } else {
  16079. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, 'INSTANCE_NAME_UNKNOWN');
  16080. }
  16081. }
  16082. const updated_nodes = new Set();
  16083. for (const kv of value_map) {
  16084. const is_graph_input = callee_graph.inputs().indexOf(kv[0]);
  16085. if (is_graph_input === -1) {
  16086. continue;
  16087. }
  16088. const new_node = kv[1].node();
  16089. if (updated_nodes.has(new_node)) {
  16090. continue;
  16091. }
  16092. updated_nodes.add(new_node);
  16093. torch._C.inlineCallStackOfNode(new_node, new_callstack_entries, callee, to_replace, module_instance_info);
  16094. }
  16095. const old_outputs = to_replace.outputs();
  16096. torch._C.AT_ASSERT(new_outputs.length === old_outputs.length);
  16097. for (let i = 0; i < old_outputs.length; i++) {
  16098. if (old_outputs[i].hasDebugName()) {
  16099. new_outputs[i].setDebugName(old_outputs[i].debugName());
  16100. }
  16101. old_outputs[i].replaceAllUsesWith(new_outputs[i]);
  16102. }
  16103. to_replace.destroy();
  16104. guard.dispose();
  16105. return new_outputs;
  16106. });
  16107. this.registerFunction('torch._C.inlineCalls', (block) => {
  16108. for (const cur of block.nodes()) {
  16109. switch (cur.kind()) {
  16110. case 'prim::CallFunction': {
  16111. const graphFunction = torch._C.tryToGraphFunction(cur);
  16112. if (graphFunction) {
  16113. const function_constant = cur.input(0).node();
  16114. // const fun_type = function_constant.output().type().expect(torch.FunctionType);
  16115. cur.removeInput(0);
  16116. let g = null;
  16117. const fallback = function_constant.hasAttribute('fallback');
  16118. if (fallback && graphFunction.get_executor().isOptimized()) {
  16119. const exec_plans = graphFunction.get_executor().getDebugState().execution_plans;
  16120. if (!exec_plans.empty()) {
  16121. g = exec_plans.begin().second.graph;
  16122. torch._C.Inline(g);
  16123. }
  16124. }
  16125. if (g === null) {
  16126. g = graphFunction.optimized_graph();
  16127. }
  16128. torch._C.inlineCallTo(cur, graphFunction, g);
  16129. }
  16130. break;
  16131. }
  16132. case 'prim::CallMethod': {
  16133. const graphFunction = torch._C.tryToGraphFunction(cur);
  16134. if (graphFunction) {
  16135. torch._C.inlineCallTo(cur, graphFunction);
  16136. }
  16137. break;
  16138. }
  16139. default: {
  16140. for (const b of cur.blocks()) {
  16141. torch._C.inlineCalls(b);
  16142. }
  16143. }
  16144. }
  16145. }
  16146. });
  16147. this.registerFunction('torch._C.Inline', (graph) => {
  16148. torch._C.inlineCalls(graph.block());
  16149. });
  16150. this.registerFunction('torch._C._jit_pass_inline', (graph) => {
  16151. torch._C.Inline(graph);
  16152. });
  16153. this.registerFunction('torch._C._set_tensor_metadata', (/* tensor, metadata */) => {
  16154. });
  16155. this.registerFunction('torch.jit._script.unpackage_script_module', (importer, script_module_id) => {
  16156. const cu = new torch.jit.CompilationUnit();
  16157. cu.execution = execution;
  16158. const cpp_module = torch._C._import_ir_module_from_package(cu, importer.zip_reader, importer.storage_context, importer.last_map_location, script_module_id);
  16159. return torch.jit._script.wrap_cpp_module(cpp_module);
  16160. });
  16161. this.registerFunction('torch.jit._script.wrap_cpp_module', (cpp_module) => {
  16162. const init_fn = (script_module) => {
  16163. for (const [name, module] of new torch.ModuleDict(script_module._c).items()) {
  16164. script_module.__setattr__(name, torch.jit._script.wrap_cpp_module(module));
  16165. }
  16166. };
  16167. return torch.jit._script.RecursiveScriptModule._construct(cpp_module, init_fn);
  16168. });
  16169. this.registerType('torch._C.DeserializationStorageContext', class extends Map {
  16170. has_storage(name) {
  16171. return this.has(name);
  16172. }
  16173. get_storage(name) {
  16174. return this.get(name);
  16175. }
  16176. add_storage(name, storage) {
  16177. return this.set(name, storage);
  16178. }
  16179. });
  16180. this.registerType('torch.ScriptFunction', class {
  16181. constructor(name, graph /*, function_creator */) {
  16182. this._name = name;
  16183. this._graph = graph;
  16184. }
  16185. });
  16186. this.registerType('torch.ScriptMethod', class {
  16187. constructor(owner, value) {
  16188. this._owner = owner;
  16189. this._function = value;
  16190. }
  16191. get name() {
  16192. return this._function.name();
  16193. }
  16194. get owner() {
  16195. return this._owner;
  16196. }
  16197. __call__(/* args, kwargs */) {
  16198. throw new python.Error("'torch.ScriptMethod.__call__' not implemented.");
  16199. }
  16200. get graph() {
  16201. return this._function.graph();
  16202. }
  16203. get schema() {
  16204. // return this.function().getSchema();
  16205. throw new python.Error("'torch.ScriptMethod.schema' not implemented.");
  16206. }
  16207. get code() {
  16208. throw new python.Error("'torch.ScriptMethod.code' not implemented.");
  16209. }
  16210. get code_with_constants() {
  16211. throw new python.Error("'torch.ScriptMethod.code_with_constants' not implemented.");
  16212. }
  16213. });
  16214. this.registerType('torch.ScriptObject', class {
  16215. constructor(type) {
  16216. this._typ = type;
  16217. this._ivalue = {};
  16218. }
  16219. static create(type) {
  16220. if (type.is_module()) {
  16221. return new torch.ScriptModule(type);
  16222. }
  16223. return new torch.ScriptObject(type);
  16224. }
  16225. type() {
  16226. return this._typ;
  16227. }
  16228. _type() {
  16229. return this._typ; // torch.ClassType
  16230. }
  16231. __setstate__(state) {
  16232. const [attrs, qualname] = state;
  16233. this._typ = torch._C.getCustomClass(qualname);
  16234. if (!this._typ) {
  16235. throw new python.Error(`Unsupported custom class '${qualname}'.`);
  16236. }
  16237. for (let i = 0; i < this._typ.numAttributes(); i++) {
  16238. const name = this._typ.getAttributeName(i);
  16239. this.__setattr__(name, attrs[i]);
  16240. }
  16241. }
  16242. find_method(basename) {
  16243. for (const fn of this.type().methods()) {
  16244. if (fn.name() === basename) {
  16245. return new torch.ScriptMethod(this /* _value() */, fn);
  16246. }
  16247. }
  16248. return null;
  16249. }
  16250. _get_method(name) {
  16251. const method = this.find_method(name);
  16252. if (method) {
  16253. return method;
  16254. }
  16255. torch._C.TORCH_CHECK(false, `Method '${name}' is not defined.`);
  16256. return null;
  16257. }
  16258. _has_method(name) {
  16259. return this.find_method(name) ? true : false;
  16260. }
  16261. _method_names() {
  16262. return this.type().methods().map((fn) => fn.name());
  16263. }
  16264. __setattr__(name, value) {
  16265. // if (this._type.hasContant(name))
  16266. this._ivalue[name] = value;
  16267. }
  16268. __getattr__(name) {
  16269. return this._ivalue[name];
  16270. }
  16271. hasattr(name) {
  16272. return this._typ.hasAttribute(name) || this._typ.hasConstant(name);
  16273. }
  16274. getattr(name) {
  16275. return this.__getattr__(name);
  16276. }
  16277. _properties() {
  16278. throw new python.Error("'torch.ScriptObject._properties' not implemented.");
  16279. }
  16280. is_weak_compilation_ref() {
  16281. return true; // not implemented
  16282. }
  16283. });
  16284. this.registerType('torch.ScriptModule', class extends torch.ScriptObject {
  16285. constructor(...args) {
  16286. if (args[0] instanceof torch._C.QualifiedName && args[1] instanceof torch.jit.CompilationUnit) {
  16287. const [class_name, cu, shouldMangle] = args;
  16288. super(...torch.ScriptModule.create_module_object(class_name, cu, shouldMangle));
  16289. } else {
  16290. super(...args);
  16291. }
  16292. }
  16293. get qualified_name() {
  16294. return this.type().qualified_name();
  16295. }
  16296. get code_with_constants() {
  16297. const const_map = {};
  16298. const_map.const_mapping = new Map(Object.entries(execution.builtins.CONSTANTS));
  16299. return [null, const_map];
  16300. }
  16301. get graph() {
  16302. if (!this._graph) {
  16303. const fn = this._typ.getMethod('forward');
  16304. this._graph = fn.graph();
  16305. }
  16306. return this._graph;
  16307. }
  16308. static create_module_object(class_name, cu, shouldMangle) {
  16309. shouldMangle = shouldMangle || false;
  16310. if (!class_name.prefix()) {
  16311. class_name = new torch._C.QualifiedName('__torch__', class_name.name());
  16312. }
  16313. if (shouldMangle && cu.get_class(class_name)) {
  16314. class_name = cu.mangle(class_name);
  16315. }
  16316. const cls = torch.ClassType.create(class_name, cu, true);
  16317. cu.register_type(cls);
  16318. return [cls, cu];
  16319. }
  16320. register_module(name, module) {
  16321. this.type().addOrCheckAttribute(name, module.type());
  16322. this.__setattr__(name, module); // _ivalue()->setAttr(name, module._ivalue());
  16323. }
  16324. register_buffer(name, v) {
  16325. this.type().addOrCheckAttribute(name, torch.TensorType.get(), false, true);
  16326. this.__setattr__(name, v); // _ivalue()->setAttr(name, std::move(v));
  16327. }
  16328. register_parameter(name, v, is_buffer) {
  16329. this.type().addOrCheckAttribute(name, torch.TensorType.get(), !is_buffer, is_buffer);
  16330. this.__setattr__(name, v); // _ivalue()->setAttr(name, std::move(v));
  16331. }
  16332. register_attribute(name, t, v, is_param, is_buffer) {
  16333. this.type().addOrCheckAttribute(name, t, is_param, is_buffer);
  16334. // _ivalue()->setAttr(name, v);
  16335. }
  16336. });
  16337. this.registerType('torch.ModuleDict', class {
  16338. constructor(mod) {
  16339. this._module = mod;
  16340. }
  16341. items() {
  16342. const result = new Map();
  16343. const type = this._module.type();
  16344. for (let i = 0; i < type.numAttributes(); i++) {
  16345. const k = type.getAttributeName(i);
  16346. const t = type.getAttribute(i);
  16347. if (t && t.is_module()) {
  16348. result.set(k, this._module.__getattr__(k));
  16349. }
  16350. }
  16351. return result;
  16352. }
  16353. });
  16354. this.registerType('torch.ParameterDict', class {
  16355. constructor(mod) {
  16356. this._module = mod;
  16357. }
  16358. items() {
  16359. const result = new Map();
  16360. const type = this._module.type();
  16361. for (let i = 0; i < type.numAttributes(); i++) {
  16362. if (type.is_parameter(i)) {
  16363. const k = type.getAttributeName(i);
  16364. const v = this._module.__getattr__(k);
  16365. if (v instanceof torch.Tensor) {
  16366. result.set(k, v);
  16367. }
  16368. }
  16369. }
  16370. return result;
  16371. }
  16372. });
  16373. this.registerType('torch.BufferDict', class {
  16374. constructor(mod) {
  16375. this._module = mod;
  16376. }
  16377. items() {
  16378. const result = new Map();
  16379. const type = this._module.type();
  16380. for (let i = 0; i < type.numAttributes(); i++) {
  16381. if (type.is_buffer(i)) {
  16382. const t = type.getAttribute(i);
  16383. if (t.isSubtypeOf(torch.TensorType.get())) {
  16384. const k = type.getAttributeName(i);
  16385. const v = this._module.__getattr__(k);
  16386. result.set(k, v);
  16387. }
  16388. }
  16389. }
  16390. return result;
  16391. }
  16392. });
  16393. this.registerType('torch._C.to_ir', class {
  16394. constructor(def, _resolver, self, method) {
  16395. this.method = method;
  16396. this.graph = method.graph();
  16397. this.resolver = _resolver;
  16398. this.integral_constants = new Map();
  16399. this.fp_constants = new Map();
  16400. this.complex_constants = new Map();
  16401. this.exit_blocks = new Set();
  16402. this._typeParser = new torch._C.ScriptTypeParser(this.resolver);
  16403. this._loop_status = 'NOT_IN_LOOP';
  16404. this.environment_stack = null;
  16405. this._def_stack = [];
  16406. this._temp_name_count = 0;
  16407. torch._C.AT_ASSERT(this.resolver);
  16408. this.pushFrame(this.graph.block(), true);
  16409. if (self && def && def.args.args.length === 0) {
  16410. throw new python.Error('Method must have a self argument.');
  16411. }
  16412. method.setSchema(this.emitDef(def, self, this.graph.block()));
  16413. // torch._C.ReplaceOldOperatorsWithUpgraders(this.graph);
  16414. torch._C.ConvertToSSA(this.graph);
  16415. torch._C.CanonicalizeModifiedLoops(this.graph);
  16416. torch._C.NormalizeOps(this.graph.block());
  16417. torch._C.runCleanupPasses(this.graph);
  16418. }
  16419. pushFrame(b, starts_def) {
  16420. starts_def = starts_def || false;
  16421. if (starts_def) {
  16422. this._def_stack.push({});
  16423. }
  16424. this.environment_stack = new torch._C.Environment(this.method, this.resolver, b, this.environment_stack);
  16425. }
  16426. popFrame(ends_def) {
  16427. const old_frame = this.environment_stack;
  16428. this.environment_stack = this.environment_stack.next;
  16429. if (ends_def) {
  16430. this._def_stack.pop();
  16431. }
  16432. return old_frame;
  16433. }
  16434. emitDef(def, self, block) {
  16435. const schema = this._typeParser.parseSchemaFromDef(def, self !== null);
  16436. if (schema.returns.length === 1) {
  16437. this._def_stack[this._def_stack.length - 1]._declared_return_type = schema.returns[0].type;
  16438. }
  16439. const args = this.emitFormalArguments(def, self, schema, block);
  16440. this.emitStatements(def.body);
  16441. this.handleMaybeNoReturn(def, block);
  16442. const returns = [this.emitOutput(def, schema, block)];
  16443. return new torch.FunctionSchema(def.name, '', args, returns);
  16444. }
  16445. emitFormalArguments(def, self, schema, block) {
  16446. const args = [];
  16447. const params = def.args.args;
  16448. const expected_annotation_size = self ? def.args.args.length - 1 : def.args.args.length;
  16449. if (schema.arguments.length !== expected_annotation_size) {
  16450. throw new python.Error('Invalid formal arguments.');
  16451. }
  16452. let it = 0;
  16453. if (self) {
  16454. const param = params[it];
  16455. const name = param.arg;
  16456. const new_input = block.addInput().setDebugName(name);
  16457. this.environment_stack.setSugaredVar(param.range(), name, self.makeSugared(new_input), null);
  16458. args.push(new torch.Argument(name, new_input.type()));
  16459. it++;
  16460. }
  16461. const shouldDeriveType = this.shouldDeriveSetStateType(def, schema);
  16462. let arg_annotation_idx = 0;
  16463. for (; it < params.length; it++) {
  16464. const param = params[it];
  16465. const name = param.arg;
  16466. const new_input = block.addInput();
  16467. if (torch._C.meaningfulName(name)) {
  16468. new_input.setDebugName(name);
  16469. }
  16470. let arg = schema.arguments[arg_annotation_idx++];
  16471. if (shouldDeriveType) {
  16472. if (schema.arguments.length === 1) {
  16473. throw new python.Error('Invalid schema.');
  16474. }
  16475. const inferredStateType = this.getTypeForSetStateArg(def, self);
  16476. arg = arg.cloneWithType(inferredStateType);
  16477. }
  16478. args.push(arg);
  16479. new_input.setType(arg.type);
  16480. this.environment_stack.setVar(param.range(), name, new_input);
  16481. }
  16482. return args;
  16483. }
  16484. emitOutput(range, schema, block) {
  16485. const ret_type = this._def_stack[this._def_stack.length - 1]._merged_return_type;
  16486. const placeholder_return = this.graph.insertNode(this.graph.createUninitialized(ret_type)).output();
  16487. block.registerOutput(placeholder_return);
  16488. return new torch.Argument('', this._def_stack[this._def_stack.length - 1]._merged_return_type);
  16489. }
  16490. emitStatements(stmts) {
  16491. for (let i = 0; i < stmts.length; i++) {
  16492. const stmt = stmts[i];
  16493. if (stmt instanceof ast.If) {
  16494. this.emitIf(stmt);
  16495. } else if (stmt instanceof ast.While) {
  16496. this.emitWhile(stmt);
  16497. } else if (stmt instanceof ast.For) {
  16498. this.emitFor(stmt);
  16499. } else if (stmt instanceof ast.Assign) {
  16500. this.emitAssignment(stmt);
  16501. } else if (stmt instanceof ast.AnnAssign) {
  16502. this.emitAssignment(stmt);
  16503. } else if (stmt instanceof ast.Expr) {
  16504. this.emitSugaredExpr(stmt.value, 0);
  16505. } else if (stmt instanceof ast.Return) {
  16506. this.emitReturn(stmt);
  16507. } else if (stmt instanceof ast.Pass) {
  16508. // pass
  16509. } else if (stmt instanceof ast.With) {
  16510. this.emitWith(stmt);
  16511. } else {
  16512. throw new python.Error(`Unrecognized statement kind '${stmt.__class__.__name__}'.`);
  16513. }
  16514. if (this.exit_blocks.has(this.environment_stack.block())) {
  16515. return;
  16516. }
  16517. }
  16518. }
  16519. emitWith(stmt) {
  16520. const targets = stmt.items;
  16521. const entered = [];
  16522. for (const target of targets) {
  16523. const e = target.context_expr;
  16524. const rhs = this.emitExpr(e);
  16525. const n = this.graph.insertNode(this.graph.create('prim::Enter', [rhs]));
  16526. entered.push(rhs);
  16527. if (rhs.type() instanceof torch.ClassType === false) {
  16528. throw new python.Error('With item expression must return an object.');
  16529. }
  16530. const rhsClass = rhs.type();
  16531. const enterMethod = rhsClass.findMethod('__enter__');
  16532. const exitMethod = rhsClass.findMethod('__exit__');
  16533. if (!enterMethod || !exitMethod) {
  16534. throw new python.Error('Object returned by with item expression does not define __enter__ and __exit__ methods.');
  16535. }
  16536. const enterSchema = enterMethod.getSchema();
  16537. if (enterSchema.arguments.length !== 1) {
  16538. throw new python.Error('__enter__ must have only one argument and one return value.');
  16539. }
  16540. const exitSchema = exitMethod.getSchema();
  16541. if (exitSchema.arguments.length === 4) {
  16542. for (let i = 1; i < 4; i++) {
  16543. if (exitSchema.arguments[i].type !== torch.AnyType.get()) {
  16544. throw new python.Error('Argument of __exit__ must have Any type.');
  16545. }
  16546. }
  16547. } else {
  16548. throw new python.Error('__exit__ must have four arguments');
  16549. }
  16550. n.output(0).setType(enterSchema.returns[0].type);
  16551. if (target.optional_vars) {
  16552. throw new python.Error('Not implemented.');
  16553. // Var i = target.var().get();
  16554. // this.environment_stack.setVar(i.range(), i.name().name(), n.output(0));
  16555. }
  16556. }
  16557. this.emitStatements(stmt.body);
  16558. while (entered.length > 0) {
  16559. const input = entered.pop();
  16560. const n = this.graph.create('prim::Exit');
  16561. this.graph.insertNode(n);
  16562. n.addInput(input);
  16563. }
  16564. }
  16565. emitLoopCommon(range, emit_body, iter_val, targets, cond) {
  16566. let max_trip_count_val = null;
  16567. if (iter_val === null) {
  16568. max_trip_count_val = torch._C.materializeConstant(Number.MAX_SAFE_INTEGER /*std::numeric_limits<int64_t>::max()*/, this.graph, range, this.integral_constants);
  16569. } else {
  16570. max_trip_count_val = iter_val.len(range, this.method);
  16571. }
  16572. const n = this.graph.insertNode(this.create('prim::Loop', range, 0));
  16573. const body_block = n.addBlock();
  16574. {
  16575. const condition_block = n.addBlock();
  16576. this.pushFrame(condition_block);
  16577. let out = null;
  16578. if (cond) {
  16579. const insert = new torch._C.WithInsertPoint(condition_block);
  16580. out = this.emitToBool(cond.range(), this.emitExpr(cond));
  16581. insert.dispose();
  16582. } else {
  16583. const insert = new torch._C.WithInsertPoint(n);
  16584. out = this.graph.insertConstant(true, range);
  16585. insert.dispose();
  16586. }
  16587. condition_block.registerOutput(out);
  16588. this.popFrame();
  16589. }
  16590. n.addInput(max_trip_count_val);
  16591. const loop_guard = new torch._C.WithLoopStatus(this, 'IN_LOOP');
  16592. const trip_count = body_block.addInput().setType(torch.IntType.get());
  16593. {
  16594. this.pushFrame(body_block);
  16595. const guard = new torch._C.WithInsertPoint(body_block);
  16596. if (iter_val !== null && targets) {
  16597. const cur_elem = iter_val.getitem(range, this.method, trip_count).asValue(range, this.method);
  16598. const sv = new torch._C.SimpleValue(cur_elem);
  16599. const target_exprs = targets;
  16600. this.validateAssignLhsExpr(target_exprs, range);
  16601. if (target_exprs.length > 1) {
  16602. throw new python.Error('Not implemented.');
  16603. // const tl = torch.TupleLiteral.create(range, target_exprs);
  16604. // target_exprs = ListExpr.create(range, [tl]);
  16605. }
  16606. this.emitExprsAssign(target_exprs, [sv], range, /*n_binders=*/1);
  16607. }
  16608. emit_body();
  16609. this.popFrame();
  16610. guard.dispose();
  16611. }
  16612. loop_guard.dispose();
  16613. }
  16614. emitFor(...args) {
  16615. if (args.length === 1 && args[0] instanceof ast.For) {
  16616. const [stmt] = args;
  16617. const emit_body = () => this.emitStatements(stmt.body);
  16618. this.emitFor(stmt.target, stmt.iter, stmt.range(), emit_body);
  16619. } else if (args.length === 4) {
  16620. const [targets, itrs, loc, emit_body] = args;
  16621. if (itrs instanceof ast.Tuple) {
  16622. throw new python.Error('List of iterables is not supported currently.');
  16623. }
  16624. const sv = this.emitSugaredExpr(itrs, 1);
  16625. const iterable = sv.iter(loc, this.method);
  16626. if (iterable.shouldEmitUnrolled()) {
  16627. this.emitUnrolledLoop(loc, emit_body, iterable, targets);
  16628. } else {
  16629. this.emitLoopCommon(loc, emit_body, iterable, [targets], null);
  16630. }
  16631. } else {
  16632. throw new python.Error('Not implemented.');
  16633. }
  16634. }
  16635. emitWhile(stmt) {
  16636. const cond = stmt.test;
  16637. const emit_body = () => this.emitStatements(stmt.body);
  16638. this.emitLoopCommon(stmt.range(), emit_body, null, [], cond);
  16639. }
  16640. emitIsInstance(obj, classinfo) {
  16641. const lhs_val = this.emitExpr(obj);
  16642. const lhs_types = [];
  16643. const rhs_types = [];
  16644. const gather_rhs = (expr) => {
  16645. if (expr instanceof ast.Tuple) {
  16646. for (const e of expr.elts) {
  16647. gather_rhs(e);
  16648. }
  16649. return;
  16650. }
  16651. const type = this._typeParser.parseTypeFromExpr(expr);
  16652. rhs_types.push(type);
  16653. };
  16654. lhs_types.push(lhs_val.type());
  16655. gather_rhs(classinfo);
  16656. torch._C.standardizeVectorForUnion(lhs_types);
  16657. torch._C.standardizeVectorForUnion(rhs_types);
  16658. let refinement = new torch._C.RefinementSet([], []);
  16659. let unified_true = null;
  16660. let unified_false = null;
  16661. const isinstance_types = [];
  16662. const not_isinstance_types = [];
  16663. let true_refinements = [];
  16664. let false_refinements = [];
  16665. let all_lhs_subtype_some_rhs = true;
  16666. for (const lhs_type of lhs_types) {
  16667. if (lhs_type === torch.AnyType.get()) {
  16668. isinstance_types.push(...rhs_types);
  16669. not_isinstance_types.push(torch.AnyType.get());
  16670. if (isinstance_types.length !== 1 || isinstance_types[0] !== torch.AnyType.get()) {
  16671. all_lhs_subtype_some_rhs = false;
  16672. }
  16673. break;
  16674. }
  16675. const get_smaller_type = (t1, t2) => {
  16676. if (t1.isSubtypeOf(t2)) {
  16677. return t1;
  16678. } else if (t2.isSubtypeOf(t1)) {
  16679. return t2;
  16680. }
  16681. return null;
  16682. };
  16683. let found_refinement = null;
  16684. for (const rhs_type of rhs_types) {
  16685. const maybe_smaller_type = get_smaller_type(lhs_type, rhs_type);
  16686. if (!maybe_smaller_type) {
  16687. continue;
  16688. } else if (maybe_smaller_type === lhs_type) {
  16689. found_refinement = lhs_type;
  16690. } else if (maybe_smaller_type === rhs_type) {
  16691. found_refinement = found_refinement ? torch._C.unifyTypes(found_refinement, rhs_type) : rhs_type;
  16692. }
  16693. }
  16694. if (found_refinement) {
  16695. if (found_refinement === lhs_type) {
  16696. all_lhs_subtype_some_rhs &= true;
  16697. }
  16698. isinstance_types.push(found_refinement);
  16699. } else {
  16700. not_isinstance_types.push(lhs_type);
  16701. all_lhs_subtype_some_rhs = false;
  16702. }
  16703. }
  16704. if (isinstance_types.length > 0) {
  16705. unified_true = torch._C.unifyTypeList(isinstance_types, null, /*default_to_union=*/true);
  16706. }
  16707. if (obj instanceof ast.Name && unified_true) {
  16708. const ident = obj.id;
  16709. true_refinements = [new torch._C.Refinement(ident, unified_true)];
  16710. }
  16711. if (not_isinstance_types.length > 0) {
  16712. unified_false = torch._C.unifyTypeList(not_isinstance_types, null, /*default_to_union=*/true);
  16713. }
  16714. if (obj instanceof ast.Name && unified_false) {
  16715. const ident = obj.id;
  16716. false_refinements = [new torch._C.Refinement(ident, unified_false)];
  16717. }
  16718. refinement = new torch._C.RefinementSet(true_refinements, false_refinements);
  16719. const is_statically_false = isinstance_types.length === 0;
  16720. if (all_lhs_subtype_some_rhs) {
  16721. return new torch._C.CondValue(this.graph, obj.range(), true, refinement);
  16722. }
  16723. if (is_statically_false) {
  16724. return new torch._C.CondValue(this.graph, obj.range(), false, refinement);
  16725. }
  16726. const result = this.graph.insertNode(this.graph.createIsInstance(lhs_val, rhs_types)).output();
  16727. return new torch._C.CondValue(result, refinement, null);
  16728. }
  16729. emitIf(stmt) {
  16730. const cond_value = this.emitCondExpr(stmt.test);
  16731. this.emitIfElseBlocks(stmt.range(), cond_value, stmt.body, stmt.orelse);
  16732. }
  16733. emitCondExpr(expr) {
  16734. /*
  16735. switch (expr.kind()) {
  16736. case TK_AND:
  16737. case TK_OR: {
  16738. const binop = BinOp(expr);
  16739. return emitShortCircuitLogical(
  16740. binop.range(), binop.lhs(), binop.rhs(), expr.kind() == TK_OR);
  16741. }
  16742. case TK_NOT: {
  16743. CondValue v = emitCondExpr(Expr(expr.tree().trees()[0]));
  16744. Value* result = emitBuiltinCall(
  16745. expr.range(), *graph, aten::__not__, {v.value()}, {});
  16746. std::optional<bool> static_if;
  16747. if (v.staticIf()) {
  16748. static_if = !*v.staticIf();
  16749. }
  16750. return CondValue(result, v.refinements().Not(), static_if);
  16751. } break;
  16752. case TK_IS:
  16753. case TK_ISNOT: {
  16754. // meta programming on AST for is/is not cases and emit branches base on
  16755. const cond_op = BinOp(expr);
  16756. Value* lhs_val = emitExpr(cond_op.lhs());
  16757. Value* rhs_val = emitExpr(cond_op.rhs());
  16758. const lhs_none = canBeNone(lhs_val);
  16759. const rhs_none = canBeNone(rhs_val);
  16760. // Dispatch logic (A: ALWAYS, N: NEVER, M: MAYBE):
  16761. // AA, -> statically IS always holds, IS_NOT never holds
  16762. // AN , NA-> statically IS_NOT always holds, IS never holds
  16763. // MA, MM, MN, NM, NN, AM -> cannot prove anything statically
  16764. bool its_is = expr.kind() == TK_IS;
  16765. if (lhs_none == ALWAYS && rhs_none == ALWAYS) {
  16766. return CondValue(*graph, expr.range(), its_is, {});
  16767. } else if (
  16768. (lhs_none == ALWAYS && rhs_none == NEVER) ||
  16769. (lhs_none == NEVER && rhs_none == ALWAYS)) {
  16770. // lhs_val/rhs_val with A/M: only emit never_none_branch
  16771. return CondValue(*graph, expr.range(), !its_is, {});
  16772. } else {
  16773. const kind = getNodeKind(expr.kind(), expr.get()->trees().size());
  16774. Value* cond_value = emitBuiltinCall(
  16775. expr.get()->range(),
  16776. *method.graph(),
  16777. kind,
  16778. {lhs_val, rhs_val},
  16779. {});
  16780. const refinements = RefinementSet(findIsNoneRefinements(
  16781. cond_op.lhs(), lhs_val, cond_op.rhs(), rhs_val, expr.kind()));
  16782. return CondValue(cond_value, refinements, null);
  16783. }
  16784. } break;
  16785. */
  16786. if (expr instanceof ast.UnaryOp) {
  16787. throw new python.Error('Not implemented.');
  16788. }
  16789. if (expr instanceof ast.Call) {
  16790. const apply = expr;
  16791. const callee = expr.func;
  16792. if (callee instanceof ast.Name) {
  16793. if (callee.id === 'isinstance') {
  16794. this.checkApplyNumInputs(apply, 2);
  16795. return this.emitIsInstance(apply.args[0], apply.args[1]);
  16796. }
  16797. if (callee.id === 'hasattr') {
  16798. this.checkApplyNumInputs(apply, 2);
  16799. return this.emitHasAttr(apply.args[0], apply.args[1]);
  16800. }
  16801. const sv = this.emitSugaredExpr(callee, 1);
  16802. if (sv instanceof torch._C.SpecialFormValue) {
  16803. if (sv.form() === 'prim::isinstance') {
  16804. this.checkApplyNumInputs(apply, 2);
  16805. return this.emitIsInstance(apply.inputs()[0], apply.inputs()[1]);
  16806. }
  16807. }
  16808. }
  16809. }
  16810. const expr_out = this.emitToBool(expr, this.emitExpr(expr));
  16811. let static_if = null;
  16812. const kind = expr_out.node().kind();
  16813. if (kind === 'aten::is_scripting') {
  16814. static_if = true;
  16815. } else if (kind === 'aten::has_torch_function') {
  16816. static_if = false;
  16817. }
  16818. const maybe_ivalue = torch._C.toIValue(expr_out);
  16819. if (maybe_ivalue) {
  16820. static_if = maybe_ivalue.toBool();
  16821. }
  16822. return new torch._C.CondValue(expr_out, new torch._C.RefinementSet([], []), static_if);
  16823. }
  16824. emitIfElseBlocks(loc, cond_value, trueBranch, falseBranch) {
  16825. if (cond_value.staticIf() !== null) {
  16826. if (cond_value.staticIf()) {
  16827. this.insertRefinements(loc, cond_value.refinements());
  16828. this.emitStatements(trueBranch);
  16829. } else {
  16830. this.insertRefinements(loc, cond_value.refinements().Not());
  16831. this.emitStatements(falseBranch);
  16832. }
  16833. return;
  16834. }
  16835. const n = this.graph.insertNode(this.create('prim::If', loc, 0));
  16836. n.addInput(cond_value.value());
  16837. const true_block = n.addBlock();
  16838. const false_block = n.addBlock();
  16839. const save_true = this.emitSingleIfBranch(true_block, trueBranch, cond_value.refinements());
  16840. const save_false = this.emitSingleIfBranch(false_block, falseBranch, cond_value.refinements().Not());
  16841. const true_exits = this.exit_blocks.has(true_block);
  16842. const false_exits = this.exit_blocks.has(false_block);
  16843. if (true_exits && false_exits) {
  16844. this.exit_blocks.add(n.owningBlock());
  16845. }
  16846. const mutated_variables = new Set();
  16847. for (const v of save_true.definedVariables()) {
  16848. const insert = new torch._C.WithInsertPoint(false_block);
  16849. if (save_false.findInAnyFrame(v) || false_exits) {
  16850. mutated_variables.add(v);
  16851. } else {
  16852. this.environment_stack.setVariableTypeError(v, () => 'Value is not defined in the false branch.');
  16853. }
  16854. insert.dispose();
  16855. }
  16856. for (const v of save_false.definedVariables()) {
  16857. const insert = new torch._C.WithInsertPoint(true_block);
  16858. if (save_true.findInAnyFrame(v) || true_exits) {
  16859. mutated_variables.add(v);
  16860. } else {
  16861. this.environment_stack.setVariableTypeError(v, () => 'Value is not defined in the true branch.');
  16862. }
  16863. insert.dispose();
  16864. }
  16865. for (const x of mutated_variables) {
  16866. let tv = null;
  16867. let fv = null;
  16868. {
  16869. const insert = new torch._C.WithInsertPoint(true_block);
  16870. if (!true_exits) {
  16871. tv = save_true.getVar(x, loc);
  16872. }
  16873. insert.dispose();
  16874. }
  16875. {
  16876. const insert = new torch._C.WithInsertPoint(false_block);
  16877. if (!false_exits) {
  16878. fv = save_false.getVar(x, loc);
  16879. }
  16880. insert.dispose();
  16881. }
  16882. if (true_exits && false_exits) {
  16883. continue;
  16884. } else if (true_exits) {
  16885. tv = this.graph.createUninitialized(fv.type()).insertBefore(true_block.return_node()).output();
  16886. this.graph.createStore(x, tv).insertBefore(true_block.return_node());
  16887. } else if (false_exits) {
  16888. fv = this.graph.createUninitialized(tv.type()).insertBefore(false_block.return_node()).output();
  16889. this.graph.createStore(x, fv).insertBefore(false_block.return_node());
  16890. }
  16891. const maybe_sugared_x = this.environment_stack.findInAnyFrame(x);
  16892. let full_type = null;
  16893. if (maybe_sugared_x) {
  16894. const maybe_simple = torch._C.asSimple(maybe_sugared_x);
  16895. if (maybe_simple) {
  16896. full_type = maybe_simple.type();
  16897. }
  16898. }
  16899. const default_to_union = full_type && (full_type instanceof torch.UnionType || full_type instanceof torch.OptionalType || full_type instanceof torch.NumberType);
  16900. const unified = torch._C.unifyTypes(tv.type(), fv.type(), /*default_to_union=*/default_to_union);
  16901. if (!unified) {
  16902. if (save_true.findInParentFrame(x) || save_false.findInParentFrame(x)) {
  16903. throw new python.Error('Type mismatch.');
  16904. } else {
  16905. this.environment_stack.setVariableTypeError(x, () => 'Type mismatch.');
  16906. continue;
  16907. }
  16908. }
  16909. this.environment_stack.setType(x, unified);
  16910. }
  16911. }
  16912. emitSingleIfBranch(b, branch, refinements) {
  16913. this.pushFrame(b);
  16914. const guard = new torch._C.WithInsertPoint(b);
  16915. this.insertRefinements(branch, refinements);
  16916. this.emitStatements(branch);
  16917. const frame = this.popFrame();
  16918. guard.dispose();
  16919. return frame;
  16920. }
  16921. create(kind, loc, n_outputs) {
  16922. return this.graph.create(kind, n_outputs).setSourceRange(loc);
  16923. }
  16924. refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint_ptr, all_candidates, match_repr, src, type_match, do_if_match, do_if_anytype, is_dict_constructor) {
  16925. is_dict_constructor = is_dict_constructor || false;
  16926. if (refined_type_hint_ptr._ instanceof torch.UnionType) {
  16927. const candidate_types = refined_type_hint_ptr._.containedTypes().filter((type_ptr) => type_match(type_ptr));
  16928. if (!is_dict_constructor && candidate_types.length === 0) {
  16929. throw new python.Error("No matching types found in Union type annotation.");
  16930. } else if (candidate_types.length === 1) {
  16931. [refined_type_hint_ptr._] = candidate_types;
  16932. } else {
  16933. all_candidates._ = candidate_types;
  16934. }
  16935. } else if (refined_type_hint_ptr._ instanceof torch.OptionalType) {
  16936. refined_type_hint_ptr._ = refined_type_hint_ptr._.getElementType();
  16937. }
  16938. if (is_dict_constructor) {
  16939. return;
  16940. }
  16941. if (all_candidates._.length === 0) {
  16942. if (type_match(refined_type_hint_ptr._)) {
  16943. do_if_match();
  16944. } else if (refined_type_hint_ptr._.kind() === 'AnyType') {
  16945. do_if_anytype();
  16946. } else {
  16947. throw new python.Error('Invalid annotation type.');
  16948. }
  16949. }
  16950. }
  16951. emitToBool(loc, v) {
  16952. let out = null;
  16953. const bool_cast = this.environment_stack.getSugaredVar('bool', loc);
  16954. out = torch._C.asSimple(bool_cast.call(loc, this.method, [new torch._C.NamedValue(v)], [], 0));
  16955. if (!out) {
  16956. throw new python.Error('Could not cast value to bool.');
  16957. }
  16958. if (!out.type().isSubtypeOf(torch.BoolType.get())) {
  16959. throw new python.Error('Expected a bool expression for condition.');
  16960. }
  16961. return out;
  16962. }
  16963. emitUnaryOp(tree, magicMethod, opSymbol) {
  16964. const inputs = [tree.operand];
  16965. const named_values = this.getNamedValues(inputs, /*maybe_unpack=*/false);
  16966. const val = torch._C.asSimple(torch._C.makeMagic(magicMethod, new torch._C.BuiltinFunction(opSymbol, null)).call(tree.range(), this.method, named_values, [], 0));
  16967. if (val.node().kind() !== opSymbol) {
  16968. return val;
  16969. }
  16970. const maybe_out_stack = torch._C.runNodeIfInputsAreConstant(val.node());
  16971. if (!maybe_out_stack) {
  16972. return val;
  16973. }
  16974. torch._C.TORCH_INTERNAL_ASSERT(maybe_out_stack.length === 1);
  16975. return this.graph.insertConstant(maybe_out_stack[0], tree);
  16976. }
  16977. emitAssignment(stmt) {
  16978. if (stmt instanceof ast.AnnAssign) {
  16979. return this.emitSingleAssignment(stmt);
  16980. }
  16981. if (stmt.targets.length === 1) {
  16982. const entries = Object.entries(stmt).filter(([key]) => key !== 'targets' && key !== 'value' && key !== 'ctx');
  16983. const assign = new ast.AnnAssign(stmt.targets[0], null, stmt.value, stmt.targets[0] instanceof ast.Name);
  16984. for (const [key, value] of entries) {
  16985. assign[key] = value;
  16986. }
  16987. return this.emitSingleAssignment(assign);
  16988. }
  16989. if (stmt.targets.length <= 1) {
  16990. throw new python.Error('Invalid assignment.');
  16991. }
  16992. throw new python.Error('Not implemented.');
  16993. /*
  16994. const tmp_name = this.createTempName('$tmp_assign_');
  16995. this.environment_stack.setSugaredVar(stmt.value, tmp_name, this.emitSugaredExpr(stmt.value, 1), annotated_type=null);
  16996. const ident = new ast.Name(tmp_name);
  16997. for (const expr of lhs_list) {
  16998. const assign = new ast.Assign(targets, value, ctx);
  16999. this.emitSingleAssignment(Assign.create(stmt,
  17000. List<Expr>.create(expr.range(), [expr]),
  17001. Maybe<Expr>::create(stmt.rhs().range(), ident),
  17002. Maybe<Expr>::create(stmt.range())));
  17003. }
  17004. */
  17005. }
  17006. emitSingleAssignment(stmt) {
  17007. torch._C.AT_ASSERT(stmt instanceof ast.AnnAssign);
  17008. const rhs = stmt.value;
  17009. const lhs = stmt.target;
  17010. if (lhs instanceof ast.Name) {
  17011. let type = null;
  17012. if (stmt.annotation) {
  17013. type = this._typeParser.parseTypeFromExpr(stmt.annotation);
  17014. }
  17015. const rhs_sugared_val = this.emitSugaredExpr(rhs, 1, type);
  17016. // BC HACK
  17017. this.environment_stack.setSugaredVar(stmt.range(), lhs.id, rhs_sugared_val, /*annotated_type=*/type);
  17018. } else if (lhs instanceof ast.Tuple) {
  17019. this.emitTupleAssign(lhs, rhs);
  17020. } else if (lhs instanceof ast.Attribute) {
  17021. this.emitSelectAssign(lhs, rhs, null, stmt.range());
  17022. } else {
  17023. throw new python.Error('Unexpected expression on left-hand side of assignment.');
  17024. }
  17025. }
  17026. emitSelectAssign(lhs, rhs, type, loc) {
  17027. if (!rhs) {
  17028. throw new python.Error('Expected RHS for assignment.');
  17029. }
  17030. let type_hint = null;
  17031. if (type) {
  17032. type_hint = this._typeParser.parseTypeFromExpr(type);
  17033. }
  17034. const lhsObject = this.emitSugaredExpr(lhs.value, 1);
  17035. const rhsValue = this.emitSugaredExpr(rhs, 1, type_hint).asValue(rhs.range(), this.method);
  17036. lhsObject.setAttr(loc, this.method, lhs.attr, rhsValue);
  17037. }
  17038. emitTupleAssign(...args) {
  17039. if (args.length === 2) {
  17040. const [tl, rhs] = args;
  17041. let n_binders = tl.elts.length;
  17042. const starred_unpack = this.validateAssignLhsExpr(tl.elts, tl);
  17043. if (starred_unpack) {
  17044. n_binders--;
  17045. }
  17046. const output = this.emitSugaredExpr(rhs, n_binders);
  17047. this.emitTupleAssign(tl, output, rhs.range(), n_binders, starred_unpack);
  17048. } else if (args.length === 5) {
  17049. const [tl, rhs_output, rhs_loc, n_binders, starred_unpack] = args;
  17050. const outputs = rhs_output.asTuple(rhs_loc, this.method, starred_unpack ? null : n_binders);
  17051. if (outputs.length < n_binders) {
  17052. throw new python.Error('Not enough values to unpack.');
  17053. }
  17054. if (outputs.length > n_binders && !starred_unpack) {
  17055. throw new python.Error('Too many values to unpack.');
  17056. }
  17057. this.emitExprsAssign(tl.elts, outputs, rhs_loc, n_binders);
  17058. } else {
  17059. throw new python.Error('Not implemented.');
  17060. }
  17061. }
  17062. emitExprsAssign(lhs_exprs, outputs /*, rhs_loc, n_binders */) {
  17063. let i = 0;
  17064. for (const assignee of lhs_exprs) {
  17065. if (assignee instanceof ast.Subscript) {
  17066. throw new python.Error('Not implemented.');
  17067. /*
  17068. this.emitSubscriptAssign(
  17069. rhs_loc,
  17070. Subscript(assignee),
  17071. NamedValue(rhs_loc, outputs.at(i).asValue(rhs_loc, method)));
  17072. i++;
  17073. */
  17074. } else if (assignee instanceof ast.Name) {
  17075. this.environment_stack.setSugaredVar(assignee.range(), assignee.id, outputs[i], /*annotated_type=*/null);
  17076. i++;
  17077. } else if (assignee instanceof ast.Starred) {
  17078. throw new python.Error('Not implemented.');
  17079. /*
  17080. const var = Starred(assignee).expr();
  17081. if (var.kind() != TK_VAR) {
  17082. throw(
  17083. ErrorReport(var) << 'Cannot pack a tuple into a non-variable');
  17084. }
  17085. size_t n_matched = outputs.size() - n_binders;
  17086. ArrayRef<std::shared_ptr<SugaredValue>> outputs_ref = outputs;
  17087. const values = fmap(
  17088. outputs_ref.slice(i, n_matched),
  17089. [&](const std::shared_ptr<SugaredValue>& v) {
  17090. return v.asValue(assignee.range(), method);
  17091. });
  17092. const tup = graph.insertNode(graph.createTuple(values)).output();
  17093. environment_stack.setVar(var.range(), Var(var).name().name(), tup);
  17094. i += n_matched;
  17095. */
  17096. } else if (assignee instanceof ast.Tuple) {
  17097. throw new python.Error('Not implemented.');
  17098. /*
  17099. // recursively emit tuple assignments on tuple literal input
  17100. TupleLiteral sub_tl = TupleLiteral(assignee);
  17101. size_t sub_n_binders = sub_tl.inputs().length;
  17102. bool sub_starred_unpack =
  17103. validateAssignLhsExpr(sub_tl.inputs(), sub_tl.range());
  17104. if (sub_starred_unpack)
  17105. sub_n_binders--;
  17106. emitTupleAssign(
  17107. sub_tl,
  17108. outputs.at(i),
  17109. rhs_loc,
  17110. sub_n_binders,
  17111. sub_starred_unpack);
  17112. i++;
  17113. */
  17114. } else if (assignee instanceof ast.Attribute) {
  17115. throw new python.Error('Not implemented.');
  17116. /*
  17117. emitSelectAssign(assignee, outputs.at(i), rhs_loc);
  17118. i++;
  17119. */
  17120. } else {
  17121. throw new python.Error('Unexpected expression on left-hand side of assignment.');
  17122. }
  17123. }
  17124. }
  17125. emitReturn(stmt) {
  17126. let declared_return_type = this._def_stack[this._def_stack.length - 1]._declared_return_type;
  17127. let actual_return = this.emitExpr(stmt.value, declared_return_type);
  17128. if (declared_return_type) {
  17129. if (!(actual_return.type().isSubtypeOf(torch.TensorType.get()) && actual_return.type().isSubtypeOf(torch.NoneType.get()))) {
  17130. actual_return = torch._C.tryConvertToType(stmt, this.graph, declared_return_type, actual_return, /*allow_conversions=*/true);
  17131. }
  17132. if (!actual_return.type().isSubtypeOf(declared_return_type)) {
  17133. throw new python.Error(`Invalid return type.`);
  17134. }
  17135. } else {
  17136. declared_return_type = this._def_stack[this._def_stack.length - 1]._merged_return_type;
  17137. if (!declared_return_type) {
  17138. declared_return_type = actual_return.type();
  17139. }
  17140. const merged_return_type = torch._C.unifyTypes(declared_return_type, actual_return.type());
  17141. if (!merged_return_type) {
  17142. throw new python.Error(`Invalid return type.`);
  17143. }
  17144. declared_return_type = merged_return_type;
  17145. }
  17146. this._def_stack[this._def_stack.length - 1]._merged_return_type = declared_return_type;
  17147. if (declared_return_type === torch.AnyType.get() && actual_return.type() !== torch.AnyType.get()) {
  17148. actual_return = this.graph.insertUncheckedCast(actual_return, declared_return_type);
  17149. }
  17150. this.graph.insertNode(this.graph.create('prim::ReturnStmt', [actual_return], 0));
  17151. this.exit_blocks.add(this.environment_stack.block());
  17152. }
  17153. getNamedValues(trees, maybe_unpack) {
  17154. const values = [];
  17155. for (const tree of trees) {
  17156. if (maybe_unpack && tree instanceof ast.Starred) {
  17157. throw new python.Error('Starred argument not supported.');
  17158. } else {
  17159. values.push(new torch._C.NamedValue(this.emitExpr(tree)));
  17160. }
  17161. }
  17162. return values;
  17163. }
  17164. getValues(trees, maybe_unpack) {
  17165. return this.getNamedValues(trees, maybe_unpack).map((value) => value.value(this.graph));
  17166. }
  17167. emitExpr(tree, type_hint) {
  17168. type_hint = type_hint || null;
  17169. let out_val = this.emitSugaredExpr(tree, 1, type_hint).asValue(tree, this.method);
  17170. if (type_hint === torch.AnyType.get() && out_val.type() !== torch.AnyType.get()) {
  17171. out_val = this.graph.insertUncheckedCast(out_val, type_hint);
  17172. }
  17173. return out_val;
  17174. }
  17175. emitSugaredExpr(tree, n_binders, type_hint) {
  17176. if (tree instanceof ast.Name) { // TK_VAR
  17177. return this.environment_stack.getSugaredVar(tree.id);
  17178. } else if (tree instanceof ast.Attribute) {
  17179. const sv = this.emitSugaredExpr(tree.value, 1);
  17180. return sv.attr(tree.range(), this.method, tree.attr);
  17181. } else if (tree instanceof ast.Call) { // TK_APPLY
  17182. return this.emitApplyExpr(tree, n_binders, type_hint);
  17183. } if (tree instanceof ast.Subscript) {
  17184. return this.emitSubscript(tree, type_hint);
  17185. }
  17186. return new torch._C.SimpleValue(this.emitSimpleExpr(tree, type_hint));
  17187. }
  17188. emitApplyExpr(apply, n_binders, type_hint) {
  17189. type_hint = type_hint || null;
  17190. const sv = this.emitSugaredExpr(apply.func, 1);
  17191. const loc = apply.func.range();
  17192. if (sv instanceof torch._C.SpecialFormValue) {
  17193. return this.emitApplySpecialForm(sv.form(), apply, sv, type_hint);
  17194. }
  17195. const args = this.getNamedValues(apply.args, true);
  17196. const kwargs = this.emitAttributes(apply.keywords);
  17197. return sv.call(loc, this.method, args, kwargs, n_binders);
  17198. }
  17199. emitAttributes(attributes) {
  17200. return attributes.map((attr) => new torch._C.NamedValue(attr.range(), attr.arg, this.emitExpr(attr.value)));
  17201. }
  17202. emitApplySpecialForm(form, apply, sv, type_hint) {
  17203. switch (form) {
  17204. case 'prim::fork': {
  17205. throw new python.Error('Not implemented.');
  17206. }
  17207. case 'prim::awaitable': {
  17208. throw new python.Error('Not implemented.');
  17209. }
  17210. case 'prim::annotate': {
  17211. this.checkApplyNumInputs(apply, 2);
  17212. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  17213. let expr = torch._C.tryConvertToType(apply.range(), this.graph, type, this.emitExpr(apply.args[1], type), /*allow_conversions=*/true);
  17214. if (!expr.type().isSubtypeOf(type)) {
  17215. throw new python.Error('Invalid expression type.');
  17216. }
  17217. if ((type instanceof torch.OptionalType || (type instanceof torch.UnionType && type.expect(torch.UnionType).canHoldType(torch.NoneType.get()))) && expr.type().isSubtypeOf(torch.NoneType.get())) {
  17218. const none = this.graph.createNone();
  17219. none.output().setType(type);
  17220. this.graph.insertNode(none);
  17221. expr = none.output();
  17222. }
  17223. return new torch._C.SimpleValue(expr);
  17224. }
  17225. case 'prim::unchecked_cast': {
  17226. this.checkApplyNumInputs(apply, 2);
  17227. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  17228. let v = this.emitExpr(apply.args[1]);
  17229. if (v.node().kind() !== 'prim::unchecked_cast' || v.type() !== type) {
  17230. v = this.graph.insertUncheckedCast(v, type);
  17231. }
  17232. return new torch._C.SimpleValue(v);
  17233. }
  17234. case 'prim::GetAttr': {
  17235. this.checkApplyNumInputsRange(apply, 2, 3);
  17236. const obj = this.emitSugaredExpr(apply.args[0], 1);
  17237. if (apply.args[1] instanceof ast.Constant === false || typeof apply.args[1].value !== 'string') {
  17238. throw new python.Error('Invalid argument.');
  17239. }
  17240. const name = apply.args[1].value;
  17241. if (apply.args.length === 2) {
  17242. return obj.attr(apply, this.method, name);
  17243. } else if (obj.hasAttr(apply, this.method, name)) {
  17244. return obj.attr(apply, this.method, name);
  17245. }
  17246. return this.emitSugaredExpr(apply.inputs()[2], 1);
  17247. }
  17248. case 'prim::Uninitialized': {
  17249. this.checkApplyNumInputs(apply, 1);
  17250. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  17251. const out = this.graph.insertNode(this.graph.createUninitialized(type)).setSourceRange(apply.range());
  17252. return new torch._C.SimpleValue(out.output());
  17253. }
  17254. case 'prim::TupleConstruct': {
  17255. throw new python.Error('Not implemented.');
  17256. }
  17257. case 'prim::isinstance': {
  17258. this.checkApplyNumInputs(apply, 2);
  17259. const result = this.emitIsInstance(apply.args[0], apply.args[1]);
  17260. return new torch._C.SimpleValue(result.value());
  17261. }
  17262. case 'prim::tolist': {
  17263. const value = apply.func.value;
  17264. const operand = this.emitSugaredExpr(value, 1);
  17265. if (!type_hint) {
  17266. throw new python.Error('Expected type hint for result of tolist().');
  17267. }
  17268. return new torch._C.SimpleValue(this.graph.insertToList(operand.asValue(value.range(), this.method), type_hint));
  17269. }
  17270. case 'prim::HasAttr': {
  17271. throw new python.Error('Not implemented.');
  17272. }
  17273. case 'prim::CreateObject': {
  17274. if (apply.args.length !== 1) {
  17275. throw python.Error('Only one argument to __new__ allowed.');
  17276. }
  17277. const arg = this.emitSugaredExpr(apply.args[0], 1);
  17278. if (arg instanceof torch._C.ClassValue === false) {
  17279. throw python.Error('Expected class value as argument to __new__.');
  17280. }
  17281. const class_arg = arg;
  17282. const createNode = this.graph.insertNode(this.graph.createObject(class_arg._type));
  17283. createNode.setSourceRange(apply.range());
  17284. return new torch._C.SimpleValue(createNode.output());
  17285. }
  17286. case 'prim::range': {
  17287. const input_vals = this.getValues(apply.args, true);
  17288. return new torch._C.RangeValue(apply.range(), this.method, input_vals);
  17289. }
  17290. case 'prim::enumerate': {
  17291. throw new python.Error('Not implemented.');
  17292. }
  17293. case 'prim::zip': {
  17294. throw new python.Error('Not implemented.');
  17295. }
  17296. case 'prim::list': {
  17297. throw new python.Error('Not implemented.');
  17298. }
  17299. case 'prim::dict': {
  17300. throw new python.Error('Not implemented.');
  17301. }
  17302. case 'aten::index': {
  17303. throw new python.Error('Not implemented.');
  17304. }
  17305. default: {
  17306. throw new python.Error(`Unsupported special form '${sv.from()}'.`);
  17307. }
  17308. }
  17309. }
  17310. emitSimpleExpr(tree, type_hint) {
  17311. if (tree instanceof ast.Constant) {
  17312. if (tree.value === true) {
  17313. return this.graph.insertConstant(new torch._C.IValue(true, 'Bool'), tree.range());
  17314. } else if (tree.value === false) {
  17315. return this.graph.insertConstant(new torch._C.IValue(false, 'Bool'), tree.range());
  17316. } else if (tree.value === null) {
  17317. return this.graph.insertConstant(new torch._C.IValue(), tree.range());
  17318. } else if (typeof tree.value === 'string') {
  17319. return this.emitStringLiteral(tree);
  17320. }
  17321. return this.emitConst(tree);
  17322. } else if (tree instanceof ast.List) {
  17323. return this.emitListLiteral(tree, type_hint);
  17324. } else if (tree instanceof ast.UnaryOp && tree.op instanceof ast.USub && tree.operand instanceof ast.Name && tree.operand.id === 'inf') {
  17325. return this.emitConst(new ast.Constant(-Infinity, 'float'));
  17326. } else if (tree instanceof ast.UnaryOp && tree.op instanceof ast.USub && tree.operand instanceof ast.Constant) {
  17327. const c = tree.operand;
  17328. if (c.type === 'complex') {
  17329. return this.emitConst(new ast.Constant(new builtins.complex(-c.value.real, -c.value.imag), 'complex'));
  17330. }
  17331. return this.emitConst(new ast.Constant(-c.value, c.type));
  17332. } else if (tree instanceof ast.UnaryOp && tree.op instanceof ast.USub) {
  17333. return this.emitUnaryOp(tree, '__neg__', 'aten::neg');
  17334. } else if (tree instanceof ast.BinOp) {
  17335. return this.emitBinaryOp(tree);
  17336. } else if (tree instanceof ast.Dict) {
  17337. return this.emitDictLiteral(tree, type_hint);
  17338. } else if (tree instanceof ast.Tuple) {
  17339. const values = this.getValues(tree.elts, /*maybe_unpack=*/true);
  17340. return this.graph.insertNode(this.graph.createTuple(values)).output();
  17341. }
  17342. throw new python.Error(`Simple expression '${tree.__class__.__name__}' not implemented.`);
  17343. }
  17344. getNodeKind(kind /*, ninputs */) {
  17345. if (kind instanceof ast.Add) {
  17346. return 'aten::add';
  17347. } else if (kind instanceof ast.Sub) {
  17348. return 'aten::sub';
  17349. } else if (kind instanceof ast.Mult) {
  17350. return 'aten::mul';
  17351. }
  17352. /*
  17353. case TK_UNARY_MINUS: return 'aten::neg';
  17354. case TK_POW: return 'aten::pow';
  17355. case '@': return 'aten::matmul';
  17356. case TK_STARRED: return 'prim::Starred';
  17357. case '/': return 'aten::div';
  17358. case '%': return 'aten::remainder';
  17359. case TK_NE: return 'aten::ne';
  17360. case TK_EQ: return 'aten::eq';
  17361. case '<': return 'aten::lt';
  17362. case '>': return 'aten::gt';
  17363. case TK_LE: return 'aten::le';
  17364. case TK_GE: return 'aten::ge';
  17365. case TK_AND: return 'aten::__and__';
  17366. case TK_OR: return 'aten::__or__';
  17367. case TK_IS: return 'aten::__is__';
  17368. case TK_ISNOT: return 'aten::__isnot__';
  17369. case TK_NOT: return 'aten::__not__';
  17370. case TK_FLOOR_DIV: return 'aten::floordiv';
  17371. case TK_LSHIFT: return 'aten::__lshift__';
  17372. case TK_RSHIFT: return 'aten::__rshift__';
  17373. case '&': return 'aten::__and__';
  17374. case '|': return 'aten::__or__';
  17375. case '^': return 'aten::__xor__';
  17376. case TK_IN: return 'aten::__contains__';
  17377. */
  17378. throw new python.Error(`Unknown kind '${kind.__class__.__name__}'.`);
  17379. }
  17380. getOperatorOverload(kind /*, ninputs */) {
  17381. if (kind instanceof ast.Add) {
  17382. return '__add__';
  17383. } else if (kind instanceof ast.Sub) {
  17384. return '__sub__';
  17385. } else if (kind instanceof ast.Mult) {
  17386. return '__mul__';
  17387. }
  17388. /*
  17389. case TK_UNARY_MINUS: return "__neg__";
  17390. case '~': return "__invert__";
  17391. case TK_POW: return "__pow__";
  17392. case '/': return "__truediv__";
  17393. case '%': return "__mod__";
  17394. case TK_NE: return "__ne__";
  17395. case TK_EQ: return "__eq__";
  17396. case '<': return "__lt__";
  17397. case '>': return "__gt__";
  17398. case TK_LE: return "__le__";
  17399. case TK_GE: return "__ge__";
  17400. case '&': return "__and__";
  17401. case '|': return "__or__";
  17402. case '^': return "__xor__";
  17403. case TK_IN: return "__contains__";
  17404. case TK_LSHIFT: return "__lshift__";
  17405. case TK_RSHIFT: return "__rshift__";
  17406. */
  17407. throw new python.Error(`Unknown kind '${kind.__class__.__name__}'.`);
  17408. }
  17409. emitBinaryOp(tree) {
  17410. const inputs = [tree.left, tree.right];
  17411. const kind = this.getNodeKind(tree.op, inputs.length);
  17412. const overload = this.getOperatorOverload(tree.op, inputs.length);
  17413. const named_values = this.getNamedValues(inputs, /*maybe_unpack=*/false);
  17414. if (tree.op instanceof ast.In) {
  17415. // std::iter_swap(named_values.begin() + 0, named_values.begin() + 1);
  17416. throw new python.Error('Not implemented.');
  17417. }
  17418. if (named_values[0].type() instanceof torch.TupleType &&
  17419. named_values[1].type() instanceof torch.TupleType &&
  17420. kind === 'aten::add') {
  17421. const first_tuple = torch._C.createTupleUnpack(named_values[0].value(this.graph)).vec();
  17422. const second_tuple = torch._C.createTupleUnpack(named_values[1].value(this.graph)).vec();
  17423. first_tuple.insert(first_tuple.end(), second_tuple.begin(), second_tuple.end());
  17424. return this.graph.insertNode(this.graph.createTuple(first_tuple)).output();
  17425. }
  17426. return torch._C.asSimple(torch._C.makeMagic(overload, new torch._C.BuiltinFunction(kind, null)).call(tree.range(), this.method, named_values, [], 0));
  17427. }
  17428. emitDictLiteral(dl, type_hint) {
  17429. const key_trees = dl.keys;
  17430. const value_trees = dl.values;
  17431. torch._C.AT_ASSERT(key_trees.length === value_trees.length);
  17432. const keys = [];
  17433. const values = [];
  17434. let rhs_value_type = null;
  17435. for (let i = 0; i < key_trees.length; i++) {
  17436. keys.push(this.emitExpr(key_trees[i]));
  17437. values.push(this.emitExpr(value_trees[i]));
  17438. if (i === 0) {
  17439. rhs_value_type = values[i].type();
  17440. } else {
  17441. if (keys[i - 1].type().kind() !== keys[i].type().kind()) {
  17442. throw new python.Error('Dict keys must contain only a single type.');
  17443. }
  17444. rhs_value_type = torch._C.unifyTypes(rhs_value_type, values[i].type(), /*default_to_union=*/true);
  17445. }
  17446. }
  17447. const refined_type_hint = { _: type_hint };
  17448. const annotated_union_type = type_hint && type_hint.isUnionType() ? type_hint : null;
  17449. const all_candidates = { _: [] };
  17450. const default_refined_type_hint_setter = () => {
  17451. if (keys.length === 0) {
  17452. refined_type_hint._ = torch.DictType.create(torch.StringType.get(), torch.TensorType.get());
  17453. } else {
  17454. refined_type_hint._ = torch.DictType.create(keys[0].type(), rhs_value_type);
  17455. if (rhs_value_type instanceof torch.UnionType) {
  17456. throw new python.Error('Dict values consist of heterogeneous types.');
  17457. }
  17458. }
  17459. };
  17460. if (type_hint) {
  17461. const type_match = (t) => t instanceof torch.DictType;
  17462. this.refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint, all_candidates, 'Dict', dl, type_match, () => [], default_refined_type_hint_setter);
  17463. if (all_candidates._.length > 0 && values.length === 0) {
  17464. throw new python.Error('Cannot assign an empty dict.');
  17465. }
  17466. } else {
  17467. default_refined_type_hint_setter();
  17468. }
  17469. torch._C.TORCH_INTERNAL_ASSERT(all_candidates._.length > 0 || refined_type_hint._);
  17470. if (values.length > 0) {
  17471. if (all_candidates._.length > 0) {
  17472. this.refineAndSetDictTypeHintFromCandidatesVector(all_candidates, type_hint, refined_type_hint, keys[0].type(), rhs_value_type, dl);
  17473. }
  17474. if (refined_type_hint._.getKeyType() !== keys[0].type()) {
  17475. throw new python.Error('Type annotation does not match key type.');
  17476. }
  17477. if (!rhs_value_type.isSubtypeOf(refined_type_hint._.getValueType())) {
  17478. throw new python.Error('Type annotation does not match value type.');
  17479. }
  17480. }
  17481. let result = this.graph.insertNode(this.graph.createDict(refined_type_hint._.getKeyType(), refined_type_hint._.getValueType(), keys, values));
  17482. if (annotated_union_type) {
  17483. const n = this.graph.insertNode(this.graph.create('prim::unchecked_cast', [result.output()]));
  17484. n.output().setType(annotated_union_type);
  17485. result = n;
  17486. }
  17487. return result.output();
  17488. }
  17489. emitStringLiteral(c) {
  17490. return torch._C.insertConstant(this.graph, c.value, c.range());
  17491. }
  17492. emitConst(c) {
  17493. if (c.type === 'int') {
  17494. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Int'), this.graph, c.range(), this.integral_constants);
  17495. } else if (c.type === 'complex') {
  17496. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Complex'), this.graph, c.range(), this.complex_constants);
  17497. } else if (c.type === 'float') {
  17498. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Double'), this.graph, c.range(), this.fp_constants);
  17499. }
  17500. throw new python.Error(`Unsupported constant type.`);
  17501. }
  17502. emitListLiteral(ll, type_hint) {
  17503. type_hint = type_hint || null;
  17504. const values = this.getValues(ll.elts, true);
  17505. if (values.length === 0 && type_hint === null) {
  17506. throw new python.Error('Not implemented.');
  17507. }
  17508. let inferred_elem_type = torch.TensorType.get();
  17509. const refined_type_hint = { _: type_hint };
  17510. const annotated_union_type = refined_type_hint._ && refined_type_hint._.isUnionType() ? refined_type_hint._ : null;
  17511. const all_candidates = { _: [] };
  17512. if (refined_type_hint._) {
  17513. const do_if_type_match = () => {
  17514. inferred_elem_type = refined_type_hint._.expect(torch.ListType).getElementType();
  17515. };
  17516. const type_match = (t) => t.isSubtypeOf(torch.Type.get('AnyListType'));
  17517. this.refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint, all_candidates, 'List', ll, type_match, do_if_type_match, do_if_type_match);
  17518. if (all_candidates._.length > 0 && values.len === 0) {
  17519. throw new python.Error('Cannot assign an empty list.');
  17520. }
  17521. }
  17522. if (values.length !== 0) {
  17523. const types = values.map((v) => v.type());
  17524. const elem_type_hint = refined_type_hint._ && refined_type_hint._.kind() === 'ListType' ? refined_type_hint._.getElementType() : null;
  17525. const unified_elem_type = torch._C.unifyTypeList(types, null /*nowhere*/, /*default_to_union=*/true, elem_type_hint);
  17526. if (!refined_type_hint._ && unified_elem_type.kind() === 'UnionType') {
  17527. throw new python.Error('Not implemented.');
  17528. }
  17529. if (all_candidates._.length === 0 && refined_type_hint._ && !unified_elem_type.isSubtypeOf(inferred_elem_type)) {
  17530. throw new python.Error('Not implemented.');
  17531. }
  17532. if (all_candidates._.length !== 0) {
  17533. this.refineAndSetListTypeHintFromCandidatesVector(all_candidates, type_hint, refined_type_hint._, unified_elem_type, ll);
  17534. inferred_elem_type = refined_type_hint._.expect(torch.ListType).getElementType();
  17535. }
  17536. if (!refined_type_hint._) {
  17537. inferred_elem_type = unified_elem_type;
  17538. }
  17539. }
  17540. let result = this.graph.insertNode(this.graph.createList(inferred_elem_type, values));
  17541. if (annotated_union_type) {
  17542. const n = this.graph.insertNode(this.graph.create('prim::unchecked_cast', [result.output()]));
  17543. n.output().setType(annotated_union_type);
  17544. result = n;
  17545. }
  17546. return result.output();
  17547. }
  17548. insertRefinements(loc, ref) {
  17549. for (const r of ref.activeRefinements()) {
  17550. const v = this.environment_stack.getVar(r.identifier(), loc);
  17551. const new_v = this.graph.insertUncheckedCast(v, r.type());
  17552. this.environment_stack.setVar(loc, r.identifier(), new_v);
  17553. }
  17554. }
  17555. shouldDeriveSetStateType(def, schema) {
  17556. const noTypeAnnotations = schema.arguments.every((arg) => arg.is_inferred_type());
  17557. const shouldInfer = def.name === '__setstate__' && noTypeAnnotations;
  17558. if (!shouldInfer) {
  17559. return false;
  17560. }
  17561. if (def.name !== '__setstate__' && def.args.args.length !== 2) {
  17562. throw new python.Error(`Invalid '__setstate' method.`);
  17563. }
  17564. return true;
  17565. }
  17566. checkApplyNumInputs(apply, expected_inputs) {
  17567. if (apply.args.length !== expected_inputs) {
  17568. throw new python.Error('Invalid number of arguments.');
  17569. }
  17570. if (apply.keywords.length > 0) {
  17571. throw new python.Error('Invalid number of keyword arguments.');
  17572. }
  17573. }
  17574. checkApplyNumInputsRange(apply, min_expected_inputs, max_expected_inputs) {
  17575. const position_arg_size = apply.args.length;
  17576. if (position_arg_size < min_expected_inputs || position_arg_size > max_expected_inputs) {
  17577. throw new python.Error('Invalid number of arguments.');
  17578. }
  17579. if (apply.keywords.length > 0) {
  17580. throw new python.Error('Invalid number of keyword arguments.');
  17581. }
  17582. }
  17583. validateAssignLhsExpr(lhs /*, r */) {
  17584. let num_normal_assign = 0;
  17585. let num_starred = 0;
  17586. for (const assignee of lhs) {
  17587. if (assignee instanceof ast.Name || assignee instanceof ast.Subscript || assignee instanceof ast.Tuple || assignee instanceof ast.Attribute) {
  17588. num_normal_assign++;
  17589. } else if (assignee instanceof ast.Starred) {
  17590. num_starred++;
  17591. } else {
  17592. throw new python.Error('Assignment must be a variable, subscript, or starred expression.');
  17593. }
  17594. }
  17595. if (num_starred > 1) {
  17596. throw new python.Error('Only one starred expression is allowed.');
  17597. }
  17598. if (num_starred > 0 && num_normal_assign === 0) {
  17599. throw new python.Error('Invalid starred expression.');
  17600. }
  17601. return num_starred;
  17602. }
  17603. createTempName(prefix) {
  17604. return `${prefix}${this._temp_name_count++}`;
  17605. }
  17606. handleMaybeNoReturn(def, block) {
  17607. const decl_ret = this._def_stack[this._def_stack.length - 1]._declared_return_type;
  17608. if (this.exit_blocks.size === 0) {
  17609. if (decl_ret && decl_ret !== torch.NoneType.get()) {
  17610. throw new python.Error('Function was not annotated as having type None, but does not return along all paths.');
  17611. }
  17612. const b = new torch._C.WithInsertPoint(block.nodes().end());
  17613. // this.emitReturn(Return::create(def.range(), Expr(Compound::create(TK_NONE, def.range(), {}))));
  17614. b.dispose();
  17615. throw new python.Error("'torch._C.to_ir.handleMaybeNoReturn' not implemented.");
  17616. } else if (this._def_stack[this._def_stack.length - 1]._merged_return_type === null) {
  17617. this._def_stack[this._def_stack.length - 1]._merged_return_type = decl_ret === null ? torch.NoneType.get() : decl_ret;
  17618. }
  17619. }
  17620. getAdjTupleIndex(loc, tuple_type, input_index, allow_out_of_bounds) {
  17621. let adj_index = input_index;
  17622. const tuple_len = tuple_type.elements().length;
  17623. if (input_index < 0) {
  17624. adj_index = tuple_len + input_index;
  17625. }
  17626. if (!allow_out_of_bounds && (adj_index >= tuple_len || adj_index < 0)) {
  17627. throw new python.Error(`Tuple index out of range at ${loc}.`);
  17628. }
  17629. return adj_index;
  17630. }
  17631. emitTupleIndex(loc, tuple_val, idx_val) {
  17632. const tuple_typ = tuple_val.type();
  17633. const elems = tuple_typ.elements();
  17634. let output_type = null;
  17635. if (idx_val.type() !== torch.IntType.get()) {
  17636. throw new python.Error('Tuple index must be an integer.');
  17637. }
  17638. const idx = torch._C.toIValue(idx_val);
  17639. if (idx) {
  17640. const adj_index = this.getAdjTupleIndex(loc, tuple_typ, idx.toInt(), /*allow_out_of_bounds*/ false);
  17641. output_type = elems[adj_index];
  17642. } else {
  17643. if (elems.length === 0 || !torch._C.convertibleToList(tuple_typ, torch.ListType.create(elems[0]))) {
  17644. throw new python.Error('Cannot index into a tuple with a non-integer literal.');
  17645. }
  17646. [output_type] = elems;
  17647. }
  17648. return this.graph.insertNode(this.graph.createTupleIndex(tuple_val, idx_val, output_type)).output();
  17649. }
  17650. getSliceInd(idx_val, loc) {
  17651. const ivalue = torch._C.toIValue(idx_val);
  17652. if (ivalue && ivalue.isInt()) {
  17653. return ivalue.toInt();
  17654. }
  17655. throw new python.Error(`Tuple slice indices must be integer constants at '${loc}'.`);
  17656. }
  17657. emitTupleSlice(loc, tuple_val, tuple_args) {
  17658. const tuple_type = tuple_val.value(this.graph).type().expect(torch.TupleType);
  17659. const tuple_len = tuple_type.elements().length;
  17660. const [beg_val, end_val, step] = tuple_args;
  17661. let step_size = 1;
  17662. if (step) {
  17663. const val = torch._C.toIValue(step.value(this.graph));
  17664. torch._C.TORCH_CHECK(val.isInt());
  17665. step_size = val.toInt();
  17666. }
  17667. let beg = { _: Number.MAX_SAFE_INTEGER }; // std::numeric_limits<int64_t>::max();
  17668. if (beg_val) {
  17669. beg = { _: this.getAdjTupleIndex(loc, tuple_type, this.getSliceInd(beg_val.value(this.graph), loc), true) };
  17670. }
  17671. let end = { _: Number.MAX_SAFE_INTEGER }; // std::numeric_limits<int64_t>::max();
  17672. if (end_val) {
  17673. end = { _: this.getAdjTupleIndex(loc, tuple_type, this.getSliceInd(end_val.value(this.graph), loc), true) };
  17674. }
  17675. const num_values = torch._C.slice_indices_adjust(tuple_len, beg, end, step_size);
  17676. return this.graph.insertNode(this.graph.createTupleSlice(tuple_val.value(this.graph), beg._, step_size, num_values)).output();
  17677. }
  17678. emitSliceOp(loc, sliceable, dim, start, end, step) {
  17679. const args = [];
  17680. args.push(new torch._C.NamedValue(loc, 'self', sliceable));
  17681. if (dim) {
  17682. torch._C.AT_ASSERT(sliceable.type().isSubtypeOf(torch.TensorType.get()));
  17683. args.emplace_back(new torch._C.NamedValue(dim));
  17684. } else {
  17685. torch._C.AT_ASSERT(!sliceable.type().isSubtypeOf(torch.TensorType.get()));
  17686. }
  17687. if (sliceable.type() instanceof torch.TupleType) {
  17688. const tuple_args = [];
  17689. tuple_args.push(start ? new torch._C.NamedValue(start) : null);
  17690. tuple_args.push(end ? new torch._C.NamedValue(end) : null);
  17691. tuple_args.push(step ? new torch._C.NamedValue(step) : null);
  17692. return this.emitTupleSlice(loc, args[0], tuple_args);
  17693. }
  17694. if (!step) {
  17695. step = this.graph.insertConstant(1, loc);
  17696. }
  17697. args.push(new torch._C.NamedValue(loc, 'start', start));
  17698. args.push(new torch._C.NamedValue(loc, 'end', end));
  17699. args.push(new torch._C.NamedValue(loc, 'step', step));
  17700. return this.emitBuiltinCall(loc, this.graph, 'aten::slice', args, []);
  17701. }
  17702. emitSlice(loc, input, dim, slice) {
  17703. let start = null;
  17704. let end = null;
  17705. let step = null;
  17706. if (slice.lower) {
  17707. start = this.emitExpr(slice.lower);
  17708. }
  17709. if (slice.upper) {
  17710. end = this.emitExpr(slice.upper);
  17711. }
  17712. if (slice.step) {
  17713. step = this.emitExpr(slice.step);
  17714. }
  17715. return this.emitSliceOp(loc, input, dim, start, end, step);
  17716. }
  17717. emitBasicSlice(loc, sliceable, subscript_exprs) {
  17718. torch._C.AT_ASSERT(subscript_exprs instanceof ast.Slice);
  17719. const slice_exp = subscript_exprs;
  17720. let maybe_dim = null;
  17721. if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  17722. maybe_dim = this.graph.insertConstant(0, loc);
  17723. }
  17724. return this.emitSlice(loc, sliceable, maybe_dim, slice_exp);
  17725. }
  17726. emitSubscript(subscript, type_hint) {
  17727. type_hint = type_hint === undefined ? null : type_hint;
  17728. const sv = this.emitSugaredExpr(subscript.value, 1);
  17729. const subscript_exprs = subscript.slice;
  17730. const range = subscript.range();
  17731. const val_range = subscript.value;
  17732. if (subscript_exprs instanceof ast.Tuple) {
  17733. return new torch._C.SimpleValue(this.emitMultidimSlicing(range, sv.asValue(val_range, this.method), subscript_exprs));
  17734. }
  17735. if (subscript_exprs instanceof ast.Slice) {
  17736. if (sv.kind() === 'module') {
  17737. const s_tuple_val = sv.asTupleValue(val_range, this.method).asValue(val_range, this.method);
  17738. const [slice] = subscript_exprs;
  17739. const tuple_args = [];
  17740. if (slice.start().present()) {
  17741. const begin = new torch._C.NamedValue(val_range, 'begin', this.emitExpr(slice.start().get()));
  17742. tuple_args.push(begin);
  17743. } else {
  17744. tuple_args.push(null);
  17745. }
  17746. if (slice.end().present()) {
  17747. const end = new torch._C.NamedValue(val_range, 'end', this.emitExpr(slice.end().get()));
  17748. tuple_args.push(end);
  17749. } else {
  17750. tuple_args.push(null);
  17751. }
  17752. if (slice.step().present()) {
  17753. const step = new torch._C.NamedValue(val_range, 'step', this.emitExpr(slice.step().get()));
  17754. tuple_args.push(step);
  17755. } else {
  17756. tuple_args.push(null);
  17757. }
  17758. const tupleSliceValue = this.emitTupleSlice(val_range, s_tuple_val, tuple_args);
  17759. return new torch._C.SimpleValue(tupleSliceValue);
  17760. }
  17761. return new torch._C.SimpleValue(this.emitBasicSlice(range, sv.asValue(val_range, this.method), subscript_exprs));
  17762. }
  17763. const sliceable = sv.asValue(val_range, this.method);
  17764. const subscript_sv = this.emitSugaredExpr(subscript_exprs, 1);
  17765. if (subscript_sv instanceof torch._C.SliceValue) {
  17766. const slice_value = subscript_sv;
  17767. let dim = null;
  17768. if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  17769. dim = this.method.graph().insertConstant(0, val_range);
  17770. }
  17771. const sliced = this.emitSliceOp(val_range, sliceable, dim, slice_value.start(), slice_value.stop(), slice_value.step());
  17772. return new torch._C.SimpleValue(sliced);
  17773. }
  17774. const idx = subscript_sv.asValue(val_range, this.method);
  17775. if (sliceable.type() instanceof torch.TupleType) {
  17776. return new torch._C.SimpleValue(this.emitTupleIndex(range, sv.asValue(val_range, this.method), idx));
  17777. } else if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  17778. return new torch._C.SimpleValue(this.emitMultidimSlicing(range, sliceable, subscript_exprs));
  17779. }
  17780. return sv.getitem(range, this.method, idx, type_hint);
  17781. }
  17782. });
  17783. this.registerType('torch.jit.CompilationUnit', class {
  17784. constructor() {
  17785. this._functions = new Map();
  17786. this._classes = new Map();
  17787. }
  17788. register_type(namedType) {
  17789. this._classes.set(namedType.annotation_str, namedType);
  17790. }
  17791. register_function(fn) {
  17792. const name = fn.qualname().qualifiedName();
  17793. torch._C.TORCH_CHECK(!this._functions.has(name));
  17794. this._functions.set(name, fn);
  17795. return fn;
  17796. }
  17797. define(...args) {
  17798. if (Array.isArray(args[1])) {
  17799. const [prefix, properties, propResolvers, definitions, defResolvers, self, shouldMangle, operator_set_version] = args;
  17800. torch._C.TORCH_INTERNAL_ASSERT(definitions.length === defResolvers.length);
  17801. torch._C.TORCH_INTERNAL_ASSERT(properties.length === propResolvers.length);
  17802. const functions = [];
  17803. const function_table = new Map();
  17804. const record_function = (fn) => {
  17805. function_table.set(fn.name(), fn);
  17806. functions.push(fn);
  17807. this.register_function(fn);
  17808. };
  17809. for (let i = 0; i < properties.length; i++) {
  17810. const property_fns = this.define_property(prefix, properties[i], propResolvers[i], self, function_table, shouldMangle);
  17811. const getter_fn = property_fns.getGetter();
  17812. const setter_fn = property_fns.getSetter();
  17813. record_function(getter_fn);
  17814. if (setter_fn) {
  17815. record_function(setter_fn);
  17816. }
  17817. }
  17818. for (let i = 0; i < definitions.length; i++) {
  17819. const fn = this.define(prefix, definitions[i], defResolvers[i], self, function_table, shouldMangle, 'Method', operator_set_version);
  17820. record_function(fn);
  17821. }
  17822. for (const [name, fn] of function_table) {
  17823. if (name === '__init__') {
  17824. fn.ensure_defined();
  17825. }
  17826. }
  17827. for (const fn of functions) {
  17828. fn.ensure_defined();
  17829. }
  17830. return functions;
  17831. } else if (args[1] instanceof ast.FunctionDef) {
  17832. const [prefix, def, resolver, self, function_table, shouldMangle, type, operator_set_version] = args;
  17833. const _resolver = self ? resolver : new torch._C.FunctionResolver(resolver, function_table);
  17834. const creator = (method) => {
  17835. return new torch._C.to_ir(def, _resolver, self, method);
  17836. };
  17837. let name = prefix ? new torch._C.QualifiedName(prefix, def.name) : new torch._C.QualifiedName(def.name);
  17838. if (shouldMangle && this.find_function(name)) {
  17839. name = this.mangle(name);
  17840. }
  17841. const graph = new torch.Graph();
  17842. graph.set_op_version(operator_set_version);
  17843. const fn = new torch._C.GraphFunction(name, graph, creator);
  17844. fn.__ast__ = def; // remove
  17845. if (self) {
  17846. if (type === 'hook') {
  17847. self.getClassType().addForwardHook(fn);
  17848. } else if (type === 'prehook') {
  17849. self.getClassType().addPreHook(fn);
  17850. } else {
  17851. self.getClassType().addMethod(fn);
  17852. }
  17853. }
  17854. return fn;
  17855. }
  17856. throw new python.Error('Invalid arguments.');
  17857. }
  17858. get_type(name) {
  17859. return this._classes.get(name.qualifiedName());
  17860. }
  17861. get_class(name) {
  17862. return this.get_type(name);
  17863. }
  17864. find_function(name) {
  17865. const key = name.qualifiedName();
  17866. return this._functions.get(key);
  17867. }
  17868. });
  17869. this.registerFunction('torch._C.ConvertToSSA', (graph) => {
  17870. const ctrl = new torch._C.ControlFlowLoadStores();
  17871. ctrl.run(graph);
  17872. const exit_vars = new torch._C.LoopContinuations();
  17873. exit_vars.run(graph);
  17874. torch._C.InlineLoopCondition(graph);
  17875. const erase_loads_stores = new torch._C.EraseLoadStores();
  17876. erase_loads_stores.run(graph);
  17877. torch._C.TransformExits(graph);
  17878. });
  17879. this.registerFunction('torch._C.canonicalizeModifiedLoop', (/* n */) => {
  17880. /*
  17881. LoopView loop(n);
  17882. if (loop.loopType() != LoopView::ModifiedLoop) {
  17883. return;
  17884. }
  17885. const g = n.owningGraph();
  17886. WithInsertPoint node_insert(n);
  17887. const zero = g.insertConstant(0);
  17888. const one = g.insertConstant(1);
  17889. const max_trip_count = loop.maxTripCount();
  17890. const condition = g.insert(aten::gt, {max_trip_count, zero});
  17891. loop.replaceMaxTripCount(g.insertConstant(std::numeric_limits<int64_t>::max()));
  17892. const inp_condition = toIValue(loop.inputCond());
  17893. if (inp_condition == null || inp_condition.toBool() == false) {
  17894. condition = g.insert(aten::__and__, {condition, loop.inputCond()});
  17895. }
  17896. loop.replaceInputCondition(condition);
  17897. n.addOutput().setType(IntType::get());
  17898. WithInsertPoint loop_insert(loop.bodyBlock());
  17899. n.addInput(zero);
  17900. const new_iter = loop.bodyBlock().addInput().setType(IntType::get());
  17901. // unset unique name for jitter, its replacement does not have a name
  17902. loop.currentTripCount().setDebugName('').replaceAllUsesWith(new_iter);
  17903. const inc_iter = g.insert(aten::add, {new_iter, one});
  17904. loop.bodyBlock().registerOutput(inc_iter);
  17905. const less_than_max_trip = g.insert(aten::lt, {inc_iter, max_trip_count});
  17906. const loop_continue = loop.nextCond();
  17907. const new_condition =
  17908. g.insert(aten::__and__, {less_than_max_trip, loop_continue});
  17909. loop.bodyBlock().eraseOutput(0);
  17910. loop.bodyBlock().insertOutput(0, new_condition);
  17911. */
  17912. });
  17913. this.registerFunction('torch._C.canonicalizeModifiedLoops', (block) => {
  17914. for (const n of block.nodes()) {
  17915. for (const b of n.blocks()) {
  17916. torch._C.canonicalizeModifiedLoops(b);
  17917. }
  17918. if (n.kind() === 'prim::Loop') {
  17919. torch._C.canonicalizeModifiedLoop(n);
  17920. }
  17921. }
  17922. });
  17923. this.registerFunction('torch._C.CanonicalizeModifiedLoops', (graph) => {
  17924. torch._C.canonicalizeModifiedLoops(graph.block());
  17925. });
  17926. this.registerType('torch._C.MiniEnvironment', class {
  17927. constructor(b, next) {
  17928. this.next = next || null;
  17929. this.table = new Map();
  17930. }
  17931. setVar(name, value) {
  17932. this.table.set(name, value);
  17933. }
  17934. definedVariables() {
  17935. const result = Array.from(this.table.keys());
  17936. return result.sort();
  17937. }
  17938. findInThisFrame(name) {
  17939. if (this.table.has(name)) {
  17940. return this.table.get(name);
  17941. }
  17942. return null;
  17943. }
  17944. findInAnyFrame(name) {
  17945. /* eslint-disable consistent-this */
  17946. const self = this;
  17947. /* eslint-enable consistent-this */
  17948. for (let runner = self; runner; runner = runner.next) {
  17949. const r = runner.findInThisFrame(name);
  17950. if (r) {
  17951. return r;
  17952. }
  17953. }
  17954. return null;
  17955. }
  17956. });
  17957. this.registerType('torch._C.ValueEnvironment', class extends torch._C.MiniEnvironment {
  17958. });
  17959. this.registerType('torch._C.TypeEnvironment', class extends torch._C.MiniEnvironment {
  17960. });
  17961. this.registerType('torch._C.ControlFlowLoadStores', class {
  17962. constructor() {
  17963. this.environment_stack = null;
  17964. }
  17965. pushFrame(b) {
  17966. this.environment_stack = new torch._C.TypeEnvironment(b, this.environment_stack);
  17967. }
  17968. popFrame() {
  17969. const old_frame = this.environment_stack;
  17970. this.environment_stack = this.environment_stack.next;
  17971. return old_frame;
  17972. }
  17973. addBlockInput(b, type, name) {
  17974. const g = b.owningGraph();
  17975. g.createStore(name, b.addInput(name).setType(type)).insertAfter(b.param_node());
  17976. }
  17977. addBlockOutput(exit_block, type, name) {
  17978. const insert = new torch._C.WithInsertPoint(exit_block);
  17979. const g = exit_block.owningGraph();
  17980. const block_exit = g.insertNode(g.createLoad(name, type)).output();
  17981. exit_block.registerOutput(block_exit);
  17982. insert.dispose();
  17983. }
  17984. addNodeOutput(n, type, name) {
  17985. const out = n.addOutput().setType(type);
  17986. if (torch._C.meaningfulName(name)) {
  17987. out.setDebugName(name);
  17988. }
  17989. const g = n.owningGraph();
  17990. g.createStore(name, out).insertAfter(n);
  17991. }
  17992. addNodeInput(n, type, name) {
  17993. const g = n.owningGraph();
  17994. const inp = g.createLoad(name, type).insertBefore(n).output();
  17995. n.addInput(inp);
  17996. }
  17997. addIfLoadStores(n) {
  17998. const [true_block, false_block] = n.blocks();
  17999. const true_vars = this.addControlFlowLoadStores(true_block);
  18000. const false_vars = this.addControlFlowLoadStores(false_block);
  18001. const mutated_variables = new Set();
  18002. for (const v of true_vars.definedVariables()) {
  18003. if (false_vars.findInAnyFrame(v)) {
  18004. mutated_variables.add(v);
  18005. }
  18006. }
  18007. for (const v of false_vars.definedVariables()) {
  18008. if (true_vars.findInAnyFrame(v)) {
  18009. mutated_variables.add(v);
  18010. }
  18011. }
  18012. for (const x of mutated_variables) {
  18013. const true_type = true_vars.findInAnyFrame(x);
  18014. const false_type = false_vars.findInAnyFrame(x);
  18015. const unified = torch._C.unifyTypes(true_type, false_type, /*default_to_union=*/true);
  18016. this.addBlockOutput(true_block, true_type, x);
  18017. this.addBlockOutput(false_block, false_type, x);
  18018. this.addNodeOutput(n, unified, x);
  18019. }
  18020. }
  18021. addLoopLoadStores(n) {
  18022. const [body_block] = n.blocks();
  18023. const loop_vars = this.addControlFlowLoadStores(body_block);
  18024. for (const name of loop_vars.definedVariables()) {
  18025. const parent_type = this.environment_stack.findInAnyFrame(name);
  18026. if (!parent_type) {
  18027. continue;
  18028. }
  18029. const block_type = loop_vars.findInThisFrame(name);
  18030. const unified_type = torch._C.unifyTypes(parent_type, block_type);
  18031. this.addNodeInput(n, parent_type, name);
  18032. this.addBlockInput(body_block, unified_type, name);
  18033. this.addBlockOutput(body_block, block_type, name);
  18034. this.addNodeOutput(n, unified_type, name);
  18035. }
  18036. }
  18037. addControlFlowLoadStores(block) {
  18038. this.pushFrame(block);
  18039. for (const n of block.nodes()) {
  18040. switch (n.kind()) {
  18041. case 'prim::If': {
  18042. this.addIfLoadStores(n);
  18043. break;
  18044. }
  18045. case 'prim::Loop': {
  18046. this.addLoopLoadStores(n);
  18047. break;
  18048. }
  18049. case 'prim::Closure': {
  18050. for (const b of n.blocks()) {
  18051. this.addControlFlowLoadStores(b);
  18052. }
  18053. break;
  18054. }
  18055. case 'prim::Store': {
  18056. this.environment_stack.setVar(n.s('name'), n.input().type());
  18057. break;
  18058. }
  18059. case 'prim::ComprehensionScope': {
  18060. this.addControlFlowLoadStores(n.blocks().at(0));
  18061. break;
  18062. }
  18063. default: {
  18064. break;
  18065. }
  18066. }
  18067. }
  18068. return this.popFrame();
  18069. }
  18070. run(graph) {
  18071. this.addControlFlowLoadStores(graph.block());
  18072. }
  18073. });
  18074. this.registerType('torch._C.LoopContinuations', class {
  18075. constructor() {
  18076. this._graph = null;
  18077. this._false_val = null;
  18078. this._curr_loop = null;
  18079. }
  18080. assignExitContinuations(block) {
  18081. for (const n of block.nodes()) {
  18082. switch (n.kind()) {
  18083. case 'prim::If': {
  18084. this.assignExitContinuations(n.blocks().at(0));
  18085. this.assignExitContinuations(n.blocks().at(1));
  18086. break;
  18087. }
  18088. case 'prim::Closure': {
  18089. const closure_block = new torch._C.LoopContinuations();
  18090. closure_block.run(n.blocks().at(0));
  18091. break;
  18092. }
  18093. case 'prim::Loop': {
  18094. const prev_loop = this._curr_loop;
  18095. this._curr_loop = n;
  18096. this.assignExitContinuations(n.blocks().at(0));
  18097. this._curr_loop = prev_loop;
  18098. break;
  18099. }
  18100. case 'prim::ContinueStmt': {
  18101. const loop_continuation = this._graph.create('prim::LoopContinuation', 0).insertAfter(n);
  18102. const header_block = loop_continuation.addBlock();
  18103. const [, pre_header] = this._curr_loop.blocks();
  18104. header_block.cloneFrom(pre_header, (v) => v);
  18105. this.InlineBlockBeforeNode(n, header_block);
  18106. loop_continuation.addInput(header_block.outputs()[0]);
  18107. loop_continuation.eraseBlock(0);
  18108. this.addLoopCarriedOutputs(loop_continuation);
  18109. n.destroy();
  18110. break;
  18111. }
  18112. case 'prim::BreakStmt': {
  18113. const loop_exit = this._graph.create('prim::LoopContinuation', 0).insertAfter(n);
  18114. loop_exit.addInput(this._false_val);
  18115. this.addLoopCarriedOutputs(loop_exit);
  18116. n.destroy();
  18117. break;
  18118. }
  18119. default: {
  18120. break;
  18121. }
  18122. }
  18123. }
  18124. }
  18125. run(...args) {
  18126. if (args.length === 1 && args[0] instanceof torch.Graph) {
  18127. const [graph] = args;
  18128. this.run(graph.block());
  18129. } else if (args.length === 1 && args[0] instanceof torch.Block) {
  18130. const [b] = args;
  18131. {
  18132. this._graph = b.owningGraph();
  18133. const guard = new torch._C.WithInsertPoint(b.nodes().front());
  18134. this._false_val = this._graph.insertConstant(false);
  18135. guard.dispose();
  18136. }
  18137. this.assignExitContinuations(b);
  18138. } else {
  18139. throw new python.Error('Not implemented.');
  18140. }
  18141. }
  18142. });
  18143. this.registerType('torch._C.LoopView', class {
  18144. constructor(node) {
  18145. torch._C.AT_ASSERT(node.kind() === 'prim::Loop' || node.kind() === 'onnx::Loop');
  18146. this._node = node;
  18147. }
  18148. bodyBlock() {
  18149. return this._node.blocks().at(0);
  18150. }
  18151. nextCond() {
  18152. return this.bodyBlock().outputs()[0];
  18153. }
  18154. carriedOutputs() {
  18155. return this._node.outputs();
  18156. }
  18157. bodyCarriedInputs() {
  18158. return this.bodyBlock().inputs().slice(1);
  18159. }
  18160. bodyCarriedOutputs() {
  18161. return this.bodyBlock().outputs().slice(1);
  18162. }
  18163. });
  18164. this.registerType('torch._C.WithLoopStatus', class {
  18165. constructor(to_ir, new_status) {
  18166. this._to_ir = to_ir;
  18167. this._prev = this._to_ir._loop_status;
  18168. this._to_ir._loop_status = new_status;
  18169. }
  18170. dispose() {
  18171. this._to_ir._loop_status = this._prev;
  18172. }
  18173. });
  18174. this.registerFunction('torch._C.InlineBlockBeforeNode', (before_node, block) => {
  18175. for (const block_node of block.nodes()) {
  18176. block_node.moveBefore(before_node);
  18177. }
  18178. });
  18179. this.registerFunction('torch._C.inlineLoopCondition', (...args) => {
  18180. if (args.length === 1 && args[0] instanceof torch.Block) {
  18181. const [block] = args;
  18182. for (const n of block.nodes()) {
  18183. for (const b of n.blocks()) {
  18184. torch._C.inlineLoopCondition(b);
  18185. }
  18186. if (n.kind() === 'prim::Loop') {
  18187. torch._C.inlineLoopCondition(n);
  18188. }
  18189. }
  18190. } else if (args.length === 1 && args[0] instanceof torch.Node) {
  18191. const [n] = args;
  18192. const [body_block, pre_header] = n.blocks();
  18193. const temp_block = n.addBlock();
  18194. temp_block.cloneFrom(pre_header, (v) => v);
  18195. torch._C.InlineBlockBeforeNode(n, temp_block);
  18196. n.insertInput(1, temp_block.outputs()[0]);
  18197. n.eraseBlock(2);
  18198. torch._C.InlineBlockBeforeNode(body_block.return_node(), pre_header);
  18199. body_block.return_node().insertInput(0, pre_header.outputs()[0]);
  18200. n.eraseBlock(1);
  18201. } else {
  18202. throw new python.Error('Not implemented.');
  18203. }
  18204. });
  18205. this.registerFunction('torch._C.InlineLoopCondition', (graph) => {
  18206. torch._C.inlineLoopCondition(graph.block());
  18207. });
  18208. this.registerType('torch._C.EraseLoadStores', class {
  18209. pushFrame(b) {
  18210. this.environment_stack = new torch._C.ValueEnvironment(b, this.environment_stack);
  18211. }
  18212. popFrame() {
  18213. const old_frame = this.environment_stack;
  18214. this.environment_stack = this.environment_stack.next;
  18215. return old_frame;
  18216. }
  18217. eraseBlockLoadStores(block) {
  18218. this.pushFrame(block);
  18219. for (const n of block.nodes()) {
  18220. switch (n.kind()) {
  18221. case 'prim::Store': {
  18222. this.environment_stack.setVar(n.s('name'), n.input());
  18223. n.destroy();
  18224. break;
  18225. }
  18226. case 'prim::Load': {
  18227. const name = n.s('name');
  18228. const value = this.environment_stack.findInAnyFrame(name);
  18229. torch._C.TORCH_INTERNAL_ASSERT(value);
  18230. n.output().replaceAllUsesWith(value);
  18231. n.destroy();
  18232. break;
  18233. }
  18234. case 'prim::ComprehensionScope': {
  18235. const [body] = n.blocks();
  18236. this.eraseBlockLoadStores(body);
  18237. for (const body_node of body.nodes()) {
  18238. body_node.moveBefore(n);
  18239. }
  18240. n.destroy();
  18241. break;
  18242. }
  18243. default: {
  18244. for (const b of n.blocks()) {
  18245. this.eraseBlockLoadStores(b);
  18246. }
  18247. break;
  18248. }
  18249. }
  18250. }
  18251. this.popFrame();
  18252. }
  18253. run(graph) {
  18254. this.eraseBlockLoadStores(graph.block());
  18255. }
  18256. });
  18257. this.registerFunction('torch._C.convertEnterExitNodesToWithBlocks', (/* graph */) => {
  18258. });
  18259. this.registerFunction('torch._C.inlineConsecutiveIfs', (/* graph */) => {
  18260. });
  18261. this.registerType('torch._C.ExitPair', class {
  18262. constructor(exit_v, exit_val_ref) {
  18263. const exit_vals = [];
  18264. for (const v of exit_val_ref) {
  18265. exit_vals.push(v);
  18266. }
  18267. if (exit_v.type() !== torch.BoolType.get()) {
  18268. throw new python.Error('Invalid exit value type.');
  18269. }
  18270. this.first = exit_v;
  18271. this.second = exit_vals;
  18272. }
  18273. hasExited() {
  18274. return this.first;
  18275. }
  18276. exitValues() {
  18277. return this.second;
  18278. }
  18279. });
  18280. this.registerType('torch._C.ExitTransformer', class {
  18281. constructor(graph) {
  18282. this._graph = graph;
  18283. this._target_block = null;
  18284. this._unit_values = new Map();
  18285. const guard = new torch._C.WithInsertPoint(this._graph.block().nodes().front());
  18286. this._true_val = this._graph.insertConstant(true);
  18287. this._false_val = this._graph.insertConstant(false);
  18288. this._throws_val = this.getUnitValue(torch.BoolType.get());
  18289. guard.dispose();
  18290. }
  18291. getUnitValue(type) {
  18292. const maybe_val = this._unit_values.get(type);
  18293. if (maybe_val) {
  18294. return maybe_val;
  18295. }
  18296. const unit = this._graph.createUninitialized(type).insertAfter(this._graph.param_node()).output();
  18297. this._unit_values.set(type, unit);
  18298. return unit;
  18299. }
  18300. transformReturnStmts() {
  18301. this._current_exit_kind = 'prim::ReturnStmt';
  18302. this.transformExits(this._graph.block());
  18303. }
  18304. transformLoopContinuations() {
  18305. this._current_exit_kind = 'prim::LoopContinuation';
  18306. this.transformExits(this._graph.block());
  18307. }
  18308. destroyNodeAfterExit(n) {
  18309. for (const output of n.outputs()) {
  18310. if (output.uses().length > 0) {
  18311. output.replaceAllUsesWith(this.getUnitValue(output.type()));
  18312. }
  18313. }
  18314. n.destroy();
  18315. }
  18316. deleteAfterExitNodes(block, iter) {
  18317. const nodes = block.nodes();
  18318. if (iter === nodes.end()) {
  18319. return;
  18320. }
  18321. const insert = new torch._C.WithInsertPoint(block.nodes().front());
  18322. for (const it of Array.from(nodes).reverse()) {
  18323. if (it === iter) {
  18324. break;
  18325. }
  18326. if (it !== block.return_node()) {
  18327. this.destroyNodeAfterExit(it);
  18328. }
  18329. }
  18330. this.destroyNodeAfterExit(iter);
  18331. insert.dispose();
  18332. }
  18333. updateTargetBlock(block) {
  18334. if (torch._C.ExitTransformer.owningNodeKind(block) === 'prim::Loop' && this._current_exit_kind === 'prim::LoopContinuation') {
  18335. this._target_block = block;
  18336. } else if (torch._C.ExitTransformer.isGraphOrClosureBlock(block) && this._current_exit_kind === 'prim::ReturnStmt') {
  18337. this._target_block = block;
  18338. }
  18339. }
  18340. transformLoop(node) {
  18341. const loop = new torch._C.LoopView(node);
  18342. const body = loop.bodyBlock();
  18343. const exit_pair = this.transformExits(body);
  18344. if (this.getExitStatus(exit_pair) === 'WONT' || this.getExitStatus(exit_pair) === 'THROWS') {
  18345. return this.constructWontExitPair();
  18346. }
  18347. const insert = new torch._C.WithInsertPoint(body);
  18348. const new_if = this._graph.insertNode(this._graph.create('prim::If', 0));
  18349. new_if.addInput(exit_pair.hasExited());
  18350. new_if.addBlock().registerOutput(this._false_val);
  18351. new_if.addBlock().registerOutput(loop.nextCond());
  18352. const new_condition = new_if.addOutput().setType(torch.BoolType.get());
  18353. loop.bodyBlock().eraseOutput(0);
  18354. loop.bodyBlock().insertOutput(0, new_condition);
  18355. node.addInput(this._false_val);
  18356. body.addInput().setType(torch.BoolType.get());
  18357. body.registerOutput(exit_pair.hasExited());
  18358. const new_has_exited = node.addOutput().setType(torch.BoolType.get());
  18359. for (const exit_value of exit_pair.exitValues()) {
  18360. const typ = exit_value.type();
  18361. node.addInput(this.getUnitValue(typ));
  18362. node.addOutput().setType(typ);
  18363. body.addInput().setType(typ);
  18364. body.registerOutput(exit_value);
  18365. }
  18366. const exit_vals = node.outputs().slice(node.outputs().length - exit_pair.exitValues().size());
  18367. const result = new torch._C.ExitPair(new_has_exited, exit_vals);
  18368. insert.dispose();
  18369. return result;
  18370. }
  18371. calcIfExitStatus(then_status, else_status) {
  18372. if (then_status === 'THROWS') {
  18373. return else_status;
  18374. } else if (else_status === 'THROWS') {
  18375. return then_status;
  18376. }
  18377. if (then_status === 'WONT' && else_status === 'WONT') {
  18378. return 'WONT';
  18379. }
  18380. if (then_status === 'WILL' && else_status === 'WILL') {
  18381. return 'WILL';
  18382. }
  18383. return 'MIGHT';
  18384. }
  18385. transformIf(node) {
  18386. const [then_block, else_block] = node.blocks();
  18387. let then_pair = this.transformExits(then_block);
  18388. let else_pair = this.transformExits(else_block);
  18389. const then_status = this.getExitStatus(then_pair);
  18390. const else_status = this.getExitStatus(else_pair);
  18391. const if_status = this.calcIfExitStatus(then_status, else_status);
  18392. if (if_status === 'THROWS') {
  18393. return this.constructThrowsExitPair();
  18394. }
  18395. if (if_status === 'WONT') {
  18396. return this.constructWontExitPair();
  18397. }
  18398. if (then_status === 'WONT' || then_status === 'THROWS') {
  18399. const exit_vals = this.matchValuesWithUnitialized(else_pair.exitValues());
  18400. then_pair = new torch._C.ExitPair(then_pair.hasExited(), exit_vals);
  18401. } else if (else_status === 'WONT' || else_status === 'THROWS') {
  18402. const exit_vals = this.matchValuesWithUnitialized(then_pair.exitValues());
  18403. else_pair = new torch._C.ExitPair(else_pair.hasExited(), exit_vals);
  18404. }
  18405. let has_exited = null;
  18406. if (if_status === 'WILL') {
  18407. has_exited = this._true_val;
  18408. } else {
  18409. this.addIfOutputs(node, [then_pair.hasExited()], [else_pair.hasExited()]);
  18410. has_exited = node.outputs().at(node.outputs().length - 1);
  18411. }
  18412. this.addIfOutputs(node, then_pair.exitValues(), else_pair.exitValues());
  18413. const num_exit_vals = then_pair.exitValues().size();
  18414. const exit_vals = node.outputs().slice(node.outputs().length - num_exit_vals);
  18415. return new torch._C.ExitPair(has_exited, exit_vals);
  18416. }
  18417. transformExits(block) {
  18418. const prev_target_block = this._target_block;
  18419. this.updateTargetBlock(block);
  18420. let exit_pair = this.constructWontExitPair();
  18421. for (const node of block.nodes()) {
  18422. const it = node.next;
  18423. switch (node.kind()) {
  18424. case 'prim::RaiseException': {
  18425. exit_pair = this.constructThrowsExitPair();
  18426. break;
  18427. }
  18428. case 'prim::ReturnStmt':
  18429. case 'prim::LoopContinuation': {
  18430. if (node.kind() === this._current_exit_kind) {
  18431. exit_pair = this.constructWillExitPair(node.inputs());
  18432. node.destroy();
  18433. }
  18434. break;
  18435. }
  18436. case 'prim::If': {
  18437. exit_pair = this.transformIf(node);
  18438. break;
  18439. }
  18440. case 'prim::With': {
  18441. exit_pair = this.transformWith(node);
  18442. break;
  18443. }
  18444. case 'prim::Closure': {
  18445. this.transformExits(node.blocks().at(0));
  18446. break;
  18447. }
  18448. case 'prim::Loop': {
  18449. exit_pair = this.transformLoop(node);
  18450. break;
  18451. }
  18452. default: {
  18453. break;
  18454. }
  18455. }
  18456. const status = this.getExitStatus(exit_pair);
  18457. if (status === 'WILL' || status === 'THROWS') {
  18458. this.deleteAfterExitNodes(block, it);
  18459. break;
  18460. }
  18461. if (status === 'MIGHT') {
  18462. throw new python.Error('Not implemented.');
  18463. // const nodes = block.nodes();
  18464. // if (node === nodes[nodes.length - 1]) {
  18465. // exit_pair = this.guardBlockNodes(block, exit_pair, it);
  18466. // }
  18467. // break;
  18468. }
  18469. }
  18470. if (this._target_block === block) {
  18471. if (this.getExitStatus(exit_pair) === 'MIGHT') {
  18472. const new_if = this._graph.create('prim::If', 0).insertBefore(block.return_node());
  18473. new_if.addBlock();
  18474. new_if.addBlock();
  18475. new_if.addInput(exit_pair.hasExited());
  18476. torch._C.ExistTransformer.addIfOutputs(new_if, exit_pair.exitValues(), block.outputs());
  18477. torch._C.ExistTransformer.replaceBlockOutputs(block, new_if.soutputs());
  18478. } else if (this.getExitStatus(exit_pair) === 'WILL') {
  18479. torch._C.ExitTransformer.replaceBlockOutputs(block, exit_pair.exitValues());
  18480. }
  18481. exit_pair = this.constructWontExitPair();
  18482. }
  18483. this._target_block = prev_target_block;
  18484. return exit_pair;
  18485. }
  18486. constructThrowsExitPair() {
  18487. return new torch._C.ExitPair(this._throws_val, []);
  18488. }
  18489. constructWontExitPair() {
  18490. return new torch._C.ExitPair(this._false_val, []);
  18491. }
  18492. constructWillExitPair(exit_val_ref) {
  18493. return new torch._C.ExitPair(this._true_val, exit_val_ref);
  18494. }
  18495. getExitStatus(exit_pair) {
  18496. const exit_v = exit_pair.hasExited();
  18497. if (exit_v === this._true_val) {
  18498. return 'WILL';
  18499. } else if (exit_v === this._false_val) {
  18500. return 'WONT';
  18501. } else if (exit_v === this._throws_val) {
  18502. return 'THROWS';
  18503. }
  18504. return 'MIGHT';
  18505. }
  18506. static owningNodeKind(block) {
  18507. if (block.owningNode()) {
  18508. return block.owningNode().kind();
  18509. }
  18510. return null;
  18511. }
  18512. static isGraphOrClosureBlock(block) {
  18513. return block.owningNode() === null || torch._C.ExitTransformer.owningNodeKind(block) === 'prim::Closure';
  18514. }
  18515. static removeOutputs(b) {
  18516. while (b.outputs().length > 0) {
  18517. b.eraseOutput(0);
  18518. }
  18519. }
  18520. static registerBlockOutputs(b, outs) {
  18521. for (const out of outs) {
  18522. b.registerOutput(out);
  18523. }
  18524. }
  18525. static replaceBlockOutputs(b, outs) {
  18526. torch._C.ExitTransformer.removeOutputs(b);
  18527. torch._C.ExitTransformer.registerBlockOutputs(b, outs);
  18528. }
  18529. });
  18530. this.registerFunction('torch._C.convertWithBlocksToEnterExitNodes', (/* graph */) => {
  18531. });
  18532. this.registerFunction('torch._C.TransformExits', (graph) => {
  18533. torch._C.convertEnterExitNodesToWithBlocks(graph);
  18534. const e_loop = new torch._C.ExitTransformer(graph);
  18535. e_loop.transformLoopContinuations();
  18536. const e_ret = new torch._C.ExitTransformer(graph);
  18537. e_ret.transformReturnStmts();
  18538. torch._C.inlineConsecutiveIfs(graph.block());
  18539. torch._C.convertWithBlocksToEnterExitNodes(graph);
  18540. });
  18541. this.registerFunction('torch._C.normalizeRSub', (iter) => {
  18542. if (iter.kind() === 'aten::rsub' && iter.schema() && iter.schema().overload === 'Tensor') {
  18543. const args = iter.inputs();
  18544. const newSub = iter.replaceWithNewSymbol('aten::sub');
  18545. newSub.replaceInput(0, args[1]);
  18546. newSub.replaceInput(1, args[0]);
  18547. iter.destroyCurrent();
  18548. return true;
  18549. }
  18550. return false;
  18551. });
  18552. this.registerFunction('torch._C.normalizeOpAliases', (/* iter */) => {
  18553. });
  18554. this.registerFunction('torch._C.normalizeIsBool', (iter) => {
  18555. const args = iter.inputs();
  18556. if (args.length === 2 && args[0].type() === torch.BoolType.get() && args[1].type() === torch.BoolType.get()) {
  18557. if (iter.kind() === 'aten::__is__') {
  18558. iter.replaceWithNewSymbol('aten::eq');
  18559. iter.destroyCurrent();
  18560. return true;
  18561. }
  18562. if (iter.kind() === 'aten::__isnot__') {
  18563. iter.replaceWithNewSymbol('aten::ne');
  18564. iter.destroyCurrent();
  18565. return true;
  18566. }
  18567. }
  18568. return false;
  18569. });
  18570. this.registerFunction('torch._C.NormalizeOps', (block) => {
  18571. for (const it of block.nodes()) {
  18572. for (const sub of it.blocks()) {
  18573. torch._C.NormalizeOps(sub);
  18574. }
  18575. if (torch._C.normalizeRSub(it)) {
  18576. continue;
  18577. }
  18578. if (torch._C.normalizeOpAliases(it)) {
  18579. continue;
  18580. }
  18581. if (torch._C.normalizeIsBool(it)) {
  18582. continue;
  18583. }
  18584. }
  18585. });
  18586. this.registerFunction('torch._C.getInlineEverythingMode', () => {
  18587. return false;
  18588. });
  18589. this.registerFunction('torch._C.runCleanupPasses', (to_clean) => {
  18590. /*
  18591. torch._C.liftClosures(to_clean);
  18592. torch._C.inlineForkedClosures(to_clean);
  18593. */
  18594. if (torch._C.getInlineEverythingMode()) {
  18595. torch._C.Inline(to_clean);
  18596. }
  18597. /*
  18598. torch._C.eraseListLiterals(to_clean);
  18599. */
  18600. torch._C.LowerSimpleTuples(to_clean);
  18601. torch._C.ConstantPropagationImmutableTypes(to_clean);
  18602. torch._C.ConstantPooling(to_clean);
  18603. /*
  18604. torch._C.CanonicalizeOutputs(to_clean);
  18605. torch._C.AnnotateWarns(to_clean);
  18606. */
  18607. });
  18608. this.registerType('torch.jit._script.ScriptModule', class extends torch.nn.modules.module.Module {});
  18609. this.registerType('torch.jit._trace.TracedModule', class extends torch.jit._script.ScriptModule {});
  18610. this.registerType('torch.jit._trace.TopLevelTracedModule', class extends torch.jit._trace.TracedModule {});
  18611. this.registerType('torch.jit._script.RecursiveScriptModule', class extends torch.jit._script.ScriptModule {
  18612. constructor(cpp_module) {
  18613. super();
  18614. this._initializing = true;
  18615. this._c = cpp_module;
  18616. }
  18617. static _construct(cpp_module, init_fn) {
  18618. const script_module = new torch.jit._script.RecursiveScriptModule(cpp_module);
  18619. init_fn(script_module);
  18620. torch.jit._script.RecursiveScriptModule._finalize_scriptmodule(script_module);
  18621. return script_module;
  18622. }
  18623. static _finalize_scriptmodule(script_module) {
  18624. script_module._parameters = new torch.ParameterDict(script_module._c).items();
  18625. script_module._buffers = new torch.BufferDict(script_module._c).items();
  18626. // script_module._modules = OrderedModuleDict(script_module._c, script_module._modules)
  18627. script_module._initializing = false;
  18628. }
  18629. get graph() {
  18630. // return this._c._get_method('forward').graph;
  18631. return this._c.graph;
  18632. }
  18633. get code_with_constants() {
  18634. // return this.forward.code_with_constants;
  18635. return this._c.code_with_constants;
  18636. }
  18637. __setattr__(name, value) {
  18638. if (this._initializing) {
  18639. super.__setattr__(name, value);
  18640. } else if (this._modules.has(name)) {
  18641. this._modules.set(name, value);
  18642. } else if (this._c.hasattr(name)) {
  18643. this._c.setattr(name, value);
  18644. } else {
  18645. //
  18646. }
  18647. }
  18648. __getattr__(name) {
  18649. if (this._initializing) {
  18650. return super.__getattr__(name);
  18651. }
  18652. if (this._modules.has(name)) {
  18653. return this._modules.get(name);
  18654. }
  18655. if (this._c.hasattr(name)) {
  18656. return this._c.getattr(name);
  18657. }
  18658. if (this._c._has_method(name)) {
  18659. //
  18660. }
  18661. return super.__getattr__(name);
  18662. }
  18663. });
  18664. torch.jit.ScriptModule = torch.jit._script.ScriptModule;
  18665. torch.jit.RecursiveScriptModule = torch.jit._script.RecursiveScriptModule;
  18666. torch.jit.TopLevelTracedModule = torch.jit._trace.TopLevelTracedModule;
  18667. torch.CompilationUnit = torch.jit.CompilationUnit;
  18668. torch._C.CompilationUnit = torch.jit.CompilationUnit;
  18669. torch._C.ScriptModule = torch.ScriptModule;
  18670. torch._C.ClassType = torch.ClassType;
  18671. this.registerType('torch._C.FlatBuffersLoader', class {
  18672. constructor(cu) {
  18673. this._cu = cu;
  18674. const torch = cu.execution.__import__('torch');
  18675. this._torch = torch;
  18676. const dtypes = Array.from(new Set(Object.values(torch).filter((obj) => obj instanceof torch.dtype)));
  18677. this._dtypes = new Map(dtypes.map((dtype) => [dtype.scalar_type(), dtype]));
  18678. this._ivalue_parsers = new Map();
  18679. this._ivalue_parsers.set(torch.mobile.serialization.Int, (ivalue) => ivalue.val.int_val);
  18680. this._ivalue_parsers.set(torch.mobile.serialization.Bool, (ivalue) => ivalue.val.bool_val);
  18681. this._ivalue_parsers.set(torch.mobile.serialization.Double, (ivalue) => ivalue.val.double_val);
  18682. this._ivalue_parsers.set(torch.mobile.serialization.TensorMetadata, (ivalue) => this.parseTensor(ivalue));
  18683. this._ivalue_parsers.set(torch.mobile.serialization.Object, (ivalue) => this.parseObject(ivalue));
  18684. }
  18685. parseModule(module) {
  18686. this._module = module;
  18687. this._all_functions = new Map();
  18688. this._all_ivalues = new Array(module.ivalues.length);
  18689. this._all_types = new Array(module.object_types.length);
  18690. const mobile_ivalue_size = module.mobile_ivalue_size ? module.mobile_ivalue_size : module.ivalues.length;
  18691. for (let i = 0; i < mobile_ivalue_size; i++) {
  18692. this.parseAndPopulate(i, module.ivalues[i]);
  18693. }
  18694. const m = this._all_ivalues[module.state_obj];
  18695. for (const [name, value] of this._all_functions) {
  18696. const class_index = module.ivalues[name].val.class_type;
  18697. const class_type = this._all_types[class_index];
  18698. if (value) {
  18699. class_type.addMethod(value);
  18700. }
  18701. }
  18702. m._min_operator_version = module.operator_version;
  18703. m._bytecode_version = module.bytecode_version;
  18704. return m;
  18705. }
  18706. parseAndPopulate(i, ivalue) {
  18707. if (ivalue.val instanceof torch.mobile.serialization.Function) {
  18708. this._all_functions.set(i, this.parseFunction(ivalue.val));
  18709. } else {
  18710. this._all_ivalues[i] = this.parseIValue(ivalue);
  18711. }
  18712. }
  18713. parseFunction(/* val */) {
  18714. return null;
  18715. }
  18716. parseIValue(ivalue) {
  18717. if (ivalue.val) {
  18718. const callback = this._ivalue_parsers.get(ivalue.val.constructor);
  18719. return callback(ivalue);
  18720. }
  18721. return null;
  18722. }
  18723. parseTensor(ivalue) {
  18724. return this.parseTensorFromMetadata(ivalue.val);
  18725. }
  18726. parseTensorFromMetadata(metadata) {
  18727. if (metadata.quantized_schema) {
  18728. throw new torch.Error('Quantized schema not implemented.');
  18729. }
  18730. const index = metadata.storage_location_index;
  18731. const data = this._module.storage_data[index].data;
  18732. const dtype = this._dtypes.get(metadata.scalar_type);
  18733. const size = data.length / dtype.itemsize();
  18734. const storage = new torch.storage.TypedStorage(size, dtype);
  18735. storage._set_cdata(data);
  18736. const tensor = new torch.Tensor();
  18737. const shape = Array.from(metadata.sizes);
  18738. const stride = Array.from(metadata.strides);
  18739. tensor.__setstate__([storage, metadata.storage_offset, shape, stride]);
  18740. return tensor;
  18741. }
  18742. parseObject(ivalue) {
  18743. const object = ivalue.val;
  18744. const obj_type = this._module.object_types[object.type_index];
  18745. const cls = this.getOrCreateClassTypeForObject(object);
  18746. switch (obj_type.type) {
  18747. case torch.mobile.serialization.TypeType.CLASS_WITH_FIELD: {
  18748. const torch = this._torch;
  18749. const obj = torch.ScriptObject.create(cls);
  18750. for (let i = 0; i < object.attrs.length; i++) {
  18751. const attr_name = obj_type.attr_names[i];
  18752. const val = this._all_ivalues[object.attrs[i]];
  18753. obj.__setattr__(attr_name, val);
  18754. }
  18755. return obj;
  18756. }
  18757. case torch.mobile.serialization.TypeType.CUSTOM_CLASS:
  18758. case torch.mobile.serialization.TypeType.CLASS_WITH_SETSTATE:
  18759. default: {
  18760. throw new python.Error(`Unknown object type type '${obj_type.type}'.`);
  18761. }
  18762. }
  18763. }
  18764. getOrCreateClassTypeForObject(object) {
  18765. let cls = this._all_types[object.type_index];
  18766. const obj_type = this._module.object_types[object.type_index];
  18767. if (!cls) {
  18768. const name = obj_type.type_name;
  18769. if (name.startsWith('__torch__') || name.startsWith('torch.jit')) {
  18770. cls = this._cu.get_class(new torch._C.QualifiedName(name));
  18771. if (!cls) {
  18772. const torch = this._torch;
  18773. cls = torch.ClassType.create(name, this._cu, true);
  18774. this._cu.register_type(cls);
  18775. }
  18776. } else {
  18777. // cls = c10::parseType(qn_str).cast<ClassType>();
  18778. }
  18779. this._all_types[object.type_index] = cls;
  18780. if (obj_type.type === torch.mobile.serialization.TypeType.CLASS_WITH_FIELD) {
  18781. for (let i = 0; i < object.attrs.length; i++) {
  18782. // const val = this._all_ivalues[object.attrs[i]];
  18783. cls.addAttribute(obj_type.attr_names[i] /*, null val.type(c10::DynamicType) */);
  18784. }
  18785. }
  18786. }
  18787. return cls;
  18788. }
  18789. });
  18790. this.registerType('torch.export.UnflattenedModule', class extends torch.nn.modules.module.Module {
  18791. constructor(export_module, flat_args_adapter) {
  18792. super();
  18793. const export_graph = copy.deepcopy(export_module.graph);
  18794. self.graph_signature = copy.deepcopy(export_module.graph_signature);
  18795. this.graph = torch.fx.Graph();
  18796. this.graph.owning_module = this;
  18797. this.module_call_graph = copy.deepcopy(export_module.module_call_graph);
  18798. this.flat_args_adapter = flat_args_adapter;
  18799. this.adapted = false;
  18800. // this._run_with_interpreter = RUN_WITH_INTERPRETER
  18801. this._inplace_buffer_mutations(export_graph, this.graph_signature);
  18802. }
  18803. });
  18804. this.registerType('torch.export.graph_signature.ExportGraphSignature', class {
  18805. constructor(input_specs, output_specs) {
  18806. this.input_specs = input_specs;
  18807. this.output_specs = output_specs;
  18808. }
  18809. get user_inputs() {
  18810. const user_inputs = [];
  18811. for (const s of this.input_specs) {
  18812. if (s.kind !== torch.export.graph_signature.InputKind.USER_INPUT) {
  18813. continue;
  18814. }
  18815. if (s.arg instanceof torch.export.graph_signature.TensorArgument ||
  18816. s.arg instanceof torch.export.graph_signature.SymIntArgument ||
  18817. s.arg instanceof torch.export.graph_signature.CustomObjArgument) {
  18818. user_inputs.push(s.arg.name);
  18819. } else if (s.arg instanceof torch.export.graph_signature.ConstantArgument) {
  18820. user_inputs.push(s.arg.value);
  18821. } else {
  18822. throw new python.Error(`Unsupported user input '${s.arg}'.`);
  18823. }
  18824. }
  18825. return user_inputs;
  18826. }
  18827. get user_outputs() {
  18828. const user_outputs = [];
  18829. for (const s of this.output_specs) {
  18830. if (s.kind !== torch.export.graph_signature.OutputKind.USER_OUTPUT) {
  18831. continue;
  18832. }
  18833. if (s.arg instanceof torch.export.graph_signature.TensorArgument ||
  18834. s.arg instanceof torch.export.graph_signature.SymIntArgument ||
  18835. s.arg instanceof torch.export.graph_signature.CustomObjArgument) {
  18836. user_outputs.push(s.arg.name);
  18837. } else if (s.arg instanceof torch.export.graph_signature.ConstantArgument) {
  18838. user_outputs.push(s.arg.value);
  18839. } else {
  18840. throw new python.Error(`Unsupported user output '${s.arg}'.`);
  18841. }
  18842. }
  18843. return user_outputs;
  18844. }
  18845. get inputs_to_parameters() {
  18846. return new Map(this.input_specs
  18847. .filter((s) => s.kind === torch.export.graph_signature.InputKind.PARAMETER && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  18848. .map((s) => [s.arg.name, s.target]));
  18849. }
  18850. get inputs_to_buffers() {
  18851. return new Map(this.input_specs
  18852. .filter((s) => s.kind === torch.export.graph_signature.InputKind.BUFFER && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  18853. .map((s) => [s.arg.name, s.target]));
  18854. }
  18855. get inputs_to_lifted_tensor_constants() {
  18856. return new Map(this.input_specs
  18857. .filter((s) => s.kind === torch.export.graph_signature.InputKind.CONSTANT_TENSOR && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  18858. .map((s) => [s.arg.name, s.target]));
  18859. }
  18860. });
  18861. torch.export.graph_signature.InputKind = {
  18862. USER_INPUT: 0,
  18863. PARAMETER: 1,
  18864. BUFFER: 2,
  18865. CONSTANT_TENSOR: 3,
  18866. CUSTOM_OBJ: 4,
  18867. TOKEN: 5
  18868. };
  18869. this.registerType('torch.export.graph_signature.InputSpec', class {
  18870. constructor(kind, arg, target, persistent) {
  18871. this.kind = kind;
  18872. this.arg = arg;
  18873. this.target = target;
  18874. this.persistent = persistent || null;
  18875. }
  18876. });
  18877. torch.export.graph_signature.OutputKind = {
  18878. USER_OUTPUT: 0,
  18879. LOSS_OUTPUT: 1,
  18880. BUFFER_MUTATION: 2,
  18881. GRADIENT_TO_PARAMETER: 3,
  18882. GRADIENT_TO_USER_INPUT: 4,
  18883. USER_INPUT_MUTATION: 5,
  18884. TOKEN: 6
  18885. };
  18886. this.registerType('torch.export.graph_signature.OutputSpec', class {
  18887. constructor(kind, arg, target) {
  18888. this.kind = kind;
  18889. this.arg = arg;
  18890. this.target = target;
  18891. }
  18892. });
  18893. this.registerType('torch.export.graph_signature.ConstantArgument', class {
  18894. constructor(name, value) {
  18895. this.name = name;
  18896. this.value = value; // Union[int, float, bool, str, None]
  18897. }
  18898. });
  18899. this.registerType('torch.export.graph_signature.TensorArgument', class {
  18900. constructor(name) {
  18901. this.name = name;
  18902. }
  18903. });
  18904. this.registerType('torch.export.graph_signature.SymIntArgument', class {
  18905. constructor(name) {
  18906. this.name = name;
  18907. }
  18908. });
  18909. this.registerType('torch.export.graph_signature.CustomObjArgument', class {
  18910. constructor(name, class_fqn, fake_val) {
  18911. this.name = name;
  18912. this.class_fqn = class_fqn;
  18913. this.fake_val = fake_val;
  18914. }
  18915. });
  18916. this.registerType('torch.export.exported_program.ExportedProgram', class {
  18917. constructor(root, graph, graph_signature, state_dict, range_constraints, module_call_graph, example_inputs, verifier, tensor_constants, constants) {
  18918. // graph._codegen = torch.fx.graph.CodeGen()
  18919. this._graph_module = this._create_graph_module_for_export(root, graph);
  18920. if (root instanceof torch.fx.GraphModule) {
  18921. // this._graph_module.meta.update(root.meta);
  18922. }
  18923. this._graph_signature = graph_signature;
  18924. this._state_dict = state_dict;
  18925. this._range_constraints = range_constraints;
  18926. this._module_call_graph = module_call_graph;
  18927. this._example_inputs = example_inputs;
  18928. this._constants = tensor_constants || constants || {};
  18929. }
  18930. _create_graph_module_for_export(root, graph) {
  18931. let gm = null;
  18932. try {
  18933. gm = new torch.fx.GraphModule(root, graph);
  18934. } catch {
  18935. const gm = new torch.fx.GraphModule(root, torch.fx.Graph());
  18936. gm._graph = graph;
  18937. }
  18938. return gm;
  18939. }
  18940. get graph_module() {
  18941. return this._graph_module;
  18942. }
  18943. get graph() {
  18944. return this._graph_module.graph;
  18945. }
  18946. get graph_signature() {
  18947. return this._graph_signature;
  18948. }
  18949. get state_dict() {
  18950. return this._state_dict;
  18951. }
  18952. get constants() {
  18953. return this._constants;
  18954. }
  18955. });
  18956. this.registerType('torch.export.exported_program.ModuleCallEntry', class {});
  18957. this.registerType('torch.export.exported_program.ModuleCallSignature', class {});
  18958. this.registerFunction('torch.export.exported_program._create_graph_module_for_export', (root, graph) => {
  18959. return new torch.fx.graph_module.GraphModule(root, graph);
  18960. });
  18961. this.registerFunction('torch.export.unflatten', (module, flat_args_adapter) => {
  18962. module = torch.export._remove_effect_tokens(module);
  18963. return new torch.export.UnflattenedModule(module, flat_args_adapter);
  18964. });
  18965. this.registerFunction('torch._export.exported_program._create_graph_module_for_export', (root, graph) => {
  18966. return new torch.fx.graph_module.GraphModule(root, graph);
  18967. });
  18968. this.registerType('torch._export.serde.serialize.SerializedArtifact', class {
  18969. constructor(exported_program, state_dict, constants, example_inputs) {
  18970. this.exported_program = exported_program;
  18971. this.state_dict = state_dict;
  18972. this.constants = constants;
  18973. this.example_inputs = example_inputs;
  18974. }
  18975. });
  18976. torch._export.serde.serialize._SYM_OPS = new Set([
  18977. operator.eq, operator.ne, operator.le, operator.ge, operator.lt, operator.gt,
  18978. operator.neg, operator.pos, operator.and_, operator.or_,
  18979. math.trunc, torch.sym_not,
  18980. operator.mul, operator.add, operator.sub, operator.floordiv, operator.mod, operator.pow,
  18981. torch.sym_int, torch.sym_float, torch.sym_ite, torch.sym_max, torch.sym_min, torch.sym_sqrt,
  18982. operator.truediv, operator.and_
  18983. ]);
  18984. this.registerType('torch._export.serde.union._Union', class {
  18985. constructor(obj) {
  18986. if (obj.$type) {
  18987. this.type = obj.$type;
  18988. this[obj.$type] = obj.$value;
  18989. delete obj.$type;
  18990. delete obj.$value;
  18991. } else if (obj.type) {
  18992. this.type = obj.type;
  18993. const entries = Object.entries(obj).filter(([key]) => key !== 'type');
  18994. this[obj.type] = Object.fromEntries(entries);
  18995. } else {
  18996. let entries = Object.entries(obj);
  18997. if (entries.length > 1) {
  18998. entries = entries.filter(([, value]) => value !== null);
  18999. }
  19000. if (entries.length !== 1) {
  19001. throw new python.Error(`Invalid union type '${entries.map(([key]) => key).join(',')}'.`);
  19002. }
  19003. const [entry] = entries;
  19004. const [type, value] = entry;
  19005. this.type = type;
  19006. this[type] = value;
  19007. }
  19008. }
  19009. get value() {
  19010. return this[this.type];
  19011. }
  19012. });
  19013. this.registerType('torch._export.serde.schema.NamedArgument', class {
  19014. constructor(obj) {
  19015. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  19016. this.name = obj.name;
  19017. }
  19018. });
  19019. this.registerType('torch._export.serde.schema.Argument', class extends torch._export.serde.union._Union {
  19020. constructor(obj) {
  19021. super(obj);
  19022. switch (this.type) {
  19023. case 'as_int':
  19024. case 'as_ints':
  19025. case 'as_float':
  19026. case 'as_floats':
  19027. case 'as_bool':
  19028. case 'as_bools':
  19029. case 'as_string':
  19030. case 'as_strings':
  19031. case 'as_scalar_type':
  19032. case 'as_device':
  19033. case 'as_memory_format':
  19034. case 'as_layout':
  19035. break;
  19036. case 'as_none':
  19037. this.as_none = null;
  19038. break;
  19039. case 'as_tensor':
  19040. this.as_tensor = new torch._export.serde.schema.TensorArgument(this.as_tensor);
  19041. break;
  19042. case 'as_tensors':
  19043. this.as_tensors = this.as_tensors.map((item) => new torch._export.serde.schema.TensorArgument(item));
  19044. break;
  19045. case 'as_graph':
  19046. this.as_graph = new torch._export.serde.schema.GraphArgument(this.as_graph);
  19047. break;
  19048. case 'as_sym_int':
  19049. this.as_sym_int = new torch._export.serde.schema.SymIntArgument(this.as_sym_int);
  19050. break;
  19051. case 'as_sym_ints':
  19052. this.as_sym_ints = this.as_sym_ints.map((item) => new torch._export.serde.schema.SymIntArgument(item));
  19053. break;
  19054. case 'as_sym_bool':
  19055. this.as_sym_bool = new torch._export.serde.schema.SymBoolArgument(this.as_sym_bool);
  19056. break;
  19057. case 'as_sym_bools':
  19058. this.as_sym_bools = this.as_sym_bools.map((item) => new torch._export.serde.schema.SymBoolArgument(item));
  19059. break;
  19060. case 'as_sym_float':
  19061. this.as_sym_float = new torch._export.serde.schema.SymFloatArgument(this.as_sym_float);
  19062. break;
  19063. case 'as_sym_floats':
  19064. this.as_sym_floats = this.as_sym_floats.map((item) => new torch._export.serde.schema.SymFloatArgument(item));
  19065. break;
  19066. case 'as_optional_tensors':
  19067. this.as_optional_tensors = this.as_optional_tensors.map((item) => new torch._export.serde.schema.OptionalTensorArgument(item));
  19068. break;
  19069. case 'as_custom_obj':
  19070. this.as_custom_obj = new torch._export.serde.schema.CustomObjArgument(this.as_custom_obj);
  19071. break;
  19072. // case 'as_graph': GraphArgument
  19073. default:
  19074. throw new python.Error(`Unsupported argument '${this.type}'.`);
  19075. }
  19076. }
  19077. });
  19078. this.registerType('torch._export.serde.schema.Node', class {
  19079. constructor(obj) {
  19080. this.target = obj.target;
  19081. this.inputs = obj.inputs.map((input) => new torch._export.serde.schema.NamedArgument(input));
  19082. this.outputs = obj.outputs.map((output) => new torch._export.serde.schema.Argument(output));
  19083. this.metadata = new Map(Object.entries(obj.metadata));
  19084. }
  19085. });
  19086. torch._export.serde.schema.ScalarType = {
  19087. UNKNOWN: 0,
  19088. BYTE: 1,
  19089. CHAR: 2,
  19090. SHORT: 3,
  19091. INT: 4,
  19092. LONG: 5,
  19093. HALF: 6,
  19094. FLOAT: 7,
  19095. DOUBLE: 8,
  19096. COMPLEXHALF: 9,
  19097. COMPLEXFLOAT: 10,
  19098. COMPLEXDOUBLE: 11,
  19099. BOOL: 12,
  19100. BFLOAT16: 13,
  19101. UINT16: 28,
  19102. FLOAT8E4M3FN: 29,
  19103. FLOAT8E5M2: 30,
  19104. FLOAT8E4M3FNUZ: 31,
  19105. FLOAT8E5M2FNUZ: 32,
  19106. };
  19107. torch._export.serde.schema.Layout = {
  19108. Unknown: 0,
  19109. SparseCoo: 1,
  19110. SparseCsr: 2,
  19111. SparseCsc: 3,
  19112. SparseBsr: 4,
  19113. SparseBsc: 5,
  19114. _mkldnn: 6,
  19115. Strided: 7
  19116. };
  19117. torch._export.serde.schema.MemoryFormat = {
  19118. Unknown: 0,
  19119. ContiguousFormat: 1,
  19120. ChannelsLast: 2,
  19121. ChannelsLast3d: 3,
  19122. PreserveFormat: 4,
  19123. };
  19124. this.registerType('torch._export.serde.schema.Device', class {
  19125. constructor(obj) {
  19126. Object.assign(this, { ...obj });
  19127. }
  19128. });
  19129. this.registerType('torch._export.serde.schema.TensorMeta', class {
  19130. constructor(obj) {
  19131. obj = obj.meta || obj;
  19132. this.dtype = obj.dtype;
  19133. this.sizes = obj.sizes.map((size) => new torch._export.serde.schema.SymInt(size));
  19134. this.requires_grad = obj.requires_grad;
  19135. this.device = obj.device;
  19136. this.strides = obj.strides.map((stride) => new torch._export.serde.schema.SymInt(stride));
  19137. this.storage_offset = new torch._export.serde.schema.SymInt(Number.isInteger(obj.storage_offset) ? { as_int: obj.storage_offset } : obj.storage_offset);
  19138. this.layout = obj.layout;
  19139. }
  19140. });
  19141. this.registerType('torch._export.serde.schema.Graph', class {
  19142. constructor(obj) {
  19143. this.inputs = obj.inputs.map((input) => new torch._export.serde.schema.Argument(input));
  19144. this.outputs = obj.outputs.map((output) => new torch._export.serde.schema.Argument(output));
  19145. this.nodes = obj.nodes.map((node) => new torch._export.serde.schema.Node(node));
  19146. this.tensor_values = new Map(Object.entries(obj.tensor_values).map(([key, value]) => [key, new torch._export.serde.schema.TensorMeta(value)]));
  19147. this.sym_int_values = new Map(Object.entries(obj.sym_int_values).map(([key, value]) => [key, new torch._export.serde.schema.SymInt(value)]));
  19148. this.sym_bool_values = new Map(Object.entries(obj.sym_bool_values).map(([key, value]) => [key, new torch._export.serde.schema.SymBool(value)]));
  19149. this.is_single_tensor_return = obj.is_single_tensor_return;
  19150. this.custom_obj_values = new Map(Object.entries(obj.custom_obj_values || {}).map(([key, value]) => [key, new torch._export.serde.schema.CustomObjArgument(value)]));
  19151. if (obj.contants) {
  19152. // this.constants = new Map(Object.entries(serialized_graph.constants).map(([k, v]) => [k, torch.load(v)]));
  19153. // graph_signature -> input_specs -> tensor_constant
  19154. }
  19155. }
  19156. });
  19157. this.registerType('torch._export.serde.schema.ModuleCallSignature', class {
  19158. constructor(obj) {
  19159. Object.assign(this, { ...obj });
  19160. this.inputs = this.inputs.map((item) => new torch._export.serde.schema.Argument(item));
  19161. this.outputs = this.outputs.map((item) => new torch._export.serde.schema.Argument(item));
  19162. }
  19163. });
  19164. this.registerType('torch._export.serde.schema.ModuleCallEntry', class {
  19165. constructor(obj) {
  19166. Object.assign(this, { ...obj });
  19167. this.signature = this.signature ? new torch._export.serde.schema.ModuleCallSignature(this.signature) : null;
  19168. }
  19169. });
  19170. this.registerType('torch._export.serde.schema.GraphModule', class {
  19171. constructor(obj) {
  19172. this.graph = new torch._export.serde.schema.Graph(obj.graph);
  19173. this.signature = new torch._export.serde.schema.GraphSignature(obj.signature);
  19174. this.module_call_graph = obj.module_call_graph.map((item) => new torch._export.serde.schema.ModuleCallEntry(item));
  19175. this.metadata = new Map(Object.entries(obj.metadata || {}));
  19176. }
  19177. });
  19178. this.registerType('torch._export.serde.schema.ExportedProgram', class {
  19179. constructor(obj) {
  19180. Object.assign(this, { ...obj });
  19181. this.graph_module = new torch._export.serde.schema.GraphModule(obj.graph_module);
  19182. }
  19183. });
  19184. this.registerType('torch._export.serde.schema.SymExprHint', class extends torch._export.serde.union._Union {});
  19185. this.registerType('torch._export.serde.schema.SymExpr', class {
  19186. constructor(obj) {
  19187. this.expr_str = obj.expr_str;
  19188. this.hint = obj.hint ? new torch._export.serde.schema.SymExprHint(obj.hint) : null;
  19189. }
  19190. });
  19191. this.registerType('torch._export.serde.schema.SymInt', class extends torch._export.serde.union._Union {
  19192. constructor(obj) {
  19193. super(obj);
  19194. if (this.type === 'as_int') {
  19195. // continue
  19196. } else if (this.type === 'as_expr') {
  19197. this.as_expr = new torch._export.serde.schema.SymExpr(this.as_expr);
  19198. } else {
  19199. throw new python.Error(`Unsupported symbolic int '${this.type}'.`);
  19200. }
  19201. }
  19202. });
  19203. this.registerType('torch._export.serde.schema.SymBool', class extends torch._export.serde.union._Union {
  19204. constructor(obj) {
  19205. super(obj);
  19206. if (this.type === 'as_bool') {
  19207. // continue
  19208. } else if (this.type === 'as_expr') {
  19209. this.as_expr = new torch._export.serde.schema.SymExpr(this.as_expr);
  19210. } else {
  19211. throw new python.Error(`Unsupported symbolic bool '${this.type}'.`);
  19212. }
  19213. }
  19214. });
  19215. this.registerType('torch._export.serde.schema.SymIntArgument', class extends torch._export.serde.union._Union {
  19216. constructor(obj) {
  19217. super(obj);
  19218. Object.assign(this, { ...obj });
  19219. }
  19220. });
  19221. this.registerType('torch._export.serde.schema.SymFloatArgument', class extends torch._export.serde.union._Union {
  19222. constructor(obj) {
  19223. super(obj);
  19224. Object.assign(this, { ...obj });
  19225. }
  19226. });
  19227. this.registerType('torch._export.serde.schema.SymBoolArgument', class extends torch._export.serde.union._Union {
  19228. constructor(obj) {
  19229. super(obj);
  19230. Object.assign(this, { ...obj });
  19231. }
  19232. });
  19233. this.registerType('torch._export.serde.schema.CustomObjArgument', class {
  19234. constructor(obj) {
  19235. Object.assign(this, { ...obj });
  19236. }
  19237. });
  19238. this.registerType('torch._export.serde.schema.GraphSignature', class {
  19239. constructor(obj) {
  19240. this.input_specs = [];
  19241. if (Array.isArray(obj.input_specs)) {
  19242. this.input_specs = obj.input_specs.map((input_spec) => new torch._export.serde.schema.InputSpec(input_spec));
  19243. }
  19244. if (Array.isArray(obj.user_inputs)) {
  19245. for (const user_input of obj.user_inputs) {
  19246. this.input_specs.push(new torch._export.serde.schema.InputSpec({ user_input: { arg: { as_string: user_input } } }));
  19247. }
  19248. }
  19249. if (obj.inputs_to_parameters) {
  19250. for (const [input, parameter_name] of Object.entries(obj.inputs_to_parameters)) {
  19251. this.input_specs.push(new torch._export.serde.schema.InputSpec({ parameter: { arg: { name: input }, parameter_name } }));
  19252. }
  19253. }
  19254. this.output_specs = [];
  19255. if (Array.isArray(obj.output_specs)) {
  19256. this.output_specs = obj.output_specs.map((output_spec) => new torch._export.serde.schema.OutputSpec(output_spec));
  19257. }
  19258. }
  19259. });
  19260. this.registerType('torch._export.serde.schema.UserInputSpec', class {
  19261. constructor(obj) {
  19262. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  19263. }
  19264. });
  19265. this.registerType('torch._export.serde.schema.InputToParameterSpec', class {
  19266. constructor(obj) {
  19267. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  19268. this.parameter_name = obj.parameter_name;
  19269. }
  19270. });
  19271. this.registerType('torch._export.serde.schema.InputToBufferSpec', class {
  19272. constructor(obj) {
  19273. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  19274. this.buffer_name = obj.buffer_name;
  19275. }
  19276. });
  19277. this.registerType('torch._export.serde.schema.InputToTensorConstantSpec', class {
  19278. constructor(obj) {
  19279. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  19280. this.tensor_constant_name = obj.tensor_constant_name;
  19281. }
  19282. });
  19283. this.registerType('torch._export.serde.schema.InputToConstantInputSpec', class {
  19284. constructor(obj) {
  19285. this.name = obj.name;
  19286. this.value = new torch._export.serde.schema.ConstantValue(obj.value);
  19287. }
  19288. });
  19289. this.registerType('torch._export.serde.schema.ConstantValue', class extends torch._export.serde.union._Union {
  19290. constructor(obj) {
  19291. super(obj);
  19292. if (this.type === 'as_int' || this.type === 'as_float' || this.type === 'as_bool' || this.type === 'as_string' || this.type === 'as_strings') {
  19293. // continue
  19294. } else if (this.type === 'as_none') {
  19295. this.as_none = null;
  19296. } else {
  19297. throw new python.Error(`Unsupported constant value type '${this.type}'.`);
  19298. }
  19299. }
  19300. });
  19301. this.registerType('torch._export.serde.schema.InputSpec', class extends torch._export.serde.union._Union {
  19302. constructor(obj) {
  19303. super(obj);
  19304. if (this.type === 'user_input') {
  19305. this.user_input = new torch._export.serde.schema.UserInputSpec(this.user_input);
  19306. } else if (this.type === 'parameter') {
  19307. this.parameter = new torch._export.serde.schema.InputToParameterSpec(this.parameter);
  19308. } else if (this.type === 'buffer') {
  19309. this.buffer = new torch._export.serde.schema.InputToBufferSpec(this.buffer);
  19310. } else if (this.type === 'tensor_constant') {
  19311. this.tensor_constant = new torch._export.serde.schema.InputToTensorConstantSpec(this.tensor_constant);
  19312. } else if (this.type === 'constant_input') {
  19313. this.constant_input = new torch._export.serde.schema.InputToConstantInputSpec(this.constant_input);
  19314. } else {
  19315. throw new python.Error(`Unsupported input spec type '${this.type}'.`);
  19316. }
  19317. /*
  19318. custom_obj: InputToCustomObjSpec
  19319. token: InputTokenSpec
  19320. */
  19321. }
  19322. });
  19323. this.registerType('torch._export.serde.schema.UserOutputSpec', class {
  19324. constructor(obj) {
  19325. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  19326. }
  19327. });
  19328. this.registerType('torch._export.serde.schema.BufferMutationSpec', class {
  19329. constructor(obj) {
  19330. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  19331. this.buffer_name = obj.buffer_name;
  19332. }
  19333. });
  19334. this.registerType('torch._export.serde.schema.GradientToParameterSpec', class {
  19335. constructor(obj) {
  19336. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  19337. this.parameter_name = obj.parameter_name;
  19338. }
  19339. });
  19340. this.registerType('torch._export.serde.schema.GradientToUserInputSpec', class {
  19341. constructor(obj) {
  19342. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  19343. this.user_input_name = obj.user_input_name;
  19344. }
  19345. });
  19346. this.registerType('torch._export.serde.schema.UserInputMutationSpec', class {
  19347. constructor(obj) {
  19348. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  19349. this.user_input_name = obj.user_input_name;
  19350. }
  19351. });
  19352. this.registerType('torch._export.serde.schema.OutputTokenSpec', class {
  19353. constructor(obj) {
  19354. this.arg = new torch._export.serde.schema.TokenArgument(obj.arg);
  19355. }
  19356. });
  19357. this.registerType('torch._export.serde.schema.OutputSpec', class extends torch._export.serde.union._Union {
  19358. constructor(obj) {
  19359. super(obj);
  19360. if (this.type === 'user_output') {
  19361. this.user_output = new torch._export.serde.schema.UserOutputSpec(this.user_output);
  19362. } else if (this.type === 'loss_output') {
  19363. this.loss_output = new torch._export.serde.schema.LossOutputSpec(this.loss_output);
  19364. } else if (this.type === 'buffer_mutation') {
  19365. this.buffer_mutation = new torch._export.serde.schema.BufferMutationSpec(this.buffer_mutation);
  19366. } else if (this.type === 'gradient_to_parameter') {
  19367. this.gradient_to_parameter = new torch._export.serde.schema.GradientToParameterSpec(this.gradient_to_parameter);
  19368. } else if (this.type === 'gradient_to_user_input') {
  19369. this.gradient_to_user_input = new torch._export.serde.schema.GradientToUserInputSpec(this.gradient_to_user_input);
  19370. } else if (this.type === 'user_input_mutation') {
  19371. this.user_input_mutation = new torch._export.serde.schema.UserInputMutationSpec(this.user_input_mutation);
  19372. } else if (this.type === 'token') {
  19373. this.token = new torch._export.serde.schema.OutputTokenSpec(this.token);
  19374. }
  19375. }
  19376. });
  19377. this.registerType('torch._export.serde.schema.TensorArgument', class {
  19378. constructor(obj) {
  19379. this.name = obj.name;
  19380. }
  19381. });
  19382. this.registerType('torch._export.serde.schema.TokenArgument', class {
  19383. constructor(obj) {
  19384. this.name = obj.name;
  19385. }
  19386. });
  19387. this.registerType('torch._export.serde.schema.GraphArgument', class {
  19388. constructor(obj) {
  19389. this.name = obj.name;
  19390. this.graph = new torch._export.serde.schema.Graph(obj.graph);
  19391. }
  19392. });
  19393. this.registerType('torch._export.serde.schema.OptionalTensorArgument', class extends torch._export.serde.union._Union {
  19394. constructor(obj) {
  19395. super(obj);
  19396. if (this.type === 'as_tensor') {
  19397. this.as_tensor = new torch._export.serde.schema.TensorArgument({ name: this.as_tensor });
  19398. } else if (this.type === 'as_none') {
  19399. this.as_none = null;
  19400. } else {
  19401. throw new python.Error(`Unsupported optional tensor argument '${this.type}'.`);
  19402. }
  19403. }
  19404. });
  19405. this.registerFunction('torch.export.pt2_archive._package._load_state_dict', (f, model_name) => {
  19406. const legacy_file = `data/weights/${model_name}.pt`;
  19407. if (f.has(legacy_file)) {
  19408. return f.get(legacy_file);
  19409. }
  19410. const weights_config_file = `data/weights/${model_name}_weights_config.json`;
  19411. if (!f.has(weights_config_file)) {
  19412. return null;
  19413. }
  19414. const weights_config = f.get(weights_config_file);
  19415. const state_dict_file_map = torch.export.pt2_archive._package._build_file_map(f, weights_config, 'data/weights/');
  19416. const state_dict = new builtins.dict();
  19417. for (const [weight_fqn, payload_meta] of Object.entries(weights_config.config)) {
  19418. if (payload_meta.use_pickle) {
  19419. const weight_bytes = f.get(`data/weights/${payload_meta.path_name}`);
  19420. const weight_tensor = torch.load(weight_bytes);
  19421. state_dict.set(weight_fqn, weight_tensor);
  19422. } else {
  19423. const tensor_meta = payload_meta.tensor_meta;
  19424. const tensor = state_dict_file_map.get(payload_meta.path_name);
  19425. const sizes = tensor_meta.sizes.map((s) => s.as_int);
  19426. const strides = tensor_meta.strides.map((s) => s.as_int);
  19427. const storage_offset = tensor_meta.storage_offset.as_int;
  19428. const weight_tensor = new torch.Tensor();
  19429. weight_tensor.__setstate__([tensor.storage(), storage_offset, sizes, strides]);
  19430. weight_tensor.requires_grad = tensor_meta.requires_grad || false;
  19431. if (payload_meta.is_param) {
  19432. state_dict.set(weight_fqn, new torch.nn.parameter.Parameter(weight_tensor, tensor_meta.requires_grad));
  19433. } else {
  19434. state_dict.set(weight_fqn, weight_tensor);
  19435. }
  19436. }
  19437. }
  19438. return state_dict;
  19439. });
  19440. this.registerFunction('torch.export.pt2_archive._package._load_constants', (f, model_name) => {
  19441. const legacy_file = `data/constants/${model_name}.pt`;
  19442. if (f.has(legacy_file)) {
  19443. const entries = f.get(legacy_file);
  19444. return new builtins.dict(entries);
  19445. }
  19446. const constants_config_file = `data/constants/${model_name}_constants_config.json`;
  19447. if (!f.has(constants_config_file)) {
  19448. return null;
  19449. }
  19450. const constants_config = f.get(constants_config_file);
  19451. const constant_file_map = torch.export.pt2_archive._package._build_file_map(f, constants_config, 'data/constants/');
  19452. const constants = new builtins.dict();
  19453. for (const [constant_fqn, payload_meta] of Object.entries(constants_config.config)) {
  19454. const path_name = payload_meta.path_name;
  19455. if (path_name.startsWith('tensor_')) {
  19456. if (payload_meta.use_pickle) {
  19457. const constant_bytes = f.get(`data/constants/${payload_meta.path_name}`);
  19458. const constant_tensor = torch.load(constant_bytes);
  19459. constants.set(constant_fqn, constant_tensor);
  19460. } else {
  19461. const tensor_meta = payload_meta.tensor_meta;
  19462. const tensor = constant_file_map.get(payload_meta.path_name);
  19463. const sizes = tensor_meta.sizes.map((s) => s.as_int);
  19464. const strides = tensor_meta.strides.map((s) => s.as_int);
  19465. const storage_offset = tensor_meta.storage_offset.as_int;
  19466. const constant_tensor = new torch.Tensor();
  19467. constant_tensor.__setstate__([tensor.storage(), storage_offset, sizes, strides]);
  19468. constants.set(constant_fqn, constant_tensor);
  19469. }
  19470. } else if (payload_meta.path_name.startsWith('custom_obj_')) {
  19471. const custom_obj_bytes = f.get(`data/constants/${payload_meta.path_name}`);
  19472. const custom_obj = torch._C._pickle_load_obj(custom_obj_bytes);
  19473. constants.set(constant_fqn, custom_obj);
  19474. }
  19475. }
  19476. return constants;
  19477. });
  19478. this.registerFunction('torch._export.serde.serialize.deserialize_scalar_type', (st) => {
  19479. if (!torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE.has(st)) {
  19480. throw new python.Error(`Unsupported scalar type '${st}'.`);
  19481. }
  19482. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE.get(st);
  19483. });
  19484. this.registerFunction('torch.export.pt2_archive._package._build_file_map', (archive_reader, config, base_dir) => {
  19485. const file_map = new builtins.dict();
  19486. for (const payload_meta of Object.values(config.config)) {
  19487. if (payload_meta.use_pickle) {
  19488. continue;
  19489. }
  19490. if (file_map.has(payload_meta.path_name)) {
  19491. continue;
  19492. }
  19493. const tensor_bytes = archive_reader.get(`${base_dir}${payload_meta.path_name}`);
  19494. const tensor = torch.export.pt2_archive._package._create_flat_tensor_from_bytes(tensor_bytes, payload_meta.tensor_meta);
  19495. file_map.set(payload_meta.path_name, tensor);
  19496. }
  19497. return file_map;
  19498. });
  19499. this.registerFunction('torch.export.pt2_archive._package._create_flat_tensor_from_bytes', (tensor_bytes, tensor_meta) => {
  19500. const dtype = torch._export.serde.serialize.deserialize_scalar_type(tensor_meta.dtype);
  19501. const itemsize = dtype.itemsize();
  19502. const num_elements = tensor_bytes.length / itemsize;
  19503. const storage = new torch.storage.TypedStorage(num_elements, dtype);
  19504. storage._set_cdata(tensor_bytes);
  19505. const tensor = new torch.Tensor();
  19506. tensor.__setstate__([storage, 0, [num_elements], [1]]);
  19507. tensor.requires_grad = tensor_meta.requires_grad || false;
  19508. return tensor;
  19509. });
  19510. this.registerFunction('torch.export.pt2_archive._package.load_pt2', (f, expected_opset_version) => {
  19511. const exported_programs = new Map();
  19512. for (const name of f.keys()) {
  19513. const match = name.match(/^models\/([^/]+)\.json$/);
  19514. if (match) {
  19515. const [, model_name] = match;
  19516. const serialized_exported_program = f.get(`models/${model_name}.json`);
  19517. const serialized_state_dict = torch.export.pt2_archive._package._load_state_dict(f, model_name);
  19518. const serialized_constants = torch.export.pt2_archive._package._load_constants(f, model_name);
  19519. const serialized_example_inputs = f.get(`data/sample_inputs/${model_name}.pt`, 'zip');
  19520. const artifact = new torch._export.serde.serialize.SerializedArtifact(serialized_exported_program, serialized_state_dict, serialized_constants, serialized_example_inputs);
  19521. const exported_program = torch._export.serde.serialize.deserialize(artifact, expected_opset_version);
  19522. exported_programs.set(model_name, exported_program);
  19523. }
  19524. }
  19525. return { exported_programs };
  19526. });
  19527. this.registerFunction('torch._export.serde.serialize._dict_to_dataclass', (cls, data) => {
  19528. if (data === null) {
  19529. return data;
  19530. }
  19531. if (cls) {
  19532. return new cls(data);
  19533. }
  19534. throw new python.Error(`Unsupported data class '${cls.__name__}'.`);
  19535. });
  19536. this.registerFunction('torch._export.serde.serialize.deserialize', (artifact, expected_opset_version) => {
  19537. const serialized_exported_program = torch._export.serde.serialize._dict_to_dataclass(torch._export.serde.schema.ExportedProgram, artifact.exported_program);
  19538. return new torch._export.serde.serialize.ExportedProgramDeserializer(expected_opset_version).deserialize(serialized_exported_program, artifact.state_dict, artifact.constants, artifact.example_inputs);
  19539. });
  19540. this.registerType('torch._export.serde.serialize.ExportedProgramDeserializer', class {
  19541. constructor(expected_opset_version) {
  19542. this.expected_opset_version = expected_opset_version;
  19543. }
  19544. deserialize(exported_program, state_dict, constants, example_inputs) {
  19545. const symbol_name_to_range = new Map(Object.entries(exported_program.range_constraints));
  19546. /*
  19547. symbol_name_to_range = {
  19548. k: symbolic_shapes.ValueRanges(_int_to_sympy_int(v.min_val), _int_to_sympy_int(v.max_val))
  19549. for k, v in exported_program.range_constraints.items()
  19550. }
  19551. */
  19552. const deserializer = new torch._export.serde.serialize.GraphModuleDeserializer();
  19553. const res = deserializer.deserialize(
  19554. exported_program.graph_module,
  19555. state_dict,
  19556. constants,
  19557. example_inputs,
  19558. symbol_name_to_range);
  19559. const range_constraints = null;
  19560. /*
  19561. range_constraints = self.deserialize_range_constraints(
  19562. symbol_name_to_range, res.names_to_symbols,
  19563. )
  19564. model_opset_version: Optional[Dict[str, int]] = serialized_artifact.exported_program.opset_version
  19565. self._validate_model_opset_version(model_opset_version)
  19566. upgrader = GraphModuleOpUpgrader(self.expected_opset_version, model_opset_version)
  19567. */
  19568. return new torch.export.exported_program.ExportedProgram(
  19569. res.graph_module, res.graph_module.graph, res.signature,
  19570. res.state_dict, range_constraints, res.module_call_graph, res.example_inputs,
  19571. null, // verifier=load_verifier(serialized_artifact.exported_program.dialect),
  19572. res.constants);
  19573. // return upgrader.upgrade(exported_program)
  19574. }
  19575. });
  19576. this.registerFunction('torch._export.serde.serialize.deserialize_torch_artifact', (serialized) => {
  19577. if (serialized instanceof builtins.dict || serialized instanceof builtins.tuple) {
  19578. return serialized;
  19579. }
  19580. if (serialized === null || serialized.length === 0) {
  19581. return new builtins.dict();
  19582. }
  19583. const artifact = torch.load(serialized);
  19584. return artifact;
  19585. });
  19586. this.registerType('torch._export.serde.serialize.GraphModuleDeserializer', class {
  19587. constructor() {
  19588. this.serialized_name_to_node = new builtins.dict();
  19589. this.serialized_name_to_meta = new builtins.dict(); // torch._export.serde.serialize.LazyMap
  19590. this.graph = new torch.fx.Graph();
  19591. this.module = new torch.nn.Module();
  19592. }
  19593. save_graph_module() {
  19594. const Context = class {
  19595. constructor(self) {
  19596. this.self = self;
  19597. }
  19598. __enter__() {
  19599. this.saved = [
  19600. this.self.graph,
  19601. this.self.module,
  19602. this.self.serialized_name_to_node,
  19603. this.self.serialized_name_to_meta,
  19604. this.self.unbacked_symbols,
  19605. ];
  19606. this.self.graph = new torch.fx.graph.Graph();
  19607. this.self.module = new torch.nn.modules.module.Module();
  19608. this.self.serialized_name_to_node = new builtins.dict();
  19609. this.self.serialized_name_to_meta = new builtins.dict(); // torch._export.serde.serialize.LazyMap
  19610. this.self.unbacked_symbols = new Set();
  19611. }
  19612. __exit__(/* exc_type, exc_value, traceback */) {
  19613. const self = this.self;
  19614. [self.graph, self.module, self.serialized_name_to_node, self.serialized_name_to_meta, self.unbacked_symbols] = this.saved;
  19615. }
  19616. };
  19617. return new Context(this);
  19618. }
  19619. deserialize_graph_output(output) {
  19620. if (output.type === 'as_tensor') {
  19621. return this.serialized_name_to_node.get(output.as_tensor.name);
  19622. } else if (output.type === 'as_sym_int') {
  19623. return this.serialized_name_to_node.get(output.as_sym_int.as_name);
  19624. } else if (output.type === 'as_sym_bool') {
  19625. return this.serialized_name_to_node.get(output.as_sym_bool.as_name);
  19626. } else if (output.type === 'as_sym_float') {
  19627. return this.serialized_name_to_node.get(output.as_sym_float.as_name);
  19628. } else if (output.type === 'as_int') {
  19629. return output.as_int;
  19630. } else if (output.type === 'as_float') {
  19631. return output.as_float;
  19632. } else if (output.type === 'as_bool') {
  19633. return output.as_bool;
  19634. } else if (output.type === 'as_none') {
  19635. return null;
  19636. }
  19637. throw new python.Error(`Unsupported graph node ${output.type}.`);
  19638. }
  19639. deserialize_graph(serialized_graph) {
  19640. for (const [name, tensor_value] of serialized_graph.tensor_values) {
  19641. const meta_val = this.deserialize_tensor_meta(tensor_value.meta || tensor_value, this.fake_tensor_mode);
  19642. this.serialized_name_to_meta.set(name, meta_val);
  19643. }
  19644. for (const [name, sym_int_value] of serialized_graph.sym_int_values) {
  19645. this.serialized_name_to_meta.set(name, this.deserialize_sym_int(sym_int_value));
  19646. }
  19647. for (const [name, sym_bool_value] of serialized_graph.sym_bool_values) {
  19648. this.serialized_name_to_meta.set(name, this.deserialize_sym_bool(sym_bool_value));
  19649. }
  19650. for (const [name, script_obj_meta] of serialized_graph.custom_obj_values) {
  19651. this.serialized_name_to_meta.set(name, this.deserialize_script_obj_meta(script_obj_meta));
  19652. }
  19653. for (let i = 0; i < serialized_graph.inputs.length; i++) {
  19654. const input = serialized_graph.inputs[i];
  19655. if (input.type === 'as_tensor' || input.type === 'as_sym_int' || input.type === 'as_custom_obj') {
  19656. const node_name = input.value.name;
  19657. const placeholder_node = this.graph.placeholder(node_name);
  19658. placeholder_node.name = node_name;
  19659. this.sync_fx_node(node_name, placeholder_node);
  19660. } else if (input.type === 'as_int' || input.type === 'as_float' || input.type === 'as_bool' || input.type === 'as_none' || input.type === 'as_string') {
  19661. const node_name = this.signature.input_specs[i].arg.name;
  19662. const placeholder_node = this.graph.placeholder(node_name);
  19663. placeholder_node.meta.set('val', this.deserialize_input(input));
  19664. } else {
  19665. throw new python.Error(`Invalid input ${input.type}.`);
  19666. }
  19667. }
  19668. for (const serialized_node of serialized_graph.nodes) {
  19669. const target = this.deserialize_operator(serialized_node.target);
  19670. this.deserialize_node(serialized_node, target);
  19671. }
  19672. let outputs = [];
  19673. for (const output of serialized_graph.outputs) {
  19674. outputs.push(this.deserialize_graph_output(output));
  19675. }
  19676. if (serialized_graph.is_single_tensor_return) {
  19677. [outputs] = outputs;
  19678. } else {
  19679. outputs = new builtins.tuple(outputs);
  19680. }
  19681. const output_node = this.graph.output(outputs);
  19682. if (serialized_graph.is_single_tensor_return) {
  19683. output_node.meta.set('val', output_node.args[0].meta.get('val'));
  19684. } else {
  19685. output_node.meta.set('val', new builtins.tuple(Array.from(output_node.args[0]).map((arg) =>
  19686. arg instanceof torch.fx.Node ? arg.meta.get('val') : arg
  19687. )));
  19688. }
  19689. return self.graph;
  19690. }
  19691. deserialize_operator(serialized_target) {
  19692. let module = null;
  19693. let serialized_target_names = null;
  19694. if (serialized_target.startsWith('_operator')) {
  19695. module = operator;
  19696. serialized_target_names = serialized_target.split('.').slice(1);
  19697. } else if (serialized_target.startsWith('torch')) {
  19698. module = torch;
  19699. serialized_target_names = serialized_target.split('.').slice(1);
  19700. } else if (serialized_target.startsWith('#')) {
  19701. return self.deserialize_extension_operator(serialized_target);
  19702. } else {
  19703. return serialized_target;
  19704. }
  19705. let target = module;
  19706. for (const name of serialized_target_names) {
  19707. target = builtins.getattr(target, name);
  19708. if (!target) {
  19709. return serialized_target;
  19710. }
  19711. }
  19712. return target;
  19713. }
  19714. deserialize_node(serialized_node, target) {
  19715. let fx_node = null;
  19716. if (torch._export.serde.serialize._SYM_OPS.has(target)) {
  19717. const name = serialized_node.outputs[0].value.as_name;
  19718. const args = this.deserialize_sym_op_inputs(serialized_node.inputs);
  19719. fx_node = this.graph.create_node('call_function', target, args, null, name);
  19720. this.deserialize_sym_op_outputs(serialized_node, fx_node);
  19721. } else if (builtins.isinstance(target, torch._ops.HigherOrderOperator)) {
  19722. const [args, kwargs] = this.deserialize_hoo_inputs(serialized_node.inputs);
  19723. const metadata = this.deserialize_metadata(serialized_node.metadata);
  19724. for (const x of [...args, ...kwargs.values()]) {
  19725. if (builtins.isinstance(x, torch.fx.Node) && x.op === 'get_attr') {
  19726. x.meta.update(metadata);
  19727. }
  19728. }
  19729. const name = serialized_node.outputs.length === 1 &&
  19730. builtins.hasattr(serialized_node.outputs[0], 'as_tensor') &&
  19731. builtins.getattr(serialized_node, 'is_hop_single_tensor_return', true) ?
  19732. serialized_node.outputs[0].as_tensor.name : null;
  19733. fx_node = this.graph.create_node('call_function', target, args, kwargs, name);
  19734. this.deserialize_outputs(serialized_node, fx_node);
  19735. fx_node.meta.update(metadata);
  19736. } else if (builtins.isinstance(target, torch._ops.OpOverload)) {
  19737. const name = this._is_single_tensor_return(target) ? serialized_node.outputs[0].as_tensor.name : null;
  19738. const [args, kwargs] = this.deserialize_inputs(target, serialized_node);
  19739. fx_node = this.graph.create_node('call_function', target, args, kwargs, name);
  19740. this.deserialize_outputs(serialized_node, fx_node);
  19741. } else if (typeof target === 'string') {
  19742. // Handle unresolved operators
  19743. execution.emit('resolve', target);
  19744. if (target.match(/^torch\.ops\.(aten|prim|quantized)\./)) {
  19745. throw new python.Error(`Unsupported node target type '${target}'.`);
  19746. }
  19747. const [args, kwargs] = this.deserialize_hoo_inputs(serialized_node.inputs);
  19748. const name = serialized_node.outputs.length === 1 && builtins.hasattr(serialized_node.outputs[0], 'as_tensor') ? serialized_node.outputs[0].as_tensor.name : null;
  19749. fx_node = this.graph.create_node('call_function', target, args, kwargs, name);
  19750. this.deserialize_outputs(serialized_node, fx_node);
  19751. } else {
  19752. throw new python.Error(`Unsupported node target type '${target}'.`);
  19753. }
  19754. fx_node.meta.update(this.deserialize_metadata(serialized_node.metadata));
  19755. if (fx_node.op !== 'placeholder' && fx_node.op !== 'output' && !fx_node.meta.has('nn_module_stack')) {
  19756. fx_node.meta.set('nn_module_stack', new builtins.dict());
  19757. }
  19758. }
  19759. deserialize_input_spec(i) {
  19760. if (i.type === 'user_input') {
  19761. return new torch.export.graph_signature.InputSpec(
  19762. torch.export.graph_signature.InputKind.USER_INPUT,
  19763. this.deserialize_argument_spec(i.user_input.arg),
  19764. null);
  19765. } else if (i.type === 'parameter') {
  19766. return new torch.export.graph_signature.InputSpec(
  19767. torch.export.graph_signature.InputKind.PARAMETER,
  19768. new torch.export.graph_signature.TensorArgument(i.parameter.arg.name),
  19769. i.parameter.parameter_name,
  19770. );
  19771. } else if (i.type === 'buffer') {
  19772. return new torch.export.graph_signature.InputSpec(
  19773. torch.export.graph_signature.InputKind.BUFFER,
  19774. new torch.export.graph_signature.TensorArgument(i.buffer.arg.name),
  19775. i.buffer.buffer_name,
  19776. i.buffer.persistent,
  19777. );
  19778. } else if (i.type === 'tensor_constant') {
  19779. return new torch.export.graph_signature.InputSpec(
  19780. torch.export.graph_signature.InputKind.CONSTANT_TENSOR,
  19781. new torch.export.graph_signature.TensorArgument(i.tensor_constant.arg.name),
  19782. i.tensor_constant.tensor_constant_name);
  19783. } else if (i.type === 'custom_obj') {
  19784. return new torch.export.graph_signature.InputSpec(
  19785. torch.export.graph_signature.InputKind.CUSTOM_OBJ,
  19786. new torch.export.graph_signature.CustomObjArgument(i.custom_obj.arg.name, i.custom_obj.arg.class_fqn),
  19787. i.custom_obj.custom_obj_name);
  19788. } else if (i.type === 'token') {
  19789. return new torch.export.graph_signature.InputSpec(
  19790. torch.export.graph_signature.InputKind.TOKEN,
  19791. new torch.export.graph_signature.TokenArgument(i.token.arg.name),
  19792. null);
  19793. } else if (i.type === 'constant_input') {
  19794. return new torch.export.graph_signature.InputSpec(
  19795. torch.export.graph_signature.InputKind.USER_INPUT,
  19796. new torch.export.graph_signature.ConstantArgument(i.constant_input.name, this.deserialize_constant_input(i.constant_input.value)),
  19797. null);
  19798. }
  19799. throw new python.Error(`Unknown input spec ${i}`);
  19800. }
  19801. deserialize_constant_input(inp) {
  19802. if (inp.type === 'as_int') {
  19803. return inp.as_int;
  19804. } else if (inp.type === 'as_float') {
  19805. return inp.as_float;
  19806. } else if (inp.type === 'as_string') {
  19807. return inp.as_string;
  19808. } else if (inp.type === 'as_bool') {
  19809. return inp.as_bool;
  19810. } else if (inp.type === 'as_none') {
  19811. return null;
  19812. }
  19813. throw new python.Error(`Unhandled constant argument ${inp} to deserialize.`);
  19814. }
  19815. deserialize_output_spec(o) {
  19816. if (o.type === 'user_output') {
  19817. return new torch.export.graph_signature.OutputSpec(
  19818. torch.export.graph_signature.OutputKind.USER_OUTPUT,
  19819. this.deserialize_argument_spec(o.user_output.arg),
  19820. null);
  19821. } else if (o.type === 'loss_output') {
  19822. return new torch.export.graph_signature.OutputSpec(
  19823. torch.export.graph_signature.OutputKind.LOSS_OUTPUT,
  19824. new torch.export.graph_signature.TensorArgument(o.loss_output.arg.name),
  19825. null);
  19826. } else if (o.type === 'buffer_mutation') {
  19827. return new torch.export.graph_signature.OutputSpec(
  19828. torch.export.graph_signature.OutputKind.BUFFER_MUTATION,
  19829. new torch.export.graph_signature.TensorArgument(o.buffer_mutation.arg.name),
  19830. o.buffer_mutation.buffer_name);
  19831. } else if (o.type === 'gradient_to_parameter') {
  19832. return new torch.export.graph_signature.OutputSpec(
  19833. torch.export.graph_signature.OutputKind.GRADIENT_TO_PARAMETER,
  19834. new torch.export.graph_signature.TensorArgument(o.gradient_to_parameter.arg.name),
  19835. o.gradient_to_parameter.parameter_name);
  19836. } else if (o.type === 'gradient_to_user_input') {
  19837. return new torch.export.graph_signature.OutputSpec(
  19838. torch.export.graph_signature.OutputKind.GRADIENT_TO_USER_INPUT,
  19839. new torch.export.graph_signature.TensorArgument(o.gradient_to_user_input.arg.name),
  19840. o.gradient_to_user_input.user_input_name);
  19841. } else if (o.type === 'user_input_mutation') {
  19842. return new torch.export.graph_signature.OutputSpec(
  19843. torch.export.graph_signature.OutputKind.USER_INPUT_MUTATION,
  19844. new torch.export.graph_signature.TensorArgument(o.user_input_mutation.arg.name),
  19845. o.user_input_mutation.user_input_name);
  19846. } else if (o.type === 'token') {
  19847. return new torch.export.graph_signature.OutputSpec(
  19848. torch.export.graph_signature.OutputKind.TOKEN,
  19849. new torch.export.graph_signature.TokenArgument(o.token.arg.name),
  19850. null);
  19851. }
  19852. throw new python.Error(`Unknown output spec ${o}.`);
  19853. }
  19854. deserialize_signature(sig) {
  19855. return new torch.export.graph_signature.ExportGraphSignature(
  19856. sig.input_specs.map((i) => this.deserialize_input_spec(i)),
  19857. sig.output_specs.map((o) => this.deserialize_output_spec(o)));
  19858. }
  19859. deserialize(serialized_graph_module, serialized_state_dict, constants, example_inputs, symbol_name_to_range) {
  19860. this.shape_env = new torch.fx.experimental.symbolic_shapes.ShapeEnv(/* assume_static_by_default = True */);
  19861. this.fake_tensor_mode = new torch._subclasses.fake_tensor.FakeTensorMode(false, true, this.shape_env);
  19862. this.sympy_functions = new Map([
  19863. ['FloorDiv', torch.utils._sympy.functions.FloorDiv],
  19864. ['ModularIndexing', torch.utils._sympy.functions.ModularIndexing],
  19865. ['Where', torch.utils._sympy.functions.Where],
  19866. ['PythonMod', torch.utils._sympy.functions.PythonMod],
  19867. ['Mod', torch.utils._sympy.functions.Mod],
  19868. ['CleanDiv', torch.utils._sympy.functions.CleanDiv],
  19869. ['CeilToInt', torch.utils._sympy.functions.CeilToInt],
  19870. ['FloorToInt', torch.utils._sympy.functions.FloorToInt],
  19871. ['CeilDiv', torch.utils._sympy.functions.CeilDiv],
  19872. ['LShift', torch.utils._sympy.functions.LShift],
  19873. ['RShift', torch.utils._sympy.functions.RShift],
  19874. ['PowByNatural', torch.utils._sympy.functions.PowByNatural],
  19875. ['FloatPow', torch.utils._sympy.functions.FloatPow],
  19876. ['FloatTrueDiv', torch.utils._sympy.functions.FloatTrueDiv],
  19877. ['IntTrueDiv', torch.utils._sympy.functions.IntTrueDiv],
  19878. ['IsNonOverlappingAndDenseIndicator', torch.utils._sympy.functions.IsNonOverlappingAndDenseIndicator],
  19879. ['TruncToFloat', torch.utils._sympy.functions.TruncToFloat],
  19880. ['TruncToInt', torch.utils._sympy.functions.TruncToInt],
  19881. ['RoundToInt', torch.utils._sympy.functions.RoundToInt],
  19882. ['RoundDecimal', torch.utils._sympy.functions.RoundDecimal],
  19883. ['ToFloat', torch.utils._sympy.functions.ToFloat],
  19884. ['Identity', torch.utils._sympy.functions.Identity],
  19885. ]);
  19886. this.symbol_name_to_symbol = new Map();
  19887. this.constants = torch._export.serde.serialize.deserialize_torch_artifact(constants);
  19888. this.signature = this.deserialize_signature(serialized_graph_module.signature);
  19889. this.symbol_name_to_range = symbol_name_to_range || new Map();
  19890. /*
  19891. if symbol_name_to_range:
  19892. for k, vr in symbol_name_to_range.items():
  19893. lower = int(vr.lower)
  19894. if vr.upper >= 2: # max is >= 2, not sym bool range
  19895. lower = max(2, lower)
  19896. this.symbol_name_to_range[k] = symbolic_shapes.ValueRanges(_int_to_sympy_int(lower), vr.upper)
  19897. */
  19898. this.example_inputs = null;
  19899. if (example_inputs) {
  19900. this.example_inputs = torch._export.serde.serialize.deserialize_torch_artifact(example_inputs);
  19901. }
  19902. this.deserialize_graph(serialized_graph_module.graph);
  19903. const module_call_graph = null; // this.deserialize_module_call_graph(serialized_graph_module.module_call_graph)
  19904. return {
  19905. graph_module: torch._export.exported_program._create_graph_module_for_export(this.module, this.graph),
  19906. signature: this.signature,
  19907. module_call_graph,
  19908. names_to_symbols: this.symbol_name_to_symbol,
  19909. state_dict: torch._export.serde.serialize.deserialize_torch_artifact(serialized_state_dict),
  19910. constants: this.constants,
  19911. example_inputs: this.example_inputs,
  19912. };
  19913. }
  19914. sync_fx_node(name, fx_node) {
  19915. if (this.serialized_name_to_node.has(name)) {
  19916. throw new python.Error(`Node ${name} has already been deserialized before.`);
  19917. }
  19918. this.serialized_name_to_node.set(name, fx_node);
  19919. fx_node.meta.set('val', this.serialized_name_to_meta.get(name));
  19920. }
  19921. deserialize_sym_op_inputs(inputs) {
  19922. return inputs.map((input) => this.deserialize_input(input.arg));
  19923. }
  19924. deserialize_inputs(target, serialized_node) {
  19925. const schema_args = this._get_schema_from_target(target).arguments;
  19926. const actual_args = new Map(serialized_node.inputs.map((input) => [input.name, this.deserialize_input(input.arg)]));
  19927. const args = new builtins.list();
  19928. const kwargs = new builtins.dict();
  19929. for (const schema_arg of schema_args) {
  19930. const is_positional = !schema_arg.has_default_value() && !schema_arg.kwarg_only;
  19931. if (is_positional) {
  19932. args.push(actual_args.get(schema_arg.name));
  19933. } else if (actual_args.has(schema_arg.name)) {
  19934. kwargs.set(schema_arg.name, actual_args.get(schema_arg.name));
  19935. }
  19936. }
  19937. return [args, kwargs];
  19938. }
  19939. deserialize_hoo_inputs(inputs) {
  19940. const args = [];
  19941. const kwargs = new builtins.dict();
  19942. for (const input_ of inputs) {
  19943. if (input_.name === '') {
  19944. args.push(this.deserialize_input(input_.arg));
  19945. } else {
  19946. kwargs.set(input_.name, this.deserialize_input(input_.arg));
  19947. }
  19948. }
  19949. return [new builtins.tuple(args), kwargs];
  19950. }
  19951. deserialize_input(inp) {
  19952. const value = inp.value;
  19953. const typ_ = inp.type;
  19954. if (typ_ === 'as_none') {
  19955. return null;
  19956. } else if (typ_ === 'as_tensor') {
  19957. return this.serialized_name_to_node.get(inp.as_tensor.name);
  19958. } else if (typ_ === 'as_scalar_type') {
  19959. return torch._export.serde.serialize.deserialize_scalar_type(inp.as_scalar_type);
  19960. } else if (typ_ === 'as_memory_format') {
  19961. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_MEMORY_FORMAT[inp.as_memory_format];
  19962. } else if (typ_ === 'as_layout') {
  19963. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_LAYOUT[inp.as_layout];
  19964. } else if (typ_ === 'as_graph') {
  19965. const context = this.save_graph_module();
  19966. context.__enter__();
  19967. this.deserialize_graph(value.graph);
  19968. const submodule = torch.export.exported_program._create_graph_module_for_export(this.module, this.graph);
  19969. context.__exit__(null, null, null);
  19970. this.module.register_module(value.name, submodule);
  19971. return this.graph.create_node('get_attr', value.name, null, null, value.name);
  19972. } else if (typ_ === 'as_device') {
  19973. return this.deserialize_device(inp.as_device);
  19974. } else if (typ_ === 'as_int') {
  19975. return inp.as_int;
  19976. } else if (typ_ === 'as_float') {
  19977. return inp.as_float;
  19978. } else if (typ_ === 'as_bool') {
  19979. return inp.as_bool;
  19980. } else if (typ_ === 'as_string') {
  19981. return inp.as_string;
  19982. } else if (typ_ === 'as_sym_int') {
  19983. return this.deserialize_sym_argument(inp.as_sym_int);
  19984. } else if (typ_ === 'as_sym_float') {
  19985. return this.deserialize_sym_argument(inp.as_sym_float);
  19986. } else if (typ_ === 'as_sym_bool') {
  19987. return this.deserialize_sym_argument(inp.as_sym_bool);
  19988. } else if (Array.isArray(value)) {
  19989. if (value.length === 0) {
  19990. return [];
  19991. } else if (typ_ === 'as_tensors') {
  19992. const result = [];
  19993. for (const arg of value) {
  19994. result.push(this.serialized_name_to_node.get(arg.name));
  19995. }
  19996. return result;
  19997. } else if (typ_ === 'as_ints' || typ_ === 'as_floats' || typ_ === 'as_bools' || typ_ === 'as_strings') {
  19998. return Array.from(value);
  19999. } else if (typ_ === 'as_sym_ints' || typ_ === 'as_sym_bools') {
  20000. return value.map((arg) => this.deserialize_sym_argument(arg));
  20001. } else if (typ_ === 'as_optional_tensors') {
  20002. const deserialize_optional_tensor_args = (a) => {
  20003. if (a.type === 'as_none') {
  20004. return null;
  20005. } else if (a.type === 'as_tensor') {
  20006. return this.serialized_name_to_node.get(a.value.name);
  20007. }
  20008. throw new python.Error(`Unsupported argument '${typ_}'.`);
  20009. };
  20010. return value.map((item) => deserialize_optional_tensor_args(item));
  20011. }
  20012. throw new python.Error(`Unsupported argument '${typ_}'.`);
  20013. } else if (typ_ === 'as_custom_obj') {
  20014. if (this.serialized_name_to_node.has(inp.as_custom_obj.name)) {
  20015. return this.serialized_name_to_node.get(inp.as_custom_obj.name);
  20016. }
  20017. return this.constants[inp.as_custom_obj.name];
  20018. } else if (typ_ === 'as_operator') {
  20019. return this.deserialize_operator(inp.as_operator);
  20020. }
  20021. throw new python.Error(`Unsupported argument '${typ_}'.`);
  20022. }
  20023. deserialize_sym_argument(sym_arg) {
  20024. if (sym_arg instanceof torch._export.serde.schema.SymIntArgument) {
  20025. if (sym_arg.type === 'as_int') {
  20026. return sym_arg.as_int;
  20027. } else if (sym_arg.type === 'as_name') {
  20028. return this.serialized_name_to_node.get(sym_arg.as_name);
  20029. }
  20030. } else if (sym_arg instanceof torch._export.serde.schema.SymFloatArgument) {
  20031. if (sym_arg.type === 'as_float') {
  20032. return sym_arg.as_float;
  20033. } else if (sym_arg.type === 'as_name') {
  20034. return this.serialized_name_to_node.get(sym_arg.as_name);
  20035. }
  20036. } else if (sym_arg instanceof torch._export.serde.schema.SymBoolArgument) {
  20037. if (sym_arg.type === 'as_bool') {
  20038. return sym_arg.as_bool;
  20039. } else if (sym_arg.type === 'as_name') {
  20040. return this.serialized_name_to_node.get(sym_arg.as_name);
  20041. }
  20042. }
  20043. throw new python.Error(`Unsupported symbolic argument type '${sym_arg.type}`);
  20044. }
  20045. deserialize_sym_op_outputs(serialized_node, fx_node) {
  20046. this.sync_fx_node(serialized_node.outputs[0].value.as_name, fx_node);
  20047. }
  20048. deserialize_outputs(serialized_node, fx_node) {
  20049. if (serialized_node.outputs.length === 0) {
  20050. return;
  20051. }
  20052. if (serialized_node.outputs.length === 1 &&
  20053. serialized_node.outputs[0].type === 'as_tensor') {
  20054. this.sync_fx_node(serialized_node.outputs[0].as_tensor.name, fx_node);
  20055. return;
  20056. } else if (serialized_node.outputs.length === 1 &&
  20057. (serialized_node.outputs[0].value instanceof torch._export.serde.schema.SymIntArgument ||
  20058. serialized_node.outputs[0].value instanceof torch._export.serde.schema.SymBoolArgument)) {
  20059. this.sync_fx_node(serialized_node.outputs[0].value.as_name, fx_node);
  20060. return;
  20061. }
  20062. this.deserialize_multiple_outputs(serialized_node, fx_node);
  20063. }
  20064. deserialize_multiple_outputs(serialized_node, fx_node) {
  20065. const deserialized_metadata = this.deserialize_metadata(serialized_node.metadata);
  20066. const generate_getitem = (meta_val, fx_node, arg, idx) => {
  20067. let name = '';
  20068. if (arg instanceof torch._export.serde.schema.TensorArgument) {
  20069. name = arg.name;
  20070. } else if (arg instanceof torch._export.serde.schema.SymIntArgument) {
  20071. name = arg.as_name;
  20072. } else if (arg instanceof torch._export.serde.schema.SymFloatArgument) {
  20073. name = arg.as_name;
  20074. } else {
  20075. throw new python.Error(`Unsupported argument type '${arg}'.`);
  20076. }
  20077. const individual_output = this.graph.create_node(
  20078. 'call_function',
  20079. operator.getitem,
  20080. new builtins.tuple([fx_node, idx]),
  20081. null,
  20082. name,
  20083. );
  20084. this.sync_fx_node(name, individual_output);
  20085. meta_val.push(this.serialized_name_to_meta.get(name));
  20086. individual_output.meta.update(deserialized_metadata);
  20087. };
  20088. const generate_getitems = (meta_val, fx_node, args) => {
  20089. for (let idx = 0; idx < args.length; idx++) {
  20090. const arg = args[idx];
  20091. if (arg instanceof torch._export.serde.schema.TensorArgument ||
  20092. arg instanceof torch._export.serde.schema.SymIntArgument ||
  20093. arg instanceof torch._export.serde.schema.SymFloatArgument) {
  20094. generate_getitem(meta_val, fx_node, arg, idx);
  20095. } else if (arg instanceof torch._export.serde.schema.Argument) {
  20096. if (arg.type === 'as_tensor' || arg.type === 'as_sym_int' || arg.type === 'as_sym_float') {
  20097. generate_getitem(meta_val, fx_node, arg.value, idx);
  20098. } else if (arg.type === 'as_none') {
  20099. const individual_output = this.graph.create_node(
  20100. 'call_function',
  20101. operator.getitem,
  20102. new builtins.tuple([fx_node, idx]),
  20103. null,
  20104. 'as_none',
  20105. );
  20106. meta_val.push(null);
  20107. individual_output.meta.set('val', null);
  20108. individual_output.meta.update(deserialized_metadata);
  20109. } else if (Array.isArray(arg.value)) {
  20110. const list_output = this.graph.create_node(
  20111. 'call_function',
  20112. operator.getitem,
  20113. new builtins.tuple([fx_node, idx]),
  20114. );
  20115. meta_val.push([]);
  20116. generate_getitems(meta_val[meta_val.length - 1], list_output, arg.value);
  20117. list_output.meta.update(deserialized_metadata);
  20118. list_output.meta.set('val', meta_val[meta_val.length - 1]);
  20119. } else {
  20120. throw new python.Error(`Unsupported node output type '${arg.type}'.`);
  20121. }
  20122. } else if (Array.isArray(arg)) {
  20123. const list_output = this.graph.create_node(
  20124. 'call_function',
  20125. operator.getitem,
  20126. new builtins.tuple([fx_node, idx]),
  20127. );
  20128. meta_val.push([]);
  20129. generate_getitems(meta_val[meta_val.length - 1], list_output, arg);
  20130. list_output.meta.update(deserialized_metadata);
  20131. list_output.meta.set('val', meta_val[meta_val.length - 1]);
  20132. } else {
  20133. throw new python.Error(`Unsupported node output type '${arg}'.`);
  20134. }
  20135. }
  20136. };
  20137. const meta_val = [];
  20138. if (serialized_node.outputs.length === 1) {
  20139. generate_getitems(meta_val, fx_node, serialized_node.outputs[0].value);
  20140. } else {
  20141. generate_getitems(meta_val, fx_node, serialized_node.outputs);
  20142. }
  20143. fx_node.meta.set('val', new builtins.tuple(meta_val));
  20144. this.serialized_name_to_node.set(fx_node.name, fx_node);
  20145. }
  20146. deserialize_metadata(metadata) {
  20147. const ret = new builtins.dict();
  20148. const stack_trace = metadata.get('stack_trace');
  20149. if (stack_trace) {
  20150. ret.set('stack_trace', stack_trace);
  20151. }
  20152. const deserialize_meta_func = (serialized_target) => {
  20153. let module = null;
  20154. let serialized_target_names = [];
  20155. if (serialized_target.startsWith('torch.nn')) {
  20156. module = torch.nn;
  20157. serialized_target_names = serialized_target.split('.').slice(1);
  20158. } else if (serialized_target.startsWith('torch')) {
  20159. module = torch;
  20160. serialized_target_names = serialized_target.split('.').slice(1);
  20161. } else {
  20162. return this.deserialize_operator(serialized_target);
  20163. }
  20164. let target = module;
  20165. for (const name of serialized_target_names) {
  20166. if (!builtins.hasattr(target, name)) {
  20167. return serialized_target;
  20168. }
  20169. target = builtins.getattr(target, name);
  20170. }
  20171. return target;
  20172. };
  20173. const nn_module_stack_str = metadata.get('nn_module_stack');
  20174. if (nn_module_stack_str) {
  20175. const import_nn_module_stack = (key, path, ty) => {
  20176. return [key, [path, ty]];
  20177. };
  20178. const nn_module_stack = new Map(nn_module_stack_str.split(';').map((item) => import_nn_module_stack(...item.split(','))));
  20179. ret.set('nn_module_stack', nn_module_stack);
  20180. }
  20181. const source_fn_st_str = metadata.get('source_fn_stack');
  20182. if (source_fn_st_str) {
  20183. const source_fn_st = [];
  20184. for (const source_fn_str of source_fn_st_str.split(';')) {
  20185. const [name, target_str] = source_fn_str.split(',');
  20186. source_fn_st.push([name, deserialize_meta_func(target_str)]);
  20187. }
  20188. ret.set('source_fn_stack', source_fn_st);
  20189. }
  20190. const torch_fn = metadata.get('torch_fn');
  20191. if (torch_fn) {
  20192. ret.set('torch_fn', new builtins.tuple(torch_fn.split(';')));
  20193. }
  20194. const custom_str = metadata.get('custom');
  20195. if (custom_str) {
  20196. ret.set('custom', JSON.parse(custom_str));
  20197. }
  20198. return ret;
  20199. }
  20200. deserialize_argument_spec(x) {
  20201. if (x.type === 'as_tensor') {
  20202. return new torch.export.graph_signature.TensorArgument(x.as_tensor.name);
  20203. } else if (x.type === 'as_sym_int') {
  20204. return new torch.export.graph_signature.SymIntArgument(x.as_sym_int.as_name);
  20205. } else if (x.type === 'as_custom_obj') {
  20206. return new torch.export.graph_signature.ConstantArgument(x.as_custom_obj.name, this.deserialize_input(x));
  20207. }
  20208. return new torch.export.graph_signature.ConstantArgument('', this.deserialize_input(x));
  20209. }
  20210. deserialize_tensor_meta(tensor_meta) {
  20211. try {
  20212. this.fake_tensor_mode.__enter__();
  20213. const sizes = tensor_meta.sizes.map((val) => this.deserialize_sym_int(val));
  20214. const strides = tensor_meta.strides.map((val) => this.deserialize_sym_int(val));
  20215. const device = this.deserialize_device(tensor_meta.device);
  20216. const dtype = torch._export.serde.serialize.deserialize_scalar_type(tensor_meta.dtype);
  20217. return torch.empty_strided(sizes, strides, dtype, null, device);
  20218. } finally {
  20219. this.fake_tensor_mode.__exit__(null, null, null);
  20220. }
  20221. }
  20222. deserialize_script_obj_meta(script_obj_meta) {
  20223. return new torch.export.graph_signature.CustomObjArgument(script_obj_meta.name, script_obj_meta.class_fqn);
  20224. }
  20225. _parse_sym_expr(expr_str, hint) {
  20226. const _process_sym_expr = (sym, hint) => {
  20227. if (sym.is_Integer || sym.is_Float || sym.is_Boolean) {
  20228. return sym;
  20229. }
  20230. expr_str = sym.__str__();
  20231. for (const arg of sym.args) {
  20232. this._parse_sym_expr(arg);
  20233. }
  20234. if (this.symbol_name_to_symbol.has(expr_str)) {
  20235. sym = this.symbol_name_to_symbol.get(expr_str);
  20236. } else {
  20237. this.symbol_name_to_symbol.set(expr_str, sym);
  20238. 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])) {
  20239. this.unbacked_symbols.add(sym);
  20240. }
  20241. }
  20242. if (hint !== null && !this.shape_env.var_to_val.has(sym)) {
  20243. this.shape_env.add_var_to_val(sym, hint);
  20244. }
  20245. const vr = this.symbol_name_to_range.get(expr_str);
  20246. if (vr) {
  20247. this.shape_env.constrain_symbol_range(sym, vr.lower, vr.upper);
  20248. }
  20249. if (builtins.isinstance(sym, sympy.core.symbol.Symbol)) {
  20250. this.shape_env.var_to_stack.set(sym, torch.utils._traceback.CapturedTraceback.extract(false, false, 1));
  20251. }
  20252. return sym;
  20253. };
  20254. const locals = new Map([...this.sympy_functions, ...this.symbol_name_to_symbol]);
  20255. const expr = sympy.core.sympify.sympify(expr_str, locals);
  20256. return _process_sym_expr(expr, hint);
  20257. }
  20258. deserialize_sym_int(s) {
  20259. const val = s.value;
  20260. let hint = null;
  20261. if (s.type === 'as_expr') {
  20262. if (val.hint === null) {
  20263. hint = null;
  20264. } else {
  20265. // assert val.hint.type == "as_int"
  20266. hint = val.hint.value;
  20267. }
  20268. const sym = this._parse_sym_expr(val.expr_str, hint);
  20269. return this.shape_env.create_symintnode(sym, hint);
  20270. } else if (s.type === 'as_int') {
  20271. // assert type(val) is int
  20272. return val;
  20273. }
  20274. throw new python.Error(`SymInt has invalid field type ${s.type} with value ${s.value}.`);
  20275. }
  20276. deserialize_sym_bool(s) {
  20277. const val = s.value;
  20278. let hint = null;
  20279. if (s.type === 'as_expr') {
  20280. if (val.hint === null) {
  20281. hint = null;
  20282. } else {
  20283. // assert val.hint.type == "as_bool"
  20284. hint = val.hint.value;
  20285. }
  20286. const sym = this._parse_sym_expr(val.expr_str, hint);
  20287. return this.shape_env.create_symboolnode(sym, hint);
  20288. } else if (s.type === 'as_bool') {
  20289. // assert type(val) is bool
  20290. return val;
  20291. }
  20292. throw new python.Error(`SymBool has invalid field type ${s.type} with value ${s.value}.`);
  20293. }
  20294. deserialize_device(d) {
  20295. if (d.index === null) {
  20296. return new torch.device(d.type);
  20297. }
  20298. return new torch.device(d.type, d.index);
  20299. }
  20300. _get_schema_from_target(target) {
  20301. if (target instanceof torch._ops.OpOverload) {
  20302. return target._schema;
  20303. }
  20304. throw new python.Error(`Unsupported schema '${target.name}'.`);
  20305. }
  20306. _is_single_tensor_return(target) {
  20307. const schema = this._get_schema_from_target(target);
  20308. const returns = schema.returns;
  20309. return returns.length === 1 && returns[0].real_type instanceof torch.TensorType;
  20310. }
  20311. });
  20312. this.registerType('torch._export.verifier.Verifier', class {});
  20313. this.registerType('torch._dynamo.convert_frame.CatchErrorsWrapper', class {});
  20314. this.registerType('torch._dynamo.convert_frame.ConvertFrameAssert', class {});
  20315. this.registerType('torch._dynamo.convert_frame.ConvertFrame', class {});
  20316. this.registerType('torch._dynamo.convert_frame.ConvertFrameBox', class {});
  20317. this.registerType('torch._dynamo.eval_frame._TorchDynamoContext', class {});
  20318. this.registerType('torch._dynamo.eval_frame.OptimizedModule', class extends torch.nn.modules.module.Module {
  20319. constructor(mod, dynamo_ctx) {
  20320. builtins.object.__setattr__(self, '_orig_mod', mod);
  20321. // this._super_module_initialized = false;
  20322. super();
  20323. // this._super_module_initialized = true;
  20324. this._orig_mod = mod;
  20325. this.dynamo_ctx = dynamo_ctx;
  20326. // this._initialize();
  20327. this.training = this._orig_mod.training;
  20328. }
  20329. });
  20330. this.registerType('torch._dynamo.eval_frame.OptimizeContext', class extends torch._dynamo.eval_frame._TorchDynamoContext {});
  20331. this.registerType('torch._dynamo.hooks.Hooks', class {});
  20332. this.registerType('torch._dynamo.output_graph.GraphCompileReason', class {});
  20333. this.registerType('torch._dynamo.repro.after_dynamo.WrapBackendDebug', class {});
  20334. this.registerType('torch._TorchCompileInductorWrapper', class {});
  20335. this.registerFunction('torch._inductor.compile_fx.compile_fx');
  20336. this.registerFunction('torch_utils.persistence._reconstruct_persistent_obj', (meta) => {
  20337. const name = `_imported_module_${Math.floor(Math.random() * 10000)}`;
  20338. const module = new types.ModuleType(name);
  20339. execution.register('sys').modules.set(name, module);
  20340. const context = new python.Execution.Context(module, null);
  20341. execution.exec(meta.get('module_src'), context);
  20342. const obj = execution.invoke(`${name}.${meta.get('class_name')}`, []);
  20343. const state = meta.get('state');
  20344. if (state) {
  20345. if (obj.__setstate__) {
  20346. obj.__setstate__(state);
  20347. } else {
  20348. for (const [key, value] of state) {
  20349. obj[key] = value;
  20350. }
  20351. }
  20352. }
  20353. return obj;
  20354. });
  20355. this.registerFunction('torch_utils.misc.assert_shape', (/* tensor, ref_shape */) => {});
  20356. this.registerFunction('torch_utils.ops.conv2d_resample.conv2d_resample', (/* x, w, f, up, down, padding, groups, flip_weight, flip_filter */) => {});
  20357. this.registerFunction('torch_utils.ops.upfirdn2d.setup_filter', (/* x, f, up, down, padding, flip_filter, gain, impl */) => {});
  20358. this.registerFunction('torch_utils.ops.bias_act', (/* x, b, dim, act, alpha, gain, clamp, impl */) => {});
  20359. this.registerFunction('torch_utils.ops.fma.fma', (/* a, b, c */) => {});
  20360. this.registerType('torch.device', class {
  20361. constructor(type, index) {
  20362. this.type = type;
  20363. this.index = index ? index : null;
  20364. }
  20365. __str__() {
  20366. return this.index === null ? this.type : `${this.type}:${this.index}`;
  20367. }
  20368. toString() {
  20369. const index = this.index === null ? '' : `, index=${this.index}`;
  20370. return `device(type='${this.type}'${index})`;
  20371. }
  20372. });
  20373. this.registerType('torch.memory_format', class {
  20374. constructor(name) {
  20375. this.name = name;
  20376. }
  20377. __str__() {
  20378. return `torch.${this.name}`;
  20379. }
  20380. toString() {
  20381. return this.__str__();
  20382. }
  20383. });
  20384. this.registerType('torch.dtype', class {
  20385. constructor(scalar_type, name, itemsize) {
  20386. this._scalar_type = scalar_type;
  20387. this._name = name;
  20388. this._itemsize = itemsize;
  20389. }
  20390. scalar_type() {
  20391. return this._scalar_type;
  20392. }
  20393. itemsize() {
  20394. return this._itemsize;
  20395. }
  20396. __reduce__() {
  20397. return this._name;
  20398. }
  20399. __str__() {
  20400. return `torch.${this._name}`;
  20401. }
  20402. toString() {
  20403. return this.__str__();
  20404. }
  20405. });
  20406. this.registerType('torch.layout', class {
  20407. constructor(name) {
  20408. this._name = name;
  20409. }
  20410. __str__() {
  20411. return `torch.${this._name}`;
  20412. }
  20413. toString() {
  20414. return this.__str__();
  20415. }
  20416. });
  20417. this.registerType('torch.qscheme', class {
  20418. constructor(name) {
  20419. this._name = name;
  20420. }
  20421. __str__() {
  20422. return this._name;
  20423. }
  20424. toString() {
  20425. return this.__str__();
  20426. }
  20427. });
  20428. this.registerType('torch.utils.hooks.RemovableHandle', class {
  20429. __setstate__(state) {
  20430. [this.hooks_dict_ref, this.id] = state;
  20431. this.hooks_dict_ref = this.hooks_dict_ref || new Map();
  20432. }
  20433. });
  20434. this.registerType('torch.storage._StorageBase', class {
  20435. constructor(size, dtype) {
  20436. this._size = size;
  20437. this._dtype = dtype;
  20438. this._device = null;
  20439. }
  20440. get device() {
  20441. return this._device;
  20442. }
  20443. get dtype() {
  20444. return this._dtype;
  20445. }
  20446. element_size() {
  20447. return this._dtype.element_size;
  20448. }
  20449. size() {
  20450. return this._size;
  20451. }
  20452. get data() {
  20453. return this._cdata;
  20454. }
  20455. _set_cdata(data) {
  20456. const length = this.size() * this.dtype.itemsize();
  20457. if (length !== data.length) {
  20458. throw new python.Error('Typed storage data size mismatch.');
  20459. }
  20460. this._cdata = data;
  20461. }
  20462. _set_from_file(unpickler) {
  20463. const buffer = unpickler.read(8);
  20464. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20465. if (size !== this.size()) {
  20466. throw new python.Error('Typed storage size mismatch.');
  20467. }
  20468. const itemsize = this.dtype.itemsize();
  20469. const data = unpickler.stream(itemsize * size);
  20470. this._set_cdata(data);
  20471. }
  20472. static _new_with_file(unpickler) {
  20473. const buffer = unpickler.read(8);
  20474. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20475. const storage = new this(size);
  20476. const itemsize = storage.dtype.itemsize();
  20477. const data = unpickler.stream(itemsize * size);
  20478. storage._set_cdata(data);
  20479. return storage;
  20480. }
  20481. });
  20482. this.registerType('torch.storage.UntypedStorage', class {
  20483. constructor(size) {
  20484. this._size = size;
  20485. }
  20486. size() {
  20487. return this._size;
  20488. }
  20489. get data() {
  20490. return this._cdata;
  20491. }
  20492. _set_cdata(data) {
  20493. if (this._size !== data.length) {
  20494. throw new python.Error('Untyped storage data size mismatch.');
  20495. }
  20496. this._cdata = data;
  20497. }
  20498. });
  20499. this.registerType('torch.storage.TypedStorage', class {
  20500. constructor(...args) {
  20501. if (args.length === 0) {
  20502. this._size = 0;
  20503. } else if (args.length === 1 && Number.isInteger(args[0])) {
  20504. [this._size] = args;
  20505. } else if (args.length >= 2 && Number.isInteger(args[0]) && args[1] instanceof torch.dtype) {
  20506. if (args[3] instanceof torch.device) {
  20507. [this._size, this.dtype, , this._device] = args;
  20508. } else {
  20509. [this._size, this.dtype] = args;
  20510. }
  20511. } else {
  20512. throw new python.Error(`Unsupported TypedStorage arguments '${JSON.stringify(args)}'.`);
  20513. }
  20514. }
  20515. get device() {
  20516. return this._device;
  20517. }
  20518. get dtype() {
  20519. return this._dtype;
  20520. }
  20521. set dtype(value) {
  20522. this._dtype = value;
  20523. }
  20524. element_size() {
  20525. return this._dtype.element_size;
  20526. }
  20527. size() {
  20528. return this._size;
  20529. }
  20530. get data() {
  20531. return this._cdata;
  20532. }
  20533. _set_cdata(data) {
  20534. const length = this.size() * this.dtype.itemsize();
  20535. if (length !== data.length) {
  20536. throw new python.Error('Storage data size mismatch.');
  20537. }
  20538. this._cdata = data;
  20539. }
  20540. _set_from_file(unpickler) {
  20541. const buffer = unpickler.read(8);
  20542. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20543. if (size !== this.size()) {
  20544. throw new python.Error('Storage size mismatch.');
  20545. }
  20546. const itemsize = this.dtype.itemsize();
  20547. const data = unpickler.stream(itemsize * size);
  20548. this._set_cdata(data);
  20549. }
  20550. static _new_with_file(unpickler) {
  20551. const buffer = unpickler.read(8);
  20552. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20553. const storage = new this(size);
  20554. const itemsize = storage.dtype.itemsize();
  20555. const data = unpickler.stream(itemsize * size);
  20556. storage._set_cdata(data);
  20557. return storage;
  20558. }
  20559. });
  20560. this.registerType('torch.storage._LegacyStorage', class extends torch.storage.TypedStorage {
  20561. });
  20562. this.registerType('torch.BoolStorage', class extends torch.storage._LegacyStorage {
  20563. constructor(...args) {
  20564. // eslint-disable-next-line no-constructor-return
  20565. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.BoolStorage.dtype);
  20566. }
  20567. });
  20568. this.registerType('torch.ByteStorage', class extends torch.storage._LegacyStorage {
  20569. constructor(...args) {
  20570. // eslint-disable-next-line no-constructor-return
  20571. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ByteStorage.dtype);
  20572. }
  20573. });
  20574. this.registerType('torch.CharStorage', class extends torch.storage._LegacyStorage {
  20575. constructor(...args) {
  20576. // eslint-disable-next-line no-constructor-return
  20577. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.CharStorage.dtype);
  20578. }
  20579. });
  20580. this.registerType('torch.ShortStorage', class extends torch.storage._LegacyStorage {
  20581. constructor(...args) {
  20582. // eslint-disable-next-line no-constructor-return
  20583. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ShortStorage.dtype);
  20584. }
  20585. });
  20586. this.registerType('torch.IntStorage', class extends torch.storage._LegacyStorage {
  20587. constructor(...args) {
  20588. // eslint-disable-next-line no-constructor-return
  20589. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.IntStorage.dtype);
  20590. }
  20591. });
  20592. this.registerType('torch.LongStorage', class extends torch.storage._LegacyStorage {
  20593. constructor(...args) {
  20594. // eslint-disable-next-line no-constructor-return
  20595. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.LongStorage.dtype);
  20596. }
  20597. });
  20598. this.registerType('torch.HalfStorage', class extends torch.storage._LegacyStorage {
  20599. constructor(...args) {
  20600. // eslint-disable-next-line no-constructor-return
  20601. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.HalfStorage.dtype);
  20602. }
  20603. });
  20604. this.registerType('torch.FloatStorage', class extends torch.storage._LegacyStorage {
  20605. constructor(...args) {
  20606. // eslint-disable-next-line no-constructor-return
  20607. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.FloatStorage.dtype);
  20608. }
  20609. });
  20610. this.registerType('torch.DoubleStorage', class extends torch.storage._LegacyStorage {
  20611. constructor(...args) {
  20612. // eslint-disable-next-line no-constructor-return
  20613. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.DoubleStorage.dtype);
  20614. }
  20615. });
  20616. this.registerType('torch.ComplexHalfStorage', class extends torch.storage._LegacyStorage {
  20617. constructor(...args) {
  20618. // eslint-disable-next-line no-constructor-return
  20619. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ComplexHalfStorage.dtype);
  20620. }
  20621. });
  20622. this.registerType('torch.ComplexFloatStorage', class extends torch.storage._LegacyStorage {
  20623. constructor(...args) {
  20624. // eslint-disable-next-line no-constructor-return
  20625. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ComplexFloatStorage.dtype);
  20626. }
  20627. });
  20628. this.registerType('torch.ComplexDoubleStorage', class extends torch.storage._LegacyStorage {
  20629. constructor(...args) {
  20630. // eslint-disable-next-line no-constructor-return
  20631. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ComplexDoubleStorage.dtype);
  20632. }
  20633. });
  20634. this.registerType('torch.QInt8Storage', class extends torch.storage._LegacyStorage {
  20635. constructor(...args) {
  20636. // eslint-disable-next-line no-constructor-return
  20637. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt8Storage.dtype);
  20638. }
  20639. });
  20640. this.registerType('torch.QUInt8Storage', class extends torch.storage._LegacyStorage {
  20641. constructor(...args) {
  20642. // eslint-disable-next-line no-constructor-return
  20643. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt8Storage.dtype);
  20644. }
  20645. });
  20646. this.registerType('torch.QInt32Storage', class extends torch.storage._LegacyStorage {
  20647. constructor(...args) {
  20648. // eslint-disable-next-line no-constructor-return
  20649. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QInt32Storage.dtype);
  20650. }
  20651. });
  20652. this.registerType('torch.BFloat16Storage', class extends torch.storage._LegacyStorage {
  20653. constructor(...args) {
  20654. // eslint-disable-next-line no-constructor-return
  20655. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.BFloat16Storage.dtype);
  20656. }
  20657. });
  20658. this.registerType('torch.QUInt4x2Storage', class extends torch.storage._LegacyStorage {
  20659. constructor(...args) {
  20660. // eslint-disable-next-line no-constructor-return
  20661. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt4x2Storage.dtype);
  20662. }
  20663. });
  20664. this.registerType('torch.QUInt2x4Storage', class extends torch.storage._LegacyStorage {
  20665. constructor(...args) {
  20666. // eslint-disable-next-line no-constructor-return
  20667. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt2x4Storage.dtype);
  20668. }
  20669. });
  20670. this.registerType('torch.UInt16Storage', class extends torch.storage._LegacyStorage {
  20671. constructor(...args) {
  20672. // eslint-disable-next-line
  20673. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.UInt16Storage.dtype);
  20674. }
  20675. });
  20676. this.registerType('torch.UInt32Storage', class extends torch.storage._LegacyStorage {
  20677. constructor(...args) {
  20678. // eslint-disable-next-line no-constructor-return
  20679. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.UInt32Storage.dtype);
  20680. }
  20681. });
  20682. this.registerType('torch.UInt64Storage', class extends torch.storage._LegacyStorage {
  20683. constructor(...args) {
  20684. // eslint-disable-next-line no-constructor-return
  20685. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.UInt64Storage.dtype);
  20686. }
  20687. });
  20688. this.registerType('torch.Size', class extends Array {
  20689. constructor(size) {
  20690. super(size.length);
  20691. for (let i = 0; i < size.length; i++) {
  20692. this[i] = size[i];
  20693. }
  20694. }
  20695. __len__() {
  20696. return this.length;
  20697. }
  20698. });
  20699. this.registerType('torch._C.TensorMeta', class {
  20700. });
  20701. this.registerType('torch._C.TensorBase', class extends torch._C.TensorMeta {
  20702. });
  20703. this.registerType('torch.Tensor', class extends torch._C.TensorBase {
  20704. constructor(storage, shape, dtype, layout, device, requires_grad) {
  20705. super();
  20706. if (storage) {
  20707. this._storage = storage;
  20708. }
  20709. if (shape !== null && shape !== undefined) {
  20710. this._shape = shape;
  20711. }
  20712. if (dtype) {
  20713. this._dtype = dtype;
  20714. }
  20715. this._layout = layout || torch.strided;
  20716. if (device) {
  20717. this._device = device;
  20718. }
  20719. if (requires_grad !== undefined) {
  20720. this.requires_grad = requires_grad;
  20721. }
  20722. }
  20723. clone() {
  20724. const tensor = new torch.Tensor(this._storage, this._shape, this._dtype, this._layout, this._device, this.requires_grad);
  20725. tensor._storage_offset = this._storage_offset;
  20726. tensor._stride = this._stride;
  20727. tensor._values = this._values;
  20728. tensor._indices = this._indices;
  20729. tensor.__quantized__ = this.__quantized__;
  20730. tensor.__nested__ = this.__nested__;
  20731. tensor.data = this.data;
  20732. tensor._backward_hooks = this._backward_hooks;
  20733. return tensor;
  20734. }
  20735. get device() {
  20736. if (this._device !== undefined) {
  20737. return this._device;
  20738. }
  20739. return this.storage().device;
  20740. }
  20741. get dtype() {
  20742. if (this._dtype !== undefined) {
  20743. return this._dtype;
  20744. }
  20745. if (this._layout === torch.sparse_coo) {
  20746. return this._values.dtype;
  20747. }
  20748. return this.storage().dtype;
  20749. }
  20750. get shape() {
  20751. return this._shape;
  20752. }
  20753. get layout() {
  20754. return this._layout;
  20755. }
  20756. get values() {
  20757. if (this._layout === torch.sparse_coo) {
  20758. return this._values;
  20759. }
  20760. throw new python.Error(`Unsupported values in layout'${this._layout.__str__()}'.`);
  20761. }
  20762. get indices() {
  20763. if (this._layout === torch.sparse_coo) {
  20764. return this._indices;
  20765. }
  20766. throw new python.Error(`Unsupported indices in layout'${this._indices.__str__()}'.`);
  20767. }
  20768. get is_quantized() {
  20769. return this.__quantized__ === true;
  20770. }
  20771. get is_nested() {
  20772. return this.__nested__ === true;
  20773. }
  20774. get is_sparse() {
  20775. return this.layout !== torch.strided;
  20776. }
  20777. size() {
  20778. return this._shape;
  20779. }
  20780. storage() {
  20781. return this._storage;
  20782. }
  20783. storage_offset() {
  20784. return this._storage_offset;
  20785. }
  20786. stride() {
  20787. return this._stride;
  20788. }
  20789. resize_(shape) {
  20790. this._shape = shape;
  20791. }
  20792. __len__() {
  20793. return this._shape[0];
  20794. }
  20795. __setstate__(state) {
  20796. switch (state.length) {
  20797. case 3:
  20798. break;
  20799. case 4:
  20800. [this._storage, this._storage_offset, this._shape, this._stride] = state;
  20801. break;
  20802. case 5:
  20803. [this.data, ,this._backward_hooks, this.requires_grad] = state;
  20804. break;
  20805. default:
  20806. throw new python.Error(`Unsupported tensor state length '${state.length}'.`);
  20807. }
  20808. }
  20809. set_(source, storage_offset, size, stride) {
  20810. this._storage = source;
  20811. this._storage_offset = storage_offset;
  20812. this._shape = size;
  20813. this._stride = stride;
  20814. }
  20815. __bool__() {
  20816. return true;
  20817. }
  20818. __int__() {
  20819. const storage = this.storage();
  20820. if (storage && storage.dtype.__reduce__() === 'int64' && storage.data.length === 8) {
  20821. const buffer = storage.data.peek ? storage.data.peek() : storage.data;
  20822. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  20823. return view.getBigInt64(0, true);
  20824. }
  20825. return NaN;
  20826. }
  20827. __float__() {
  20828. const storage = this.storage();
  20829. if (storage && storage.dtype.__reduce__() === 'float32') {
  20830. if (storage.size() !== undefined && storage.data.length === 4) {
  20831. const buffer = storage.data.peek ? storage.data.peek() : storage.data;
  20832. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  20833. return view.getFloat32(0, true);
  20834. }
  20835. }
  20836. return NaN;
  20837. }
  20838. tolist() {
  20839. const storage = this.storage();
  20840. const dtype = storage.dtype.__reduce__();
  20841. const itemsize = storage.dtype.itemsize();
  20842. const offset = (this._storage_offset || 0) * itemsize;
  20843. const data = storage.data.peek ? storage.data.peek() : storage.data;
  20844. const view = new DataView(data.buffer, data.byteOffset + offset, data.byteLength - offset);
  20845. const size = this._shape.reduce((a, b) => a * b, 1);
  20846. const list = new Array(size);
  20847. switch (dtype) {
  20848. case 'int16':
  20849. for (let i = 0; i < size; i++) {
  20850. list[i] = view.getInt16(i * 2, true);
  20851. }
  20852. return list;
  20853. case 'int64':
  20854. for (let i = 0; i < size; i++) {
  20855. list[i] = view.getInt32(i * 8, true);
  20856. if (view.getUint32(i * 8 + 4, true) !== 0) {
  20857. throw new python.Error('Signed 64-bit value exceeds 32-bit range.');
  20858. }
  20859. }
  20860. return list;
  20861. default:
  20862. throw new python.Error(`Unsupported tolist dtype '${dtype}'.`);
  20863. }
  20864. }
  20865. __str__() {
  20866. return 'tensor(...)';
  20867. }
  20868. static _make_wrapper_subclass(cls, size, stride, dtype, storage_offset, layout, device, requires_grad) {
  20869. const t = new torch.Tensor(null, size, dtype, layout, device, requires_grad);
  20870. t.__setstate__([null, storage_offset, size, stride]);
  20871. return t;
  20872. }
  20873. });
  20874. this.registerType('torch.nn.parameter.Parameter', class extends torch.Tensor {
  20875. constructor(data, requires_grad) {
  20876. super();
  20877. this.data = data || new torch.Tensor([]);
  20878. this.requires_grad = requires_grad === undefined ? true : requires_grad;
  20879. }
  20880. });
  20881. this.registerType('torch._subclasses.fake_tensor.FakeTensor', class extends torch.Tensor {
  20882. });
  20883. this.registerType('torch._subclasses.fake_tensor.FakeTensorMode', class extends torch.utils._python_dispatch.TorchDispatchMode {
  20884. constructor(allow_fallback_kernels, allow_non_fake_inputs, shape_env) {
  20885. super();
  20886. this.allow_fallback_kernels = allow_fallback_kernels;
  20887. this.allow_non_fake_inputs = allow_non_fake_inputs;
  20888. this.shape_env = shape_env;
  20889. this.enter_stack = [];
  20890. this._mode_key = 0; // torch._C._TorchDispatchModeKey.FAKE
  20891. }
  20892. __enter__() {
  20893. const prev_only_lift_cpu_tensors = null;
  20894. const maybe_prev_fake_mode = torch._C._unset_dispatch_mode(this._mode_key);
  20895. if (this === maybe_prev_fake_mode) {
  20896. torch._C._set_dispatch_mode(this);
  20897. this.enter_stack.push([false, null, prev_only_lift_cpu_tensors]);
  20898. } else {
  20899. this.enter_stack.push([true, maybe_prev_fake_mode, prev_only_lift_cpu_tensors]);
  20900. return super.__enter__();
  20901. }
  20902. return this;
  20903. }
  20904. __exit__(exc_type, exc_value, traceback) {
  20905. const [live, maybe_prev_fake_mode, maybe_prev_only_lift_cpu_tensors] = this.enter_stack.pop();
  20906. if (live) {
  20907. super.__exit__(exc_type, exc_value, traceback);
  20908. if (maybe_prev_fake_mode !== null) {
  20909. torch._C._set_dispatch_mode(maybe_prev_fake_mode);
  20910. }
  20911. if (maybe_prev_only_lift_cpu_tensors !== null) {
  20912. torch._C._set_only_lift_cpu_tensors(maybe_prev_only_lift_cpu_tensors);
  20913. }
  20914. torch._C._set_dispatch_mode(maybe_prev_fake_mode);
  20915. }
  20916. }
  20917. });
  20918. this.registerType('torch.nn.parameter.UninitializedParameter', class extends torch.nn.parameter.Parameter {
  20919. constructor(requires_grad /*, device, dtype */) {
  20920. super(undefined, requires_grad);
  20921. }
  20922. });
  20923. this.registerType('torch.nn.parameter.UninitializedBuffer', class extends torch.Tensor {});
  20924. this.registerType('torch.BoolTensor', class extends torch.Tensor {
  20925. constructor(...args) {
  20926. // eslint-disable-next-line no-constructor-return
  20927. return new torch.Tensor(...args);
  20928. }
  20929. });
  20930. this.registerType('torch.ByteTensor', class extends torch.Tensor {
  20931. constructor(...args) {
  20932. // eslint-disable-next-line no-constructor-return
  20933. return new torch.Tensor(...args);
  20934. }
  20935. });
  20936. this.registerType('torch.CharTensor', class extends torch.Tensor {
  20937. constructor(...args) {
  20938. // eslint-disable-next-line no-constructor-return
  20939. return new torch.Tensor(...args);
  20940. }
  20941. });
  20942. this.registerType('torch.ShortTensor', class extends torch.Tensor {
  20943. constructor(...args) {
  20944. // eslint-disable-next-line no-constructor-return
  20945. return new torch.Tensor(...args);
  20946. }
  20947. });
  20948. this.registerType('torch.IntTensor', class extends torch.Tensor {
  20949. constructor(...args) {
  20950. // eslint-disable-next-line no-constructor-return
  20951. return new torch.Tensor(...args);
  20952. }
  20953. });
  20954. this.registerType('torch.LongTensor', class extends torch.Tensor {
  20955. constructor(...args) {
  20956. // eslint-disable-next-line no-constructor-return
  20957. return new torch.Tensor(...args);
  20958. }
  20959. });
  20960. this.registerType('torch.HalfTensor', class extends torch.Tensor {
  20961. constructor(...args) {
  20962. // eslint-disable-next-line no-constructor-return
  20963. return new torch.Tensor(...args);
  20964. }
  20965. });
  20966. this.registerType('torch.FloatTensor', class extends torch.Tensor {
  20967. constructor(...args) {
  20968. // eslint-disable-next-line no-constructor-return
  20969. return new torch.Tensor(...args);
  20970. }
  20971. });
  20972. this.registerType('torch.DoubleTensor', class extends torch.Tensor {
  20973. constructor(...args) {
  20974. // eslint-disable-next-line no-constructor-return
  20975. return new torch.Tensor(...args);
  20976. }
  20977. });
  20978. this.registerType('torch.ComplexFloatTensor', class extends torch.Tensor {
  20979. constructor(...args) {
  20980. // eslint-disable-next-line no-constructor-return
  20981. return new torch.Tensor(...args);
  20982. }
  20983. });
  20984. this.registerType('torch.ComplexDoubleTensor', class extends torch.Tensor {
  20985. constructor(...args) {
  20986. // eslint-disable-next-line no-constructor-return
  20987. return new torch.Tensor(...args);
  20988. }
  20989. });
  20990. this.registerType('torch.QInt8Tensor', class extends torch.Tensor {
  20991. constructor(...args) {
  20992. // eslint-disable-next-line no-constructor-return
  20993. return new torch.Tensor(...args);
  20994. }
  20995. });
  20996. this.registerType('torch.QUInt8Tensor', class extends torch.Tensor {
  20997. constructor(...args) {
  20998. // eslint-disable-next-line no-constructor-return
  20999. return new torch.Tensor(...args);
  21000. }
  21001. });
  21002. this.registerType('torch.QInt32Tensor', class extends torch.Tensor {
  21003. constructor(...args) {
  21004. // eslint-disable-next-line no-constructor-return
  21005. return new torch.Tensor(...args);
  21006. }
  21007. });
  21008. this.registerType('torch.BFloat16Tensor', class extends torch.Tensor {
  21009. constructor(...args) {
  21010. // eslint-disable-next-line no-constructor-return
  21011. return new torch.Tensor(...args);
  21012. }
  21013. });
  21014. this.registerType('torch.cuda._CudaLegacyStorage', class extends torch.storage._LegacyStorage {});
  21015. this.registerType('torch.cuda.FloatStorage', class extends torch.cuda._CudaLegacyStorage {});
  21016. this.registerType('torch.cuda.FloatTensor', class extends torch.Tensor {
  21017. constructor(...args) {
  21018. // eslint-disable-next-line no-constructor-return
  21019. return new torch.Tensor(...args);
  21020. }
  21021. });
  21022. this.registerType('torch.cuda.DoubleStorage', class extends torch.cuda._CudaLegacyStorage {});
  21023. this.registerType('torch.cuda.DoubleTensor', class extends torch.Tensor {
  21024. constructor(...args) {
  21025. // eslint-disable-next-line no-constructor-return
  21026. return new torch.Tensor(...args);
  21027. }
  21028. });
  21029. this.registerType('torch.cuda.amp.grad_scaler.GradScaler', class {});
  21030. this.registerType('torchao.utils.TorchAOBaseTensor', class extends torch.Tensor {
  21031. constructor(...args) {
  21032. // eslint-disable-next-line no-constructor-return
  21033. return new torch.Tensor(...args);
  21034. }
  21035. });
  21036. this.registerType('torchao.dtypes.affine_quantized_tensor.AffineQuantizedTensor', class extends torchao.utils.TorchAOBaseTensor {});
  21037. this.registerType('torchao.dtypes.utils.Layout', class {});
  21038. this.registerType('torchao.dtypes.uintx.plain_layout.PlainAQTTensorImpl', class {});
  21039. this.registerType('torchao.dtypes.floatx.float8_layout.Float8Layout', class extends torchao.dtypes.utils.Layout {});
  21040. this.registerType('torchao.dtypes.utils.AQTTensorImpl', class extends torchao.utils.TorchAOBaseTensor {});
  21041. this.registerType('torchao.dtypes.utils.PlainLayout', class extends torchao.dtypes.utils.Layout {});
  21042. this.registerType('torchao.dtypes.floatx.float8_layout.Float8AQTTensorImpl', class extends torchao.dtypes.utils.AQTTensorImpl {});
  21043. this.registerType('torchao.quantization.linear_activation_quantized_tensor.LinearActivationQuantizedTensor', class extends torchao.utils.TorchAOBaseTensor {});
  21044. this.registerFunction('torchao.quantization.quant_api._int8_symm_per_token_reduced_range_quant');
  21045. this.registerType('torchao.quantization.quant_primitives.ZeroPointDomain', class extends this.enum.Enum {});
  21046. this.registerType('torchao.prototype.mx_formats.mx_tensor.MXTensor', class extends torchao.utils.TorchAOBaseTensor {});
  21047. torchao.prototype.mx_formats.mx_tensor.MXTensor.tensor_attribute_names = ['_elem_dtype', 'block_size'];
  21048. torchao.prototype.mx_formats.mx_tensor.MXTensor.tensor_data_names = ['qdata', 'scale'];
  21049. this.registerType('torchao.prototype.mx_formats.mx_tensor.QuantizeTensorToMXKwargs', class {});
  21050. this.registerType('torchao.prototype.mx_formats.config.ScaleCalculationMode', class extends this.enum.Enum {});
  21051. this.registerType('torchao.quantization.quantize_.common.kernel_preference.KernelPreference', class extends this.enum.Enum {});
  21052. this.registerFunction('torch.cuda.amp.grad_scaler._refresh_per_optimizer_state');
  21053. this.registerType('torch.SymBool', class {
  21054. constructor(node) {
  21055. this.node = node;
  21056. }
  21057. });
  21058. this.registerType('torch.SymInt', class {
  21059. constructor(node) {
  21060. this.node = node;
  21061. }
  21062. toString() {
  21063. return this.node.__str__();
  21064. }
  21065. });
  21066. this.register('torch.nn').Module = this.register('torch.nn.modules.module').Module;
  21067. this.register('torch.optim').Adam = this.register('torch.optim.adam').Adam;
  21068. this.register('torch.nn').ReLU = this.register('torch.nn.modules.activation').ReLU;
  21069. this.register('sklearn.utils').Bunch = this.register('sklearn.utils._bunch').Bunch;
  21070. /* eslint-disable no-multi-assign */
  21071. // https://github.com/pytorch/pytorch/blob/main/c10/core/ScalarType.h
  21072. torch.uint8 = torch.ByteStorage.dtype = new torch.dtype(0, 'uint8', 1);
  21073. torch.int8 = torch.CharStorage.dtype = new torch.dtype(1, 'int8', 1);
  21074. torch.int16 = torch.ShortStorage.dtype = new torch.dtype(2, 'int16', 2);
  21075. torch.int32 = torch.IntStorage.dtype = new torch.dtype(3, 'int32', 4);
  21076. torch.int64 = torch.LongStorage.dtype = new torch.dtype(4, 'int64', 8);
  21077. torch.float16 = torch.HalfStorage.dtype = new torch.dtype(5, 'float16', 2);
  21078. torch.float32 = torch.FloatStorage.dtype = new torch.dtype(6, 'float32', 4);
  21079. torch.float64 = torch.DoubleStorage.dtype = new torch.dtype(7, 'float64', 8);
  21080. torch.complex32 = torch.ComplexHalfStorage.dtype = new torch.dtype(8, 'complex<float16>', 4);
  21081. torch.complex64 = torch.ComplexFloatStorage.dtype = new torch.dtype(9, 'complex<float32>', 8);
  21082. torch.complex128 = torch.ComplexDoubleStorage.dtype = new torch.dtype(10, 'complex<float64>', 16);
  21083. torch.bool = torch.BoolStorage.dtype = new torch.dtype(11, 'boolean', 1);
  21084. torch.qint8 = torch.QInt8Storage.dtype = new torch.dtype(12, 'qint8', 1);
  21085. torch.quint8 = torch.QUInt8Storage.dtype = new torch.dtype(13, 'quint8', 1);
  21086. torch.qint32 = torch.QInt32Storage.dtype = new torch.dtype(14, 'qint32', 4);
  21087. torch.bfloat16 = torch.BFloat16Storage.dtype = new torch.dtype(15, 'bfloat16', 2);
  21088. torch.quint4x2 = torch.QUInt4x2Storage.dtype = new torch.dtype(16, 'quint4x2', 1);
  21089. torch.quint2x4 = torch.QUInt2x4Storage.dtype = new torch.dtype(17, 'quint2x4');
  21090. torch.bits1x8 = new torch.dtype(18, 'bits1x8');
  21091. torch.bits2x4 = new torch.dtype(19, 'bits2x4');
  21092. torch.bits4x2 = new torch.dtype(20, 'bits4x2');
  21093. torch.bits8 = new torch.dtype(21, 'bits8');
  21094. torch.bits16 = new torch.dtype(22, 'bits16');
  21095. torch.float8_e5m2 = new torch.dtype(23, 'float8_e5m2', 1);
  21096. torch.float8_e5m2fnuz = new torch.dtype(24, 'float8_e5m2fnuz', 1);
  21097. torch.float8_e4m3fn = new torch.dtype(25, 'float8_e4m3fn', 1);
  21098. torch.float8_e4m3fnuz = new torch.dtype(26, 'float8_e4m3fnuz', 1);
  21099. torch.float8_e8m0fnu = new torch.dtype(44, 'float8_e8m0fnu', 1);
  21100. torch.float4_e2m1fn_x2 = new torch.dtype(45, 'float4_e2m1fn_x2', 1);
  21101. torch.uint16 = torch.UInt16Storage.dtype = new torch.dtype(27, 'uint16', 2);
  21102. torch.uint32 = torch.UInt32Storage.dtype = new torch.dtype(28, 'uint32', 4);
  21103. torch.uint64 = torch.UInt64Storage.dtype = new torch.dtype(29, 'uint64', 8);
  21104. torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE = new Map([
  21105. ['uint8', 'BYTE'],
  21106. ['int8', 'CHAR'], ['int16', 'SHORT'], ['int32', 'INT'], ['int64', 'LONG'],
  21107. ['float16', 'HALF'], ['float32', 'FLOAT'], ['float64', 'DOUBLE'],
  21108. ['complex32', 'COMPLEXHALF'], ['complex64', 'COMPLEXFLOAT'], ['complex128', 'COMPLEXDOUBLE'],
  21109. ['bool', 'BOOL'], ['bfloat16', 'BFLOAT16'], ['uint16', 'UINT16'],
  21110. ['float8_e4m3fn','FLOAT8E4M3FN'], ['float8_e5m2','FLOAT8E5M2'], ['float8_e4m3fnuz','FLOAT8E4M3FNUZ'], ['float8_e5m2fnuz','FLOAT8E5M2FNUZ']
  21111. ].map(([key, value]) => [torch._export.serde.schema.ScalarType[value], torch[key]]));
  21112. torch.contiguous_format = new torch.memory_format('contiguous_format');
  21113. torch.channels_last = new torch.memory_format('channels_last');
  21114. torch.channels_last_3d = new torch.memory_format('channels_last_3d');
  21115. torch.preserve_format = new torch.memory_format('preserve_format');
  21116. torch._export.serde.serialize._SERIALIZE_TO_TORCH_MEMORY_FORMAT = Object.fromEntries([
  21117. ['contiguous_format', 'ContiguousFormat'],
  21118. ['channels_last', 'ChannelsLast'],
  21119. ['channels_last_3d', 'ChannelsLast3d'],
  21120. ['preserve_format', 'PreserveFormat']
  21121. ].map(([key, value]) => [torch._export.serde.schema.MemoryFormat[value], torch[key]]));
  21122. /* eslint-enable no-multi-assign */
  21123. torch.strided = new torch.layout('strided');
  21124. torch.sparse_coo = new torch.layout('sparse_coo');
  21125. torch.sparse_csr = new torch.layout('sparse_csr');
  21126. torch.sparse_csc = new torch.layout('sparse_csc');
  21127. torch.sparse_bsr = new torch.layout('sparse_bsr');
  21128. torch.sparse_bsc = new torch.layout('sparse_bsc');
  21129. torch._mkldnn = new torch.layout('_mkldnn');
  21130. torch._export.serde.serialize._SERIALIZE_TO_TORCH_LAYOUT = Object.fromEntries([
  21131. ['sparse_coo', 'SparseCoo'],
  21132. ['sparse_csr', 'SparseCsr'],
  21133. ['sparse_csc', 'SparseCsc'],
  21134. ['sparse_bsr', 'SparseBsr'],
  21135. ['sparse_bsc', 'SparseBsc'],
  21136. ['_mkldnn', '_mkldnn'],
  21137. ['strided', 'Strided'],
  21138. ].map(([key, value]) => [torch._export.serde.schema.Layout[value], torch[key]]));
  21139. torch.per_tensor_affine = new torch.qscheme('torch.per_tensor_affine');
  21140. torch.per_channel_affine = new torch.qscheme('torch.per_channel_affine');
  21141. torch.per_tensor_symmetric = new torch.qscheme('torch.per_tensor_symmetric');
  21142. torch.per_channel_symmetric = new torch.qscheme('torch.per_channel_symmetric');
  21143. torch.per_channel_affine_float_qparams = new torch.qscheme('torch.per_channel_affine_float_qparams');
  21144. torch.inf = this.register('math').inf;
  21145. this.registerFunction('fastcore.basics._using_attr');
  21146. this.registerFunction('fastcore.imports.noop');
  21147. this.registerType('fastcore.basics.fastuple', class {});
  21148. this.registerType('fastcore.basics.GetAttr', class {});
  21149. this.registerType('fastcore.dispatch._TypeDict', class {});
  21150. this.registerType('fastcore.dispatch.TypeDispatch', class {});
  21151. this.registerType('fastcore.foundation.L', class {});
  21152. this.registerType('fastcore.transform.Pipeline', class extends builtins.object {});
  21153. this.registerType('fastcore.transform.Transform', class extends builtins.object {});
  21154. this.registerType('fastcore.transform.DisplayedTransform', class extends fastcore.transform.Transform {});
  21155. this.registerType('fastcore.transform.ItemTransform', class extends fastcore.transform.Transform {});
  21156. this.registerType('fastai.basic_train.Learner', class {});
  21157. this.registerType('fastai.basic_train.Recorder', class {});
  21158. this.registerFunction('fastai.torch_core._fa_rebuild_tensor', (cls, ...args) => {
  21159. const tensor = torch._utils._rebuild_tensor_v2(...args);
  21160. return self.invoke(cls, [tensor]);
  21161. });
  21162. this.registerFunction('fastai.torch_core.trainable_params');
  21163. this.registerFunction('fastai.torch_core._rebuild_from_type', (func, type, args, dict) => {
  21164. const tensor = self.invoke(type, [func(...args)]);
  21165. Object.assign(tensor, dict);
  21166. return tensor;
  21167. });
  21168. this.registerType('fastai.torch_core.Module', class extends torch.nn.modules.module.Module {});
  21169. this.registerType('fastai.torch_core.TensorBase', class extends torch.Tensor {
  21170. constructor(x) {
  21171. super();
  21172. Object.assign(this, x);
  21173. }
  21174. });
  21175. this.registerType('fastai.torch_core.TensorCategory', class extends fastai.torch_core.TensorBase {});
  21176. this.registerType('fastai.torch_core.TensorImageBase', class extends fastai.torch_core.TensorBase {});
  21177. this.registerType('fastai.torch_core.TensorImage', class extends fastai.torch_core.TensorImageBase {});
  21178. this.registerType('fastai.torch_core.TensorMask', class extends fastai.torch_core.TensorImageBase {});
  21179. this.registerType('fastai.torch_core.TensorMultiCategory', class extends fastai.torch_core.TensorCategory {});
  21180. this.registerFunction('fastai.torch_core.uniform');
  21181. this.registerType('fastai.callback.core.Callback', class extends fastcore.basics.GetAttr {});
  21182. this.registerType('fastai.callback.core.TrainEvalCallback', class extends fastai.callback.core.Callback {});
  21183. this.registerType('fastai.callback.fp16.AMPMode', class extends this.enum.Enum {});
  21184. this.registerType('fastai.callback.fp16.MixedPrecision', class {});
  21185. this.registerFunction('fastai.callback.hook._hook_inner');
  21186. this.registerType('fastai.callback.hook.Hook', class extends builtins.object {});
  21187. this.registerType('fastai.callback.hook.Hooks', class extends builtins.object {});
  21188. this.registerType('fastai.callback.mixup.MixHandler', class extends fastai.callback.core.Callback {});
  21189. this.registerType('fastai.callback.mixup.CutMix', class extends fastai.callback.mixup.MixHandler {});
  21190. this.registerType('fastai.callback.progress.ProgressCallback', class {});
  21191. this.registerType('fastai.callback.progress.ShowGraphCallback', class {});
  21192. this.registerType('fastai.callback.tracker.EarlyStoppingCallback', class {});
  21193. this.registerType('fastai.callback.tracker.TrackerCallback', class {});
  21194. this.registerType('fastai.callback.tracker.SaveModelCallback', class extends fastai.callback.tracker.TrackerCallback {});
  21195. this.registerType('fastai.data.core.DataLoaders', class extends fastcore.basics.GetAttr {});
  21196. this.registerType('fastai.data.core.Datasets', class {});
  21197. this.registerType('fastai.data.load.DataLoader', class extends fastcore.basics.GetAttr {});
  21198. this.registerType('fastai.data.core.FilteredBase', class {});
  21199. this.registerType('fastai.data.core.TfmdDL', class extends fastai.data.load.DataLoader {});
  21200. this.registerType('fastai.data.core.TfmdLists', class {});
  21201. this.registerType('fastai.data.load._FakeLoader', class {});
  21202. this.registerFunction('fastai.data.load._wif');
  21203. this.registerType('fastai.data.transforms.Categorize', class {});
  21204. this.registerType('fastai.data.transforms.Category', class {});
  21205. this.registerType('fastai.data.transforms.CategoryMap', class {});
  21206. this.registerType('fastai.data.transforms.ColReader', class {});
  21207. this.registerType('fastai.data.transforms.IntToFloatTensor', class {});
  21208. this.registerType('fastai.data.transforms.MultiCategorize', class {});
  21209. this.registerType('fastai.data.transforms.Normalize', class {});
  21210. this.registerType('fastai.data.transforms.parent_label', class {});
  21211. this.registerType('fastai.data.transforms.OneHotEncode', class {});
  21212. this.registerType('fastai.data.transforms.RegressionSetup', class {});
  21213. this.registerType('fastai.data.transforms.ToTensor', class {});
  21214. this.registerType('fastai.data_block.CategoryList', class {});
  21215. this.registerType('fastai.data_block.CategoryProcessor', class {});
  21216. this.registerType('fastai.imports.noop', class {});
  21217. this.registerType('fastai.layers.AdaptiveConcatPool2d', class {});
  21218. this.registerType('fastai.layers.ConvLayer', class {});
  21219. this.registerType('fastai.layers.Embedding', class {});
  21220. this.registerType('fastai.layers.Flatten', class {});
  21221. this.registerType('fastai.layers.FlattenedLoss', class {});
  21222. this.registerType('fastai.layers.LinBnDrop', class {});
  21223. this.registerType('fastai.layers.MergeLayer', class {});
  21224. this.registerType('fastai.layers.PixelShuffle_ICNR', class {});
  21225. this.registerType('fastai.layers.ResBlock', class {});
  21226. this.registerType('fastai.layers.SelfAttention', class {});
  21227. this.registerType('fastai.layers.SigmoidRange', class {});
  21228. this.registerType('fastai.layers.TimeDistributed', class {});
  21229. this.registerType('fastai.layers.ToTensorBase', class {});
  21230. this.registerType('fastai.learner._ConstantFunc', class {});
  21231. this.registerType('fastai.learner.Metric', class {});
  21232. this.registerType('fastai.learner.AvgLoss', class extends fastai.learner.Metric {});
  21233. this.registerType('fastai.learner.AvgMetric', class extends fastai.learner.Metric {});
  21234. this.registerType('fastai.learner.AvgSmoothLoss', class extends fastai.learner.Metric {});
  21235. this.registerType('fastai.learner.CastToTensor', class extends fastai.callback.core.Callback {});
  21236. this.registerType('fastai.learner.Dice', class extends fastai.learner.Metric {});
  21237. this.registerType('fastai.learner.Learner', class extends fastcore.basics.GetAttr {});
  21238. this.registerType('fastai.learner.Recorder', class {});
  21239. this.registerType('fastai.losses.BaseLoss', class {});
  21240. this.registerType('fastai.losses.BCEWithLogitsLossFlat', class {});
  21241. this.registerType('fastai.losses.CrossEntropyLossFlat', class extends fastai.losses.BaseLoss {});
  21242. this.registerType('fastai.losses.FocalLoss', class extends fastai.torch_core.Module {});
  21243. this.registerType('fastai.losses.FocalLossFlat', class extends fastai.losses.BaseLoss {});
  21244. this.registerType('fastai.losses.LabelSmoothingCrossEntropy', class extends fastai.torch_core.Module {});
  21245. this.registerType('fastai.metrics.AccumMetric', class extends fastai.learner.Metric {});
  21246. this.registerType('fastai.metrics.Dice', class {});
  21247. this.registerType('fastai.metrics.JaccardCoeff', class {});
  21248. this.registerFunction('fastai.metrics._rmse');
  21249. this.registerFunction('fastai.metrics.accuracy');
  21250. this.registerFunction('fastai.metrics.accuracy_multi');
  21251. this.registerFunction('fastai.metrics.foreground_acc');
  21252. this.registerFunction('fastai.metrics.mse');
  21253. this.registerFunction('fastai.metrics.error_rate');
  21254. this.registerType('fastai.optimizer._BaseOptimizer', class {});
  21255. this.registerType('fastai.optimizer.Optimizer', class extends fastai.optimizer._BaseOptimizer {});
  21256. this.registerFunction('fastai.optimizer.Adam');
  21257. this.registerFunction('fastai.optimizer.adam_step');
  21258. this.registerFunction('fastai.optimizer.average_grad');
  21259. this.registerFunction('fastai.optimizer.average_sqr_grad');
  21260. this.registerFunction('fastai.optimizer.RAdam');
  21261. this.registerFunction('fastai.optimizer.step_stat');
  21262. this.registerFunction('fastai.optimizer.weight_decay');
  21263. this.registerType('fastai.tabular.core.Categorify', class {});
  21264. this.registerType('fastai.tabular.core.FillMissing', class {});
  21265. this.registerType('fastai.tabular.core.FillStrategy', class {});
  21266. this.registerType('fastai.tabular.core.ReadTabBatch', class extends fastcore.transform.ItemTransform {});
  21267. this.registerType('fastai.tabular.core.TabDataLoader', class extends fastai.data.core.TfmdDL {});
  21268. this.registerType('fastai.tabular.data.TabularDataLoaders', class extends fastai.data.core.DataLoaders {});
  21269. this.registerType('fastai.tabular.core.Tabular', class {});
  21270. this.registerType('fastai.tabular.core.TabularPandas', class extends fastai.tabular.core.Tabular {});
  21271. this.registerType('fastai.tabular.core.TabWeightedDL', class {});
  21272. this.registerType('fastai.tabular.learner.TabularLearner', class extends fastai.learner.Learner {});
  21273. this.registerType('fastai.tabular.model.TabularModel', class {});
  21274. this.registerFunction('fastai.vision.augment.aug_transforms');
  21275. this.registerFunction('fastai.vision.augment.dihedral_mat');
  21276. this.registerType('fastai.vision.augment._BrightnessLogit', class {});
  21277. this.registerType('fastai.vision.augment._ContrastLogit', class {});
  21278. this.registerType('fastai.vision.augment._WarpCoord', class {});
  21279. this.registerType('fastai.vision.augment.RandTransform', class extends fastcore.transform.DisplayedTransform {});
  21280. this.registerType('fastai.vision.augment.AffineCoordTfm', class extends fastai.vision.augment.RandTransform {});
  21281. this.registerType('fastai.vision.augment.Brightness', class {});
  21282. this.registerType('fastai.vision.augment.flip_mat', class {});
  21283. this.registerType('fastai.vision.augment.Flip', class {});
  21284. this.registerType('fastai.vision.augment.RandomResizedCrop', class {});
  21285. this.registerType('fastai.vision.augment.RandomResizedCropGPU', class {});
  21286. this.registerType('fastai.vision.augment.Resize', class {});
  21287. this.registerType('fastai.vision.augment.rotate_mat', class {});
  21288. this.registerFunction('fastai.vision.augment.TensorImage.lighting');
  21289. this.registerType('fastai.vision.augment.Warp', class extends fastai.vision.augment.AffineCoordTfm {});
  21290. this.registerType('fastai.vision.augment.zoom_mat', class {});
  21291. this.registerType('fastai.vision.core.PILImage', class {});
  21292. this.registerType('fastai.vision.core.PILMask', class {});
  21293. this.registerType('fastai.vision.core.AddMaskCodes', class {});
  21294. this.registerType('fastai.vision.data.ImageList', class {});
  21295. this.registerType('fastai.vision.data.ImageItemList', class {});
  21296. this.registerType('fastai.vision.image.Image', class {});
  21297. this.registerType('fastai.vision.image.RandTransform', class {});
  21298. this.registerType('fastai.vision.image.TfmCrop', class {});
  21299. this.registerFunction('fastai.vision.learner._resnet_split');
  21300. this.registerFunction('fastai.vision.learner.default_split');
  21301. this.registerFunction('fastai.vision.learner.default_split');
  21302. this.registerType('fastai.vision.learner.TimmBody', class {});
  21303. this.registerType('fastai.vision.models.unet.DynamicUnet', class {});
  21304. this.registerType('fastai.vision.models.unet.ResizeToOrig', class {});
  21305. this.registerType('fastai.vision.models.unet.UnetBlock', class {});
  21306. this.registerType('fastai.vision.models.xresnet.XResNet', class {});
  21307. this.registerFunction('fastai.vision.transform._crop_pad');
  21308. }
  21309. exec(code , context) {
  21310. const ast = this.ast;
  21311. const program = ast.parse(code, '', null, null);
  21312. if (!program) {
  21313. throw new python.Error("Module '?' parse error.");
  21314. }
  21315. this.block(program.body, context);
  21316. }
  21317. debug(/* file */) {
  21318. }
  21319. source(file) {
  21320. if (this._sources.has(file)) {
  21321. return this._sources.get(file);
  21322. }
  21323. return null;
  21324. }
  21325. read(file) {
  21326. const buffer = this.source(file);
  21327. if (buffer) {
  21328. const debug = this.debug(file);
  21329. return this.parse(file, buffer, debug);
  21330. }
  21331. return null;
  21332. }
  21333. parse(filename, buffer, debug) {
  21334. const ast = this.ast;
  21335. const source = this._utf8Decoder.decode(buffer);
  21336. const program = ast.parse(source, filename, null, debug);
  21337. if (!program) {
  21338. throw new python.Error(`Module '${filename}' parse error.`);
  21339. }
  21340. return program;
  21341. }
  21342. import(name, current, level) {
  21343. if (level) {
  21344. let bits = current.split('.');
  21345. if (bits.length < level) {
  21346. throw new python.Error('Invalid relative import beyond top-level package.');
  21347. }
  21348. bits = bits.slice(0, bits.length - level);
  21349. const base = bits.join('.');
  21350. name = name ? [base, name].join('.') : base;
  21351. }
  21352. const index = name.lastIndexOf('.');
  21353. let parent = null;
  21354. let child = null;
  21355. if (index > 0) {
  21356. parent = name.substring(0, index);
  21357. child = name.substring(index + 1);
  21358. this.import(parent);
  21359. }
  21360. if (!this._modules.has(name)) {
  21361. const module = this._registry.get(name) || new this.builtins.module(name);
  21362. module.__package__ = name;
  21363. this._modules.set(name, module);
  21364. const path = name.split('.').join('/');
  21365. module.__path__ = [path];
  21366. const file = `${path}.py`;
  21367. const program = this.read(file);
  21368. if (program) {
  21369. module.__file__ = file;
  21370. for (const [name, value] of Object.entries(this.builtins)) {
  21371. switch (name) {
  21372. case '__class__':
  21373. case '__package__':
  21374. case '__module__':
  21375. case '__name__':
  21376. case '__path__':
  21377. case '__file__':
  21378. break;
  21379. default:
  21380. module[name] = value;
  21381. break;
  21382. }
  21383. }
  21384. const context = new python.Execution.Context(module, null);
  21385. if (name !== 'builtins') {
  21386. context.set('__builtins__', this._modules.get('builtins'));
  21387. }
  21388. this.block(program.body, context);
  21389. }
  21390. if (parent) {
  21391. const parent_module = this._modules.get(parent);
  21392. parent_module[child] = module;
  21393. }
  21394. }
  21395. return this._modules.get(name);
  21396. }
  21397. __import__(name, globals, locals, fromlist, level) {
  21398. let module = null;
  21399. level = level || 0;
  21400. if (level === 0) {
  21401. module = this.import(name);
  21402. } else {
  21403. globals = globals || {};
  21404. let current = globals.__package__;
  21405. if (!current) {
  21406. const spec = globals.__spec__;
  21407. if (spec) {
  21408. current = spec.parent;
  21409. } else {
  21410. const name = globals.__name__;
  21411. const bits = name.split('.');
  21412. bits.pop();
  21413. current = bits.join('.');
  21414. }
  21415. }
  21416. module = this.import(name, current, level);
  21417. }
  21418. if (!fromlist) {
  21419. if (level === 0) {
  21420. return this.import(name.split('.')[0]);
  21421. } else if (name) {
  21422. throw new python.Error(`Unsupported relative import '${name}'.`);
  21423. // cut_off = len(name) - len(name.partition('.')[0])
  21424. // return sys.modules[module.__name__[:len(module.__name__)-cut_off]]
  21425. }
  21426. } else if (module.__path__) {
  21427. const handle_fromlist = (module, fromlist, recursive) => {
  21428. for (const name of fromlist) {
  21429. if (name === '*') {
  21430. if (!recursive && module.__all__) {
  21431. handle_fromlist(module, module.__all__, true);
  21432. }
  21433. } else if (!module[name]) {
  21434. this.import(`${module.__name__}.${name}`);
  21435. }
  21436. }
  21437. return module;
  21438. };
  21439. handle_fromlist(module, fromlist);
  21440. }
  21441. return module;
  21442. }
  21443. module(name) {
  21444. return this._modules.get(name);
  21445. }
  21446. resolve(name) {
  21447. const index = name.lastIndexOf('.');
  21448. const memberName = index === -1 ? name : name.substring(index + 1, name.length);
  21449. const moduleName = index === -1 ? '' : name.substring(0, index);
  21450. const module = this.import(moduleName);
  21451. let type = module ? module[memberName] : null;
  21452. if (!type) {
  21453. if (!this._unresolved.has(name)) {
  21454. const moduleName = name.split('.').shift();
  21455. if (this._registry.has(moduleName) && moduleName !== '__main__' && moduleName !== '__torch__') {
  21456. this.emit('resolve', name);
  21457. }
  21458. const type = this._createType(name, class {});
  21459. this._unresolved.set(name, type);
  21460. }
  21461. type = this._unresolved.get(name);
  21462. }
  21463. return type;
  21464. }
  21465. invoke(target, args) {
  21466. const builtins = this.builtins;
  21467. if (typeof target === 'string') {
  21468. target = this.resolve(target);
  21469. }
  21470. if (target) {
  21471. if (target.__class__ === builtins.type) {
  21472. if (target.prototype && target.prototype.__class__ === target) {
  21473. return Reflect.construct(target, args);
  21474. }
  21475. const obj = Object.create(target);
  21476. if (obj.__init__ && typeof obj.__init__ === 'function') {
  21477. obj.__init__(...args);
  21478. }
  21479. return obj;
  21480. } else if (target.__class__ === builtins.function) {
  21481. if (target.__call__) {
  21482. return target.__call__(args);
  21483. }
  21484. return target(...args);
  21485. }
  21486. }
  21487. throw new python.Error('Unsupported invoke target.');
  21488. }
  21489. call(target, name, args, keywords, context) {
  21490. const builtins = this.builtins;
  21491. const callTarget = this.target(target, context);
  21492. const callArguments = args.map((arg) => this.expression(arg, context));
  21493. if (!callTarget || (name !== null && !callTarget[name])) {
  21494. if (name === '__new__' && callArguments.length === 1 && callArguments[0] === callTarget) {
  21495. name = null;
  21496. callArguments.shift();
  21497. } else {
  21498. const targetName = `${this.identifier(target)}.${name}`;
  21499. throw new python.Error(`Unknown function '${targetName}'.`);
  21500. }
  21501. }
  21502. const func = name ? callTarget[name] : callTarget;
  21503. if (func.__class__ === builtins.type) {
  21504. if (func.prototype && func.prototype.__class__ === func) {
  21505. return Reflect.construct(func, callArguments);
  21506. }
  21507. const obj = Object.create(func);
  21508. obj.__class__ = func;
  21509. if (obj.__init__ && typeof obj.__init__ === 'function') {
  21510. obj.__init__(...args);
  21511. }
  21512. return obj;
  21513. }
  21514. if (func.__class__ === builtins.function) {
  21515. if (func.__call__) {
  21516. return func.__call__(callArguments);
  21517. }
  21518. }
  21519. if (func.__class__ === builtins.method) {
  21520. if (func.__call__) {
  21521. return func.__call__([callTarget].concat(callArguments));
  21522. }
  21523. }
  21524. if (typeof func === 'function') {
  21525. return func.apply(callTarget, callArguments);
  21526. }
  21527. throw new python.Error('Unsupported call expression.');
  21528. }
  21529. apply(method, args, context) {
  21530. const locals = Array.prototype.slice.call(args);
  21531. context = new python.Execution.Context(context.globals, {});
  21532. args = method.args.posonlyargs.concat(method.args.args);
  21533. const default_pos = args.length - method.args.defaults.length;
  21534. for (let i = 0; i < method.args.args.length; i++) {
  21535. const arg = method.args.args[i];
  21536. let value = null;
  21537. if (locals.length > 0) {
  21538. value = locals.shift();
  21539. } else if (i >= default_pos) {
  21540. value = this.expression(method.args.defaults[i - default_pos], context);
  21541. } else {
  21542. throw new python.Error('Missing required positional argument.');
  21543. }
  21544. context.set(arg.arg, value);
  21545. }
  21546. return this.block(method.body, context);
  21547. }
  21548. block(statements, context) {
  21549. statements = Array.prototype.slice.call(statements);
  21550. while (statements.length > 0) {
  21551. const stmt = statements.shift();
  21552. const value = this.statement(stmt, context);
  21553. if (value !== undefined) {
  21554. return value;
  21555. }
  21556. }
  21557. return undefined;
  21558. }
  21559. statement(stmt, context) {
  21560. const ast = this.ast;
  21561. const builtins = this.builtins;
  21562. if (stmt instanceof ast.Pass) {
  21563. // pass
  21564. } else if (stmt instanceof ast.Constant) {
  21565. // pass
  21566. } else if (stmt instanceof ast.Return) {
  21567. return this.expression(stmt.value, context);
  21568. } else if (stmt instanceof ast.FunctionDef) {
  21569. const module = context.get('__name__');
  21570. /* eslint-disable consistent-this */
  21571. const self = this;
  21572. /* eslint-enable consistent-this */
  21573. const parent = context.get('__class__');
  21574. const type = (parent === builtins.module) ? builtins.function : builtins.method;
  21575. const func = {
  21576. __class__: type,
  21577. __globals__: context,
  21578. __module__: module,
  21579. __name__: stmt.name,
  21580. __code__: stmt,
  21581. __call__(args) {
  21582. return self.apply(this.__code__, args, this.__globals__);
  21583. }
  21584. };
  21585. context.set(stmt.name, func);
  21586. } else if (stmt instanceof ast.ClassDef) {
  21587. const bases = stmt.bases.map((base) => this.base(base, context));
  21588. if (bases.length > 1) {
  21589. throw new python.Error(`Unsupported multiple bases for class '${stmt.name}'.`);
  21590. }
  21591. const base = bases.length === 1 ? bases[0] : null;
  21592. const name = `${context.get('__name__')}.${stmt.name}`;
  21593. const value = this._createType(name, base ? class extends base {} : class {});
  21594. value.__bases__ = bases;
  21595. context.set(stmt.name, value);
  21596. this.block(stmt.body, new python.Execution.Context(context.globals, value.prototype));
  21597. } else if (stmt instanceof ast.AnnAssign) {
  21598. const target = this.identifier(stmt.target, context);
  21599. context.set(target, stmt.value ? this.expression(stmt.value, context) : undefined);
  21600. } else if (stmt instanceof ast.Assign) {
  21601. this.expression(stmt, context);
  21602. } else if (stmt instanceof ast.If) {
  21603. const test = this.expression(stmt.test, context);
  21604. if (test === true || test) {
  21605. const value = this.block(stmt.body, context);
  21606. if (value !== undefined) {
  21607. return value;
  21608. }
  21609. } else if (test === false) {
  21610. if (stmt.orelse) {
  21611. const value = this.block(stmt.orelse, context);
  21612. if (value !== undefined) {
  21613. return value;
  21614. }
  21615. }
  21616. } else {
  21617. throw new python.Error('Unsupported condition.');
  21618. }
  21619. } else if (stmt instanceof ast.For) {
  21620. if (stmt.target instanceof ast.Name && stmt.iter instanceof ast.Tuple === false) {
  21621. const range = this.expression(stmt.iter, context);
  21622. const variable = stmt.target;
  21623. for (const current of range) {
  21624. this.statement({ type: '=', target: variable, expression: { type: 'number', value: current } }, context);
  21625. const value = this.block(stmt.body.statements, context);
  21626. if (value !== undefined) {
  21627. return value;
  21628. }
  21629. }
  21630. } else {
  21631. throw new python.Error("Unsupported 'for' statement.");
  21632. }
  21633. } else if (stmt instanceof ast.While) {
  21634. const test = this.expression(stmt.test, context);
  21635. if (test) {
  21636. const value = this.block(stmt.body.statements, context);
  21637. if (value !== undefined) {
  21638. return value;
  21639. }
  21640. }
  21641. } else if (stmt instanceof ast.With) {
  21642. const items = [];
  21643. for (const item of stmt.items) {
  21644. items.push(this.expression(item.context_expr, context));
  21645. }
  21646. for (const item of items) {
  21647. if (item.__enter__ && item.__enter__.__call__) {
  21648. item.__enter__.__call__([item]);
  21649. }
  21650. }
  21651. const value = this.block(stmt.body, context);
  21652. for (const item of items) {
  21653. if (item.__exit__ && item.__exit__.__call__) {
  21654. item.__exit__.__call__([item]);
  21655. }
  21656. }
  21657. if (value !== undefined) {
  21658. return value;
  21659. }
  21660. } else if (stmt instanceof ast.Expr) {
  21661. this.expression(stmt.value, context);
  21662. } else if (stmt instanceof ast.Import) {
  21663. for (const alias of stmt.names) {
  21664. let module = this.__import__(alias.name, context);
  21665. if (alias.asname) {
  21666. const bits = alias.name.split('.').reverse();
  21667. bits.pop();
  21668. while (bits.length > 0) {
  21669. module = module[bits.pop()];
  21670. }
  21671. context.set(alias.asname, module);
  21672. } else {
  21673. context.set(alias.name.split('.')[0], module);
  21674. }
  21675. }
  21676. } else if (stmt instanceof ast.ImportFrom) {
  21677. const fromlist = stmt.names.map((name) => name.name);
  21678. const module = this.__import__(stmt.module, context.globals, context.locals, fromlist, stmt.level);
  21679. for (const entry of stmt.names) {
  21680. const name = entry.name;
  21681. const asname = entry.asname ? entry.asname : null;
  21682. if (!module[name]) {
  21683. throw new python.Error(`Cannot import '${name}' from '${stmt.module}'.`);
  21684. }
  21685. context.set(asname ? asname : name, module[name]);
  21686. }
  21687. } else {
  21688. throw new python.Error(`Unsupported statement '${stmt.__class__.__name__}'.`);
  21689. }
  21690. return undefined;
  21691. }
  21692. expression(expr, context) {
  21693. const ast = this.ast;
  21694. const builtins = this.builtins;
  21695. const typing = this.typing;
  21696. const self = context.get('self');
  21697. switch (expr.__class__.__name__) {
  21698. case 'Assign': {
  21699. const [target] = expr.targets;
  21700. if (target instanceof ast.Name) {
  21701. const value = this.expression(expr.value, context);
  21702. context.set(target.id, value);
  21703. return undefined;
  21704. } else if (target instanceof ast.Subscript) {
  21705. if (target.value instanceof ast.Name &&
  21706. target.slice instanceof ast.List &&
  21707. target.slice.elts.length === 1) {
  21708. const index = this.expression(target.slice.elts[0], context);
  21709. const id = target.value.id;
  21710. if (id === '__annotations__') {
  21711. context.set(id, context.get(id) || {});
  21712. }
  21713. const obj = context.get(id);
  21714. const value = this.expression(expr.value, context);
  21715. if (obj instanceof Map) {
  21716. obj.set(index, value);
  21717. } else {
  21718. obj[index] = value;
  21719. }
  21720. return undefined;
  21721. }
  21722. } else if (target instanceof ast.Attribute) {
  21723. const obj = this.expression(target.value, context);
  21724. const value = this.expression(expr.value, context);
  21725. obj[target.attr] = value;
  21726. return undefined;
  21727. } else if (target instanceof ast.Tuple) {
  21728. context.target.push(target.elts);
  21729. const value = this.expression(expr.value, context);
  21730. context.target.pop();
  21731. if (target.elts.every((elt) => elt instanceof ast.Name)) {
  21732. if (target.elts.length < value.length) {
  21733. throw new python.Error(`ValueError: too many values to unpack (expected ${target.value.length}, actual ${value.length}).`);
  21734. }
  21735. if (target.elts.length > value.length) {
  21736. throw new python.Error(`ValueError: not enough values to unpack (expected ${target.value.length}, actual ${value.length}).`);
  21737. }
  21738. for (let i = 0; i < value.length; i++) {
  21739. context.set(target.elts[i].id, value[i]);
  21740. }
  21741. return undefined;
  21742. }
  21743. }
  21744. break;
  21745. }
  21746. case 'List': {
  21747. return expr.elts.map((expr) => this.expression(expr, context));
  21748. }
  21749. case 'Constant': {
  21750. return expr.value;
  21751. }
  21752. case 'Subscript': {
  21753. if (expr.value instanceof ast.Name && expr.slice instanceof ast.Tuple === false) {
  21754. const id = expr.value.id;
  21755. if (context.get(id)) {
  21756. const index = this.expression(expr.slice, context);
  21757. const target = context.get(id);
  21758. if (target instanceof Map) {
  21759. return target.get(index);
  21760. }
  21761. return target[index < 0 ? target.length + index : index];
  21762. }
  21763. }
  21764. const value = this.expression(expr.value, context);
  21765. if (value && expr.slice instanceof ast.List &&
  21766. (value.__class__ === typing._TupleType ||
  21767. value.__class__ === typing._SpecialGenericAlias ||
  21768. value.__class__ === typing._SpecialForm)) {
  21769. const type = { ...value };
  21770. type.__args__ = expr.slice.elts.map((arg) => this.expression(arg, context));
  21771. return type;
  21772. }
  21773. if (expr.slice instanceof ast.List && expr.slice.elts.length === 1) {
  21774. const index = this.expression(expr.slice.elts[0], context);
  21775. if (value instanceof Map) {
  21776. return value.get(index);
  21777. }
  21778. return value[index < 0 ? value.length + index : index];
  21779. }
  21780. break;
  21781. }
  21782. case 'Attribute': {
  21783. const value = this.target(expr.value, context);
  21784. return value[expr.attr];
  21785. }
  21786. case 'Call': {
  21787. const func = expr.func;
  21788. if (func instanceof ast.Attribute) {
  21789. return this.call(func.value, func.attr, expr.args, expr.keywords, context, expr.range ? expr.range() : null);
  21790. }
  21791. return this.call(func, null, expr.args, expr.keywords, context, expr.range ? expr.range() : null);
  21792. }
  21793. case 'Name': {
  21794. const id = expr.id;
  21795. if (id === 'self') {
  21796. return self;
  21797. }
  21798. const type = (value) => {
  21799. return value &&
  21800. (value.__class__ === builtins.type ||
  21801. value.__class__ === typing._TupleType ||
  21802. value.__class__ === typing._SpecialGenericAlias ||
  21803. value.__class__ === typing._SpecialForm);
  21804. };
  21805. const builtin = builtins[id];
  21806. if (type(builtin)) {
  21807. return builtin;
  21808. }
  21809. const value = context.get(id);
  21810. if (value === undefined) {
  21811. const value = typing[id];
  21812. if (type(value)) {
  21813. return value;
  21814. }
  21815. }
  21816. return value;
  21817. }
  21818. case 'Tuple': {
  21819. return expr.elts.map((expr) => this.expression(expr, context));
  21820. }
  21821. case 'Dict': {
  21822. const dict = {};
  21823. for (let i = 0; i < expr.keys.length; i++) {
  21824. const key = this.expression(expr.keys[i], context);
  21825. const value = this.expression(expr.values[i], context);
  21826. dict[key] = value;
  21827. }
  21828. return dict;
  21829. }
  21830. case 'UnaryOp': {
  21831. if (expr.op instanceof ast.USub) {
  21832. return -this.expression(expr.operand, context);
  21833. }
  21834. throw new python.Error(`Unsupported unary expression '${expr.op}'.`);
  21835. }
  21836. case 'binary': {
  21837. switch (expr.op) {
  21838. case '==': {
  21839. return this.expression(expr.left, context) === this.expression(expr.right, context);
  21840. }
  21841. default: {
  21842. throw new python.Error(`Unsupported binary expression '${expr.op}'.`);
  21843. }
  21844. }
  21845. }
  21846. default: {
  21847. throw new python.Error(`Unsupported expression '${expr.type}'.`);
  21848. }
  21849. }
  21850. return undefined;
  21851. }
  21852. base(expr, context) {
  21853. return this.expression(expr, context);
  21854. }
  21855. identifier(expr) {
  21856. const ast = this.ast;
  21857. if (expr instanceof ast.Name) {
  21858. return expr.id;
  21859. }
  21860. if (expr instanceof ast.Attribute) {
  21861. return `${this.identifier(expr.value)}.${expr.attr}`;
  21862. }
  21863. return null;
  21864. }
  21865. target(expr, context) {
  21866. const ast = this.ast;
  21867. let current = expr;
  21868. let path = [];
  21869. for (;;) {
  21870. if (current instanceof ast.Attribute) {
  21871. path.push(current.attr);
  21872. current = current.value;
  21873. } else if (current instanceof ast.Name && current.id !== 'self' && current.id !== 'CONSTANTS') {
  21874. path.push(current.id);
  21875. break;
  21876. } else {
  21877. path = null;
  21878. break;
  21879. }
  21880. }
  21881. if (path) {
  21882. let target = null;
  21883. for (let i = path.length - 1; i >= 0; i--) {
  21884. const name = path[i];
  21885. if (target) {
  21886. target = target.__getattr__ ? target.__getattr__(name) : target[name];
  21887. } else {
  21888. target = context.get(name);
  21889. }
  21890. if (!target) {
  21891. break;
  21892. }
  21893. }
  21894. if (!target) {
  21895. path.reverse();
  21896. const name = path.join('.');
  21897. const file = `${path.join('/')}.py`;
  21898. if (this._sources.has(file)) {
  21899. target = this.import(name);
  21900. } else {
  21901. target = this.resolve(name);
  21902. }
  21903. }
  21904. return target;
  21905. }
  21906. return this.expression(expr, context);
  21907. }
  21908. add(name, source) {
  21909. this._sources.set(name, source);
  21910. }
  21911. on(event, listener) {
  21912. const value = this._events.get(event) || [];
  21913. value.push(listener);
  21914. this._events.set(event, value);
  21915. }
  21916. emit(event, ...args) {
  21917. if (this._events.has(event)) {
  21918. for (const callback of this._events.get(event)) {
  21919. callback(this, ...args);
  21920. }
  21921. }
  21922. }
  21923. register(name, value) {
  21924. if (!this._registry.has(name)) {
  21925. value = value || new (this._registry.get('builtins').module)(name);
  21926. this._registry.set(name, value);
  21927. let current = name;
  21928. for (;;) {
  21929. const index = current.lastIndexOf('.');
  21930. if (index === -1) {
  21931. break;
  21932. }
  21933. const child = current.substring(index + 1);
  21934. current = current.substring(0, index);
  21935. if (!value.__module__) {
  21936. value.__module__ = current;
  21937. }
  21938. const parent = this.register(current);
  21939. parent[child] = value;
  21940. value = parent;
  21941. }
  21942. }
  21943. return this._registry.get(name);
  21944. }
  21945. registerFunction(name, value) {
  21946. const builtins = this.builtins;
  21947. const index = name.lastIndexOf('.');
  21948. if (!value) {
  21949. value = () => {
  21950. throw new python.Error(`'${name}' is not implemented.`);
  21951. };
  21952. }
  21953. value.__class__ = builtins.function;
  21954. value.__name__ = index === -1 ? name : name.substring(index + 1);
  21955. value.__module__ = index === -1 ? '' : name.substring(0, index);
  21956. const module = this.register(value.__module__);
  21957. if (module[name]) {
  21958. throw new python.Error(`Function '${name}' is already registered.`);
  21959. }
  21960. module[value.__name__] = value;
  21961. return value;
  21962. }
  21963. registerOperator(name, value) {
  21964. this._operators.set(name, value);
  21965. }
  21966. _createType(name, value) {
  21967. const builtins = this.builtins;
  21968. const index = name.lastIndexOf('.');
  21969. value.__class__ = builtins.type;
  21970. value.__name__ = index === -1 ? name : name.substring(index + 1);
  21971. value.__module__ = index === -1 ? '' : name.substring(0, index);
  21972. value.prototype.__class__ = value;
  21973. return value;
  21974. }
  21975. registerType(name, value) {
  21976. value = this._createType(name, value);
  21977. const parts = name.split('.');
  21978. const memberName = parts.pop();
  21979. const moduleName = parts.join('.');
  21980. const module = this.register(moduleName);
  21981. if (module[memberName]) {
  21982. throw new python.Error(`Class '${memberName}' is already registered.`);
  21983. }
  21984. module[memberName] = value;
  21985. return value;
  21986. }
  21987. };
  21988. python.Execution.Context = class {
  21989. constructor(globals, locals) {
  21990. this.globals = globals;
  21991. this.locals = locals;
  21992. }
  21993. set(name, value) {
  21994. if (this.locals) {
  21995. this.locals[name] = value;
  21996. } else {
  21997. this.globals[name] = value;
  21998. }
  21999. }
  22000. get(name) {
  22001. if (this.locals && name in this.locals) {
  22002. return this.locals[name];
  22003. }
  22004. if (name in this.globals) {
  22005. return this.globals[name];
  22006. }
  22007. return undefined;
  22008. }
  22009. get target() {
  22010. this._target = this._target || [];
  22011. return this._target;
  22012. }
  22013. };
  22014. python.BinaryReader = class {
  22015. constructor(buffer) {
  22016. this._buffer = buffer;
  22017. this._length = buffer.length;
  22018. this._position = 0;
  22019. this._view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  22020. this._utf8Decoder = new TextDecoder('utf-8');
  22021. this._asciiDecoder = new TextDecoder('ascii');
  22022. }
  22023. get position() {
  22024. return this._position;
  22025. }
  22026. get length() {
  22027. return this._length;
  22028. }
  22029. seek(position) {
  22030. this._position = position >= 0 ? position : this._length + position;
  22031. if (this._position > this._buffer.length) {
  22032. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  22033. }
  22034. }
  22035. skip(offset) {
  22036. this._position += offset;
  22037. if (this._position > this._buffer.length) {
  22038. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  22039. }
  22040. }
  22041. stream(length) {
  22042. const buffer = this.read(length);
  22043. return new python.BinaryReader(buffer);
  22044. }
  22045. peek(length) {
  22046. const position = this._position;
  22047. length = length === undefined ? this._length - this._position : length;
  22048. this.skip(length);
  22049. const end = this._position;
  22050. this.skip(-length);
  22051. if (position === 0 && length === this._length) {
  22052. return this._buffer;
  22053. }
  22054. return this._buffer.subarray(position, end);
  22055. }
  22056. read(length) {
  22057. const position = this._position;
  22058. length = length === undefined ? this._length - this._position : length;
  22059. this.skip(length);
  22060. if (position === 0 && length === this._length) {
  22061. return this._buffer;
  22062. }
  22063. return this._buffer.subarray(position, this._position);
  22064. }
  22065. byte() {
  22066. const position = this._position;
  22067. this.skip(1);
  22068. return this._view.getUint8(position);
  22069. }
  22070. uint16() {
  22071. const position = this._position;
  22072. this.skip(2);
  22073. return this._view.getUint16(position, true);
  22074. }
  22075. int32() {
  22076. const position = this._position;
  22077. this.skip(4);
  22078. return this._view.getInt32(position, true);
  22079. }
  22080. uint32() {
  22081. const position = this._position;
  22082. this.skip(4);
  22083. return this._view.getUint32(position, true);
  22084. }
  22085. int64() {
  22086. const position = this._position;
  22087. this.skip(8);
  22088. return this._view.getBigInt64(position, true);
  22089. }
  22090. float64() {
  22091. const position = this._position;
  22092. this.skip(8);
  22093. return this._view.getFloat64(position, false);
  22094. }
  22095. string(size, encoding) {
  22096. const data = this.read(size);
  22097. return (encoding === 'utf-8') ?
  22098. this._utf8Decoder.decode(data) :
  22099. this._asciiDecoder.decode(data);
  22100. }
  22101. line() {
  22102. const index = this._buffer.indexOf(0x0A, this._position);
  22103. if (index === -1) {
  22104. throw new python.Error('Could not find end of line.');
  22105. }
  22106. const size = index - this._position;
  22107. const text = this.string(size, 'ascii');
  22108. this.skip(1);
  22109. return text;
  22110. }
  22111. };
  22112. python.StreamReader = class {
  22113. constructor(stream) {
  22114. this._stream = stream;
  22115. this._length = stream.length;
  22116. this._position = 0;
  22117. this._utf8Decoder = new TextDecoder('utf-8');
  22118. this._asciiDecoder = new TextDecoder('ascii');
  22119. }
  22120. get position() {
  22121. return this._position;
  22122. }
  22123. get length() {
  22124. return this._length;
  22125. }
  22126. seek(position) {
  22127. this._stream.seek(position);
  22128. this._position = this._stream.position;
  22129. }
  22130. skip(offset) {
  22131. this._position += offset;
  22132. if (this._position > this._length) {
  22133. throw new python.Error(`Expected ${this._position - this._length} more bytes. The file might be corrupted. Unexpected end of file.`);
  22134. }
  22135. }
  22136. stream(length) {
  22137. this._stream.seek(this._position);
  22138. this.skip(length);
  22139. return this._stream.stream(length);
  22140. }
  22141. peek(length) {
  22142. this._stream.seek(this._position);
  22143. return this._stream.peek(length);
  22144. }
  22145. read(length) {
  22146. this._stream.seek(this._position);
  22147. this.skip(length);
  22148. return this._stream.read(length);
  22149. }
  22150. byte() {
  22151. const position = this._fill(1);
  22152. return this._view.getUint8(position);
  22153. }
  22154. uint16() {
  22155. const position = this._fill(2);
  22156. return this._view.getUint16(position, true);
  22157. }
  22158. int32() {
  22159. const position = this._fill(4);
  22160. return this._view.getInt32(position, true);
  22161. }
  22162. uint32() {
  22163. const position = this._fill(4);
  22164. return this._view.getUint32(position, true);
  22165. }
  22166. int64() {
  22167. const position = this._fill(8);
  22168. return this._view.getBigInt64(position, true);
  22169. }
  22170. float64() {
  22171. const position = this._fill(8);
  22172. return this._view.getFloat64(position, false);
  22173. }
  22174. string(size, encoding) {
  22175. const data = this.read(size);
  22176. return (encoding === 'utf-8') ?
  22177. this._utf8Decoder.decode(data) :
  22178. this._asciiDecoder.decode(data);
  22179. }
  22180. line() {
  22181. let position = this._fill(0);
  22182. let index = this._buffer.indexOf(0x0A, position);
  22183. if (index === -1) {
  22184. const size = Math.min(0x20000000, this._stream.length - this._position);
  22185. this._fill(size);
  22186. this.skip(-size);
  22187. position = this._fill(0);
  22188. index = this._buffer.indexOf(0x0A, position);
  22189. if (index === -1) {
  22190. throw new python.Error('Could not find end of line.');
  22191. }
  22192. }
  22193. const size = index - position;
  22194. const text = this.string(size, 'ascii');
  22195. this.skip(1);
  22196. return text;
  22197. }
  22198. _fill(length) {
  22199. if (this._position + length > this._length) {
  22200. throw new Error(`Expected ${this._position + length - this._length} more bytes. The file might be corrupted. Unexpected end of file.`);
  22201. }
  22202. if (!this._buffer || this._position < this._offset || this._position + length > this._offset + this._buffer.length) {
  22203. this._offset = this._position;
  22204. this._stream.seek(this._offset);
  22205. const size = Math.max(length, Math.min(0x10000000, this._length - this._offset));
  22206. this._buffer = this._stream.read(size);
  22207. this._view = new DataView(this._buffer.buffer, this._buffer.byteOffset, this._buffer.byteLength);
  22208. }
  22209. const position = this._position;
  22210. this._position += length;
  22211. return position - this._offset;
  22212. }
  22213. };
  22214. python.Error = class extends Error {
  22215. constructor(message) {
  22216. super(message);
  22217. this.name = 'Python Error';
  22218. }
  22219. };
  22220. export const Execution = python.Execution;