python.js 1.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048
  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. if (this.order === 'F') {
  2851. throw new python.Error('Fortran order not implemented.');
  2852. }
  2853. const size = this.dtype.itemsize * this.shape.reduce((a, b) => a * b, 1);
  2854. this.data = unpickler.read(size);
  2855. return execution.invoke(this.subclass, [this.shape, this.dtype, this.data]);
  2856. }
  2857. });
  2858. this.registerType('joblib.numpy_pickle.NDArrayWrapper', class {
  2859. __setstate__(state) {
  2860. this.subclass = state.get('subclass');
  2861. this.filename = state.get('state');
  2862. this.allow_mmap = state.get('allow_mmap');
  2863. }
  2864. __read__(/* unpickler */) {
  2865. return this; // return execution.invoke(this.subclass, [ this.shape, this.dtype, this.data ]);
  2866. }
  2867. });
  2868. sklearn.externals.joblib.numpy_pickle.NDArrayWrapper = joblib.numpy_pickle.NDArrayWrapper;
  2869. sklearn.externals.joblib.numpy_pickle.NumpyArrayWrapper = joblib.numpy_pickle.NumpyArrayWrapper;
  2870. this.registerType('keras.engine.sequential.Sequential', class {});
  2871. this.registerType('keras.src.legacy.preprocessing.text.Tokenizer', class {});
  2872. this.registerType('lasagne.layers.conv.Conv2DLayer', class {});
  2873. this.registerType('lasagne.layers.dense.DenseLayer', class {});
  2874. this.registerType('lasagne.layers.input.InputLayer', class {});
  2875. this.registerType('lasagne.layers.pool.MaxPool2DLayer', class {});
  2876. this.registerType('lightgbm.sklearn.LGBMRegressor', class {});
  2877. this.registerType('lightgbm.sklearn.LGBMClassifier', class {});
  2878. this.registerType('lightgbm.basic.Booster', class {
  2879. constructor() {
  2880. this.average_output = false;
  2881. this.models = [];
  2882. this.loaded_parameter = '';
  2883. }
  2884. __setstate__(state) {
  2885. const model_str = state.get('_handle', state.get('handle', null));
  2886. if (model_str) {
  2887. this.LoadModelFromString(model_str);
  2888. return;
  2889. }
  2890. for (const [key, value] of state) {
  2891. this[key] = value;
  2892. }
  2893. }
  2894. LoadModelFromString(model_str) {
  2895. const lines = model_str.split('\n');
  2896. const signature = lines.shift() || '?';
  2897. if (signature.trim() !== 'tree') {
  2898. throw new python.Error(`Invalid signature '${signature.trim()}'.`);
  2899. }
  2900. // GBDT::LoadModelFromString() in https://github.com/microsoft/LightGBM/blob/master/src/boosting/gbdt_model_text.cpp
  2901. const key_vals = new Map();
  2902. while (lines.length > 0 && !lines[0].startsWith('Tree=')) {
  2903. const cur_line = lines.shift().trim();
  2904. if (cur_line.length > 0) {
  2905. const strs = cur_line.split('=');
  2906. if (strs.length === 1) {
  2907. key_vals.set(strs[0], '');
  2908. } else if (strs.length === 2) {
  2909. key_vals.set(strs[0], strs[1]);
  2910. } else if (strs.length > 2) {
  2911. if (strs[0] === "feature_names") {
  2912. key_vals.set(strs[0], cur_line.substring("feature_names=".length));
  2913. } else if (strs[0] === 'monotone_constraints') {
  2914. key_vals.set(strs[0], cur_line.substring('monotone_constraints='.length));
  2915. } else {
  2916. throw new python.Error(`Wrong line: ${cur_line.substring(0, Math.min(128, cur_line.length))}`);
  2917. }
  2918. }
  2919. }
  2920. }
  2921. const atoi = (key, value) => {
  2922. if (key_vals.has(key)) {
  2923. return parseInt(key_vals.get(key), 10);
  2924. }
  2925. if (value !== undefined) {
  2926. return value;
  2927. }
  2928. throw new python.Error(`Model file does not specify ${key}.`);
  2929. };
  2930. const list = (key, size) => {
  2931. if (key_vals.has(key)) {
  2932. const value = key_vals.get(key).split(' ');
  2933. if (value.length !== size) {
  2934. throw new python.Error(`Wrong size of ${key}.`);
  2935. }
  2936. return value;
  2937. }
  2938. throw new python.Error(`Model file does not contain ${key}.`);
  2939. };
  2940. this.version = key_vals.get('version') || '';
  2941. this.num_class = atoi('num_class');
  2942. this.num_tree_per_iteration = atoi('num_tree_per_iteration', this.num_class);
  2943. this.label_index = atoi('label_index');
  2944. this.max_feature_idx = atoi('max_feature_idx');
  2945. if (key_vals.has('average_output')) {
  2946. this.average_output = true;
  2947. }
  2948. this.feature_names = list('feature_names', this.max_feature_idx + 1);
  2949. this.feature_infos = list('feature_infos', this.max_feature_idx + 1);
  2950. if (key_vals.has('monotone_constraints')) {
  2951. this.monotone_constraints = list('monotone_constraints', this.max_feature_idx + 1);
  2952. }
  2953. if (key_vals.has('objective')) {
  2954. this.objective = key_vals.get('objective');
  2955. }
  2956. let tree = null;
  2957. while (lines.length > 0) {
  2958. const text = lines.shift();
  2959. const line = text.trim();
  2960. if (line.length === 0) {
  2961. continue;
  2962. }
  2963. if (line.startsWith('Tree=')) {
  2964. tree = { index: parseInt(line.split('=').pop(), 10) };
  2965. this.models.push(tree);
  2966. continue;
  2967. }
  2968. if (line === 'end of trees') {
  2969. break;
  2970. }
  2971. const param = line.split('=');
  2972. if (param.length !== 2) {
  2973. throw new python.Error(`Invalid property '${line}'.`);
  2974. }
  2975. const name = param[0].trim();
  2976. const value = param[1].trim();
  2977. tree[name] = value;
  2978. }
  2979. const ss = [];
  2980. let is_inparameter = false;
  2981. while (lines.length > 0) {
  2982. const text = lines.shift();
  2983. const line = text.trim();
  2984. if (line === 'parameters:') {
  2985. is_inparameter = true;
  2986. continue;
  2987. } else if (line === 'end of parameters') {
  2988. break;
  2989. } else if (is_inparameter) {
  2990. ss.push(line);
  2991. }
  2992. }
  2993. if (ss.length > 0) {
  2994. this.loaded_parameter = ss.join('\n');
  2995. }
  2996. }
  2997. });
  2998. this.registerFunction('megengine.functional.elemwise.clip', () => {});
  2999. this.registerFunction('megengine.functional.elemwise.sqrt', () => {});
  3000. this.registerFunction('megengine.functional.nn.conv2d', () => {});
  3001. this.registerFunction('megengine.functional.nn.relu', () => {});
  3002. this.registerFunction('megengine.functional.nn.sigmoid', () => {});
  3003. this.registerFunction('megengine.functional.tensor.arange', () => {});
  3004. this.registerFunction('megengine.functional.tensor.broadcast_to', () => {});
  3005. this.registerFunction('megengine.functional.tensor.concat', () => {});
  3006. this.registerFunction('megengine.functional.tensor.expand_dims', () => {});
  3007. this.registerFunction('megengine.functional.tensor.flatten', () => {});
  3008. this.registerFunction('megengine.functional.tensor.full', () => {});
  3009. this.registerFunction('megengine.functional.tensor.reshape', () => {});
  3010. this.registerFunction('megengine.functional.tensor.split', () => {});
  3011. this.registerFunction('megengine.functional.tensor.stack', () => {});
  3012. this.registerFunction('megengine.functional.tensor.transpose', () => {});
  3013. this.registerFunction('megengine.functional.vision.interpolate', () => {});
  3014. this.registerFunction('megengine.module.qat.module.QATModule._apply_fakequant_with_observer', () => {});
  3015. this.registerType('megengine.core._imperative_rt.common.CompNode', class {});
  3016. this.registerType('megengine.core._imperative_rt.ops.ElemwiseMultiType', class {});
  3017. this.registerType('megengine.core._imperative_rt.ops.FakeQuant', class {});
  3018. this.registerType('megengine.core._imperative_rt.ops.GetVarShape', class {});
  3019. this.registerType('megengine.core._imperative_rt.ops.Resize', class {});
  3020. this.registerType('megengine.core.ops._internal.param_defs.ConvolutionV0.Mode', class {});
  3021. this.registerType('megengine.core.ops._internal.param_defs.Convolution.ComputeMode', class {});
  3022. this.registerType('megengine.distributed.group.Group', class {});
  3023. this.registerType('megengine.module.activation.ReLU', class {});
  3024. this.registerType('megengine.module.activation.Softmax', class {});
  3025. this.registerType('megengine.module.adaptive_pooling.AdaptiveAvgPool2d', class {});
  3026. this.registerType('megengine.module.batchnorm.BatchNorm1d', class {});
  3027. this.registerType('megengine.module.batchnorm.BatchNorm2d', class {});
  3028. this.registerType('megengine.module.conv.Conv2d', class {});
  3029. this.registerType('megengine.module.conv.ConvTranspose2d', class {});
  3030. this.registerType('megengine.module.conv_bn.ConvBn2d', class {});
  3031. this.registerType('megengine.module.dropout.Dropout', class {});
  3032. this.registerType('megengine.module.identity.Identity', class {});
  3033. this.registerType('megengine.module.linear.Linear', class {});
  3034. this.registerType('megengine.module.module.Module', class {});
  3035. this.registerType('megengine.module.normalization.InstanceNorm', class {});
  3036. this.registerType('megengine.module.normalization.GroupNorm', class {});
  3037. this.registerType('megengine.module.normalization.LayerNorm', class {});
  3038. this.registerType('megengine.module.pooling.AvgPool2d', class {});
  3039. this.registerType('megengine.module.pooling.MaxPool2d', class {});
  3040. this.registerType('megengine.module.qat.concat.Concat', class {});
  3041. this.registerType('megengine.module.qat.elemwise.Elemwise', class {});
  3042. this.registerType('megengine.module.sequential.Sequential', class {});
  3043. this.registerType('megengine.quantization.fake_quant.FakeQuantize', class {});
  3044. this.registerType('megengine.quantization.fake_quant.LSQ', class {});
  3045. this.registerType('megengine.quantization.fake_quant.TQT', class {});
  3046. this.registerType('megengine.quantization.utils.QParams', class {});
  3047. this.registerType('megengine.quantization.utils.QuantMode', class {});
  3048. this.registerType('megengine.quantization.observer.ExponentialMovingAverageObserver', class {});
  3049. this.registerType('megengine.quantization.observer.HistogramObserver', class {});
  3050. this.registerType('megengine.quantization.observer.MinMaxObserver', class {});
  3051. this.registerType('megengine.quantization.observer.PassiveObserver', class {});
  3052. this.registerType('megengine.quantization.observer.SyncExponentialMovingAverageObserver', class {});
  3053. this.registerType('megengine.quantization.observer.SyncMinMaxObserver', class {});
  3054. this.registerType('megengine.traced_module.expr.Apply', class {});
  3055. this.registerType('megengine.traced_module.expr.CallFunction', class {});
  3056. this.registerType('megengine.traced_module.expr.CallMethod', class {});
  3057. this.registerType('megengine.traced_module.expr.Constant', class {});
  3058. this.registerType('megengine.traced_module.expr.GetAttr', class {});
  3059. this.registerType('megengine.traced_module.expr.Input', class {});
  3060. this.registerType('megengine.traced_module.fake_quant.FakeQuantize', class {});
  3061. this.registerType('megengine.traced_module.node.ModuleNode', class {});
  3062. this.registerType('megengine.traced_module.node.NodeMixin', class {});
  3063. this.registerType('megengine.traced_module.node.TensorNode', class {});
  3064. this.registerType('megengine.traced_module.pytree.ArgsIndex', class {});
  3065. this.registerType('megengine.traced_module.serialization._ModuleState', class {});
  3066. this.registerType('megengine.traced_module.traced_module.InternalGraph', class {});
  3067. this.registerType('megengine.traced_module.traced_module.NameSpace', class {});
  3068. this.registerType('megengine.traced_module.traced_module.TracedModule', class {});
  3069. this.registerType('megengine.tensor.Parameter', class {
  3070. constructor(data, dtype, device) {
  3071. this.data = data;
  3072. this.dtype = dtype;
  3073. this.device = device;
  3074. }
  3075. });
  3076. this.registerType('megengine.traced_module.pytree.TreeDef', class {
  3077. toString() {
  3078. let content = '';
  3079. for (const child of this.children_defs) {
  3080. content += `${child},`;
  3081. }
  3082. if (typeof this.type === "string") {
  3083. return `${this.type.split(".").slice(-1)}(${content})`;
  3084. }
  3085. return `${this.type.__name__}(${content})`;
  3086. }
  3087. });
  3088. this.registerType('megengine.traced_module.pytree.LeafDef', class {
  3089. toString() {
  3090. let content = '';
  3091. if (this.const_val === null) {
  3092. content += '[';
  3093. } else {
  3094. content += this.const_val;
  3095. }
  3096. for (const t of Object.values(this.type)) {
  3097. content += t.__name__;
  3098. }
  3099. content += ']';
  3100. return content;
  3101. }
  3102. });
  3103. this.registerType('megengine.tensor.Tensor', class {
  3104. constructor(data, dtype, device) {
  3105. this.data = data;
  3106. this.dtype = dtype;
  3107. this.device = device;
  3108. }
  3109. });
  3110. this.registerType('megengine.core.tensor.dtype.QuantDtypeMeta', class {
  3111. constructor(name, cname, np_dtype, qmin, qmax, is_signed) {
  3112. this.name = name;
  3113. this.cname = cname;
  3114. this.np_dtype = np_dtype;
  3115. this.qmin = qmin;
  3116. this.qmax = qmax;
  3117. this.is_signed = is_signed;
  3118. }
  3119. });
  3120. this.registerType('nolearn.lasagne.base.BatchIterator', class {});
  3121. this.registerType('nolearn.lasagne.base.Layers', class {});
  3122. this.registerType('nolearn.lasagne.base.NeuralNet', class {});
  3123. this.registerType('nolearn.lasagne.base.TrainSplit', class {});
  3124. this.registerType('nolearn.lasagne.handlers.PrintLayerInfo', class {});
  3125. this.registerType('nolearn.lasagne.handlers.PrintLog', class {});
  3126. this.registerType('numpy.ndarray', class {
  3127. constructor(shape, dtype, buffer, offset, strides, order) {
  3128. this.shape = shape;
  3129. this.dtype = dtype;
  3130. this.data = buffer === undefined ? null : buffer;
  3131. this.offset = offset === undefined ? 0 : offset;
  3132. this._strides = strides === undefined ? null : strides;
  3133. this.order = order === undefined ? null : order;
  3134. this.flags = {};
  3135. this._read();
  3136. }
  3137. static __new__(cls, shape, dtype, buffer, offset, strides, order) {
  3138. return new cls(shape, dtype, buffer, offset, strides, order);
  3139. }
  3140. __setstate__(state) {
  3141. [this.version, this.shape, this.dtype, this.flags.fn, this.data] = state;
  3142. this._read();
  3143. }
  3144. flatten() {
  3145. const size = this.shape.reduce((a, b) => a * b, 1);
  3146. const value = new numpy.ndarray([size], this.dtype, this.data, this.offset, this.strides, this.order);
  3147. value.flags = this.flags;
  3148. return value;
  3149. }
  3150. reshape(shape, order) {
  3151. return new numpy.ndarray(shape, this.dtype, this.data, this.offset, this.strides, order);
  3152. }
  3153. tobytes() {
  3154. return this.data;
  3155. }
  3156. tolist() {
  3157. if (this.shape.length < 0 || this.shape.length > 1) {
  3158. throw new python.Error(`Unsupported shape '${JSON.stringify(this.shape)}'.`);
  3159. }
  3160. const size = this.shape.reduce((a, b) => a * b, 1);
  3161. const list = new Array(size);
  3162. switch (this.dtype.kind) {
  3163. case 'U': {
  3164. const data = new Uint32Array(new Uint8Array(this.data).buffer);
  3165. const itemsize = this.dtype.itemsize >> 2;
  3166. let offset = 0;
  3167. for (let i = 0; i < size; i++) {
  3168. const buffer = data.subarray(offset, offset + itemsize);
  3169. const index = buffer.indexOf(0);
  3170. list[i] = Array.from(index >= 0 ? buffer.subarray(0, index) : buffer).map((c) => String.fromCodePoint(c)).join('');
  3171. offset += itemsize;
  3172. }
  3173. return list;
  3174. }
  3175. case 'S': {
  3176. const data = this.data;
  3177. const itemsize = this.dtype.itemsize;
  3178. const decoder = new TextDecoder('utf-8');
  3179. let offset = 0;
  3180. for (let i = 0; i < size; i++) {
  3181. const buffer = data.subarray(offset, offset + itemsize);
  3182. const index = buffer.indexOf(0);
  3183. list[i] = decoder.decode(index >= 0 ? buffer.subarray(0, index) : buffer);
  3184. offset += itemsize;
  3185. }
  3186. return list;
  3187. }
  3188. case 'V': {
  3189. const itemsize = this.dtype.itemsize;
  3190. let offset = 0;
  3191. for (let i = 0; i < size; i++) {
  3192. list[i] = this.data.slice(offset, offset + itemsize);
  3193. offset += itemsize;
  3194. }
  3195. return list;
  3196. }
  3197. case 'M': {
  3198. const itemsize = this.dtype.itemsize;
  3199. let offset = 0;
  3200. for (let i = 0; i < size; i++) {
  3201. const buffer = this.data.slice(offset, offset + itemsize);
  3202. list[i] = new numpy.datetime64(buffer);
  3203. offset += itemsize;
  3204. }
  3205. return list;
  3206. }
  3207. case 'T': {
  3208. return this.data;
  3209. }
  3210. case 'O': {
  3211. return this.data;
  3212. }
  3213. default: {
  3214. throw new python.Error(`Type kind '${this.dtype.kind}' not implemented.`);
  3215. }
  3216. }
  3217. }
  3218. get itemsize() {
  3219. return this.dtype.itemsize;
  3220. }
  3221. get size() {
  3222. return (this.shape || []).reduce((a, b) => a * b, 1);
  3223. }
  3224. get strides() {
  3225. if (!this._strides) {
  3226. const shape = this.shape;
  3227. const strides = new Array(shape.length);
  3228. let stride = this.itemsize;
  3229. for (let i = shape.length - 1; i >= 0; i--) {
  3230. strides[i] = stride;
  3231. stride *= shape[i];
  3232. }
  3233. return strides;
  3234. }
  3235. return this._strides;
  3236. }
  3237. _read() {
  3238. if (this.data) {
  3239. const length = this.dtype.itemsize * this.size;
  3240. if (typeof this.data === 'string') {
  3241. this.data = this._unescape(this.data, length);
  3242. if (this.data.length !== length) {
  3243. throw new python.Error('Invalid string array data size.');
  3244. }
  3245. } else if (this.data.length !== length) {
  3246. // throw new python.Error('Invalid array data size.');
  3247. }
  3248. }
  3249. }
  3250. _unescape(token, size) {
  3251. const length = token.length;
  3252. const a = new Uint8Array(length);
  3253. if (size && size === length) {
  3254. for (let p = 0; p < size; p++) {
  3255. a[p] = token.charCodeAt(p);
  3256. }
  3257. return a;
  3258. }
  3259. let i = 0;
  3260. let o = 0;
  3261. while (i < length) {
  3262. let c = token.charCodeAt(i++);
  3263. if (c !== 0x5C || i >= length) {
  3264. a[o++] = c;
  3265. } else {
  3266. c = token.charCodeAt(i++);
  3267. switch (c) {
  3268. case 0x27: a[o++] = 0x27; break; // '
  3269. case 0x5C: a[o++] = 0x5C; break; // \\
  3270. case 0x22: a[o++] = 0x22; break; // "
  3271. case 0x72: a[o++] = 0x0D; break; // \r
  3272. case 0x6E: a[o++] = 0x0A; break; // \n
  3273. case 0x74: a[o++] = 0x09; break; // \t
  3274. case 0x62: a[o++] = 0x08; break; // \b
  3275. case 0x58: // x
  3276. case 0x78: { // X
  3277. const xsi = i - 1;
  3278. const xso = o;
  3279. for (let xi = 0; xi < 2; xi++) {
  3280. if (i >= length) {
  3281. i = xsi;
  3282. o = xso;
  3283. a[o] = 0x5c;
  3284. break;
  3285. }
  3286. let c = token.charCodeAt(i++);
  3287. if (c >= 65 && c <= 70) {
  3288. c -= 55;
  3289. } else if (c >= 97 && c <= 102) {
  3290. c -= 87;
  3291. } else if (c >= 48 && c <= 57) {
  3292. c -= 48;
  3293. } else {
  3294. c = -1;
  3295. }
  3296. if (c === -1) {
  3297. i = xsi;
  3298. o = xso;
  3299. a[o] = 0x5c;
  3300. break;
  3301. }
  3302. a[o] = a[o] << 4 | c;
  3303. }
  3304. o++;
  3305. break;
  3306. }
  3307. default:
  3308. if (c < 48 || c > 57) { // 0-9
  3309. a[o++] = 0x5c;
  3310. a[o++] = c;
  3311. } else {
  3312. i--;
  3313. const osi = i;
  3314. const oso = o;
  3315. for (let oi = 0; oi < 3; oi++) {
  3316. if (i >= length) {
  3317. i = osi;
  3318. o = oso;
  3319. a[o] = 0x5c;
  3320. break;
  3321. }
  3322. const od = token.charCodeAt(i++);
  3323. if (od < 48 || od > 57) {
  3324. i = osi;
  3325. o = oso;
  3326. a[o] = 0x5c;
  3327. break;
  3328. }
  3329. a[o] = a[o] << 3 | od - 48;
  3330. }
  3331. o++;
  3332. }
  3333. break;
  3334. }
  3335. }
  3336. }
  3337. return a.slice(0, o);
  3338. }
  3339. });
  3340. this.registerType('numpy.matrix', class extends numpy.ndarray {
  3341. static __new__(/* subtype, data, dtype, copy */) {
  3342. throw new python.Error("'numpy.matrix.__new__' not implemented.");
  3343. }
  3344. });
  3345. numpy.matrixlib.defmatrix.matrix = numpy.matrix;
  3346. this.registerType('numpy.ma.core.MaskedArray', class extends numpy.ndarray {
  3347. constructor(data /*, mask, dtype, copy, subok, ndmin, fill_value, keep_mask, hard_mask, shrink, order */) {
  3348. super(data.shape, data.dtype, data.data);
  3349. }
  3350. });
  3351. this.registerType('numpy.core.memmap.memmap', class extends numpy.ndarray {});
  3352. this.registerType('pandas.core.arrays.categorical.Categorical', class {});
  3353. this.registerType('pandas.core.arrays.base.ExtensionArray', class {});
  3354. this.registerType('pandas.core.arrays.masked.BaseMaskedArray', class extends pandas.core.arrays.base.ExtensionArray {});
  3355. this.registerType('pandas.core.arrays.numeric.NumericArray', class extends pandas.core.arrays.masked.BaseMaskedArray {});
  3356. this.registerType('pandas.core.arrays.datetimes.DatetimeArray', class {
  3357. __setstate__(state) {
  3358. [this._dtype, this._ndarray] = state;
  3359. Object.assign(this, Object.fromEntries(state[2]));
  3360. }
  3361. });
  3362. this.registerType('pandas.core.arrays.timedeltas.TimedeltaArray', class {
  3363. __setstate__(state) {
  3364. [this._dtype, this._ndarray] = state;
  3365. Object.assign(this, Object.fromEntries(state[2]));
  3366. }
  3367. });
  3368. this.registerType('pandas.core.arrays.period.PeriodArray', class {
  3369. __setstate__(state) {
  3370. [this._dtype, this._ndarray] = state;
  3371. Object.assign(this, Object.fromEntries(state[2]));
  3372. }
  3373. });
  3374. this.registerType('pandas.core.arrays.interval.IntervalArray', class {});
  3375. this.registerType('pandas.core.arrays.integer.IntegerArray', class extends pandas.core.arrays.numeric.NumericArray {});
  3376. this.registerType('pandas.core.arrays.integer.Int64Dtype', class {});
  3377. this.registerType('pandas._libs.tslibs.dtypes.PeriodDtypeBase', class {});
  3378. this.registerType('pandas.core.dtypes.dtypes.PeriodDtype', class extends pandas._libs.tslibs.dtypes.PeriodDtypeBase {});
  3379. this.registerType('pandas.core.dtypes.dtypes.IntervalDtype', class {});
  3380. this.registerType('pandas.core.generic.Flags', class {});
  3381. this.registerType('pandas.core.generic.NDFrame', class {
  3382. constructor(data) {
  3383. this._internal_names = ["_mgr", "_item_cache", "_cache", "_name", "_metadata", "_flags"];
  3384. this._metadata = [];
  3385. builtins.object.__setattr__(self, "_mgr", data);
  3386. builtins.object.__setattr__(self, "_attrs", {});
  3387. builtins.object.__setattr__(self, "_flags", new pandas.core.generic.Flags(this, true));
  3388. }
  3389. __setstate__(state) {
  3390. if (state instanceof pandas.core.internals.managers.BlockManager) {
  3391. this._mgr = state;
  3392. } else if (state instanceof builtins.dict) {
  3393. if (state.__contains__('_data') && !state.__contains__('_mgr')) {
  3394. state.__setitem__('_mgr', state.pop('_data'));
  3395. }
  3396. const typ = state.get('_typ');
  3397. if (typ) {
  3398. let attrs = state.get('_attrs', new builtins.dict());
  3399. if (!attrs) {
  3400. attrs = new builtins.dict();
  3401. }
  3402. builtins.object.__setattr__(this, '_attrs', attrs);
  3403. const flags = state.get('_flags', new builtins.dict({ 'allows_duplicate_labels': true }));
  3404. builtins.object.__setattr__(this, '_flags', new pandas.core.generic.Flags(this, flags));
  3405. const meta = new builtins.set(this._internal_names.concat(this._metadata));
  3406. for (const k of meta) {
  3407. if (state.__contains__(k) && k !== '_flags') {
  3408. const v = state.__getitem__(k);
  3409. builtins.object.__setattr__(this, k, v);
  3410. }
  3411. }
  3412. for (const [k, v] of state) {
  3413. if (!meta.has(k)) {
  3414. builtins.object.__setattr__(this, k, v);
  3415. }
  3416. }
  3417. } else {
  3418. throw new python.Error('Pre-0.12 pickles are no longer supported.');
  3419. }
  3420. } else if (state.size === 2) {
  3421. throw new python.Error('Pre-0.12 pickles are no longer supported.');
  3422. }
  3423. }
  3424. });
  3425. this.registerType('pandas.core.frame.DataFrame', class extends pandas.core.generic.NDFrame {
  3426. });
  3427. this.registerFunction('pandas.core.indexes.base._new_Index', (cls, d) => {
  3428. return new cls(d);
  3429. });
  3430. this.registerType('pandas.core.indexes.datetimes._new_DatetimeIndex', class {});
  3431. this.registerType('pandas.core.indexes.datetimes.DatetimeIndex', class {});
  3432. this.registerType('pandas.core.indexes.base.Index', class {});
  3433. this.registerType('pandas.core.indexes.range.RangeIndex', class {});
  3434. this.registerType('pandas.core.indexes.multi.MultiIndex', class {});
  3435. this.registerType('pandas.core.indexes.numeric.Int64Index', class {});
  3436. this.registerType('pandas.core.index.Int64Index', class {});
  3437. this.registerFunction('pandas.core.internals.blocks.Block', class {
  3438. });
  3439. this.registerFunction('pandas.core.internals.blocks.NumpyBlock', class extends pandas.core.internals.blocks.Block {
  3440. });
  3441. this.registerFunction('pandas.core.internals.blocks.get_block_type', (/* dtype */) => {
  3442. return pandas.core.internals.blocks.NumpyBlock;
  3443. });
  3444. this.registerFunction('pandas.core.internals.blocks.maybe_coerce_values', (values) => {
  3445. return values;
  3446. });
  3447. this.registerFunction('pandas.core.internals.blocks.new_block', (values, placement, ndim, refs) => {
  3448. const klass = execution.invoke('pandas.core.internals.blocks.get_block_type', [values.dtype]);
  3449. return new klass(values, ndim, placement, refs);
  3450. });
  3451. this.registerType('pandas.core.internals.managers.SingleBlockManager', class {});
  3452. this.registerType('pandas.core.internals.managers.BlockManager', class {});
  3453. this.registerType('pandas.core.series.Series', class {});
  3454. this.registerFunction('pandas._libs.arrays.__pyx_unpickle_NDArrayBacked', (cls, checksum, state) => {
  3455. const obj = new cls();
  3456. if (state && obj.__setstate__) {
  3457. obj.__setstate__(state);
  3458. }
  3459. return obj;
  3460. });
  3461. this.registerFunction('pandas._libs.interval.__pyx_unpickle_IntervalMixin', (cls, checksum, state) => {
  3462. const obj = new cls();
  3463. if (state && obj.__setstate__) {
  3464. obj.__setstate__(state);
  3465. }
  3466. return obj;
  3467. });
  3468. this.registerFunction('pandas._libs.internals._unpickle_block', (values, placement, ndim) => {
  3469. values = pandas.core.internals.blocks.maybe_coerce_values(values);
  3470. // if not isinstance(placement, BlockPlacement):
  3471. // placement = BlockPlacement(placement)
  3472. return pandas.core.internals.blocks.new_block(values, placement, ndim);
  3473. });
  3474. this.registerType('pandas._libs.tslibs.base.ABCTimestamp', class extends datetime.datetime {});
  3475. this.registerType('pandas._libs.tslibs.offsets.BaseOffset', class {});
  3476. this.registerType('pandas._libs.tslibs.offsets.SingleConstructorOffset', class extends pandas._libs.tslibs.offsets.BaseOffset {});
  3477. this.registerType('pandas._libs.tslibs.offsets.Tick', class extends pandas._libs.tslibs.offsets.SingleConstructorOffset {});
  3478. this.registerType('pandas._libs.tslibs.offsets.Day', class extends pandas._libs.tslibs.offsets.Tick {});
  3479. this.registerType('pandas._libs.tslibs.offsets.Minute', class extends datetime.datetime {});
  3480. this.registerFunction('pandas._libs.tslibs.timestamps._unpickle_timestamp');
  3481. this.registerType('pandas._libs.tslibs.timestamps._Timestamp', class extends pandas._libs.tslibs.base.ABCTimestamp {});
  3482. this.registerType('pandas._libs.tslibs.timestamps.Timestamp', class extends pandas._libs.tslibs.timestamps._Timestamp {});
  3483. pandas.indexes.base._new_Index = pandas.core.indexes.base._new_Index;
  3484. pandas.indexes.base.Index = pandas.core.indexes.base.Index;
  3485. pandas.indexes.range.RangeIndex = pandas.core.indexes.range.RangeIndex;
  3486. pandas.core.index.Index = pandas.core.indexes.base.Index;
  3487. pandas.core.index._new_Index = pandas.core.indexes.base._new_Index;
  3488. pandas.core.internals.BlockManager = pandas.core.internals.managers.BlockManager;
  3489. pandas._libs.tslib.Timestamp = pandas._libs.tslibs.timestamps.Timestamp;
  3490. this.registerType('pathlib.Path', class {});
  3491. this.registerType('pathlib._local.PosixPath', class {});
  3492. this.registerType('pathlib._local.WindowsPath', class {});
  3493. const pathlib = this.register('pathlib');
  3494. pathlib.PosixPath = pathlib._local.PosixPath;
  3495. pathlib.WindowsPath = pathlib._local.WindowsPath;
  3496. this.registerType('shap._serializable.Serializable', class {});
  3497. this.registerType('shap.explainers._explainer.Explainer', class extends shap._serializable.Serializable {});
  3498. this.registerType('shap.explainers._linear.LinearExplainer', class extends shap.explainers._explainer.Explainer {});
  3499. shap.explainers.LinearExplainer = shap.explainers._linear.LinearExplainer;
  3500. shap.explainers.linear.LinearExplainer = shap.explainers._linear.LinearExplainer;
  3501. this.registerType('sklearn._loss.link.BaseLink', class {});
  3502. this.registerType('sklearn._loss._loss.__pyx_unpickle_CyHalfBinomialLoss', class {});
  3503. this.registerType('sklearn._loss._loss.__pyx_unpickle_CyHalfMultinomialLoss', class {});
  3504. this.registerType('sklearn._loss._loss.CyLossFunction', class {});
  3505. this.registerType('sklearn._loss._loss.CyHalfBinomialLoss', class {});
  3506. this.registerType('sklearn._loss._loss.CyHalfMultinomialLoss', class {});
  3507. this.registerType('sklearn._loss._loss.CyHalfSquaredError', class extends sklearn._loss._loss.CyLossFunction {});
  3508. this.registerType('sklearn._loss.link.IdentityLink', class extends sklearn._loss.link.BaseLink {});
  3509. this.registerType('sklearn._loss.link.Interval', class {});
  3510. this.registerType('sklearn._loss.link.LogitLink', class {});
  3511. this.registerType('sklearn._loss.link.MultinomialLogit', class extends sklearn._loss.link.BaseLink {});
  3512. this.registerFunction('sklearn._loss._loss.__pyx_unpickle_CyHalfSquaredError');
  3513. this.registerType('sklearn._loss.loss.BaseLoss', class {});
  3514. this.registerType('sklearn._loss.loss.HalfBinomialLoss', class {});
  3515. this.registerType('sklearn._loss.loss.HalfMultinomialLoss', class extends sklearn._loss.loss.BaseLoss {});
  3516. this.registerType('sklearn._loss.loss.HalfSquaredError', class extends sklearn._loss.loss.BaseLoss {});
  3517. this.registerType('sklearn.base.BaseEstimator', class {});
  3518. this.registerType('sklearn.base.TransformerMixin', class {});
  3519. this.registerType('sklearn.calibration._CalibratedClassifier', class {});
  3520. this.registerType('sklearn.calibration._SigmoidCalibration', class {});
  3521. this.registerType('sklearn.calibration.CalibratedClassifierCV', class {});
  3522. this.registerType('sklearn.cluster._agglomerative.FeatureAgglomeration', class {});
  3523. this.registerType('sklearn.cluster._dbscan.DBSCAN', class {});
  3524. this.registerType('sklearn.cluster._kmeans.KMeans', class {});
  3525. this.registerType('sklearn.cluster._kmeans.MiniBatchKMeans', class {});
  3526. this.registerType('sklearn.cluster.k_means_.MiniBatchKMeans', class {});
  3527. this.registerType('sklearn.compose._column_transformer._RemainderColsList', class {});
  3528. this.registerType('sklearn.compose._column_transformer.ColumnTransformer', class {});
  3529. this.registerType('sklearn.compose._column_transformer.make_column_selector', class {});
  3530. this.registerType('sklearn.compose._target.TransformedTargetRegressor', class {});
  3531. this.registerType('sklearn.cross_decomposition._pls.PLSRegression', class {});
  3532. this.registerType('sklearn.cross_decomposition._pls.CCA', class {});
  3533. this.registerType('sklearn.decomposition._fastica.FastICA', class {});
  3534. this.registerType('sklearn.decomposition._incremental_pca.IncrementalPCA', class {});
  3535. this.registerType('sklearn.decomposition._pca.PCA', class {});
  3536. this.registerType('sklearn.decomposition._truncated_svd.TruncatedSVD', class {});
  3537. this.registerType('sklearn.decomposition.pca.PCA', class {});
  3538. this.registerType('sklearn.decomposition.PCA', class {});
  3539. this.registerType('sklearn.decomposition.truncated_svd.TruncatedSVD', class {});
  3540. this.registerType('sklearn.discriminant_analysis.LinearDiscriminantAnalysis', class {});
  3541. this.registerType('sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis', class {});
  3542. this.registerType('sklearn.dummy.DummyClassifier', class {});
  3543. this.registerType('sklearn.dummy.DummyRegressor', class {});
  3544. this.registerType('sklearn.ensemble._bagging.BaggingClassifier', class {});
  3545. this.registerType('sklearn.ensemble._bagging.BaggingRegressor', class {});
  3546. this.registerType('sklearn.ensemble._forest.RandomForestClassifier', class {});
  3547. this.registerType('sklearn.ensemble._forest.RandomForestRegressor', class {});
  3548. this.registerType('sklearn.ensemble._forest.ExtraTreesClassifier', class {});
  3549. this.registerType('sklearn.ensemble._forest.ExtraTreesRegressor', class {});
  3550. this.registerType('sklearn.ensemble._gb_losses.BinomialDeviance', class {});
  3551. this.registerType('sklearn.ensemble._gb_losses.ExponentialLoss', class {});
  3552. this.registerType('sklearn.ensemble._gb_losses.LeastAbsoluteError', class {});
  3553. this.registerType('sklearn.ensemble._gb_losses.LeastSquaresError', class {});
  3554. this.registerType('sklearn.ensemble._gb_losses.MultinomialDeviance', class {});
  3555. this.registerType('sklearn.ensemble._gb.GradientBoostingClassifier', class {});
  3556. this.registerType('sklearn.ensemble._gb.GradientBoostingRegressor', class {});
  3557. this.registerType('sklearn.ensemble._hist_gradient_boosting.binning._BinMapper', class {});
  3558. this.registerType('sklearn.ensemble._hist_gradient_boosting.gradient_boosting.HistGradientBoostingRegressor', class {});
  3559. this.registerType('sklearn.ensemble._hist_gradient_boosting.gradient_boosting.HistGradientBoostingClassifier', class {});
  3560. this.registerType('sklearn.ensemble._hist_gradient_boosting.loss.LeastSquares', class {});
  3561. this.registerType('sklearn.ensemble._hist_gradient_boosting.predictor.TreePredictor', class {});
  3562. this.registerType('sklearn.ensemble._iforest.IsolationForest', class {});
  3563. this.registerType('sklearn.ensemble._stacking.StackingClassifier', class {});
  3564. this.registerType('sklearn.ensemble._stacking.StackingRegressor', class {});
  3565. this.registerType('sklearn.ensemble._voting.VotingClassifier', class {});
  3566. this.registerType('sklearn.ensemble._voting.VotingRegressor', class {});
  3567. this.registerType('sklearn.ensemble._weight_boosting.AdaBoostClassifier', class {});
  3568. this.registerType('sklearn.ensemble._weight_boosting.AdaBoostRegressor', class {});
  3569. this.registerType('sklearn.ensemble.forest.RandomForestClassifier', class {});
  3570. this.registerType('sklearn.ensemble.forest.RandomForestRegressor', class {});
  3571. this.registerType('sklearn.ensemble.forest.ExtraTreesClassifier', class {});
  3572. this.registerType('sklearn.ensemble.gradient_boosting.BinomialDeviance', class {});
  3573. this.registerType('sklearn.ensemble.gradient_boosting.GradientBoostingClassifier', class {});
  3574. this.registerType('sklearn.ensemble.gradient_boosting.LogOddsEstimator', class {});
  3575. this.registerType('sklearn.ensemble.gradient_boosting.MultinomialDeviance', class {});
  3576. this.registerType('sklearn.ensemble.gradient_boosting.PriorProbabilityEstimator', class {});
  3577. this.registerType('sklearn.ensemble.voting_classifier.VotingClassifier', class {});
  3578. this.registerType('sklearn.ensemble.weight_boosting.AdaBoostClassifier', class {});
  3579. this.registerType('sklearn.feature_extraction._dict_vectorizer.DictVectorizer', class {});
  3580. this.registerType('sklearn.feature_extraction._hashing.FeatureHasher', class {});
  3581. this.registerType('sklearn.feature_extraction._hash.FeatureHasher', class {});
  3582. this.registerType('sklearn.feature_extraction.text.CountVectorizer', class {});
  3583. this.registerType('sklearn.feature_extraction.text.HashingVectorizer', class {});
  3584. this.registerType('sklearn.feature_extraction.text.TfidfTransformer', class {});
  3585. this.registerType('sklearn.feature_extraction.text.TfidfVectorizer', class {});
  3586. this.registerType('sklearn.feature_selection._from_model.SelectFromModel', class {});
  3587. this.registerFunction('sklearn.feature_selection._mutual_info.mutual_info_classif');
  3588. this.registerFunction('sklearn.feature_selection._univariate_selection.chi2');
  3589. this.registerType('sklearn.feature_selection._univariate_selection.GenericUnivariateSelect', class {});
  3590. this.registerType('sklearn.feature_selection._univariate_selection.SelectKBest', class {});
  3591. this.registerType('sklearn.feature_selection._univariate_selection.SelectPercentile', class {});
  3592. this.registerType('sklearn.feature_selection._variance_threshold.VarianceThreshold', class {});
  3593. this.registerType('sklearn.feature_selection._rfe.RFE', class {});
  3594. this.registerType('sklearn.feature_selection._rfe.RFECV', class extends sklearn.feature_selection._rfe.RFE {});
  3595. this.registerType('sklearn.feature_selection.univariate_selection.SelectKBest', class {});
  3596. this.registerType('sklearn.feature_selection.variance_threshold.VarianceThreshold', class {});
  3597. this.registerType('sklearn.gaussian_process._gpc.GaussianProcessClassifier', class {});
  3598. this.registerType('sklearn.gaussian_process._gpr.GaussianProcessRegressor', class {});
  3599. this.registerType('sklearn.gaussian_process.gpc.GaussianProcessClassifier', class {});
  3600. this.registerType('sklearn.gaussian_process.kernels.ConstantKernel', class {});
  3601. this.registerType('sklearn.gaussian_process.kernels.DotProduct', class {});
  3602. this.registerType('sklearn.gaussian_process.kernels.Product', class {});
  3603. this.registerType('sklearn.gaussian_process.kernels.RBF', class {});
  3604. this.registerType('sklearn.gaussian_process.kernels.Sum', class {});
  3605. this.registerType('sklearn.gaussian_process.kernels.WhiteKernel', class {});
  3606. this.registerType('sklearn.grid_search._CVScoreTuple', class {});
  3607. this.registerType('sklearn.grid_search.GridSearchCV', class {});
  3608. this.registerType('sklearn.impute._base.SimpleImputer', class {});
  3609. this.registerType('sklearn.impute._iterative.IterativeImputer', class {});
  3610. this.registerType('sklearn.impute._iterative._ImputerTriplet', class {});
  3611. this.registerType('sklearn.impute.SimpleImputer', class {});
  3612. this.registerType('sklearn.isotonic.IsotonicRegression', class {});
  3613. this.registerType('sklearn.kernel_ridge.KernelRidge', class {});
  3614. this.registerType('sklearn.linear_model._base.LinearRegression', class {});
  3615. this.registerType('sklearn.linear_model._bayes.BayesianRidge', class {});
  3616. this.registerType('sklearn.linear_model._coordinate_descent.ElasticNetCV', class {});
  3617. this.registerType('sklearn.linear_model._coordinate_descent.ElasticNet', class {});
  3618. this.registerType('sklearn.linear_model._coordinate_descent.Lasso', class {});
  3619. this.registerType('sklearn.linear_model._least_angle.LassoLarsCV', class {});
  3620. this.registerType('sklearn.linear_model._logistic.LogisticRegression', class {});
  3621. this.registerType('sklearn.linear_model._logistic.LogisticRegressionCV', class {});
  3622. this.registerType('sklearn.linear_model._perceptron.Perceptron', class {});
  3623. this.registerType('sklearn.linear_model._quantile.QuantileRegressor', class {});
  3624. this.registerType('sklearn.linear_model._ridge.Ridge', class {});
  3625. this.registerType('sklearn.linear_model._ridge.RidgeClassifier', class {});
  3626. this.registerType('sklearn.linear_model._ridge.RidgeClassifierCV', class {});
  3627. this.registerType('sklearn.linear_model._sgd_fast.Hinge', class {});
  3628. this.registerType('sklearn.linear_model._sgd_fast.Log', class {});
  3629. this.registerType('sklearn.linear_model._sgd_fast.ModifiedHuber', class {});
  3630. this.registerType('sklearn.linear_model._sgd_fast.SquaredHinge', class {});
  3631. this.registerType('sklearn.linear_model._stochastic_gradient.SGDClassifier', class {});
  3632. this.registerType('sklearn.linear_model._stochastic_gradient.SGDRegressor', class {});
  3633. this.registerType('sklearn.linear_model.base.LinearRegression', class {});
  3634. this.registerType('sklearn.linear_model.coordinate_descent.ElasticNet', class {});
  3635. this.registerType('sklearn.linear_model.sgd_fast.Hinge', class {});
  3636. this.registerType('sklearn.linear_model.LogisticRegression', class {});
  3637. this.registerType('sklearn.linear_model.logistic.LogisticRegression', class {});
  3638. this.registerType('sklearn.linear_model.logistic.LogisticRegressionCV', class {});
  3639. this.registerType('sklearn.linear_model.LassoLars​', class {});
  3640. this.registerType('sklearn.linear_model.ridge.Ridge', class {});
  3641. this.registerType('sklearn.linear_model.sgd_fast.Log', class {});
  3642. this.registerType('sklearn.linear_model.stochastic_gradient.SGDClassifier', class {});
  3643. this.registerType('sklearn.manifold._t_sne.TSNE', class {});
  3644. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric', class extends builtins.object {});
  3645. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric32', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3646. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric64', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3647. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3648. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance32', class extends sklearn.metrics._dist_metrics.DistanceMetric32 {});
  3649. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance64', class extends sklearn.metrics._dist_metrics.DistanceMetric64 {});
  3650. this.registerType('sklearn.metrics._dist_metrics.ManhattanDistance', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3651. this.registerType('sklearn.metrics._dist_metrics.ManhattanDistance64', class extends sklearn.metrics._dist_metrics.DistanceMetric64 {});
  3652. this.registerType('sklearn.metrics._scorer._PassthroughScorer', class {});
  3653. this.registerType('sklearn.metrics._scorer._PredictScorer', class {});
  3654. this.registerType('sklearn.metrics.scorer._PredictScorer', class {});
  3655. this.registerType('sklearn.metrics._scorer._ThresholdScorer', class {});
  3656. this.registerType('sklearn.metrics._scorer._Scorer', class {});
  3657. this.registerType('sklearn.mixture._bayesian_mixture.BayesianGaussianMixture', class {});
  3658. this.registerType('sklearn.mixture._gaussian_mixture.GaussianMixture', class {});
  3659. this.registerType('sklearn.model_selection._search.GridSearchCV', class {});
  3660. this.registerType('sklearn.model_selection._search.RandomizedSearchCV', class {});
  3661. this.registerType('sklearn.model_selection._split.KFold', class {});
  3662. this.registerType('sklearn.model_selection._split.RepeatedKFold', class {});
  3663. this.registerType('sklearn.model_selection._split.StratifiedKFold', class {});
  3664. this.registerType('sklearn.model_selection._split.StratifiedShuffleSplit', class {});
  3665. this.registerType('sklearn.model_selection._split.TimeSeriesSplit', class {});
  3666. this.registerType('sklearn.multiclass.OneVsRestClassifier', class {});
  3667. this.registerType('sklearn.multioutput.ClassifierChain', class {});
  3668. this.registerType('sklearn.multioutput.MultiOutputClassifier', class {});
  3669. this.registerType('sklearn.multioutput.MultiOutputRegressor', class {});
  3670. this.registerType('sklearn.naive_bayes.BernoulliNB', class {});
  3671. this.registerType('sklearn.naive_bayes.ComplementNB', class {});
  3672. this.registerType('sklearn.naive_bayes.GaussianNB', class {});
  3673. this.registerType('sklearn.naive_bayes.MultinomialNB', class {});
  3674. this.registerType('sklearn.neighbors.ball_tree.BallTree', class {});
  3675. this.registerFunction('sklearn.neighbors.ball_tree.newObj', (obj) => {
  3676. return obj.__new__(obj);
  3677. });
  3678. this.registerType('sklearn.neighbors._classification.KNeighborsClassifier', class {});
  3679. this.registerFunction('sklearn.neighbors._dist_metrics.newObj');
  3680. this.registerType('sklearn.neighbors._dist_metrics.EuclideanDistance', class {});
  3681. this.registerType('sklearn.neighbors._kd_tree.BinaryTree64', class extends builtins.object {});
  3682. this.registerType('sklearn.neighbors._kd_tree.KDTree64', class extends sklearn.neighbors._kd_tree.BinaryTree64 {});
  3683. this.registerType('sklearn.neighbors._kd_tree.KDTree', class extends sklearn.neighbors._kd_tree.KDTree64 {});
  3684. this.registerFunction('sklearn.neighbors._kd_tree.newObj', (obj) => {
  3685. return obj.__new__(obj);
  3686. });
  3687. this.registerType('sklearn.neighbors._regression.KNeighborsRegressor', class {});
  3688. this.registerType('sklearn.neighbors._unsupervised.NearestNeighbors', class {});
  3689. this.registerType('sklearn.neighbors.classification.KNeighborsClassifier', class {});
  3690. this.registerFunction('sklearn.neighbors.dist_metrics.newObj', (obj) => {
  3691. return obj.__new__(obj);
  3692. });
  3693. this.registerType('sklearn.neighbors.dist_metrics.EuclideanDistance', class {});
  3694. this.registerFunction('sklearn.neighbors.kd_tree.newObj', (obj) => {
  3695. return obj.__new__(obj);
  3696. });
  3697. this.registerType('sklearn.neighbors.kd_tree.KDTree', class {});
  3698. this.registerType('sklearn.neighbors.KNeighborsClassifier', class {});
  3699. this.registerType('sklearn.neighbors.KNeighborsRegressor', class {});
  3700. this.registerType('sklearn.neighbors.regression.KNeighborsRegressor', class {});
  3701. this.registerType('sklearn.neighbors.unsupervised.NearestNeighbors', class {});
  3702. this.registerType('sklearn.neural_network._multilayer_perceptron.MLPClassifier', class {});
  3703. this.registerType('sklearn.neural_network._multilayer_perceptron.MLPRegressor', class {});
  3704. this.registerType('sklearn.neural_network._stochastic_optimizers.AdamOptimizer', class {});
  3705. this.registerType('sklearn.neural_network._stochastic_optimizers.SGDOptimizer', class {});
  3706. this.registerType('sklearn.neural_network.rbm.BernoulliRBM', 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_gradient.SGDClassifier', class {});
  3710. this.registerType('sklearn.pipeline.Pipeline', class {});
  3711. this.registerType('sklearn.pipeline.FeatureUnion', class {});
  3712. this.registerType('sklearn.preprocessing._data.MinMaxScaler', class {});
  3713. this.registerType('sklearn.preprocessing._data.MaxAbsScaler', class {});
  3714. this.registerType('sklearn.preprocessing._data.Normalizer', class {});
  3715. this.registerType('sklearn.preprocessing._data.PolynomialFeatures', class {});
  3716. this.registerType('sklearn.preprocessing._data.PowerTransformer', class {});
  3717. this.registerType('sklearn.preprocessing._data.QuantileTransformer', class {});
  3718. this.registerType('sklearn.preprocessing._data.RobustScaler', class {});
  3719. this.registerType('sklearn.preprocessing._data.StandardScaler', class {});
  3720. this.registerType('sklearn.preprocessing._discretization.KBinsDiscretizer', class {});
  3721. this.registerType('sklearn.preprocessing._encoders.OneHotEncoder', class {});
  3722. this.registerType('sklearn.preprocessing._encoders.OrdinalEncoder', class {});
  3723. this.registerType('sklearn.preprocessing._function_transformer.FunctionTransformer', class {});
  3724. this.registerType('sklearn.preprocessing._label.LabelBinarizer', class {});
  3725. this.registerType('sklearn.preprocessing._label.LabelEncoder', class {});
  3726. this.registerType('sklearn.preprocessing._label.MultiLabelBinarizer', class {});
  3727. this.registerType('sklearn.preprocessing._polynomial.PolynomialFeatures', class {});
  3728. this.registerType('sklearn.preprocessing.data.Binarizer', class {});
  3729. this.registerType('sklearn.preprocessing.data.MaxAbsScaler', class {});
  3730. this.registerType('sklearn.preprocessing.data.MinMaxScaler', class {});
  3731. this.registerType('sklearn.preprocessing.data.Normalizer', class {});
  3732. this.registerType('sklearn.preprocessing.data.OneHotEncoder', class {});
  3733. this.registerType('sklearn.preprocessing.data.PolynomialFeatures', class {});
  3734. this.registerType('sklearn.preprocessing.data.PowerTransformer', class {});
  3735. this.registerType('sklearn.preprocessing.data.RobustScaler', class {});
  3736. this.registerType('sklearn.preprocessing.data.QuantileTransformer', class {});
  3737. this.registerType('sklearn.preprocessing.data.StandardScaler', class {});
  3738. this.registerType('sklearn.preprocessing.imputation.Imputer', class {});
  3739. this.registerType('sklearn.preprocessing.label.LabelBinarizer', class {});
  3740. this.registerType('sklearn.preprocessing.label.LabelEncoder', class {});
  3741. this.registerType('sklearn.preprocessing.label.MultiLabelBinarizer', class {});
  3742. this.registerType('sklearn.random_projection.GaussianRandomProjection', class {});
  3743. this.registerType('sklearn.svm._classes.LinearSVC', class {});
  3744. this.registerType('sklearn.svm._classes.NuSVC', class {});
  3745. this.registerType('sklearn.svm._classes.OneClassSVM', class {});
  3746. this.registerType('sklearn.svm._classes.SVC', class {});
  3747. this.registerType('sklearn.svm._classes.SVR', class {});
  3748. this.registerType('sklearn.svm.classes.LinearSVC', class {});
  3749. this.registerType('sklearn.svm.classes.OneClassSVM', class {});
  3750. this.registerType('sklearn.svm.classes.SVC', class {});
  3751. this.registerType('sklearn.svm.classes.SVR', class {});
  3752. this.registerType('sklearn.tree._classes.DecisionTreeClassifier', class {});
  3753. this.registerType('sklearn.tree._classes.DecisionTreeRegressor', class {});
  3754. this.registerType('sklearn.tree._classes.ExtraTreeClassifier', class {});
  3755. this.registerType('sklearn.tree._classes.ExtraTreeRegressor', class {});
  3756. this.registerType('sklearn.tree._tree.Tree', class {
  3757. constructor(n_features, n_classes, n_outputs) {
  3758. this.n_features = n_features;
  3759. this.n_classes = n_classes;
  3760. this.n_outputs = n_outputs;
  3761. }
  3762. __setstate__(state) {
  3763. this.max_depth = state.get('max_depth');
  3764. this.node_count = state.get('node_count');
  3765. this.nodes = state.get('nodes');
  3766. this.values = state.get('values');
  3767. }
  3768. });
  3769. this.registerType('sklearn.tree.tree.DecisionTreeClassifier', class {});
  3770. this.registerType('sklearn.tree.tree.DecisionTreeRegressor', class {});
  3771. this.registerType('sklearn.tree.tree.ExtraTreeClassifier', class {});
  3772. this.registerType('sklearn.utils._bunch.Bunch', class {});
  3773. this.registerType('sklearn.utils._metadata_requests.MetadataRequest', class {});
  3774. this.registerType('sklearn.utils._metadata_requests.MethodMetadataRequest', class {});
  3775. this.registerType('sklearn.utils.deprecation.DeprecationDict', class {});
  3776. this.registerType('pickle.Unpickler', class {
  3777. constructor(data) {
  3778. this._reader = data instanceof Uint8Array ? new python.BinaryReader(data) : new python.StreamReader(data);
  3779. this.persistent_load = () => {
  3780. throw new python.Error('Unsupported persistent id.');
  3781. };
  3782. }
  3783. load() {
  3784. const reader = this._reader;
  3785. const marker = [];
  3786. let stack = [];
  3787. const memo = {};
  3788. let size = 0;
  3789. while (reader.position < reader.length) {
  3790. const opcode = reader.byte();
  3791. // console.log(`${(reader.position - 1).toString()} ${opcode}`);
  3792. // https://svn.python.org/projects/python/trunk/Lib/pickletools.py
  3793. // https://github.com/python/cpython/blob/master/Lib/pickle.py
  3794. switch (opcode) {
  3795. case 128: { // PROTO
  3796. const version = reader.byte();
  3797. if (version > 5) {
  3798. throw new python.Error(`Unsupported protocol version '${version}'.`);
  3799. }
  3800. break;
  3801. }
  3802. case 99: { // GLOBAL 'c'
  3803. const module = reader.line();
  3804. const name = reader.line();
  3805. stack.push(this.find_class(module, name));
  3806. break;
  3807. }
  3808. case 147: { // STACK_GLOBAL '\x93' (Protocol 4)
  3809. const name = stack.pop();
  3810. const module = stack.pop();
  3811. stack.push(this.find_class(module, name));
  3812. break;
  3813. }
  3814. case 111: { // OBJ 'o'
  3815. const args = stack;
  3816. const cls = args.pop();
  3817. stack = marker.pop();
  3818. const obj = this._instantiate(cls, args);
  3819. stack.push(obj);
  3820. break;
  3821. }
  3822. case 112 : { // PUT 'p'
  3823. const index = parseInt(reader.line(), 10);
  3824. if (stack.length === 0) {
  3825. throw new python.Error(`Empty stack during 'PUT' operation.`);
  3826. }
  3827. memo[index] = stack[stack.length - 1];
  3828. size++;
  3829. break;
  3830. }
  3831. case 103: { // GET 'g'
  3832. const index = parseInt(reader.line(), 10);
  3833. if (index in memo === false) {
  3834. throw new python.Error(`Memo value not found at index '${index}'.`);
  3835. }
  3836. stack.push(memo[index]);
  3837. break;
  3838. }
  3839. case 48: // POP '0'
  3840. stack.pop();
  3841. break;
  3842. case 49: // POP_MARK '1'
  3843. stack = marker.pop();
  3844. break;
  3845. case 50: // DUP '2'
  3846. if (stack.length === 0) {
  3847. throw new python.Error(`Empty stack during 'DUP' operation.`);
  3848. }
  3849. stack.push(stack[stack.length - 1]);
  3850. break;
  3851. case 80: // PERSID 'P'
  3852. stack.push(this.persistent_load(reader.line()));
  3853. break;
  3854. case 81: // BINPERSID 'Q'
  3855. stack.push(this.persistent_load(stack.pop()));
  3856. break;
  3857. case 82: { // REDUCE 'R'
  3858. const args = stack.pop();
  3859. const func = stack.pop();
  3860. stack.push(this._reduce(func, args));
  3861. break;
  3862. }
  3863. case 129: { // NEWOBJ
  3864. const args = stack.pop();
  3865. const cls = stack.pop();
  3866. const obj = this._newobj(cls, args);
  3867. stack.push(obj);
  3868. break;
  3869. }
  3870. case 146: { // NEWOBJ_EX '\x92' (Protocol 4)
  3871. const kwargs = stack.pop();
  3872. const args = stack.pop();
  3873. const cls = stack.pop();
  3874. if (Object.entries(kwargs).length > 0) {
  3875. throw new python.Error("Unpickle 'NEWOBJ_EX' not implemented.");
  3876. }
  3877. const obj = this._newobj(cls, args);
  3878. stack.push(obj);
  3879. break;
  3880. }
  3881. case 104: { // BINGET 'h'
  3882. const index = reader.byte();
  3883. if (index in memo === false) {
  3884. throw new python.Error(`Memo value not found at index '${index}'.`);
  3885. }
  3886. stack.push(memo[index]);
  3887. break;
  3888. }
  3889. case 105: { // INST 'i'
  3890. const module = reader.line();
  3891. const name = reader.line();
  3892. const args = stack;
  3893. const cls = `${module}.${name}`;
  3894. stack = marker.pop();
  3895. // cls = this.find_class(module, name)
  3896. const obj = this._instantiate(cls, args);
  3897. stack.push(obj);
  3898. break;
  3899. }
  3900. case 106: { // LONG_BINGET 'j'
  3901. const index = reader.uint32();
  3902. if (index in memo === false) {
  3903. throw new python.Error(`Memo value not found at index '${index}'.`);
  3904. }
  3905. stack.push(memo[index]);
  3906. break;
  3907. }
  3908. case 113: // BINPUT 'q'
  3909. if (stack.length === 0) {
  3910. throw new python.Error(`Empty stack during 'BINPUT' operation.`);
  3911. }
  3912. memo[reader.byte()] = stack[stack.length - 1];
  3913. size++;
  3914. break;
  3915. case 114: // LONG_BINPUT 'r'
  3916. if (stack.length === 0) {
  3917. throw new python.Error(`Empty stack during 'LONG_BINPUT' operation.`);
  3918. }
  3919. memo[reader.uint32()] = stack[stack.length - 1];
  3920. size++;
  3921. break;
  3922. case 74: // BININT 'J'
  3923. stack.push(reader.int32());
  3924. break;
  3925. case 75: // BININT1 'K'
  3926. stack.push(reader.byte());
  3927. break;
  3928. case 76: // LONG 'L'
  3929. stack.push(parseInt(reader.line(), 10));
  3930. break;
  3931. case 77: // BININT2 'M'
  3932. stack.push(reader.uint16());
  3933. break;
  3934. case 66: // BINBYTES 'B' (Protocol 3)
  3935. stack.push(reader.read(reader.int32()));
  3936. break;
  3937. case 67: // SHORT_BINBYTES 'C' (Protocol 3)
  3938. stack.push(reader.read(reader.byte()));
  3939. break;
  3940. case 142: // BINBYTES8 '\x8e' (Protocol 4)
  3941. stack.push(reader.read(reader.int64().toNumber()));
  3942. break;
  3943. case 70: // FLOAT 'F'
  3944. stack.push(parseFloat(reader.line()));
  3945. break;
  3946. case 71: // BINFLOAT 'G'
  3947. stack.push(reader.float64());
  3948. break;
  3949. case 73: { // INT 'I'
  3950. const value = reader.line();
  3951. if (value === '01') {
  3952. stack.push(true);
  3953. } else if (value === '00') {
  3954. stack.push(false);
  3955. } else {
  3956. stack.push(parseInt(value, 10));
  3957. }
  3958. break;
  3959. }
  3960. case 93: // EMPTY_LIST ']'
  3961. stack.push(new builtins.list());
  3962. break;
  3963. case 41: // EMPTY_TUPLE ')'
  3964. stack.push([]);
  3965. break;
  3966. case 143: // EMPTY_SET '\x8f' (Protocol 4)
  3967. stack.push([]);
  3968. break;
  3969. case 144: { // ADDITEMS '\x90' (Protocol 4)
  3970. const items = stack;
  3971. stack = marker.pop();
  3972. const obj = stack[stack.length - 1];
  3973. for (let i = 0; i < items.length; i++) {
  3974. obj.push(items[i]);
  3975. }
  3976. break;
  3977. }
  3978. case 145: { // FROZENSET '\x91' (Protocol 4)
  3979. const items = stack;
  3980. stack = marker.pop();
  3981. stack.push(items);
  3982. break;
  3983. }
  3984. case 100: { // DICT 'd'
  3985. const items = stack;
  3986. stack = marker.pop();
  3987. const dict = new builtins.dict();
  3988. for (let i = 0; i < items.length; i += 2) {
  3989. dict.__setitem__(items[i], items[i + 1]);
  3990. }
  3991. stack.push(dict);
  3992. break;
  3993. }
  3994. case 108: { // LIST 'l'
  3995. const items = stack;
  3996. stack = marker.pop();
  3997. stack.push(items);
  3998. break;
  3999. }
  4000. case 116: { // TUPLE 't'
  4001. const items = stack;
  4002. stack = marker.pop();
  4003. stack.push(items);
  4004. break;
  4005. }
  4006. case 133: { // TUPLE1 // '\x85'
  4007. stack.push([stack.pop()]);
  4008. break;
  4009. }
  4010. case 134: { // TUPLE2 '\x86'
  4011. const b = stack.pop();
  4012. const a = stack.pop();
  4013. stack.push([a, b]);
  4014. break;
  4015. }
  4016. case 135: { // TUPLE3 '\x87'
  4017. const c = stack.pop();
  4018. const b = stack.pop();
  4019. const a = stack.pop();
  4020. stack.push([a, b, c]);
  4021. break;
  4022. }
  4023. case 115: { // SETITEM 's'
  4024. const value = stack.pop();
  4025. const key = stack.pop();
  4026. const obj = stack[stack.length - 1];
  4027. if (obj.__setitem__) {
  4028. obj.__setitem__(key, value);
  4029. } else {
  4030. obj[key] = value;
  4031. }
  4032. break;
  4033. }
  4034. case 117: { // SETITEMS 'u'
  4035. const items = stack;
  4036. stack = marker.pop();
  4037. const obj = stack[stack.length - 1];
  4038. if (obj.__setitem__) {
  4039. for (let i = 0; i < items.length; i += 2) {
  4040. obj.__setitem__(items[i], items[i + 1]);
  4041. }
  4042. } else {
  4043. for (let i = 0; i < items.length; i += 2) {
  4044. obj[items[i]] = items[i + 1];
  4045. }
  4046. }
  4047. break;
  4048. }
  4049. case 125: // EMPTY_DICT '}'
  4050. stack.push(new builtins.dict());
  4051. break;
  4052. case 97: { // APPEND 'a'
  4053. const append = stack.pop();
  4054. stack[stack.length - 1].push(append);
  4055. break;
  4056. }
  4057. case 101: { // APPENDS 'e'
  4058. const appends = stack;
  4059. stack = marker.pop();
  4060. const list = stack[stack.length - 1];
  4061. list.push(...appends);
  4062. break;
  4063. }
  4064. case 83: { // STRING 'S'
  4065. const str = reader.line();
  4066. stack.push(str.substring(1, str.length - 1));
  4067. break;
  4068. }
  4069. case 84: // BINSTRING 'T'
  4070. stack.push(reader.string(reader.uint32()));
  4071. break;
  4072. case 85 : // SHORT_BINSTRING 'U'
  4073. stack.push(reader.string(reader.byte()));
  4074. break;
  4075. case 86: // UNICODE 'V'
  4076. stack.push(reader.line());
  4077. break;
  4078. case 88: // BINUNICODE 'X
  4079. stack.push(reader.string(reader.uint32(), 'utf-8'));
  4080. break;
  4081. case 140: // SHORT_BINUNICODE '\x8c' (Protocol 4)
  4082. stack.push(reader.string(reader.byte(), 'utf-8'));
  4083. break;
  4084. case 98: { // BUILD 'b'
  4085. const state = stack.pop();
  4086. let obj = stack.pop();
  4087. if (obj.__setstate__) {
  4088. if (obj.__setstate__.__call__) {
  4089. obj.__setstate__.__call__([obj, state]);
  4090. } else {
  4091. obj.__setstate__(state);
  4092. }
  4093. } else if (ArrayBuffer.isView(state) || Object(state) !== state) {
  4094. obj.__state__ = state;
  4095. } else if (obj instanceof Map && state instanceof Map) {
  4096. for (const [key, value] of state) {
  4097. obj.set(key, value);
  4098. }
  4099. } else if (obj instanceof Map) {
  4100. /* eslint-disable guard-for-in */
  4101. for (const key in state) {
  4102. obj.set(key, state[key]);
  4103. }
  4104. /* eslint-enable guard-for-in */
  4105. } else if (state instanceof Map) {
  4106. for (const [key, value] of state) {
  4107. obj[key] = value;
  4108. }
  4109. } else {
  4110. Object.assign(obj, state);
  4111. }
  4112. if (obj.__read__) {
  4113. obj = obj.__read__(this);
  4114. }
  4115. stack.push(obj);
  4116. break;
  4117. }
  4118. case 40: // MARK '('
  4119. marker.push(stack);
  4120. stack = [];
  4121. break;
  4122. case 136: // NEWTRUE '\x88'
  4123. stack.push(true);
  4124. break;
  4125. case 137: // NEWFALSE '\x89'
  4126. stack.push(false);
  4127. break;
  4128. case 138: { // LONG1 '\x8a'
  4129. const data = reader.read(reader.byte());
  4130. let number = 0;
  4131. switch (data.length) {
  4132. case 0: number = 0; break;
  4133. case 1: [number] = data; break;
  4134. case 2: number = data[1] << 8 | data[0]; break;
  4135. case 3: number = data[2] << 16 | data[1] << 8 | data[0]; break;
  4136. case 4: number = (data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]) >>> 0; break;
  4137. case 5: number = data[4] * 0x100000000 + ((data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]) >>> 0); break;
  4138. default: number = Array.prototype.slice.call(data, 0); break;
  4139. }
  4140. stack.push(number);
  4141. break;
  4142. }
  4143. case 139: // LONG4 '\x8b'
  4144. // decode LONG4
  4145. stack.push(reader.read(reader.uint32()));
  4146. break;
  4147. case 148: // MEMOIZE '\x94' (Protocol 4)
  4148. memo[size++] = stack[stack.length - 1];
  4149. break;
  4150. case 149: // FRAME '\x95' (Protocol 4)
  4151. reader.read(8);
  4152. break;
  4153. case 150: { // BYTEARRAY8 '\x96' (Protocol 5)
  4154. stack.push(reader.read(reader.int64().toNumber()));
  4155. break;
  4156. }
  4157. case 78: // NONE 'N'
  4158. stack.push(null);
  4159. break;
  4160. case 46: // STOP '.'
  4161. return stack.pop();
  4162. case 141: // BINUNICODE8 '\x8d' (Protocol 4)
  4163. case 151: // NEXT_BUFFER '\x97' (Protocol 5)
  4164. case 152: // READONLY_BUFFER '\x98' (Protocol 5)
  4165. default:
  4166. throw new python.Error(`Unknown opcode ${opcode} at position ${(reader.position - 1)}.`);
  4167. }
  4168. }
  4169. throw new python.Error('Unexpected end of file.');
  4170. }
  4171. find_class(module, name) {
  4172. execution.__import__(module);
  4173. return execution.resolve(`${module}.${name}`);
  4174. }
  4175. _instantiate(cls, args) {
  4176. return execution.invoke(cls, args);
  4177. }
  4178. _newobj(cls, args) {
  4179. // cls.__new__(cls, args)
  4180. return execution.invoke(cls, args);
  4181. }
  4182. _reduce(func, args) {
  4183. return execution.invoke(func, args);
  4184. }
  4185. read(size) {
  4186. return this._reader.read(size);
  4187. }
  4188. stream(size) {
  4189. return this._reader.stream(size);
  4190. }
  4191. });
  4192. this.registerType('random.Random', class {});
  4193. this.registerType('re.Pattern', class {
  4194. constructor(pattern, flags) {
  4195. this.pattern = pattern;
  4196. this.flags = flags;
  4197. }
  4198. });
  4199. this.registerType('spacy._ml.PrecomputableAffine', class {
  4200. __setstate__(state) {
  4201. Object.assign(this, new pickle.Unpickler(state).load());
  4202. }
  4203. });
  4204. this.registerType('spacy.syntax._parser_model.ParserModel', class {
  4205. __setstate__(state) {
  4206. Object.assign(this, new pickle.Unpickler(state).load());
  4207. }
  4208. });
  4209. this.registerType('theano.compile.function_module._constructor_Function', class {});
  4210. this.registerType('theano.compile.function_module._constructor_FunctionMaker', class {});
  4211. this.registerType('theano.compile.function_module.Function', class {});
  4212. this.registerType('theano.compile.function_module.Supervisor', class {});
  4213. this.registerType('theano.compile.io.In', class {});
  4214. this.registerType('theano.compile.io.SymbolicOutput', class {});
  4215. this.registerType('theano.compile.mode.Mode', class {});
  4216. this.registerType('theano.compile.ops.OutputGuard', class {});
  4217. this.registerType('theano.compile.ops.Shape', class {});
  4218. this.registerType('theano.compile.ops.Shape_i', class {});
  4219. this.registerType('theano.gof.destroyhandler.DestroyHandler', class {});
  4220. this.registerType('theano.gof.fg.FunctionGraph', class {});
  4221. this.registerType('theano.gof.graph.Apply', class {});
  4222. this.registerType('theano.gof.link.Container', class {});
  4223. this.registerType('theano.gof.opt._metadict', class {});
  4224. this.registerType('theano.gof.opt.ChangeTracker', class {});
  4225. this.registerType('theano.gof.opt.MergeFeature', class {});
  4226. this.registerType('theano.gof.optdb.Query', class {});
  4227. this.registerType('theano.gof.toolbox.PreserveVariableAttributes', class {});
  4228. this.registerType('theano.gof.toolbox.ReplaceValidate', class {});
  4229. this.registerType('theano.gof.utils.scratchpad', class {});
  4230. this.registerType('theano.misc.ordered_set.Link', class {});
  4231. this.registerType('theano.misc.ordered_set.OrderedSet', class {});
  4232. this.registerType('theano.sandbox.cuda.basic_ops.HostFromGpu', class {});
  4233. this.registerType('theano.sandbox.cuda.type.CudaNdarray_unpickler', class {});
  4234. this.registerType('theano.sandbox.cuda.type.CudaNdarrayType', class {});
  4235. this.registerType('theano.sandbox.cuda.var.CudaNdarraySharedVariable', class {});
  4236. this.registerType('theano.scalar.basic.Abs', class {});
  4237. this.registerType('theano.scalar.basic.Add', class {});
  4238. this.registerType('theano.scalar.basic.Cast', class {});
  4239. this.registerType('theano.scalar.basic.Composite', class {});
  4240. this.registerType('theano.scalar.basic.EQ', class {});
  4241. this.registerType('theano.scalar.basic.GE', class {});
  4242. this.registerType('theano.scalar.basic.Identity', class {});
  4243. this.registerType('theano.scalar.basic.IntDiv', class {});
  4244. this.registerType('theano.scalar.basic.Inv', class {});
  4245. this.registerType('theano.scalar.basic.LE', class {});
  4246. this.registerType('theano.scalar.basic.LT', class {});
  4247. this.registerType('theano.scalar.basic.Mul', class {});
  4248. this.registerType('theano.scalar.basic.Neg', class {});
  4249. this.registerType('theano.scalar.basic.Pow', class {});
  4250. this.registerType('theano.scalar.basic.Scalar', class {});
  4251. this.registerType('theano.scalar.basic.ScalarConstant', class {});
  4252. this.registerType('theano.scalar.basic.ScalarVariable', class {});
  4253. this.registerType('theano.scalar.basic.Second', class {});
  4254. this.registerType('theano.scalar.basic.Sgn', class {});
  4255. this.registerType('theano.scalar.basic.specific_out', class {});
  4256. this.registerType('theano.scalar.basic.Sub', class {});
  4257. this.registerType('theano.scalar.basic.Switch', class {});
  4258. this.registerType('theano.scalar.basic.Tanh', class {});
  4259. this.registerType('theano.scalar.basic.transfer_type', class {});
  4260. this.registerType('theano.scalar.basic.TrueDiv', class {});
  4261. this.registerType('theano.tensor.basic.Alloc', class {});
  4262. this.registerType('theano.tensor.basic.Dot', class {});
  4263. this.registerType('theano.tensor.basic.MaxAndArgmax', class {});
  4264. this.registerType('theano.tensor.basic.Reshape', class {});
  4265. this.registerType('theano.tensor.basic.ScalarFromTensor', class {});
  4266. this.registerType('theano.tensor.blas.Dot22', class {});
  4267. this.registerType('theano.tensor.blas.Dot22Scalar', class {});
  4268. this.registerType('theano.tensor.blas.Gemm', class {});
  4269. this.registerType('theano.tensor.elemwise.DimShuffle', class {});
  4270. this.registerType('theano.tensor.elemwise.Elemwise', class {});
  4271. this.registerType('theano.tensor.elemwise.Sum', class {});
  4272. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d', class {});
  4273. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d_gradInputs', class {});
  4274. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d_gradWeights', class {});
  4275. this.registerType('theano.tensor.nnet.corr.CorrMM', class {});
  4276. this.registerType('theano.tensor.nnet.corr.CorrMM_gradInputs', class {});
  4277. this.registerType('theano.tensor.nnet.corr.CorrMM_gradWeights', class {});
  4278. this.registerType('theano.tensor.nnet.nnet.CrossentropyCategorical1Hot', class {});
  4279. this.registerType('theano.tensor.nnet.nnet.CrossentropyCategorical1HotGrad', class {});
  4280. this.registerType('theano.tensor.nnet.nnet.CrossentropySoftmax1HotWithBiasDx', class {});
  4281. this.registerType('theano.tensor.nnet.nnet.CrossentropySoftmaxArgmax1HotWithBias', class {});
  4282. this.registerType('theano.tensor.nnet.nnet.Softmax', class {});
  4283. this.registerType('theano.tensor.nnet.nnet.SoftmaxGrad', class {});
  4284. this.registerType('theano.tensor.nnet.nnet.SoftmaxWithBias', class {});
  4285. this.registerType('theano.tensor.opt.MakeVector', class {});
  4286. this.registerType('theano.tensor.opt.ShapeFeature', class {});
  4287. this.registerType('theano.tensor.sharedvar.TensorSharedVariable', class {});
  4288. this.registerType('theano.tensor.signal.pool.MaxPoolGrad', class {});
  4289. this.registerType('theano.tensor.signal.pool.Pool', class {});
  4290. this.registerType('theano.tensor.subtensor.Subtensor', class {});
  4291. this.registerType('theano.tensor.type.TensorType', class {});
  4292. this.registerType('theano.tensor.var.TensorConstant', class {});
  4293. this.registerType('theano.tensor.var.TensorConstantSignature', class {});
  4294. this.registerType('theano.tensor.var.TensorVariable', class {});
  4295. this.registerType('thinc.describe.Biases', class {});
  4296. this.registerType('thinc.describe.Dimension', class {});
  4297. this.registerType('thinc.describe.Gradient', class {});
  4298. this.registerType('thinc.describe.Weights', class {});
  4299. this.registerType('thinc.describe.Synapses', class {});
  4300. this.registerType('thinc.neural._classes.affine.Affine', class {
  4301. __setstate__(state) {
  4302. Object.assign(this, new pickle.Unpickler(state).load());
  4303. }
  4304. });
  4305. this.registerType('thinc.neural._classes.convolution.ExtractWindow', class {
  4306. __setstate__(state) {
  4307. Object.assign(this, new pickle.Unpickler(state).load());
  4308. }
  4309. });
  4310. this.registerType('thinc.neural._classes.feature_extracter.FeatureExtracter', class {
  4311. __setstate__(state) {
  4312. Object.assign(this, new pickle.Unpickler(state).load());
  4313. }
  4314. });
  4315. this.registerType('thinc.neural._classes.feed_forward.FeedForward', class {
  4316. __setstate__(state) {
  4317. Object.assign(this, new pickle.Unpickler(state).load());
  4318. }
  4319. });
  4320. this.registerType('thinc.neural._classes.function_layer.FunctionLayer', class {
  4321. __setstate__(state) {
  4322. Object.assign(this, new pickle.Unpickler(state).load());
  4323. }
  4324. });
  4325. this.registerType('thinc.neural._classes.hash_embed.HashEmbed', class {
  4326. __setstate__(state) {
  4327. Object.assign(this, new pickle.Unpickler(state).load());
  4328. }
  4329. });
  4330. this.registerType('thinc.neural._classes.layernorm.LayerNorm', class {
  4331. __setstate__(state) {
  4332. Object.assign(this, new pickle.Unpickler(state).load());
  4333. }
  4334. });
  4335. this.registerType('thinc.neural._classes.maxout.Maxout', class {
  4336. __setstate__(state) {
  4337. Object.assign(this, new pickle.Unpickler(state).load());
  4338. }
  4339. });
  4340. this.registerType('thinc.neural._classes.resnet.Residual', class {
  4341. __setstate__(state) {
  4342. Object.assign(this, new pickle.Unpickler(state).load());
  4343. }
  4344. });
  4345. this.registerType('thinc.neural._classes.softmax.Softmax', class {
  4346. __setstate__(state) {
  4347. Object.assign(this, new pickle.Unpickler(state).load());
  4348. }
  4349. });
  4350. this.registerType('thinc.neural.mem.Memory', class {
  4351. });
  4352. this.registerType('thinc.neural.ops.NumpyOps', class {
  4353. });
  4354. this.registerType('__main__.BYOLState', class {
  4355. constructor(dict) {
  4356. Object.assign(this, dict);
  4357. }
  4358. });
  4359. const types = this.register('types');
  4360. this.registerType('types.GenericAlias', class {});
  4361. this.registerType('types.SimpleNamespace', class {});
  4362. this.registerType('types.BuiltinFunctionType', class {});
  4363. this.registerType('types.BuiltinMethodType', class {});
  4364. this.registerFunction('types.resolve_bases', (bases) => {
  4365. return bases;
  4366. });
  4367. this.registerFunction('types.prepare_class', (name, bases, kwds) => {
  4368. if (kwds) {
  4369. kwds = new builtins.dict(kwds);
  4370. } else {
  4371. kwds = new builtins.dict();
  4372. }
  4373. let meta = null;
  4374. if (kwds.__contains__('metaclass')) {
  4375. meta = kwds.pop('metaclass');
  4376. } else if (bases && bases.length > 0) {
  4377. meta = builtins.type(bases[0]);
  4378. } else {
  4379. meta = builtins.type;
  4380. }
  4381. if (meta instanceof builtins.type) {
  4382. meta = types._calculate_meta(meta, bases);
  4383. }
  4384. let ns = null;
  4385. if (builtins.hasattr(meta, '__prepare__')) {
  4386. // ns = meta.__prepare__(name, bases, **kwds)
  4387. } else {
  4388. ns = new builtins.dict();
  4389. }
  4390. return [meta, ns, kwds];
  4391. });
  4392. this.registerFunction('types._calculate_meta', (meta /*, bases*/) => {
  4393. const winner = meta;
  4394. return winner;
  4395. });
  4396. this.registerFunction('types.new_class', (name, bases, kwds, exec_body) => {
  4397. const resolved_bases = types.resolve_bases(bases);
  4398. const [meta, ns] = types.prepare_class(name, bases, kwds);
  4399. if (exec_body) {
  4400. exec_body(ns);
  4401. }
  4402. return new meta(name, resolved_bases, ns);
  4403. });
  4404. types.ObjectType = builtins.object;
  4405. types.ModuleType = builtins.module;
  4406. types.MethodType = builtins.method;
  4407. types.FunctionType = builtins.function;
  4408. types.TypeType = builtins.type;
  4409. types.CodeType = builtins.code;
  4410. this.registerType('xgboost.compat.XGBoostLabelEncoder', class {});
  4411. this.registerType('xgboost.core.Booster', class {
  4412. load_model(fname) {
  4413. if (fname instanceof Uint8Array) {
  4414. // XGBoosterLoadModel()
  4415. } else {
  4416. // XGBoosterUnserializeFromBuffer(handle) {
  4417. }
  4418. }
  4419. __setstate__(state) {
  4420. const handle = state.get('handle');
  4421. if (handle) {
  4422. this.handle = handle;
  4423. // XGBoosterLoadModelFromBuffer()
  4424. }
  4425. }
  4426. });
  4427. this.registerType('xgboost.sklearn.XGBClassifier', class {});
  4428. this.registerType('xgboost.sklearn.XGBRegressor', class {});
  4429. this.registerType('xgboost.sklearn.XGBRFClassifier', class {});
  4430. this.registerFunction('_codecs.encode', (obj, encoding) => {
  4431. return new builtins.bytearray(obj, encoding);
  4432. });
  4433. this.registerType('builtins.bytearray', class extends Uint8Array {
  4434. constructor(source, encoding /*, errors */) {
  4435. source = builtins.bytes.__encode__(source, encoding);
  4436. super(Number.isInteger(source) ? source : source.length);
  4437. if (Array.isArray(source)) {
  4438. for (let i = 0; i < source.length; i++) {
  4439. this[i] = source;
  4440. }
  4441. } else if (source instanceof Uint8Array) {
  4442. this.set(source, 0);
  4443. } else if (typeof source === 'string') {
  4444. for (let i = 0; i < source.length; i++) {
  4445. this[i] = source.charCodeAt(i);
  4446. }
  4447. }
  4448. }
  4449. static __encode__(source, encoding) {
  4450. if (source === undefined) {
  4451. return 0;
  4452. }
  4453. if (Number.isInteger(source)) {
  4454. return source;
  4455. }
  4456. if (Array.isArray(source) || source instanceof Uint8Array) {
  4457. return source;
  4458. }
  4459. if (typeof source === 'string') {
  4460. switch (encoding) {
  4461. case 'latin1':
  4462. case 'latin-1':
  4463. return source;
  4464. case 'utf8':
  4465. case 'utf-8':
  4466. return new TextEncoder('utf-8').encode(source);
  4467. case undefined:
  4468. throw new python.Error('Unsupported string argument without an encoding.');
  4469. default:
  4470. throw new python.Error(`Unsupported encoding '${encoding}'.`);
  4471. }
  4472. }
  4473. throw new python.Error('Unsupported source.');
  4474. }
  4475. });
  4476. this.registerType('builtins.bytes', class extends Uint8Array {
  4477. constructor(source, encoding /*, errors */) {
  4478. source = builtins.bytes.__encode__(source, encoding);
  4479. super(Number.isInteger(source) ? source : source.length);
  4480. if (Array.isArray(source)) {
  4481. for (let i = 0; i < source.length; i++) {
  4482. this[i] = source;
  4483. }
  4484. } else if (source instanceof Uint8Array) {
  4485. this.set(source, 0);
  4486. } else if (typeof source === 'string') {
  4487. for (let i = 0; i < source.length; i++) {
  4488. this[i] = source.charCodeAt(i);
  4489. }
  4490. }
  4491. }
  4492. static __encode__(source, encoding) {
  4493. if (source === undefined) {
  4494. return 0;
  4495. }
  4496. if (Number.isInteger(source)) {
  4497. return source;
  4498. }
  4499. if (Array.isArray(source) || source instanceof Uint8Array) {
  4500. return source;
  4501. }
  4502. if (typeof source === 'string') {
  4503. switch (encoding) {
  4504. case 'latin1':
  4505. case 'latin-1':
  4506. return source;
  4507. case 'utf8':
  4508. case 'utf-8':
  4509. return new TextEncoder('utf-8').encode(source);
  4510. case undefined:
  4511. throw new python.Error('Unsupported string argument without an encoding.');
  4512. default:
  4513. throw new python.Error(`Unsupported encoding '${encoding}'.`);
  4514. }
  4515. }
  4516. throw new python.Error('Unsupported source.');
  4517. }
  4518. });
  4519. this.registerType('builtins.memoryview', class {
  4520. constructor(buf) {
  4521. this._buf = buf;
  4522. }
  4523. get nbytes() {
  4524. return this._buf.length;
  4525. }
  4526. });
  4527. this.registerType('builtins.frozenset', class extends Set {
  4528. constructor(iterable) {
  4529. super();
  4530. if (iterable) {
  4531. for (const item of iterable) {
  4532. this.add(item);
  4533. }
  4534. }
  4535. }
  4536. });
  4537. this.registerFunction('builtins.exec');
  4538. this.registerFunction('builtins.issubclass', (obj, type) => {
  4539. const name = `${type.__module__}.${type.__name__}`;
  4540. if (obj.__module__ && obj.__name__) {
  4541. if (name === `${obj.__module__}.${obj.__name__}`) {
  4542. return true;
  4543. }
  4544. }
  4545. if (obj.__bases__) {
  4546. for (const base of obj.__bases__) {
  4547. if (builtins.issubclass(base, type)) {
  4548. return true;
  4549. }
  4550. }
  4551. }
  4552. return false;
  4553. });
  4554. this.registerFunction('builtins.isinstance', (obj, type) => {
  4555. if (obj && type && obj instanceof type) {
  4556. return true;
  4557. }
  4558. if (obj && obj.__class__) {
  4559. return builtins.issubclass(obj.__class__, type);
  4560. }
  4561. return false;
  4562. });
  4563. this.registerFunction('builtins.hasattr', (obj, name) => {
  4564. if (obj instanceof Map && obj.__contains__) {
  4565. return obj.__contains__(name);
  4566. }
  4567. return Object.prototype.hasOwnProperty.call(obj, name);
  4568. });
  4569. this.registerFunction('builtins.getattr', (obj, name, defaultValue) => {
  4570. if (obj && obj.__getattr__) {
  4571. return obj.__getattr__(name);
  4572. }
  4573. if (Object.prototype.hasOwnProperty.call(obj, name)) {
  4574. return obj[name];
  4575. }
  4576. return defaultValue;
  4577. });
  4578. this.registerFunction('builtins.len', (obj) => {
  4579. return obj.length;
  4580. });
  4581. this.registerFunction('builtins.setattr', (obj, name, value) => {
  4582. if (obj && obj.__setattr__) {
  4583. obj.__setattr__(name, value);
  4584. } else {
  4585. obj[name] = value;
  4586. }
  4587. });
  4588. this.registerType('builtins.set', class extends Set {
  4589. __contains__(item) {
  4590. return this.has(item);
  4591. }
  4592. update(iterable) {
  4593. for (const item of iterable) {
  4594. this.add(item);
  4595. }
  4596. }
  4597. });
  4598. this.registerType('builtins.slice', class {
  4599. constructor(start, stop, step) {
  4600. this.start = start;
  4601. this.stop = stop;
  4602. this.step = step;
  4603. }
  4604. });
  4605. this.registerFunction('builtins.hash');
  4606. this.registerType('functools.partial', class {});
  4607. this.registerFunction('functools.reduce', (func, iterable, ...args) => {
  4608. const iter = Array.from(iterable);
  4609. let acc = args.length > 0 ? args[0] : iter.shift();
  4610. for (const item of iter) {
  4611. acc = func(acc, item);
  4612. }
  4613. return acc;
  4614. });
  4615. builtins.reduce = functools.reduce;
  4616. this.registerFunction('cloudpickle.cloudpickle._builtin_type', (name) => {
  4617. return name;
  4618. });
  4619. this.registerFunction('cloudpickle.cloudpickle._fill_function');
  4620. this.registerType('cloudpickle.cloudpickle._empty_cell_value', class {});
  4621. this.registerFunction('cloudpickle.cloudpickle._make_cell', (value) => {
  4622. value = value || cloudpickle.cloudpickle._empty_cell_value;
  4623. const cell = cloudpickle.cloudpickle._make_empty_cell();
  4624. if (value !== cloudpickle.cloudpickle._empty_cell_value) {
  4625. cell.cell_contents = value;
  4626. }
  4627. return cell;
  4628. });
  4629. this.registerFunction('cloudpickle.cloudpickle._make_function', (code, globals, name, argdefs, closure) => {
  4630. // globals["__builtins__"] = __builtins__
  4631. return new types.FunctionType(code, globals, name, argdefs, closure);
  4632. });
  4633. this.registerFunction('cloudpickle.cloudpickle._make_skel_func');
  4634. cloudpickle.cloudpickle._DYNAMIC_CLASS_TRACKER_BY_ID = new builtins.dict();
  4635. this.registerFunction('cloudpickle.cloudpickle._lookup_class_or_track', (class_tracker_id, class_def) => {
  4636. if (class_tracker_id) {
  4637. class_def = cloudpickle.cloudpickle._DYNAMIC_CLASS_TRACKER_BY_ID.setdefault(class_tracker_id, class_def);
  4638. }
  4639. return class_def;
  4640. });
  4641. this.registerFunction('cloudpickle.cloudpickle._make_skeleton_class', (type_constructor, name, bases, type_kwargs, class_tracker_id /*, extra */) => {
  4642. // https://github.com/ray-project/ray/blob/5cd8967f1c0c16d3ae5fedb8449d0d25dd4f9f3e/python/ray/cloudpickle/cloudpickle.py#L523
  4643. const kwds = { 'metaclass': type_constructor };
  4644. const skeleton_class = types.new_class(name, bases, kwds, (ns) => ns.update(type_kwargs));
  4645. return cloudpickle.cloudpickle._lookup_class_or_track(class_tracker_id, skeleton_class);
  4646. });
  4647. this.registerFunction('cloudpickle.cloudpickle._make_empty_cell', () => {
  4648. return new builtins.cell();
  4649. });
  4650. this.registerFunction('cloudpickle.cloudpickle._class_setstate', (obj, state) => {
  4651. [state] = state;
  4652. let registry = null;
  4653. for (const [attrname, attr] of state.items()) {
  4654. if (attrname === '_abc_impl') {
  4655. registry = attr;
  4656. } else {
  4657. builtins.setattr(obj, attrname, attr);
  4658. }
  4659. }
  4660. if (sys.version_info >= (3, 13) && state.__contains__('__firstlineno__')) {
  4661. obj.__firstlineno__ = state.get('__firstlineno__');
  4662. }
  4663. if (registry) {
  4664. for (const subclass of registry) {
  4665. obj.register(subclass);
  4666. }
  4667. }
  4668. return obj;
  4669. });
  4670. this.registerFunction('cloudpickle.cloudpickle._function_setstate', (obj, state) => {
  4671. const [, slotstate] = state;
  4672. [state] = state;
  4673. // obj.__dict__.update(state)
  4674. /* const obj_globals = */ slotstate.pop('__globals__');
  4675. const obj_closure = slotstate.pop('__closure__');
  4676. slotstate.pop('_cloudpickle_submodules');
  4677. if (obj.__globals__) {
  4678. // obj.__globals__.update(obj_globals);
  4679. // obj.__globals__.__builtins__ = __builtins__;
  4680. }
  4681. if (obj_closure) {
  4682. // let value = null;
  4683. for (let i = 0; i < obj_closure.length; i++) {
  4684. // const cell = obj_closure[i];
  4685. try {
  4686. // value = cell.cell_contents;
  4687. } catch {
  4688. // cell is empty
  4689. }
  4690. // obj.__closure__[i].cell_contents = value;
  4691. }
  4692. }
  4693. for (const [k, v] of slotstate.items()) {
  4694. builtins.setattr(obj, k, v);
  4695. }
  4696. });
  4697. this.registerFunction('cloudpickle.cloudpickle.subimport', (name) => {
  4698. execution.__import__(name);
  4699. return sys.modules.get(name);
  4700. });
  4701. this.registerFunction('cloudpickle.cloudpickle_fast._class_setstate');
  4702. this.registerFunction('cloudpickle.cloudpickle_fast._function_setstate');
  4703. const ray = this.register('ray');
  4704. this.register('ray.cloudpickle.cloudpickle');
  4705. this.register('ray.cloudpickle.cloudpickle_fast');
  4706. ray.cloudpickle.cloudpickle._builtin_type = cloudpickle.cloudpickle._builtin_type;
  4707. ray.cloudpickle.cloudpickle._fill_function = cloudpickle.cloudpickle._fill_function;
  4708. ray.cloudpickle.cloudpickle._make_cell = cloudpickle.cloudpickle._make_cell;
  4709. ray.cloudpickle.cloudpickle._make_function = cloudpickle.cloudpickle._make_function;
  4710. ray.cloudpickle.cloudpickle._make_skel_func = cloudpickle.cloudpickle._make_skel_func;
  4711. ray.cloudpickle.cloudpickle._make_skeleton_class = cloudpickle.cloudpickle._make_skeleton_class;
  4712. ray.cloudpickle.cloudpickle._make_empty_cell = cloudpickle.cloudpickle._make_empty_cell;
  4713. ray.cloudpickle.cloudpickle._empty_cell_value = cloudpickle.cloudpickle._empty_cell_value;
  4714. ray.cloudpickle.cloudpickle._class_setstate = cloudpickle.cloudpickle._class_setstate;
  4715. ray.cloudpickle.cloudpickle._function_setstate = cloudpickle.cloudpickle._function_setstate;
  4716. ray.cloudpickle.cloudpickle._lookup_class_or_track = cloudpickle.cloudpickle._lookup_class_or_track;
  4717. ray.cloudpickle.cloudpickle_fast._class_setstate = cloudpickle.cloudpickle._class_setstate;
  4718. ray.cloudpickle.cloudpickle_fast._function_setstate = cloudpickle.cloudpickle._function_setstate;
  4719. this.registerType('ray.rllib.algorithms.ppo.ppo.PPO', class {});
  4720. this.registerType('ray.rllib.algorithms.ppo.ppo.PPOConfig', class {});
  4721. this.registerType('ray.rllib.algorithms.algorithm_config.AlgorithmConfig', class {});
  4722. this.registerFunction('ray.rllib.algorithms.algorithm_config.AlgorithmConfig.DEFAULT_POLICY_MAPPING_FN');
  4723. this.registerType('ray.rllib.algorithms.algorithm_config.TorchCompileWhatToCompile', class {});
  4724. this.registerType('ray.rllib.evaluation.collectors.simple_list_collector.SimpleListCollector', class {});
  4725. this.registerType('ray.rllib.callbacks.callbacks.RLlibCallback', class {});
  4726. this.registerType('ray.rllib.core.learner.learner.TorchCompileWhatToCompile', class {});
  4727. this.registerType('ray.rllib.policy.policy.PolicySpec', class {});
  4728. this.registerType('ray.rllib.policy.sample_batch.SampleBatch', class {});
  4729. this.registerType('ray.rllib.utils.metrics.stats.mean.MeanStats', class {});
  4730. this.registerType('ray.rllib.utils.metrics.stats.ema.EmaStats', class {});
  4731. this.registerType('ray.rllib.utils.metrics.stats.min.MinStats', class {});
  4732. this.registerType('ray.rllib.utils.metrics.stats.max.MaxStats', class {});
  4733. this.registerType('ray.rllib.utils.metrics.stats.sum.SumStats', class {});
  4734. this.registerType('ray.rllib.utils.metrics.stats.lifetime_sum.LifetimeSumStats', class {});
  4735. this.registerType('ray.rllib.utils.metrics.stats.percentiles.PercentilesStats', class {});
  4736. this.registerType('ray.rllib.utils.metrics.stats.item.ItemStats', class {});
  4737. this.registerType('ray.rllib.utils.metrics.stats.item_series.ItemSeriesStats', class {});
  4738. this.registerType('collections.Counter', class {});
  4739. this.registerFunction('collections.defaultdict', (/* default_factory */) => {
  4740. return {};
  4741. });
  4742. this.registerFunction('copy.deepcopy');
  4743. this.registerFunction('copy_reg._reconstructor', (cls, base, state) => {
  4744. // copyreg._reconstructor in Python 3
  4745. if (base === '__builtin__.object' || base === builtins.object) {
  4746. return self.invoke(cls, []);
  4747. } else if (base === '__builtin__.tuple' || base === builtins.tuple) {
  4748. const obj = self.invoke(cls, []);
  4749. for (let i = 0; i < state.length; i++) {
  4750. obj[i] = state[i];
  4751. }
  4752. return obj;
  4753. }
  4754. throw new python.Error(`Unsupported copy_reg._reconstructor base type '${base}'.`);
  4755. });
  4756. this.registerFunction('copy.deepcopy', (/* x */) => {
  4757. throw new python.Error('Unsupported copy.deepcopy().');
  4758. });
  4759. this.registerFunction('dill._dill._create_array', (f, args, state, npdict) => {
  4760. const array = f(...args);
  4761. if (array.__setstate__) {
  4762. array.__setstate__(state);
  4763. }
  4764. if (npdict) {
  4765. throw new python.Error("'dill._dill._create_array::npdict' not implemented.");
  4766. }
  4767. return array;
  4768. });
  4769. this.registerFunction('dill._dill._create_cell', (/* args */) => {
  4770. return function() {
  4771. };
  4772. });
  4773. this.registerFunction('dill._dill._create_code', (args) => {
  4774. return self.invoke('types.CodeType', [args]);
  4775. });
  4776. this.registerFunction('dill._dill._create_function', (/* fcode, fglobals, fname, fdefaults, fclosure, fdict, fkwdefaults */) => {
  4777. return function() {
  4778. };
  4779. });
  4780. this.registerFunction('dill._dill._create_namedtuple', (name, fieldnames, modulename /*, defaults */) => {
  4781. const obj = execution.invoke('dill._dill._import_module', [`${modulename}.${name}`]);
  4782. if (obj) {
  4783. return obj;
  4784. }
  4785. return undefined;
  4786. });
  4787. this.registerFunction('dill._dill._create_type', (typeobj, ...args) => {
  4788. const [name, bases, dict] = args;
  4789. const type = class extends bases[0] {};
  4790. const identifier = dict.__contains__('__module__') ? `${dict.__getitem__('__module__')}.${name}` : name;
  4791. return self.registerType(identifier, Object.assign(type, dict));
  4792. });
  4793. this.registerFunction('dill._dill._eval_repr');
  4794. this.registerFunction('dill._dill._get_attr', (self, name) => {
  4795. if (Object.prototype.hasOwnProperty.call(self, name)) {
  4796. return self[name];
  4797. }
  4798. return undefined;
  4799. });
  4800. this.registerFunction('dill._dill._import_module', (import_name, safe) => {
  4801. try {
  4802. if (import_name.startsWith('__runtime__.')) {
  4803. return execution.module(import_name);
  4804. } else if (import_name.indexOf('.') === -1) {
  4805. return execution.__import__(import_name);
  4806. }
  4807. return execution.resolve(import_name);
  4808. } catch (error) {
  4809. if (safe) {
  4810. return null;
  4811. }
  4812. throw error;
  4813. }
  4814. });
  4815. this.registerFunction('dill._dill._load_type', (name) => {
  4816. const _dill = self.register('dill._dill');
  4817. if (!_dill._reverse_typemap) {
  4818. _dill._reverse_typemap = new Map();
  4819. for (const name of ['__builtin__', 'types']) {
  4820. const module = self.register(name);
  4821. for (const [name, obj] of Object.entries(module)) {
  4822. if (obj.__module__ === 'builtins' && obj.__class__ === builtins.type) {
  4823. _dill._reverse_typemap.set(name, obj);
  4824. }
  4825. }
  4826. }
  4827. _dill._reverse_typemap.set('PartialType', functools.partial);
  4828. _dill._reverse_typemap.set('CellType', builtins.cell);
  4829. }
  4830. if (!_dill._reverse_typemap.has(name)) {
  4831. throw new python.Error(`Unknown type name '${name}' in 'dill._dill._load_type'.`);
  4832. }
  4833. return _dill._reverse_typemap.get(name);
  4834. });
  4835. this.registerFunction('dill._dill.loads');
  4836. this.registerFunction('jax._src.array._reconstruct_array', (fun, args, arr_state, aval_state) => {
  4837. const np_value = fun(...args);
  4838. np_value.__setstate__(arr_state);
  4839. const jnp_value = jax.device_put(np_value);
  4840. jnp_value.aval = jnp_value.aval.update(aval_state);
  4841. return jnp_value;
  4842. });
  4843. jax._src.device_array.reconstruct_device_array = jax._src.array._reconstruct_array;
  4844. this.registerFunction('jax.device_put', (x) => {
  4845. const aval = new jax._src.core.ShapedArray(x.shape, x.dtype);
  4846. return new jax.Array(aval, x.data);
  4847. });
  4848. this.registerType('jax._src.core.AbstractValue', class {});
  4849. this.registerType('jax._src.core.UnshapedArray', class extends jax._src.core.AbstractValue {});
  4850. this.registerType('jax._src.core.ShapedArray', class extends jax._src.core.UnshapedArray {
  4851. constructor(shape, dtype, weak_type) {
  4852. super();
  4853. this.shape = shape;
  4854. this.dtype = dtype;
  4855. this.weak_type = weak_type || false;
  4856. }
  4857. update(dict) {
  4858. const shape = dict.get('shape') || this.shape;
  4859. const dtype = dict.get('dtype') || this.dtype;
  4860. const weak_type = dict.get('weak_type') || this.weak_type;
  4861. return new jax._src.core.ShapedArray(shape, dtype, weak_type);
  4862. }
  4863. });
  4864. this.registerType('jax.Array', class {
  4865. constructor(aval, data) {
  4866. this.aval = aval;
  4867. this.data = data;
  4868. }
  4869. get dtype() {
  4870. return this.aval.dtype;
  4871. }
  4872. get shape() {
  4873. return this.aval.shape;
  4874. }
  4875. tobytes() {
  4876. return this.data;
  4877. }
  4878. });
  4879. jax.numpy.ndarray = jax.Array;
  4880. this.registerFunction('keras.saving.pickle_utils.deserialize_model_from_bytecode', (/* serialized_model */) => {
  4881. return null; // throw new python.Error("'keras.saving.pickle_utils.deserialize_model_from_bytecode' not implemented.");
  4882. });
  4883. this.registerFunction('keras.src.saving.pickle_utils.deserialize_model_from_bytecode', keras.saving.pickle_utils.deserialize_model_from_bytecode);
  4884. this.registerFunction('lasagne.nonlinearities.rectify');
  4885. this.registerFunction('lasagne.nonlinearities.softmax');
  4886. this.registerFunction('lasagne.objectives.categorical_crossentropy');
  4887. this.registerFunction('lasagne.updates.nesterov_momentum');
  4888. this.registerFunction('msgpack.unpackb', (packed, ext_hook) => {
  4889. const BinaryReader = class {
  4890. constructor(buffer, ext_hook) {
  4891. // https://github.com/msgpack/msgpack-javascript/blob/master/src/Decoder.ts
  4892. // https://github.com/msgpack/msgpack-python/blob/main/msgpack/_unpacker.pyx
  4893. this._buffer = buffer;
  4894. this._position = 0;
  4895. this._view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  4896. this._ext_hook = ext_hook;
  4897. }
  4898. value() {
  4899. const c = this._view.getUint8(this.skip(1));
  4900. if (c >= 0xe0) {
  4901. return c - 0x100;
  4902. }
  4903. if (c < 0xC0) {
  4904. if (c < 0x80) {
  4905. return c;
  4906. }
  4907. if (c < 0x90) {
  4908. return this.map(c - 0x80);
  4909. }
  4910. if (c < 0xa0) {
  4911. return this.array(c - 0x90);
  4912. }
  4913. return this.string(c - 0xa0);
  4914. }
  4915. switch (c) {
  4916. case 0xC0: return null;
  4917. case 0xC2: return false;
  4918. case 0xC3: return true;
  4919. case 0xC4: return this.read(this._view.getUint8(this.skip(1)));
  4920. case 0xC5: return this.read(this._view.getUint16(this.skip(2)));
  4921. case 0xC6: return this.read(this._view.getUint32(this.skip(4)));
  4922. case 0xC7: return this.extension(this._view.getUint8(this.skip(1)));
  4923. case 0xC8: return this.extension(this._view.getUint16(this.skip(2)));
  4924. case 0xC9: return this.extension(this._view.getUint32(this.skip(4)));
  4925. case 0xCA: return this._view.getFloat32(this.skip(4));
  4926. case 0xCB: return this._view.getFloat64(this.skip(8));
  4927. case 0xCC: return this._view.getUint8(this.skip(1));
  4928. case 0xCD: return this._view.getUint16(this.skip(2));
  4929. case 0xCE: return this._view.getUint32(this.skip(4));
  4930. case 0xCF: return this._view.getBitUint64(this.skip(8));
  4931. case 0xD0: return this._view.getInt8(this.skip(1));
  4932. case 0xD1: return this._view.getInt16(this.skip(2));
  4933. case 0xD2: return this._view.getInt32(this.skip(4));
  4934. case 0xD3: return this._view.getBigInt64(this.skip(8));
  4935. case 0xD4: return this.extension(1);
  4936. case 0xD5: return this.extension(2);
  4937. case 0xD6: return this.extension(4);
  4938. case 0xD7: return this.extension(8);
  4939. case 0xD8: return this.extension(16);
  4940. case 0xD9: return this.string(this._view.getUint8(this.skip(1)));
  4941. case 0xDA: return this.string(this._view.getUint16(this.skip(2)));
  4942. case 0xDB: return this.string(this._view.getUint32(this.skip(4)));
  4943. case 0xDC: return this.array(this._view.getUint16(this.skip(2)));
  4944. case 0xDD: return this.array(this._view.getUint32(this.skip(4)));
  4945. case 0xDE: return this.map(this._view.getUint16(this.skip(2)));
  4946. case 0xDF: return this.map(this._view.getUint32(this.skip(4)));
  4947. default: throw new python.Error(`Invalid code '${c}'.`);
  4948. }
  4949. }
  4950. map(size) {
  4951. const map = {};
  4952. for (let i = 0; i < size; i++) {
  4953. const key = this.value();
  4954. const value = this.value();
  4955. map[key] = value;
  4956. }
  4957. return map;
  4958. }
  4959. array(size) {
  4960. const array = new Array(size);
  4961. for (let i = 0; i < size; i++) {
  4962. array[i] = this.value();
  4963. }
  4964. return array;
  4965. }
  4966. extension(size) {
  4967. const code = this._view.getUint8(this.skip(1));
  4968. const data = this.read(size);
  4969. return this._ext_hook(code, data);
  4970. }
  4971. skip(offset) {
  4972. const position = this._position;
  4973. this._position += offset;
  4974. if (this._position > this._buffer.length) {
  4975. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  4976. }
  4977. return position;
  4978. }
  4979. read(size) {
  4980. const data = this._buffer.subarray(this._position, this._position + size);
  4981. this._position += size;
  4982. return data;
  4983. }
  4984. string(size) {
  4985. const buffer = this.read(size);
  4986. this._decoder = this._decoder || new TextDecoder('utf8');
  4987. return this._decoder.decode(buffer);
  4988. }
  4989. };
  4990. return new BinaryReader(packed, ext_hook).value();
  4991. });
  4992. this.registerFunction('nolearn.lasagne.base.objective');
  4993. this.registerFunction('numpy.core._DType_reconstruct');
  4994. this.registerFunction('numpy.core._ufunc_reconstruct');
  4995. this.registerFunction('numpy.core.multiarray._reconstruct', (subtype, shape, dtype) => {
  4996. return numpy.ndarray.__new__(subtype, shape, dtype);
  4997. });
  4998. this.registerFunction('numpy.core.multiarray.frombuffer', (buf, dtype) => {
  4999. const shape = [buf.length / dtype.itemsize];
  5000. return new numpy.ndarray(shape, dtype, buf);
  5001. });
  5002. this.registerFunction('numpy._core.numeric._frombuffer', (buf, dtype, shape, order) => {
  5003. return numpy._core.multiarray.frombuffer(buf, dtype).reshape(shape, order);
  5004. });
  5005. this.registerFunction('numpy._core._internal._convert_to_stringdtype_kwargs', () => {
  5006. return new numpy.dtypes.StringDType();
  5007. });
  5008. this.registerFunction('numpy.core.multiarray.scalar', (dtype, rawData) => {
  5009. let data = rawData;
  5010. if (typeof rawData === 'string' || rawData instanceof String) {
  5011. data = new Uint8Array(rawData.length);
  5012. for (let i = 0; i < rawData.length; i++) {
  5013. data[i] = rawData.charCodeAt(i);
  5014. }
  5015. }
  5016. switch (dtype.kind) {
  5017. case 'b': {
  5018. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5019. switch (dtype.itemsize) {
  5020. case 1: return view.getInt8(0) ? true : false;
  5021. default: throw new python.Error(`Unsupported scalar dtype boolean itemsize '${dtype.itemsize}'.`);
  5022. }
  5023. }
  5024. case 'f': {
  5025. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5026. switch (dtype.itemsize) {
  5027. case 2: return view.getFloat16(0, dtype.byteorder === '<');
  5028. case 4: return view.getFloat32(0, dtype.byteorder === '<');
  5029. case 8: return view.getFloat64(0, dtype.byteorder === '<');
  5030. default: throw new python.Error(`Unsupported scalar dtype float itemsize '${dtype.itemsize}'.`);
  5031. }
  5032. }
  5033. case 'i': {
  5034. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5035. switch (dtype.itemsize) {
  5036. case 1: return view.getInt8(0);
  5037. case 2: return view.getInt16(0, dtype.byteorder === '<');
  5038. case 4: return view.getInt32(0, dtype.byteorder === '<');
  5039. case 8: return view.getBigInt64(0, dtype.byteorder === '<');
  5040. default: throw new python.Error(`Unsupported scalar dtype int itemsize '${dtype.itemsize}'.`);
  5041. }
  5042. }
  5043. case 'u': {
  5044. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5045. switch (dtype.itemsize) {
  5046. case 1: return view.getUint8(0);
  5047. case 2: return view.getUint16(0, dtype.byteorder === '<');
  5048. case 4: return view.getUint32(0, dtype.byteorder === '<');
  5049. case 8: return view.getBigUint64(0, dtype.byteorder === '<');
  5050. default: throw new python.Error(`Unsupported scalar dtype uint itemsize '${dtype.itemsize}'.`);
  5051. }
  5052. }
  5053. case 'U': {
  5054. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5055. const list = [];
  5056. for (let i = 0; i < dtype.itemsize; i += 4) {
  5057. list.push(String.fromCodePoint(view.getUint32(i, true)));
  5058. }
  5059. return list.join('');
  5060. }
  5061. default: {
  5062. throw new python.Error(`Unsupported scalar dtype kind '${dtype.kind}'.`);
  5063. }
  5064. }
  5065. });
  5066. this.registerFunction('numpy.core._multiarray_umath.cbrt');
  5067. this.registerFunction('numpy.core._multiarray_umath.fmin');
  5068. this.registerFunction('numpy.core._multiarray_umath.fmax');
  5069. this.registerFunction('numpy.core._multiarray_umath.greater');
  5070. this.registerFunction('numpy.core._multiarray_umath.less');
  5071. this.registerFunction('numpy.core._multiarray_umath.log');
  5072. this.registerFunction('numpy.core._multiarray_umath.scalar', (dtype, rawData) => {
  5073. let data = rawData;
  5074. if (typeof rawData === 'string') {
  5075. data = new Uint8Array(rawData.length);
  5076. for (let i = 0; i < rawData.length; i++) {
  5077. data[i] = rawData.charCodeAt(i);
  5078. }
  5079. }
  5080. const dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5081. switch (dtype.__name__) {
  5082. case 'uint8':
  5083. return dataView.getUint8(0);
  5084. case 'float32':
  5085. return dataView.getFloat32(0, true);
  5086. case 'float64':
  5087. return dataView.getFloat64(0, true);
  5088. case 'int8':
  5089. return dataView.getInt8(0, true);
  5090. case 'int16':
  5091. return dataView.getInt16(0, true);
  5092. case 'int32':
  5093. return dataView.getInt32(0, true);
  5094. case 'int64':
  5095. return dataView.getBigInt64(0, true);
  5096. default:
  5097. throw new python.Error(`Unsupported scalar type '${dtype.__name__}'.`);
  5098. }
  5099. });
  5100. this.registerFunction('numpy.core._multiarray_umath.sin');
  5101. this.registerFunction('numpy.core._multiarray_umath.sqrt');
  5102. this.register('numpy._core.multiarray', numpy.core.multiarray);
  5103. this.register('numpy._core._multiarray_umath', numpy.core._multiarray_umath);
  5104. this.register('numpy._core._multiarray_umath', numpy.core._multiarray_umath);
  5105. this.register('numpy.core.numeric', numpy._core.numeric);
  5106. numpy._core._multiarray_umath._reconstruct = numpy.core.multiarray._reconstruct;
  5107. this.registerFunction('numpy.load', (file) => {
  5108. // https://github.com/numpy/numpy/blob/main/numpy/lib/_format_impl.py
  5109. const signature = [0x93, 0x4E, 0x55, 0x4D, 0x50, 0x59];
  5110. if (!file.read(6).every((v, i) => v === signature[i])) {
  5111. throw new python.Error('Invalid signature.');
  5112. }
  5113. const version = file.read(2);
  5114. const [major, minor] = version;
  5115. if (major > 3) {
  5116. throw new python.Error(`Invalid version '${[major, minor].join('.')}'.`);
  5117. }
  5118. const [shape, fortran_order, dtype] = numpy.lib._format_impl._read_array_header(file, version);
  5119. let data = null;
  5120. switch (dtype.byteorder) {
  5121. case '|': {
  5122. data = file.read();
  5123. if (dtype.kind === 'O') {
  5124. const unpickler = new pickle.Unpickler(data);
  5125. return unpickler.load();
  5126. }
  5127. break;
  5128. }
  5129. case '>':
  5130. case '<': {
  5131. const count = shape.length === 0 ? 1 : shape.reduce((a, b) => a * b, 1);
  5132. const stream = file.getbuffer().nbytes > 0x1000000;
  5133. data = file.read(dtype.itemsize * count, stream);
  5134. break;
  5135. }
  5136. default: {
  5137. throw new python.Error(`Unsupported data type '${dtype.str}'.`);
  5138. }
  5139. }
  5140. if (fortran_order) {
  5141. data = null;
  5142. }
  5143. return self.invoke('numpy.ndarray', [shape, dtype, data]);
  5144. });
  5145. this.registerFunction('numpy.save', (file, arr) => {
  5146. const descr = arr.dtype.str;
  5147. if (descr[0] !== '<' && descr[0] !== '>') {
  5148. throw new python.Error(`Unsupported byte order '${descr}'.`);
  5149. }
  5150. if ((descr.length !== 3 && descr.substring(1) !== 'c16') || (descr[1] !== 'f' && descr[1] !== 'i' && descr[1] !== 'u' && descr[1] !== 'c' && descr.substring(1) !== 'b1')) {
  5151. throw new python.Error(`Unsupported data type '${descr}'.`);
  5152. }
  5153. let shape = '';
  5154. switch (arr.shape.length) {
  5155. case 0: shape = '()'; break;
  5156. case 1: shape = `(${arr.shape[0]},)`; break;
  5157. default: shape = `(${arr.shape.map((dimension) => dimension.toString()).join(', ')})`; break;
  5158. }
  5159. const properties = [
  5160. `'descr': '${descr}'`,
  5161. "'fortran_order': False",
  5162. `'shape': ${shape}`
  5163. ];
  5164. let header = `{ ${properties.join(', ')} }`;
  5165. header += `${' '.repeat(64 - ((header.length + 2 + 8 + 1) & 0x3f))}\n`;
  5166. const encoder = new TextEncoder('ascii');
  5167. file.write([0x93, 0x4E, 0x55, 0x4D, 0x50, 0x59, 0x01, 0x00]); // '\\x93NUMPY' + version
  5168. file.write([header.length & 0xff, (header.length >> 8) & 0xff]);
  5169. file.write(encoder.encode(header));
  5170. file.write(arr.tobytes());
  5171. });
  5172. this.registerFunction('numpy.lib._format_impl._read_array_header', (file, version) => {
  5173. const buffer = new Uint8Array([0, 0, 0, 0]);
  5174. const [major] = version;
  5175. buffer.set(file.read(major >= 2 ? 4 : 2), 0);
  5176. const header_length = buffer[3] << 24 | buffer[2] << 16 | buffer[1] << 8 | buffer[0];
  5177. let header = file.read(header_length);
  5178. const decoder = new TextDecoder(major >= 3 ? 'utf-8' : 'ascii');
  5179. header = decoder.decode(header).trim();
  5180. try {
  5181. header = ast.literal_eval(header);
  5182. } catch {
  5183. if (major <= 2) {
  5184. header = numpy.lib._format_impl._filter_header(header);
  5185. header = ast.literal_eval(header);
  5186. }
  5187. }
  5188. if (header.descr === undefined) {
  5189. throw new python.Error("Invalid 'descr'.");
  5190. }
  5191. if (!Array.isArray(header.shape)) {
  5192. throw new python.Error("Invalid 'shape'.");
  5193. }
  5194. const dtype = numpy.lib._format_impl.descr_to_dtype(header.descr);
  5195. return [header.shape, header.fortran_order, dtype];
  5196. });
  5197. this.registerFunction('numpy.lib._format_impl.descr_to_dtype', (descr) => {
  5198. if (typeof descr === 'string') {
  5199. return new numpy.dtype(descr);
  5200. } else if (descr instanceof builtins.tuple) {
  5201. const dt = numpy.lib._format_impl.descr_to_dtype(descr[0]);
  5202. return new numpy.dtype([dt, descr[1]]);
  5203. }
  5204. const titles = [];
  5205. const names = [];
  5206. const formats = [];
  5207. const offsets = [];
  5208. let offset = 0;
  5209. for (const field of descr) {
  5210. let name = null;
  5211. let dt = null;
  5212. let descr_str = null;
  5213. let shape = null;
  5214. let title = null;
  5215. if (field.length === 2) {
  5216. [name, descr_str] = field;
  5217. dt = numpy.lib._format_impl.descr_to_dtype(descr_str);
  5218. } else {
  5219. [name, descr_str, shape] = field;
  5220. dt = new numpy.dtype([numpy.lib._format_impl.descr_to_dtype(descr_str), shape]);
  5221. }
  5222. const is_pad = name === '' && dt.type === numpy.void && dt.names === null;
  5223. if (!is_pad) {
  5224. [title, name] = name instanceof builtins.tuple ? name : [null, name];
  5225. titles.push(title);
  5226. names.push(name);
  5227. formats.push(dt);
  5228. offsets.push(offset);
  5229. }
  5230. offset += dt.itemsize;
  5231. }
  5232. return new numpy.dtype({ names, formats, titles, offsets, itemsize: offset });
  5233. });
  5234. this.registerFunction('numpy.lib._format_impl._filter_header', (s) => {
  5235. const tokens = [];
  5236. const tokenizer = new ast._Tokenizer(s, '');
  5237. while (!tokenizer.match('eof')) {
  5238. const token = tokenizer.read();
  5239. if (token.type === 'int') {
  5240. const next = tokenizer.peek();
  5241. if (next.type === 'id' && next.value === 'L') {
  5242. tokenizer.read();
  5243. }
  5244. }
  5245. tokens.push(token.value);
  5246. }
  5247. return tokens.join('');
  5248. });
  5249. this.registerFunction('numpy.amin');
  5250. this.registerFunction('numpy.amax');
  5251. this.registerFunction('numpy.std');
  5252. this.registerFunction('numpy.asarray', (a, dtype) => {
  5253. const encode = (context, data, dim) => {
  5254. const size = context.shape[dim];
  5255. const littleendian = context.littleendian;
  5256. if (dim === context.shape.length - 1) {
  5257. for (let i = 0; i < size; i++) {
  5258. switch (context.dtype) {
  5259. case 'f2':
  5260. context.view.setFloat16(context.position, data[i], littleendian);
  5261. break;
  5262. case 'f4':
  5263. context.view.setFloat32(context.position, data[i], littleendian);
  5264. break;
  5265. case 'f8':
  5266. context.view.setFloat64(context.position, data[i], littleendian);
  5267. break;
  5268. case 'i1':
  5269. context.view.setInt8(context.position, data[i], littleendian);
  5270. break;
  5271. case 'i2':
  5272. context.view.setInt16(context.position, data[i], littleendian);
  5273. break;
  5274. case 'i4':
  5275. context.view.setInt32(context.position, data[i], littleendian);
  5276. break;
  5277. case 'i8':
  5278. context.view.setBigInt64(context.position, typeof data[i] === 'number' ? BigInt(data[i]) : data[i], littleendian);
  5279. break;
  5280. case 'u1':
  5281. context.view.setUint8(context.position, data[i], littleendian);
  5282. break;
  5283. case 'u2':
  5284. context.view.setUint16(context.position, data[i], littleendian);
  5285. break;
  5286. case 'u4':
  5287. context.view.setUint32(context.position, data[i], littleendian);
  5288. break;
  5289. case 'u8':
  5290. context.view.setComplexFloat16(context.position, data[i], littleendian);
  5291. break;
  5292. case 'c8':
  5293. context.view.setComplexFloat32(context.position, data[i], littleendian);
  5294. break;
  5295. case 'c16':
  5296. context.view.setComplexFloat64(context.position, data[i], littleendian);
  5297. break;
  5298. case 'b1':
  5299. context.view.setInt8(context.position, data[i] ? 1 : 0);
  5300. break;
  5301. default:
  5302. throw new python.Error(`Unsupported tensor data type '${context.dtype}'.`);
  5303. }
  5304. context.position += context.itemsize;
  5305. }
  5306. } else {
  5307. for (let j = 0; j < size; j++) {
  5308. encode(context, data[j], dim + 1);
  5309. }
  5310. }
  5311. };
  5312. const array_size = (value) => {
  5313. if (value.every((item) => Array.isArray(item))) {
  5314. const dims = value.map((item) => array_size(item));
  5315. const [dim] = dims;
  5316. for (let i = 1; i < dims.length; i++) {
  5317. if (dim.length === dims[i].length) {
  5318. if (!dims[i].every((value, i) => value === dim[i])) {
  5319. throw new python.Error('Invalid array shape.');
  5320. }
  5321. }
  5322. }
  5323. return [value.length].concat(dim);
  5324. }
  5325. return [value.length];
  5326. };
  5327. const shape = Array.isArray(a) ? array_size(a) : [];
  5328. const size = dtype.itemsize * shape.reduce((a, b) => a * b, 1);
  5329. const context = {
  5330. position: 0,
  5331. itemsize: dtype.itemsize,
  5332. dtype: dtype.str.substring(1),
  5333. littleendian: dtype.str[0],
  5334. shape,
  5335. data: new Uint8Array(size)
  5336. };
  5337. context.view = new DataView(context.data.buffer, context.data.byteOffset, size);
  5338. encode(context, a, 0);
  5339. return self.invoke('numpy.ndarray', [shape, dtype, context.data]);
  5340. });
  5341. this.registerFunction('numpy.max');
  5342. this.registerFunction('numpy.mean');
  5343. this.registerFunction('numpy.min');
  5344. this.registerFunction('numpy.ma.core._mareconstruct', (subtype, baseclass, baseshape, basetype) => {
  5345. const data = self.invoke(baseclass, [baseshape, basetype]);
  5346. // = ndarray.__new__(ndarray, baseshape, make_mask_descr(basetype))
  5347. const mask = self.invoke('numpy.ndarray', [baseshape, '']);
  5348. return self.invoke(subtype, [data, mask, basetype]);
  5349. });
  5350. this.registerFunction('numpy.random.__RandomState_ctor', () => {
  5351. return {};
  5352. });
  5353. this.registerFunction('numpy.random._pickle.__randomstate_ctor', () => {
  5354. return {};
  5355. });
  5356. this.registerType('numpy.random.bit_generator.BitGenerator', class {
  5357. __setstate__(state) {
  5358. if (state instanceof Map || !Array.isArray(state)) {
  5359. this.state = state;
  5360. } else {
  5361. [this.state, this._seed_seq] = state;
  5362. }
  5363. }
  5364. });
  5365. this.registerType('numpy.random.bit_generator.SeedSequence', class extends builtins.object {
  5366. __setstate__(state) {
  5367. [this.entropy, this.n_children_spawned, this.pool, this.pool_size, this.spawn_key] = state;
  5368. }
  5369. });
  5370. this.registerFunction('numpy.random.bit_generator.__pyx_unpickle_SeedSequence', (cls, checksum, state) => {
  5371. const obj = new cls();
  5372. if (state) {
  5373. obj.__setstate__(state);
  5374. }
  5375. return obj;
  5376. });
  5377. this.registerType('numpy.random._mt19937.MT19937', class extends numpy.random.bit_generator.BitGenerator {});
  5378. this.registerType('numpy.random._pcg64.PCG64', class extends numpy.random.bit_generator.BitGenerator {});
  5379. this.registerType('numpy.random._pcg64.PCG64DXSM', class extends numpy.random.bit_generator.BitGenerator {});
  5380. this.registerType('numpy.random._philox.Philox', class extends numpy.random.bit_generator.BitGenerator {});
  5381. this.registerType('numpy.random._sfc64.SFC64', class extends numpy.random.bit_generator.BitGenerator {});
  5382. numpy.random._pickle.BitGenerators = {
  5383. 'MT19937': numpy.random._mt19937.MT19937,
  5384. 'PCG64': numpy.random._pcg64.PCG64,
  5385. 'PCG64DXSM': numpy.random._pcg64.PCG64DXSM,
  5386. 'Philox': numpy.random._philox.Philox,
  5387. 'SFC64': numpy.random._sfc64.SFC64,
  5388. };
  5389. this.registerType('numpy.random._generator.Generator', class {
  5390. constructor(bit_generator) {
  5391. this.bit_generator = bit_generator;
  5392. }
  5393. });
  5394. this.registerFunction('numpy.random._pickle.__bit_generator_ctor', (bit_generator) => {
  5395. bit_generator = bit_generator || 'MT19937';
  5396. let bit_gen_class = null;
  5397. if (builtins.isinstance(bit_generator, builtins.type)) {
  5398. bit_gen_class = bit_generator;
  5399. } else {
  5400. bit_gen_class = numpy.random._pickle.BitGenerators[bit_generator];
  5401. }
  5402. if (bit_gen_class) {
  5403. return new bit_gen_class();
  5404. }
  5405. throw new python.Error(`Unknown bit generator '${bit_generator}'.`);
  5406. });
  5407. this.registerFunction('numpy.random._pickle.__generator_ctor', (bit_generator_name, bit_generator_ctor) => {
  5408. if (bit_generator_name instanceof numpy.random.bit_generator.BitGenerator) {
  5409. return new numpy.random._generator.Generator(bit_generator_name);
  5410. }
  5411. bit_generator_ctor = bit_generator_ctor || numpy.random._pickle.__bit_generator_ctor;
  5412. return new numpy.random._generator.Generator(bit_generator_ctor(bit_generator_name));
  5413. });
  5414. this.registerFunction('numpy.reshape');
  5415. this.registerFunction('sklearn.feature_selection._univariate_selection.f_classif');
  5416. this.registerFunction('sklearn.feature_selection._univariate_selection.f_regression');
  5417. this.registerFunction('sklearn.metrics.scorer._passthrough_scorer');
  5418. this.registerFunction('sklearn.metrics._classification.accuracy_score');
  5419. this.registerFunction('sklearn.metrics._classification.balanced_accuracy_score');
  5420. this.registerFunction('sklearn.metrics._classification.cohen_kappa_score');
  5421. this.registerFunction('sklearn.metrics._classification.f1_score');
  5422. this.registerFunction('sklearn.metrics._classification.log_loss');
  5423. this.registerFunction('sklearn.metrics._classification.precision_score');
  5424. this.registerFunction('sklearn.metrics._classification.recall_score');
  5425. this.registerFunction('sklearn.metrics._dist_metrics.newObj', (obj) => {
  5426. return obj.__new__(obj);
  5427. });
  5428. this.registerFunction('sklearn.metrics._ranking.roc_auc_score');
  5429. this.registerFunction('sklearn.metrics._regression.mean_absolute_error');
  5430. this.registerFunction('sklearn.metrics._regression.mean_absolute_percentage_error');
  5431. this.registerFunction('sklearn.metrics._regression.mean_squared_error');
  5432. this.registerFunction('sklearn.metrics._regression.r2_score');
  5433. sklearn.metrics.regression = sklearn.metrics._regression;
  5434. sklearn.metrics.r2_score = sklearn.metrics._regression.r2_score;
  5435. this.registerFunction('sklearn.metrics._regression.root_mean_squared_error');
  5436. this.registerFunction('sklearn.metrics._scorer._passthrough_scorer');
  5437. this.registerFunction('re._compile', (pattern, flags) => {
  5438. return self.invoke('re.Pattern', [pattern, flags]);
  5439. });
  5440. this.registerFunction('srsly.cloudpickle.cloudpickle._builtin_type', (...args) => {
  5441. return function() {
  5442. return self.invoke(`types.${args[0]}`, args);
  5443. };
  5444. });
  5445. this.registerType('sympy.printing.defaults.Printable', class {});
  5446. this.registerType('sympy.core.basic.Basic', class extends sympy.printing.defaults.Printable {
  5447. constructor(...args) {
  5448. super();
  5449. this._args = args;
  5450. }
  5451. get args() {
  5452. return this._args;
  5453. }
  5454. });
  5455. this.registerType('sympy.core.function.Function', class extends sympy.core.basic.Basic {
  5456. });
  5457. this.registerType('sympy.core.expr.Expr', class extends sympy.core.basic.Basic {
  5458. });
  5459. this.registerType('sympy.core.operations.AssocOp', class extends sympy.core.expr.Expr /* sympy.core.basic.Basic */ {});
  5460. this.registerType('sympy.core.power.Pow', class extends sympy.core.expr.Expr {
  5461. __str__() {
  5462. return this._args.map((a) => a.__str__()).join('**');
  5463. }
  5464. });
  5465. this.registerType('sympy.core.add.Add', class extends sympy.core.operations.AssocOp {
  5466. __str__() {
  5467. return this._args.map((a) => a.__str__()).join(' + ');
  5468. }
  5469. });
  5470. this.registerType('sympy.core.mul.Mul', class extends sympy.core.operations.AssocOp {
  5471. __str__() {
  5472. return this._args.map((a) => a.__str__()).join('*');
  5473. }
  5474. });
  5475. this.registerType('sympy.core.numbers.Number', class extends sympy.core.expr.Expr {});
  5476. this.registerType('sympy.core.numbers.Rational', class extends sympy.core.numbers.Number {});
  5477. this.registerType('sympy.core.numbers.Integer', class extends sympy.core.numbers.Rational {
  5478. constructor(value) {
  5479. super();
  5480. this.value = value;
  5481. this.is_Integer = true;
  5482. }
  5483. __int__() {
  5484. return this.value;
  5485. }
  5486. __str__() {
  5487. return this.value.toString();
  5488. }
  5489. });
  5490. this.registerType('sympy.core.symbol.Symbol', class extends sympy.core.expr.Expr {
  5491. constructor(name) {
  5492. super();
  5493. this.name = name;
  5494. }
  5495. __int__() {
  5496. throw new python.Error('Cannot convert symbols to int.');
  5497. }
  5498. __str__() {
  5499. return this.name;
  5500. }
  5501. });
  5502. this.registerType('sympy.core.relational.Relational', class extends sympy.core.expr.Expr {
  5503. constructor(lhs, rhs, op) {
  5504. super();
  5505. this._args = [lhs, rhs];
  5506. this._op = op;
  5507. }
  5508. __str__() {
  5509. return `${this._args[0].__str__()} ${this._op} ${this._args[1].__str__()}`;
  5510. }
  5511. });
  5512. this.registerType('sympy.core.relational._Inequality', class extends sympy.core.relational.Relational {
  5513. });
  5514. this.registerType('sympy.core.relational._Greater', class extends sympy.core.relational._Inequality {
  5515. });
  5516. this.registerType('sympy.core.relational.GreaterThan', class extends sympy.core.relational._Greater {
  5517. constructor(lhs, rhs) {
  5518. super(lhs, rhs, '>=');
  5519. }
  5520. });
  5521. this.registerType('sympy.core.relational._Less', class extends sympy.core.relational._Inequality {
  5522. });
  5523. this.registerType('sympy.core.relational.LessThan', class extends sympy.core.relational.Relational {
  5524. constructor(lhs, rhs) {
  5525. super(lhs, rhs, '<=');
  5526. }
  5527. });
  5528. this.registerType('sympy.core.relational.StrictLessThan', class extends sympy.core.relational.Relational {
  5529. constructor(lhs, rhs) {
  5530. super(lhs, rhs, '<');
  5531. }
  5532. });
  5533. this.registerType('sympy.core.relational.StrictGreaterThan', class extends sympy.core.relational.Relational {
  5534. constructor(lhs, rhs) {
  5535. super(lhs, rhs, '>');
  5536. }
  5537. });
  5538. this.registerType('sympy.core.relational.Equality', class extends sympy.core.relational.Relational {
  5539. constructor(lhs, rhs) {
  5540. super(lhs, rhs, '==');
  5541. }
  5542. });
  5543. this.registerType('sympy.functions.elementary.miscellaneous.MinMaxBase', class extends sympy.core.expr.Expr {
  5544. });
  5545. this.registerType('sympy.functions.elementary.miscellaneous.Max', class extends sympy.functions.elementary.miscellaneous.MinMaxBase {
  5546. __str__() {
  5547. return `Max(${this._args.map((a) => a.__str__()).join(', ')})`;
  5548. }
  5549. });
  5550. this.registerFunction('sympy.core.sympify.sympify', (a /*, locals */) => {
  5551. if (a instanceof sympy.core.expr.Expr) {
  5552. return a;
  5553. }
  5554. const p = ast.parse(a);
  5555. const sympify = (node) => {
  5556. if (node instanceof ast.Call) {
  5557. switch (node.func.id) {
  5558. case 'Symbol': return new sympy.core.symbol.Symbol(node.args[0].value);
  5559. case 'Mul': return new sympy.core.mul.Mul(...node.args.map((arg) => sympify(arg)));
  5560. case 'Add': return new sympy.core.add.Add(...node.args.map((arg) => sympify(arg)));
  5561. case 'Pow': return new sympy.core.power.Pow(...node.args.map((arg) => sympify(arg)));
  5562. case 'Max': return new sympy.functions.elementary.miscellaneous.Max(...node.args.map((arg) => sympify(arg)));
  5563. case 'Integer': return new sympy.core.numbers.Integer(node.args[0].value);
  5564. case 'GreaterThan': return new sympy.core.relational.GreaterThan(sympify(node.args[0]), sympify(node.args[1]));
  5565. case 'StrictGreaterThan': return new sympy.core.relational.StrictGreaterThan(sympify(node.args[0]), sympify(node.args[1]));
  5566. case 'LessThan': return new sympy.core.relational.LessThan(sympify(node.args[0]), sympify(node.args[1]));
  5567. case 'StrictLessThan': return new sympy.core.relational.StrictLessThan(sympify(node.args[0]), sympify(node.args[1]));
  5568. case 'Equality': return new sympy.core.relational.Equality(sympify(node.args[0]), sympify(node.args[1]));
  5569. case 'FloorDiv': return new torch.utils._sympy.functions.FloorDiv(sympify(node.args[0]), sympify(node.args[1]));
  5570. default: throw new python.Error(`Unsupported SymPy function '${node.func.id}'.`);
  5571. }
  5572. }
  5573. if (node instanceof ast.Name) {
  5574. return new sympy.core.symbol.Symbol(node.id);
  5575. }
  5576. if (node instanceof ast.Constant) {
  5577. if (node.type === 'int') {
  5578. return new sympy.core.numbers.Integer(node.value);
  5579. }
  5580. }
  5581. if (node instanceof ast.BinOp) {
  5582. if (node.op instanceof ast.Mult) {
  5583. return new sympy.core.mul.Mul(sympify(node.left), sympify(node.right));
  5584. }
  5585. if (node.op instanceof ast.Pow) {
  5586. return new sympy.core.power.Pow(sympify(node.left), sympify(node.right));
  5587. }
  5588. throw new python.Error(`Unsupported SymPy BinOp op '${node.op.__class__.__name__}'.`);
  5589. }
  5590. if (node instanceof ast.Compare) {
  5591. const left = sympify(node.left);
  5592. const right = sympify(node.comparators[0]);
  5593. const [op] = node.ops;
  5594. if (op instanceof ast.Gt) {
  5595. return new sympy.core.relational.StrictGreaterThan(left, right);
  5596. }
  5597. if (op instanceof ast.GtE) {
  5598. return new sympy.core.relational.GreaterThan(left, right);
  5599. }
  5600. if (op instanceof ast.Lt) {
  5601. return new sympy.core.relational.StrictLessThan(left, right);
  5602. }
  5603. if (op instanceof ast.LtE) {
  5604. return new sympy.core.relational.LessThan(left, right);
  5605. }
  5606. if (op instanceof ast.Eq) {
  5607. return new sympy.core.relational.Equality(left, right);
  5608. }
  5609. throw new python.Error(`Unsupported comparison operator '${op.__class__.__name__}'.`);
  5610. }
  5611. throw new python.Error(`Unsupported SymPy expression '${node.__class__.__name__}'.`);
  5612. };
  5613. return sympify(p.body[0].value);
  5614. });
  5615. this.registerFunction('theano.scalar.basic.same_out');
  5616. this.registerFunction('theano.scalar.basic.same_out_nocomplex');
  5617. this.registerFunction('theano.scalar.basic.upcast_out');
  5618. this.registerFunction('theano.scalar.basic.upgrade_to_float');
  5619. this.registerFunction('theano.tensor.nnet.conv2d');
  5620. this.registerFunction('theano.tensor.type.values_eq_approx_remove_inf_nan');
  5621. this.registerFunction('theano.tensor.type.values_eq_approx_remove_nan');
  5622. this.registerType('torch.nn.modules.module.Module', class {
  5623. constructor() {
  5624. this._modules = new collections.OrderedDict();
  5625. this._parameters = new collections.OrderedDict();
  5626. this._buffers = new collections.OrderedDict();
  5627. }
  5628. __setattr__(name, value) {
  5629. if (value instanceof torch.nn.modules.module.Module) {
  5630. this._modules.set(name, value);
  5631. } else {
  5632. this[name] = value;
  5633. }
  5634. }
  5635. __getattr__(name) {
  5636. if (this._modules.has(name)) {
  5637. return this._modules.get(name);
  5638. }
  5639. return this[name];
  5640. }
  5641. __delattr__(name) {
  5642. if (this._modules.has(name)) {
  5643. this._modules.delete(name);
  5644. }
  5645. }
  5646. children() {
  5647. return this._modules.values();
  5648. }
  5649. named_modules(memo, prefix, remove_duplicate) {
  5650. memo = memo || new Set();
  5651. prefix = prefix || '';
  5652. const modules = new builtins.dict();
  5653. if (!memo.has(this)) {
  5654. if (remove_duplicate) {
  5655. memo.add(this);
  5656. }
  5657. modules.set(prefix, this);
  5658. for (const [name, module] of this._modules.items()) {
  5659. if (module && module.named_modules) {
  5660. const submodule_prefix = `${prefix}${(prefix ? '.' : '')}${name}`;
  5661. for (const [k, v] of module.named_modules(memo, submodule_prefix, remove_duplicate)) {
  5662. modules.set(k, v);
  5663. }
  5664. }
  5665. }
  5666. }
  5667. return modules;
  5668. }
  5669. named_children() {
  5670. return this._modules;
  5671. }
  5672. parameters() {
  5673. return this._parameters.values();
  5674. }
  5675. named_parameters(recurse) {
  5676. if (recurse) {
  5677. throw new python.Error('Named parameters with recurse not implemented.');
  5678. }
  5679. return this._parameters;
  5680. }
  5681. buffers() {
  5682. return this._buffers.values();
  5683. }
  5684. named_buffers(recurse) {
  5685. if (recurse) {
  5686. throw new python.Error('Named parameters with recurse not implemented.');
  5687. }
  5688. return this._buffers;
  5689. }
  5690. _get_name() {
  5691. return this.__class__.__name__;
  5692. }
  5693. add_module(name, module) {
  5694. this._modules.set(name, module);
  5695. }
  5696. register_module(name, module) {
  5697. this.add_module(name, module);
  5698. }
  5699. });
  5700. torch.nn.Module = torch.nn.modules.module.Module;
  5701. torch.nn.modules.Module = torch.nn.modules.module.Module;
  5702. this.registerType('torch._C._TensorBase', class extends builtins.object {});
  5703. this.registerType('torch._C._TensorMeta', class extends builtins.type {});
  5704. this.registerType('torch._C._VariableFunctionsClass', class extends builtins.object {});
  5705. this.registerType('torch._C.SchemaParser', class {
  5706. constructor(str, allow_typevars) {
  5707. this.L = new torch._C.Lexer(str);
  5708. this.type_parser = new torch._C.SchemaTypeParser(this.L, false, allow_typevars);
  5709. }
  5710. parseName() {
  5711. const L = this.L;
  5712. let name = L.expect('id').text();
  5713. if (L.nextIf(':')) {
  5714. L.expect(':');
  5715. name = `${name}::${L.expect('ident').text()}`;
  5716. }
  5717. let overload_name = '';
  5718. if (L.nextIf('.')) {
  5719. overload_name = L.expect('ident').text();
  5720. }
  5721. // const is_a_valid_overload_name = !((overload_name === "default") || (overload_name.rfind("__", 0) == 0));
  5722. // TORCH_CHECK(is_a_valid_overload_name, overload_name, " is not a legal overload name for aten operators");
  5723. return new torch._C.OperatorName(name, overload_name);
  5724. }
  5725. parseDeclaration() {
  5726. const L = this.L;
  5727. const name = this.parseName();
  5728. if (L.cur().kind !== '(') {
  5729. return name;
  5730. }
  5731. throw new python.Error('Not implemented.');
  5732. }
  5733. parseExactlyOneDeclaration() {
  5734. // const L = this.L;
  5735. const result = this.parseDeclaration();
  5736. // L.nextIf(TK_NEWLINE);
  5737. // L.expect(TK_EOF);
  5738. return result;
  5739. }
  5740. parseArgument(idx, is_return, kwarg_only) {
  5741. const L = this.L;
  5742. const type_parser = this.type_parser;
  5743. let [fake_type, real_type, alias_info] = type_parser.parseFakeAndRealType();
  5744. let N = null;
  5745. if (L.nextIf('[')) {
  5746. fake_type = torch.ListType.create(fake_type);
  5747. real_type = torch.ListType.create(real_type);
  5748. if (L.cur().kind === '#') {
  5749. N = Number(L.cur().text());
  5750. L.next();
  5751. }
  5752. L.expect(']');
  5753. let container = type_parser.parseAliasAnnotation();
  5754. if (alias_info) {
  5755. if (!container) {
  5756. container = new torch._C.AliasInfo();
  5757. container.is_write = alias_info.is_write;
  5758. }
  5759. container.addContainedType(alias_info);
  5760. }
  5761. alias_info = container;
  5762. if (L.nextIf('?')) {
  5763. fake_type = torch.OptionalType.create(fake_type);
  5764. real_type = torch.OptionalType.create(real_type);
  5765. }
  5766. }
  5767. let name = null;
  5768. /* eslint-disable no-undef-init */
  5769. let default_value = undefined;
  5770. /* eslint-enable no-undef-init */
  5771. if (is_return) {
  5772. kwarg_only = false;
  5773. if (L.cur().kind === 'id') {
  5774. name = L.next().text();
  5775. } else {
  5776. name = '';
  5777. }
  5778. } else {
  5779. name = L.expect('id').text();
  5780. if (L.nextIf('=')) {
  5781. default_value = this.parseDefaultValue(fake_type, fake_type.kind(), real_type, N);
  5782. }
  5783. }
  5784. return new torch.Argument(name, fake_type, real_type, N, default_value, kwarg_only, alias_info);
  5785. }
  5786. parseDefaultValue(arg_type, kind, real_type, arg_N) {
  5787. // auto range = L.cur().range;
  5788. const L = this.L;
  5789. const range = null;
  5790. switch (kind) {
  5791. case torch._C.TypeKind.StringType:
  5792. case torch._C.TypeKind.OptionalType:
  5793. case torch._C.TypeKind.NumberType:
  5794. case torch._C.TypeKind.IntType:
  5795. case torch._C.TypeKind.BoolType:
  5796. case torch._C.TypeKind.FloatType:
  5797. case torch._C.TypeKind.ComplexType:
  5798. return this.parseSingleConstant(arg_type, kind, real_type);
  5799. case torch._C.TypeKind.ListType: {
  5800. const elem_type = arg_type.containedType(0);
  5801. const real_elem_type = real_type.containedType(0);
  5802. if (L.cur().kind === 'id') {
  5803. return this.parseTensorDefault(range);
  5804. } else if (arg_N && L.cur().kind !== '[') {
  5805. const v = this.parseSingleConstant(elem_type, elem_type.kind(), real_elem_type);
  5806. const repeated = Array(arg_N).fill(v);
  5807. // std::vector<IValue> repeated(arg_N, v);
  5808. return this.convertToList(elem_type, elem_type.kind(), range, repeated);
  5809. }
  5810. return this.parseConstantList(elem_type, elem_type.kind(), real_elem_type);
  5811. }
  5812. case torch._C.TypeKind.DynamicType:
  5813. return this.parseDefaultValue(arg_type, arg_type.dynamicKind(), real_type, arg_N);
  5814. default:
  5815. throw new python.Error(`Unsupported default value kind '${kind}'.`);
  5816. }
  5817. }
  5818. parseSingleConstant(type, kind, real_type) {
  5819. const L = this.L;
  5820. if (kind === torch._C.TypeKind.DynamicType) {
  5821. return this.parseSingleConstant(type, type.dynamicKind(), real_type);
  5822. }
  5823. // const auto& str2dtype = c10::getStringToDtypeMap();
  5824. if (L.cur().kind === 'id') {
  5825. if (L.cur().text() === 'True') {
  5826. L.next();
  5827. return new torch._C.IValue(true);
  5828. }
  5829. if (L.cur().text() === 'False') {
  5830. L.next();
  5831. return new torch._C.IValue(false);
  5832. }
  5833. if (L.cur().text() === 'None') {
  5834. L.next();
  5835. return new torch._C.IValue();
  5836. }
  5837. } else if (L.cur().kind === 'string') {
  5838. const token = L.next();
  5839. return new torch._C.IValue(torch._C.parseStringLiteral(null, token.text()));
  5840. } else if (L.cur().kind === '#') {
  5841. let n = '';
  5842. if (L.nextIf('-')) {
  5843. n = `-${L.expect('#').text()}`; // # .text();
  5844. } else {
  5845. n = L.expect('#').text(); // # .text();
  5846. }
  5847. if (kind === torch._C.TypeKind.ComplexType || n.indexOf('j') !== -1) {
  5848. throw new Error("Complex type not implemented.");
  5849. /*
  5850. const imag = std::stod(n.substr(0, n.size() - 1));
  5851. return c10::complex<double>(0, imag);
  5852. */
  5853. } else if (kind === torch._C.TypeKind.FloatType || n.indexOf('.') !== -1 || n.indexOf('e') !== -1) {
  5854. const v = parseFloat(n);
  5855. return new torch._C.IValue(v, 'Double');
  5856. } else {
  5857. const v = parseInt(n, 10);
  5858. return new torch._C.IValue(v, 'Int');
  5859. }
  5860. }
  5861. throw new python.Error('Not implemented.');
  5862. /*
  5863. switch (L.cur().kind) {
  5864. case TK_TRUE:
  5865. L.next();
  5866. return true;
  5867. case TK_FALSE:
  5868. L.next();
  5869. return false;
  5870. case TK_NONE:
  5871. L.next();
  5872. return IValue();
  5873. case TK_STRINGLITERAL: {
  5874. const token = L.next();
  5875. return parseStringLiteral(token.range, token.text());
  5876. }
  5877. case TK_IDENT: {
  5878. const tok = L.next();
  5879. const text_view = tok.text_view();
  5880. // NB: float/complex/long are here for BC purposes. Other dtypes
  5881. // are handled via str2dtype.
  5882. // Please don't add more cases to this if-else block.
  5883. if ("float" == text_view) {
  5884. return static_cast<int64_t>("at::kFloat");
  5885. } else if ("complex" == text_view) {
  5886. return static_cast<int64_t>("at::kComplexFloat");
  5887. } else if ("long" == text_view) {
  5888. return static_cast<int64_t>("at::kLong");
  5889. } else if ("strided" == text_view) {
  5890. return static_cast<int64_t>("at::kStrided");
  5891. } else if ("Mean" == text_view) {
  5892. return static_cast<int64_t>("at::Reduction::Mean");
  5893. } else if ("contiguous_format" == text_view) {
  5894. return static_cast<int64_t>("c10::MemoryFormat::Contiguous");
  5895. } else {
  5896. const text = tok.text();
  5897. if (isPossiblyOptionalScalarType(real_type) &&
  5898. str2dtype.count(text) > 0) {
  5899. return static_cast<int64_t>(str2dtype.at(text));
  5900. } else {
  5901. throw(ErrorReport(L.cur().range) << "invalid numeric default value");
  5902. }
  5903. }
  5904. }
  5905. default: {
  5906. let n;
  5907. if (L.nextIf('-')) {
  5908. n = "-" + L.expect(TK_NUMBER).text();
  5909. }
  5910. else {
  5911. n = L.expect(TK_NUMBER).text();
  5912. }
  5913. if (kind == torch._C.TypeKind.ComplexType || n.find('j') != "std::string::npos") {
  5914. throw new python.Error('Complex type not implemented.');
  5915. const imag = std::stod(n.substr(0, n.size() - 1));
  5916. return c10::complex<double>(0, imag);
  5917. } else if (kind == torch._C.TypeKind.FloatType || n.find('.') != "std::string::npos" || n.find('e') != "std::string::npos") {
  5918. throw new python.Error('Float type not implemented.');
  5919. return std::stod(n);
  5920. } else {
  5921. throw new python.Error("'torch._C.SchemaParser.parseSingleConstant' not implemented.");
  5922. int64_t v = std::stoll(n);
  5923. return v;
  5924. }
  5925. }
  5926. }
  5927. */
  5928. }
  5929. parseConstantList(type, kind, real_type) {
  5930. const L = this.L;
  5931. const tok = L.expect('[');
  5932. const vs = [];
  5933. if (L.cur().kind !== ']') {
  5934. do {
  5935. vs.push(this.parseSingleConstant(type, kind, real_type));
  5936. } while (L.nextIf(','));
  5937. }
  5938. L.expect(']');
  5939. return this.convertToList(type, kind, tok.range, vs);
  5940. }
  5941. convertToList(type, kind, range, vs) {
  5942. switch (kind) {
  5943. case torch._C.TypeKind.ComplexType:
  5944. return new torch._C.IValue(new torch._C.List(torch.ComplexType.get(), vs.map((v) => v)));
  5945. case torch._C.TypeKind.FloatType:
  5946. return new torch._C.IValue(new torch._C.List(torch.FloatType.get(), vs.map((v) => v)));
  5947. case torch._C.TypeKind.IntType:
  5948. return new torch._C.IValue(new torch._C.List(torch.IntType.get(), vs.map((v) => v)));
  5949. case torch._C.TypeKind.BoolType:
  5950. return new torch._C.IValue(new torch._C.List(torch.BoolType.get(), vs.map((v) => v)));
  5951. case torch._C.TypeKindDynamicType:
  5952. return this.convertToList(type.dynamicKind(), range, vs);
  5953. default:
  5954. // throw(ErrorReport(range) << "lists are only supported for float, int and complex types");
  5955. throw new python.Error('lists are only supported for float, int and complex types');
  5956. }
  5957. }
  5958. });
  5959. this.registerType('torch.FunctionSchema', class {
  5960. constructor(name, overload_name, args, returns, is_vararg, is_varret) {
  5961. const index = name.indexOf('(');
  5962. if (index === -1) {
  5963. this._name = name;
  5964. this._overload_name = overload_name || '';
  5965. this._arguments = args || [];
  5966. this._returns = returns || [];
  5967. this._is_vararg = is_vararg || false;
  5968. this._is_varret = is_varret || false;
  5969. } else {
  5970. const value = name.substring(0, index).trim();
  5971. const dot = value.indexOf('.');
  5972. if (dot === -1) {
  5973. this._name = value;
  5974. this._overload_name = '';
  5975. } else {
  5976. this._name = value.substring(0, dot);
  5977. this._overload_name = value.substring(dot + 1, value.length);
  5978. }
  5979. this._buffer = name.substring(index, name.length);
  5980. }
  5981. }
  5982. static parse(schema) {
  5983. return new torch.FunctionSchema(schema);
  5984. }
  5985. get name() {
  5986. return this._name;
  5987. }
  5988. get overload_name() {
  5989. return this._overload_name;
  5990. }
  5991. get arguments() {
  5992. this._parse();
  5993. return this._arguments;
  5994. }
  5995. get returns() {
  5996. this._parse();
  5997. return this._returns;
  5998. }
  5999. get is_vararg() {
  6000. this._parse();
  6001. return this._is_vararg;
  6002. }
  6003. get is_varret() {
  6004. this._parse();
  6005. return this._is_varret;
  6006. }
  6007. argumentIndexWithName(name) {
  6008. const index = this.arguments.findIndex((arg) => arg.name === name);
  6009. return index === -1 ? null : index;
  6010. }
  6011. _parse() {
  6012. if (this._buffer) {
  6013. const parser = new torch._C.SchemaParser(this._buffer, true /* parseSchemaOrName */);
  6014. const L = parser.L;
  6015. this._arguments = [];
  6016. this._is_vararg = false;
  6017. this._kwarg_only = false;
  6018. let idx = 0;
  6019. L.expect('(');
  6020. if (!L.nextIf(')')) {
  6021. while (true) {
  6022. if (this._is_vararg) {
  6023. throw new python.Error("Unexpected 'torch.FunctionSchema._is_vararg'.");
  6024. }
  6025. if (L.nextIf('*')) {
  6026. this._kwarg_only = true;
  6027. } else if (L.nextIf('...')) {
  6028. this._is_vararg = true;
  6029. } else {
  6030. const argument = parser.parseArgument(idx++, false, this._kwarg_only);
  6031. this._arguments.push(argument);
  6032. }
  6033. if (!L.nextIf(',')) {
  6034. break;
  6035. }
  6036. }
  6037. L.expect(')');
  6038. }
  6039. L.expect('->');
  6040. this._returns = [];
  6041. this._is_varret = false;
  6042. if (L.nextIf('...')) {
  6043. this._is_varret = true;
  6044. } else if (L.nextIf('(')) {
  6045. if (!L.nextIf(')')) {
  6046. while (true) {
  6047. if (this._is_varret) {
  6048. throw new python.Error("Unexpected 'torch.FunctionSchema._is_varret'.");
  6049. }
  6050. if (L.nextIf('...')) {
  6051. this._is_varret = true;
  6052. } else {
  6053. const argument = parser.parseArgument(idx++, true, false);
  6054. this._returns.push(argument);
  6055. }
  6056. if (!L.nextIf(',')) {
  6057. break;
  6058. }
  6059. }
  6060. L.expect(')');
  6061. }
  6062. } else {
  6063. this._returns.push(parser.parseArgument(0, true, false));
  6064. }
  6065. delete this._buffer;
  6066. }
  6067. }
  6068. __str__() {
  6069. const list = [this.name];
  6070. const overload_name = this.overload_name;
  6071. if (overload_name !== '' && overload_name !== 'default') {
  6072. list.push(`.${this.overload_name}`);
  6073. }
  6074. list.push('(');
  6075. let first = true;
  6076. let kwarg_only = false;
  6077. for (const argument of this.arguments) {
  6078. if (!first) {
  6079. list.push(', ');
  6080. }
  6081. if (argument.kwarg_only && !kwarg_only) {
  6082. list.push('*, ');
  6083. kwarg_only = true;
  6084. }
  6085. first = false;
  6086. list.push(argument.str());
  6087. }
  6088. if (this.is_vararg) {
  6089. if (!first) {
  6090. list.push(', ');
  6091. }
  6092. first = true;
  6093. list.push('...');
  6094. }
  6095. list.push(') -> ');
  6096. const returns = this.returns;
  6097. const braces = !this.is_varret &&
  6098. (returns.length !== 1 ||
  6099. returns[0].name ||
  6100. returns[0].real_type instanceof torch.TupleType ||
  6101. returns[0].real_type instanceof torch.ListType && returns[0].real_type.getElementType() instanceof torch.TupleType);
  6102. if (braces) {
  6103. list.push('(');
  6104. }
  6105. first = true;
  6106. for (const argument of this.returns) {
  6107. if (!first) {
  6108. list.push(', ');
  6109. }
  6110. first = false;
  6111. list.push(argument.str());
  6112. }
  6113. if (this.is_varret) {
  6114. if (!first) {
  6115. list.push(', ');
  6116. }
  6117. first = true;
  6118. list.push('...');
  6119. }
  6120. if (braces) {
  6121. list.push(')');
  6122. }
  6123. return list.join('');
  6124. }
  6125. aliasAnalysis() {
  6126. return this._alias_kind || 'CONSERVATIVE';
  6127. }
  6128. setAliasAnalysis(v) {
  6129. this._alias_kind = v;
  6130. }
  6131. hasAnyAliasInfo() {
  6132. for (const arg of this.arguments) {
  6133. if (arg.alias_info !== null) {
  6134. return true;
  6135. }
  6136. }
  6137. for (const ret of this.returns) {
  6138. if (ret.alias_info !== null) {
  6139. return true;
  6140. }
  6141. }
  6142. return false;
  6143. }
  6144. is_mutable() {
  6145. return this.arguments.some((arg) => {
  6146. const aliasInfo = arg.alias_info;
  6147. return aliasInfo && aliasInfo.is_write;
  6148. });
  6149. }
  6150. });
  6151. this.registerType('torch._C.SchemaInfo', class {
  6152. constructor(schema) {
  6153. this._schema = schema;
  6154. this._alias_maps_current = false;
  6155. this._has_init = false;
  6156. }
  6157. is_nondeterministic() {
  6158. if (this._schema.name === 'aten::dropout' && this._schema.overload === '') {
  6159. //
  6160. }
  6161. torch._C.nondeterministic_op_strings = torch._C.nondeterministic_op_strings || new Set([
  6162. 'aten::dropout(Tensor input, float p, bool train) -> Tensor',
  6163. 'aten::_fused_dropout(Tensor self, float p, Generator? generator) -> (Tensor, Tensor)',
  6164. 'aten::_standard_gamma(Tensor self, Generator? generator) -> Tensor',
  6165. 'aten::bernoulli(Tensor self, *, Generator? generator) -> Tensor',
  6166. 'aten::bernoulli(Tensor self, float p, *, Generator? generator) -> Tensor',
  6167. 'aten::multinomial(Tensor self, int num_samples, bool replacement, *, Generator? generator) -> Tensor',
  6168. 'aten::native_dropout(Tensor input, float p, bool? train) -> (Tensor, Tensor)',
  6169. 'aten::normal(Tensor mean, Tensor std, *, Generator? generator) -> Tensor',
  6170. 'aten::normal(float mean, Tensor std, *, Generator? generator) -> Tensor',
  6171. 'aten::normal(Tensor mean, float std, *, Generator? generator) -> Tensor',
  6172. 'aten::poisson(Tensor self, Generator? generator) -> Tensor',
  6173. 'aten::binomial(Tensor count, Tensor prob, Generator? generator=None) -> Tensor',
  6174. 'aten::rrelu(Tensor self, Scalar lower, Scalar upper, bool training, Generator? generator) -> Tensor',
  6175. 'aten::rrelu_with_noise(Tensor self, Tensor noise, Scalar lower, Scalar upper, bool training, Generator? generator) -> Tensor',
  6176. 'aten::rand(int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6177. 'aten::rand_like(Tensor self, *, int? dtype=None, int? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor',
  6178. 'aten::randint(int high, int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6179. 'aten::randint(int low, int high, int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6180. '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',
  6181. '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',
  6182. 'aten::randn(int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6183. 'aten::randn_like(Tensor self, *, int? dtype=None, int? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor',
  6184. 'aten::randperm(int n, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor'
  6185. ]);
  6186. if (torch._C.nondeterministic_op_strings.has(this._schema.__str__())) {
  6187. return true;
  6188. }
  6189. /*
  6190. const auto& op = c10::Dispatcher::singleton().findOp(
  6191. c10::OperatorName(schema_.name(), schema_.overload_name()));
  6192. return op && op->hasTag(at::Tag::nondeterministic_seeded);
  6193. */
  6194. return false;
  6195. }
  6196. });
  6197. this.registerType('torch._C.OperatorRegistry', class {
  6198. constructor() {
  6199. this.to_register = [];
  6200. this.operators = new Map();
  6201. }
  6202. registerPendingOperators() {
  6203. for (const op of this.to_register) {
  6204. const sym = op.schema().name;
  6205. if (!this.operators.has(sym)) {
  6206. this.operators.set(sym, []);
  6207. }
  6208. this.operators.get(sym).push(op);
  6209. }
  6210. this.to_register = [];
  6211. }
  6212. registerOperator(op) {
  6213. this.to_register.push(op);
  6214. }
  6215. getOperators(name) {
  6216. this.registerPendingOperators();
  6217. if (this.operators.has(name)) {
  6218. return this.operators.get(name);
  6219. }
  6220. return [];
  6221. }
  6222. });
  6223. this.registerFunction('torch._C.getAllOperatorsFor', (name) => {
  6224. return torch._C.getRegistry().getOperators(name);
  6225. });
  6226. this.registerType('torch._C.Operator', class {
  6227. constructor(schema) {
  6228. this._schema = schema;
  6229. }
  6230. schema() {
  6231. return this._schema;
  6232. }
  6233. getOperation(/* node */) {
  6234. return null;
  6235. }
  6236. aliasAnalysisKind() {
  6237. const schemaRef = this.schema();
  6238. const alias_analysis = schemaRef.aliasAnalysis();
  6239. torch._C.TORCH_CHECK(alias_analysis === 'FROM_SCHEMA' || !schemaRef.hasAnyAliasInfo());
  6240. return alias_analysis;
  6241. }
  6242. });
  6243. this.registerFunction('torch._C.getRegistry', () => {
  6244. torch._C.r = torch._C.r || new torch._C.OperatorRegistry();
  6245. return torch._C.r;
  6246. });
  6247. this.registerFunction('torch._C._get_schema', (op_name, overload_name) => {
  6248. const operations = torch._C.getAllOperatorsFor(op_name);
  6249. for (const op of operations) {
  6250. if (op.schema().overload_name === overload_name) {
  6251. return op.schema();
  6252. }
  6253. }
  6254. throw new python.Error(`Schema '${op_name}.${overload_name}' not found.`);
  6255. });
  6256. this.registerFunction('torch._C._jit_get_schemas_for_operator', (op_name) => {
  6257. return torch._C.getAllOperatorsFor(op_name).map((op) => op.schema());
  6258. });
  6259. this.registerFunction('torch._C._jit_get_operation', (op_name) => {
  6260. const sortedOps = torch._C.getAllOperatorsFor(op_name);
  6261. if (sortedOps.length === 0) {
  6262. return [null, null];
  6263. }
  6264. const overload_names = sortedOps.map((op) => op.schema().overload_name);
  6265. return [{}, overload_names];
  6266. });
  6267. this.registerFunction('torch._C._get_operation_overload', (op_name, overload_name) => {
  6268. const operations = torch._C.getAllOperatorsFor(op_name);
  6269. for (const op of operations) {
  6270. if (op.schema().overload_name === overload_name) {
  6271. return [{}, {}, null];
  6272. }
  6273. }
  6274. return null;
  6275. });
  6276. this.registerFunction('torch._C._unset_dispatch_mode', () => {
  6277. return null;
  6278. });
  6279. this.registerFunction('torch._C._set_dispatch_mode', () => {
  6280. });
  6281. this.registerType('torch._C.MatchedSchema', class {
  6282. constructor(inputs, return_types, return_field_names, schema_name) {
  6283. this.inputs = inputs;
  6284. this.return_types = return_types;
  6285. this.register_field_names = return_field_names;
  6286. this.schema_name = schema_name;
  6287. }
  6288. });
  6289. this.registerType('torch._C.Self', class {
  6290. });
  6291. this.registerFunction('torch._C.toValues', (g, nvs) => {
  6292. return nvs.map((v) => v.value(g));
  6293. });
  6294. this.registerType('torch._C.SimpleSelf', class extends torch._C.Self {
  6295. constructor(classType) {
  6296. super();
  6297. this._classType = classType;
  6298. }
  6299. makeSugared(v) {
  6300. v.setType(this._classType);
  6301. return new torch._C.SimpleValue(v);
  6302. }
  6303. getClassType() {
  6304. return this._classType;
  6305. }
  6306. });
  6307. this.registerType('torch._C.Function', class {
  6308. isGraphFunction() {
  6309. return false;
  6310. }
  6311. name() {
  6312. return this.qualname().name();
  6313. }
  6314. });
  6315. this.registerType('torch._C.BuiltinOpFunction', class extends torch._C.Function {
  6316. constructor(qualname, schema) {
  6317. super();
  6318. this._name = qualname;
  6319. this._schema = schema;
  6320. }
  6321. qualname() {
  6322. return this._name;
  6323. }
  6324. getSchema() {
  6325. return this._schema;
  6326. }
  6327. ensure_defined() {
  6328. }
  6329. });
  6330. this.registerType('torch._C.DeadCodeEliminator', class {
  6331. constructor(...args) {
  6332. this._aliasDb = null;
  6333. this._useAliasDb = false;
  6334. this._memo = new Map();
  6335. this._marked = new Set();
  6336. this._liveValues = new Set();
  6337. this._deleteCallback = () => {};
  6338. if (args.length > 0 && args[0] instanceof torch.Graph) {
  6339. [this._graph, this._sideEffectPolicy] = args;
  6340. this._useAliasDb = true;
  6341. } else {
  6342. [this._sideEffectPolicy] = args;
  6343. }
  6344. }
  6345. run(block, recurse) {
  6346. this.eliminateDeadForkInputs(block, recurse);
  6347. this.mark(block.return_node());
  6348. this.mark(block);
  6349. this._deleteCallback(this._liveValues);
  6350. this.sweep(block, recurse);
  6351. }
  6352. setDeleteCallback(deleteCallback) {
  6353. this._deleteCallback = deleteCallback;
  6354. }
  6355. eliminateDeadForkInputs(block, recurse) {
  6356. for (const node of block.nodes()) {
  6357. if (recurse) {
  6358. for (const sb of node.blocks()) {
  6359. this.eliminateDeadForkInputs(sb, recurse);
  6360. }
  6361. }
  6362. if (node.kind() !== 'prim::fork') {
  6363. continue;
  6364. }
  6365. const g = node.g("Subgraph");
  6366. for (let i = 0; i < g.inputs().length; i++) {
  6367. if (!g.inputs()[i].hasUses()) {
  6368. g.eraseInput(i);
  6369. node.removeInput(i);
  6370. }
  6371. }
  6372. }
  6373. }
  6374. markReturnNode(node) {
  6375. if (this._marked.has(node)) {
  6376. return false;
  6377. }
  6378. torch._C.AT_ASSERT(node.owningBlock().return_node() === node);
  6379. const outerNode = node.owningBlock().owningNode();
  6380. if (outerNode === null || outerNode.kind() === 'prim::Reverse') {
  6381. return this.mark(node);
  6382. }
  6383. if (outerNode.kind() === 'prim::Loop' || outerNode.kind() === 'c10::onnx::Loop') {
  6384. const loop = new torch._C.LoopView(outerNode);
  6385. for (let i = 0; i < loop.carriedOutputs().length; i++) {
  6386. if (outerNode.kind() === 'onnx::Loop') {
  6387. this._liveValues.add(loop.bodyCarriedOutputs()[i]);
  6388. continue;
  6389. }
  6390. const innerInput = loop.bodyCarriedInputs()[i];
  6391. const innerOutput = loop.bodyCarriedOutputs()[i];
  6392. const outerOutput = loop.carriedOutputs()[i];
  6393. if (this._liveValues.has(outerOutput) || innerInput.hasUses()) {
  6394. this._liveValues.add(innerOutput);
  6395. }
  6396. }
  6397. this._liveValues.add(loop.nextCond());
  6398. } else {
  6399. torch._C.AT_ASSERT(outerNode.outputs().length === node.inputs().length);
  6400. for (let i = 0; i < outerNode.outputs().length; i++) {
  6401. const innerOutput = node.inputs()[i];
  6402. const outerOutput = outerNode.outputs()[i];
  6403. if (!this._liveValues.has(outerOutput)) {
  6404. this._liveValues.add(innerOutput);
  6405. }
  6406. }
  6407. }
  6408. this._marked.add(node);
  6409. return true;
  6410. }
  6411. markLoop(node) {
  6412. torch._C.TORCH_INTERNAL_ASSERT(node.kind() === 'prim::Loop');
  6413. let marked = false;
  6414. let anyMarked = false;
  6415. do {
  6416. marked = this.mark(node.blocks().at(0));
  6417. anyMarked = anyMarked || marked;
  6418. } while (marked);
  6419. return anyMarked;
  6420. }
  6421. mark(...args) {
  6422. if (args.length === 1 && args[0] instanceof torch.Block) {
  6423. const [block] = args;
  6424. let anyMarked = false;
  6425. for (const node of block.nodes()) {
  6426. if (this._sideEffectPolicy === 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS' && this.hasSideEffects(node)) {
  6427. const marked = this.mark(node);
  6428. anyMarked = anyMarked || marked;
  6429. }
  6430. }
  6431. const marked = this.markReturnNode(block.return_node());
  6432. anyMarked = anyMarked || marked;
  6433. for (const node of block.nodes()) {
  6434. if (node.kind() === 'prim::Loop') {
  6435. const marked = this.markLoop(node);
  6436. anyMarked = anyMarked || marked;
  6437. } else {
  6438. for (const subBlock of node.blocks()) {
  6439. const marked = this.mark(subBlock);
  6440. anyMarked = anyMarked || marked;
  6441. }
  6442. }
  6443. const marked = this.markIfLive(node);
  6444. anyMarked = anyMarked || marked;
  6445. }
  6446. return anyMarked;
  6447. }
  6448. if (args.length === 1 && args[0] instanceof torch.Node) {
  6449. const [node] = args;
  6450. if (this._marked.has(node)) {
  6451. return false;
  6452. }
  6453. this._marked.add(node);
  6454. let curNode = node;
  6455. while (curNode && curNode.owningBlock()) {
  6456. this.mark(curNode);
  6457. curNode = curNode.owningBlock().owningNode();
  6458. }
  6459. for (const input of node.inputs()) {
  6460. if (!this._liveValues.has(input)) {
  6461. this._liveValues.add(input);
  6462. }
  6463. }
  6464. return true;
  6465. }
  6466. throw new python.Error('Not implemented.');
  6467. }
  6468. markIfLive(node) {
  6469. for (const output of node.outputs()) {
  6470. if (this._liveValues.has(output)) {
  6471. return this.mark(node);
  6472. }
  6473. }
  6474. if (this._useAliasDb) {
  6475. if (this.getOrCreateAliasDb().writesToAlias(node, this._liveValues)) {
  6476. return this.mark(node);
  6477. }
  6478. }
  6479. return false;
  6480. }
  6481. sweep(block, recurse) {
  6482. const nodes = Array.from(block.nodes()).reverse();
  6483. for (const node of nodes) {
  6484. this.removeDeadBlockOutputs(node);
  6485. this.removeDeadLoopOutputs(node);
  6486. if (recurse) {
  6487. for (const block of node.blocks()) {
  6488. this.sweep(block, true);
  6489. }
  6490. }
  6491. if (!this._marked.has(node) && !node.hasUses()) {
  6492. node.destroy();
  6493. }
  6494. }
  6495. }
  6496. hasUntrackedMutation(node) {
  6497. if (!this._useAliasDb) {
  6498. if (node.kind() === 'prim::SetAttr') {
  6499. return true;
  6500. }
  6501. const schema = node.maybeSchema();
  6502. return schema && schema.is_mutable();
  6503. }
  6504. return this.getOrCreateAliasDb().writesToWildcard(node);
  6505. }
  6506. hasSideEffects(node) {
  6507. const it = this._memo.get(node);
  6508. if (it) {
  6509. return it;
  6510. }
  6511. const has_side_effects = node.hasSideEffects() ||
  6512. node.blocks().some((b) => Array.from(b.nodes()).some((n) => this.hasSideEffects(n))) ||
  6513. this.hasUntrackedMutation(node);
  6514. this._memo.set(node, has_side_effects);
  6515. return has_side_effects;
  6516. }
  6517. removeDeadBlockOutputs(node) {
  6518. if (node.kind() !== 'prim::If' && node.kind() !== 'prim::GradOf') {
  6519. return;
  6520. }
  6521. for (let i_1 = node.outputs().length; i_1 > 0; i_1--) {
  6522. const i = i_1 - 1;
  6523. if (!node.outputs()[i].hasUses()) {
  6524. node.eraseOutput(i);
  6525. for (const b of node.blocks()) {
  6526. b.eraseOutput(i);
  6527. }
  6528. }
  6529. }
  6530. }
  6531. removeDeadLoopOutputs() {
  6532. }
  6533. getOrCreateAliasDb() {
  6534. if (!this._aliasDb) {
  6535. this._aliasDb = new torch._C.AliasDb(this._graph);
  6536. }
  6537. return this._aliasDb;
  6538. }
  6539. });
  6540. this.registerFunction('torch._C.EliminateDeadCode', (...args) => {
  6541. if (args.length === 1 && args[0] instanceof torch.Graph) {
  6542. const [graph] = args;
  6543. const sideEffectPolicy = 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS';
  6544. const worker = new torch._C.DeadCodeEliminator(graph, sideEffectPolicy);
  6545. worker.run(graph.block(), /*recurse=*/true);
  6546. } else if (args.length > 0 && args[0] instanceof torch.Block) {
  6547. const [block] = args;
  6548. const recurse = false;
  6549. const sideEffectPolicy = 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS';
  6550. const worker = new torch._C.DeadCodeEliminator(sideEffectPolicy);
  6551. worker.run(block, recurse);
  6552. } else {
  6553. throw new python.Error('Not implemented.');
  6554. }
  6555. });
  6556. this.registerFunction('torch._C.removeTupleNodes', () => {
  6557. });
  6558. this.registerFunction('torch._C.LowerSimpleTuples', (...args) => {
  6559. if (args.length === 1 && args[0] instanceof torch.Graph) {
  6560. const [graph] = args;
  6561. torch._C.LowerSimpleTuples(graph.block());
  6562. torch._C.EliminateDeadCode(graph);
  6563. } else if (args.length === 1 && args[0] instanceof torch.Block) {
  6564. const [block] = args;
  6565. for (const n of block.nodes()) {
  6566. torch._C.removeTupleNodes(n, false);
  6567. for (const b of n.blocks()) {
  6568. torch._C.LowerSimpleTuples(b);
  6569. }
  6570. }
  6571. } else {
  6572. throw new python.Error('Not implemented.');
  6573. }
  6574. });
  6575. this.registerFunction('torch._C.attributesEqualCSE', (lhs, rhs) => {
  6576. torch._C.AT_ASSERT(lhs !== null);
  6577. torch._C.AT_ASSERT(rhs !== null);
  6578. if (lhs.hasAttributes() !== rhs.hasAttributes()) {
  6579. return false;
  6580. }
  6581. if (!lhs.hasAttributes() && !rhs.hasAttributes()) {
  6582. return true;
  6583. }
  6584. const lnames = lhs.attributeNames();
  6585. const rnames = rhs.attributeNames();
  6586. lnames.sort();
  6587. rnames.sort();
  6588. if (lnames.length !== rnames.length && !lnames.every((v, i) => v !== rnames[i])) {
  6589. return false;
  6590. }
  6591. for (const name of lnames) {
  6592. if (lhs.kindOf(name) !== rhs.kindOf(name)) {
  6593. return false;
  6594. }
  6595. const kind = lhs.kindOf(name);
  6596. switch (kind) {
  6597. case 'i':
  6598. case 'f':
  6599. case 's':
  6600. case 't': {
  6601. if (lhs[kind](name) !== rhs[kind](name)) {
  6602. return false;
  6603. }
  6604. break;
  6605. }
  6606. case 'c': {
  6607. const lc = lhs.c(name);
  6608. const rc = rhs.c(name);
  6609. if (lc.real !== rc.real || lc.imag !== rc.imag) {
  6610. return false;
  6611. }
  6612. break;
  6613. }
  6614. case 'ival': {
  6615. if (lhs[kind](name) !== rhs[kind](name)) {
  6616. return false;
  6617. }
  6618. break;
  6619. }
  6620. default: {
  6621. throw new python.Error('Not implemented.');
  6622. }
  6623. }
  6624. }
  6625. return true;
  6626. });
  6627. this.registerFunction('torch._C.get_hash', (...args) => {
  6628. let hash = 0;
  6629. for (const value of args) {
  6630. if (typeof value === 'number') {
  6631. hash += (value | 0);
  6632. } else if (typeof value === 'string') {
  6633. hash += (value.length | 0);
  6634. } else if (Array.isArray(value)) {
  6635. for (const item of value) {
  6636. hash += torch._C.get_hash(item);
  6637. }
  6638. } else if (value instanceof builtins.complex) {
  6639. hash += (value.real | 0) + (value.imag | 0);
  6640. }
  6641. }
  6642. return hash;
  6643. });
  6644. this.registerFunction('torch._C.HashNode', (k) => {
  6645. torch._C.AT_ASSERT(k !== null);
  6646. let constant_hash = 0;
  6647. if (k.kind() === 'prim::Constant') {
  6648. const type = k.output().type();
  6649. if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'i') {
  6650. constant_hash = k.i('value');
  6651. } else if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'f') {
  6652. constant_hash = k.f('value');
  6653. } else if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'c') {
  6654. constant_hash = k.c('value');
  6655. } else if (type.isSubtypeOf(torch.BoolType.get())) {
  6656. constant_hash = k.i('value');
  6657. }
  6658. }
  6659. return torch._C.get_hash(k.kind(), k.outputs().map((v) => v.type().kind()), k.inputs().map((v) => v.unique()), constant_hash);
  6660. });
  6661. this.registerFunction('torch._C.EqualNode', (lhs, rhs) => {
  6662. if (lhs === null && rhs === null) {
  6663. return true;
  6664. }
  6665. if (lhs === null || rhs === null) {
  6666. return false;
  6667. }
  6668. if (lhs.kind() !== rhs.kind()) {
  6669. return false;
  6670. }
  6671. const lhs_outputs = lhs.outputs();
  6672. const rhs_outputs = rhs.outputs();
  6673. if (lhs_outputs.length !== rhs_outputs.length) {
  6674. return false;
  6675. }
  6676. for (let i = 0; i < lhs_outputs.length; i++) {
  6677. const lt = lhs_outputs[i].type();
  6678. const rt = rhs_outputs[i].type();
  6679. if (!lt.equals(rt)) {
  6680. return false;
  6681. }
  6682. }
  6683. const lhs_inputs = lhs.inputs();
  6684. const rhs_inputs = rhs.inputs();
  6685. if (lhs_inputs.length !== rhs_inputs.length) {
  6686. return false;
  6687. }
  6688. if (!lhs_inputs.every((v, i) => v === rhs_inputs[i])) {
  6689. return false;
  6690. }
  6691. if (!torch._C.attributesEqualCSE(lhs, rhs)) {
  6692. return false;
  6693. }
  6694. if (lhs.blocks().length !== rhs.blocks().length) {
  6695. return false;
  6696. }
  6697. for (let i = 0; i < lhs.blocks().length; i++) {
  6698. if (lhs.blocks().at(i) !== rhs.blocks().at(i)) {
  6699. return false;
  6700. }
  6701. }
  6702. return true;
  6703. });
  6704. this.registerType('torch._C.NodeSet', class {
  6705. constructor() {
  6706. this._nodes = new Map();
  6707. }
  6708. insert(n) {
  6709. const key = torch._C.HashNode(n);
  6710. if (this._nodes.has(key)) {
  6711. this._nodes.get(key).push(n);
  6712. } else {
  6713. this._nodes.set(key, [n]);
  6714. }
  6715. }
  6716. get(n) {
  6717. const key = torch._C.HashNode(n);
  6718. if (this._nodes.has(key)) {
  6719. const nodes = this._nodes.get(key);
  6720. for (const node of nodes) {
  6721. if (torch._C.EqualNode(node, n)) {
  6722. return node;
  6723. }
  6724. }
  6725. }
  6726. return null;
  6727. }
  6728. has(n) {
  6729. return this.get(n) !== null;
  6730. }
  6731. });
  6732. this.registerFunction('torch._C.isinstance', (stack, types) => {
  6733. const ty = stack.pop().type();
  6734. for (const candidate of types) {
  6735. if (ty.isSubtypeOf(candidate)) {
  6736. stack.push(new torch._C.IValue(true, 'Bool'));
  6737. stack.push(true);
  6738. return;
  6739. }
  6740. }
  6741. stack.push(new torch._C.IValue(false, 'Bool'));
  6742. });
  6743. this.registerType('torch._C.Tuple', class {
  6744. constructor(elements) {
  6745. this._elements = elements;
  6746. }
  6747. static create(elements) {
  6748. return new torch._C.Tuple(elements);
  6749. }
  6750. elements() {
  6751. return this._elements;
  6752. }
  6753. });
  6754. this.registerFunction('torch._C.tupleConstruct', (stack, num_inputs) => {
  6755. torch._C.TORCH_CHECK(num_inputs <= stack.length);
  6756. const elems = stack.splice(stack.length - num_inputs, num_inputs);
  6757. const tuple = torch._C.Tuple.create(elems.reverse());
  6758. stack.push(new torch._C.IValue(tuple));
  6759. });
  6760. this.registerFunction('torch._C.runNodeIfInputsAreConstant', (n, ignore_custom_classes, db) => {
  6761. let stack = [];
  6762. for (const input of n.inputs()) {
  6763. const ival = torch._C.toIValue(input);
  6764. if (ival) {
  6765. stack.push(ival);
  6766. } else {
  6767. return null;
  6768. }
  6769. }
  6770. switch (n.kind()) {
  6771. case 'prim::ListUnpack': {
  6772. if (stack.back().toList().size() !== n.outputs().length) {
  6773. return null;
  6774. }
  6775. torch._C.listUnpack(stack, n.outputs().length);
  6776. break;
  6777. }
  6778. case 'prim::TupleConstruct': {
  6779. const tt = n.output().type().expect(torch.TupleType);
  6780. if (tt.name()) {
  6781. torch._C.namedTupleConstruct(stack, tt, n.inputs().length);
  6782. } else {
  6783. torch._C.tupleConstruct(stack, n.inputs().length);
  6784. }
  6785. break;
  6786. }
  6787. case 'prim::ListConstruct': {
  6788. torch._C.listConstruct(stack, n.output().type().expect(torch.ListType), n.inputs().length);
  6789. break;
  6790. }
  6791. case 'prim::DictConstruct': {
  6792. torch._C.dictConstruct(stack, n.output().type().expect(torch.DictType), n.inputs().length);
  6793. break;
  6794. }
  6795. case 'prim::CreateObject': {
  6796. torch._C.createObject(stack, n.output().type().expect(torch.ClassType), /*use_weak_ref*/ true);
  6797. break;
  6798. }
  6799. case 'prim::GetAttr': {
  6800. const attr = torch._C.pop(stack).toObject().getAttr(n.s('name'));
  6801. torch._C.push(stack, attr);
  6802. break;
  6803. }
  6804. case 'prim::isinstance': {
  6805. torch._C.isinstance(stack, n.tys('types'));
  6806. break;
  6807. }
  6808. default: {
  6809. const maybe_schema = n.maybeSchema();
  6810. if (maybe_schema && maybe_schema.is_vararg) {
  6811. return null;
  6812. }
  6813. // try
  6814. // {
  6815. // const op = n.getOperation();
  6816. // op(stack);
  6817. const [module, name] = n.kind().split('::');
  6818. const obj = torch.ops[module];
  6819. if (!obj) {
  6820. throw new python.Error(`Unknown constant module 'torch.ops.${module}'.`);
  6821. }
  6822. const fn = torch.ops[module].__getattr__(name);
  6823. if (!fn || !fn.__call__) {
  6824. throw new python.Error(`Unknown constant function 'torch.ops.${module}.${name}'.`);
  6825. }
  6826. const args = stack.map((v) => v.value);
  6827. const result = fn.__call__(...args);
  6828. if (result === undefined) {
  6829. stack = [];
  6830. } else if (result instanceof torch._C.IValue) {
  6831. stack = [result];
  6832. } else if (Array.isArray(result) && result.every((v) => v instanceof torch._C.IValue)) {
  6833. stack = result;
  6834. } else {
  6835. stack = [new torch._C.IValue(result)];
  6836. }
  6837. // } catch {
  6838. // stack = [];
  6839. // return null;
  6840. // }
  6841. break;
  6842. }
  6843. }
  6844. for (const v of stack) {
  6845. if (v.isTensor()) {
  6846. const t = v.toTensor();
  6847. if (t.defined() && t.requires_grad()) {
  6848. return null;
  6849. }
  6850. }
  6851. if (ignore_custom_classes) {
  6852. if (v.isCustomClass()) {
  6853. return null;
  6854. }
  6855. }
  6856. if (v.isCustomClass()) {
  6857. if (v.toObject().is_weak_compilation_ref()) {
  6858. continue;
  6859. }
  6860. if (!db) {
  6861. continue;
  6862. }
  6863. const n_non_const = n;
  6864. if (db.mayContainAlias(n_non_const.inputs(), [n_non_const.outputs()])) {
  6865. continue;
  6866. }
  6867. const obj = v.toObject();
  6868. obj.unsafe_make_weak_compilation_ref();
  6869. }
  6870. if (v.isObject()) {
  6871. if (!v.toObject().is_weak_compilation_ref()) {
  6872. return null;
  6873. }
  6874. }
  6875. }
  6876. return stack;
  6877. });
  6878. this.registerType('torch._C.ConstantPropagator', class {
  6879. constructor(graph, aliasing_types, ignore_custom_classes) {
  6880. this._made_change = false;
  6881. this._graph = graph;
  6882. this._aliasing_types = aliasing_types;
  6883. this._ignore_custom_classes = ignore_custom_classes;
  6884. }
  6885. static NoAliasDb(graph) {
  6886. return new torch._C.ConstantPropagator(graph, false, false);
  6887. }
  6888. run() {
  6889. this.ConstantPropagation(this._graph.block());
  6890. return this._made_change;
  6891. }
  6892. propagateNode(n) {
  6893. let outputs = [];
  6894. const outputs_opt = torch._C.runNodeIfInputsAreConstant(n, this._ignore_custom_classes);
  6895. if (outputs_opt) {
  6896. outputs = outputs_opt;
  6897. const graph = n.owningGraph();
  6898. const guard = new torch._C.WithInsertPoint(n);
  6899. for (let i = 0; i < outputs.length; i++) {
  6900. const new_output = torch._C.tryInsertConstant(graph, outputs[i]);
  6901. if (new_output) {
  6902. this._made_change = true;
  6903. if (outputs[i].isNone()) {
  6904. new_output.setType(n.outputs()[i].type());
  6905. }
  6906. n.outputs()[i].replaceAllUsesWith(new_output);
  6907. }
  6908. }
  6909. guard.dispose();
  6910. }
  6911. }
  6912. removeLoopNode(n) {
  6913. const loop_input_offset = 2;
  6914. for (let i = 0; i < n.outputs().length; i++) {
  6915. n.outputs()[i].replaceAllUsesWith(n.inputs()[i + loop_input_offset]);
  6916. }
  6917. this._made_change = true;
  6918. n.destroy();
  6919. }
  6920. loopWillNotRun(node) {
  6921. const [trip_count, start_cond] = node.inputs();
  6922. const iter_len = torch._C.constant_as(trip_count, 'toInt', 1);
  6923. const cond_val = torch._C.constant_as(start_cond, 'toBool', true);
  6924. const loop_might_run = cond_val && iter_len > 0;
  6925. return !loop_might_run;
  6926. }
  6927. inlineIfBody(body) {
  6928. const n = body.owningNode();
  6929. for (const body_node of body.nodes()) {
  6930. body_node.moveBefore(n);
  6931. }
  6932. for (let i = 0; i < n.outputs().length; i++) {
  6933. n.outputs()[i].replaceAllUsesWith(body.outputs()[i]);
  6934. }
  6935. n.destroy();
  6936. }
  6937. inlineIf(n) {
  6938. const input_bool = torch._C.constant_as(n.input(), 'toBool');
  6939. torch._C.AT_ASSERT(input_bool !== null);
  6940. const block_index = input_bool ? 0 : 1;
  6941. this.ConstantPropagation(n.blocks().at(block_index));
  6942. this.inlineIfBody(n.blocks().at(block_index));
  6943. this._made_change = true;
  6944. }
  6945. replaceAndRemoveIfOutput(n, i, replacement) {
  6946. n.outputs()[i].replaceAllUsesWith(replacement);
  6947. n.eraseOutput(i);
  6948. n.blocks().at(0).eraseOutput(i);
  6949. n.blocks().at(1).eraseOutput(i);
  6950. }
  6951. removeExtraIfOutputs(n) {
  6952. torch._C.TORCH_CHECK(n.kind() === 'prim::If');
  6953. const [true_block, false_block] = n.blocks();
  6954. const graph = n.owningGraph();
  6955. const initial_outputs = true_block.outputs().length;
  6956. const guard = new torch._C.WithInsertPoint(n);
  6957. for (let i = 0; i < true_block.outputs().length;) {
  6958. const t_out = true_block.outputs()[i];
  6959. const f_out = false_block.outputs()[i];
  6960. if (true_block.outputs()[i] === false_block.outputs()[i]) {
  6961. this.replaceAndRemoveIfOutput(n, i, true_block.outputs()[i]);
  6962. continue;
  6963. }
  6964. const maybe_const = torch._C.toIValue(t_out);
  6965. if (maybe_const && torch._C.EqualNode(t_out.node(), f_out.node())) {
  6966. const new_const = graph.insertConstant(maybe_const);
  6967. this.replaceAndRemoveIfOutput(n, i, new_const);
  6968. continue;
  6969. }
  6970. i++;
  6971. }
  6972. this._made_change = this._made_change || (initial_outputs !== true_block.outputs().length);
  6973. guard.dispose();
  6974. }
  6975. removeExtraLoopOutputs(node) {
  6976. const initial_outputs = node.outputs().length;
  6977. const [loop_body] = node.blocks();
  6978. const loop_input_offset = 2;
  6979. const loop_body_offset = 1;
  6980. for (let i_1 = node.outputs().length; i_1 > 0; i_1--) {
  6981. const i = i_1 - 1;
  6982. if (loop_body.inputs()[loop_body_offset + i] === loop_body.outputs()[loop_body_offset + i]) {
  6983. const node_input = node.inputs()[loop_input_offset + i];
  6984. node.outputs().at(i).replaceAllUsesWith(node_input);
  6985. loop_body.inputs()[loop_body_offset + i].replaceAllUsesWith(node_input);
  6986. node.eraseOutput(i);
  6987. node.removeInput(loop_input_offset + i);
  6988. loop_body.eraseInput(loop_body_offset + i);
  6989. loop_body.eraseOutput(loop_body_offset + i);
  6990. }
  6991. }
  6992. this._made_change = this._made_change || (initial_outputs !== node.outputs().length);
  6993. }
  6994. noMutableValues(values) {
  6995. return values.every((v) => !torch._C.AliasDb.isMutableType(v));
  6996. }
  6997. getOrCreateAliasDb() {
  6998. if (!this._aliasDb) {
  6999. this._aliasDb = new torch._C.AliasDb(this._graph);
  7000. }
  7001. return this._aliasDb;
  7002. }
  7003. supportedNode(n) {
  7004. torch._C.skip_list = torch._C.skip_list || new Set([
  7005. 'prim::If',
  7006. 'prim::Loop',
  7007. 'prim::Closure',
  7008. 'prim::Constant',
  7009. 'prim::AutogradZero',
  7010. 'prim::Uninitialized',
  7011. 'prim::Guard',
  7012. 'prim::profile',
  7013. 'prim::profile_ivalue',
  7014. 'prim::unchecked_unwrap_optional',
  7015. 'prim::awaitable',
  7016. 'aten::dequantize'
  7017. ]);
  7018. let no_mutation = false;
  7019. if (this._aliasing_types) {
  7020. no_mutation = !this.getOrCreateAliasDb().hasWriters(n);
  7021. } else {
  7022. no_mutation = this.noMutableValues(n.inputs()) && this.noMutableValues(n.outputs());
  7023. }
  7024. return no_mutation && !n.kind().startsWith('onnx::') && !torch._C.skip_list.has(n.kind()) && !n.isNondeterministic() && !n.hasSideEffects() && n.blocks().length === 0;
  7025. }
  7026. ConstantPropagation(...args) {
  7027. if (args[0] instanceof torch.Graph) {
  7028. throw new python.Error('Not implemented.');
  7029. } else if (args[0] instanceof torch.Block) {
  7030. const [block] = args;
  7031. for (const n of block.nodes()) {
  7032. this.ConstantPropagation(n);
  7033. }
  7034. } else if (args[0] instanceof torch.Node) {
  7035. const [n] = args;
  7036. const constant_inputs = n.inputs().every((v) => v.node().kind() === 'prim::Constant');
  7037. if (n.kind() === 'prim::If') {
  7038. if (constant_inputs) {
  7039. this.inlineIf(n);
  7040. } else {
  7041. this.ConstantPropagation(n.blocks());
  7042. this.removeExtraIfOutputs(n);
  7043. }
  7044. } else if (n.kind() === 'prim::Loop') {
  7045. if (this.loopWillNotRun(n)) {
  7046. this.removeLoopNode(n);
  7047. } else {
  7048. this.ConstantPropagation(n.blocks());
  7049. this.removeExtraLoopOutputs(n);
  7050. }
  7051. } else if (constant_inputs && this.supportedNode(n)) {
  7052. this.propagateNode(n);
  7053. } else {
  7054. this.ConstantPropagation(n.blocks()); // not implemented
  7055. }
  7056. } else if (args.length === 1 && Array.isArray(args[0]) && args[0].every((b) => b instanceof torch.Block)) {
  7057. const [blocks] = args;
  7058. for (const block of blocks) {
  7059. this.ConstantPropagation(block);
  7060. }
  7061. } else {
  7062. throw new python.Error('Not implemented.');
  7063. }
  7064. }
  7065. });
  7066. this.registerFunction('torch._C.ConstantPropagationImmutableTypes', (graph) => {
  7067. const cp = torch._C.ConstantPropagator.NoAliasDb(graph);
  7068. const made_change = cp.run();
  7069. if (made_change) {
  7070. torch._C.EliminateDeadCode(graph);
  7071. }
  7072. return made_change;
  7073. });
  7074. this.registerType('torch._C.MutableTypePtrHelper', class {
  7075. constructor(mutable_type_cache) {
  7076. this._mutable_type_cache = mutable_type_cache;
  7077. }
  7078. mapTypeToAliasTypeSet(type) {
  7079. if (this._mutable_type_cache) {
  7080. const result = this.mapTypeToBorrowedAliasTypeSet(type);
  7081. if (result) {
  7082. return result;
  7083. }
  7084. }
  7085. return this.mapTypeToAliasTypeSetImpl(type);
  7086. }
  7087. mapTypeToAliasTypeSetImpl(type) {
  7088. if (type instanceof torch.ListType ||
  7089. type instanceof torch.DictType ||
  7090. type instanceof torch.ClassType ||
  7091. type instanceof torch.TensorType) {
  7092. return [torch._C.unshapedType(type)];
  7093. }
  7094. if (type instanceof torch.UnionType) {
  7095. const mutable_types = [];
  7096. for (const inner of type.expect(torch.UnionType).containedTypes()) {
  7097. const maybe_inner_types = this.mapTypeToAliasTypeSet(inner);
  7098. if (maybe_inner_types) {
  7099. mutable_types.push(...maybe_inner_types);
  7100. }
  7101. }
  7102. if (mutable_types.length === 0) {
  7103. return null;
  7104. }
  7105. return mutable_types;
  7106. }
  7107. if (type instanceof torch.OptionalType) {
  7108. const inner = type.getElementType();
  7109. return this.mapTypeToAliasTypeSet(inner);
  7110. }
  7111. if (type instanceof torch.AnyType) {
  7112. return [torch._C.AliasTypeSet([type])];
  7113. }
  7114. if (type instanceof torch.FutureType) {
  7115. const maybe_mut_types = this.mapTypeToAliasTypeSet(type.getElementType());
  7116. if (maybe_mut_types) {
  7117. return [torch._C.AliasTypeSet([torch.FutureType.create(torch._C.toSingleType(maybe_mut_types))])];
  7118. }
  7119. return null;
  7120. }
  7121. if (type instanceof torch.AwaitType) {
  7122. const maybe_mut_types = this.mapTypeToAliasTypeSet(type.getElementType());
  7123. if (maybe_mut_types) {
  7124. return [torch._C.AliasTypeSet([torch.AwaitType.create(torch._C.toSingleType(maybe_mut_types))])];
  7125. }
  7126. return null;
  7127. }
  7128. if (type instanceof torch.TupleType) {
  7129. const mutable_types = [];
  7130. for (const inner of type.elements()) {
  7131. const maybe_inner_types = this.mapTypeToAliasTypeSet(inner);
  7132. if (maybe_inner_types) {
  7133. mutable_types.push(...maybe_inner_types);
  7134. }
  7135. }
  7136. if (mutable_types.length === 0) {
  7137. return null;
  7138. }
  7139. return [[torch.TupleType.create(mutable_types)]];
  7140. }
  7141. return null;
  7142. }
  7143. });
  7144. this.registerFunction('torch._C.isMutableTypeImpl', (type, mutable_type_cache) => {
  7145. if (type instanceof torch.TensorType || type instanceof torch.ListType ||
  7146. type instanceof torch.ClassType || type instanceof torch.DictType) {
  7147. return true;
  7148. }
  7149. const helper = new torch._C.MutableTypePtrHelper(mutable_type_cache);
  7150. if (mutable_type_cache) {
  7151. return helper.mapTypeToBorrowedAliasTypeSet(type) !== null;
  7152. }
  7153. return helper.mapTypeToAliasTypeSet(type) !== null;
  7154. });
  7155. this.registerType('torch._C.AliasDb', class {
  7156. constructor() {
  7157. this._writeIndex = new Map();
  7158. }
  7159. static isMutableType(...args) {
  7160. if (args[0] instanceof torch.Type) {
  7161. const [type] = args;
  7162. return torch._C.isMutableTypeImpl(type, null);
  7163. }
  7164. if (args[0] instanceof torch.Value) {
  7165. const [value] = args;
  7166. return torch._C.AliasDb.isMutableType(value.type());
  7167. }
  7168. throw new python.Error('Not implemented.');
  7169. }
  7170. writesToAlias(/* n, vs */) {
  7171. /*
  7172. const writtenTo = this.getWrites(n);
  7173. if (writtenTo.length === 0) {
  7174. return false;
  7175. }
  7176. MemoryLocations locs;
  7177. for (const v of vs) {
  7178. const it = elementMap_.find(v);
  7179. if (it != elementMap_.end()) {
  7180. const auto& vlocs = memoryDAG_->getMemoryLocations(it->second);
  7181. if (writtenTo.intersects(vlocs)) {
  7182. return true;
  7183. }
  7184. }
  7185. }
  7186. */
  7187. return false;
  7188. }
  7189. writesToWildcard(n) {
  7190. if (!this._writeIndex.has(n)) {
  7191. return false;
  7192. }
  7193. const writes = this._writeIndex.get(n);
  7194. for (const pr of this._wildcardIndex) {
  7195. const [, wildcardElement] = pr;
  7196. if (writes.test(wildcardElement.index)) {
  7197. return true;
  7198. }
  7199. }
  7200. return false;
  7201. }
  7202. safeToChangeAliasingRelationship(a, b) {
  7203. if (torch._C.hasWriters(a) || torch._C.hasWriters(b)) {
  7204. return false;
  7205. }
  7206. return !(torch._C.escapesScope(a) && torch._C.escapesScope(b));
  7207. }
  7208. });
  7209. this.registerFunction('torch._C.hasWriters', () => {
  7210. });
  7211. this.registerFunction('torch._C.escapesScope', () => {
  7212. });
  7213. this.registerType('torch._C.DepthFirstGraphNodeIterator', class {
  7214. constructor(graph) {
  7215. this._current = graph.block().nodes().front();
  7216. }
  7217. next() {
  7218. return null;
  7219. }
  7220. });
  7221. this.registerType('torch._C.ConcatCombiner', class {
  7222. constructor(graph) {
  7223. this._graph = graph;
  7224. this._aliasDb = new torch._C.AliasDb(graph);
  7225. this._combinable_concats = [];
  7226. }
  7227. collectOptimizableConcats() {
  7228. const graph_it = new torch._C.DepthFirstGraphNodeIterator(this._graph);
  7229. for (let node = graph_it.next(); node !== null; node = graph_it.next()) {
  7230. if (node.kind() === 'aten::cat') {
  7231. this.handleConcat(node);
  7232. }
  7233. }
  7234. }
  7235. combineConcats() {
  7236. if (this._combinable_concats.length === 0) {
  7237. return false;
  7238. }
  7239. const list_construct_inputs = this.getListConstructInputs();
  7240. for (const node_and_new_list of list_construct_inputs) {
  7241. const [node, inputs] = node_and_new_list;
  7242. const new_list_construct = this.createListConstruct(inputs);
  7243. const old_list_construct = node.input(0).node();
  7244. new_list_construct.output().setType(old_list_construct.output().type());
  7245. new_list_construct.insertBefore(node);
  7246. old_list_construct.replaceAllUsesWith(new_list_construct);
  7247. }
  7248. return true;
  7249. }
  7250. run() {
  7251. this.collectOptimizableConcats();
  7252. const changed = this.combineConcats();
  7253. if (changed) {
  7254. torch._C.EliminateDeadCode(this._graph);
  7255. }
  7256. return changed;
  7257. }
  7258. });
  7259. this.registerFunction('torch._C.CombineConcats', (graph) => {
  7260. const changed = new torch._C.ConcatCombiner(graph).run();
  7261. return changed;
  7262. });
  7263. this.registerType('torch._C.PeepholeOptimizeImpl', class {
  7264. constructor(graph, disable_shape_peepholes) {
  7265. this._graph = graph;
  7266. this._shape_peepholes = !disable_shape_peepholes;
  7267. }
  7268. run() {
  7269. let changed = this.optimizeBlock(this._graph.block());
  7270. /* changed |= torch._C.PeepholeOptimizeListIdioms(this._graph);
  7271. changed |= torch._C.PeepholeOptimizeDictIdioms(this._graph);
  7272. changed |= torch._C.PeepholeOptimizeAliasSensitive(this._graph, this._shape_peepholes);
  7273. changed |= torch._C.PeepholeOptimizeNonTensor(this._graph); */
  7274. changed = changed || torch._C.CombineConcats(this._graph);
  7275. return changed;
  7276. }
  7277. optimizeBlock(block) {
  7278. let changed = false;
  7279. for (const node of block.nodes()) {
  7280. for (const sub_block of node.blocks()) {
  7281. changed = changed || this.optimizeBlock(sub_block);
  7282. }
  7283. if (node.kind() !== 'prim::Constant') {
  7284. const guard = new torch._C.WithInsertPoint(node);
  7285. for (const output of node.outputs()) {
  7286. if (output.type() instanceof torch.NoneType) {
  7287. output.replaceAllUsesWith(this._graph.insertConstant(new torch._C.IValue()));
  7288. changed = true;
  7289. }
  7290. }
  7291. guard.dispose();
  7292. }
  7293. if (node.kind() === 'prim::If') {
  7294. // throw new python.Error('Not implemented.');
  7295. /*
  7296. const n = new torch._C.IfView(node);
  7297. // this handles redundant short circuits like "x and True" or "x or
  7298. // False"
  7299. for (const auto i : c10::irange(n.outputs().length)) {
  7300. if (n.outputs().at(i).type() != torch.BoolType.get()) {
  7301. continue;
  7302. }
  7303. const true_val = constant_as<bool>(n.thenOutputs().at(i)).value_or(false);
  7304. const false_val = constant_as<bool>(n.elseOutputs().at(i)).value_or(true);
  7305. if (true_val && !false_val) {
  7306. n.outputs().at(i).replaceAllUsesWith(n.cond());
  7307. changed = true;
  7308. }
  7309. }
  7310. for (let i = 0; i < n.outputs().length; ++i) {
  7311. const inputs_non_optional = !n.thenOutputs().at(i).type().cast<OptionalType>() && !n.elseOutputs().at(i).type().cast<OptionalType>();
  7312. const output_optional = n.outputs()[i].type();
  7313. if (inputs_non_optional && output_optional instanceof torch.OptionalType) {
  7314. const unif = torch._c.unifyTypes(n.thenOutputs().at(i).type(), n.elseOutputs().at(i).type())
  7315. if (unif) {
  7316. n.outputs()[i].setType(unif);
  7317. changed = true;
  7318. }
  7319. }
  7320. }
  7321. */
  7322. } else if (node.kind() === 'aten::__is__' || node.kind() === 'aten::__isnot__') {
  7323. torch._C.AT_ASSERT(node.inputs().length === 2);
  7324. for (const check_none_index of [0, 1]) {
  7325. const input_must_be_none = node.inputs()[check_none_index].mustBeNone();
  7326. const other_must_not_be_none = node.inputs().at(1 - check_none_index).mustNotBeNone();
  7327. if (input_must_be_none && other_must_not_be_none) {
  7328. const guard = new torch._C.WithInsertPoint(node);
  7329. const output = node.owningGraph().insertConstant(node.kind() === 'aten::__isnot__');
  7330. node.output().replaceAllUsesWith(output);
  7331. changed = true;
  7332. guard.dispose();
  7333. }
  7334. }
  7335. } else if (node.kind() === 'prim::unchecked_unwrap_optional' || node.kind() === 'aten::_unwrap_optional') {
  7336. throw new python.Error('Not implemented.');
  7337. /*
  7338. // we are unwrapping an input that can't be None, remove the unwrap
  7339. const input = node.input();
  7340. if (input.mustNotBeNone()) {
  7341. node.output().replaceAllUsesWith(node.input());
  7342. changed = true;
  7343. }
  7344. */
  7345. } else if (node.kind() === 'prim::unchecked_cast') {
  7346. const input_type = torch._C.unshapedType(node.input().type());
  7347. const output_type = torch._C.unshapedType(node.output().type());
  7348. if (input_type.isSubtypeOf(output_type)) {
  7349. node.output().replaceAllUsesWith(node.input());
  7350. changed = true;
  7351. }
  7352. } else if ((node.kind() === 'aten::Int' || node.kind() === 'aten::ceil') && node.inputs().length === 1 && node.input().type() instanceof torch.IntType) {
  7353. node.output().replaceAllUsesWith(node.input());
  7354. changed = true;
  7355. } else if (node.kind() === 'aten::ne' || node.kind() === 'aten::eq') {
  7356. if (node.inputs().length !== 2 || node.inputs()[0] !== node.inputs()[1]) {
  7357. continue;
  7358. }
  7359. const inp_type = node.inputs()[0].type();
  7360. const immut_type = (type) => {
  7361. const kind = type.kind();
  7362. const handled_immutable_types = new Set('BoolType', 'IntType', 'FloatType', 'NoneType');
  7363. return handled_immutable_types.has(kind);
  7364. };
  7365. let non_throwing_type = false;
  7366. if (inp_type instanceof torch.ListType) {
  7367. non_throwing_type = immut_type(inp_type.getElementType());
  7368. } else if (inp_type instanceof torch.DictType) {
  7369. non_throwing_type = immut_type(inp_type.getKeyType()) && immut_type(inp_type.getValueType());
  7370. } else {
  7371. non_throwing_type = immut_type(inp_type);
  7372. }
  7373. if (non_throwing_type) {
  7374. const guard = new torch._C.WithInsertPoint(node);
  7375. node.output().replaceAllUsesWith(this._graph.insertConstant(node.kind() === 'aten::eq'));
  7376. changed = true;
  7377. guard.dispose();
  7378. }
  7379. } else if (node.kind() === 'aten::mul' || node.kind() === 'aten::floordiv' || node.kind() === 'aten::div') {
  7380. // changed = changed || torch._C.trySimplifyMulOrDiv(node);
  7381. } else if (node.kind() === 'aten::add' || node.kind() === 'aten::sub') {
  7382. // changed = changed || torch._C.trySimplifyAddOrSub(node);
  7383. }
  7384. }
  7385. return changed;
  7386. }
  7387. });
  7388. this.registerFunction('torch._C.PeepholeOptimize', (graph, addmm_fusion_enabled) => {
  7389. const peephole = new torch._C.PeepholeOptimizeImpl(graph, addmm_fusion_enabled);
  7390. const changed = peephole.run();
  7391. if (changed) {
  7392. torch._C.EliminateDeadCode(graph.block());
  7393. }
  7394. return changed;
  7395. });
  7396. this.registerFunction('torch._C.TORCH_INTERNAL_ASSERT', (cond) => {
  7397. if (!cond) {
  7398. throw new python.Error('Assertion failed.');
  7399. }
  7400. });
  7401. this.registerFunction('torch._C.TORCH_CHECK', (cond) => {
  7402. if (!cond) {
  7403. throw new python.Error('Assertion failed.');
  7404. }
  7405. });
  7406. this.registerFunction('torch._C.AT_ASSERT', (cond) => {
  7407. if (!cond) {
  7408. throw new python.Error('Assertion failed.');
  7409. }
  7410. });
  7411. this.registerFunction('torch._C.eraseListLiterals', (graph) => {
  7412. const it = new torch._C.DepthFirstGraphNodeIterator(graph);
  7413. for (let next_node = it.next(); next_node !== null;) {
  7414. const node = next_node;
  7415. next_node = it.next();
  7416. if (node.kind() === 'prim::EmptyListLiteral') {
  7417. if (node.hasUses()) {
  7418. torch._C.TORCH_INTERNAL_ASSERT(node.output().type().isSubtypeOf(torch.ListType.ofTensors()));
  7419. }
  7420. const li = graph.createList(torch.TensorType.get(), []);
  7421. li.insertBefore(node);
  7422. node.replaceAllUsesWith(li);
  7423. }
  7424. node.destroy();
  7425. }
  7426. });
  7427. this.registerFunction('torch._C.ConstantPooling', (...args) => {
  7428. if (args.length === 1 && args[0] instanceof torch.Graph) {
  7429. const [graph] = args;
  7430. const aliasDb = new torch._C.AliasDb(graph);
  7431. const constants = new torch._C.NodeSet();
  7432. torch._C.ConstantPooling(graph.block(), constants, aliasDb);
  7433. } else if (args.length === 3 && args[0] instanceof torch.Block) {
  7434. const [block, constants, aliasDb] = args;
  7435. for (const node of block.nodes()) {
  7436. if (node.blocks().length > 0) {
  7437. for (const block of node.blocks()) {
  7438. torch._C.ConstantPooling(block, constants, aliasDb);
  7439. }
  7440. continue;
  7441. }
  7442. if (node.kind() !== 'prim::Constant') {
  7443. continue;
  7444. }
  7445. if (constants.has(node)) {
  7446. const existing = constants.get(node);
  7447. const old_ivalue = torch._C.toIValue(existing.output());
  7448. const new_ivalue = torch._C.toIValue(node.output());
  7449. const same_identity = (old_ivalue && new_ivalue && (old_ivalue.is(new_ivalue)));
  7450. if (!same_identity && !aliasDb.safeToChangeAliasingRelationship(node.outputs(), existing.outputs())) {
  7451. continue;
  7452. }
  7453. node.replaceAllUsesWith(existing);
  7454. node.destroy();
  7455. continue;
  7456. } else {
  7457. constants.insert(node);
  7458. }
  7459. const [first_node] = node.owningGraph().block().nodes();
  7460. if (node !== first_node) {
  7461. node.moveBefore(first_node);
  7462. }
  7463. }
  7464. } else {
  7465. throw new python.Error('Not implemented.');
  7466. }
  7467. });
  7468. this.registerFunction('torch._C.handleBlock', (/* block, initial_state */) =>{
  7469. /*
  7470. const autocast_stack = [];
  7471. let incompatible_amp = null;
  7472. const current_state = () => autocast_stack.length === 0 ? initial_state : autocast_stack.top().context;
  7473. for (const node of block.nodes()) {
  7474. switch (node.kind()) {
  7475. case 'prim::CallFunction':
  7476. if (current_state() === initial_state) {
  7477. if (current_state()) {
  7478. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7479. }
  7480. break;
  7481. }
  7482. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || incompatible_amp.value(), "Calls are not expected with AMP & JIT");
  7483. incompatible_amp = true;
  7484. break;
  7485. case 'prim::CallMethod':
  7486. if (current_state() === initial_state) {
  7487. if (current_state()) {
  7488. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7489. }
  7490. break;
  7491. }
  7492. if (node.input(0).type() instanceof torch.ClassType) {
  7493. const class_type = node.input(0).type();
  7494. const name = node.s('name');
  7495. const fn = class_type.getMethod(name);
  7496. if (!fn.isGraphFunction()) {
  7497. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || incompatible_amp.value());
  7498. incompatible_amp = true;
  7499. }
  7500. } else {
  7501. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || incompatible_amp.value());
  7502. incompatible_amp = true;
  7503. }
  7504. break;
  7505. case 'prim::Enter': {
  7506. const autocast_scope = torch._C.parseAutocast(node.input(), current_state());
  7507. if (autocast_scope) {
  7508. if (node.hasUses()) {
  7509. torch._C.TORCH_CHECK(false, "`with autocast() as ...` is not supported");
  7510. }
  7511. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || !incompatible_amp.value());
  7512. incompatible_amp = false;
  7513. autocast_stack.push(autocast_scope);
  7514. }
  7515. break;
  7516. }
  7517. case 'prim::Exit': {
  7518. if (torch._C.isAutocastNode(node.input(0))) {
  7519. torch._C.TORCH_INTERNAL_ASSERT(!autocast_stack.empty());
  7520. torch._C.TORCH_INTERNAL_ASSERT(autocast_stack.top().instance === node.input());
  7521. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || !incompatible_amp.value());
  7522. incompatible_amp = false;
  7523. autocast_stack.pop();
  7524. }
  7525. break;
  7526. }
  7527. case 'aten::is_autocast_enabled': {
  7528. torch._C.updateAutocastEnabledCheck(node, current_state().gpu_enabled);
  7529. break;
  7530. }
  7531. case 'aten::is_autocast_cpu_enabled': {
  7532. torch._C.updateAutocastEnabledCheck(node, current_state().cpu_enabled);
  7533. break;
  7534. }
  7535. case 'aten::_convolution':
  7536. case 'aten::conv1d':
  7537. case 'aten::conv2d':
  7538. case 'aten::conv3d':
  7539. case 'aten::conv_tbc':
  7540. case 'aten::conv_transpose1d':
  7541. case 'aten::convolution':
  7542. case 'aten::cudnn_convolution':
  7543. case 'aten::cudnn_convolution_transpose':
  7544. case 'aten::prelu':
  7545. case 'aten::addmm':
  7546. case 'aten::addmv':
  7547. case 'aten::addr':
  7548. case 'aten::matmul':
  7549. case 'aten::mm':
  7550. case 'aten::mv':
  7551. case 'aten::linear':
  7552. case 'aten::addbmm':
  7553. case 'aten::baddbmm':
  7554. case 'aten::bmm':
  7555. case 'aten::chain_matmul':
  7556. case 'aten::_thnn_fused_lstm_cell':
  7557. case 'aten::_thnn_fused_gru_cell':
  7558. case 'aten::lstm_cell':
  7559. case 'aten::gru_cell':
  7560. case 'aten::rnn_tanh_cell':
  7561. case 'aten::rnn_relu_cell': {
  7562. if (!node.schema().is_mutable()) {
  7563. torch._C.castTensorInputs(node, 'aten::_autocast_to_reduced_precision', current_state());
  7564. }
  7565. break;
  7566. }
  7567. case 'aten::native_layer_norm':
  7568. case 'aten::acos':
  7569. case 'aten::asin':
  7570. case 'aten::cosh':
  7571. case 'aten::erfinv':
  7572. case 'aten::exp':
  7573. case 'aten::expm1':
  7574. case 'aten::log':
  7575. case 'aten::log10':
  7576. case 'aten::log2':
  7577. case 'aten::log1p':
  7578. case 'aten::reciprocal':
  7579. case 'aten::rsqrt':
  7580. case 'aten::sinh':
  7581. case 'aten::tan':
  7582. case 'aten::pow':
  7583. case 'aten::softplus':
  7584. case 'aten::gelu':
  7585. case 'aten::layer_norm':
  7586. case 'aten::group_norm':
  7587. case 'aten::frobenius_norm':
  7588. case 'aten::nuclear_norm':
  7589. case 'aten::cosine_similarity':
  7590. case 'aten::cosine_embedding_loss':
  7591. case 'aten::nll_loss':
  7592. case 'aten::nll_loss2d':
  7593. case 'aten::hinge_embedding_loss':
  7594. case 'aten::kl_div':
  7595. case 'aten::l1_loss':
  7596. case 'aten::smooth_l1_loss':
  7597. case 'aten::mse_loss':
  7598. case 'aten::margin_ranking_loss':
  7599. case 'aten::multilabel_margin_loss':
  7600. case 'aten::soft_margin_loss':
  7601. case 'aten::triplet_margin_loss':
  7602. case 'aten::multi_margin_loss':
  7603. case 'aten::binary_cross_entropy_with_logits':
  7604. case 'aten::dist':
  7605. case 'aten::pdist':
  7606. case 'aten::cdist':
  7607. case 'aten::renorm':
  7608. case 'aten::logsumexp': {
  7609. if (!node.schema().is_mutable()) {
  7610. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7611. }
  7612. break;
  7613. }
  7614. case 'aten::prod':
  7615. case 'aten::log_softmax':
  7616. case 'aten::cumprod':
  7617. case 'aten::cumsum':
  7618. case 'aten::sum': {
  7619. if (!node.schema().is_mutable() && !torch._C.hasExplicitDtypeArgument(node)) {
  7620. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7621. }
  7622. break;
  7623. }
  7624. case 'aten::softmax': {
  7625. if (!node.schema().is_mutable() && !torch._C.hasExplicitDtypeArgument(node)) {
  7626. const context = current_state();
  7627. context.cpu_enabled = false;
  7628. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', context);
  7629. }
  7630. break;
  7631. }
  7632. case 'aten::addcdiv':
  7633. case 'aten::addcmul':
  7634. case 'aten::atan2':
  7635. case 'aten::bilinear':
  7636. case 'aten::cat':
  7637. case 'aten::cross':
  7638. case 'aten::dot':
  7639. case 'aten::equal':
  7640. case 'aten::index_put':
  7641. case 'aten::stack':
  7642. case 'aten::tensordot':
  7643. case 'aten::add':
  7644. case 'aten::sub':
  7645. case 'aten::mul':
  7646. case 'aten::div': {
  7647. if (!node.schema().is_mutable()) {
  7648. torch._C.castInputsToWidestType(node, current_state());
  7649. }
  7650. break;
  7651. }
  7652. case 'aten::binary_cross_entropy': {
  7653. if (current_state()) {
  7654. torch._C.TORCH_CHECK(false, "Unsafe to autocast");
  7655. }
  7656. break;
  7657. }
  7658. default: {
  7659. break;
  7660. }
  7661. }
  7662. for (const sub_block of node.blocks()) {
  7663. torch._C.handleBlock(sub_block, current_state());
  7664. }
  7665. }
  7666. torch._C.TORCH_INTERNAL_ASSERT(autocast_stack.length === 0);
  7667. */
  7668. });
  7669. this.registerFunction('torch._C.autocastEnabled', () => {
  7670. return true;
  7671. });
  7672. this.registerFunction('torch._C.Autocast', (graph) => {
  7673. if (torch._C.autocastEnabled()) {
  7674. const init = null;
  7675. /* AutocastContext init = {
  7676. at::autocast::is_autocast_enabled(at::kCUDA),
  7677. at::autocast::is_autocast_enabled(at::kCPU),
  7678. at::autocast::get_autocast_dtype(at::kCUDA),
  7679. at::autocast::get_autocast_dtype(at::kCPU)}; */
  7680. torch._C.handleBlock(graph.block(), init);
  7681. }
  7682. });
  7683. this.registerFunction('torch._C.preoptimizeGraph', (graph, disable_autocast) => {
  7684. disable_autocast = disable_autocast || false;
  7685. torch._C.Inline(graph);
  7686. torch._C.PeepholeOptimize(graph, true);
  7687. torch._C.ConstantPropagationImmutableTypes(graph);
  7688. if (!disable_autocast) {
  7689. torch._C.Autocast(graph);
  7690. }
  7691. torch._C.ConstantPooling(graph);
  7692. });
  7693. this.registerType('torch._C.GraphFunction', class extends torch._C.Function {
  7694. constructor(name, graph, function_creator, executor_execution_mode) {
  7695. super();
  7696. this._name = name;
  7697. this._graph = graph;
  7698. this._executor_execution_mode = executor_execution_mode || null;
  7699. this._function_creator = function_creator;
  7700. this._force_no_amp = false;
  7701. }
  7702. isGraphFunction() {
  7703. return true;
  7704. }
  7705. qualname() {
  7706. return this._name;
  7707. }
  7708. graph() {
  7709. return this._graph;
  7710. }
  7711. optimized_graph() {
  7712. const graph_ref = this._graph.copy();
  7713. torch._C.preoptimizeGraph(graph_ref, this._force_no_amp);
  7714. return graph_ref;
  7715. }
  7716. ensure_defined() {
  7717. if (this._function_creator) {
  7718. const creator = this._function_creator;
  7719. this._function_creator = () => {
  7720. throw new python.Error('Recursive method call.');
  7721. };
  7722. creator(this);
  7723. this._function_creator = null;
  7724. }
  7725. this.check_single_output();
  7726. }
  7727. check_single_output() {
  7728. if (this.graph().outputs().length !== 1) {
  7729. throw new python.Error('Graph must have a single output.');
  7730. }
  7731. }
  7732. getSchema() {
  7733. this._schema = this._schema || this.defaultSchemaFor(this);
  7734. return this._schema;
  7735. }
  7736. setSchema(schema) {
  7737. this._schema = schema;
  7738. }
  7739. num_inputs() {
  7740. return this.graph().inputs().length;
  7741. }
  7742. unshapedType(type) {
  7743. if (type.isSubtypeOf(torch.TensorType.get())) {
  7744. return torch.TensorType.get();
  7745. }
  7746. const contained = type.containedTypes();
  7747. if (contained.length === 0) {
  7748. return type;
  7749. }
  7750. return type.withContained(type.containedTypes((type) => this.unshapedType(type)));
  7751. }
  7752. defaultSchemaFor(fn) {
  7753. const args = [];
  7754. const returns = [];
  7755. const g = fn.graph();
  7756. const num_inputs = fn.num_inputs();
  7757. for (let i = 0; i < num_inputs; i++) {
  7758. const v = g.inputs()[i];
  7759. const name = v.hasDebugName() ? v.debugNameBase() : `argument_${i}`;
  7760. const argument = new torch.Argument(name, this.unshapedType(g.inputs()[i].type()));
  7761. args.push(argument);
  7762. }
  7763. const num_outputs = g.outputs().length;
  7764. for (let i = 0; i < num_outputs; i++) {
  7765. const argument = new torch.Argument('', this.unshapedType(g.outputs()[i].type()));
  7766. returns.push(argument);
  7767. }
  7768. return new torch.FunctionSchema(fn.name(), '', args, returns);
  7769. }
  7770. });
  7771. this.registerType('torch.utils._contextlib._DecoratorContextManager', class {});
  7772. this.registerType('torch.utils._contextlib._NoParamDecoratorContextManager', class extends torch.utils._contextlib._DecoratorContextManager {});
  7773. this.registerType('torch.utils._sympy.symbol.SymT', class extends this.enum.Enum {});
  7774. this.registerType('torch.utils._sympy.functions.FloorDiv', class extends sympy.core.function.Function {
  7775. __str__() {
  7776. return this._args.map((a) => a.__str__()).join('//');
  7777. }
  7778. });
  7779. this.registerType('torch.utils._sympy.functions.ModularIndexing', class {});
  7780. this.registerType('torch.utils._sympy.functions.Where', class {});
  7781. this.registerType('torch.utils._sympy.functions.PythonMod', class {});
  7782. this.registerType('torch.utils._sympy.functions.Mod', class {});
  7783. this.registerType('torch.utils._sympy.functions.CleanDiv', class {});
  7784. this.registerType('torch.utils._sympy.functions.CeilToInt', class {});
  7785. this.registerType('torch.utils._sympy.functions.FloorToInt', class {});
  7786. this.registerType('torch.utils._sympy.functions.CeilDiv', class {});
  7787. this.registerType('torch.utils._sympy.functions.LShift', class {});
  7788. this.registerType('torch.utils._sympy.functions.RShift', class {});
  7789. this.registerType('torch.utils._sympy.functions.PowByNatural', class {});
  7790. this.registerType('torch.utils._sympy.functions.FloatPow', class {});
  7791. this.registerType('torch.utils._sympy.functions.FloatTrueDiv', class {});
  7792. this.registerType('torch.utils._sympy.functions.IntTrueDiv', class {});
  7793. this.registerType('torch.utils._sympy.functions.IsNonOverlappingAndDenseIndicator', class {});
  7794. this.registerType('torch.utils._sympy.functions.TruncToFloat', class {});
  7795. this.registerType('torch.utils._sympy.functions.TruncToInt', class {});
  7796. this.registerType('torch.utils._sympy.functions.RoundToInt', class {});
  7797. this.registerType('torch.utils._sympy.functions.RoundDecimal', class {});
  7798. this.registerType('torch.utils._sympy.functions.ToFloat', class {});
  7799. this.registerType('torch.utils._sympy.functions.Identity', class {});
  7800. this.registerType('torch.utils._traceback.CapturedTraceback', class {
  7801. static extract() {
  7802. }
  7803. });
  7804. this.registerFunction('torch.utils.checkpoint.checkpoint');
  7805. this.registerType('torch.utils.data.dataloader._MultiProcessingDataLoaderIter', class {});
  7806. this.registerType('torch.utils.data.dataloader.DataLoader', class {});
  7807. this.registerFunction('torch.utils.data._utils.collate.default_collate');
  7808. torch.utils.data.dataloader.default_collate = torch.utils.data._utils.collate.default_collate;
  7809. this.registerType('torch.utils.data.dataset.Subset', class {});
  7810. this.registerType('torch.utils.data.dataset.Dataset', class {});
  7811. this.registerType('torch.utils.data.dataset.ConcatDataset', class {});
  7812. this.registerType('torch.utils.data.dataset.TensorDataset', class {});
  7813. this.registerType('torch.utils.data.sampler.BatchSampler', class {});
  7814. this.registerType('torch.utils.data.sampler.RandomSampler', class {});
  7815. this.registerType('torch.utils.data.sampler.SequentialSampler', class {});
  7816. this.registerType('torch.utils.data.sampler.SubsetRandomSampler', class {});
  7817. this.registerType('torch.ao.quantization.fake_quantize.FakeQuantize', class {});
  7818. this.registerType('torch.ao.quantization.fake_quantize.FusedMovingAvgObsFakeQuantize', class {});
  7819. this.registerType('torch.ao.quantization.observer._PartialWrapper', class {});
  7820. this.registerType('torch.ao.quantization.observer.HistogramObserver', class {});
  7821. this.registerType('torch.ao.quantization.observer.MovingAverageMinMaxObserver', class {});
  7822. this.registerType('torch.ao.quantization.observer.MovingAveragePerChannelMinMaxObserver', class {});
  7823. this.registerType('torch.ao.quantization.observer.MinMaxObserver', class {});
  7824. this.registerType('torch.ao.quantization.observer.PerChannelMinMaxObserver', class {});
  7825. this.registerType('torch.ao.quantization.observer.PlaceholderObserver', class {});
  7826. this.registerType('torch.ao.quantization.qconfig.QConfig', class {});
  7827. this.registerType('torch.ao.quantization.qconfig.QConfigDynamic', class {});
  7828. this.registerType('torch.ao.quantization.stubs.DeQuantStub', class {});
  7829. this.registerType('torch.ao.quantization.stubs.QuantStub', class {});
  7830. this.registerType('torch.ao.quantization.stubs.QuantWrapper', class {});
  7831. this.registerFunction('torch.ao.quantization.qconfig._activation_is_memoryless');
  7832. this.registerFunction('torch.ao.quantization.qconfig._add_module_to_qconfig_obs_ctr');
  7833. this.registerFunction('torch.ao.quantization.fx.graph_module._save_packed_weight');
  7834. this.registerFunction('torch.ao.quantization.fx._lower_to_native_backend._load_packed_weight');
  7835. this.registerFunction('torch.ao.quantization.fx._lower_to_native_backend._save_packed_weight');
  7836. this.registerFunction('torch.ao.quantization.observer._is_activation_post_process');
  7837. this.registerFunction('torch.ao.quantization.quantize._observer_forward_hook');
  7838. this.registerFunction('torch.ao.quantization.quantization_mappings._get_special_act_post_process');
  7839. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_dynamic_quant_module_mappings');
  7840. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_qat_module_mappings');
  7841. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_qconfig_propagation_list');
  7842. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_static_quant_module_mappings');
  7843. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_static_quant_reference_module_mappings');
  7844. this.registerFunction('torch.ao.quantization.quantization_mappings.no_observer_set');
  7845. this.registerFunction('torch.ao.quantization.quantization_mappings._has_special_act_post_process');
  7846. this.registerFunction('torch.ao.quantization.utils.get_qparam_dict');
  7847. this.registerFunction('torch.ao.quantization.utils.has_no_children_ignoring_parametrizations');
  7848. this.registerFunction('torch.amp.grad_scaler._refresh_per_optimizer_state');
  7849. this.registerType('torch.amp.grad_scaler.GradScaler', class {});
  7850. this.registerType('torch._C._LegacyVariableBase', class {});
  7851. this.registerType('torch.autograd.grad_mode.no_grad', class extends torch.utils._contextlib._NoParamDecoratorContextManager {});
  7852. this.registerType('torch.autograd.variable.Variable', class extends torch._C._LegacyVariableBase {});
  7853. this.registerType('torch.autograd.function._SingleLevelFunction', class {});
  7854. this.registerType('torch.autograd.function.Function', class extends torch.autograd.function._SingleLevelFunction {});
  7855. this.registerType('torch.backends.cudnn.rnn.Unserializable', class {});
  7856. this.registerFunction('torch.distributed._shard.sharded_tensor.pre_load_state_dict_hook');
  7857. this.registerFunction('torch.distributed._shard.sharded_tensor.state_dict_hook');
  7858. this.registerFunction('torch.distributed._sharded_tensor.state_dict_hook');
  7859. this.registerFunction('torch.distributed._sharded_tensor.pre_load_state_dict_hook');
  7860. this.registerType('torch.distributed.algorithms.join._JoinConfig', class {});
  7861. this.registerType('torch.distributed.remote_device._remote_device', class {});
  7862. this.registerType('torch.distributed._shard.metadata.ShardMetadata', class {});
  7863. this.registerType('torch.distributed._shard.sharded_tensor.api.ShardedTensor', class {});
  7864. this.registerType('torch.distributed._shard.sharded_tensor.metadata.ShardedTensorMetadata', class {});
  7865. this.registerType('torch.distributed._shard.sharded_tensor.metadata.TensorProperties', class {});
  7866. this.registerType('torch.distributed._shard.sharded_tensor.shard.Shard', class {});
  7867. this.registerType('torch.distributed._tensor.api.DTensor', class extends torch._C._TensorMeta {});
  7868. this.registerType('torch.distributed._tensor.placement_types.DTensorSpec', class {});
  7869. this.registerType('torch.distributed._tensor.placement_types.Shard', class {});
  7870. this.registerType('torch.distributed._tensor.placement_types.TensorMeta', class {});
  7871. this.registerType('torch.distributed.device_mesh.DeviceMesh', class {});
  7872. this.registerType('torch.distributions.bernoulli.Bernoulli', class {});
  7873. this.registerType('torch.distributions.beta.Beta', class {});
  7874. this.registerType('torch.distributions.binomial.Binomial', class {});
  7875. this.registerType('torch.distributions.categorical.Categorical', class {});
  7876. this.registerType('torch.distributions.constraints._GreaterThan', class {});
  7877. this.registerType('torch.distributions.constraints._Interval', class {});
  7878. this.registerType('torch.distributions.constraints._LowerCholesky', class {});
  7879. this.registerType('torch.distributions.constraints._Real', class {});
  7880. this.registerType('torch.distributions.dirichlet.Dirichlet', class {});
  7881. this.registerType('torch.distributions.mixture_same_family.MixtureSameFamily', class {});
  7882. this.registerType('torch.distributions.multivariate_normal.MultivariateNormal', class {});
  7883. this.registerType('torch.distributions.normal.Normal', class {});
  7884. this.registerType('torch.distributions.transforms._InverseTransform', class {});
  7885. this.registerType('torch.distributions.transforms.AffineTransform', class {});
  7886. this.registerType('torch.distributions.transforms.ComposeTransform', class {});
  7887. this.registerType('torch.distributions.transforms.ExpTransform', class {});
  7888. this.registerType('torch.distributions.transforms.LowerCholeskyTransform', class {});
  7889. this.registerType('torch.distributions.uniform.Uniform', class {});
  7890. this.registerType('torch.nn.backends.thnn._get_thnn_function_backend', class {});
  7891. this.registerType('torch.nn.intrinsic.modules.fused._FusedModule', class {});
  7892. this.registerType('torch.nn.intrinsic.modules.fused.ConvBnReLU2d', class {});
  7893. this.registerType('torch.nn.intrinsic.modules.fused.ConvReLU2d', class {});
  7894. this.registerType('torch.nn.intrinsic.modules.fused.BNReLU2d', class {});
  7895. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvBn2d', class {});
  7896. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU2d', class {});
  7897. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvReLU2d', class {});
  7898. this.registerType('torch.nn.intrinsic.quantized.modules.bn_relu.BNReLU2d', class {});
  7899. this.registerType('torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU1d', class {});
  7900. this.registerType('torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', class {});
  7901. this.registerType('torch.nn.intrinsic.quantized.modules.linear_relu.LinearReLU', class {});
  7902. this.registerType('torch.nn.modules.activation.CELU', class extends torch.nn.modules.module.Module {});
  7903. this.registerType('torch.nn.modules.activation.ELU', class extends torch.nn.modules.module.Module {});
  7904. this.registerType('torch.nn.modules.activation.GELU', class extends torch.nn.modules.module.Module {});
  7905. this.registerType('torch.nn.modules.activation.GLU', class extends torch.nn.modules.module.Module {});
  7906. this.registerType('torch.nn.modules.activation.Hardtanh', class extends torch.nn.modules.module.Module {});
  7907. this.registerType('torch.nn.modules.activation.Hardshrink', class extends torch.nn.modules.module.Module {});
  7908. this.registerType('torch.nn.modules.activation.Hardsigmoid', class extends torch.nn.modules.module.Module {});
  7909. this.registerType('torch.nn.modules.activation.Hardswish', class extends torch.nn.modules.module.Module {});
  7910. this.registerType('torch.nn.modules.activation.LeakyReLU', class extends torch.nn.modules.module.Module {});
  7911. this.registerType('torch.nn.modules.activation.LogSigmoid', class extends torch.nn.modules.module.Module {});
  7912. this.registerType('torch.nn.modules.activation.LogSoftmax', class extends torch.nn.modules.module.Module {});
  7913. this.registerType('torch.nn.modules.activation.Mish', class extends torch.nn.modules.module.Module {});
  7914. this.registerType('torch.nn.modules.activation.MultiheadAttention', class extends torch.nn.modules.module.Module {});
  7915. this.registerType('torch.nn.modules.activation.ReLU', class extends torch.nn.modules.module.Module {});
  7916. this.registerType('torch.nn.modules.activation.ReLU6', class extends torch.nn.modules.module.Module {});
  7917. this.registerType('torch.nn.modules.activation.PReLU', class extends torch.nn.modules.module.Module {});
  7918. this.registerType('torch.nn.modules.activation.RReLU', class extends torch.nn.modules.module.Module {});
  7919. this.registerType('torch.nn.modules.activation.SELU', class extends torch.nn.modules.module.Module {});
  7920. this.registerType('torch.nn.modules.activation.Sigmoid', class extends torch.nn.modules.module.Module {});
  7921. this.registerType('torch.nn.modules.activation.SiLU', class extends torch.nn.modules.module.Module {});
  7922. this.registerType('torch.nn.modules.activation.Softmax', class extends torch.nn.modules.module.Module {});
  7923. this.registerType('torch.nn.modules.activation.Softmax2d', class extends torch.nn.modules.module.Module {});
  7924. this.registerType('torch.nn.modules.activation.Softmin', class extends torch.nn.modules.module.Module {});
  7925. this.registerType('torch.nn.modules.activation.Softplus', class extends torch.nn.modules.module.Module {});
  7926. this.registerType('torch.nn.modules.activation.Softshrink', class extends torch.nn.modules.module.Module {});
  7927. this.registerType('torch.nn.modules.activation.Softsign', class extends torch.nn.modules.module.Module {});
  7928. this.registerType('torch.nn.modules.activation.Tanh', class extends torch.nn.modules.module.Module {});
  7929. this.registerType('torch.nn.modules.activation.Tanhshrink', class extends torch.nn.modules.module.Module {});
  7930. this.registerType('torch.nn.modules.activation.Threshold', class extends torch.nn.modules.module.Module {});
  7931. this.registerType('torch.nn.modules.adaptive.AdaptiveLogSoftmaxWithLoss', class {});
  7932. this.registerType('torch.nn.modules.batchnorm._NormBase', class extends torch.nn.modules.module.Module {});
  7933. this.registerType('torch.nn.modules.batchnorm._BatchNorm', class extends torch.nn.modules.batchnorm._NormBase {});
  7934. this.registerType('torch.nn.modules.batchnorm.BatchNorm1d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  7935. this.registerType('torch.nn.modules.batchnorm.BatchNorm2d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  7936. this.registerType('torch.nn.modules.batchnorm.BatchNorm3d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  7937. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm1d', class {});
  7938. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm2d', class {});
  7939. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm3d', class {});
  7940. this.registerType('torch.nn.modules.batchnorm.SyncBatchNorm', class {});
  7941. this.registerType('torch.nn.modules.byted_batchnorm.BytedBatchNorm2d', class {});
  7942. this.registerType('torch.nn.modules.channelshuffle.ChannelShuffle', class {});
  7943. this.registerType('torch.nn.modules.container.ModuleDict', class extends torch.nn.modules.module.Module {});
  7944. this.registerType('torch.nn.modules.container.ModuleList', class extends torch.nn.modules.module.Module {});
  7945. this.registerType('torch.nn.modules.container.ParameterDict', class extends torch.nn.modules.module.Module {});
  7946. this.registerType('torch.nn.modules.container.ParameterList', class extends torch.nn.modules.module.Module {});
  7947. this.registerType('torch.nn.modules.container.Sequential', class extends torch.nn.modules.module.Module {});
  7948. this.registerType('torch.nn.modules.conv._ConvNd', class extends torch.nn.modules.module.Module {});
  7949. this.registerType('torch.nn.modules.conv.Conv1d', class extends torch.nn.modules.conv._ConvNd {});
  7950. this.registerType('torch.nn.modules.conv.Conv2d', class extends torch.nn.modules.conv._ConvNd {});
  7951. this.registerType('torch.nn.modules.conv.Conv3d', class extends torch.nn.modules.conv._ConvNd {});
  7952. this.registerType('torch.nn.modules.conv._ConvTransposeNd', class extends torch.nn.modules.module.Module {});
  7953. this.registerType('torch.nn.modules.conv.ConvTranspose1d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  7954. this.registerType('torch.nn.modules.conv.ConvTranspose2d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  7955. this.registerType('torch.nn.modules.conv.ConvTranspose3d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  7956. this.registerType('torch.nn.modules.conv.LazyConv1d', class {});
  7957. this.registerType('torch.nn.modules.conv.LazyConv2d', class {});
  7958. this.registerType('torch.nn.modules.conv.LazyConv3d', class {});
  7959. this.registerType('torch.nn.modules.conv.LazyConvTranspose2d', class {});
  7960. this.registerType('torch.nn.modules.conv.LazyConvTranspose3d', class {});
  7961. this.registerType('torch.nn.modules.distance.CosineSimilarity', class extends torch.nn.modules.module.Module {});
  7962. this.registerType('torch.nn.modules.distance.PairwiseDistance', class extends torch.nn.modules.module.Module {});
  7963. this.registerType('torch.nn.modules.dropout._DropoutNd', class extends torch.nn.modules.module.Module {});
  7964. this.registerType('torch.nn.modules.dropout.AlphaDropout', class extends torch.nn.modules.dropout._DropoutNd {});
  7965. this.registerType('torch.nn.modules.dropout.Dropout', class extends torch.nn.modules.dropout._DropoutNd {});
  7966. this.registerType('torch.nn.modules.dropout.Dropout1d', class extends torch.nn.modules.dropout._DropoutNd {});
  7967. this.registerType('torch.nn.modules.dropout.Dropout2d', class extends torch.nn.modules.dropout._DropoutNd {});
  7968. this.registerType('torch.nn.modules.dropout.Dropout3d', class extends torch.nn.modules.dropout._DropoutNd {});
  7969. this.registerType('torch.nn.modules.dropout.FeatureAlphaDropout', class extends torch.nn.modules.dropout._DropoutNd {});
  7970. this.registerType('torch.nn.modules.fold.Fold', class extends torch.nn.modules.module.Module {});
  7971. this.registerType('torch.nn.modules.fold.Unfold', class extends torch.nn.modules.module.Module {});
  7972. this.registerType('torch.nn.modules.flatten.Flatten', class extends torch.nn.modules.module.Module {});
  7973. this.registerType('torch.nn.modules.flatten.Unflatten', class extends torch.nn.modules.module.Module {});
  7974. this.registerType('torch.nn.modules.instancenorm.InstanceNorm1d', class {});
  7975. this.registerType('torch.nn.modules.instancenorm.InstanceNorm2d', class {});
  7976. this.registerType('torch.nn.modules.instancenorm.InstanceNorm3d', class {});
  7977. this.registerType('torch.nn.modules.instancenorm.LazyInstanceNorm2d', class {});
  7978. this.registerType('torch.nn.modules.instancenorm.LazyInstanceNorm3d', class {});
  7979. this.registerType('torch.nn.modules.linear._LinearWithBias', class {});
  7980. this.registerType('torch.nn.modules.linear.Bilinear', class extends torch.nn.modules.module.Module {});
  7981. this.registerType('torch.nn.modules.linear.Identity', class extends torch.nn.modules.module.Module {});
  7982. this.registerType('torch.nn.modules.linear.LazyLinear', class extends torch.nn.modules.module.Module {});
  7983. this.registerType('torch.nn.modules.linear.Linear', class extends torch.nn.modules.module.Module {});
  7984. this.registerType('torch.nn.modules.linear.NonDynamicallyQuantizableLinear', class extends torch.nn.modules.linear.Linear {});
  7985. this.registerType('torch.nn.modules.loss._Loss', class extends torch.nn.modules.module.Module {});
  7986. this.registerType('torch.nn.modules.loss._WeightedLoss', class extends torch.nn.modules.loss._Loss {});
  7987. this.registerType('torch.nn.modules.loss.BCELoss', class extends torch.nn.modules.loss._WeightedLoss {});
  7988. this.registerType('torch.nn.modules.loss.BCEWithLogitsLoss', class extends torch.nn.modules.loss._Loss {});
  7989. this.registerType('torch.nn.modules.loss.CrossEntropyLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  7990. this.registerType('torch.nn.modules.loss.CosineEmbeddingLoss', class extends torch.nn.modules.loss._Loss {});
  7991. this.registerType('torch.nn.modules.loss.CTCLoss', class extends torch.nn.modules.loss._Loss {});
  7992. this.registerType('torch.nn.modules.loss.GaussianNLLLoss', class extends torch.nn.modules.loss._Loss {});
  7993. this.registerType('torch.nn.modules.loss.HuberLoss', class extends torch.nn.modules.loss._Loss {});
  7994. this.registerType('torch.nn.modules.loss.HingeEmbeddingLoss', class extends torch.nn.modules.loss._Loss {});
  7995. this.registerType('torch.nn.modules.loss.KLDivLoss', class extends torch.nn.modules.loss._Loss {});
  7996. this.registerType('torch.nn.modules.loss.L1Loss', class extends torch.nn.modules.loss._Loss {});
  7997. this.registerType('torch.nn.modules.loss.MarginRankingLoss', class extends torch.nn.modules.loss._Loss {});
  7998. this.registerType('torch.nn.modules.loss.MultiLabelMarginLoss', class extends torch.nn.modules.loss._Loss {});
  7999. this.registerType('torch.nn.modules.loss.MultiLabelSoftMarginLoss', class extends torch.nn.modules.loss._Loss {});
  8000. this.registerType('torch.nn.modules.loss.MultiMarginLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  8001. this.registerType('torch.nn.modules.loss.MSELoss', class extends torch.nn.modules.loss._Loss {});
  8002. this.registerType('torch.nn.modules.loss.NLLLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  8003. this.registerType('torch.nn.modules.loss.NLLLoss2d', class extends torch.nn.modules.loss.NLLLoss {});
  8004. this.registerType('torch.nn.modules.loss.PoissonNLLLoss', class {});
  8005. this.registerType('torch.nn.modules.loss.SmoothL1Loss', class {});
  8006. this.registerType('torch.nn.modules.loss.SoftMarginLoss', class {});
  8007. this.registerType('torch.nn.modules.loss.TripletMarginLoss', class {});
  8008. this.registerType('torch.nn.modules.loss.TripletMarginWithDistanceLoss', class {});
  8009. this.registerType('torch.nn.modules.module._IncompatibleKeys', class {});
  8010. this.registerType('torch.nn.modules.module._WrappedHook', class {});
  8011. this.registerType('torch.nn.modules.module.PatchForward', class {});
  8012. this.registerType('torch.nn.modules.normalization.CrossMapLRN2d', class {});
  8013. this.registerType('torch.nn.modules.normalization.GroupNorm', class extends torch.nn.modules.module.Module {});
  8014. this.registerType('torch.nn.modules.normalization.LayerNorm', class extends torch.nn.modules.module.Module {});
  8015. this.registerType('torch.nn.modules.normalization.LocalResponseNorm', class {});
  8016. this.registerType('torch.nn.modules.normalization.RMSNorm', class {});
  8017. this.registerType('torch.nn.modules.padding._ReflectionPadNd', class extends torch.nn.modules.module.Module {});
  8018. this.registerType('torch.nn.modules.padding.ReflectionPad1d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  8019. this.registerType('torch.nn.modules.padding.ReflectionPad2d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  8020. this.registerType('torch.nn.modules.padding.ReflectionPad3d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  8021. this.registerType('torch.nn.modules.padding._ReplicationPadNd', class extends torch.nn.modules.module.Module {});
  8022. this.registerType('torch.nn.modules.padding.ReplicationPad1d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  8023. this.registerType('torch.nn.modules.padding.ReplicationPad2d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  8024. this.registerType('torch.nn.modules.padding.ReplicationPad3d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  8025. this.registerType('torch.nn.modules.padding.ZeroPad1d', class {});
  8026. this.registerType('torch.nn.modules.padding.ZeroPad2d', class {});
  8027. this.registerType('torch.nn.modules.padding.ZeroPad3d', class {});
  8028. this.registerType('torch.nn.modules.padding.ConstantPad1d', class {});
  8029. this.registerType('torch.nn.modules.padding.ConstantPad2d', class {});
  8030. this.registerType('torch.nn.modules.padding.ConstantPad3d', class {});
  8031. this.registerType('torch.nn.modules.padding.CircularPad3d', class {});
  8032. this.registerType('torch.nn.modules.pixelshuffle.PixelShuffle', class {});
  8033. this.registerType('torch.nn.modules.pixelshuffle.PixelUnshuffle', class {});
  8034. this.registerType('torch.nn.modules.pooling._AdaptiveAvgPoolNd', class extends torch.nn.modules.module.Module {});
  8035. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool1d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  8036. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool2d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  8037. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool3d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  8038. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool1d', class {});
  8039. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool2d', class {});
  8040. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool3d', class {});
  8041. this.registerType('torch.nn.modules.pooling.AvgPool1d', class {});
  8042. this.registerType('torch.nn.modules.pooling.AvgPool2d', class {});
  8043. this.registerType('torch.nn.modules.pooling.AvgPool3d', class {});
  8044. this.registerType('torch.nn.modules.pooling.FractionalMaxPool2d', class {});
  8045. this.registerType('torch.nn.modules.pooling.FractionalMaxPool3d', class {});
  8046. this.registerType('torch.nn.modules.pooling.LPPool1d', class {});
  8047. this.registerType('torch.nn.modules.pooling.LPPool2d', class {});
  8048. this.registerType('torch.nn.modules.pooling.LPPool3d', class {});
  8049. this.registerType('torch.nn.modules.pooling._MaxPoolNd', class extends torch.nn.modules.module.Module {});
  8050. this.registerType('torch.nn.modules.pooling.MaxPool1d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  8051. this.registerType('torch.nn.modules.pooling.MaxPool2d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  8052. this.registerType('torch.nn.modules.pooling.MaxPool3d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  8053. this.registerType('torch.nn.modules.pooling._MaxUnpoolNd', class extends torch.nn.modules.module.Module {});
  8054. this.registerType('torch.nn.modules.pooling.MaxUnpool1d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  8055. this.registerType('torch.nn.modules.pooling.MaxUnpool2d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  8056. this.registerType('torch.nn.modules.pooling.MaxUnpool3d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  8057. this.registerType('torch.nn.modules.rnn.GRU', class {});
  8058. this.registerType('torch.nn.modules.rnn.GRUCell', class {});
  8059. this.registerType('torch.nn.modules.rnn.LSTM', class {});
  8060. this.registerType('torch.nn.modules.rnn.LSTMCell', class {});
  8061. this.registerType('torch.nn.modules.rnn.RNNBase', class extends torch.nn.modules.module.Module {});
  8062. this.registerType('torch.nn.modules.rnn.RNN', class extends torch.nn.modules.rnn.RNNBase {});
  8063. this.registerType('torch.nn.modules.rnn.RNNCellBase', class extends torch.nn.modules.module.Module {});
  8064. this.registerType('torch.nn.modules.rnn.RNNCell', class extends torch.nn.modules.rnn.RNNCellBase {});
  8065. this.registerType('torch.nn.modules.sparse.Embedding', class {});
  8066. this.registerType('torch.nn.modules.sparse.EmbeddingBag', class {});
  8067. this.registerType('torch.nn.modules.transformer.Transformer', class {});
  8068. this.registerType('torch.nn.modules.transformer.TransformerDecoder', class {});
  8069. this.registerType('torch.nn.modules.transformer.TransformerDecoderLayer', class {});
  8070. this.registerType('torch.nn.modules.transformer.TransformerEncoder', class {});
  8071. this.registerType('torch.nn.modules.transformer.TransformerEncoderLayer', class {});
  8072. this.registerType('torch.nn.modules.upsampling.Upsample', class {});
  8073. this.registerType('torch.nn.modules.upsampling.UpsamplingBilinear2d', class {});
  8074. this.registerType('torch.nn.modules.upsampling.UpsamplingNearest2d', class {});
  8075. this.registerType('torch.nn.parallel.data_parallel.DataParallel', class {});
  8076. this.registerType('torch.nn.parallel.distributed._DDPUnevenInputsConfig', class {});
  8077. this.registerType('torch.nn.parallel.distributed.DistributedDataParallel', class {});
  8078. this.registerType('torch.nn.qat.modules.conv.Conv2d', class {});
  8079. this.registerType('torch.nn.qat.modules.linear.Linear', class {});
  8080. this.registerType('torch.nn.quantized.modules.activation.ReLU', class {});
  8081. this.registerType('torch.nn.quantized.modules.activation.LeakyReLU', class {});
  8082. this.registerType('torch.nn.quantized.modules.activation.Softmax', class {});
  8083. this.registerType('torch.nn.quantized.dynamic.modules.linear.Linear', class {});
  8084. this.registerType('torch.nn.quantized.dynamic.modules.rnn.GRU', class {});
  8085. this.registerType('torch.nn.quantized.dynamic.modules.rnn.LSTM', class {});
  8086. this.registerType('torch.nn.quantized.dynamic.modules.rnn.LSTMCell', class {});
  8087. this.registerType('torch.nn.quantized.dynamic.modules.rnn.PackedParameter', class {});
  8088. this.registerType('torch.nn.quantized.modules.activation.ReLU6', class {});
  8089. this.registerType('torch.nn.quantized.modules.batchnorm.BatchNorm2d', class {});
  8090. this.registerType('torch.nn.quantized.modules.conv.Conv1d', class {});
  8091. this.registerType('torch.nn.quantized.modules.conv.Conv2d', class {});
  8092. this.registerType('torch.nn.quantized.modules.conv.ConvTranspose2d', class {});
  8093. this.registerType('torch.nn.quantized.modules.DeQuantize', class {});
  8094. this.registerType('torch.nn.quantized.modules.dropout.Dropout', class {});
  8095. this.registerType('torch.nn.quantized.modules.embedding_ops.Embedding', class {});
  8096. this.registerType('torch.nn.quantized.modules.embedding_ops.EmbeddingPackedParams', class {});
  8097. this.registerType('torch.nn.quantized.modules.functional_modules.FloatFunctional', class {});
  8098. this.registerType('torch.nn.quantized.modules.functional_modules.QFunctional', class {});
  8099. this.registerType('torch.nn.quantized.modules.linear.Linear', class {});
  8100. this.registerType('torch.nn.quantized.modules.linear.LinearPackedParams', class {});
  8101. this.registerType('torch.nn.quantized.modules.normalization.InstanceNorm2d', class {});
  8102. this.registerType('torch.nn.quantized.modules.normalization.GroupNorm', class extends torch.nn.modules.normalization.GroupNorm {});
  8103. this.registerType('torch.nn.quantized.modules.normalization.LayerNorm', class extends torch.nn.modules.normalization.LayerNorm {});
  8104. this.registerType('torch.nn.quantized.modules.Quantize', class {});
  8105. this.registerType('torch.ao.nn.quantizable.modules.activation.MultiheadAttention', class extends torch.nn.modules.activation.MultiheadAttention {});
  8106. this.registerType('torch.ao.nn.quantizable.modules.rnn._LSTMLayer', class {});
  8107. this.registerType('torch.ao.nn.quantizable.modules.rnn._LSTMSingleLayer', class {});
  8108. this.registerType('torch.ao.nn.quantizable.modules.rnn.LSTM', class {});
  8109. this.registerType('torch.ao.nn.quantizable.modules.rnn.LSTMCell', class {});
  8110. this.registerType('torch.ao.nn.quantized.modules.activation.ELU', class extends torch.nn.modules.activation.ELU {});
  8111. this.registerType('torch.ao.nn.quantized.modules.activation.Hardswish', class extends torch.nn.modules.activation.Hardswish {});
  8112. this.registerType('torch.ao.nn.quantized.modules.activation.MultiheadAttention', class extends torch.ao.nn.quantizable.modules.activation.MultiheadAttention {});
  8113. this.registerType('torch.ao.nn.quantized.modules.activation.PReLU', class extends torch.nn.modules.module.Module {});
  8114. this.registerType('torch.ao.nn.quantized.modules.activation.ReLU6', class extends torch.nn.modules.activation.ReLU {});
  8115. this.registerType('torch.ao.nn.quantized.modules.activation.LeakyReLU', class extends torch.nn.modules.activation.LeakyReLU {});
  8116. this.registerType('torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule', class extends torch.nn.modules.module.Module {});
  8117. this.registerType('torch.ao.nn.quantized.modules.batchnorm._BatchNorm', class extends torch.nn.modules.batchnorm._BatchNorm {});
  8118. this.registerType('torch.ao.nn.quantized.modules.batchnorm.BatchNorm2d', class extends torch.ao.nn.quantized.modules.batchnorm._BatchNorm {});
  8119. this.registerType('torch.ao.nn.quantized.modules.conv.Conv1d', class extends torch.nn.modules.module.Module {});
  8120. this.registerType('torch.ao.nn.quantized.modules.conv.Conv2d', class extends torch.nn.modules.module.Module {});
  8121. this.registerType('torch.ao.nn.quantized.modules.conv._ConvNd', class extends torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule {});
  8122. this.registerType('torch.ao.nn.quantized.modules.conv._ConvTransposeNd', class extends torch.ao.nn.quantized.modules.conv._ConvNd {});
  8123. this.registerType('torch.ao.nn.quantized.modules.conv.ConvTranspose1d', class extends torch.ao.nn.quantized.modules.conv._ConvTransposeNd {});
  8124. this.registerType('torch.ao.nn.quantized.modules.conv.ConvTranspose2d', class extends torch.ao.nn.quantized.modules.conv._ConvTransposeNd {});
  8125. this.registerType('torch.ao.nn.quantized.modules.Quantize', class extends torch.nn.modules.module.Module {});
  8126. this.registerType('torch.ao.nn.quantized.modules.DeQuantize', class extends torch.nn.modules.module.Module {});
  8127. this.registerType('torch.ao.nn.quantized.modules.dropout.Dropout', class extends torch.nn.modules.dropout.Dropout {});
  8128. this.registerType('torch.ao.nn.quantized.modules.embedding_ops.Embedding', class extends torch.nn.modules.module.Module {});
  8129. this.registerType('torch.ao.nn.quantized.modules.embedding_ops.EmbeddingPackedParams', class extends torch.nn.modules.module.Module {});
  8130. this.registerType('torch.ao.nn.quantized.modules.functional_modules.FloatFunctional', class extends torch.nn.modules.module.Module {});
  8131. this.registerType('torch.ao.nn.quantized.modules.functional_modules.QFunctional', class extends torch.nn.modules.module.Module {});
  8132. this.registerType('torch.ao.nn.quantized.modules.functional_modules.FXFloatFunctional', class extends torch.nn.modules.module.Module {});
  8133. this.registerType('torch.ao.nn.quantized.modules.linear.Linear', class extends torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule {});
  8134. this.registerType('torch.ao.nn.quantized.modules.linear.LinearPackedParams', class extends torch.nn.modules.module.Module {});
  8135. this.registerType('torch.ao.nn.quantized.modules.normalization.LayerNorm', class extends torch.nn.modules.normalization.LayerNorm {});
  8136. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm1d', class extends torch.nn.modules.instancenorm.InstanceNorm1d {});
  8137. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm2d', class extends torch.nn.modules.instancenorm.InstanceNorm2d {});
  8138. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm3d', class extends torch.nn.modules.instancenorm.InstanceNorm3d {});
  8139. this.registerType('torch.ao.nn.quantized.modules.rnn.LSTM', class {});
  8140. this.registerType('torch.ao.nn.quantized.dynamic.modules.linear.Linear', class extends torch.ao.nn.quantized.modules.linear.Linear {});
  8141. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.PackedParameter', class extends torch.nn.modules.module.Module {});
  8142. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase', class extends torch.nn.modules.module.Module {});
  8143. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.GRU', class extends torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase {});
  8144. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.LSTM', class extends torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase {});
  8145. this.registerType('torch.ao.nn.quantized.reference.modules.conv.Conv1d', class {});
  8146. this.registerType('torch.ao.nn.quantized.reference.modules.conv.Conv2d', class {});
  8147. this.registerType('torch.ao.nn.quantized.reference.modules.linear.Linear', class {});
  8148. this.registerType('torch.ao.nn.qat.modules.conv.Conv2d', class {});
  8149. this.registerType('torch.ao.nn.qat.modules.linear.Linear', class {});
  8150. this.registerType('torch.ao.nn.intrinsic.quantized.modules.conv_relu.ConvReLU1d', class extends torch.ao.nn.quantized.modules.conv.Conv1d {});
  8151. this.registerType('torch.ao.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', class extends torch.ao.nn.quantized.modules.conv.Conv2d {});
  8152. this.registerType('torch.ao.nn.intrinsic.quantized.modules.linear_relu.LinearReLU', class extends torch.ao.nn.quantized.modules.linear.Linear {});
  8153. this.registerType('torch.ao.nn.intrinsic.quantized.modules.bn_relu.BNReLU2d', class extends torch.ao.nn.quantized.modules.batchnorm.BatchNorm2d {});
  8154. this.registerType('torch.ao.nn.intrinsic.modules.fused._FusedModule', class extends torch.nn.modules.container.Sequential {});
  8155. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvBn2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8156. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvReLU1d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8157. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvReLU2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8158. this.registerType('torch.ao.nn.intrinsic.modules.fused.LinearReLU', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8159. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvBnReLU2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8160. this.registerType('torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU2d', class {});
  8161. this.registerType('torch.nn.utils.prune.CustomFromMask', class {});
  8162. this.registerType('torch.nn.utils.prune.Identity', class {});
  8163. this.registerType('torch.nn.utils.prune.L1Unstructured', class {});
  8164. this.registerType('torch.nn.utils.prune.LnStructured', class {});
  8165. this.registerType('torch.nn.utils.prune.PruningContainer', class {});
  8166. this.registerType('torch.nn.utils.prune.RandomUnstructured', class {});
  8167. this.registerType('torch.nn.utils.spectral_norm.SpectralNorm', class {});
  8168. this.registerType('torch.nn.utils.spectral_norm.SpectralNormStateDictHook', class {});
  8169. this.registerType('torch.nn.utils.spectral_norm.SpectralNormLoadStateDictPreHook', class {});
  8170. this.registerType('torch.nn.utils.weight_norm.WeightNorm', class {});
  8171. this.registerFunction('torch.nn.utils.parametrize.type_before_parametrizations');
  8172. this.registerType('torch.nn.utils.parametrize.ParametrizationList', class extends torch.nn.modules.container.ModuleList {});
  8173. this.registerType('torch.torch_version.TorchVersion', class extends String {});
  8174. this.registerType('torch.optim.optimizer.Optimizer', class {});
  8175. this.registerType('torch.optim.adam.Adam', class extends torch.optim.optimizer.Optimizer {});
  8176. this.registerType('torch.optim.adamw.AdamW', class {});
  8177. this.registerType('torch.optim.adagrad.Adagrad', class {});
  8178. this.registerType('torch.optim.adadelta.Adadelta', class {});
  8179. this.registerType('torch.optim.lbfgs.LBFGS', class {});
  8180. this.registerType('torch.optim.lr_scheduler.CosineAnnealingLR', class {});
  8181. this.registerType('torch.optim.lr_scheduler.CosineAnnealingWarmRestarts', class {});
  8182. this.registerType('torch.optim.lr_scheduler.CyclicLR', class {});
  8183. this.registerType('torch.optim.lr_scheduler.ExponentialLR', class {});
  8184. this.registerType('torch.optim.lr_scheduler.LambdaLR', class {});
  8185. this.registerType('torch.optim.lr_scheduler.LinearLR', class {});
  8186. this.registerType('torch.optim.lr_scheduler.MultiStepLR', class {});
  8187. this.registerType('torch.optim.lr_scheduler.OneCycleLR', class {});
  8188. this.registerType('torch.optim.lr_scheduler.ReduceLROnPlateau', class {});
  8189. this.registerType('torch.optim.lr_scheduler.StepLR', class {});
  8190. this.registerType('torch.optim.optimizer._RequiredParameter', class {});
  8191. this.registerType('torch.optim.radam.RAdam', class extends torch.optim.optimizer.Optimizer {});
  8192. this.registerType('torch.optim.rmsprop.RMSprop', class {});
  8193. this.registerType('torch.optim.sgd.SGD', class {});
  8194. this.registerType('torch.optim.sparse_adam.SparseAdam', class {});
  8195. this.registerType('torch.optim.swa_utils.SWALR', class {});
  8196. torch.optim.RAdam = torch.optim.radam.RAdam;
  8197. this.registerType('torch.quantization.fake_quantize.FakeQuantize', class {});
  8198. this.registerFunction('torch.quantization.fx.graph_module._save_packed_weight');
  8199. this.registerType('torch.quantization.observer._PartialWrapper', class {});
  8200. this.registerType('torch.quantization.observer.HistogramObserver', class {});
  8201. this.registerType('torch.quantization.observer.MinMaxObserver', class {});
  8202. this.registerType('torch.quantization.observer.MovingAverageMinMaxObserver', class {});
  8203. this.registerType('torch.quantization.observer.MovingAveragePerChannelMinMaxObserver', class {});
  8204. this.registerFunction('torch.quantization.observer._with_args');
  8205. this.registerType('torch.quantization.qconfig.QConfig', class {});
  8206. this.registerType('torch.quantization.stubs.DeQuantStub', class {});
  8207. this.registerType('torch.quantization.stubs.QuantStub', class {});
  8208. this.registerType('torch.utils._pytree.LeafSpec', class {});
  8209. this.registerType('torch.utils._pytree.TreeSpec', class {});
  8210. this.registerType('torch.utils._python_dispatch.TorchDispatchMode', class {
  8211. __enter__() {
  8212. return this;
  8213. }
  8214. __exit__(/* exc_type, exc_value, traceback */) {
  8215. }
  8216. });
  8217. this.registerFunction('torch.utils._pytree.tree_map');
  8218. torch.nn.Sequential = torch.nn.modules.container.Sequential;
  8219. this.registerFunction('torch.fx.experimental.sym_node.SymNode', class {
  8220. constructor(expr, shape_env, pytype, hint, constant, fx_node, optimized_summation) {
  8221. this._expr = expr;
  8222. this.shape_env = shape_env;
  8223. this.pytype = pytype;
  8224. this._optimized_summation = optimized_summation;
  8225. this._hint = hint;
  8226. this.constant = constant;
  8227. const tx_validation_en = this.shape_env && this.shape_env._translation_validation_enabled ? true : false;
  8228. this.fx_node = tx_validation_en && fx_node ? fx_node : null;
  8229. }
  8230. __str__() {
  8231. return this._expr.__str__();
  8232. }
  8233. });
  8234. this.registerType('torch.fx.experimental.symbolic_shapes.ShapeEnv', class {
  8235. constructor() {
  8236. this.var_to_val = new Map();
  8237. this.var_to_stack = new Map();
  8238. }
  8239. add_var_to_val(expr, val) {
  8240. this.var_to_val.set(expr, new sympy.core.numbers.Integer(val));
  8241. }
  8242. constrain_symbol_range(/* s, compiler_min, compiler_max */) {
  8243. }
  8244. create_symintnode(sym, hint, source) {
  8245. let out = null;
  8246. let fx_node = null;
  8247. if (this._translation_validation_enabled && source !== null) {
  8248. throw new python.Error('Not implemented.');
  8249. } else {
  8250. fx_node = null;
  8251. }
  8252. if (builtins.isinstance(sym, sympy.core.numbers.Integer)) {
  8253. out = builtins.int(sym);
  8254. if (hint !== null && out !== hint) {
  8255. throw new python.Error(`Symbolic integer has value '${out}' but expected '${hint}'.`);
  8256. }
  8257. } else {
  8258. // if free_unbacked_symbols(sym):
  8259. // hint = None
  8260. out = new torch.SymInt(new torch.fx.experimental.sym_node.SymNode(sym, this, builtins.int, hint, null, fx_node));
  8261. }
  8262. return out;
  8263. }
  8264. create_symboolnode(sym) {
  8265. return new torch.SymBool(new torch.fx.experimental.sym_node.SymNode(sym, this, builtins.bool, null));
  8266. }
  8267. });
  8268. this.registerFunction('torch.fx.experimental.symbolic_shapes.symbol_is_type', (/* sym, prefix */) => {
  8269. /*
  8270. assert isinstance(sym, sympy.Symbol)
  8271. const name_str = sym.name.toLowerCase();
  8272. if (builtins.isinstance(prefix, torch.utils._sympy.symbol.SymT)) {
  8273. return name_str.startsWith(prefix_str[prefix])
  8274. }
  8275. return name_str.startswith(tuple(prefix_str[p] for p in prefix));
  8276. */
  8277. return false;
  8278. });
  8279. this.registerType('torch.fx.proxy.TracerBase', class {
  8280. constructor() {
  8281. this.traced_func_name = 'forward';
  8282. }
  8283. });
  8284. this.registerType('torch.fx._symbolic_trace.Tracer', class extends torch.fx.proxy.TracerBase {
  8285. trace(root /*, concrete_args */) {
  8286. let fn = null;
  8287. if (root instanceof torch.nn.Module) {
  8288. // torch.fx._lazy_graph_module._LazyGraphModule.force_recompile(root)
  8289. this.root = root;
  8290. fn = builtins.getattr(new builtins.type(root), this.traced_func_name);
  8291. this.root_module_name = root._get_name();
  8292. this.submodule_paths = new builtins.dict(root.named_modules());
  8293. } else {
  8294. this.root = new torch.nn.Module();
  8295. fn = root;
  8296. }
  8297. const tracer_cls = builtins.getattr(this, '__class__', null);
  8298. this.graph = new torch.fx.graph.Graph(null, tracer_cls);
  8299. if (builtins.hasattr(this, '__code__')) {
  8300. const code = fn.__code__;
  8301. this.graph._co_fields = {
  8302. co_name: code.co_name,
  8303. co_filename: code.co_filename,
  8304. co_firstlineno: code.co_firstlineno,
  8305. };
  8306. }
  8307. return this.graph;
  8308. }
  8309. is_leaf_module(m /*, module_qualified_name */) {
  8310. return (m.__module__.startsWith('torch.nn') || m.__module__.startsWith('torch.ao.nn')) && m instanceof torch.nn.Sequential === false;
  8311. }
  8312. });
  8313. this.registerType('torch.fx.experimental.proxy_tensor.PythonKeyTracer', class extends torch.fx._symbolic_trace.Tracer {});
  8314. this.registerType('torch.fx.experimental.proxy_tensor._ModuleStackTracer', class extends torch.fx.experimental.proxy_tensor.PythonKeyTracer {});
  8315. this.registerFunction('torch.fx._lazy_graph_module._make_graph_module', (...args) => {
  8316. const graph_module_cls = args.pop() || torch.fx.graph_module.GraphModule;
  8317. return new graph_module_cls(...args);
  8318. });
  8319. this.registerFunction('torch.fx.graph_module._deserialize_graph_module', (forward, body, graph_module_cls) => {
  8320. let tracer_cls = body.get('_tracer_cls');
  8321. if (!tracer_cls) {
  8322. tracer_cls = torch.fx._symbolic_trace.Tracer;
  8323. }
  8324. const graphmodule_cls_name = body.get('_graphmodule_cls_name', 'GraphModule');
  8325. const cls_tracer = tracer_cls;
  8326. const KeepModules = class extends cls_tracer {
  8327. is_leaf_module() {
  8328. return true;
  8329. }
  8330. };
  8331. const com = new torch.fx.graph_module._CodeOnlyModule(body);
  8332. const tracer_extras = body.get('_tracer_extras', new builtins.dict());
  8333. const graph = new KeepModules().trace(com, tracer_extras);
  8334. graph._tracer_cls = tracer_cls;
  8335. const gm = torch.fx._lazy_graph_module._make_graph_module(com, graph, graphmodule_cls_name, graph_module_cls);
  8336. for (const [k, v] of body.items()) {
  8337. if (!builtins.hasattr(gm, k)) {
  8338. builtins.setattr(gm, k, v);
  8339. }
  8340. }
  8341. return gm;
  8342. });
  8343. this.registerFunction('torch.fx.graph_module._forward_from_src', (src, globals /*, co_fields */) => {
  8344. globals = { ...globals };
  8345. const context = new python.Execution.Context(globals, null);
  8346. execution.exec(src, context);
  8347. const forward_fn = globals.forward;
  8348. delete globals.forward;
  8349. return forward_fn;
  8350. });
  8351. this.registerFunction('torch.fx.graph_module.reduce_graph_module', (body, import_block) => {
  8352. // https://github.com/pytorch/pytorch/blob/master/torch/fx/graph_module.py
  8353. let fn_src = null;
  8354. if (body.has('_code')) {
  8355. fn_src = body.get('_code');
  8356. } else if (body.has('code')) {
  8357. fn_src = body.get('code');
  8358. } else {
  8359. fn_src = body._code || body.code;
  8360. }
  8361. const forward = torch.fx.graph_module._forward_from_src(import_block + fn_src, {});
  8362. return torch.fx.graph_module._deserialize_graph_module(forward, body);
  8363. });
  8364. this.registerFunction('torch.fx.graph_module.reduce_package_graph_module', (importer, body, generated_module_name) => {
  8365. const forward = importer.import_module(generated_module_name).forward;
  8366. return torch.fx.graph_module._deserialize_graph_module(forward, body);
  8367. });
  8368. this.registerType('torch.fx.graph.CodeGen', class {});
  8369. this.registerType('torch.fx.graph._PyTreeInfo', class {
  8370. constructor(orig_args, in_spec, out_spec) {
  8371. this.orig_args = orig_args;
  8372. this.in_spec = in_spec;
  8373. this.out_spec = out_spec;
  8374. }
  8375. });
  8376. this.registerType('torch.fx.graph._Namespace', class {
  8377. constructor() {
  8378. this._obj_to_name = new Map();
  8379. this._unassociated_names = new Set();
  8380. this._used_names = new Set();
  8381. this._base_count = {};
  8382. }
  8383. create_name(candidate, obj) {
  8384. if (obj && this._obj_to_name.has(obj)) {
  8385. return self._obj_to_name.get(obj);
  8386. }
  8387. candidate = candidate || '_unnamed';
  8388. candidate = /^\d+$/.test(candidate) ? `_${candidate}` : candidate;
  8389. candidate = candidate.replace(/[^0-9a-zA-Z_]+/, '_');
  8390. const match = candidate.match(/(.*)_(\d+)$"/);
  8391. let base = candidate;
  8392. let num = null;
  8393. if (match) {
  8394. [, base] = match;
  8395. num = parseInt(match[2], 10);
  8396. }
  8397. candidate = num ? `${base}_${num}` : base;
  8398. if (!num) {
  8399. num = this._base_count[base] || 0;
  8400. }
  8401. while (this._used_names.has(candidate) || this._is_illegal_name(candidate, obj)) {
  8402. num += 1;
  8403. candidate = `${base}_${num}`;
  8404. }
  8405. this._used_names.add(candidate);
  8406. this._base_count[base] = num;
  8407. if (obj) {
  8408. this._obj_to_name[obj] = candidate;
  8409. } else {
  8410. this._unassociated_names.add(candidate);
  8411. }
  8412. return candidate;
  8413. }
  8414. _is_illegal_name(/* name, obj */) {
  8415. /*
  8416. if name in keyword.kwlist:
  8417. return True
  8418. if name in builtins.__dict__:
  8419. return obj is not builtins.__dict__[name]
  8420. if name in _custom_builtins:
  8421. return obj is not _custom_builtins[name].obj
  8422. */
  8423. return false;
  8424. }
  8425. associate_name_with_obj() {
  8426. }
  8427. });
  8428. this.registerType('torch.fx.node.Node', class {
  8429. constructor(graph, name, op, target, args, kwargs, return_type) {
  8430. this.graph = graph;
  8431. this.name = name;
  8432. this.op = op;
  8433. this.target = target;
  8434. this._input_nodes = new builtins.dict();
  8435. this.__update_args_kwargs(args, kwargs);
  8436. this.users = new builtins.dict();
  8437. this.type = return_type;
  8438. this._prev = this;
  8439. this._next = this;
  8440. this._erased = false;
  8441. this._repr_fn = null;
  8442. this.meta = new builtins.dict();
  8443. }
  8444. get args() {
  8445. return this._args;
  8446. }
  8447. get kwargs() {
  8448. return this._kwargs;
  8449. }
  8450. get next() {
  8451. return this._next;
  8452. }
  8453. prepend(x) {
  8454. x._remove_from_list();
  8455. const p = this._prev;
  8456. [p._next, x._prev] = [x, p];
  8457. [x._next, this._prev] = [this, x];
  8458. }
  8459. _remove_from_list() {
  8460. const [p, n] = [this._prev, this._next];
  8461. [p._next, n._prev] = [n, p];
  8462. }
  8463. __update_args_kwargs(new_args, new_kwargs) {
  8464. const update_users_and_input_nodes = (n) => {
  8465. if (n instanceof torch.fx.node.Node) {
  8466. this._input_nodes.setdefault(n);
  8467. n.users.setdefault(this);
  8468. }
  8469. return n;
  8470. };
  8471. const map_aggregate = (a, fn) => {
  8472. if (a instanceof builtins.tuple) {
  8473. const t = new builtins.tuple(a.map((elem) => map_aggregate(elem, fn)));
  8474. if (!builtins.hasattr(a, '_fields')) {
  8475. return t;
  8476. }
  8477. throw new python.Error('Not implemented.');
  8478. // return type(a)(*t);
  8479. } else if (Array.isArray(a)) {
  8480. return a.map((elem) => map_aggregate(elem, fn));
  8481. } else if (a instanceof builtins.dict) {
  8482. const rv = new builtins.dict();
  8483. for (const [k, v] of a) {
  8484. rv.__setitem__(k, map_aggregate(v, fn));
  8485. }
  8486. return rv;
  8487. } else if (a instanceof builtins.slice) {
  8488. throw new python.Error('Not implemented.');
  8489. // return slice(map_aggregate(a.start, fn), map_aggregate(a.stop, fn), map_aggregate(a.step, fn))
  8490. }
  8491. return fn(a);
  8492. };
  8493. for (const old_use of this._input_nodes.keys()) {
  8494. old_use.users.pop(this);
  8495. }
  8496. // object.__setattr__(self, "_input_nodes", {})
  8497. this._input_nodes = new builtins.dict();
  8498. // object.__setattr__(self, "_args", map_aggregate(new_args, update_users_and_input_nodes))
  8499. this._args = map_aggregate(new_args, update_users_and_input_nodes);
  8500. // object.__setattr__(self, "_kwargs", map_aggregate(new_kwargs, update_users_and_input_nodes))
  8501. this._kwargs = map_aggregate(new_kwargs, update_users_and_input_nodes);
  8502. }
  8503. });
  8504. torch.fx.Node = torch.fx.node.Node;
  8505. torch.fx.graph.Node = torch.fx.node.Node;
  8506. this.registerType('torch.fx.graph.Graph', class {
  8507. constructor(owning_module, tracer_cls, tracer_extras) {
  8508. this._root = new torch.fx.node.Node(self, '', 'root', '', new builtins.list(), new builtins.dict());
  8509. this._used_names = new Map();
  8510. this._len = 0;
  8511. this._graph_namespace = new torch.fx.graph._Namespace();
  8512. this._owning_module = owning_module;
  8513. this._tracer_cls = tracer_cls;
  8514. this._tracer_extras = tracer_extras;
  8515. // this._codegen = CodeGen()
  8516. // this._co_fields = {}
  8517. }
  8518. get nodes() {
  8519. const array = new Array(this._len);
  8520. let node = this._root.next;
  8521. for (let i = 0; node !== this._root; i++) {
  8522. array[i] = node;
  8523. node = node.next;
  8524. }
  8525. return array;
  8526. }
  8527. placeholder(name, type_expr /*, default_value */) {
  8528. const args = []; // () if default_value is inspect.Signature.empty else (default_value,)
  8529. const kwargs = new builtins.dict();
  8530. return this.create_node('placeholder', name, args, kwargs, type_expr);
  8531. }
  8532. create_node(op, target, args, kwargs, name, type_expr) {
  8533. args = args || new builtins.tuple();
  8534. kwargs = kwargs || new builtins.dict();
  8535. const candidate = name || this._target_to_str(target);
  8536. name = this._graph_namespace.create_name(candidate, null);
  8537. const n = new torch.fx.node.Node(this, name, op, target, args, kwargs, type_expr);
  8538. this._graph_namespace.associate_name_with_obj(name, n);
  8539. this._insert(n);
  8540. this._len += 1;
  8541. return n;
  8542. }
  8543. _insert(n) {
  8544. this._root.prepend(n);
  8545. }
  8546. output(result, type_expr) {
  8547. return this.create_node('output', 'output', new builtins.tuple(result), null, type_expr);
  8548. }
  8549. _target_to_str(target) {
  8550. if (typeof target === 'string') {
  8551. if (target.startsWith('__') && target.endsWith('__')) {
  8552. target = target.substring(2, target.length - 2);
  8553. }
  8554. } else {
  8555. target = target.__name__;
  8556. }
  8557. return this._snake_case(target);
  8558. }
  8559. _snake_case(s) {
  8560. const chars = [];
  8561. let prev_lower = false;
  8562. for (const c of s) {
  8563. const x = c.toLowerCase();
  8564. if (prev_lower && x !== c) {
  8565. chars.push('_');
  8566. } else {
  8567. prev_lower = true;
  8568. }
  8569. chars.push(x);
  8570. }
  8571. return chars.join('');
  8572. }
  8573. });
  8574. this.registerType('torch.fx.graph_module._CodeOnlyModule', class extends torch.nn.modules.module.Module {
  8575. constructor(body) {
  8576. super();
  8577. for (const [k, v] of body.items()) {
  8578. builtins.setattr(this, k, v);
  8579. }
  8580. }
  8581. });
  8582. this.registerFunction('torch.fx.graph_module._copy_attr', (from_module, to_module, target) => {
  8583. const parts = target.split('.');
  8584. const field = parts.pop();
  8585. for (const item of parts) {
  8586. const f = builtins.getattr(from_module, item);
  8587. let t = builtins.getattr(to_module, item, null);
  8588. if (f === t) {
  8589. return;
  8590. }
  8591. if (t === null) {
  8592. t = new torch.nn.modules.module.Module();
  8593. builtins.setattr(to_module, item, t);
  8594. }
  8595. from_module = f;
  8596. to_module = t;
  8597. }
  8598. const orig = builtins.getattr(from_module, field);
  8599. builtins.setattr(to_module, field, orig);
  8600. });
  8601. this.registerType('torch.fx.graph_module.GraphModule', class extends torch.nn.modules.module.Module {
  8602. constructor(root, graph, class_name) {
  8603. super();
  8604. this.__class__.__name__ = class_name || 'GraphModule';
  8605. this.graph = graph;
  8606. if (root instanceof torch.nn.modules.module.Module && graph && graph.nodes) {
  8607. for (const node of graph.nodes) {
  8608. if (node.op === 'get_attr' || node.op === 'call_module') {
  8609. torch.fx.graph_module._copy_attr(root, this, node.target);
  8610. }
  8611. }
  8612. }
  8613. }
  8614. });
  8615. torch.fx.Graph = torch.fx.graph.Graph;
  8616. torch.fx.GraphModule = torch.fx.graph_module.GraphModule;
  8617. this.registerType('torch.fx.immutable_collections.immutable_dict', class extends builtins.dict {});
  8618. this.registerType('torch.fx.immutable_collections.immutable_list', class extends builtins.list {});
  8619. this.registerFunction('torch.fx._symbolic_trace.wrap', (fn_or_name) => {
  8620. return fn_or_name;
  8621. });
  8622. this.registerFunction('torch.fx._symbolic_trace._assert_is_none');
  8623. this.registerFunction('torchvision.datasets.folder.default_loader');
  8624. this.registerType('torchvision.datasets.folder.ImageFolder', class {});
  8625. this.registerType('torchvision.datasets.mnist.FashionMNIST', class {});
  8626. this.registerType('torchvision.datasets.mnist.MNIST', class {});
  8627. this.registerType('torchvision.datasets.video_utils.VideoClips', class {});
  8628. this.registerType('torchvision.datasets.vision.StandardTransform', class {});
  8629. this.registerType('torchvision.ops.deform_conv.DeformConv2d', class {});
  8630. this.registerType('torchvision.ops.feature_pyramid_network.FeaturePyramidNetwork', class {});
  8631. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelMaxPool', class {});
  8632. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelP6P7', class {});
  8633. this.registerType('torchvision.ops.misc.Conv2dNormActivation', class {});
  8634. this.registerType('torchvision.ops.misc.ConvNormActivation', class {});
  8635. this.registerType('torchvision.ops.misc.MLP', class extends torch.nn.modules.container.Sequential {});
  8636. this.registerType('torchvision.ops.misc.ConvTranspose2d', class {});
  8637. this.registerType('torchvision.ops.misc.FrozenBatchNorm2d', class {});
  8638. this.registerType('torchvision.ops.misc.Permute', class {});
  8639. this.registerType('torchvision.ops.misc.SqueezeExcitation', class {});
  8640. this.registerType('torchvision.ops.poolers.LevelMapper', class {});
  8641. this.registerType('torchvision.ops.poolers.MultiScaleRoIAlign', class {});
  8642. this.registerType('torchvision.ops.roi_align.RoIAlign', class {});
  8643. this.registerType('torchvision.ops.stochastic_depth.StochasticDepth', class {});
  8644. this.registerType('torchvision.models._api.Weights', class {});
  8645. this.registerType('torchvision.models.alexnet.AlexNet', class {});
  8646. this.registerType('torchvision.models.convnext.ConvNeXt', class {});
  8647. this.registerType('torchvision.models.convnext.CNBlock', class {});
  8648. this.registerType('torchvision.models.convnext.LayerNorm2d', class {});
  8649. this.registerType('torchvision.models.densenet.DenseNet', class extends torch.nn.modules.module.Module {});
  8650. this.registerType('torchvision.models.densenet._DenseBlock', class extends torch.nn.modules.container.ModuleDict {});
  8651. this.registerType('torchvision.models.densenet._DenseLayer', class extends torch.nn.modules.module.Module {});
  8652. this.registerType('torchvision.models.densenet._Transition', class extends torch.nn.modules.container.Sequential {});
  8653. this.registerType('torchvision.models.detection._utils.BalancedPositiveNegativeSampler', class {});
  8654. this.registerType('torchvision.models.detection._utils.BoxCoder', class {});
  8655. this.registerType('torchvision.models.detection._utils.Matcher', class {});
  8656. this.registerType('torchvision.models.detection._utils.SSDMatcher', class {});
  8657. this.registerType('torchvision.models.detection.anchor_utils.AnchorGenerator', class {});
  8658. this.registerType('torchvision.models.detection.anchor_utils.DefaultBoxGenerator', class {});
  8659. this.registerType('torchvision.models.detection.backbone_utils.BackboneWithFPN', class {});
  8660. this.registerType('torchvision.models.detection.faster_rcnn.FasterRCNN', class {});
  8661. this.registerType('torchvision.models.detection.faster_rcnn.FastRCNNConvFCHead', class {});
  8662. this.registerType('torchvision.models.detection.faster_rcnn.FastRCNNPredictor', class {});
  8663. this.registerType('torchvision.models.detection.faster_rcnn.TwoMLPHead', class {});
  8664. this.registerType('torchvision.models.detection.fcos.FCOS', class {});
  8665. this.registerType('torchvision.models.detection.fcos.FCOSHead', class {});
  8666. this.registerType('torchvision.models.detection.fcos.FCOSClassificationHead', class {});
  8667. this.registerType('torchvision.models.detection.fcos.FCOSRegressionHead', class {});
  8668. this.registerType('torchvision.models.detection._utils.BoxLinearCoder', class {});
  8669. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNN', class {});
  8670. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNHeads', class {});
  8671. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNPredictor', class {});
  8672. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNN', class {});
  8673. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNHeads', class {});
  8674. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNPredictor', class {});
  8675. this.registerType('torchvision.models.detection.retinanet.RetinaNet', class {});
  8676. this.registerType('torchvision.models.detection.retinanet.RetinaNetClassificationHead', class {});
  8677. this.registerType('torchvision.models.detection.retinanet.RetinaNetHead', class {});
  8678. this.registerType('torchvision.models.detection.retinanet.RetinaNetRegressionHead', class {});
  8679. this.registerType('torchvision.models.detection.roi_heads.RoIHeads', class {});
  8680. this.registerType('torchvision.models.detection.rpn.AnchorGenerator', class {});
  8681. this.registerType('torchvision.models.detection.rpn.RegionProposalNetwork', class {});
  8682. this.registerType('torchvision.models.detection.rpn.RPNHead', class {});
  8683. this.registerType('torchvision.models.detection.ssd.SSD', class {});
  8684. this.registerType('torchvision.models.detection.ssd.SSDClassificationHead', class {});
  8685. this.registerType('torchvision.models.detection.ssd.SSDHead', class {});
  8686. this.registerType('torchvision.models.detection.ssd.SSDFeatureExtractorVGG', class {});
  8687. this.registerType('torchvision.models.detection.ssd.SSDRegressionHead', class {});
  8688. this.registerType('torchvision.models.detection.ssdlite.SSDLiteClassificationHead', class {});
  8689. this.registerType('torchvision.models.detection.ssdlite.SSDLiteFeatureExtractorMobileNet', class {});
  8690. this.registerType('torchvision.models.detection.ssdlite.SSDLiteHead', class {});
  8691. this.registerType('torchvision.models.detection.ssdlite.SSDLiteRegressionHead', class {});
  8692. this.registerType('torchvision.models.detection.transform.GeneralizedRCNNTransform', class {});
  8693. this.registerType('torchvision.models.efficientnet.EfficientNet', class {});
  8694. this.registerType('torchvision.models.efficientnet.EfficientNet_B3_Weights', class {});
  8695. this.registerType('torchvision.models.efficientnet.FusedMBConv', class {});
  8696. this.registerType('torchvision.models.efficientnet.MBConv', class {});
  8697. this.registerType('torchvision.models.feature_extraction.LeafModuleAwareTracer', class extends torch.fx._symbolic_trace.Tracer {});
  8698. this.registerType('torchvision.models.feature_extraction.NodePathTracer', class extends torchvision.models.feature_extraction.LeafModuleAwareTracer {});
  8699. this.registerType('torchvision.models.googlenet.BasicConv2d', class {});
  8700. this.registerType('torchvision.models.googlenet.GoogLeNet', class {});
  8701. this.registerType('torchvision.models.googlenet.Inception', class {});
  8702. this.registerType('torchvision.models.googlenet.InceptionAux', class {});
  8703. this.registerType('torchvision.models.inception.BasicConv2d', class {});
  8704. this.registerType('torchvision.models.inception.Inception3', class {});
  8705. this.registerType('torchvision.models.inception.InceptionAux', class {});
  8706. this.registerType('torchvision.models.inception.InceptionA', class {});
  8707. this.registerType('torchvision.models.inception.InceptionB', class {});
  8708. this.registerType('torchvision.models.inception.InceptionC', class {});
  8709. this.registerType('torchvision.models.inception.InceptionD', class {});
  8710. this.registerType('torchvision.models.inception.InceptionE', class {});
  8711. this.registerFunction('torchvision.models.inception.inception_v3');
  8712. this.registerType('torchvision.models.mnasnet._InvertedResidual', class {});
  8713. this.registerType('torchvision.models.mnasnet.MNASNet', class {});
  8714. this.registerType('torchvision.models.maxvit.MaxVit', class {});
  8715. this.registerType('torchvision.models.maxvit.MaxVitBlock', class {});
  8716. this.registerType('torchvision.models.maxvit.MaxVitLayer', class {});
  8717. this.registerType('torchvision.models.maxvit.MBConv', class {});
  8718. this.registerType('torchvision.models.maxvit.PartitionAttentionLayer', class {});
  8719. this.registerType('torchvision.models.maxvit.RelativePositionalMultiHeadAttention', class {});
  8720. this.registerType('torchvision.models.maxvit.SwapAxes', class {});
  8721. this.registerType('torchvision.models.maxvit.WindowDepartition', class {});
  8722. this.registerType('torchvision.models.mobilenet.ConvBNReLU', class {});
  8723. this.registerType('torchvision.models.mobilenet.MobileNetV2', class {});
  8724. this.registerType('torchvision.models.mobilenet.InvertedResidual', class {});
  8725. this.registerType('torchvision.models.mobilenetv2.ConvBNActivation', class {});
  8726. this.registerType('torchvision.models.mobilenetv2.InvertedResidual', class {});
  8727. this.registerType('torchvision.models.mobilenetv2.MobileNetV2', class {});
  8728. this.registerType('torchvision.models.mobilenetv3.InvertedResidual', class {});
  8729. this.registerType('torchvision.models.mobilenetv3.MobileNetV3', class {});
  8730. this.registerType('torchvision.models.mobilenetv3.SqueezeExcitation', class {});
  8731. this.registerType('torchvision.models.regnet.AnyStage', class extends torch.nn.modules.container.Sequential {});
  8732. this.registerType('torchvision.models.regnet.BottleneckTransform', class {});
  8733. this.registerType('torchvision.models.regnet.ResBottleneckBlock', class {});
  8734. this.registerType('torchvision.models.regnet.RegNet', class {});
  8735. this.registerType('torchvision.models.regnet.SimpleStemIN', class {});
  8736. this.registerType('torchvision.models.resnet.Bottleneck', class {});
  8737. this.registerType('torchvision.models.resnet.BasicBlock', class {});
  8738. this.registerType('torchvision.models.quantization.mobilenet.QuantizableInvertedResidual', class {});
  8739. this.registerType('torchvision.models.quantization.mobilenet.QuantizableMobileNetV2', class {});
  8740. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableInvertedResidual', class {});
  8741. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableMobileNetV2', class {});
  8742. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableMobileNetV3', class {});
  8743. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableInvertedResidual', class {});
  8744. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableSqueezeExcitation', class {});
  8745. this.registerType('torchvision.models.quantization.resnet.QuantizableBasicBlock', class {});
  8746. this.registerType('torchvision.models.quantization.resnet.QuantizableBottleneck', class {});
  8747. this.registerType('torchvision.models.quantization.resnet.QuantizableResNet', class {});
  8748. this.registerType('torchvision.models.segmentation.deeplabv3.ASPP', class {});
  8749. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPConv', class {});
  8750. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPPooling', class {});
  8751. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabHead', class {});
  8752. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabV3', class {});
  8753. this.registerType('torchvision.models.segmentation.fcn.FCN', class {});
  8754. this.registerType('torchvision.models.segmentation.fcn.FCNHead', class {});
  8755. this.registerType('torchvision.models.segmentation.lraspp.LRASPP', class {});
  8756. this.registerType('torchvision.models.segmentation.lraspp.LRASPPHead', class {});
  8757. this.registerType('torchvision.models.shufflenetv2.ShuffleNetV2', class {});
  8758. this.registerType('torchvision.models.shufflenetv2.InvertedResidual', class {});
  8759. this.registerType('torchvision.models.squeezenet.Fire', class {});
  8760. this.registerType('torchvision.models.squeezenet.SqueezeNet', class {});
  8761. this.registerType('torchvision.models.swin_transformer.PatchMerging', class {});
  8762. this.registerType('torchvision.models.swin_transformer.PatchMergingV2', class {});
  8763. this.registerType('torchvision.models.swin_transformer.ShiftedWindowAttention', class {});
  8764. this.registerType('torchvision.models.swin_transformer.ShiftedWindowAttentionV2', class {});
  8765. this.registerType('torchvision.models.swin_transformer.SwinTransformer', class {});
  8766. this.registerType('torchvision.models.swin_transformer.SwinTransformerBlock', class {});
  8767. this.registerType('torchvision.models.swin_transformer.SwinTransformerBlockV2', class {});
  8768. this.registerType('torchvision.models.resnet.ResNet', class {});
  8769. this.registerType('torchvision.models.vgg.VGG', class {});
  8770. this.registerType('torchvision.models.video.resnet.BasicBlock', class {});
  8771. this.registerType('torchvision.models.video.resnet.BasicStem', class {});
  8772. this.registerType('torchvision.models.video.resnet.Conv2Plus1D', class {});
  8773. this.registerType('torchvision.models.video.resnet.Conv3DNoTemporal', class {});
  8774. this.registerType('torchvision.models.video.resnet.Conv3DSimple', class {});
  8775. this.registerType('torchvision.models.video.resnet.R2Plus1dStem', class {});
  8776. this.registerType('torchvision.models.video.resnet.VideoResNet', class {});
  8777. this.registerType('torchvision.models.vision_transformer.Encoder', class extends torch.nn.modules.module.Module {});
  8778. this.registerType('torchvision.models.vision_transformer.EncoderBlock', class extends torch.nn.modules.module.Module {});
  8779. this.registerType('torchvision.models.vision_transformer.MLPBlock', class extends torchvision.ops.misc.MLP {});
  8780. this.registerType('torchvision.models.vision_transformer.VisionTransformer', class extends torch.nn.modules.module.Module {});
  8781. this.registerType('torchvision.models._utils.IntermediateLayerGetter', class {});
  8782. this.registerType('torchvision.transforms._presets.ImageClassification', class extends torch.nn.modules.module.Module {});
  8783. this.registerType('torchvision.transforms.autoaugment.AutoAugment', class {});
  8784. this.registerType('torchvision.transforms.autoaugment.AutoAugmentPolicy', class {});
  8785. this.registerType('torchvision.transforms.autoaugment.AugMix', class {});
  8786. this.registerType('torchvision.transforms.functional.InterpolationMode', class {});
  8787. this.registerFunction('torchvision.transforms.functional.adjust_brightness');
  8788. this.registerFunction('torchvision.transforms.functional.adjust_contrast');
  8789. this.registerFunction('torchvision.transforms.functional.adjust_brightness');
  8790. this.registerFunction('torchvision.transforms.functional.adjust_contrast');
  8791. this.registerFunction('torchvision.transforms.functional.adjust_gamma');
  8792. this.registerFunction('torchvision.transforms.functional.adjust_hue');
  8793. this.registerFunction('torchvision.transforms.functional.adjust_saturation');
  8794. this.registerType('torchvision.transforms.transforms.ColorJitter', class extends torch.nn.modules.module.Module {});
  8795. this.registerType('torchvision.transforms.transforms.Compose', class {});
  8796. this.registerType('torchvision.transforms.transforms.ConvertImageDtype', class {});
  8797. this.registerType('torchvision.transforms.transforms.CenterCrop', class extends torch.nn.modules.module.Module {});
  8798. this.registerType('torchvision.transforms.transforms.GaussianBlur', class extends torch.nn.modules.module.Module {});
  8799. this.registerType('torchvision.transforms.transforms.Grayscale', class extends torch.nn.modules.module.Module {});
  8800. this.registerType('torchvision.transforms.transforms.Lambda', class {});
  8801. this.registerType('torchvision.transforms.transforms.Normalize', class extends torch.nn.modules.module.Module {});
  8802. this.registerType('torchvision.transforms.transforms.PILToTensor', class {});
  8803. this.registerType('torchvision.transforms.transforms.RandomAffine', class extends torch.nn.modules.module.Module {});
  8804. this.registerType('torchvision.transforms.transforms.RandomApply', class extends torch.nn.modules.module.Module {});
  8805. this.registerType('torchvision.transforms.transforms.RandomCrop', class extends torch.nn.modules.module.Module {});
  8806. this.registerType('torchvision.transforms.transforms.RandomChoice', class {});
  8807. this.registerType('torchvision.transforms.transforms.RandomErasing', class {});
  8808. this.registerType('torchvision.transforms.transforms.RandomInvert', class {});
  8809. this.registerType('torchvision.transforms.transforms.RandomPerspective', class {});
  8810. this.registerType('torchvision.transforms.transforms.RandomHorizontalFlip', class extends torch.nn.modules.module.Module {});
  8811. this.registerType('torchvision.transforms.transforms.RandomVerticalFlip', class extends torch.nn.modules.module.Module {});
  8812. this.registerType('torchvision.transforms.transforms.RandomResizedCrop', class extends torch.nn.modules.module.Module {});
  8813. this.registerType('torchvision.transforms.transforms.RandomRotation', class extends torch.nn.modules.module.Module {});
  8814. this.registerType('torchvision.transforms.transforms.Resize', class extends torch.nn.modules.module.Module {});
  8815. this.registerType('torchvision.transforms.transforms.Scale', class extends torch.nn.modules.module.Module {});
  8816. this.registerType('torchvision.transforms.transforms.ToPILImage', class {});
  8817. this.registerType('torchvision.transforms.transforms.ToTensor', class {});
  8818. this.registerType('torchvision.transforms.v2._color.Grayscale', class {});
  8819. this.registerType('torchvision.transforms.v2._color.RandomGrayscale', class {});
  8820. this.registerType('torchvision.transforms.v2._container.Compose', class {});
  8821. this.registerType('torchvision.transforms.v2._deprecated.ToTensor', class {});
  8822. this.registerType('torchvision.transforms.v2._misc.ConvertImageDtype', class {});
  8823. this.registerType('torchvision.transforms.v2._misc.Normalize', class {});
  8824. this.registerType('torchvision.transforms.v2._misc.ToDtype', class {});
  8825. this.registerType('torchvision.transforms.v2._geometry.CenterCrop', class {});
  8826. this.registerType('torchvision.transforms.v2._geometry.Resize', class {});
  8827. this.registerType('torchvision.transforms.v2._geometry.Pad', class {});
  8828. this.registerType('torchvision.transforms.v2._geometry.RandomCrop', class {});
  8829. this.registerType('torchvision.transforms.v2._transform.Transform', class extends torch.nn.modules.module.Module {});
  8830. this.registerType('torchvision.transforms.v2._type_conversion.ToImage', class extends torchvision.transforms.v2._transform.Transform {});
  8831. this.registerType('torchvision.transforms.v2._type_conversion.PILToTensor', class {});
  8832. this.registerFunction('torchvision.models.resnet.resnet18', () => {});
  8833. this.registerFunction('torchvision.models.resnet.resnet34', () => {});
  8834. this.registerFunction('torchvision.models.resnet.resnet50', () => {});
  8835. this.registerFunction('torchvision.models.resnet.resnet101', () => {});
  8836. this.registerFunction('torchvision.models.resnet.resnet152', () => {});
  8837. this.registerFunction('torchvision.models.vision_transformer.vit_h_14', () => {});
  8838. this.registerFunction('torchvision.ops.boxes.box_iou');
  8839. this.registerFunction('torchvision.ops.focal_loss.sigmoid_focal_loss');
  8840. this.registerType('ultralytics.nn.modules.block.Bottleneck', class extends torch.nn.modules.module.Module {});
  8841. this.registerType('ultralytics.nn.modules.block.C1', class extends torch.nn.modules.module.Module {});
  8842. this.registerType('ultralytics.nn.modules.block.C2', class extends torch.nn.modules.module.Module {});
  8843. this.registerType('ultralytics.nn.modules.block.C2f', class extends torch.nn.modules.module.Module {});
  8844. this.registerType('ultralytics.nn.modules.block.C2fAttn', class extends torch.nn.modules.module.Module {});
  8845. this.registerType('ultralytics.nn.modules.block.C2fCIB', class extends torch.nn.modules.module.Module {});
  8846. this.registerType('ultralytics.nn.modules.block.C2fPSA', class extends torch.nn.modules.module.Module {});
  8847. this.registerType('ultralytics.nn.modules.block.C2PSA', class extends torch.nn.modules.module.Module {});
  8848. this.registerType('ultralytics.nn.modules.block.C3', class extends torch.nn.modules.module.Module {});
  8849. this.registerType('ultralytics.nn.modules.block.C3Ghost', class extends torch.nn.modules.module.Module {});
  8850. this.registerType('ultralytics.nn.modules.block.C3k2', class extends torch.nn.modules.module.Module {});
  8851. this.registerType('ultralytics.nn.modules.block.C3k2_v2', class extends torch.nn.modules.module.Module {});
  8852. this.registerType('ultralytics.nn.modules.block.C3TR', class extends torch.nn.modules.module.Module {});
  8853. this.registerType('ultralytics.nn.modules.block.C3x', class extends torch.nn.modules.module.Module {});
  8854. this.registerType('ultralytics.nn.modules.block.DFL', class extends torch.nn.modules.module.Module {});
  8855. this.registerType('ultralytics.nn.modules.block.GhostBottleneck', class extends torch.nn.modules.module.Module {});
  8856. this.registerType('ultralytics.nn.modules.block.HGBlock', class extends torch.nn.modules.module.Module {});
  8857. this.registerType('ultralytics.nn.modules.block.HGStem', class extends torch.nn.modules.module.Module {});
  8858. this.registerType('ultralytics.nn.modules.block.Proto', class extends torch.nn.modules.module.Module {});
  8859. this.registerType('ultralytics.nn.modules.block.RepC3', class extends torch.nn.modules.module.Module {});
  8860. this.registerType('ultralytics.nn.modules.block.SCDown', class extends torch.nn.modules.module.Module {});
  8861. this.registerType('ultralytics.nn.modules.block.SPP', class extends torch.nn.modules.module.Module {});
  8862. this.registerType('ultralytics.nn.modules.block.SPPF', class extends torch.nn.modules.module.Module {});
  8863. this.registerType('ultralytics.nn.modules.conv.Concat', class extends torch.nn.modules.module.Module {});
  8864. this.registerType('ultralytics.nn.modules.conv.Conv', class extends torch.nn.modules.module.Module {});
  8865. this.registerType('ultralytics.nn.modules.conv.Conv2', class extends torch.nn.modules.module.Module {});
  8866. this.registerType('ultralytics.nn.modules.conv.ConvTranspose', class extends torch.nn.modules.module.Module {});
  8867. this.registerType('ultralytics.nn.modules.conv.DWConv', class extends torch.nn.modules.module.Module {});
  8868. this.registerType('ultralytics.nn.modules.conv.DWConvTranspose2d', class extends torch.nn.modules.module.Module {});
  8869. this.registerType('ultralytics.nn.modules.conv.Focus', class extends torch.nn.modules.module.Module {});
  8870. this.registerType('ultralytics.nn.modules.conv.GhostConv', class extends torch.nn.modules.module.Module {});
  8871. this.registerType('ultralytics.nn.modules.conv.LightConv', class extends torch.nn.modules.module.Module {});
  8872. this.registerType('ultralytics.nn.modules.conv.RepConv', class extends torch.nn.modules.module.Module {});
  8873. this.registerType('ultralytics.nn.modules.head.Classify', class extends torch.nn.modules.module.Module {});
  8874. this.registerType('ultralytics.nn.modules.head.Detect', class extends torch.nn.modules.module.Module {});
  8875. this.registerType('ultralytics.nn.modules.head.OBB', class extends torch.nn.modules.module.Module {});
  8876. this.registerType('ultralytics.nn.modules.head.Pose', class extends torch.nn.modules.module.Module {});
  8877. this.registerType('ultralytics.nn.modules.head.RTDETRDecoder', class extends torch.nn.modules.module.Module {});
  8878. this.registerType('ultralytics.nn.modules.head.Segment', class extends torch.nn.modules.module.Module {});
  8879. this.registerType('ultralytics.nn.modules.head.WorldDetect', class extends torch.nn.modules.module.Module {});
  8880. this.registerType('ultralytics.nn.modules.head.v10Detect', class extends torch.nn.modules.module.Module {});
  8881. this.registerType('ultralytics.nn.modules.transformer.AIFI', class extends torch.nn.modules.module.Module {});
  8882. this.registerType('ultralytics.nn.modules.transformer.DeformableTransformerDecoder', class extends torch.nn.modules.module.Module {});
  8883. this.registerType('ultralytics.nn.modules.transformer.DeformableTransformerDecoderLayer', class extends torch.nn.modules.module.Module {});
  8884. this.registerType('ultralytics.nn.modules.transformer.MLP', class extends torch.nn.modules.module.Module {});
  8885. this.registerType('ultralytics.nn.modules.transformer.TransformerEncoderLayer', class extends torch.nn.modules.module.Module {});
  8886. this.registerType('ultralytics.nn.modules.transformer.TransformerLayer', class extends torch.nn.modules.module.Module {});
  8887. this.registerType('ultralytics.nn.extra_modules.Down_WT.Down_wt', class extends torch.nn.modules.module.Module {});
  8888. this.registerType('ultralytics.nn.extra_modules.prune_module.C3k2_v2', class extends torch.nn.modules.module.Module {});
  8889. this.registerType('ultralytics.nn.tasks.BaseModel', class extends torch.nn.modules.module.Module {});
  8890. this.registerType('ultralytics.nn.tasks.ClassificationModel', class extends torch.nn.modules.module.Module {});
  8891. this.registerType('ultralytics.nn.tasks.DetectionModel', class extends torch.nn.modules.module.Module {});
  8892. this.registerType('ultralytics.nn.tasks.Ensemble', class extends torch.nn.modules.module.Module {});
  8893. this.registerType('ultralytics.nn.tasks.OBBModel', class extends torch.nn.modules.module.Module {});
  8894. this.registerType('ultralytics.nn.tasks.PoseModel', class extends torch.nn.modules.module.Module {});
  8895. this.registerType('ultralytics.nn.tasks.RTDETRDetectionModel', class extends torch.nn.modules.module.Module {});
  8896. this.registerType('ultralytics.nn.tasks.SegmentationModel', class extends torch.nn.modules.module.Module {});
  8897. this.registerType('ultralytics.nn.tasks.WorldModel', class extends torch.nn.modules.module.Module {});
  8898. this.registerType('ultralytics.nn.tasks.YOLOEModel', class extends torch.nn.modules.module.Module {});
  8899. this.registerType('ultralytics.nn.tasks.YOLOESegModel', class extends torch.nn.modules.module.Module {});
  8900. this.registerType('ultralytics.utils.IterableSimpleNamespace', class {});
  8901. this.registerType('ultralytics.utils.loss.BboxLoss', class extends torch.nn.modules.module.Module {});
  8902. this.registerType('ultralytics.utils.loss.E2EDetectLoss', class {});
  8903. this.registerType('ultralytics.utils.loss.v8ClassificationLoss', class {});
  8904. this.registerType('ultralytics.utils.loss.v8DetectionLoss', class {});
  8905. this.registerType('ultralytics.utils.loss.v8OBBLoss', class {});
  8906. this.registerType('ultralytics.utils.loss.v8PoseLoss', class {});
  8907. this.registerType('ultralytics.utils.loss.v8SegmentationLoss', class {});
  8908. this.registerType('ultralytics.utils.tal.TaskAlignedAssigner', class extends torch.nn.modules.module.Module {});
  8909. this.registerType('ultralytics.utils.torch_utils.ModelEMA', class {});
  8910. this.registerFunction('builtins.annotate', (type, value) => {
  8911. if (type === builtins.int) {
  8912. return Number.isInteger(value) ? value : NaN;
  8913. }
  8914. if (type === builtins.float) {
  8915. return typeof value === 'number' ? value : NaN;
  8916. }
  8917. if (type === builtins.number) {
  8918. // if (pytorch.Utility.isTensor(value)) {
  8919. // value.resize_([]);
  8920. // }
  8921. }
  8922. return value;
  8923. });
  8924. this.registerFunction('builtins.uninitialized', (/* type */) => {
  8925. return undefined;
  8926. });
  8927. this.registerFunction('builtins.range', (start, stop, step) => {
  8928. if (stop === undefined && step === undefined) {
  8929. if (Number.isInteger(start)) {
  8930. return Array(start).keys();
  8931. }
  8932. if (isNaN(start)) {
  8933. return [];
  8934. }
  8935. }
  8936. if (Number.isInteger(start) && Number.isInteger(stop) && (step === undefined || Number.isInteger(step))) {
  8937. step = step === undefined ? 1 : step;
  8938. const result = [];
  8939. if (step > 0) {
  8940. for (let i = start; i < stop; i += step) {
  8941. result.push(i);
  8942. }
  8943. } else if (step < 0) {
  8944. for (let i = start; i > stop; i += step) {
  8945. result.push(i);
  8946. }
  8947. }
  8948. return result;
  8949. }
  8950. throw new python.Error(`Unsupported range(${JSON.stringify(start)}, ${JSON.stringify(stop)}, ${JSON.stringify(step)})`);
  8951. });
  8952. this.registerFunction('math.trunc');
  8953. builtins.xrange = builtins.range;
  8954. this.registerFunction('torch._C._nn.gelu');
  8955. this.registerFunction('torch._C._nn.avg_pool2d');
  8956. this.registerFunction('torch._C._nn.avg_pool3d');
  8957. this.registerFunction('torch._C._nn.scaled_dot_product_attention');
  8958. this.registerFunction('torch._C._nn.softplus');
  8959. this.registerFunction('torch._native_multi_head_attention');
  8960. this.registerFunction('torch._utils._rebuild_sparse_tensor', (layout, data) => {
  8961. if (layout === torch.sparse_coo) {
  8962. return self.invoke('torch._sparse_coo_tensor_unsafe', data);
  8963. }
  8964. throw new python.Error(`Unsupported sparse tensor layout '${layout ? layout.__str__() : ''}'.`);
  8965. });
  8966. this.registerFunction('torch._utils._get_restore_location', (device) => {
  8967. return device;
  8968. });
  8969. this.registerFunction('torch._utils._rebuild_wrapper_subclass', (cls, dtype, size, stride, storage_offset, layout, device, requires_grad) => {
  8970. device = torch._utils._get_restore_location(device);
  8971. return torch.Tensor._make_wrapper_subclass(cls, size, stride, dtype, storage_offset, layout, device, requires_grad);
  8972. });
  8973. this.registerFunction('torch.from_numpy', (obj) => {
  8974. const dtypes = new Map([
  8975. ['<f2', torch.float16],
  8976. ['<f4', torch.float32],
  8977. ['<f8', torch.float64],
  8978. ['<i2', torch.int16],
  8979. ['<i4', torch.int32],
  8980. ['<i8', torch.int64],
  8981. ]);
  8982. if (!dtypes.has(obj.dtype.str)) {
  8983. throw new python.Error(`Unsupported numpy.ndarray type '${obj.dtype.str}'.`);
  8984. }
  8985. const dtype = dtypes.get(obj.dtype.str);
  8986. const strides = obj.strides.map((stride) => stride / obj.itemsize);
  8987. const storage = new torch.storage.TypedStorage(obj.size, dtype);
  8988. storage._set_cdata(obj.data);
  8989. const tensor = new torch.Tensor();
  8990. tensor.__setstate__([storage, 0, obj.shape, strides]);
  8991. return tensor;
  8992. });
  8993. this.registerFunction('torch._utils._rebuild_device_tensor_from_numpy', (data, dtype, device, requires_grad) => {
  8994. const tensor = torch.from_numpy(data);
  8995. // tensor = tensor.to(dtype, device)
  8996. tensor.requires_grad = requires_grad;
  8997. return tensor;
  8998. });
  8999. this.registerFunction('torch._utils._rebuild_device_tensor_from_cpu_tensor', (data, dtype, device, requires_grad) => {
  9000. data = data.clone();
  9001. data.requires_grad = requires_grad;
  9002. return data;
  9003. });
  9004. this.registerFunction('torch._sparse_coo_tensor_unsafe', (indices, values, size) => {
  9005. const tensor = self.invoke('torch.Tensor', []);
  9006. tensor._layout = torch.sparse_coo;
  9007. tensor._indices = indices;
  9008. tensor._values = values;
  9009. tensor._shape = size;
  9010. return tensor;
  9011. });
  9012. this.registerFunction('torch._utils.set_tensor_metadata', (tensor, metadata) => {
  9013. torch._C._set_tensor_metadata(tensor, metadata);
  9014. });
  9015. this.registerFunction('torch._utils._restore_device_fake_mode', (tensor) => {
  9016. return tensor;
  9017. });
  9018. this.registerFunction('torch._utils._rebuild_meta_tensor_no_storage', (dtype, size, stride, requires_grad) => {
  9019. return torch.empty_strided(size, stride, dtype, null, 'meta', false, requires_grad);
  9020. });
  9021. this.registerFunction('torch._utils._rebuild_tensor', (storage, storage_offset, size, stride) => {
  9022. if (Array.isArray(storage) && storage.length === 5 && storage[0] === 'storage') {
  9023. const [, storage_type, , ,size] = storage;
  9024. storage = new storage_type(size);
  9025. }
  9026. const tensor = new torch.Tensor();
  9027. tensor.__setstate__([storage, storage_offset, size, stride]);
  9028. return tensor;
  9029. });
  9030. this.registerFunction('torch._utils._rebuild_tensor_v2', (storage, storage_offset, size, stride, requires_grad, backward_hooks, metadata) => {
  9031. const tensor = torch._utils._rebuild_tensor(storage, storage_offset, size, stride);
  9032. tensor.requires_grad = requires_grad;
  9033. if (metadata) {
  9034. torch._utils.set_tensor_metadata(tensor, metadata);
  9035. }
  9036. tensor.backward_hooks = backward_hooks;
  9037. return tensor;
  9038. });
  9039. this.registerFunction('torch._utils._rebuild_tensor_v3', (storage, storage_offset, size, stride, requires_grad, backward_hooks, dtype, metadata) => {
  9040. const t = new torch.Tensor(null, null, dtype);
  9041. t.set_(storage, storage_offset, size, stride);
  9042. if (metadata) {
  9043. torch._utils.set_tensor_metadata(t, metadata);
  9044. }
  9045. t._backward_hooks = backward_hooks;
  9046. return torch._utils._restore_device_fake_mode(t);
  9047. });
  9048. this.registerFunction('torch._utils._rebuild_parameter', (data, requires_grad, backward_hooks) => {
  9049. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  9050. param.backward_hooks = backward_hooks;
  9051. return param;
  9052. });
  9053. this.registerFunction('torch._utils._rebuild_parameter_v2', (data, requires_grad, backward_hooks, state) => {
  9054. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  9055. param.backward_hooks = backward_hooks;
  9056. torch._utils._set_obj_state(param, state);
  9057. return param;
  9058. });
  9059. this.registerFunction('torch._utils._rebuild_parameter_with_state', (data, requires_grad, backward_hooks, state) => {
  9060. const _set_obj_state = (obj, state) => {
  9061. const [dict_state, slots_state] = Array.isArray(state) ? state : [state, null];
  9062. if (dict_state) {
  9063. for (const [k, v] of Object.entries(dict_state)) {
  9064. builtins.setattr(obj, k, v);
  9065. }
  9066. }
  9067. if (slots_state) {
  9068. for (const [k, v] of Object.entries(slots_state)) {
  9069. builtins.setattr(obj, k, v);
  9070. }
  9071. }
  9072. };
  9073. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  9074. param._backward_hooks = backward_hooks;
  9075. _set_obj_state(param, state);
  9076. return param;
  9077. });
  9078. this.registerFunction('torch._utils._rebuild_qtensor', (storage, storage_offset, size, stride, quantizer_params, requires_grad, backward_hooks) => {
  9079. const tensor = torch._utils._rebuild_tensor_v2(storage, storage_offset, size, stride, requires_grad, backward_hooks);
  9080. tensor.quantizer_params = quantizer_params;
  9081. return tensor;
  9082. });
  9083. this.registerFunction('torch._utils._set_obj_state', (obj, state) => {
  9084. let dict_state = state;
  9085. let slots_state = null;
  9086. if (state instanceof self.builtins.tuple) {
  9087. if (state.length !== 2) {
  9088. throw new python.Error(`Invalid serialized state: '${state}'.`);
  9089. }
  9090. [dict_state, slots_state] = state;
  9091. }
  9092. if (dict_state) {
  9093. for (const [name, value] of Object.entries(dict_state)) {
  9094. builtins.setattr(obj, name, value);
  9095. }
  9096. }
  9097. if (slots_state) {
  9098. for (const [name, value] of Object.entries(slots_state)) {
  9099. builtins.setattr(obj, name, value);
  9100. }
  9101. }
  9102. return obj;
  9103. });
  9104. this.registerFunction('torch._set_item', (dict, key, value) => {
  9105. dict[key] = value;
  9106. });
  9107. this.registerFunction('torch._tensor._rebuild_from_type_v2', (func, new_type, args, state) => {
  9108. let ret = func(...args);
  9109. if (ret.__class__ !== new_type) {
  9110. // ret = ret.as_subclass(new_type);
  9111. }
  9112. const setstate = builtins.getattr(ret.__class__, '__setstate__', torch.Tensor.__setstate__);
  9113. if (setstate === torch.Tensor.__setstate__) {
  9114. ret = torch._utils._set_obj_state(ret, state);
  9115. } else {
  9116. ret.__setstate__(state);
  9117. }
  9118. return ret;
  9119. });
  9120. this.registerFunction('torch.__range_length', (lo, hi, step) => {
  9121. if (step === 0) {
  9122. throw new python.Error('range() arg 3 must not be zero');
  9123. }
  9124. if (step > 0 && lo < hi) {
  9125. return 1 + (hi - 1 - lo) / step;
  9126. } else if (step < 0 && lo > hi) {
  9127. return 1 + (lo - 1 - hi) / (0 - step);
  9128. }
  9129. return 0;
  9130. });
  9131. this.registerFunction('torch._nested_tensor_from_mask_left_aligned');
  9132. this.registerOperator('aten::_unwrap_optional', (value) => {
  9133. return value;
  9134. });
  9135. this.registerFunction('torch.get_default_dtype', () => {
  9136. torch._default_type = torch._default_type || torch.float32;
  9137. return torch._default_type;
  9138. });
  9139. this.registerFunction('torch.set_default_dtype', (value) => {
  9140. torch._default_type = value;
  9141. });
  9142. this.registerFunction('torch._prims_common.dtype_or_default', (value) => {
  9143. return value || torch.get_default_dtype();
  9144. });
  9145. this.registerFunction('torch.empty_strided', (size, stride, dtype, layout, device, pin_memory, requires_grad) => {
  9146. const shape = size;
  9147. dtype = torch._prims_common.dtype_or_default(dtype);
  9148. let storage = null;
  9149. if (size.every((d) => d instanceof torch.SymInt === false)) {
  9150. const size = shape.reduce((a, b) => a * b, 1);
  9151. storage = new torch.storage.TypedStorage(size, dtype);
  9152. }
  9153. const tensor = new torch.Tensor(storage, shape, dtype, layout, device, requires_grad);
  9154. tensor.__setstate__([storage, 0, shape, stride]);
  9155. return tensor;
  9156. });
  9157. this.registerFunction('torch.all', (input) => {
  9158. if (Array.isArray(input) && input.length === 0) {
  9159. return true;
  9160. }
  9161. throw new python.Error(`Unsupported 'torch.all' expression type.`);
  9162. });
  9163. this.registerFunction('torch.append', (list, value) => {
  9164. list.push(value);
  9165. return value;
  9166. });
  9167. this.registerFunction('torch.clear', (value) => {
  9168. if (value instanceof torch.Value) {
  9169. throw new python.Error('Invalid value.');
  9170. }
  9171. if (Object(value) === value) {
  9172. for (const key of Object.keys(value)) {
  9173. delete value[key];
  9174. }
  9175. }
  9176. });
  9177. this.registerFunction('torch.dict', (args) => {
  9178. const obj = {};
  9179. if (args) {
  9180. if (Array.isArray(args)) {
  9181. for (const [key, value] of args) {
  9182. obj[key] = value;
  9183. }
  9184. } else {
  9185. throw new python.Error("'torch.dict' arguments not supported.");
  9186. }
  9187. }
  9188. return obj;
  9189. });
  9190. this.registerOperator('aten::cosine_similarity', () => {
  9191. throw new python.Error(`'aten::cosine_similarity' not implemented.`);
  9192. });
  9193. this.registerOperator('aten::extend', (list, value) => {
  9194. list.push(...value);
  9195. });
  9196. this.registerOperator('aten::insert', (list, index, value) => {
  9197. list.splice(index, 0, value);
  9198. return value;
  9199. });
  9200. this.registerOperator('aten::replace', (value, oldvalue, newvalue /*, max */) => {
  9201. return value.replace(oldvalue, newvalue);
  9202. });
  9203. this.registerOperator('aten::add', (a, b) => {
  9204. if ((typeof a === 'number' || a instanceof Number) && (typeof b === 'number' || b instanceof Number)) {
  9205. return a + b;
  9206. }
  9207. if (typeof a === 'number' && b instanceof builtins.complex) {
  9208. return new builtins.complex(a + b.real, b.imag);
  9209. }
  9210. if (a instanceof builtins.complex && typeof b === 'number') {
  9211. return new builtins.complex(a.real + b, a.imag);
  9212. }
  9213. if (a instanceof builtins.complex && b instanceof builtins.complex) {
  9214. return new builtins.complex(a.real + b.real, a.imag + b.imag);
  9215. }
  9216. if (Array.isArray(a) && Array.isArray(b)) {
  9217. return a.concat(b);
  9218. }
  9219. if (typeof a === 'string' && typeof b === 'string') {
  9220. return a + b;
  9221. }
  9222. throw new python.Error('Unsupported aten::add expression type.');
  9223. });
  9224. this.registerOperator('aten::log', (x) => {
  9225. if (typeof x === 'number' || x instanceof Number) {
  9226. return Math.log(x);
  9227. }
  9228. throw new python.Error('Unsupported aten::log expression type.');
  9229. });
  9230. this.registerOperator('aten::dim', (tensor) => {
  9231. if (tensor && tensor.size) {
  9232. const size = tensor.size();
  9233. if (size) {
  9234. return size.length;
  9235. }
  9236. }
  9237. return NaN;
  9238. });
  9239. this.registerOperator('aten::numel', (tensor) => {
  9240. if (tensor && tensor.size) {
  9241. const size = tensor.size();
  9242. if (size) {
  9243. return size.reduce((a, b) => a * b, 1);
  9244. }
  9245. }
  9246. return NaN;
  9247. });
  9248. this.registerOperator('aten::eq', (left, right) => {
  9249. if (typeof left === 'string' && typeof right === 'string') {
  9250. return left === right;
  9251. }
  9252. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9253. if (isNaN(left) && isNaN(right)) {
  9254. return true;
  9255. }
  9256. return left === right;
  9257. }
  9258. if (left === undefined || right === undefined) {
  9259. return true;
  9260. }
  9261. if (Array.isArray(left) && Array.isArray(right)) {
  9262. return left.length === right.length && left.every((item, index) => item === right[index]);
  9263. }
  9264. throw new python.Error("Unsupported 'torch.eq' expression type.");
  9265. });
  9266. this.registerOperator('aten::floor', (value) => {
  9267. return Math.floor(value);
  9268. });
  9269. this.registerOperator('aten::ceil', (value) => {
  9270. return Math.ceil(value);
  9271. });
  9272. this.registerOperator('aten::floordiv', (left, right) => {
  9273. return Math.floor(left / right);
  9274. });
  9275. this.registerOperator('aten::format', (...args) => {
  9276. const list = args.shift().split(/({}D?)/);
  9277. return list.map((text) => {
  9278. if (text === '{}' || text === '{}D') {
  9279. const arg = args.shift();
  9280. if (Array.isArray(arg)) {
  9281. return `[${arg.map((item) => item.toString()).join(', ')}]`;
  9282. }
  9283. return arg ? arg.toString() : '?';
  9284. }
  9285. return text;
  9286. }).join('');
  9287. });
  9288. this.registerOperator('aten::strip', (self, chars) => {
  9289. chars = chars || '\\n\\t\\f\\v';
  9290. const regex = new RegExp(`[${chars}]`, 'g');
  9291. return self.replace(regex, '');
  9292. });
  9293. this.registerOperator('aten::gt', (left, right) => {
  9294. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9295. if (!isNaN(left) && !isNaN(right)) {
  9296. return left > right;
  9297. }
  9298. }
  9299. if (isNaN(left) && !isNaN(right)) {
  9300. return true;
  9301. }
  9302. throw new python.Error("Unsupported 'ops.aten.gt' expression type.");
  9303. });
  9304. this.registerOperator('aten::ge', (left, right) => {
  9305. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9306. if (!isNaN(left) && !isNaN(right)) {
  9307. return left > right;
  9308. }
  9309. }
  9310. if (isNaN(left) && !isNaN(right)) {
  9311. return true;
  9312. }
  9313. throw new python.Error("Unsupported 'ops.aten.ge' expression type.");
  9314. });
  9315. this.registerOperator('aten::is_floating_point', (tensor) => {
  9316. const type = tensor.dtype.scalar_type();
  9317. return (type === 5 || type === 6 || type === 7);
  9318. });
  9319. this.registerOperator('aten::is_grad_enabled', () => {
  9320. return false;
  9321. });
  9322. this.registerOperator('aten::is_autocast_enabled', () => {
  9323. return false;
  9324. });
  9325. this.registerOperator('aten::isfinite');
  9326. this.registerOperator('aten::set_grad_enabled', (/* value */) => {
  9327. });
  9328. this.registerFunction('torch.serialization._get_layout', (name) => {
  9329. const value = name.startsWith('torch.') ? torch[name.split('.')[1]] : null;
  9330. return value instanceof torch.layout ? value : null;
  9331. });
  9332. this.registerFunction('torch.storage._load_from_bytes', (b) => {
  9333. return torch.load(b);
  9334. });
  9335. this.registerFunction('torch.jit._pickle.build_boollist', (data) => {
  9336. return data;
  9337. });
  9338. this.registerFunction('torch.jit._pickle.build_doublelist', (data) => {
  9339. return data;
  9340. });
  9341. this.registerFunction('torch.jit._pickle.build_intlist', (data) => {
  9342. return data;
  9343. });
  9344. this.registerFunction('torch.jit._pickle.build_tensorlist', (data) => {
  9345. return data;
  9346. });
  9347. this.registerFunction('torch.jit._pickle.build_tensor_from_id', (data) => {
  9348. return self.builtins.CONSTANTS[`c${data}`];
  9349. });
  9350. this.registerFunction('torch.jit._pickle.restore_type_tag', (value /*, type_str */) => {
  9351. return value;
  9352. });
  9353. this.registerOperator('aten::keys', (dict) => {
  9354. return Object.keys(dict);
  9355. });
  9356. this.registerOperator('aten::len', (value) => {
  9357. if (Array.isArray(value)) {
  9358. return value.length;
  9359. }
  9360. if (value && value.shape && value.__len__) {
  9361. return value.__len__();
  9362. }
  9363. return NaN;
  9364. });
  9365. this.registerOperator('aten::le', (left, right) => {
  9366. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9367. if (isNaN(left) || isNaN(right)) {
  9368. return false;
  9369. }
  9370. return left <= right;
  9371. }
  9372. if (left === undefined || right === undefined) {
  9373. return true;
  9374. }
  9375. throw new python.Error("Unsupported 'torch.le' expression type.");
  9376. });
  9377. this.registerOperator('aten::list', (args) => {
  9378. return args;
  9379. });
  9380. this.registerOperator('aten::list_with_default', (size /*, defaults */) => {
  9381. return size;
  9382. });
  9383. this.registerType('torch.PyTorchFileReader', class {
  9384. constructor(entries) {
  9385. let prefix = 0;
  9386. const paths = Array.from(entries.keys()).map((path) => path.replace(/\\/g, '/').split('/').reverse());
  9387. for (let set = new Set(); set && paths.length > 0;) {
  9388. set = new Set(paths.map((path) => path.length > 1 ? path.pop() : null));
  9389. set = set.size > 1 || set.keys().next().value === null ? null : set;
  9390. prefix += set ? set.keys().next().value.length + 1 : 0;
  9391. }
  9392. this._records = new Map(Array.from(entries).map(([name, value]) => [name.substring(prefix), value]));
  9393. this._version = 0;
  9394. this.init();
  9395. }
  9396. init() {
  9397. let stream = null;
  9398. if (this.has_record('.data/version')) {
  9399. stream = this.get_record('.data/version');
  9400. } else if (this.has_record('version')) {
  9401. stream = this.get_record('version');
  9402. }
  9403. if (stream) {
  9404. const decoder = new TextDecoder('utf-8');
  9405. const buffer = stream.peek();
  9406. const text = decoder.decode(buffer);
  9407. this._version = Number(text.split('\n').shift().trim());
  9408. }
  9409. }
  9410. has_record(name) {
  9411. return this._records.has(name);
  9412. }
  9413. get_record(name) {
  9414. if (!this.has_record(name)) {
  9415. throw new python.Error(`Record '${name}' not found.`);
  9416. }
  9417. return this._records.get(name);
  9418. }
  9419. get_all_records() {
  9420. return Array.from(this._records.keys());
  9421. }
  9422. version() {
  9423. return this._version;
  9424. }
  9425. });
  9426. this.registerFunction('torch.load', (f) => {
  9427. const legacy_load = (entries) => {
  9428. const deserialized_objects = {};
  9429. if (entries.has('storages')) {
  9430. const data = entries.get('storages');
  9431. const unpickler = new pickle.Unpickler(data);
  9432. const num_storages = unpickler.load();
  9433. for (let i = 0; i < num_storages; i++) {
  9434. const args = unpickler.load();
  9435. const [key, , storage_type] = args;
  9436. const obj = storage_type._new_with_file(unpickler);
  9437. deserialized_objects[key] = obj;
  9438. }
  9439. /*
  9440. let storage_views = unpickler.load();
  9441. for target_cdata, root_cdata, offset, size in storage_views:
  9442. root = deserialized_objects[root_cdata]
  9443. deserialized_objects[target_cdata] = root[offset:offset + size]
  9444. */
  9445. }
  9446. if (entries.has('tensors')) {
  9447. const data = entries.get('tensors');
  9448. const unpickler = new pickle.Unpickler(data);
  9449. const num_tensors = unpickler.load();
  9450. const int32 = (unpickler) => {
  9451. const buffer = unpickler.read(4);
  9452. return buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24);
  9453. };
  9454. const int64 = (unpickler) => {
  9455. const buffer = unpickler.read(8);
  9456. if (buffer[6] !== 0 && buffer[7] !== 0) {
  9457. throw new python.Error('Unsigned 64-bit value exceeds 32-bit range.');
  9458. }
  9459. return buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24) + (buffer[4] * 4294967296) + (buffer[5] * 1099511627776);
  9460. };
  9461. for (let i = 0; i < num_tensors; i++) {
  9462. const args = unpickler.load();
  9463. const [key, storage_id] = args;
  9464. const storage = deserialized_objects[storage_id];
  9465. const ndim = int32(unpickler);
  9466. unpickler.read(4);
  9467. const shape = Array.from(new Array(ndim)).map(() => int64(unpickler));
  9468. const stride = Array.from(new Array(ndim)).map(() => int64(unpickler));
  9469. const storage_offset = int64(unpickler);
  9470. const tensor = torch._utils._rebuild_tensor(storage, storage_offset, shape, stride);
  9471. deserialized_objects[key] = tensor;
  9472. }
  9473. }
  9474. const data = entries.get('pickle');
  9475. const unpickler = new pickle.Unpickler(data);
  9476. unpickler.persistent_load = (saved_id) => deserialized_objects[saved_id];
  9477. return unpickler.load();
  9478. };
  9479. const _legacy_load = () => {
  9480. const unpickler = new pickle.Unpickler(f);
  9481. unpickler.load(); // magic_number
  9482. const protocol_version = unpickler.load();
  9483. if (protocol_version !== 1001) {
  9484. throw new python.Error(`Unsupported protocol version '${protocol_version}'.`);
  9485. }
  9486. const sys_info = unpickler.load();
  9487. if (sys_info.get('protocol_version') !== 1001) {
  9488. throw new python.Error(`Unsupported protocol version '${sys_info.protocol_version}'.`);
  9489. }
  9490. if (sys_info.get('little_endian') === false) {
  9491. throw new python.Error("Unsupported big-endian storage data.");
  9492. }
  9493. const module_source_map = new Map();
  9494. const deserialized_objects = new Map();
  9495. unpickler.persistent_load = (saved_id) => {
  9496. switch (saved_id[0]) {
  9497. case 'module': {
  9498. const [, module, ,source] = saved_id;
  9499. module_source_map.set(module, source);
  9500. return saved_id[1];
  9501. }
  9502. case 'storage': {
  9503. const [, storage_type, key, , size, view_metadata] = saved_id;
  9504. if (!deserialized_objects.has(key)) {
  9505. const obj = new storage_type(size);
  9506. deserialized_objects.set(key, obj);
  9507. }
  9508. if (view_metadata) {
  9509. const view_key = view_metadata.shift();
  9510. view_metadata.shift(); // view_offset
  9511. view_metadata.shift(); // view_size
  9512. if (!deserialized_objects.has(view_key)) {
  9513. const view = null; // storage.slice(view_offset, view_offset + view_size);
  9514. deserialized_objects.set(view_key, view);
  9515. }
  9516. return deserialized_objects.get(view_key);
  9517. }
  9518. return deserialized_objects.get(key);
  9519. }
  9520. default: {
  9521. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  9522. }
  9523. }
  9524. };
  9525. const obj = unpickler.load();
  9526. const deserialized_storage_keys = unpickler.load();
  9527. for (const deserialized_storage_key of deserialized_storage_keys) {
  9528. const storage = deserialized_objects.get(deserialized_storage_key);
  9529. storage._set_from_file(unpickler);
  9530. }
  9531. if (!obj) {
  9532. throw new python.Error('File format is not PyTorch.');
  9533. }
  9534. if (obj === 'None') {
  9535. throw new python.Error("File contains 'None' root object.");
  9536. }
  9537. return obj;
  9538. };
  9539. const _load = (entries) => {
  9540. if (f.has('constant.pkl')) {
  9541. throw python.Error("TorchScript 'torch.load' not supported.");
  9542. }
  9543. const loaded_storages = new Map();
  9544. const persistent_load = (saved_id) => {
  9545. switch (saved_id[0]) {
  9546. case 'storage': {
  9547. const [, storage_type, key, , numel] = saved_id;
  9548. if (!loaded_storages.has(key)) {
  9549. const storage = new storage_type(numel);
  9550. if (!storage._set_cdata) {
  9551. throw new python.Error(`'${storage_type.__name__}._set_cdata' is not a function.`);
  9552. }
  9553. const name = `data/${key}`;
  9554. const stream = entries.get(name);
  9555. if (!stream) {
  9556. throw new python.Error(`Record '${name}' not found.`);
  9557. }
  9558. storage._set_cdata(stream);
  9559. loaded_storages.set(key, storage);
  9560. }
  9561. return loaded_storages.get(key);
  9562. }
  9563. default: {
  9564. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  9565. }
  9566. }
  9567. };
  9568. const data_file = entries.get('data.pkl');
  9569. const unpickler = new pickle.Unpickler(data_file);
  9570. unpickler.persistent_load = persistent_load;
  9571. const result = unpickler.load();
  9572. return result;
  9573. };
  9574. if (f instanceof Map) {
  9575. const reader = new torch.PyTorchFileReader(f);
  9576. const records = reader.get_all_records().map((name) => [name, reader.get_record(name)]);
  9577. f = new Map(records);
  9578. if (f.has('pickle')) {
  9579. return legacy_load(f);
  9580. }
  9581. if (f.has('data.pkl')) {
  9582. return _load(f);
  9583. }
  9584. throw new python.Error(`Unsupported 'torch.load' input '${JSON.stringify(Array.from(f.keys()))}'.`);
  9585. }
  9586. return _legacy_load(f);
  9587. });
  9588. this.registerOperator('prim::abs', (a) => {
  9589. if (typeof a === 'number' || a instanceof Number) {
  9590. return Math.abs(a);
  9591. }
  9592. if (a instanceof builtins.complex) {
  9593. return Math.hypot(a.real, a.imag);
  9594. }
  9595. throw new python.Error('Unsupported prim::abs expression type.');
  9596. });
  9597. this.registerOperator('prim::unchecked_cast', (type, value) => {
  9598. return value;
  9599. });
  9600. this.registerOperator('prim::data', (tensor) => {
  9601. return tensor;
  9602. });
  9603. this.registerOperator('prim::device', (tensor) => {
  9604. return tensor.device;
  9605. });
  9606. this.registerOperator('prim::dtype', (tensor) => {
  9607. return tensor.dtype.scalar_type();
  9608. });
  9609. this.registerOperator('prim::is_quantized', (tensor) => {
  9610. return tensor.is_quantized;
  9611. });
  9612. this.registerOperator('prim::is_cuda', (/* tensor */) => {
  9613. return false;
  9614. });
  9615. this.registerOperator('prim::is_nested', (tensor) => {
  9616. return tensor.is_nested;
  9617. });
  9618. this.registerOperator('prim::is_sparse', (tensor) => {
  9619. return tensor.is_sparse;
  9620. });
  9621. this.registerOperator('prim::unchecked_unwrap_optional', (value) => {
  9622. return value;
  9623. });
  9624. this.registerOperator('prim::NumToTensor', (value) => {
  9625. const tensor = self.invoke('torch.Tensor', []);
  9626. tensor.value = value;
  9627. return tensor;
  9628. });
  9629. this.registerOperator('prim::min', (...args) => {
  9630. if (Array.isArray(args[0])) {
  9631. return Math.min.apply(null, args[0]);
  9632. }
  9633. return Math.min.apply(null, args);
  9634. });
  9635. this.registerOperator('prim::max', (...args) => {
  9636. if (Array.isArray(args[0])) {
  9637. return Math.max.apply(null, args[0]);
  9638. }
  9639. return Math.max.apply(null, args);
  9640. });
  9641. this.registerOperator('prim::shape', (tensor) => {
  9642. return tensor && tensor.size ? tensor.size() : undefined;
  9643. });
  9644. this.registerOperator('quantized::conv_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9645. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9646. params.weight = weight;
  9647. params.bias = bias;
  9648. params.stride = stride;
  9649. params.padding = padding;
  9650. params.dilation = dilation;
  9651. params.groups = groups;
  9652. return params;
  9653. });
  9654. this.registerOperator('quantized::conv1d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9655. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9656. params.weight = weight;
  9657. params.bias = bias;
  9658. params.stride = stride;
  9659. params.padding = padding;
  9660. params.dilation = dilation;
  9661. params.groups = groups;
  9662. return params;
  9663. });
  9664. this.registerOperator('quantized::conv2d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9665. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9666. params.weight = weight;
  9667. params.bias = bias;
  9668. params.stride = stride;
  9669. params.padding = padding;
  9670. params.dilation = dilation;
  9671. params.groups = groups;
  9672. return params;
  9673. });
  9674. this.registerOperator('quantized::conv3d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9675. const params = self.invoke('__torch__.torch.classes.quantized.Conv3dPackedParamsBase', []);
  9676. params.weight = weight;
  9677. params.bias = bias;
  9678. params.stride = stride;
  9679. params.padding = padding;
  9680. params.dilation = dilation;
  9681. params.groups = groups;
  9682. return params;
  9683. });
  9684. this.registerOperator('quantized::conv_transpose1d_prepack', (weight, bias, stride, padding, output_padding, dilation, groups) => {
  9685. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9686. params.weight = weight;
  9687. params.bias = bias;
  9688. params.stride = stride;
  9689. params.padding = padding;
  9690. params.output_padding = output_padding;
  9691. params.dilation = dilation;
  9692. params.groups = groups;
  9693. return params;
  9694. });
  9695. this.registerOperator('quantized::conv_transpose2d_prepack', (weight, bias, stride, padding, output_padding, dilation, groups) => {
  9696. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9697. params.weight = weight;
  9698. params.bias = bias;
  9699. params.stride = stride;
  9700. params.padding = padding;
  9701. params.output_padding = output_padding;
  9702. params.dilation = dilation;
  9703. params.groups = groups;
  9704. return params;
  9705. });
  9706. this.registerOperator('quantized::linear_prepack', (weight, bias) => {
  9707. const params = self.invoke('__torch__.torch.classes.quantized.LinearPackedParamsBase', []);
  9708. params.weight = weight;
  9709. params.bias = bias;
  9710. return params;
  9711. });
  9712. this.registerOperator('prim::RaiseException', (message) => {
  9713. throw new python.Error(message);
  9714. });
  9715. this.registerOperator('prim::TupleIndex', (t, i) => {
  9716. return t.elements()[i];
  9717. });
  9718. this.registerOperator('prim::TupleUnpack', (t) => {
  9719. return t.elements();
  9720. });
  9721. this.registerOperator('aten::is_scripting', () => {
  9722. return true;
  9723. });
  9724. this.registerOperator('aten::__and__', (left, right) => {
  9725. return left && right;
  9726. });
  9727. this.registerOperator('aten::__contains__', (dict, key) => {
  9728. return builtins.hasattr(dict, key);
  9729. });
  9730. this.registerFunction('torch.__derive_index', (index, start, step) => {
  9731. return start + index * step;
  9732. });
  9733. this.registerOperator('aten::__is__', (left, right) => {
  9734. return left === right;
  9735. });
  9736. this.registerOperator('aten::__isnot__', (left, right) => {
  9737. return left !== right;
  9738. });
  9739. this.registerOperator('aten::__not__', (value) => {
  9740. if (Number.isInteger(value)) {
  9741. value = Boolean(value);
  9742. }
  9743. if (typeof value === 'boolean') {
  9744. return !value;
  9745. }
  9746. throw new python.Error("Unsupported 'ops.aten.__not__' expression type.");
  9747. });
  9748. this.registerOperator('aten::log10', (value) => {
  9749. return Math.log10(value);
  9750. });
  9751. this.registerOperator('aten::device', (type, index) => {
  9752. return new torch.device(type, index);
  9753. });
  9754. this.registerOperator('aten::lt', (left, right) => {
  9755. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9756. return left < right;
  9757. }
  9758. throw new python.Error("Unsupported 'ops.aten.lt' expression type.");
  9759. });
  9760. this.registerOperator('aten::mul', (left, right) => {
  9761. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9762. return left * right;
  9763. }
  9764. if (isNaN(left) || isNaN(right)) {
  9765. return NaN;
  9766. }
  9767. if (Array.isArray(left) && left.every((value) => typeof value === 'number' || value instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9768. return left.map((value) => value * right);
  9769. }
  9770. throw new python.Error("Unsupported 'ops.aten.mul' expression type.");
  9771. });
  9772. this.registerOperator('aten::div', (left, right) => {
  9773. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9774. return left / right;
  9775. }
  9776. if (isNaN(left) || isNaN(right)) {
  9777. return NaN;
  9778. }
  9779. throw new python.Error("Unsupported 'ops.aten.div' expression type.");
  9780. });
  9781. this.registerFunction('torch.round', (value) => {
  9782. if (typeof value === 'number' || value instanceof Number) {
  9783. return Math.round(value);
  9784. }
  9785. if (isNaN(value)) {
  9786. return value;
  9787. }
  9788. throw new python.Error("Unsupported 'torch.round' expression type.");
  9789. });
  9790. this.registerOperator('aten::remainder', (left, right) => {
  9791. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9792. return left % right;
  9793. }
  9794. if (isNaN(left) || isNaN(right)) {
  9795. return NaN;
  9796. }
  9797. throw new python.Error("Unsupported 'ops.aten.remainder' expression type.");
  9798. });
  9799. this.registerOperator('aten::ne', (left, right) => {
  9800. if (typeof left === 'boolean' && typeof right === 'boolean') {
  9801. return left !== right;
  9802. }
  9803. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9804. if (isNaN(left) || isNaN(right)) {
  9805. return false;
  9806. }
  9807. return left !== right;
  9808. }
  9809. if (Array.isArray(left) && Array.isArray(right) && left.length === right.length) {
  9810. return false;
  9811. }
  9812. if (typeof left === 'string' && typeof right === 'string') {
  9813. return left !== right;
  9814. }
  9815. if (left === undefined || right === undefined) {
  9816. return true;
  9817. }
  9818. throw new python.Error("Unsupported 'ops.aten.ne' expression type.");
  9819. });
  9820. this.registerOperator('aten::neg', (value) => {
  9821. if (typeof value === 'number') {
  9822. return -value;
  9823. }
  9824. throw new python.Error("Unsupported 'ops.aten.neg' expression type.");
  9825. });
  9826. this.registerOperator('aten::pow', (left, right) => {
  9827. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9828. return Math.pow(left, right);
  9829. }
  9830. throw new python.Error("Unsupported 'ops.aten.pow' expression type.");
  9831. });
  9832. this.registerFunction('torch.q_scale', (/* tensor */) => {
  9833. return -1;
  9834. });
  9835. this.registerFunction('torch.t', (tensor) => {
  9836. return tensor;
  9837. });
  9838. this.registerOperator('aten::size', (tensor, dim) => {
  9839. if (tensor && tensor.size) {
  9840. const size = tensor.size();
  9841. if (Array.isArray(size)) {
  9842. if (dim === undefined) {
  9843. return size;
  9844. }
  9845. if (Number.isInteger(dim)) {
  9846. if (dim >= 0 && dim < size.length) {
  9847. return size[dim];
  9848. }
  9849. if (dim < 0 && -dim < size.length) {
  9850. return size[size.length + dim];
  9851. }
  9852. }
  9853. throw new python.Error(`Dimension out of range (expected to be in range of ${JSON.stringify(size)}, but got ${JSON.stringify(dim)}).`);
  9854. }
  9855. }
  9856. if (Number.isInteger(dim)) {
  9857. return NaN;
  9858. }
  9859. return [];
  9860. });
  9861. this.registerFunction('aten::sqrt', (x) => {
  9862. return Math.sqrt(x);
  9863. });
  9864. this.registerOperator('aten::slice', (l, start, end, step) => {
  9865. if (!Array.isArray(l)) {
  9866. throw new python.Error('Slicing expected array');
  9867. }
  9868. step = step || 1;
  9869. if (step !== 1) {
  9870. throw new python.Error('Slicing only supports step=1');
  9871. }
  9872. start = Math.max(0, start >= 0 ? start : l.length + start);
  9873. end = Math.min(l.length, end || Number.MAX_SAFE_INTEGER);
  9874. return l.slice(start, end);
  9875. });
  9876. this.registerOperator('aten::sub', (left, right) => {
  9877. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9878. return left - right;
  9879. }
  9880. if (typeof left === 'number' && right instanceof builtins.complex) {
  9881. return new builtins.complex(left - right.real, right.imag);
  9882. }
  9883. if (left instanceof builtins.complex && typeof right === 'number') {
  9884. return new builtins.complex(left.real - right, left.imag);
  9885. }
  9886. if (left instanceof builtins.complex && right instanceof builtins.complex) {
  9887. return new builtins.complex(left.real - right.real, left.imag - right.imag);
  9888. }
  9889. throw new python.Error("Unsupported 'torch.sub' expression type.");
  9890. });
  9891. this.registerFunction('torch.sym_int');
  9892. this.registerFunction('torch.sym_float');
  9893. this.registerFunction('torch.sym_ite');
  9894. this.registerFunction('torch.sym_max');
  9895. this.registerFunction('torch.sym_min');
  9896. this.registerFunction('torch.sym_not');
  9897. this.registerFunction('torch.sym_sqrt');
  9898. this.registerFunction('torch.sym_sqrt');
  9899. this.registerFunction('torch.functional.einsum');
  9900. this.registerFunction('torch.functional.norm');
  9901. this.registerFunction('torch.functional.split');
  9902. this.registerFunction('torch.nn.init.constant_');
  9903. this.registerFunction('torch.nn.init.normal_');
  9904. this.registerFunction('torch.nn.init.xavier_uniform_');
  9905. this.registerFunction('torch.nn.functional.adaptive_avg_pool2d');
  9906. this.registerFunction('torch.nn.functional.binary_cross_entropy');
  9907. this.registerFunction('torch.nn.functional.binary_cross_entropy_with_logits');
  9908. this.registerFunction('torch.nn.functional.cross_entropy');
  9909. this.registerFunction('torch.nn.functional.elu');
  9910. this.registerFunction('torch.nn.functional.gelu');
  9911. this.registerFunction('torch.nn.functional.hardsigmoid');
  9912. this.registerFunction('torch.nn.functional.hardswish');
  9913. this.registerFunction('torch.nn.functional.hardtanh');
  9914. this.registerFunction('torch.nn.functional.interpolate');
  9915. this.registerFunction('torch.nn.functional.leaky_relu');
  9916. this.registerFunction('torch.nn.functional.l1_loss');
  9917. this.registerFunction('torch.nn.functional.linear');
  9918. this.registerFunction('torch.nn.functional.log_softmax');
  9919. this.registerFunction('torch.nn.functional._max_pool2d');
  9920. this.registerFunction('torch.nn.functional.max_pool2d_with_indices');
  9921. this.registerFunction('torch.nn.functional.mse_loss');
  9922. this.registerFunction('torch.nn.functional.pad');
  9923. this.registerFunction('torch.nn.functional.relu');
  9924. this.registerFunction('torch.nn.functional.relu6');
  9925. this.registerFunction('torch.nn.functional.sigmoid');
  9926. this.registerFunction('torch.nn.functional.silu');
  9927. this.registerFunction('torch.nn.functional.softmax');
  9928. this.registerFunction('torch.nn.functional.tanh');
  9929. this.registerFunction('torch.values', (dict) => {
  9930. return Object.values(dict);
  9931. });
  9932. this.registerFunction('torch.warn', () => {
  9933. });
  9934. this.registerType('torch._ops.OperatorBase', class {
  9935. constructor() {
  9936. this.functorch_table = {};
  9937. }
  9938. });
  9939. this.registerType('torch._ops.HigherOrderOperator', class extends torch._ops.OperatorBase {
  9940. constructor(name, cacheable) {
  9941. super();
  9942. this._name = name;
  9943. this.__name__ = name;
  9944. this._ns = 'higher_order';
  9945. this.__module__ = 'torch.ops.higher_order';
  9946. this._cacheable = cacheable;
  9947. }
  9948. get namespace() {
  9949. return this._ns;
  9950. }
  9951. get name() {
  9952. return this._name;
  9953. }
  9954. });
  9955. this.registerType('torch._higher_order_ops.wrap.WrapWithAutocast', class extends torch._ops.HigherOrderOperator {
  9956. constructor(name) {
  9957. super(name, false);
  9958. this._schema = torch.FunctionSchema.parse('higher_order::wrap_with_autocast(str device_type, ScalarType? dtype, bool enabled, bool? cache_enabled, Any wrapped_func, ...) -> Tensor');
  9959. }
  9960. });
  9961. torch.ops.higher_order.wrap_with_autocast = new torch._higher_order_ops.wrap.WrapWithAutocast('wrap_with_autocast');
  9962. this.registerType('torch._higher_order_ops.wrap.WrapWithSetGradEnabled', class extends torch._ops.HigherOrderOperator {
  9963. constructor(name) {
  9964. super(name, false);
  9965. this._schema = torch.FunctionSchema.parse('higher_order::wrap_with_set_grad_enabled(bool enable_grad, Any wrapped_func) -> Tensor');
  9966. }
  9967. });
  9968. torch.ops.higher_order.wrap_with_set_grad_enabled = new torch._higher_order_ops.wrap.WrapWithSetGradEnabled('wrap_with_set_grad_enabled');
  9969. this.registerType('torch._higher_order_ops.wrap.Wrap', class extends torch._ops.HigherOrderOperator {
  9970. constructor(name) {
  9971. super(name, false);
  9972. this._schema = torch.FunctionSchema.parse('higher_order::wrap(Any func) -> Tensor');
  9973. }
  9974. });
  9975. torch.ops.higher_order.wrap = new torch._higher_order_ops.wrap.Wrap('wrap');
  9976. this.registerType('torch._higher_order_ops.wrap.WrapActivationCheckpoint', class extends torch._ops.HigherOrderOperator {
  9977. constructor(name) {
  9978. super(name, false);
  9979. }
  9980. });
  9981. torch.ops.higher_order.wrap_activation_checkpoint = new torch._higher_order_ops.wrap.WrapActivationCheckpoint('wrap_activation_checkpoint', false);
  9982. this.registerType('torch._higher_order_ops.wrap.TagActivationCheckpoint', class extends torch._ops.HigherOrderOperator {
  9983. constructor(name) {
  9984. super(name, false);
  9985. }
  9986. });
  9987. torch.ops.higher_order.tag_activation_checkpoint = new torch._higher_order_ops.wrap.TagActivationCheckpoint('tag_activation_checkpoint', false);
  9988. this.registerType('torch.Type', class {
  9989. constructor(kind, annotation_str) {
  9990. this._kind = kind;
  9991. if (annotation_str) {
  9992. this._annotation_str = annotation_str;
  9993. }
  9994. }
  9995. static get(kind, annotation_str) {
  9996. torch.Type.cache = torch.Type.cache || new Map();
  9997. if (!annotation_str) {
  9998. if (!torch.Type.cache.has(kind)) {
  9999. torch.Type.cache.set(kind, new torch.Type(kind));
  10000. }
  10001. return torch.Type.cache.get(kind);
  10002. }
  10003. return new torch.Type(kind, annotation_str);
  10004. }
  10005. kind() {
  10006. return this._kind;
  10007. }
  10008. get annotation_str() {
  10009. return this._annotation_str;
  10010. }
  10011. equals(rhs) {
  10012. return this.kind() === rhs.kind();
  10013. }
  10014. isSubtypeOf(rhs) {
  10015. if (rhs.kind() === 'AnyType' || this === rhs) {
  10016. return true;
  10017. }
  10018. if (rhs instanceof torch.OptionalType && this instanceof torch.OptionalType === false) {
  10019. return this.isSubtypeOf(rhs.getElementType());
  10020. }
  10021. if (rhs instanceof torch.UnionType) {
  10022. return rhs.containedTypes().some((inner) => this.isSubtypeOf(inner));
  10023. }
  10024. if (rhs instanceof torch._C.DynamicType) {
  10025. return torch._C.DynamicType.create(this).isSubtypeOf(rhs);
  10026. }
  10027. return this.equals(rhs);
  10028. }
  10029. containedTypes() {
  10030. return [];
  10031. }
  10032. containedType(i) {
  10033. return this.containedTypes()[i];
  10034. }
  10035. withContained(contained_types) {
  10036. const current_contained = this.containedTypes();
  10037. torch._C.TORCH_INTERNAL_ASSERT(current_contained.length > 0 && current_contained.length === contained_types.length);
  10038. if (current_contained.length === contained_types.length && current_contained.every((x, index) => x === contained_types[index])) {
  10039. return this;
  10040. }
  10041. return this.createWithContained(contained_types);
  10042. }
  10043. createWithContained(/* createWithContained */) {
  10044. throw new python.Error('Not implemented.');
  10045. }
  10046. isUnionType() {
  10047. return false;
  10048. }
  10049. hasFreeVariables() {
  10050. return false;
  10051. }
  10052. is_module() {
  10053. return false;
  10054. }
  10055. expect(type) {
  10056. torch._C.AT_ASSERT(this instanceof type);
  10057. return this;
  10058. }
  10059. str() {
  10060. if (this instanceof torch._C.VarType && this._annotation_str) {
  10061. return this._annotation_str;
  10062. } else if (this._kind === 'ScalarTypeType') {
  10063. return 'ScalarType';
  10064. } else if (this._kind === 'QSchemeType') {
  10065. return 'QScheme';
  10066. } else if (this._kind) {
  10067. return this._kind;
  10068. }
  10069. throw new python.Error(`Not implemented '${this.kind()}'.`);
  10070. }
  10071. __str__() {
  10072. return this.str();
  10073. }
  10074. toString() {
  10075. return this.__str__();
  10076. }
  10077. });
  10078. this.registerType('torch.ClassType', class extends torch.Type {
  10079. constructor(qualified_name, cu, is_module) {
  10080. super('ClassType', typeof qualified_name === 'string' ? qualified_name : qualified_name.qualifiedName());
  10081. this._name = typeof qualified_name === 'string' ? new torch._C.QualifiedName(qualified_name) : qualified_name;
  10082. this._is_module = is_module;
  10083. this._attributes = [];
  10084. this._attributeTypes = [];
  10085. this._methods = [];
  10086. this._staticmethods = new Map();
  10087. this._forward_hooks = [];
  10088. this._forward_pre_hooks = [];
  10089. this._properties = [];
  10090. this._constants = new Map();
  10091. }
  10092. static create(qualifiedName, cu, is_module /*, doc_string, unresolved_class_attributes */) {
  10093. return new torch.ClassType(qualifiedName, cu, is_module);
  10094. }
  10095. qualified_name() {
  10096. return this.annotation_str;
  10097. }
  10098. name() {
  10099. return this._name;
  10100. }
  10101. is_module() {
  10102. return this._is_module;
  10103. }
  10104. is_parameter(slot) {
  10105. return this._attributes[slot].is_parameter === true;
  10106. }
  10107. is_buffer(slot) {
  10108. return this._attributes[slot].is_buffer === true;
  10109. }
  10110. addMethod(method) {
  10111. torch._C.TORCH_CHECK(this.findMethod(method.name()) === null);
  10112. this._methods.push(method);
  10113. }
  10114. findMethod(name) {
  10115. for (const method of this._methods) {
  10116. if (name === method.name()) {
  10117. return method;
  10118. }
  10119. }
  10120. return null;
  10121. }
  10122. getMethod(name) {
  10123. const method = this.findMethod(name);
  10124. if (!method) {
  10125. throw new python.Error(`Method '${name}' not found on class '${this.str()}.`);
  10126. }
  10127. return method;
  10128. }
  10129. methods() {
  10130. return this._methods;
  10131. }
  10132. addStaticMethod(func) {
  10133. this._staticmethods.set(func.name, func);
  10134. }
  10135. findStaticMethod(name) {
  10136. return this._staticmethods.get(name);
  10137. }
  10138. findHook(name) {
  10139. let hook = this.findForwardHook(name);
  10140. if (hook === null) {
  10141. hook = this.findForwardPreHook(name);
  10142. }
  10143. return hook;
  10144. }
  10145. findForwardHook(name) {
  10146. for (const hook of this._forward_hooks) {
  10147. if (name === hook.name()) {
  10148. return hook;
  10149. }
  10150. }
  10151. return null;
  10152. }
  10153. findForwardPreHook(name) {
  10154. for (const pre_hook of this._forward_pre_hooks) {
  10155. if (name === pre_hook.name()) {
  10156. return pre_hook;
  10157. }
  10158. }
  10159. return null;
  10160. }
  10161. numAttributes() {
  10162. return this._attributes.length;
  10163. }
  10164. addAttribute(name, type, is_parameter, is_buffer) {
  10165. is_parameter = is_parameter || false;
  10166. is_buffer = is_buffer || false;
  10167. const slot = this._attributes.length;
  10168. this._attributes.push({ name, type, is_parameter, is_buffer });
  10169. this._attributeTypes.push(type);
  10170. return slot;
  10171. }
  10172. addOrCheckAttribute(name, ty, is_parameter, is_buffer) {
  10173. is_parameter = is_parameter || false;
  10174. is_buffer = is_buffer || false;
  10175. const slot_idx = this.findAttributeSlot(name);
  10176. if (slot_idx === null) {
  10177. return this.addAttribute(name, ty, is_parameter, is_buffer);
  10178. }
  10179. // TORCH_CHECK(is_parameter == this.is_parameter(*slot_idx), "Parameter field mismatch for the field '", name, "'");
  10180. // const TypePtr& atype = getAttribute(*slot_idx);
  10181. // TORCH_CHECK(ty.isSubtypeOf(*atype), ty.repr_str(), " is not compatible with the type ", atype.repr_str(), " for the field '", name, "'");
  10182. return slot_idx;
  10183. }
  10184. findAttributeSlot(name) {
  10185. for (let pos = 0; pos < this._attributes.length; pos++) {
  10186. if (name === this._attributes[pos].name) {
  10187. return pos;
  10188. }
  10189. }
  10190. return null;
  10191. }
  10192. findAttribute(name) {
  10193. const slot = this.findAttributeSlot(name);
  10194. if (slot !== null) {
  10195. return this._attributes[slot].type;
  10196. }
  10197. return null;
  10198. }
  10199. hasAttribute(name) {
  10200. return this._attributes.find((attr) => attr.name === name);
  10201. }
  10202. getAttribute(arg) {
  10203. const slot = Number.isInteger(arg) ? arg : this.findAttributeSlot(arg);
  10204. return this._attributes[slot].type;
  10205. }
  10206. getAttributeName(slot) {
  10207. return this._attributes[slot].name;
  10208. }
  10209. addConstant(name, value) {
  10210. this._constants.set(name, value);
  10211. }
  10212. hasConstant(name) {
  10213. return this._constants.has(name);
  10214. }
  10215. getProperty(name) {
  10216. for (const prop of this._properties) {
  10217. if (name === prop.name) {
  10218. return prop;
  10219. }
  10220. }
  10221. return null;
  10222. }
  10223. containedTypes() {
  10224. return this._attributeTypes;
  10225. }
  10226. createWithContained(contained_types) {
  10227. const ptr = torch.ClassType.create(this.name(), this._compilation_unit, this.is_module());
  10228. torch._C.AT_ASSERT(this.numAttributes() === contained_types.length);
  10229. for (let i = 0; i < this._attributes.length; i++) {
  10230. torch._C.AT_ASSERT(this._attributes[i].type.isSubtypeOf(contained_types[i]));
  10231. ptr.addAttribute(this._attributes[i].name, contained_types[i]);
  10232. }
  10233. for (const method of this.methods()) {
  10234. ptr.addMethod(method);
  10235. }
  10236. return ptr;
  10237. }
  10238. str() {
  10239. return this.qualified_name();
  10240. }
  10241. });
  10242. this.registerType('torch.EnumType', class extends torch.Type {
  10243. constructor(qualified_class_name, value_type, enum_names_values, cu) {
  10244. super('EnumType', qualified_class_name);
  10245. this._name = qualified_class_name;
  10246. this._value_type = value_type;
  10247. this._enum_names_values = enum_names_values;
  10248. this._cu = cu;
  10249. }
  10250. static create(qualified_class_name, value, enum_names_values, cu) {
  10251. if (value instanceof torch.IntType || value instanceof torch.FloatType || value instanceof torch.StringType) {
  10252. return new torch.EnumType(qualified_class_name, value, enum_names_values, cu);
  10253. }
  10254. torch._C.TORCH_CHECK(false);
  10255. return null;
  10256. }
  10257. name() {
  10258. return this._name;
  10259. }
  10260. get annotation_str() {
  10261. return this._name.qualifiedName();
  10262. }
  10263. enumNamesValues() {
  10264. return this._enum_names_values;
  10265. }
  10266. compilation_unit() {
  10267. return this._cu;
  10268. }
  10269. getValueType() {
  10270. return this._value_type;
  10271. }
  10272. equals(rhs) {
  10273. if (rhs instanceof torch.EnumType) {
  10274. return this.name() && this.name() === rhs.name() && this.getValueType() === rhs.getValueType() && this.compilation_unit() === rhs.compilation_unit();
  10275. }
  10276. return false;
  10277. }
  10278. isSubtypeOf(rhs) {
  10279. if (rhs instanceof torch.AnyType || rhs.kind() === 'AnyEnumType' || this === rhs) {
  10280. return true;
  10281. }
  10282. return super.isSubtypeOf(rhs);
  10283. }
  10284. });
  10285. this.registerFunction('torch._C.standardizeVectorForUnion', (...args) => {
  10286. if (args.length === 1) {
  10287. const [to_flatten] = args;
  10288. torch._C.TORCH_INTERNAL_ASSERT(to_flatten !== null);
  10289. const to_fill = [];
  10290. torch._C.standardizeVectorForUnion(to_flatten, to_fill);
  10291. to_flatten.splice(0, to_flatten.length);
  10292. to_flatten.push(...to_fill);
  10293. } else if (args.length === 2) {
  10294. const [reference, to_fill] = args;
  10295. for (const type of reference) {
  10296. torch._C.flattenUnion(type, to_fill);
  10297. }
  10298. torch._C.filterDuplicateSubtypes(to_fill);
  10299. torch._C.sortUnion(to_fill);
  10300. } else {
  10301. throw new python.Error('Not implemented.');
  10302. }
  10303. });
  10304. this.registerFunction('torch._C.flattenUnion', (type, to_fill) => {
  10305. if (type instanceof torch.UnionType) {
  10306. for (const inner of type.containedTypes()) {
  10307. torch._C.flattenUnion(inner, to_fill);
  10308. }
  10309. } else if (type instanceof torch.OptionalType) {
  10310. const inner = type.getElementType();
  10311. torch._C.flattenUnion(inner, to_fill);
  10312. to_fill.push(torch.NoneType.get());
  10313. } else if (type instanceof torch.NumberType) {
  10314. to_fill.push(torch.IntType.get());
  10315. to_fill.push(torch.FloatType.get());
  10316. to_fill.push(torch.ComplexType.get());
  10317. } else {
  10318. to_fill.push(type);
  10319. }
  10320. });
  10321. this.registerFunction('torch._C.filterDuplicateSubtypes', (types) => {
  10322. if (types.length === 0) {
  10323. // return;
  10324. }
  10325. /*
  10326. const get_supertype = [](const TypePtr& t1, const TypePtr& t2) -> std::optional<TypePtr> {
  10327. // We don't want nested Optionals. Also, prematurely unifying to
  10328. // `Optional` could prevent us from coalescing other types
  10329. if ((t1->isSubtypeOf(*NoneType::get()) && !t2->isSubtypeOf(*NoneType::get()))
  10330. || (!t1->isSubtypeOf(*NoneType::get()) && t2->isSubtypeOf(*NoneType::get()))) {
  10331. return null;
  10332. } else {
  10333. return unifyTypes(t1, t2, default_to_union=false);
  10334. }
  10335. };
  10336. size_t end_idx = types->size()-1;
  10337. for (size_t i = types->size()-1; i > 0; --i) {
  10338. for (size_t j = std::min(i-1, end_idx); ; --j) {
  10339. std::optional<TypePtr> unified;
  10340. unified = get_supertype((*types)[i], (*types)[j]);
  10341. if (unified) {
  10342. (*types)[j] = *unified;
  10343. (*types)[i] = (*types)[end_idx];
  10344. --end_idx;
  10345. break;
  10346. }
  10347. if (j == 0) {
  10348. break;
  10349. }
  10350. }
  10351. }
  10352. types.erase(types->begin() + static_cast<std::ptrdiff_t>(end_idx) + 1, types->end());
  10353. */
  10354. });
  10355. this.registerFunction('torch._C.sortUnion', (/* types */) => {
  10356. /*
  10357. std::sort(types->begin(), types->end(),
  10358. [](const TypePtr& a, const TypePtr& b) -> bool {
  10359. if (a->kind() != b->kind()) {
  10360. return a->kind() < b->kind();
  10361. }
  10362. return a->str() < b->str();
  10363. });
  10364. */
  10365. });
  10366. this.registerType('torch.UnionType', class extends torch.Type {
  10367. constructor(reference, kind) {
  10368. super(kind || 'UnionType');
  10369. torch._C.TORCH_INTERNAL_ASSERT(reference.length > 0);
  10370. this._types = [];
  10371. torch._C.standardizeVectorForUnion(reference, this._types);
  10372. if (this._types.length === 1) {
  10373. throw new python.Error('Invalid union type reference.');
  10374. }
  10375. this._can_hold_none = false;
  10376. this._has_free_variables = false;
  10377. for (const type of this._types) {
  10378. if (type instanceof torch.NoneType) {
  10379. this._can_hold_none = true;
  10380. }
  10381. if (type.hasFreeVariables()) {
  10382. this._has_free_variables = true;
  10383. }
  10384. }
  10385. }
  10386. static create(reference) {
  10387. const union_type = new torch.UnionType(reference);
  10388. /*
  10389. bool int_found = false;
  10390. bool float_found = false;
  10391. bool complex_found = false;
  10392. bool nonetype_found = false;
  10393. const update_is_opt_flags = [&](const TypePtr& t) {
  10394. if (t == IntType::get()) {
  10395. int_found = true;
  10396. } else if (t == FloatType::get()) {
  10397. float_found = true;
  10398. } else if (t == ComplexType::get()) {
  10399. complex_found = true;
  10400. } else if (t == NoneType::get()) {
  10401. nonetype_found = true;
  10402. }
  10403. };
  10404. for (const auto& t : union_type->containedTypes()) {
  10405. update_is_opt_flags(t);
  10406. }
  10407. bool numbertype_found = int_found && float_found && complex_found;
  10408. if (nonetype_found) {
  10409. if (union_type->containedTypes().size() == 4 && numbertype_found) {
  10410. return OptionalType::create(NumberType::get());
  10411. }
  10412. if (union_type->containedTypes().size() == 2) {
  10413. const not_none = union_type->containedTypes()[0] != NoneType::get()
  10414. ? union_type->containedTypes()[0]
  10415. : union_type->containedTypes()[1];
  10416. return OptionalType::create(not_none);
  10417. }
  10418. }
  10419. */
  10420. return union_type;
  10421. }
  10422. containedTypes() {
  10423. return this._types;
  10424. }
  10425. isUnionType() {
  10426. return true;
  10427. }
  10428. hasFreeVariables() {
  10429. return this._has_free_variables;
  10430. }
  10431. equals(rhs) {
  10432. if (rhs instanceof torch.UnionType) {
  10433. if (rhs.containedTypes().length !== this.containedTypes().length) {
  10434. return false;
  10435. }
  10436. return this.containedTypes().every((lhs_type) => rhs.containedTypes().some((rhs_type) => lhs_type === rhs_type));
  10437. } else if (rhs instanceof torch.OptionalType) {
  10438. if (rhs.getElementType() === torch.NumberType.get()) {
  10439. return this.containedTypes().length === 4 && this._can_hold_none && this.canHoldType(torch.NumberType.get());
  10440. }
  10441. const optional_lhs = this.toOptional();
  10442. return optional_lhs && rhs === optional_lhs.expect(torch.OptionalType);
  10443. } else if (rhs instanceof torch.NumberType) {
  10444. return this.containedTypes().length === 3 && this.canHoldType(torch.NumberType.get());
  10445. }
  10446. return false;
  10447. }
  10448. isSubtypeOf(rhs) {
  10449. const rhs_types = [];
  10450. if (rhs instanceof torch.UnionType) {
  10451. if (this.containedTypes() === rhs.containedTypes()) {
  10452. return true;
  10453. }
  10454. for (const typePtr of rhs.containedTypes()) {
  10455. rhs_types.push(typePtr);
  10456. }
  10457. } else if (rhs instanceof torch.OptionalType) {
  10458. rhs_types.push(torch.NoneType.get());
  10459. if (rhs.getElementType() === torch.NumberType.get()) {
  10460. const number_types = [torch.IntType.get(), torch.FloatType.get(), torch.ComplexType.get()];
  10461. rhs_types.push(...number_types);
  10462. } else {
  10463. rhs_types.push(rhs.getElementType());
  10464. }
  10465. } else if (rhs instanceof torch.NumberType) {
  10466. const number_types = [torch.IntType.get(), torch.FloatType.get(), torch.ComplexType.get()];
  10467. rhs_types.push(...number_types);
  10468. } else {
  10469. rhs_types.push(rhs);
  10470. }
  10471. return this.containedTypes().every((lhs_type) => rhs_types.some((rhs_type) => lhs_type.isSubtypeOf(rhs_type)));
  10472. }
  10473. });
  10474. this.registerType('torch.OptionalType', class extends torch.UnionType {
  10475. constructor(contained) {
  10476. super([contained, torch.NoneType.get()], 'OptionalType');
  10477. let is_numbertype = false;
  10478. if (contained instanceof torch.UnionType) {
  10479. is_numbertype = contained.containedTypes().length === 3 && contained.canHoldType(torch.NumberType.get());
  10480. }
  10481. if (super.containedTypes().length === 2) {
  10482. this._contained = super.containedTypes()[0] instanceof torch.NoneType ? super.containedTypes()[1] : super.containedTypes()[0];
  10483. } else if (contained === torch.NumberType.get() || is_numbertype) {
  10484. this._contained = torch.NumberType.get();
  10485. this._types.splice(0, this._types.length);
  10486. this._types.push(torch.NumberType.get());
  10487. this._types.push(torch.NoneType.get());
  10488. } else {
  10489. const to_subtract = [torch.NoneType.get()];
  10490. const without_none = this.subtractTypeSetFrom(to_subtract, this._types);
  10491. this._contained = torch.UnionType.create([without_none]);
  10492. }
  10493. this._has_free_variables = contained.hasFreeVariables();
  10494. }
  10495. static create(elem) {
  10496. return new torch.OptionalType(elem);
  10497. }
  10498. getElementType() {
  10499. return this._contained;
  10500. }
  10501. equals(rhs) {
  10502. return this.kind() === rhs.kind() && this.getElementType().equals(rhs.getElementType());
  10503. }
  10504. isSubtypeOf(rhs) {
  10505. if (rhs instanceof torch.OptionalType) {
  10506. return this.getElementType().isSubtypeOf(rhs.getElementType());
  10507. } else if (rhs instanceof torch.UnionType) {
  10508. throw new python.Error('Not implemented.');
  10509. }
  10510. // return super.isSubtypeOf(rhs);
  10511. return torch.Type.prototype.isSubtypeOf.call(this, rhs);
  10512. }
  10513. containedTypes() {
  10514. return [this._contained];
  10515. }
  10516. createWithContained(contained_types) {
  10517. torch._C.AT_ASSERT(contained_types.length === 1);
  10518. return torch.OptionalType.create(contained_types[0]);
  10519. }
  10520. subtractTypeSetFrom(to_subtract, from) {
  10521. const types = [];
  10522. const should_subtract = (lhs) => to_subtract.some((rhs) => lhs.isSubtypeOf(rhs));
  10523. for (const t of from) {
  10524. if (!should_subtract(t)) {
  10525. types.push(t);
  10526. }
  10527. }
  10528. if (types.length === 0) {
  10529. return null;
  10530. } else if (types.length === 1) {
  10531. return types[0];
  10532. }
  10533. return torch.UnionType.create(types);
  10534. }
  10535. str() {
  10536. return `${this.getElementType().str()}?`;
  10537. }
  10538. __str__() {
  10539. return `Optional[${this.getElementType().__str__()}]`;
  10540. }
  10541. });
  10542. this.registerType('torch.ListType', class extends torch.Type {
  10543. constructor(elem) {
  10544. super('ListType');
  10545. this._elem = elem;
  10546. }
  10547. static create(elem) {
  10548. return new torch.ListType(elem);
  10549. }
  10550. getElementType() {
  10551. return this._elem;
  10552. }
  10553. equals(rhs) {
  10554. if (rhs instanceof torch.ListType) {
  10555. return this.getElementType().equals(rhs.getElementType());
  10556. }
  10557. return false;
  10558. }
  10559. isSubtypeOf(rhs) {
  10560. if (super.isSubtypeOf(rhs)) {
  10561. return true;
  10562. }
  10563. if (rhs.kind() === 'AnyListType') {
  10564. return true;
  10565. }
  10566. return false;
  10567. }
  10568. containedTypes() {
  10569. return [this._elem];
  10570. }
  10571. createWithContained(contained_types) {
  10572. return new torch.ListType(contained_types[0]);
  10573. }
  10574. hasFreeVariables() {
  10575. return this.getElementType().hasFreeVariables();
  10576. }
  10577. str() {
  10578. return `${this.getElementType().str()}[]`;
  10579. }
  10580. __str__() {
  10581. return `List[${this.getElementType().__str__()}]`;
  10582. }
  10583. });
  10584. this.registerType('torch.FutureType', class extends torch.Type {
  10585. constructor(elem) {
  10586. super('FutureType');
  10587. this._elem = elem;
  10588. }
  10589. static create(elem) {
  10590. return new torch.FutureType(elem);
  10591. }
  10592. getElementType() {
  10593. return this._elem;
  10594. }
  10595. containedTypes() {
  10596. throw new python.Error('Not implemented.');
  10597. }
  10598. str() {
  10599. return `Future(${this.getElementType().str()})`;
  10600. }
  10601. __str__() {
  10602. return `Future[${this.getElementType().__str__()}]`;
  10603. }
  10604. });
  10605. this.registerType('torch.RRefType', class extends torch.Type {
  10606. constructor(elem) {
  10607. super('RRefType');
  10608. this._elem = elem;
  10609. }
  10610. static create(elem) {
  10611. return new torch.RRefType(elem);
  10612. }
  10613. getElementType() {
  10614. return this._elem;
  10615. }
  10616. containedTypes() {
  10617. throw new python.Error('Not implemented.');
  10618. }
  10619. str() {
  10620. return `RRef(${this.getElementType().str()})`;
  10621. }
  10622. __str__() {
  10623. return `RRef[${this.getElementType().__str__()}]`;
  10624. }
  10625. });
  10626. this.registerType('torch.AwaitType', class extends torch.Type {
  10627. constructor(elem) {
  10628. super('AwaitType');
  10629. this._elem = elem;
  10630. }
  10631. static get(elem) {
  10632. return new torch.AwaitType(elem);
  10633. }
  10634. getElementType() {
  10635. return this._elem;
  10636. }
  10637. containedTypes() {
  10638. throw new python.Error('Not implemented.');
  10639. }
  10640. str() {
  10641. return `Await(${this.getElementType().str()})`;
  10642. }
  10643. __str__() {
  10644. return `Await[${this.getElementType().__str__()}]`;
  10645. }
  10646. });
  10647. this.registerType('torch.TupleType', class extends torch.Type {
  10648. constructor(elements, annotation_str, schema) {
  10649. super('TupleType', annotation_str);
  10650. this._elements = elements;
  10651. this._has_free_variables = elements.some((v) => {
  10652. if (!v) {
  10653. throw new python.Error('Can not create tuple with None type');
  10654. }
  10655. return v.hasFreeVariables();
  10656. });
  10657. this._schema = schema;
  10658. }
  10659. static create(elements) {
  10660. return new torch.TupleType(elements, null, null);
  10661. }
  10662. static createNamed(qualified_name, field_names, field_types /*, field_defaults */) {
  10663. const args = [];
  10664. for (let i = 0; i < field_names.length; i++) {
  10665. const arg = new torch.Argument(field_names[i], field_types[i], field_types[i]);
  10666. args.push(arg);
  10667. }
  10668. const schema = new torch.FunctionSchema(qualified_name, '', args, []);
  10669. return new torch.TupleType(field_types, qualified_name, schema);
  10670. }
  10671. elements() {
  10672. return this._elements;
  10673. }
  10674. name() {
  10675. return this.annotation_str;
  10676. }
  10677. containedTypes() {
  10678. return this._elements;
  10679. }
  10680. createWithContained(createWithContained) {
  10681. return new torch.TupleType(createWithContained, this.name(), this.schema());
  10682. }
  10683. hasFreeVariables() {
  10684. return this._has_free_variables;
  10685. }
  10686. schema() {
  10687. return this._schema;
  10688. }
  10689. str() {
  10690. if (this._schema) {
  10691. return `NamedTuple(...)`;
  10692. }
  10693. return `(${this.elements().map((elem) => elem.str()).join(', ')})`;
  10694. }
  10695. __str__() {
  10696. if (this.annotation_str) {
  10697. return this.annotation_str;
  10698. }
  10699. return `Tuple[${this.elements().map((elem) => elem.__str__()).join(', ')}]`;
  10700. }
  10701. });
  10702. this.registerType('torch.AnyType', class extends torch.Type {
  10703. constructor() {
  10704. super('AnyType');
  10705. }
  10706. static get() {
  10707. torch.AnyType.value = torch.AnyType.value || new torch.AnyType();
  10708. return torch.AnyType.value;
  10709. }
  10710. str() {
  10711. return 'Any';
  10712. }
  10713. __str__() {
  10714. return 'Any';
  10715. }
  10716. });
  10717. this.registerType('torch.NoneType', class extends torch.Type {
  10718. constructor() {
  10719. super('NoneType');
  10720. }
  10721. static get() {
  10722. torch.NoneType.value = torch.NoneType.value || new torch.NoneType();
  10723. return torch.NoneType.value;
  10724. }
  10725. equals(rhs) {
  10726. return this.kind() === rhs.kind();
  10727. }
  10728. isSubtypeOf(rhs) {
  10729. if (rhs.kind() === 'OptionalType') {
  10730. return true;
  10731. }
  10732. return super.isSubtypeOf(rhs);
  10733. }
  10734. str() {
  10735. return 'NoneType';
  10736. }
  10737. __str__() {
  10738. return 'NoneType';
  10739. }
  10740. });
  10741. this.registerType('torch.TensorType', class extends torch.Type {
  10742. constructor() {
  10743. super('TensorType');
  10744. this._is_inferred = false;
  10745. }
  10746. static get() {
  10747. torch.TensorType.value = torch.TensorType.value || new torch.TensorType();
  10748. return torch.TensorType.value;
  10749. }
  10750. equals(rhs) {
  10751. return this.kind() === rhs.kind();
  10752. }
  10753. isInferredType() {
  10754. return this._is_inferred;
  10755. }
  10756. str() {
  10757. return 'Tensor';
  10758. }
  10759. __str__() {
  10760. return 'Tensor';
  10761. }
  10762. });
  10763. this.registerType('torch.NumberType', class extends torch.Type {
  10764. constructor() {
  10765. super('NumberType');
  10766. }
  10767. static get() {
  10768. torch.NumberType.value = torch.NumberType.value || new torch.NumberType();
  10769. return torch.NumberType.value;
  10770. }
  10771. str() {
  10772. return 'Scalar';
  10773. }
  10774. __str__() {
  10775. return 'number';
  10776. }
  10777. });
  10778. this.registerType('torch.BoolType', class extends torch.Type {
  10779. constructor() {
  10780. super('BoolType');
  10781. }
  10782. static get() {
  10783. torch.BoolType.value = torch.BoolType.value || new torch.BoolType();
  10784. return torch.BoolType.value;
  10785. }
  10786. equals(rhs) {
  10787. return this.kind() === rhs.kind();
  10788. }
  10789. str() {
  10790. return 'bool';
  10791. }
  10792. __str__() {
  10793. return 'bool';
  10794. }
  10795. });
  10796. this.registerType('torch.IntType', class extends torch.Type {
  10797. constructor() {
  10798. super('IntType');
  10799. }
  10800. static get() {
  10801. torch.IntType.value = torch.IntType.value || new torch.IntType();
  10802. return torch.IntType.value;
  10803. }
  10804. equals(rhs) {
  10805. return this.kind() === rhs.kind();
  10806. }
  10807. isSubtypeOf(rhs) {
  10808. return rhs instanceof torch.NumberType || rhs instanceof torch.FloatType || super.isSubtypeOf(rhs);
  10809. }
  10810. str() {
  10811. return 'int';
  10812. }
  10813. __str__() {
  10814. return 'int';
  10815. }
  10816. });
  10817. this.registerType('torch.SymIntType', class extends torch.Type {
  10818. constructor() {
  10819. super('SymIntType');
  10820. }
  10821. static get() {
  10822. torch.SymIntType.value = torch.SymIntType.value || new torch.SymIntType();
  10823. return torch.SymIntType.value;
  10824. }
  10825. equals(rhs) {
  10826. return this.kind() === rhs.kind();
  10827. }
  10828. str() {
  10829. return 'SymInt';
  10830. }
  10831. __str__() {
  10832. return 'int';
  10833. }
  10834. });
  10835. this.registerType('torch.FloatType', class extends torch.Type {
  10836. constructor() {
  10837. super('FloatType');
  10838. }
  10839. static get() {
  10840. torch.FloatType.value = torch.FloatType.value || new torch.FloatType();
  10841. return torch.FloatType.value;
  10842. }
  10843. equals(rhs) {
  10844. return this.kind() === rhs.kind();
  10845. }
  10846. isSubtypeOf(rhs) {
  10847. return rhs.kind() === 'NumberType' || super.isSubtypeOf(rhs);
  10848. }
  10849. str() {
  10850. return 'float';
  10851. }
  10852. __str__() {
  10853. return 'float';
  10854. }
  10855. });
  10856. this.registerType('torch.StringType', class extends torch.Type {
  10857. constructor() {
  10858. super('StringType');
  10859. }
  10860. static get() {
  10861. torch.StringType.value = torch.StringType.value || new torch.StringType();
  10862. return torch.StringType.value;
  10863. }
  10864. equals(rhs) {
  10865. return this.kind() === rhs.kind();
  10866. }
  10867. str() {
  10868. return 'str';
  10869. }
  10870. __str__() {
  10871. return 'str';
  10872. }
  10873. });
  10874. this.registerType('torch.ComplexType', class extends torch.Type {
  10875. constructor() {
  10876. super('ComplexType');
  10877. }
  10878. static get() {
  10879. torch.ComplexType.value = torch.ComplexType.value || new torch.ComplexType();
  10880. return torch.ComplexType.value;
  10881. }
  10882. equals(rhs) {
  10883. return this.kind() === rhs.kind();
  10884. }
  10885. isSubtypeOf(rhs) {
  10886. return rhs.kind() === 'NumberType' || super.isSubtypeOf(rhs);
  10887. }
  10888. str() {
  10889. return 'complex';
  10890. }
  10891. __str__() {
  10892. return 'complex';
  10893. }
  10894. });
  10895. this.registerType('torch.DictType', class extends torch.Type {
  10896. constructor(key, value) {
  10897. super('DictType');
  10898. this.types = [key, value];
  10899. }
  10900. static create(key, value) {
  10901. let kind = key.kind();
  10902. if (key instanceof torch._C.DynamicType) {
  10903. kind = key.dynamicKind();
  10904. }
  10905. switch (kind) {
  10906. case 'AnyType':
  10907. case 'IntType':
  10908. case 'BoolType':
  10909. case 'FloatType':
  10910. case 'ComplexType':
  10911. case 'StringType':
  10912. case 'TensorType':
  10913. case 'DeviceObjType':
  10914. return new torch.DictType(key, value);
  10915. default:
  10916. throw new python.Error(`Invalid dict key type '${kind}'.`);
  10917. }
  10918. }
  10919. createWithContained(contained_types) {
  10920. if (contained_types.length !== 2) {
  10921. throw new python.Error('Expected 2 contained types.');
  10922. }
  10923. return torch.DictType.create(contained_types[0], contained_types[1]);
  10924. }
  10925. getKeyType() {
  10926. return this.types[0];
  10927. }
  10928. getValueType() {
  10929. return this.types[1];
  10930. }
  10931. hasFreeVariables() {
  10932. return this.getKeyType().hasFreeVariables() || this.getValueType().hasFreeVariables();
  10933. }
  10934. containedTypes() {
  10935. return this.types;
  10936. }
  10937. equals(rhs) {
  10938. if (rhs instanceof torch.DictType) {
  10939. return this.getKeyType().equals(rhs.getKeyType()) && this.getValueType().equals(rhs.getValueType());
  10940. }
  10941. return false;
  10942. }
  10943. str() {
  10944. return `Dict(${this.getKeyType().str()}, ${this.getValueType().str()})`;
  10945. }
  10946. __str__() {
  10947. return `Dict(${this.getKeyType().__str__()}, ${this.getValueType().__str__()})`;
  10948. }
  10949. });
  10950. this.registerType('torch.DeviceObjType', class extends torch.Type {
  10951. constructor() {
  10952. super('DeviceObjType');
  10953. }
  10954. static get() {
  10955. torch.DeviceObjType.value ||= new torch.DeviceObjType();
  10956. return torch.DeviceObjType.value;
  10957. }
  10958. str() {
  10959. return 'Device';
  10960. }
  10961. __str__() {
  10962. return 'Device';
  10963. }
  10964. });
  10965. this.registerType('torch.StreamObjType', class extends torch.Type {
  10966. constructor() {
  10967. super('StreamObjType');
  10968. }
  10969. str() {
  10970. return 'Stream';
  10971. }
  10972. __str__() {
  10973. return 'Stream';
  10974. }
  10975. });
  10976. this.registerType('torch._C._GeneratorType', class extends torch.Type {
  10977. constructor() {
  10978. super('GeneratorType');
  10979. }
  10980. static get() {
  10981. torch._C._GeneratorType.value = torch._C._GeneratorType.value || new torch._C._GeneratorType();
  10982. return torch._C._GeneratorType.value;
  10983. }
  10984. str() {
  10985. return 'Generator';
  10986. }
  10987. __str__() {
  10988. return 'Generator';
  10989. }
  10990. });
  10991. this.registerType('torch.InterfaceType', class extends torch.Type {
  10992. constructor() {
  10993. super('InterfaceType');
  10994. }
  10995. });
  10996. this.registerType('torch._C.DynamicType', class extends torch.Type {
  10997. constructor() {
  10998. super('DynamicType');
  10999. }
  11000. });
  11001. this.registerType('torch._C.FunctionType', class extends torch.Type {
  11002. constructor(func) {
  11003. super('FunctionType');
  11004. this._func = func;
  11005. }
  11006. static create(func) {
  11007. return new torch._C.FunctionType(func);
  11008. }
  11009. function() {
  11010. return this._func;
  11011. }
  11012. });
  11013. this.registerType('torch._C.VarType', class extends torch.Type {
  11014. constructor(name) {
  11015. super('VarType', name);
  11016. }
  11017. static create(name) {
  11018. return new torch._C.VarType(name);
  11019. }
  11020. name() {
  11021. return this._annotation_str;
  11022. }
  11023. hasFreeVariables() {
  11024. return true;
  11025. }
  11026. });
  11027. this.registerType('torch._C.AliasInfo', class {
  11028. constructor() {
  11029. this.is_write = false;
  11030. this.before_set = [];
  11031. this.after_set = [];
  11032. this.containedTypes = [];
  11033. }
  11034. addBeforeSet(value) {
  11035. this.before_set.push(value);
  11036. }
  11037. addAfterSet(value) {
  11038. this.after_set.push(value);
  11039. }
  11040. addContainedType(alias_info) {
  11041. this.containedTypes.push(alias_info);
  11042. }
  11043. str() {
  11044. const list = ['('];
  11045. list.push(this.before_set.join('|'));
  11046. if (this.after_set.length > 0) {
  11047. list.push(' -> ');
  11048. list.push(this.after_set.join('|'));
  11049. }
  11050. if (this.is_write) {
  11051. list.push('!');
  11052. }
  11053. list.push(')');
  11054. return list.join('');
  11055. }
  11056. });
  11057. this.registerFunction('torch._C.parseStringLiteral', (range, str) => {
  11058. if (str.startsWith('"') && str.endsWith('"')) {
  11059. return str.slice(1, -1);
  11060. }
  11061. if (str.startsWith("'") && str.endsWith("'")) {
  11062. return str.slice(1, -1);
  11063. }
  11064. throw new python.Error(`Invalid string literal '${str}'.`);
  11065. // inline std::string parseStringLiteral(
  11066. });
  11067. this.registerType('torch._C.Token', class {
  11068. constructor() {
  11069. this.kind = '';
  11070. this.value = '';
  11071. }
  11072. text() {
  11073. return this.value;
  11074. }
  11075. });
  11076. this.registerType('torch._C.Lexer', class {
  11077. constructor(buffer) {
  11078. this.buffer = buffer;
  11079. this.position = 0;
  11080. this.next_tokens = [new torch._C.Token(), new torch._C.Token(), new torch._C.Token(), new torch._C.Token()];
  11081. this.next();
  11082. }
  11083. cur() {
  11084. return this.next_tokens[0];
  11085. }
  11086. lookahead() {
  11087. if (!this.next_tokens[1].kind) {
  11088. this.position += this.cur().text().length;
  11089. this.lex(this.next_tokens[1]);
  11090. }
  11091. return this.next_tokens[1];
  11092. }
  11093. next() {
  11094. const [cur] = this.next_tokens;
  11095. [, this.next_tokens[0], this.next_tokens[1], this.next_tokens[2]] = this.next_tokens;
  11096. this.next_tokens[1].kind = '';
  11097. this.next_tokens[3] = cur;
  11098. const [token] = this.next_tokens;
  11099. if (token.kind) {
  11100. return cur;
  11101. }
  11102. this.position += cur.text().length;
  11103. this.lex(token);
  11104. return cur;
  11105. }
  11106. nextIf(kind) {
  11107. if (this.cur().kind !== kind) {
  11108. return false;
  11109. }
  11110. this.next();
  11111. return true;
  11112. }
  11113. expect(kind) {
  11114. if (this.cur().kind !== kind) {
  11115. throw new python.Error(`Unexpected '${this.cur().kind}' instead of '${kind}'.`);
  11116. }
  11117. return this.next();
  11118. }
  11119. lex(token) {
  11120. while (this.buffer[this.position] === ' ') {
  11121. this.position += 1;
  11122. }
  11123. let i = this.position;
  11124. if (i >= this.buffer.length) {
  11125. token.kind = '\0';
  11126. token.value = '';
  11127. } else if (this.buffer[i] === '.' && this.buffer[i + 1] === '.' && this.buffer[i + 2] === '.') {
  11128. token.kind = '...';
  11129. token.value = '...';
  11130. /* } else if (this.buffer[i] === '[' && this.buffer[i + 1] === ']') {
  11131. this.kind = '[]';
  11132. this.value = '[]'; */
  11133. } 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] === '|') {
  11134. token.kind = this.buffer[i];
  11135. token.value = this.buffer[i];
  11136. } else if ((this.buffer[i] >= 'a' && this.buffer[i] <= 'z') || (this.buffer[i] >= 'A' && this.buffer[i] <= 'Z') || this.buffer[i] === '_') {
  11137. i += 1;
  11138. 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] === '_')) {
  11139. i += 1;
  11140. }
  11141. token.kind = 'id';
  11142. token.value = this.buffer.slice(this.position, i);
  11143. } else if (this.buffer[i] === '-' && this.buffer[i + 1] === '>') {
  11144. token.kind = '->';
  11145. token.value = '->';
  11146. } else if ((this.buffer[i] >= '0' && this.buffer[i] <= '9') || this.buffer[i] === '-') {
  11147. i += 1;
  11148. while (i < this.buffer.length && ((this.buffer[i] >= '0' && this.buffer[i] <= '9') || this.buffer[i] === '.' || this.buffer[i] === 'e' || this.buffer[i] === '-')) {
  11149. i += 1;
  11150. }
  11151. token.kind = '#';
  11152. token.value = this.buffer.slice(this.position, i);
  11153. } else if (this.buffer[i] === "'" || this.buffer[i] === '"') {
  11154. const quote = this.buffer[i];
  11155. i += 1;
  11156. while (i < this.buffer.length && this.buffer[i] !== quote) {
  11157. i += (this.buffer[i] === '\\' && (this.buffer[i + 1] === "'" || this.buffer[i + 1] === '"' || this.buffer[i + 1] === '\\')) ? 2 : 1;
  11158. }
  11159. i += 1;
  11160. token.kind = 'string';
  11161. token.value = this.buffer.slice(this.position, i);
  11162. } else {
  11163. throw new python.Error(`Unsupported token at '${this.position}'.`);
  11164. }
  11165. }
  11166. });
  11167. this.registerType('torch._C.SchemaTypeParser', class {
  11168. constructor(L, complete_tensor_types, allow_typevars) {
  11169. this.L = L;
  11170. this.complete_tensor_types = complete_tensor_types;
  11171. this._allow_typevars = allow_typevars;
  11172. }
  11173. parseType() {
  11174. const r = this.parseFakeAndRealType();
  11175. return { first: r[0], second: r[2] };
  11176. }
  11177. parseBaseType() {
  11178. const L = this.L;
  11179. const tok = L.cur();
  11180. const text = tok.text();
  11181. L.next();
  11182. switch (text) {
  11183. case 'Tensor': return torch.TensorType.get();
  11184. case 'bool': return torch.BoolType.get();
  11185. case 'int': return torch.IntType.get();
  11186. case 'float': return torch.FloatType.get();
  11187. case 'complex': return torch.ComplexType.get();
  11188. case 'str': return torch.StringType.get();
  11189. case 'SymInt': return torch.SymIntType.get();
  11190. case 'Scalar': return torch.NumberType.get();
  11191. case 'ScalarType': return torch.Type.get('ScalarTypeType');
  11192. case 'Device': return torch.DeviceObjType.get();
  11193. case 'Layout': return torch.Type.get('Layout');
  11194. case 'MemoryFormat': return torch.Type.get('MemoryFormat');
  11195. case 'Generator': return torch._C._GeneratorType.get();
  11196. case 't': case 't1': case 't2': case 'tVal': return torch._C.VarType.create(text);
  11197. case 'Any': return torch.AnyType.get();
  11198. case 'AnyEnumType': return torch.Type.get('AnyEnumType');
  11199. case 'Dimname': return torch.StringType.get();
  11200. case 'QScheme': return torch.Type.get('QSchemeType');
  11201. case 'Stream': return torch.StreamObjType.get();
  11202. case 'Storage': return torch.Type.get('Storage');
  11203. case 'AnyClassType': return torch.Type.get('AnyClassType');
  11204. case 'NoneType': return torch.NoneType.get();
  11205. default: throw new python.Error(`Unsupported type '${text}'.`);
  11206. }
  11207. }
  11208. parseFakeAndRealType() {
  11209. const L = this.L;
  11210. let fake_value = null;
  11211. let real_value = null;
  11212. let alias_info = null;
  11213. if (L.nextIf('(')) {
  11214. const types = [];
  11215. while (!L.nextIf(')')) {
  11216. const r = this.parseType();
  11217. types.push(r.first);
  11218. if (alias_info && r.second) {
  11219. alias_info.addContainedType(r.second);
  11220. }
  11221. L.nextIf(',');
  11222. }
  11223. real_value = torch.TupleType.create(types);
  11224. fake_value = real_value;
  11225. } else if (L.cur().text() === 'Future') {
  11226. L.next();
  11227. L.expect('(');
  11228. const p = this.parseType();
  11229. const subtype = p.first;
  11230. // const subalias = p.second;
  11231. L.expect(')');
  11232. real_value = torch.FutureType.create(subtype);
  11233. fake_value = real_value;
  11234. } else if (L.cur().text() === 'Await') {
  11235. L.next();
  11236. L.expect('(');
  11237. const p = this.parseType();
  11238. const subtype = p.first;
  11239. // const subalias = p.second;
  11240. L.expect(')');
  11241. real_value = torch.AwaitType.get(subtype);
  11242. fake_value = real_value;
  11243. } else if (L.cur().text() === 'RRef') {
  11244. L.next();
  11245. L.expect('(');
  11246. const p = this.parseType();
  11247. const subtype = p.first;
  11248. // const subalias = p.second;
  11249. L.expect(')');
  11250. real_value = torch.RRefType.create(subtype);
  11251. fake_value = real_value;
  11252. } else if (L.cur().text() === 'Tensor') {
  11253. L.next();
  11254. real_value = torch.TensorType.get();
  11255. fake_value = real_value;
  11256. alias_info = this.parseAliasAnnotation();
  11257. } else if (L.cur().text() === 'Dict') {
  11258. L.next();
  11259. L.expect('(');
  11260. const key_type = this.parseType().first;
  11261. L.expect(',');
  11262. const value_type = this.parseType().first;
  11263. L.expect(')');
  11264. alias_info = this.parseAliasAnnotation();
  11265. real_value = torch.DictType.create(key_type, value_type);
  11266. fake_value = real_value;
  11267. } else if (L.nextIf('Union')) {
  11268. L.next();
  11269. L.expect('(');
  11270. const types = [];
  11271. types.push(this.parseType().first);
  11272. while (L.cur().kind !== ')') {
  11273. L.expect(',');
  11274. types.push(this.parseType().first);
  11275. }
  11276. L.expect(')');
  11277. alias_info = this.parseAliasAnnotation();
  11278. real_value = new torch.UnionType(types);
  11279. fake_value = real_value;
  11280. /* } else if (complete_tensor_types && L.cur().kind == TK_IDENT && parseTensorDType(L.cur().text())) {
  11281. fake_value = real_value = parseRefinedTensor();
  11282. alias_info = parseAliasAnnotation(); */
  11283. } else if (L.cur().kind === 'id' && L.cur().text() === '__torch__') {
  11284. L.next();
  11285. L.expect('.');
  11286. const torch_tok = L.expect('id');
  11287. if (torch_tok.text() !== 'torch') {
  11288. throw new python.Error('Expected classes namespace.');
  11289. }
  11290. L.expect('.');
  11291. const classes_tok = L.expect('id');
  11292. if (classes_tok.text() !== 'classes') {
  11293. throw new python.Error('Expected classes namespace.');
  11294. }
  11295. L.expect('.');
  11296. const ns_tok = L.expect('id');
  11297. L.expect('.');
  11298. const class_tok = L.expect('id');
  11299. real_value = torch._C.getCustomClass(`__torch__.torch.classes.${ns_tok.text()}.${class_tok.text()}`);
  11300. fake_value = real_value;
  11301. if (!fake_value) {
  11302. throw new python.Error(`Unknown custom class type '${ns_tok.text()}.${class_tok.text()}'.`);
  11303. }
  11304. } else {
  11305. real_value = this.parseBaseType();
  11306. fake_value = real_value;
  11307. if (real_value.kind() === 'ScalarTypeType' ||
  11308. real_value.kind() === 'MemoryFormat' ||
  11309. real_value.kind() === 'Layout' ||
  11310. real_value.kind() === 'SymIntType') {
  11311. fake_value = torch.IntType.get();
  11312. }
  11313. alias_info = this.parseAliasAnnotation();
  11314. }
  11315. while (true) {
  11316. if (L.cur().kind === '[' && L.lookahead().kind === ']') {
  11317. L.expect('[');
  11318. L.expect(']');
  11319. fake_value = torch.ListType.create(fake_value);
  11320. real_value = torch.ListType.create(real_value);
  11321. let container = this.parseAliasAnnotation();
  11322. if (alias_info) {
  11323. if (!container) {
  11324. container = new torch._C.AliasInfo();
  11325. container.is_write = alias_info.is_write;
  11326. }
  11327. container.addContainedType(alias_info);
  11328. }
  11329. alias_info = container;
  11330. } else if (L.nextIf('?')) {
  11331. fake_value = torch.OptionalType.create(fake_value);
  11332. real_value = torch.OptionalType.create(real_value);
  11333. } else {
  11334. break;
  11335. }
  11336. }
  11337. return [fake_value, real_value, alias_info];
  11338. }
  11339. parseAliasAnnotation() {
  11340. const L = this.L;
  11341. let alias_info = null;
  11342. if (L.nextIf('(')) {
  11343. alias_info = new torch._C.AliasInfo();
  11344. do {
  11345. alias_info.addBeforeSet(L.cur().text());
  11346. L.next();
  11347. if (L.nextIf('!')) {
  11348. alias_info.is_write = true;
  11349. }
  11350. }
  11351. while (L.nextIf('|'));
  11352. if (L.nextIf('->')) {
  11353. do {
  11354. alias_info.addAfterSet(L.cur().text());
  11355. L.next();
  11356. }
  11357. while (L.nextIf('|'));
  11358. }
  11359. L.expect(')');
  11360. }
  11361. return alias_info;
  11362. }
  11363. });
  11364. this.registerType('torch.Argument', class {
  11365. constructor(...args) {
  11366. // torch/aten/src/ATen/core/function_schema.h
  11367. this.N = null;
  11368. this.default_value = null;
  11369. this.kwarg_only = false;
  11370. this.alias_info = null;
  11371. if (args.length === 2) {
  11372. [this.name, this.type] = args;
  11373. this.real_type = this.type;
  11374. } else if (args.length === 3 && args[1] instanceof torch.Type && args[2] instanceof torch.Type) {
  11375. [this.name, this.type, this.real_type] = args;
  11376. } else if (args.length === 6) {
  11377. [this.name, this.type, this.real_type, this.N, this.default_value, this.kwarg_only] = args;
  11378. } else if (args.length === 7) {
  11379. [this.name, this.type, this.real_type, this.N, this.default_value, this.kwarg_only, this.alias_info] = args;
  11380. } else {
  11381. throw new python.Error('Invalid arguments.');
  11382. }
  11383. const is_alias = this.alias_info && this.alias_info.is_write;
  11384. this.is_out = this.kwarg_only && is_alias;
  11385. }
  11386. has_default_value() {
  11387. return this.default_value !== undefined;
  11388. }
  11389. is_inferred_type() {
  11390. if (this.type instanceof torch.TensorType) {
  11391. return this.type.isInferredType();
  11392. }
  11393. return false;
  11394. }
  11395. str() {
  11396. const list = [];
  11397. const type = this.real_type;
  11398. const is_opt = type instanceof torch.OptionalType;
  11399. const unopt_type = is_opt ? type.getElementType() : type;
  11400. if (unopt_type instanceof torch.ListType) {
  11401. list.push(unopt_type.getElementType().str());
  11402. if (this.alias_info && this.alias_info.containedTypes.length > 0) {
  11403. list.push(this.alias_info.containedTypes[0].str());
  11404. }
  11405. list.push(this.N === null ? `[]` : `[${this.N}]`);
  11406. } else {
  11407. list.push(unopt_type.str());
  11408. }
  11409. if (this.alias_info && this.alias_info.before_set.length > 0) {
  11410. list.push(this.alias_info.str());
  11411. }
  11412. if (is_opt) {
  11413. list.push('?');
  11414. }
  11415. if (this.name) {
  11416. list.push(' ');
  11417. list.push(this.name);
  11418. }
  11419. if (this.default_value !== undefined) {
  11420. const value = this.default_value;
  11421. if (value === null) {
  11422. list.push('=None');
  11423. } else if (typeof value === 'boolean') {
  11424. list.push('=');
  11425. list.push(value ? 'True' : 'False');
  11426. } else if (typeof value === 'string') {
  11427. list.push(`="${value}"`);
  11428. } else if (typeof value === 'number') {
  11429. list.push(`=${value}`);
  11430. if (Number.isInteger(value) && this.real_type instanceof torch.FloatType) {
  11431. list.push(`.`);
  11432. }
  11433. } else if (Array.isArray(value)) {
  11434. list.push(`=[${value.join(', ')}]`);
  11435. }
  11436. }
  11437. return list.join('');
  11438. }
  11439. });
  11440. torch._C.TypeKind = {
  11441. StringType: 'StringType',
  11442. NumberType: 'NumberType',
  11443. IntType: 'IntType',
  11444. BoolType: 'BoolType',
  11445. DynamicType: 'DynamicType',
  11446. OptionalType: 'OptionalType',
  11447. FloatType: 'FloatType',
  11448. ComplexType: 'ComplexType',
  11449. ListType: 'ListType',
  11450. };
  11451. this.registerType('torch._C.List', class extends Array {
  11452. constructor(type, elements) {
  11453. super(elements ? elements.length : 0);
  11454. if (Array.isArray(elements)) {
  11455. for (let i = 0; i < elements.length; i++) {
  11456. this[i] = elements[i];
  11457. }
  11458. }
  11459. this.type = type;
  11460. }
  11461. elementType() {
  11462. return this.type;
  11463. }
  11464. });
  11465. this.registerFunction('torch._C.builtin_cast_method_to_scalar_type', () => {
  11466. return new Map();
  11467. });
  11468. this.registerFunction('torch._C.string_to_type_lut', () => {
  11469. if (!torch._C.string_to_type_lut.basePythonTypes) {
  11470. const map = new Map();
  11471. map.set('Tensor', torch.TensorType.get());
  11472. map.set('int', torch.IntType.get());
  11473. map.set('float', torch.FloatType.get());
  11474. map.set('bool', torch.BoolType.get());
  11475. map.set('complex', torch.ComplexType.get());
  11476. map.set('str', torch.StringType.get());
  11477. map.set('Device', torch.DeviceObjType.get());
  11478. map.set('number', torch.NumberType.get());
  11479. map.set('None', torch.NoneType.get());
  11480. map.set('NoneType', torch.NoneType.get());
  11481. map.set('Any', torch.AnyType.get());
  11482. map.set('list', torch.Type.get('AnyListType'));
  11483. map.set('tuple', torch.Type.get('AnyTupleType'));
  11484. torch._C.string_to_type_lut.basePythonTypes = map;
  11485. }
  11486. return torch._C.string_to_type_lut.basePythonTypes;
  11487. });
  11488. this.registerType('torch._C.ScriptTypeParser', class {
  11489. constructor(resolver) {
  11490. this._resolver = resolver;
  11491. }
  11492. parseSchemaFromDef(def, skip_self) {
  11493. const name = def.name;
  11494. const args = this.parseArgsFromDecl(def, skip_self);
  11495. const returns = this.parseReturnFromDecl(def);
  11496. return new torch.FunctionSchema(name, '', args, returns, false, false);
  11497. }
  11498. parseArgsFromDecl(decl, skip_self) {
  11499. const retval = [];
  11500. if (decl.args.posonlyargs.length > 0 || decl.args.kwonlyargs.length > 0) {
  11501. throw new python.Error('Unsupported function argument.');
  11502. }
  11503. const params = decl.args.args.slice();
  11504. const kwonlyargs = new Set(Array.from(decl.args.kwonlyargs));
  11505. const start = skip_self ? 1 : 0;
  11506. for (let i = start; i < params.length; i++) {
  11507. const decl_arg = params[i];
  11508. const N = null;
  11509. const default_value = undefined;
  11510. const type = decl_arg.annotation ? this.parseTypeFromExpr(decl_arg.annotation) : null;
  11511. const arg = new torch.Argument(decl_arg.arg, type, type, N, default_value, kwonlyargs.has(decl_arg), null);
  11512. retval.push(arg);
  11513. }
  11514. return retval;
  11515. }
  11516. parseReturnFromDecl(decl) {
  11517. if (!decl.returns) {
  11518. return [];
  11519. }
  11520. if (this.parseBroadcastList(decl.returns)) {
  11521. throw new python.Error('Broadcastable lists cannot appear as a return type.');
  11522. }
  11523. const parsed_type = this.parseTypeFromExpr(decl.returns);
  11524. return [new torch.Argument('', parsed_type, parsed_type, null, undefined, false)];
  11525. }
  11526. parseTypeFromExpr(expr) {
  11527. if (this._resolver) {
  11528. if (expr instanceof ast.Name) {
  11529. const type = this._resolver.resolveType(expr.id);
  11530. if (type) {
  11531. return type;
  11532. }
  11533. }
  11534. }
  11535. return this.parseTypeFromExprImpl(expr);
  11536. }
  11537. parseTypeFromExprImpl(expr) {
  11538. if (expr instanceof ast.Subscript) {
  11539. const value_name = this.parseBaseTypeName(expr.value);
  11540. if (!value_name) {
  11541. throw new python.Error('Subscripted type must be a type identifier.');
  11542. }
  11543. return this.subscriptToType(value_name, expr);
  11544. }
  11545. const name = this.parseBaseTypeName(expr);
  11546. if (name) {
  11547. const itr = torch._C.string_to_type_lut().get(name);
  11548. if (itr) {
  11549. return itr;
  11550. }
  11551. if (this._resolver) {
  11552. const typePtr = this._resolver.resolveType(name, expr);
  11553. if (typePtr) {
  11554. return typePtr;
  11555. }
  11556. }
  11557. }
  11558. throw new python.Error(`Unknown type name '${name}'.`);
  11559. }
  11560. parseBaseTypeName(expr) {
  11561. if (expr instanceof ast.Name) {
  11562. return expr.id;
  11563. } else if (expr instanceof ast.Constant && expr.value === null) {
  11564. return 'None';
  11565. } else if (expr instanceof ast.Attribute) {
  11566. const name = expr.attr;
  11567. const tensor_subtypes = new Set(['Tensor', 'LongTensor', 'FloatTensor', 'DoubleTensor', 'IntTensor', 'ShortTensor', 'HalfTensor', 'CharTensor', 'ByteTensor', 'BoolTensor']);
  11568. if (torch._C.isTorch(expr.value) && tensor_subtypes.has(name)) {
  11569. return name;
  11570. }
  11571. return torch._C.collectQualname(expr);
  11572. }
  11573. throw new python.Error(`Unsupported type '${expr.__class__.__name__}'.`);
  11574. }
  11575. parseBroadcastList(/* expr */) {
  11576. return null;
  11577. }
  11578. parseType(str) {
  11579. const expr = ast.parse(str);
  11580. return this.parseTypeFromExpr(expr.body[0].value);
  11581. }
  11582. subscriptToType(typeName, subscript) {
  11583. if (typeName === 'Tuple' || typeName === 'tuple') {
  11584. const subscript_expr_types = [];
  11585. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11586. for (const expr of elts) {
  11587. subscript_expr_types.push(this.parseTypeFromExprImpl(expr));
  11588. }
  11589. return torch.TupleType.create(subscript_expr_types);
  11590. } else if (typeName === 'List' || typeName === 'list') {
  11591. if (subscript.slice instanceof ast.Slice || subscript.slice instanceof ast.Tuple) {
  11592. throw new python.Error('List type must have exactly one element type.');
  11593. }
  11594. const elem_type = this.parseTypeFromExprImpl(subscript.slice);
  11595. return torch.ListType.create(elem_type);
  11596. } else if (typeName === 'Optional') {
  11597. if (subscript.slice instanceof ast.Slice || subscript.slice instanceof ast.Tuple) {
  11598. throw new python.Error('Optional type must have exactly one element type.');
  11599. }
  11600. const elem_type = this.parseTypeFromExprImpl(subscript.slice);
  11601. return torch.OptionalType.create(elem_type);
  11602. } else if (typeName === 'Union') {
  11603. const subscript_expr_types = [];
  11604. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11605. for (const expr of elts) {
  11606. subscript_expr_types.push(this.parseTypeFromExprImpl(expr));
  11607. }
  11608. return torch.UnionType.create(subscript_expr_types);
  11609. } else if (typeName === 'Future' || typeName === 'torch.jit.Future') {
  11610. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11611. if (elts.length !== 1) {
  11612. throw new python.Error('Future type must have exactly one element type.');
  11613. }
  11614. const elem_type = this.parseTypeFromExprImpl(elts[0]);
  11615. return torch.FutureType.create(elem_type);
  11616. } else if (typeName === 'Await' || typeName === 'torch.jit._Await') {
  11617. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11618. if (elts.length !== 1) {
  11619. throw new python.Error('Await type must have exactly one element type.');
  11620. }
  11621. const elem_type = this.parseTypeFromExprImpl(elts[0]);
  11622. return torch.AwaitType.create(elem_type);
  11623. } else if (typeName === 'RRef') {
  11624. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11625. if (elts.length !== 1) {
  11626. throw new python.Error('RRef type must have exactly one element type.');
  11627. }
  11628. const elem_type = this.parseTypeFromExprImpl(elts[0]);
  11629. return torch.RRefType.create(elem_type);
  11630. } else if (typeName === 'Dict' || typeName === 'dict') {
  11631. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11632. if (elts.length !== 2) {
  11633. throw new python.Error('Dict type must have exactly two element types.');
  11634. }
  11635. const key_type = this.parseTypeFromExprImpl(elts[0]);
  11636. const value_type = this.parseTypeFromExprImpl(elts[1]);
  11637. return torch.DictType.create(key_type, value_type);
  11638. }
  11639. throw new python.Error(`Unknown type constructor '${typeName}'.`);
  11640. }
  11641. });
  11642. this.registerFunction('torch._C.isTorch', (expr) => {
  11643. return expr instanceof ast.Name && expr.id === 'torch';
  11644. });
  11645. this.registerFunction('torch._C.collectQualname', (select) => {
  11646. const base = select.value;
  11647. if (base instanceof ast.Name) {
  11648. return `${base.id}.${select.attr}`;
  11649. }
  11650. const basename = torch._C.collectQualname(base);
  11651. return `${basename}.${select.attr}`;
  11652. });
  11653. this.registerType('torch._ops.OpOverload', class extends torch._ops.OperatorBase {
  11654. constructor(overloadpacket, op, op_dk, schema, tags) {
  11655. super();
  11656. this._op = op;
  11657. this._op_dk = op_dk;
  11658. this._schema = schema;
  11659. this._overloadpacket = overloadpacket;
  11660. this._tags = tags;
  11661. this._overloadname = schema.overload_name === '' ? 'default' : schema.overload_name;
  11662. this._name = this._schema.name;
  11663. this._name = schema.overload_name ? `${this._name}.${schema.overload_name}` : this._name;
  11664. this.__name__ = `${this._schema.name.split('::')[1]}.${this._overloadname}`;
  11665. this.__module__ = overloadpacket.__module__;
  11666. op.__module__ = overloadpacket.__module__;
  11667. this.__qualname__ = self._name;
  11668. this.__annotations__ = {};
  11669. // this._defined_in_python = this.__qualname__ in torch.library._defs
  11670. let is_write = null;
  11671. for (const a of this._schema.arguments) {
  11672. if (a.alias_info) {
  11673. is_write = is_write === null ? a.alias_info.is_write : a.alias_info.is_write || is_write;
  11674. }
  11675. }
  11676. this.is_view = is_write !== null && !is_write;
  11677. }
  11678. name() {
  11679. return this._name;
  11680. }
  11681. });
  11682. this.registerType('torch._ops.OpOverloadPacket', class {
  11683. constructor(qualified_op_name, op_name, op, overload_names) {
  11684. this._qualified_op_name = qualified_op_name;
  11685. this.__name__ = op_name;
  11686. this._op = op;
  11687. this._overload_names = overload_names;
  11688. this._dir = [];
  11689. this._has_torchbind_op_overload = this._schemas.some((schema) => this._has_script_object_arg(schema));
  11690. }
  11691. get _schemas() {
  11692. return this._overload_names.map((overload_name) => torch._C._get_schema(this._qualified_op_name, overload_name));
  11693. }
  11694. __getattr__(key) {
  11695. key = key === 'default' ? '' : key;
  11696. const op_dk_tags = torch._C._get_operation_overload(this._qualified_op_name, key);
  11697. const [op_, op_dk_, tags] = op_dk_tags;
  11698. const schema = torch._C._get_schema(this._qualified_op_name, key);
  11699. const overload = this._has_script_object_arg(schema) ?
  11700. new torch._ops.TorchBindOpOverload(this, op_, op_dk_, schema, tags) :
  11701. new torch._ops.OpOverload(this, op_, op_dk_, schema, tags);
  11702. builtins.setattr(self, key, overload);
  11703. this._dir.push(key);
  11704. return overload;
  11705. }
  11706. _has_script_object_arg(schema) {
  11707. return schema.arguments.some((arg) => arg.type instanceof torch.ClassType);
  11708. }
  11709. __call__(...args) {
  11710. const fn = execution._operators.get(this._qualified_op_name);
  11711. if (!fn) {
  11712. throw new python.Error(`Operator call '${this._qualified_op_name}' is not registered.`);
  11713. }
  11714. return fn(...args);
  11715. }
  11716. });
  11717. this.registerType('torch._ops._OpNamespace', class extends types.ModuleType {
  11718. constructor(name) {
  11719. super(`torch.ops.${name}`);
  11720. this.name = name;
  11721. this._dir = [];
  11722. }
  11723. __getattr__(op_name) {
  11724. const namespace_name = this.name;
  11725. const qualified_op_name = `${namespace_name}::${op_name}`;
  11726. const module_name = `${this.__module__}.${namespace_name}`;
  11727. let op = null;
  11728. let overload_names = null;
  11729. try {
  11730. [op, overload_names] = this._get_packet(qualified_op_name, module_name);
  11731. } catch {
  11732. // continue regardless of error
  11733. }
  11734. if (!op) {
  11735. throw new python.Error(`Unknown operator type '${qualified_op_name}'.`);
  11736. }
  11737. op.__module__ = module_name;
  11738. const opoverloadpacket = new torch._ops.OpOverloadPacket(qualified_op_name, op_name, op, overload_names);
  11739. opoverloadpacket.__module__ = `${this.__module__}.${namespace_name}`;
  11740. builtins.setattr(this, op_name, opoverloadpacket);
  11741. this._dir.push(op_name);
  11742. return opoverloadpacket;
  11743. }
  11744. _get_packet(qualname, op_module) {
  11745. const [op, overload_names] = torch._C._jit_get_operation(qualname);
  11746. if (op) {
  11747. // torch.jit._builtins._register_builtin(op, qualname);
  11748. }
  11749. op.__module__ = op_module;
  11750. return [op, overload_names];
  11751. }
  11752. });
  11753. this.registerType('torch._C.graph_node_list', class {
  11754. constructor(head) {
  11755. this.head = head;
  11756. }
  11757. front() {
  11758. return this.head.next;
  11759. }
  11760. end() {
  11761. return this.head.prev;
  11762. }
  11763. [Symbol.iterator]() {
  11764. let current = this.head.next;
  11765. const prev = this.head.prev;
  11766. return {
  11767. next() {
  11768. if (current !== prev) {
  11769. const value = current;
  11770. current = current.next;
  11771. return { value, done: false };
  11772. }
  11773. return { done: true };
  11774. }
  11775. };
  11776. }
  11777. });
  11778. this.registerType('torch.Graph', class {
  11779. constructor() {
  11780. this._next_unique = 0;
  11781. this._unique_names = new Map();
  11782. this._name_base_suffix = new Map();
  11783. this.all_nodes = new Set();
  11784. this.all_values = new Set();
  11785. this.all_blocks = new Set();
  11786. this._block = new torch.Block(this, null);
  11787. this._insert_before = this.return_node();
  11788. }
  11789. insert(opname, args, kwargs, range) {
  11790. return torch._C.emitBuiltinCall(range, this, opname, args, kwargs);
  11791. }
  11792. create(kind, ...args) {
  11793. let inputs = null;
  11794. let num_outputs = 1;
  11795. if (args.length === 2 && Array.isArray(args[0]) && typeof args[1] === 'number') {
  11796. [inputs, num_outputs] = args;
  11797. } else if (args.length === 1) {
  11798. if (typeof args[0] === 'number') {
  11799. [num_outputs] = args;
  11800. } else if (Array.isArray(args[0])) {
  11801. [inputs] = args;
  11802. }
  11803. }
  11804. const n = new torch.Node(this, kind);
  11805. if (inputs) {
  11806. for (const i of inputs) {
  11807. n.addInput(i);
  11808. }
  11809. }
  11810. for (let i = 0; i < num_outputs; i++) {
  11811. n.addOutput();
  11812. }
  11813. return n;
  11814. }
  11815. createClone(n, value_map, copy_blocks) {
  11816. copy_blocks = copy_blocks === undefined ? true : copy_blocks;
  11817. const r = n.allocNewInstance(this);
  11818. for (const o of n.outputs()) {
  11819. r.addOutput().copyMetadata(o);
  11820. }
  11821. r.cloneFrom(n);
  11822. for (const i of n.inputs()) {
  11823. r.addInput(value_map(i));
  11824. }
  11825. if (copy_blocks) {
  11826. for (const b of n.blocks()) {
  11827. r.addBlock().cloneFrom(b, value_map);
  11828. }
  11829. }
  11830. return r;
  11831. }
  11832. createNone() {
  11833. const n = this.create('prim::Constant');
  11834. n.output().setType(torch.NoneType.get());
  11835. return n;
  11836. }
  11837. createUninitialized(typ) {
  11838. const n = this.create('prim::Uninitialized');
  11839. n.output().setType(typ);
  11840. return n;
  11841. }
  11842. createEnumValue(e) {
  11843. const enum_type = e.type().expect(torch.EnumType);
  11844. const n = this.create('prim::EnumValue', [e]);
  11845. n.output().setType(enum_type.getValueType());
  11846. return n;
  11847. }
  11848. createList(contained_type, values) {
  11849. const n = this.create('prim::ListConstruct', values);
  11850. for (const v of values) {
  11851. if (!v.type().isSubtypeOf(contained_type)) {
  11852. throw new python.Error('Invalid list item.');
  11853. }
  11854. }
  11855. n.output().setType(torch.ListType.create(contained_type));
  11856. return n;
  11857. }
  11858. createListUnpack(v, size) {
  11859. const list_type = v.type().expect(torch.ListType);
  11860. const elem_type = list_type.getElementType();
  11861. const n = this.create('prim::ListUnpack', [v], 0);
  11862. for (let i = 0; i < size; i++) {
  11863. n.addOutput().setType(elem_type);
  11864. }
  11865. return n;
  11866. }
  11867. createTuple(values, tuple_type) {
  11868. if (!tuple_type) {
  11869. const types = values.map((v) => v.type());
  11870. tuple_type = torch.TupleType.create(types);
  11871. }
  11872. const n = this.create('prim::TupleConstruct', values);
  11873. n.output().setType(tuple_type);
  11874. return n;
  11875. }
  11876. createTupleUnpack(v) {
  11877. const tt = v.type().expect(torch.TupleType);
  11878. const n = this.create('prim::TupleUnpack', [v], 0);
  11879. for (const element of tt.elements()) {
  11880. n.addOutput().setType(element);
  11881. }
  11882. return n;
  11883. }
  11884. createTupleIndex(tup, idx, output_type) {
  11885. const n = this.create('prim::TupleIndex', [tup, idx]);
  11886. n.output().setType(output_type);
  11887. return n;
  11888. }
  11889. createTupleSlice(tup, beg, step_size, num_values) {
  11890. const new_vals = [];
  11891. const tt = tup.type().expect(torch.TupleType);
  11892. let i = beg;
  11893. for (let j = 0; j < num_values; j++) {
  11894. const idx = this.insertConstant(new torch._C.IValue(i, 'Int'));
  11895. const tupleIndex = this.insertNode(this.createTupleIndex(tup, idx, tt.elements()[i]));
  11896. new_vals.push(tupleIndex.output());
  11897. i += step_size;
  11898. }
  11899. const n = this.createTuple(new_vals);
  11900. return n;
  11901. }
  11902. createDict(key_type, value_type, keys, values) {
  11903. if (keys.length !== values.length) {
  11904. throw new python.Error('Invalid dictionary size.');
  11905. }
  11906. const n = this.create('prim::DictConstruct');
  11907. const length = keys.length;
  11908. for (let i = 0; i < length; i++) {
  11909. if (!keys[i].type().isSubtypeOf(key_type)) {
  11910. throw new python.Error('Invalid key.');
  11911. }
  11912. if (!values[i].type().isSubtypeOf(value_type)) {
  11913. throw new python.Error('Invalid value.');
  11914. }
  11915. n.addInput(keys[i]);
  11916. n.addInput(values[i]);
  11917. }
  11918. n.output().setType(torch.DictType.create(key_type, value_type));
  11919. return n;
  11920. }
  11921. createObject(type) {
  11922. const node = this.create('prim::CreateObject');
  11923. node.output().setType(type);
  11924. return node;
  11925. }
  11926. createIsInstance(v, types) {
  11927. const n = this.create('prim::isinstance', [v], 1);
  11928. n.tys_('types', types);
  11929. n.output().setType(torch.BoolType.get());
  11930. return n;
  11931. }
  11932. createSetAttr(obj, field, newValue) {
  11933. const n = this.create('prim::SetAttr', [obj, newValue], 0);
  11934. n.s_('name', field);
  11935. return n;
  11936. }
  11937. createGetAttr(obj, field) {
  11938. const n = this.create('prim::GetAttr', [obj]);
  11939. n.s_('name', field);
  11940. const classType = obj.type();
  11941. const outputType = classType.getAttribute(field);
  11942. n.output().setType(outputType);
  11943. n.output().setDebugName(torch._C.normalizeAttrName(field));
  11944. return n;
  11945. }
  11946. createLoad(name, type) {
  11947. const n = this.create('prim::Load', [], 1);
  11948. n.s_('name', name);
  11949. n.output().setType(type);
  11950. return n;
  11951. }
  11952. createStore(name, v) {
  11953. const n = this.create('prim::Store', [v], 0);
  11954. n.s_('name', name);
  11955. return n;
  11956. }
  11957. inputs() {
  11958. return this._block.inputs();
  11959. }
  11960. outputs() {
  11961. return this._block.outputs();
  11962. }
  11963. nodes() {
  11964. return this._block.nodes();
  11965. }
  11966. param_node() {
  11967. return this._block.param_node();
  11968. }
  11969. return_node() {
  11970. return this._block.return_node();
  11971. }
  11972. block() {
  11973. return this._block;
  11974. }
  11975. addInput(name) {
  11976. return this._block.addInput(name);
  11977. }
  11978. insertNode(node) {
  11979. torch._C.AT_ASSERT(this._insert_before.inBlockList());
  11980. return node.insertBefore(this._insert_before);
  11981. }
  11982. insertConstant(val, loc, scope) {
  11983. return torch._C.insertConstant(this, val, loc, scope);
  11984. }
  11985. insertMethodCall(method_name, matched) {
  11986. const result = this.insertNode(this.create('prim::CallMethod', matched.inputs))
  11987. .s_('name', method_name)
  11988. .output().setType(matched.return_types[0]);
  11989. return result;
  11990. }
  11991. insertUncheckedCast(v, type) {
  11992. const n = this.create('prim::unchecked_cast', [v]);
  11993. this.insertNode(n);
  11994. n.output().setType(type);
  11995. return n.output();
  11996. }
  11997. insertToList(v, type) {
  11998. let dim = 0;
  11999. let ptr = type;
  12000. while (ptr instanceof torch.ListType) {
  12001. ptr = ptr.getElementType();
  12002. dim += 1;
  12003. }
  12004. let elem_ty = 0;
  12005. if (ptr instanceof torch.IntType) {
  12006. elem_ty = 0;
  12007. } else if (ptr instanceof torch.FloatType) {
  12008. elem_ty = 1;
  12009. } else if (ptr instanceof torch.BoolType) {
  12010. elem_ty = 2;
  12011. } else if (ptr instanceof torch.ComplexType) {
  12012. elem_ty = 3;
  12013. } else {
  12014. throw new python.Error(`Unsupported list type '${type.kind()}'.`);
  12015. }
  12016. const dim_val = this.insertConstant(dim);
  12017. const elem_ty_val = this.insertConstant(elem_ty);
  12018. const n = this.insertNode(this.create('prim::tolist', [v, dim_val, elem_ty_val]));
  12019. n.output().setType(type);
  12020. return n.output();
  12021. }
  12022. insertFunctionCall(callee, matched) {
  12023. const func_name = callee.name();
  12024. const fn_constant = this.insertNode(this.create('prim::Constant')).s_('name', func_name).output().setType(torch._C.FunctionType.create(callee));
  12025. const inputs = [fn_constant, ...matched.inputs];
  12026. const result = this.insertNode(this.create('prim::CallFunction', inputs)).output().setType(matched.return_types[0]);
  12027. return result;
  12028. }
  12029. insertPoint() {
  12030. return this._insert_before;
  12031. }
  12032. setInsertPoint(node) {
  12033. if (node instanceof torch.Block) {
  12034. node = node.return_node();
  12035. }
  12036. this._insert_before = node;
  12037. }
  12038. freeNode(n) {
  12039. this.all_nodes.delete(n);
  12040. }
  12041. freeValue(v) {
  12042. v.setDebugName('');
  12043. this.all_values.delete(v);
  12044. }
  12045. freeBlock(b) {
  12046. this.all_blocks.delete(b);
  12047. }
  12048. copy() {
  12049. const new_g = new torch.Graph();
  12050. new_g.cloneFrom(this);
  12051. return new_g;
  12052. }
  12053. cloneFrom(src) {
  12054. const env = (v) => {
  12055. throw new python.Error(`Use of value '${v.debugName()}' not in scope.`);
  12056. };
  12057. this.block().cloneFrom(src.block(), env);
  12058. }
  12059. set_op_version(version) {
  12060. this._op_version = version;
  12061. }
  12062. get_op_version() {
  12063. return this._op_version;
  12064. }
  12065. print(out, print_source_locations) {
  12066. out.write('graph(');
  12067. torch._C.const_value_list_with_types(out, this.inputs(), ',\n ');
  12068. out.write('):\n');
  12069. const groups = [];
  12070. for (const node of this.nodes()) {
  12071. node.print(out, 1, groups, print_source_locations);
  12072. }
  12073. out.write(' return (');
  12074. torch._C.printValueRefs(out, this.outputs());
  12075. out.write(')\n');
  12076. for (let i = 0; i < groups.length; i++) {
  12077. const fg = groups[i];
  12078. out.write('with ');
  12079. out.write(fg.kind());
  12080. out.write(`_${i} = `);
  12081. out.write(fg.g('Subgraph'));
  12082. }
  12083. return out;
  12084. }
  12085. toString() {
  12086. const out = new io.StringIO();
  12087. this.print(out, true);
  12088. return out.toString();
  12089. }
  12090. });
  12091. this.registerType('torch.Block', class {
  12092. constructor(graph, node) {
  12093. this._graph = graph;
  12094. this._input = graph.create('prim::Param', 0);
  12095. this._output = graph.create('prim::Return', 0);
  12096. this._owning_node = node;
  12097. this._input.next = this._output;
  12098. this._input.prev = this._output;
  12099. this._output.next = this._input;
  12100. this._output.prev = this._input;
  12101. this._graph.all_blocks.add(this);
  12102. this._output._owning_block = this;
  12103. // output_.topo_position_ = kUpperBound;
  12104. this._input._owning_block = this;
  12105. // input_.topo_position_ = kLowerBound;
  12106. }
  12107. inputs() {
  12108. return this._input.outputs();
  12109. }
  12110. outputs() {
  12111. return this._output.inputs();
  12112. }
  12113. nodes() {
  12114. return new torch._C.graph_node_list(this._input);
  12115. }
  12116. return_node() {
  12117. return this._output;
  12118. }
  12119. param_node() {
  12120. return this._input;
  12121. }
  12122. owningNode() {
  12123. return this._owning_node;
  12124. }
  12125. owningGraph() {
  12126. return this._graph;
  12127. }
  12128. addInput(name) {
  12129. const value = this._input.addOutput();
  12130. value.setDebugName(name || '');
  12131. return value;
  12132. }
  12133. registerOutput(value) {
  12134. this._output.addInput(value);
  12135. return this.outputs().length - 1;
  12136. }
  12137. appendNode(n) {
  12138. if (n._graph !== this._graph || n.inBlockList()) {
  12139. throw new python.Error('Node not in graph.');
  12140. }
  12141. n.insertBefore(this._output);
  12142. return n;
  12143. }
  12144. cloneFrom(src, value_map) {
  12145. const local_map = new Map();
  12146. const env = (v) => {
  12147. if (local_map.has(v)) {
  12148. return local_map.get(v);
  12149. }
  12150. return value_map(v);
  12151. };
  12152. const graph = this.owningGraph();
  12153. for (const input of src.inputs()) {
  12154. local_map.set(input, this.addInput().copyMetadata(input));
  12155. }
  12156. for (const node of src.nodes()) {
  12157. const new_node = this.appendNode(graph.createClone(node, env));
  12158. for (let i = 0; i < node.outputs().length; i++) {
  12159. const oo = node.outputs()[i];
  12160. const no = new_node.outputs()[i];
  12161. local_map.set(oo, no);
  12162. no.copyMetadata(oo);
  12163. }
  12164. }
  12165. for (const output of src.outputs()) {
  12166. this.registerOutput(env(output));
  12167. }
  12168. }
  12169. eraseOutput(i) {
  12170. this._output.removeInput(i);
  12171. }
  12172. destroy() {
  12173. this._output.removeAllInputs();
  12174. for (const n of this.nodes()) {
  12175. n.destroy();
  12176. }
  12177. this._output.destroy();
  12178. this._input.destroy();
  12179. this._graph.freeBlock(this);
  12180. }
  12181. });
  12182. this.registerType('torch.Node', class {
  12183. constructor(graph, kind) {
  12184. this._kind = kind;
  12185. this._graph = graph;
  12186. this._owning_block = null;
  12187. this._values = new Map();
  12188. this._inputs = [];
  12189. this._outputs = [];
  12190. this._blocks = [];
  12191. this._graph.all_nodes.add(this);
  12192. this._prev = null;
  12193. this._next = null;
  12194. this._source_range = null;
  12195. this._op = null;
  12196. }
  12197. owningGraph() {
  12198. return this._graph;
  12199. }
  12200. owningBlock() {
  12201. return this._owning_block;
  12202. }
  12203. kind() {
  12204. return this._kind;
  12205. }
  12206. schema() {
  12207. if (this._op) {
  12208. return this._op.schema();
  12209. }
  12210. // Node::schema() throws while torch.Node.schema() does not.
  12211. const op = this.maybeOperator();
  12212. if (op) {
  12213. return op.schema();
  12214. }
  12215. return null;
  12216. // return this.getOperator().schema();
  12217. }
  12218. hasNamedInput(name) {
  12219. for (const argument of this.schema().arguments) {
  12220. if (argument.name === name) {
  12221. return true;
  12222. }
  12223. }
  12224. return false;
  12225. }
  12226. matches(schema) {
  12227. if (torch._C.isBlockListedSchema(schema)) {
  12228. return false;
  12229. }
  12230. if (this.kind() !== schema.name) {
  12231. return false;
  12232. }
  12233. const actuals = this.inputs();
  12234. const formals = schema.arguments;
  12235. if (actuals.length < formals.length) {
  12236. return false;
  12237. }
  12238. const type_env = new Map();
  12239. for (let i = 0; i < formals.length; i++) {
  12240. let formal = formals[i].type;
  12241. const matched_type = torch._C.matchTypeVariables(formal, actuals[i].type(), type_env);
  12242. if (!matched_type.success()) {
  12243. return false;
  12244. }
  12245. const resolved = torch._C.tryEvalTypeVariables(formal, type_env);
  12246. if (resolved) {
  12247. formal = resolved;
  12248. }
  12249. if (!actuals[i].type().isSubtypeOf(formal)) {
  12250. return false;
  12251. }
  12252. }
  12253. if (!schema.is_vararg && actuals.length !== formals.length) {
  12254. return false;
  12255. }
  12256. return true;
  12257. }
  12258. mustBeNone() {
  12259. return this._kind === 'prim::AutogradZero' ||
  12260. (this.outputs().length === 1 && this.output().type() === torch.NoneType.get()) ||
  12261. (this._kind === 'prim::Constant' && !this.hasAttributes() && this.output().type() instanceof torch.OptionalType);
  12262. }
  12263. maybeSchema() {
  12264. const op = this.maybeOperator();
  12265. if (op) {
  12266. return op.schema();
  12267. }
  12268. return null;
  12269. }
  12270. maybeOperator() {
  12271. if (!this._op) {
  12272. const candidates = torch._C.getAllOperatorsFor(this.kind());
  12273. for (const candidate of candidates) {
  12274. if (this.matches(candidate.schema())) {
  12275. this._op = candidate;
  12276. break;
  12277. }
  12278. }
  12279. }
  12280. return this._op;
  12281. }
  12282. getOperator() {
  12283. const maybe = this.maybeOperator();
  12284. if (maybe) {
  12285. return maybe;
  12286. }
  12287. throw new python.Error(`Schema not found for node '${this.kind()}'.`);
  12288. }
  12289. getOperation() {
  12290. return this.getOperator().getOperation(this);
  12291. }
  12292. isNondeterministic() {
  12293. const schema = this.maybeSchema();
  12294. if (!this.kind().startsWith('aten::')) {
  12295. return false;
  12296. }
  12297. if (!schema) {
  12298. return false;
  12299. }
  12300. const schema_info = new torch._C.SchemaInfo(schema);
  12301. if (this.hasNamedInput('train')) {
  12302. throw new python.Error('Not Implemented.');
  12303. // const value = constant_as<bool>(this.namedInput("train"));
  12304. // if (value) {
  12305. // schema_info.addArgumentValue('train', value);
  12306. // }
  12307. }
  12308. return schema_info.is_nondeterministic();
  12309. }
  12310. hasSideEffects() {
  12311. switch (this._kind) {
  12312. case 'prim::PythonOp':
  12313. case 'prim::IgnoredPythonOp':
  12314. case 'prim::Print':
  12315. case 'prim::RaiseException':
  12316. case 'aten::warn':
  12317. case 'aten::save':
  12318. case 'aten::manual_seed':
  12319. case 'prim::AddStatValue':
  12320. case 'prim::TimePoint':
  12321. case 'prim::CallFunction':
  12322. case 'prim::CallMethod':
  12323. case 'prim::BailoutTemplate':
  12324. case 'prim::BailOut':
  12325. case 'prim::rpc_async':
  12326. case 'prim::rpc_sync':
  12327. case 'prim::rpc_remote':
  12328. case 'aten::wait':
  12329. case 'cuda::set_stream':
  12330. case 'cuda::_set_device':
  12331. case 'cuda::_current_device':
  12332. case 'cuda::synchronize':
  12333. case 'prim::Enter':
  12334. case 'prim::Exit':
  12335. return true;
  12336. default:
  12337. break;
  12338. }
  12339. const op = this.maybeOperator();
  12340. if (!op) {
  12341. torch._C.TORCH_INTERNAL_ASSERT(this._kind.startsWith('prim::'));
  12342. return false;
  12343. }
  12344. if (this._kind.startsWith('prim::') || this._kind.startsWith('aten::') || this._kind.startsWith('cuda::')) {
  12345. torch._C.TORCH_INTERNAL_ASSERT(
  12346. op.aliasAnalysisKind() === 'INTERNAL_SPECIAL_CASE' ||
  12347. op.aliasAnalysisKind() === 'FROM_SCHEMA' ||
  12348. op.aliasAnalysisKind() === 'CONSERVATIVE');
  12349. }
  12350. switch (op.aliasAnalysisKind()) {
  12351. case 'PURE_FUNCTION':
  12352. case 'FROM_SCHEMA':
  12353. case 'INTERNAL_SPECIAL_CASE':
  12354. return false;
  12355. case 'CONSERVATIVE':
  12356. return true;
  12357. default:
  12358. break;
  12359. }
  12360. torch._C.TORCH_INTERNAL_ASSERT(false);
  12361. return false;
  12362. }
  12363. inputs() {
  12364. return this._inputs;
  12365. }
  12366. outputs() {
  12367. return this._outputs;
  12368. }
  12369. input(i) {
  12370. if (i === undefined) {
  12371. torch._C.AT_ASSERT(this._inputs.length === 1);
  12372. return this._inputs[0];
  12373. }
  12374. return this._inputs[i];
  12375. }
  12376. output(i) {
  12377. if (i === undefined) {
  12378. torch._C.AT_ASSERT(this._outputs.length === 1);
  12379. return this._outputs[0];
  12380. }
  12381. return this._outputs[i];
  12382. }
  12383. hasUses() {
  12384. for (const o of this.outputs()) {
  12385. if (o.uses().length > 0) {
  12386. return true;
  12387. }
  12388. }
  12389. return false;
  12390. }
  12391. blocks() {
  12392. return this._blocks;
  12393. }
  12394. insertInput(i, value) {
  12395. torch._C.AT_ASSERT(this._graph === value.owningGraph());
  12396. this._op = null;
  12397. for (let use_itr = i; use_itr < this._inputs.length; use_itr++) {
  12398. const use = this.findUseForInput(use_itr);
  12399. use.offset += 1;
  12400. }
  12401. this._inputs.splice(i, 0, value);
  12402. value._uses.push(new torch.Use(this, i));
  12403. return value;
  12404. }
  12405. addInput(value) {
  12406. torch._C.AT_ASSERT(this._graph === value.owningGraph());
  12407. this._op = null;
  12408. const use = new torch.Use(this, this._inputs.length);
  12409. value.uses().push(use);
  12410. this._inputs.push(value);
  12411. return value;
  12412. }
  12413. addOutput() {
  12414. const value = new torch.Value(this, this._outputs.length);
  12415. this._outputs.push(value);
  12416. return value;
  12417. }
  12418. addBlock() {
  12419. this._op = null;
  12420. this._blocks.push(new torch.Block(this.owningGraph(), this));
  12421. return this._blocks[this._blocks.length - 1];
  12422. }
  12423. get prev() {
  12424. return this._prev;
  12425. }
  12426. set prev(value) {
  12427. this._prev = value;
  12428. }
  12429. get next() {
  12430. return this._next;
  12431. }
  12432. set next(value) {
  12433. this._next = value;
  12434. }
  12435. insertBefore(n) {
  12436. if (!n.inBlockList()) {
  12437. throw new python.Error('Node not in block.');
  12438. }
  12439. this.insertAfter(n.prev);
  12440. return this;
  12441. }
  12442. insertAfter(n) {
  12443. torch._C.AT_ASSERT(!this.inBlockList() || n.inBlockList());
  12444. torch._C.AT_ASSERT(n.owningBlock());
  12445. torch._C.TORCH_INTERNAL_ASSERT(n.kind() !== 'prim::Return');
  12446. this._owning_block = n.owningBlock();
  12447. const next = n.next;
  12448. n.next = this;
  12449. this.prev = n;
  12450. this.next = next;
  12451. next.prev = this;
  12452. // this.assignTopoPosition();
  12453. return this;
  12454. }
  12455. allocNewInstance(g) {
  12456. return new torch.Node(g, this.kind());
  12457. }
  12458. cloneFrom(s) {
  12459. this._source_range = s._source_range;
  12460. if (s._scope && !s._scope.isBlank()) {
  12461. this._scope = s._scope;
  12462. }
  12463. this.copyAttributes(s);
  12464. this._callstack = s._callstack;
  12465. }
  12466. copyAttributes(rhs) {
  12467. this._values = new Map(rhs._values);
  12468. return this;
  12469. }
  12470. dropInput(i) {
  12471. torch._C.AT_ASSERT(i < this._inputs.length);
  12472. const input_node = this._inputs[i];
  12473. const use_it = this.findUseForInput(i);
  12474. input_node._uses = input_node._uses.filter((use) => use !== use_it);
  12475. this._inputs[i] = null;
  12476. return input_node;
  12477. }
  12478. eraseOutput(i) {
  12479. torch._C.AT_ASSERT(i < this._outputs.length);
  12480. // torch._C.AT_ASSERT(this._outputs[i].uses().length === 0);
  12481. this._op = null;
  12482. const n = this._outputs[i];
  12483. this._outputs.splice(i, 1);
  12484. this.owningGraph().freeValue(n);
  12485. for (let j = i; j < this._outputs.length; j++) {
  12486. this._outputs[j]._offset--;
  12487. }
  12488. }
  12489. eraseBlock(i) {
  12490. this._op = null;
  12491. const n = this._blocks[i];
  12492. this._blocks.splice(i, 1);
  12493. n.destroy();
  12494. }
  12495. findUseForInput(i) {
  12496. const input_uses = this._inputs[i]._uses;
  12497. for (const use_it of input_uses) {
  12498. if (use_it.user === this && use_it.offset === i) {
  12499. return use_it;
  12500. }
  12501. }
  12502. throw new python.Error('Input use not found.');
  12503. }
  12504. moveBefore(n) {
  12505. this.removeFromList();
  12506. this.insertBefore(n);
  12507. }
  12508. removeInput(i) {
  12509. this._op = null;
  12510. this.dropInput(i);
  12511. for (let j = i + 1; j < this._inputs.length; j++) {
  12512. const it = this.findUseForInput(j);
  12513. it.offset--;
  12514. }
  12515. this._inputs.splice(i, 1);
  12516. }
  12517. removeAllInputs() {
  12518. this._op = null;
  12519. for (let i = 0; i < this._inputs.length; i++) {
  12520. this.dropInput(i);
  12521. }
  12522. this._inputs = [];
  12523. }
  12524. inBlockList() {
  12525. return this.next !== null;
  12526. }
  12527. removeFromList() {
  12528. this._owning_block = null;
  12529. const next = this.next;
  12530. const prev = this.prev;
  12531. prev.next = next;
  12532. next.prev = prev;
  12533. this.next = null;
  12534. this.prev = null;
  12535. }
  12536. destroy() {
  12537. while (this.outputs().length > 0) {
  12538. this.eraseOutput(this.outputs().length - 1);
  12539. }
  12540. while (this.blocks().length > 0) {
  12541. this.eraseBlock(this.blocks().length - 1);
  12542. }
  12543. this.removeAllInputs();
  12544. if (this.inBlockList()) {
  12545. this.removeFromList();
  12546. }
  12547. this._graph.freeNode(this);
  12548. }
  12549. replaceAllUsesWith(n) {
  12550. torch._C.AT_ASSERT(this.outputs().length === n.outputs().length);
  12551. const nOutputs = this.outputs().length;
  12552. for (let i = 0; i < nOutputs; i++) {
  12553. this.outputs()[i].replaceAllUsesWith(n.outputs()[i]);
  12554. }
  12555. }
  12556. s_(name, value) {
  12557. this._values.set(name, [value, 's']);
  12558. return this;
  12559. }
  12560. s(name) {
  12561. return this._values.get(name)[0];
  12562. }
  12563. ss_(name, value) {
  12564. this._values.set(name, [value, 'ss']);
  12565. return this;
  12566. }
  12567. ss(name) {
  12568. return this._values.get(name)[0];
  12569. }
  12570. i_(name, value) {
  12571. this._values.set(name, [value, 'i']);
  12572. return this;
  12573. }
  12574. i(name) {
  12575. return this._values.get(name)[0];
  12576. }
  12577. f_(name, value) {
  12578. this._values.set(name, [value, 'f']);
  12579. return this;
  12580. }
  12581. f(name) {
  12582. return this._values.get(name)[0];
  12583. }
  12584. c_(name, value) {
  12585. this._values.set(name, [value, 'c']);
  12586. return this;
  12587. }
  12588. c(name) {
  12589. return this._values.get(name)[0];
  12590. }
  12591. t_(name, value) {
  12592. this._values.set(name, [value, 't']);
  12593. return this;
  12594. }
  12595. t(name) {
  12596. return this._values.get(name)[0];
  12597. }
  12598. tys_(name, value) {
  12599. this._values.set(name, [value, 'tys']);
  12600. return this;
  12601. }
  12602. tys(name) {
  12603. return this._values.get(name)[0];
  12604. }
  12605. ival_(name, value) {
  12606. this._values.set(name, [value, 'ival']);
  12607. return this;
  12608. }
  12609. ival(name) {
  12610. return this._values.get(name)[0];
  12611. }
  12612. hasAttribute(name) {
  12613. return this._values.has(name);
  12614. }
  12615. hasAttributes() {
  12616. return this._values.size > 0;
  12617. }
  12618. attributeNames() {
  12619. return Array.from(this._values.keys());
  12620. }
  12621. kindOf(name) {
  12622. return this._values.get(name)[1];
  12623. }
  12624. setSourceRange(r) {
  12625. torch._C.AT_ASSERT(r instanceof torch._C.SourceRange);
  12626. this._source_range = r;
  12627. return this;
  12628. }
  12629. sourceRange() {
  12630. if (this._source_range) {
  12631. return this._source_range;
  12632. }
  12633. return new torch._C.SourceRange();
  12634. }
  12635. print_attributes(out, ignore_subgraph) {
  12636. ignore_subgraph = ignore_subgraph || false;
  12637. out.write('[');
  12638. const names = this.attributeNames();
  12639. for (let i = 0; i < names.length; i++) {
  12640. const name = names[i];
  12641. if (ignore_subgraph && name === 'Subgraph') {
  12642. continue;
  12643. }
  12644. if (i > 0) {
  12645. out.write(', ');
  12646. }
  12647. out.write(`${name}=`);
  12648. this.printAttrValue(out, name);
  12649. }
  12650. out.write(']');
  12651. }
  12652. printTypeList(out, items) {
  12653. out.write('[');
  12654. for (let i = 0; i < items.length; i++) {
  12655. const item = items[i];
  12656. if (i++ > 0) {
  12657. out.write(', ');
  12658. }
  12659. out.write(item.str());
  12660. }
  12661. out.write(']');
  12662. }
  12663. printAttrValue(out, name) {
  12664. const kind = this.kindOf(name);
  12665. switch (kind) {
  12666. case 'c': case 'cs': case 'f': case 'fs': case 'i': case 'is':
  12667. case 'ss': case 'ival': case 'ty':
  12668. out.write(this[kind](name));
  12669. break;
  12670. case 's':
  12671. out.write(`"${this.s(name)}"`);
  12672. break;
  12673. case 't':
  12674. out.write(`"{}"`);
  12675. break;
  12676. case 'ts': out.write('[<Tensors>]'); break;
  12677. case 'g': out.write('[<Graph>]'); break;
  12678. case 'gs': out.write('[<Graphs>]'); break;
  12679. case 'tys': this.printTypeList(out, this.tys(name)); break;
  12680. default: throw new python.Error(`Unknown attribute kind '${kind}'.`);
  12681. }
  12682. }
  12683. print(out, level, groups, print_source_locations, print_attributes, print_scopes, print_body) {
  12684. print_source_locations = print_source_locations === false ? false : true;
  12685. print_attributes = print_attributes === false ? false : true;
  12686. print_scopes = print_scopes === false ? false : true;
  12687. print_body = print_body === false ? false : true;
  12688. const outs = this.outputs();
  12689. torch._C.indent(out, level);
  12690. torch._C.const_value_list_with_types(out, outs, ', ');
  12691. out.write(' = ');
  12692. if (this.kind() === 'prim::PythonOp') {
  12693. throw new python.Error('Not implemented.');
  12694. } else if (this.hasAttribute('Subgraph') && groups) {
  12695. throw new python.Error('Not implemented.');
  12696. } else {
  12697. out.write(this.kind());
  12698. if (print_attributes && this.hasAttributes()) {
  12699. this.print_attributes(out);
  12700. }
  12701. }
  12702. out.write('(');
  12703. torch._C.printValueRefs(out, this.inputs());
  12704. out.write(')');
  12705. if (print_scopes) {
  12706. //
  12707. }
  12708. if (print_source_locations) {
  12709. let r = this.sourceRange();
  12710. if (r.source()) {
  12711. const orig = this.sourceRange().source().findSourceRangeThatGenerated(r);
  12712. if (orig) {
  12713. r = orig;
  12714. }
  12715. }
  12716. const file_line_col = r.file_line_col();
  12717. if (file_line_col !== null) {
  12718. const [filename, line, col] = file_line_col;
  12719. out.write(` # ${filename}:${line}:${col}`);
  12720. }
  12721. }
  12722. if (!print_body) {
  12723. return out;
  12724. }
  12725. out.write('\n');
  12726. for (let i = 0; i < this.blocks().length; i++) {
  12727. const b = this.blocks().at(i);
  12728. torch._C.indent(out, level + 1);
  12729. out.write(`block${i}(`);
  12730. torch._C.const_value_list_with_types(out, b.inputs());
  12731. out.write('):\n');
  12732. for (const nested of b.nodes()) {
  12733. nested.print(out, level + 2, groups);
  12734. }
  12735. torch._C.indent(out, level + 2);
  12736. out.write('-> (');
  12737. torch._C.printValueRefs(out, b.outputs());
  12738. out.write(')\n');
  12739. }
  12740. return out;
  12741. }
  12742. toString() {
  12743. const out = new io.StringIO();
  12744. this.print(out, 0, true);
  12745. return out.toString();
  12746. }
  12747. });
  12748. this.registerType('torch.Value', class {
  12749. constructor(node, offset) {
  12750. this._node = node;
  12751. this._offset = offset;
  12752. this._unique = node._graph._next_unique++;
  12753. this._uses = [];
  12754. this._node._graph.all_values.add(this);
  12755. }
  12756. unique() {
  12757. return this._unique;
  12758. }
  12759. node() {
  12760. return this._node;
  12761. }
  12762. owningGraph() {
  12763. return this._node.owningGraph();
  12764. }
  12765. uses() {
  12766. return this._uses;
  12767. }
  12768. hasUses() {
  12769. return this._uses.length > 0;
  12770. }
  12771. mustBeNone() {
  12772. return this.type() instanceof torch.NoneType || this._node.mustBeNone();
  12773. }
  12774. mustNotBeNone() {
  12775. return this._node.kind() !== 'prim::AutogradAdd' &&
  12776. this.type() !== torch.NoneType.get() &&
  12777. !(this.type() instanceof torch.OptionalType) &&
  12778. !(this.type() instanceof torch.UnionType && this.type().expect(torch.UnionType).canHoldType(torch.NoneType.get()));
  12779. }
  12780. isValidName(name) {
  12781. if (name.length === 0) {
  12782. return true;
  12783. }
  12784. if (torch._C.isNumber(name)) {
  12785. return false;
  12786. }
  12787. return true;
  12788. }
  12789. hasDebugName() {
  12790. return this._unique_name && this._unique_name.length > 0;
  12791. }
  12792. setDebugName(name) {
  12793. if (!this.isValidName(name)) {
  12794. throw new python.Error(`Invalid name '${name}'.`);
  12795. }
  12796. const names = this.node().owningGraph()._unique_names;
  12797. if (this.hasDebugName()) {
  12798. names.delete(this._unique_name);
  12799. this._unique_name = '';
  12800. }
  12801. if (!name) {
  12802. return this;
  12803. }
  12804. const old_owner_of_name = names.get(name);
  12805. if (old_owner_of_name) {
  12806. let suffix = 1;
  12807. let name_base = name;
  12808. const last_dot_pos = name.lastIndexOf('.');
  12809. if (last_dot_pos !== -1) {
  12810. if (/^\d+$/.test(name.substring(last_dot_pos + 1))) {
  12811. suffix = Number(name.substring(last_dot_pos + 1));
  12812. name_base = name.substring(0, last_dot_pos);
  12813. }
  12814. }
  12815. const names_suffixes = this.node().owningGraph()._name_base_suffix;
  12816. if (names_suffixes.has(name_base)) {
  12817. suffix = Math.max(suffix, names_suffixes.get(name_base));
  12818. }
  12819. let replacement_name = null;
  12820. do {
  12821. replacement_name = `${name_base}.${suffix++}`;
  12822. } while (names.has(replacement_name));
  12823. names_suffixes.set(name_base, suffix);
  12824. old_owner_of_name.setDebugName(replacement_name);
  12825. }
  12826. names.set(name, this);
  12827. this._unique_name = name;
  12828. return this;
  12829. }
  12830. debugName() {
  12831. if (this.hasDebugName()) {
  12832. return this._unique_name;
  12833. }
  12834. return this.unique().toString();
  12835. }
  12836. type() {
  12837. return this._type;
  12838. }
  12839. setType(type) {
  12840. // torch._C.AT_ASSERT(type instanceof torch.Type);
  12841. if (type instanceof torch._C.DynamicType) {
  12842. type = type.fallback();
  12843. }
  12844. this._type = type;
  12845. for (const use of this._uses) {
  12846. use.user._op = null;
  12847. }
  12848. return this;
  12849. }
  12850. set value(value) { // remove
  12851. if (value instanceof torch.Value) {
  12852. throw new python.Error('Value cannot be a value.');
  12853. }
  12854. this._value = value;
  12855. }
  12856. get value() { // remove
  12857. return this._value;
  12858. }
  12859. replaceFirstUseWith(newValue) {
  12860. torch._C.AT_ASSERT(this.owningGraph() === newValue.owningGraph());
  12861. const [u] = this.uses();
  12862. u.user._inputs[u.offset] = newValue;
  12863. newValue._uses.push(u);
  12864. this._uses.shift();
  12865. }
  12866. replaceAllUsesWith(newValue) {
  12867. while (this.uses().length > 0) {
  12868. this.replaceFirstUseWith(newValue);
  12869. }
  12870. }
  12871. copyMetadata(from) {
  12872. this.setType(from.type());
  12873. if (from.hasDebugName()) {
  12874. this.setDebugName(from.debugName());
  12875. }
  12876. return this;
  12877. }
  12878. toString() {
  12879. return `${this.debugName()} : ${this.type().toString()}`;
  12880. }
  12881. });
  12882. this.registerType('torch.Use', class {
  12883. constructor(user, offset) {
  12884. this.user = user;
  12885. this.offset = offset;
  12886. }
  12887. });
  12888. this.registerType('torch._C.IValue', class {
  12889. constructor(value, tag) {
  12890. this.value = value;
  12891. if (tag) {
  12892. this.tag = tag;
  12893. } else if (value === undefined) {
  12894. this.tag = 'None';
  12895. this.value = null;
  12896. } else if (typeof value === 'boolean') {
  12897. this.tag = 'Bool';
  12898. } else if (typeof value === 'string') {
  12899. this.tag = 'String';
  12900. } else if (value instanceof torch.Tensor) {
  12901. this.tag = 'Tensor';
  12902. } else if (value instanceof torch.ScriptObject) {
  12903. this.tag = 'Object';
  12904. } else if (Array.isArray(value)) {
  12905. this.tag = 'GenericList';
  12906. } else if (value instanceof torch._C.Tuple) {
  12907. this.tag = 'Tuple';
  12908. } else if (value instanceof torch.device) {
  12909. this.tag = 'Device';
  12910. } else if (Number.isInteger(value)) {
  12911. this.tag = 'Int';
  12912. } else if (typeof value === 'number') {
  12913. this.tag = 'Double';
  12914. } else if (value instanceof builtins.complex) {
  12915. this.tag = 'ComplexDouble';
  12916. } else if (value instanceof torch._C.EnumHolder) {
  12917. this.tag = 'Enum';
  12918. } else {
  12919. throw new python.Error('Unsupported type.');
  12920. }
  12921. }
  12922. isNone() {
  12923. return this.tag === 'None';
  12924. }
  12925. isBool() {
  12926. return this.tag === 'Bool';
  12927. }
  12928. toBool() {
  12929. return this.value;
  12930. }
  12931. isObject() {
  12932. return this.tag === 'Object';
  12933. }
  12934. toObject() {
  12935. return this.value;
  12936. }
  12937. isTensor() {
  12938. return this.tag === 'Tensor';
  12939. }
  12940. toTensor() {
  12941. return this.value;
  12942. }
  12943. isDouble() {
  12944. return this.tag === 'Double';
  12945. }
  12946. toDouble() {
  12947. return this.value;
  12948. }
  12949. isComplexDouble() {
  12950. return this.tag === 'ComplexDouble' || this.tag === 'Complex';
  12951. }
  12952. toComplexDouble() {
  12953. return this.value;
  12954. }
  12955. isInt() {
  12956. return this.tag === 'Int';
  12957. }
  12958. toInt() {
  12959. if (this.isInt()) {
  12960. return this.value;
  12961. } else if (this.isSymInt()) {
  12962. return this.toSymInt().guard_int(/* __FILE__, __LINE__ */);
  12963. }
  12964. throw new python.Error('Expected int.');
  12965. }
  12966. isString() {
  12967. return this.tag === 'String';
  12968. }
  12969. toStringRef() {
  12970. return this.value;
  12971. }
  12972. isList() {
  12973. return this.tag === 'GenericList';
  12974. }
  12975. toList() {
  12976. return this.value;
  12977. }
  12978. toListRef() {
  12979. return this.value;
  12980. }
  12981. isBoolList() {
  12982. return this.value instanceof torch._C.List && this.value.elementType() instanceof torch.BoolType;
  12983. }
  12984. isIntList() {
  12985. return this.value instanceof torch._C.List && this.value.elementType() instanceof torch.IntType;
  12986. }
  12987. isDoubleList() {
  12988. return this.value instanceof torch._C.List && this.value.elementType() instanceof torch.FloatType;
  12989. }
  12990. isDevice() {
  12991. return this.tag === 'Device';
  12992. }
  12993. toDevice() {
  12994. return this.value;
  12995. }
  12996. isGenerator() {
  12997. return this.tag === 'Generator';
  12998. }
  12999. isStream() {
  13000. return this.tag === 'Stream';
  13001. }
  13002. isGenericDict() {
  13003. return this.tag === 'GenericDict';
  13004. }
  13005. isEnum() {
  13006. return this.tag === 'Enum';
  13007. }
  13008. toEnumHolder() {
  13009. return this.value;
  13010. }
  13011. isTuple() {
  13012. return this.tag === 'Tuple';
  13013. }
  13014. toTupleRef() {
  13015. return this.value;
  13016. }
  13017. isCustomClass() {
  13018. return torch._C.isCustomClass(this);
  13019. }
  13020. equals(rhs) {
  13021. switch (this.tag) {
  13022. case 'None': return rhs.isNone();
  13023. case 'Bool': return rhs.isBool() && this.toBool() === rhs.toBool();
  13024. case 'Int': return rhs.isInt() && this.toInt() === rhs.toInt();
  13025. case 'Double': return rhs.isDouble() && this.toDouble() === rhs.toDouble();
  13026. case 'String': return rhs.isString() && this.toString() === rhs.toString();
  13027. case 'Tensor': return rhs.isTensor() && this.toTensor() === rhs.toTensor();
  13028. case 'Object': return rhs.isObject() && this.toObject() === rhs.toObject();
  13029. case 'Device': return rhs.isObject() && this.toDevice() === rhs.toDevice();
  13030. case 'GenericList': {
  13031. if (rhs.isList()) {
  13032. const a = this.toList();
  13033. const b = rhs.toList();
  13034. return (a.length === b.length) && a.every((v, i) => v === b[i]);
  13035. }
  13036. return false;
  13037. }
  13038. default: throw new python.Error(`IValue.equals() not implemented for '${this.tag}.`);
  13039. }
  13040. }
  13041. is(rhs) {
  13042. return this.equals(rhs);
  13043. }
  13044. type() {
  13045. switch (this.tag) {
  13046. case 'None': return torch.NoneType.get();
  13047. case 'Bool': return torch.BoolType.get();
  13048. case 'Int': return torch.IntType.get();
  13049. case 'Double': return torch.FloatType.get();
  13050. case 'String': return torch.StringType.get();
  13051. case 'Device': return torch.DeviceObjType.get();
  13052. case 'Tuple': return torch.TupleType.create(this.value.elements().map((ivalue) => ivalue.type()));
  13053. case 'Enum': return this.toEnumHolder().type();
  13054. case 'GenericList': return torch.ListType.create(this.toList().elementType());
  13055. default: throw new python.Error(`IValue.type('${this.tag}') not implemented.`);
  13056. }
  13057. }
  13058. });
  13059. this.registerFunction('torch._C.indent', (out, level) => {
  13060. for (let i = 0; i < level; i++) {
  13061. out.write(' ');
  13062. }
  13063. return out;
  13064. });
  13065. this.registerFunction('torch._C.printValueRef', (out, n) => {
  13066. out.write(`%${n.debugName()}`);
  13067. });
  13068. this.registerFunction('torch._C.printValueRefs', (out, nodes) => {
  13069. for (let i = 0; i < nodes.length; i++) {
  13070. const n = nodes[i];
  13071. if (i > 0) {
  13072. out.write(', ');
  13073. }
  13074. torch._C.printValueRef(out, n);
  13075. }
  13076. return out;
  13077. });
  13078. this.registerFunction('torch._C.const_value_list_with_types', (out, values, delim) => {
  13079. for (let i = 0; i < values.length; i++) {
  13080. const n = values[i];
  13081. if (i > 0) {
  13082. out.write(delim);
  13083. }
  13084. torch._C.printValueRef(out, n);
  13085. out.write(' : ');
  13086. out.write(n.type().str());
  13087. }
  13088. });
  13089. this.register('torch.jit._script');
  13090. this.register('torch.jit._trace');
  13091. this.registerType('torch._C.Parser', class {
  13092. constructor(source) {
  13093. this.L = source;
  13094. }
  13095. parse() {
  13096. const p = ast.parse(this.L.text_str(), this.L.filename());
  13097. return p;
  13098. }
  13099. parseExp() {
  13100. const expr = ast.parse(this.L.text_str());
  13101. return expr.body[0].value;
  13102. }
  13103. });
  13104. this.registerType('torch._C.StringCordView', class {
  13105. });
  13106. this.registerType('torch._C.Source', class {
  13107. constructor(text_view, filename, starting_line_no, gen_ranges /*, copies_str */) {
  13108. if (text_view instanceof Uint8Array) {
  13109. const decoder = new TextDecoder('utf-8');
  13110. this._text_view = decoder.decode(text_view);
  13111. } else if (typeof text_view === 'string') {
  13112. this._text_view = text_view;
  13113. } else {
  13114. throw new python.Error('Invalid text view.');
  13115. }
  13116. this._filename = filename;
  13117. this._starting_line_no = starting_line_no;
  13118. this._gen_ranges = gen_ranges;
  13119. this.calc_line_start_offsets();
  13120. }
  13121. text_str() {
  13122. return this._text_view;
  13123. }
  13124. size() {
  13125. return this._text_view.length;
  13126. }
  13127. filename() {
  13128. return this._filename;
  13129. }
  13130. calc_line_start_offsets() {
  13131. let pos = 0;
  13132. this._line_starting_offsets = [0];
  13133. while ((pos = this._text_view.indexOf('\n', pos)) !== -1) {
  13134. pos += 1;
  13135. this._line_starting_offsets.push(pos);
  13136. }
  13137. }
  13138. offset_for_line(line) {
  13139. return this._line_starting_offsets[line];
  13140. }
  13141. lineno_for_offset(offset) {
  13142. const iter = this._line_starting_offsets.findIndex((value) => value > offset);
  13143. return (iter === -1 ? this._line_starting_offsets.length : iter) - 1;
  13144. }
  13145. lineno_to_source_lineno(lineno) {
  13146. if (this._filename) {
  13147. return lineno + this._starting_line_no;
  13148. }
  13149. return lineno;
  13150. }
  13151. findSourceRangeThatGenerated(range) {
  13152. if (!this._gen_ranges) {
  13153. return null;
  13154. }
  13155. return this._gen_ranges.findSourceRangeThatGenerated(range);
  13156. }
  13157. });
  13158. this.registerType('torch._C.SourceRange', class {
  13159. constructor(...args) {
  13160. if (args.length === 0) {
  13161. this._source_view = null;
  13162. } else if (args.length === 2) {
  13163. let node = null;
  13164. [this._source_view, node] = args;
  13165. this._start = this._source_view.offset_for_line(node.lineno - 1) + (node.col_offset - 1);
  13166. this._end = this._source_view.offset_for_line(node.end_lineno - 1) + (node.end_col_offset - 1);
  13167. } else if (args.length === 3) {
  13168. [this._source_view, this._start, this._end] = args;
  13169. } else {
  13170. throw new python.Error('Not implemented.');
  13171. }
  13172. }
  13173. source() {
  13174. return this._source_view;
  13175. }
  13176. file_line_col() {
  13177. if (!this._source_view || this.source().filename() === null) {
  13178. return null;
  13179. }
  13180. const lineno = this._source_view.lineno_for_offset(this._start);
  13181. const col_offset = this._start - this._source_view.offset_for_line(lineno);
  13182. return [this._source_view.filename(), this._source_view.lineno_to_source_lineno(lineno), col_offset];
  13183. }
  13184. start() {
  13185. return this._start;
  13186. }
  13187. toString() {
  13188. const loc = this.file_line_col();
  13189. return loc ? `${loc[0]}:${loc[1]}:${loc[2]}` : '';
  13190. }
  13191. });
  13192. this.registerType('torch._C.QualifiedName', class {
  13193. constructor(...args) {
  13194. let name = null;
  13195. if (args.length === 1 && typeof args[0] === 'string') {
  13196. [name] = args;
  13197. } else if (args.length === 1 && Array.isArray(args[0]) && args[0].every((arg) => typeof arg === 'string')) {
  13198. name = args[0].join('.');
  13199. } else {
  13200. name = `${args[0].qualifiedName()}.${args[1]}`;
  13201. }
  13202. const index = name.lastIndexOf('.');
  13203. this._qualifiedName = name;
  13204. this._prefix = index === -1 ? '' : name.substring(0, index);
  13205. this._name = index === -1 ? name : name.substring(index + 1);
  13206. }
  13207. qualifiedName() {
  13208. return this._qualifiedName; // "foo.bar.baz"
  13209. }
  13210. prefix() {
  13211. return this._prefix; // "foo.bar"
  13212. }
  13213. name() {
  13214. return this._name; // "baz"
  13215. }
  13216. atoms() {
  13217. return this._qualifiedName.split('.');
  13218. }
  13219. });
  13220. this.registerType('torch._C.Resolver', class {
  13221. resolveValue() {
  13222. throw new python.Error('Not implemented.');
  13223. }
  13224. resolveType() {
  13225. throw new python.Error('Not implemented.');
  13226. }
  13227. });
  13228. this.registerFunction('torch._C.registerCustomClass', (class_type) => {
  13229. torch._C.customClasses = torch._C.customClasses || new Map();
  13230. torch._C.TORCH_INTERNAL_ASSERT(class_type.name());
  13231. const name = class_type.name().qualifiedName();
  13232. torch._C.TORCH_CHECK(!torch._C.customClasses.has(name));
  13233. torch._C.customClasses.set(name, class_type);
  13234. });
  13235. this.registerFunction('torch._C.getCustomClass', (class_name) => {
  13236. torch._C.customClasses = torch._C.customClasses || new Map();
  13237. const ret = torch._C.customClasses.has(class_name) ? torch._C.customClasses.get(class_name) : null;
  13238. return ret;
  13239. });
  13240. this.registerFunction('torch._C.isCustomClass', (v) => {
  13241. return v.isObject() && v.toObject().type().name() && torch._C.getCustomClass(v.toObject().type().name().qualifiedName());
  13242. });
  13243. this.registerType('torch._C.SourceImporter', class extends torch._C.Resolver {
  13244. constructor(cu, constant_table, source_loader, version) {
  13245. super();
  13246. this._cu = cu;
  13247. this._constant_table = constant_table;
  13248. this._source_loader = source_loader;
  13249. this._version = version;
  13250. this._loaded_sources = new Set();
  13251. this._sources = new Map();
  13252. const sources = this._sources;
  13253. ast.AST.prototype.range = function() {
  13254. if (!this._range) {
  13255. if (sources.has(this.filename)) {
  13256. const source_view = sources.get(this.filename);
  13257. this._range = new torch._C.SourceRange(source_view, this);
  13258. } else {
  13259. this._range = new torch._C.SourceRange();
  13260. }
  13261. }
  13262. return this._range;
  13263. };
  13264. this._to_be_defined = new Map();
  13265. this._env = new Map([
  13266. ['torch', new torch._C.BuiltinModule('aten', version)],
  13267. ['ops', new torch._C.OpsValue(version)],
  13268. ['CONSTANTS', new torch._C.ConstantTableValue(constant_table)],
  13269. ['fork', torch._C.SpecialFormValue.create('prim::fork')],
  13270. ['awaitable', torch._C.SpecialFormValue.create('prim::awaitable')],
  13271. ['annotate', torch._C.SpecialFormValue.create('prim::annotate')],
  13272. ['unchecked_cast', torch._C.SpecialFormValue.create('prim::unchecked_cast')],
  13273. ['uninitialized', torch._C.SpecialFormValue.create('prim::Uninitialized')],
  13274. ]);
  13275. }
  13276. loadType(name) {
  13277. const type_parser = new torch._C.ScriptTypeParser(this);
  13278. return type_parser.parseType(name.qualifiedName());
  13279. }
  13280. resolveType(name) {
  13281. name = new torch._C.QualifiedName(name);
  13282. return this.findNamedType(name);
  13283. }
  13284. resolveValue(name, m, loc) {
  13285. if (this._env.has(name)) {
  13286. return this._env.get(name);
  13287. }
  13288. const graph = m.graph();
  13289. switch (name) {
  13290. case 'inf': return new torch._C.SimpleValue(graph.insertConstant(Infinity /* 'std::numeric_limits<double>::infinity()' */, loc));
  13291. case 'nan': return new torch._C.SimpleValue(graph.insertConstant(NaN /* 'std::numeric_limits<double>::quiet_NaN()' */, loc));
  13292. case 'infj': return new torch._C.SimpleValue(graph.insertConstant('c10::complex<double>(0, std::numeric_limits<double>::infinity())', loc));
  13293. case 'nanj': return new torch._C.SimpleValue(graph.insertConstant('c10::complex<double>(0, std::numeric_limits<double>::quiet_NaN()', loc));
  13294. case '__torch__': return new torch._C.ClassNamespaceValue(new torch._C.QualifiedName(name), this);
  13295. default: return null;
  13296. }
  13297. }
  13298. findNamedType(name) {
  13299. const custom_class = torch._C.getCustomClass(name.qualifiedName());
  13300. if (custom_class) {
  13301. return custom_class;
  13302. }
  13303. this.parseSourceIfNeeded(name.prefix());
  13304. const key = name.qualifiedName();
  13305. const it = this._to_be_defined.get(key);
  13306. if (it && it instanceof ast.ClassDef) {
  13307. this._to_be_defined.delete(key);
  13308. this.importNamedType(name.prefix(), it);
  13309. }
  13310. return this._cu.get_type(name);
  13311. }
  13312. importNamedType(qualifier, class_def) {
  13313. const qualified_name = new torch._C.QualifiedName(`${qualifier}.${class_def.name}`);
  13314. if (class_def.bases.length === 0) {
  13315. this.importClass(qualified_name, class_def, false);
  13316. return;
  13317. }
  13318. const superclass_name = class_def.bases[0].id;
  13319. if (superclass_name === 'Module') {
  13320. this.importClass(qualified_name, class_def, true);
  13321. } else if (superclass_name === 'NamedTuple') {
  13322. this.importNamedTuple(qualified_name, class_def);
  13323. } else if (superclass_name === 'Interface') {
  13324. // this._cu.define_interface(qualified_name, class_def, shared_from_this(), is_module=false);
  13325. } else if (superclass_name === 'ModuleInterface') {
  13326. // this._cu.define_interface(qualified_name, class_def, shared_from_this(), is_module=true);
  13327. } else if (superclass_name === 'Enum') {
  13328. this.importEnum(qualified_name, class_def);
  13329. } else {
  13330. throw new python.Error('TorchScript does not support class inheritance.');
  13331. }
  13332. }
  13333. importClass(qualified_classname, class_def, is_module) {
  13334. if (qualified_classname.prefix().startsWith('__torch__.torch.classes')) {
  13335. return;
  13336. }
  13337. const parameter_names = new Set();
  13338. const buffer_names = new Set();
  13339. const methods = [];
  13340. const method_resolvers = [];
  13341. const attributes = [];
  13342. const constants = [];
  13343. const pre_hook_names = new Set();
  13344. const pre_hook_def_map = new Map();
  13345. const hook_names = new Set();
  13346. const hook_def_map = new Map();
  13347. const class_type = torch.ClassType.create(qualified_classname.qualifiedName(), this._cu, is_module);
  13348. for (const stmt of class_def.body) {
  13349. if (stmt instanceof ast.Assign || stmt instanceof ast.AnnAssign) {
  13350. let target = null;
  13351. let annotation = null;
  13352. let value = null;
  13353. if (stmt instanceof ast.Assign) {
  13354. [target] = stmt.targets;
  13355. value = stmt.value;
  13356. } else {
  13357. target = stmt.target;
  13358. annotation = stmt.annotation;
  13359. value = stmt.value;
  13360. }
  13361. if (target instanceof ast.Name) {
  13362. const name = this._cu.execution.identifier(target);
  13363. switch (name) {
  13364. case '__annotations__': {
  13365. continue;
  13366. }
  13367. case '__parameters__': {
  13368. for (const elt of value.elts) {
  13369. parameter_names.add(elt.value);
  13370. }
  13371. break;
  13372. }
  13373. case '__buffers__': {
  13374. for (const elt of value.elts) {
  13375. buffer_names.add(elt.value);
  13376. }
  13377. break;
  13378. }
  13379. case '__forward_pre_hooks__': {
  13380. for (const elt of value.elts) {
  13381. pre_hook_names.add(elt.value);
  13382. }
  13383. break;
  13384. }
  13385. case '__forward_hooks__': {
  13386. for (const elt of value.elts) {
  13387. hook_names.add(elt.value);
  13388. }
  13389. break;
  13390. }
  13391. default: {
  13392. const fixed_up = this.attributeAssignmentSpecialHandlingHack(qualified_classname, stmt);
  13393. if (fixed_up) {
  13394. attributes.push({ name: fixed_up.target.id, value: fixed_up.value, annotation: fixed_up.annotation });
  13395. } else if (value) {
  13396. constants.push({ name, value, annotation });
  13397. } else {
  13398. attributes.push({ name, value, annotation });
  13399. }
  13400. break;
  13401. }
  13402. }
  13403. } else if (target instanceof ast.Subscript && target.value instanceof ast.Name && target.value.id === '__annotations__') {
  13404. const name = target.slice.value;
  13405. attributes.push({ name, value, annotation: stmt.value });
  13406. continue;
  13407. } else {
  13408. throw new python.Error('Unexpected statement kind in module metadata.');
  13409. }
  13410. } else if (stmt instanceof ast.FunctionDef) {
  13411. const def = stmt;
  13412. const def_name = def.name;
  13413. if (pre_hook_names.has(def_name)) {
  13414. pre_hook_def_map.set(def_name, def);
  13415. } else if (hook_names.has(def_name)) {
  13416. hook_def_map.set(def_name, def);
  13417. } else {
  13418. methods.push(def);
  13419. method_resolvers.push(this);
  13420. }
  13421. } else {
  13422. throw new python.Error('Unexpected statement kind in class body.');
  13423. }
  13424. }
  13425. const type_parser = new torch._C.ScriptTypeParser(this);
  13426. for (const assign of attributes) {
  13427. const name = assign.name;
  13428. const annotation = type_parser.parseTypeFromExpr(assign.annotation);
  13429. const is_parameter = parameter_names.has(name);
  13430. const is_buffer = buffer_names.has(name);
  13431. class_type.addAttribute(name, annotation, is_parameter, is_buffer);
  13432. }
  13433. for (const constant of constants) {
  13434. class_type.addConstant(constant.name, constant.value);
  13435. }
  13436. this._cu.register_type(class_type);
  13437. const self = new torch._C.SimpleSelf(class_type);
  13438. this._cu.define(qualified_classname, [], [], methods, method_resolvers, self, false, this._version);
  13439. }
  13440. importEnum(qualified_name, enum_def) {
  13441. const names_values = [];
  13442. let value_type = null;
  13443. const set_or_check_type = (t) => {
  13444. if (!value_type) {
  13445. value_type = t;
  13446. } else if (value_type !== t) {
  13447. throw new python.Error('Enum class with varying value types are not supported.');
  13448. }
  13449. };
  13450. for (const stmt of enum_def.body) {
  13451. if (stmt instanceof ast.Assign === false) {
  13452. throw new python.Error('Unexpected statement in Enum class body.');
  13453. }
  13454. const assign = stmt;
  13455. const name = assign.targets[0].id;
  13456. let ivalue = null;
  13457. const rhs = assign.value;
  13458. switch (rhs.type) {
  13459. case 'str':
  13460. ivalue = new torch._C.IValue(rhs.value, 'String');
  13461. set_or_check_type(torch.StringType.get());
  13462. break;
  13463. case 'int':
  13464. ivalue = new torch._C.IValue(rhs.value, 'Int');
  13465. set_or_check_type(torch.IntType.get());
  13466. break;
  13467. case 'float':
  13468. ivalue = new torch._C.IValue(rhs.value, 'Double');
  13469. set_or_check_type(torch.FloatType.get());
  13470. break;
  13471. default:
  13472. throw new python.Error(`Unsupported enum value type '${rhs.type}'.`);
  13473. }
  13474. names_values.push([name, ivalue]);
  13475. }
  13476. if (!value_type) {
  13477. throw new python.Error('No enum values defined.');
  13478. }
  13479. const enum_type = torch.EnumType.create(qualified_name, value_type, names_values, this._cu);
  13480. this._cu.register_type(enum_type);
  13481. }
  13482. importNamedTuple(qualified_name, named_tuple_def) {
  13483. const type_parser = new torch._C.ScriptTypeParser(this);
  13484. const field_names = [];
  13485. const field_types = [];
  13486. const field_defaults = [];
  13487. for (const stmt of named_tuple_def.body) {
  13488. if (stmt instanceof ast.AnnAssign === false) {
  13489. throw new python.Error('Unexpected statement in NamedTuple body.');
  13490. }
  13491. const assign = stmt;
  13492. const target = this._cu.execution.identifier(stmt.target);
  13493. // const annotation = this._cu.execution.type(stmt.annotation);
  13494. const type = type_parser.parseTypeFromExpr(assign.annotation);
  13495. field_names.push(target);
  13496. // field_types.push(annotation);
  13497. field_types.push(type);
  13498. }
  13499. const tt = torch.TupleType.createNamed(qualified_name.qualifiedName(), field_names, field_types, field_defaults);
  13500. this._cu.register_type(tt);
  13501. }
  13502. importFunction(qualifier, def) {
  13503. const definitions = [def];
  13504. const resolvers = [this];
  13505. this._cu.define(new torch._C.QualifiedName(qualifier), /*properties=*/[], /*propResolvers=*/[], definitions, resolvers, null);
  13506. }
  13507. parseSourceIfNeeded(qualifier) {
  13508. if (!qualifier || this._loaded_sources.has(qualifier)) {
  13509. return;
  13510. }
  13511. this._loaded_sources.add(qualifier);
  13512. const src = this._source_loader(qualifier);
  13513. if (!src) {
  13514. return;
  13515. }
  13516. this._sources.set(src.filename(), src);
  13517. const p = new torch._C.Parser(src);
  13518. const L = p.parse();
  13519. this.parsePossibleVersionNumber(p);
  13520. for (const stmt of L.body) {
  13521. if (stmt instanceof ast.ClassDef) {
  13522. const name = `${qualifier}.${stmt.name}`;
  13523. this._to_be_defined.set(name, stmt);
  13524. } else if (stmt instanceof ast.FunctionDef) {
  13525. const name = `${qualifier}.${stmt.name}`;
  13526. this._to_be_defined.set(name, stmt);
  13527. }
  13528. }
  13529. }
  13530. parsePossibleVersionNumber(/* p */) {
  13531. }
  13532. parseImports(/* p */) {
  13533. }
  13534. attributeAssignmentSpecialHandlingHack(qualified_classname, assign) {
  13535. const replacements = new Map([
  13536. ['__torch__.torch.ao.nn.quantized.modules.linear.LinearPackedParams', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  13537. ['__torch__.torch.ao.nn.quantized.modules.linear.Linear', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  13538. ['__torch__.torch.ao.nn.quantized.dynamic.modules.linear.Linear', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  13539. ['__torch__.torch.ao.nn.quantized.modules.conv.Conv2d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv2dPackedParamsBase']],
  13540. ['__torch__.torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv2dPackedParamsBase']],
  13541. ['__torch__.torch.ao.nn.quantized.modules.conv.Conv3d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv3dPackedParamsBase']],
  13542. ['__torch__.torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU3d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv3dPackedParamsBase']],
  13543. ['__torch__.torch.nn.quantized.modules.linear.LinearPackedParams', ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]],
  13544. ["__torch__.torch.nn.quantized.modules.linear.Linear", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]],
  13545. ["__torch__.torch.nn.quantized.modules.conv.Conv2d", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.Conv2dPackedParamsBase"]],
  13546. ["__torch__.torch.nn.quantized.modules.conv.Conv3d", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.Conv3dPackedParamsBase"]],
  13547. ["__torch__.torch.nn.quantized.dynamic.modules.linear.Linear", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]]
  13548. ]);
  13549. const mangleRe = /\.___torch_mangle_\d+/g;
  13550. const demangled_classname = qualified_classname.qualifiedName().replace(mangleRe, '');
  13551. if (replacements.has(demangled_classname)) {
  13552. const lhs = assign.target;
  13553. if (!assign.annotation || assign.annotation instanceof ast.Name === false) {
  13554. return null;
  13555. }
  13556. const type = assign.annotation.id;
  13557. const [attr_name, expected_type, replacement_type] = replacements.get(demangled_classname);
  13558. if (lhs.id === attr_name && type === expected_type) {
  13559. const p = new torch._C.Parser(new torch._C.Source(replacement_type));
  13560. const typename_expr = p.parseExp();
  13561. return new ast.AnnAssign(lhs, typename_expr, assign.value, lhs instanceof ast.Name);
  13562. }
  13563. }
  13564. return null;
  13565. }
  13566. LEGACY_import_methods(mod, src) {
  13567. const self = new torch._C.SimpleSelf(mod.type());
  13568. const prefix = mod.type().name();
  13569. const p = new torch._C.Parser(src);
  13570. const L = p.parse();
  13571. this.parsePossibleVersionNumber(L);
  13572. this.parseImports(L);
  13573. const definitions = [];
  13574. const resolvers = [];
  13575. for (const def of L.body) {
  13576. if (def instanceof ast.FunctionDef) {
  13577. definitions.push(def);
  13578. resolvers.push(this);
  13579. }
  13580. }
  13581. this._cu.define(prefix, /*properties=*/[], /*propResolvers=*/[], definitions, resolvers, self);
  13582. }
  13583. findFunction(name) {
  13584. this.parseSourceIfNeeded(name.prefix());
  13585. const key = name.qualifiedName();
  13586. const it = this._to_be_defined.get(key);
  13587. if (it && it instanceof ast.FunctionDef) {
  13588. this._to_be_defined.delete(key);
  13589. this.importFunction(name.prefix(), it);
  13590. }
  13591. return this._cu.find_function(name);
  13592. }
  13593. });
  13594. this.registerType('torch._C.FunctionResolver', class extends torch._C.Resolver {
  13595. constructor(otherResolver, functionTable) {
  13596. super();
  13597. this._otherResolver = otherResolver;
  13598. this._functionTable = functionTable;
  13599. }
  13600. resolveValue(name, m, loc) {
  13601. const it = this._functionTable.get(name);
  13602. if (it) {
  13603. return new torch._C.FunctionValue(it);
  13604. }
  13605. return this._otherResolver.resolveValue(name, m, loc);
  13606. }
  13607. resolveType(name, loc) {
  13608. return this._otherResolver.resolveType(name, loc);
  13609. }
  13610. });
  13611. this.registerType('torch._C.SourceRangeDeserializer', class {
  13612. constructor(text_table) {
  13613. this.cached_sources = new Map();
  13614. this._text_table = text_table || [];
  13615. }
  13616. deserialize(iv) {
  13617. torch._C.TORCH_INTERNAL_ASSERT(iv.length === 3);
  13618. const [file, start, end] = iv;
  13619. const source = this.deserialize_source(file);
  13620. return new torch._C.SourceRange(source, start, end);
  13621. }
  13622. deserialize_source(iv) {
  13623. const tup = iv;
  13624. if (this.cached_sources.has(tup)) {
  13625. return this.cached_sources.get(tup);
  13626. }
  13627. let source = null;
  13628. const tup_elems = tup;
  13629. torch._C.TORCH_INTERNAL_ASSERT(tup_elems.length === 3);
  13630. if (this._text_table.length > 0) {
  13631. const [textIndex, fnameIndex, starting_line_no] = tup_elems;
  13632. torch._C.TORCH_CHECK(fnameIndex < this._text_table.length);
  13633. const filename = this._text_table[fnameIndex];
  13634. const pieces = [];
  13635. const strs = [];
  13636. for (const i of textIndex) {
  13637. pieces.push(this._text_table[i]);
  13638. strs.push(this._text_table[i]);
  13639. }
  13640. // const str_cord = new torch._C.StringCordView(pieces, strs);
  13641. source = new torch._C.Source(pieces.join(''), filename, starting_line_no);
  13642. } else {
  13643. const [text, filename, starting_line_no] = tup_elems;
  13644. source = new torch._C.Source(text, filename, starting_line_no);
  13645. }
  13646. this.cached_sources.set(tup, source);
  13647. return source;
  13648. }
  13649. });
  13650. this.registerType('torch._C.SourceRangeUnpickler', class {
  13651. });
  13652. this.registerType('torch._C.ConcreteSourceRangeUnpickler', class extends torch._C.SourceRangeUnpickler {
  13653. constructor (data) {
  13654. super();
  13655. this.data = data;
  13656. this.deserializer = null;
  13657. this.unpickled_records = null;
  13658. }
  13659. unpickle() {
  13660. if (this.unpickled_records) {
  13661. return;
  13662. }
  13663. const unpickler = new pickle.Unpickler(this.data);
  13664. const ivalues = unpickler.load();
  13665. torch._C.TORCH_CHECK(ivalues.length > 0);
  13666. this.unpickled_records = [];
  13667. let lines = null;
  13668. if (ivalues[0] === 'FORMAT_WITH_STRING_TABLE') {
  13669. this.deserializer = new torch._C.SourceRangeDeserializer(ivalues[1]);
  13670. lines = ivalues[2];
  13671. } else {
  13672. this.deserializer = new torch._C.SourceRangeDeserializer();
  13673. lines = ivalues;
  13674. }
  13675. for (const tup_elems of lines) {
  13676. const [offset, range] = tup_elems;
  13677. const source_range = this.deserializer.deserialize(range);
  13678. this.unpickled_records.push([offset, source_range]);
  13679. }
  13680. }
  13681. findSourceRangeThatGenerated(range) {
  13682. this.unpickle();
  13683. const start = range.start();
  13684. const records = this.unpickled_records;
  13685. for (let i = 0; i < records.length; i++) {
  13686. const [offset, target] = records[i];
  13687. const next = i < records.length - 1 ? records[i + 1][0] : range.source().size();
  13688. if (start >= offset && start < next) {
  13689. return target;
  13690. }
  13691. }
  13692. return null;
  13693. }
  13694. });
  13695. this.registerFunction('torch._C.qualifierToArchivePath', (qualifier, export_prefix) => {
  13696. return `${export_prefix}${qualifier.replace(/\./g, '/')}.py`;
  13697. });
  13698. this.registerFunction('torch._C.findSourceInArchiveFromQualifier', (reader, export_prefix, qualifier) =>{
  13699. const path = torch._C.qualifierToArchivePath(qualifier, export_prefix);
  13700. if (!reader.has_record(path)) {
  13701. return null;
  13702. }
  13703. const stream = reader.get_record(path);
  13704. let gen_ranges = null;
  13705. const debug_file = `${path}.debug_pkl`;
  13706. if (reader.has_record(debug_file)) {
  13707. const debug_stream = reader.get_record(debug_file);
  13708. gen_ranges = new torch._C.ConcreteSourceRangeUnpickler(debug_stream.peek());
  13709. }
  13710. return new torch._C.Source(stream.peek(), path, 1, gen_ranges);
  13711. });
  13712. this.registerType('torch._C.ScriptModuleDeserializer', class {
  13713. constructor(cu, reader, pickle_dir_prefix, tensor_dir_prefix, storage_context) {
  13714. this._compilation_unit = cu;
  13715. this._reader = reader;
  13716. this._storage_context = storage_context;
  13717. this._code_prefix = !pickle_dir_prefix && !tensor_dir_prefix ? 'code/' : '.data/ts_code/code/';
  13718. this._pickle_dir_prefix = pickle_dir_prefix || '';
  13719. this._tensor_dir_prefix = tensor_dir_prefix || '';
  13720. this._constant_table = [];
  13721. const SourceLoader = (qualifier) => {
  13722. return torch._C.findSourceInArchiveFromQualifier(this._reader, this._code_prefix, qualifier);
  13723. };
  13724. this._source_importer = new torch._C.SourceImporter(this._compilation_unit, this._constant_table, SourceLoader, reader.version());
  13725. }
  13726. deserialize() {
  13727. const execution = this._compilation_unit.execution;
  13728. const code_prefix = this._code_prefix;
  13729. for (const name of this._reader.get_all_records()) {
  13730. if (name.startsWith(code_prefix) && name.endsWith('.py')) {
  13731. const file = name.substring(code_prefix.length);
  13732. const stream = this._reader.get_record(name);
  13733. const buffer = stream.peek();
  13734. execution.add(file, buffer);
  13735. }
  13736. }
  13737. const torch = execution.import('torch');
  13738. execution.builtins.torch = torch;
  13739. execution.builtins.Tensor = torch.Tensor;
  13740. execution.builtins.ops = torch.ops;
  13741. execution.builtins.inf = torch.inf;
  13742. execution.builtins.CONSTANTS = {};
  13743. execution._resolver = this._source_importer;
  13744. if (this._reader.has_record('model.json')) {
  13745. return this.LEGACY_deserialize();
  13746. }
  13747. const constants = this.readArchive('constants');
  13748. for (let i = 0; i < constants.length; i++) {
  13749. let val = constants[i];
  13750. if (val && val.__class__ && val.__class__.__module__.startsWith('__torch__.torch.classes.')) {
  13751. const type = this._source_importer.resolveType(`${val.__class__.__module__}.${val.__class__.__name__}`);
  13752. const obj = torch.ScriptObject.create(type);
  13753. obj._ivalue = val;
  13754. val = obj;
  13755. }
  13756. execution.builtins.CONSTANTS[`c${i}`] = val;
  13757. this._constant_table.push(val);
  13758. }
  13759. const obj = this.readArchive('data');
  13760. const convertObject = (obj) => {
  13761. if (obj.__class__) {
  13762. const name = `${obj.__class__.__module__}.${obj.__class__.__name__}`;
  13763. const type = this._source_importer.loadType(new torch._C.QualifiedName(name));
  13764. const module = type.is_module() ? new torch.ScriptModule(type, this._compilation_unit) : new torch.ScriptObject(type);
  13765. for (let i = 0; i < type.numAttributes(); i++) {
  13766. const k = type.getAttributeName(i);
  13767. const t = type.getAttribute(i);
  13768. const v = obj[k];
  13769. if (t instanceof torch.ClassType) {
  13770. module.__setattr__(k, convertObject(v));
  13771. } else {
  13772. if (t instanceof torch.TensorType && v && v.__class__ && v instanceof torch.Tensor === false && v.__class__.__module__ === '__torch__.torch.classes.quantized') {
  13773. const name = `${v.__class__.__module__}.${v.__class__.__name__}`;
  13774. type._attributes[i].type = this._source_importer.resolveType(name);
  13775. }
  13776. module.__setattr__(k, obj[k]);
  13777. }
  13778. }
  13779. for (const [key, value] of Object.entries(Object.getPrototypeOf(obj))) {
  13780. if (value && value.__class__ === builtins.method) {
  13781. module[key] = value;
  13782. }
  13783. }
  13784. return module;
  13785. }
  13786. throw new python.Error('Module class not found.');
  13787. };
  13788. return convertObject(obj);
  13789. }
  13790. LEGACY_deserialize() {
  13791. // https://github.com/pytorch/pytorch/blob/5e69e11d098a2cfccc8a59377c431e9c71cab9a8/torch/csrc/jit/serialization/import_legacy.cpp#L88
  13792. const execution = this._compilation_unit.execution;
  13793. const caffe2 = execution.proto.caffe2;
  13794. const torch = execution.import('torch');
  13795. const stream = this._reader.get_record('model.json');
  13796. const buffer = stream.peek();
  13797. const decoder = new TextDecoder('utf-8');
  13798. const content = decoder.decode(buffer);
  13799. const obj = JSON.parse(content);
  13800. const model = execution.proto.torch.ModelDef.decodeJson(obj);
  13801. const tensorTypeMap = new Map([
  13802. [caffe2.TensorProto.DataType.FLOAT, 'Float'],
  13803. [caffe2.TensorProto.DataType.FLOAT16, 'Half'],
  13804. [caffe2.TensorProto.DataType.DOUBLE, 'Double'],
  13805. [caffe2.TensorProto.DataType.INT8, 'Char'],
  13806. [caffe2.TensorProto.DataType.INT32, 'Int'],
  13807. [caffe2.TensorProto.DataType.INT64, 'Long']
  13808. ]);
  13809. const tensor_table = (model.tensors || []).map((constant) => {
  13810. const key = constant.data.key;
  13811. if (!tensorTypeMap.has(constant.data_type)) {
  13812. throw new python.Error(`Unsupported tensor data type '${constant.data_type}'.`);
  13813. }
  13814. const type = tensorTypeMap.get(constant.data_type);
  13815. const shape = constant.dims ? constant.dims.map((dim) => parseInt(dim, 10)) : null;
  13816. const strides = constant.strides ? constant.strides.map((dim) => parseInt(dim, 10)) : null;
  13817. const storage_type = execution.resolve(`torch.${type}Storage`);
  13818. const size = (shape || []).reduce((a, b) => a * b, 1);
  13819. const offset = parseInt(constant.offset, 10) || 0;
  13820. const storage = new storage_type(size);
  13821. const itemsize = storage.dtype.itemsize();
  13822. const stream = this._reader.get_record(key);
  13823. if (stream) {
  13824. const buffer = stream.peek();
  13825. const length = size * itemsize;
  13826. const data = buffer.slice(offset, offset + length);
  13827. storage._set_cdata(data);
  13828. }
  13829. const tensor = torch._utils._rebuild_tensor(storage, 0, shape, strides);
  13830. tensor.name = key;
  13831. return tensor;
  13832. });
  13833. execution.builtins.CONSTANTS = {};
  13834. for (let i = 0; i < tensor_table.length; i++) {
  13835. execution.builtins.CONSTANTS[`c${i}`] = tensor_table[i];
  13836. }
  13837. const attributes = [];
  13838. if (this._reader.has_record('attributes.pkl')) {
  13839. const stream = this._reader.get_record('attributes.pkl');
  13840. const buffer = stream.peek();
  13841. const unpickler = new pickle.Unpickler(buffer);
  13842. const obj = unpickler.load();
  13843. attributes.push(...obj);
  13844. }
  13845. this._LEGACY_moduleStack = ['__torch__'];
  13846. const module_def = model.main_module;
  13847. for (const tensor of tensor_table) {
  13848. this._constant_table.push(tensor);
  13849. }
  13850. return this.LEGACY_convertModule(module_def);
  13851. }
  13852. LEGACY_convertModule(module_def) {
  13853. const atoms = new torch._C.QualifiedName(module_def.name).atoms();
  13854. const numPushed = atoms.length;
  13855. for (const atom of atoms) {
  13856. const sanitized = /^\d+$/.test(atom) ? `_${atom}` : atom;
  13857. this._LEGACY_moduleStack.push(sanitized);
  13858. }
  13859. const qn = new torch._C.QualifiedName(this._LEGACY_moduleStack);
  13860. const module = new torch.ScriptModule(qn, this._compilation_unit);
  13861. for (const sub_def of module_def.submodules || []) {
  13862. const submodule = this.LEGACY_convertModule(sub_def);
  13863. module.register_module(sub_def.name, submodule);
  13864. }
  13865. for (const param_def of module_def.parameters || []) {
  13866. const tensor = this._constant_table[Number(param_def.tensor_id)];
  13867. if (param_def.isBuffer) {
  13868. module.register_buffer(param_def.name, tensor);
  13869. } else {
  13870. module.register_parameter(param_def.name, tensor, false);
  13871. }
  13872. }
  13873. // const typeParser = new torch._C.ScriptTypeParser(this._source_importer);
  13874. for (const attr_def of module_def.attributes || []) {
  13875. if (module.hasattr(attr_def.name)) {
  13876. continue;
  13877. }
  13878. throw new python.Error('Not implemented.');
  13879. // IValue ivalue;
  13880. // if (attr_def.id() >= 0) {
  13881. // ivalue = LEGACY_pickled_ivalues_.at(attr_def.id());
  13882. // }
  13883. // module.register_attribute(attr_def.name, typeParser.parseType(attr_def.type), ivalue);
  13884. }
  13885. if (module_def.torchscript_arena) {
  13886. const key = module_def.torchscript_arena.key;
  13887. const file = key.substring('code/'.length);
  13888. const name = file.replace(/\.py$/, '').split('/').join('.');
  13889. const code = execution.import(name);
  13890. if (code.forward.__class__ === execution.builtins.function) {
  13891. module.forward = code.forward;
  13892. }
  13893. }
  13894. // let gen_ranges = null;
  13895. if (module_def.torchscript_debug_arena) {
  13896. throw new python.Error('Not implemented.');
  13897. //const [data, size] = reader_->getRecord(module_def.torchscript_debug_arena().key());
  13898. //gen_ranges = std::make_shared<ConcreteSourceRangeUnpickler>(std::move(data), size);
  13899. }
  13900. if (module_def.torchscript_arena) {
  13901. const filename = module_def.torchscript_arena.key;
  13902. const stream = this._reader.get_record(filename);
  13903. const data = stream.peek();
  13904. const src = new torch._C.Source(data, filename);
  13905. this._source_importer.LEGACY_import_methods(module, src);
  13906. }
  13907. if (module_def.get_state_attribute_id) {
  13908. throw new python.Error('Not implemented.');
  13909. // LEGACY_moduleSetState(module, LEGACY_pickled_ivalues_.at(module_def.get_state_attribute_id()));
  13910. }
  13911. /*
  13912. const module_type = module._ivalue().type();
  13913. const N = module_type.numAttributes();
  13914. for (let i = 0; i < N; ++i) {
  13915. const v = module._ivalue().getSlot(i);
  13916. if (module_type.getAttribute(i) instanceof torch.OptionalType === false) {
  13917. torch._C.TORCH_CHECK(!v.isNone());
  13918. }
  13919. }
  13920. */
  13921. for (let i = 0; i < numPushed; i++) {
  13922. this._LEGACY_moduleStack.pop();
  13923. }
  13924. return module;
  13925. }
  13926. readArchive(archive_name) {
  13927. const type_resolver = (qn) => {
  13928. const cls = this._source_importer.loadType(qn);
  13929. return cls;
  13930. };
  13931. const ObjLoaderFunc = (/* type, ivalue */) => {
  13932. };
  13933. return this.readArchiveAndTensors(archive_name, this._pickle_dir_prefix, this._tensor_dir_prefix, type_resolver, ObjLoaderFunc, this._device, this._reader, null, this._storage_context);
  13934. }
  13935. readArchiveAndTensors(archive_name, pickle_prefix, tensor_prefix, type_resolver, obj_loader, device, stream_reader, type_parser, storage_context) {
  13936. const picklename = `${pickle_prefix + archive_name}.pkl`;
  13937. const stream = stream_reader.get_record(picklename);
  13938. if (!stream) {
  13939. throw new python.Error(`File '${picklename}' is not found.`);
  13940. }
  13941. const buffer = stream.peek();
  13942. const tensor_dir_path = tensor_prefix ? tensor_prefix : `${archive_name}/`;
  13943. const read_record = (name) => {
  13944. const stream = stream_reader.get_record(tensor_dir_path + name);
  13945. return stream.length <= 0x40000 ? stream.peek() : stream;
  13946. };
  13947. const execution = this._compilation_unit.execution;
  13948. const pickle = execution.__import__('pickle');
  13949. const Unpickler = class extends pickle.Unpickler {
  13950. find_class(module, name) {
  13951. return super.find_class(module, name);
  13952. }
  13953. };
  13954. const unpickler = new Unpickler(buffer);
  13955. unpickler.persistent_load = (saved_id) => {
  13956. if (saved_id[0] !== 'storage') {
  13957. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  13958. }
  13959. const [, storage_type, key, , size] = saved_id;
  13960. if (storage_context && storage_context.has_storage(key)) {
  13961. return storage_context.get_storage(key);
  13962. }
  13963. const storage = new storage_type(size);
  13964. if (!storage._set_cdata) {
  13965. throw new python.Error(`'${storage_type.__name__}._set_cdata' is not a function.`);
  13966. }
  13967. const storage_ptr = read_record(key);
  13968. storage._set_cdata(storage_ptr);
  13969. if (storage_context) {
  13970. storage_context.add_storage(key);
  13971. }
  13972. return storage;
  13973. };
  13974. return unpickler.load();
  13975. }
  13976. });
  13977. this.registerType('torch._C.WithInsertPoint', class {
  13978. constructor(...args) {
  13979. let n = null;
  13980. if (args.length === 1 && args[0] instanceof torch.Block) {
  13981. const [b] = args;
  13982. n = b.return_node();
  13983. } else if (args.length === 1 && args[0] instanceof torch.Node) {
  13984. [n] = args;
  13985. } else {
  13986. throw new python.Error('Invalid arguments.');
  13987. }
  13988. this._prev = n.owningGraph().insertPoint();
  13989. n.owningGraph().setInsertPoint(n);
  13990. }
  13991. dispose() {
  13992. this._prev.owningGraph().setInsertPoint(this._prev);
  13993. }
  13994. });
  13995. this.registerType('torch._C.Environment', class {
  13996. constructor(method, resolver, b, next) {
  13997. this.method = method;
  13998. this.resolver = resolver;
  13999. this.b = b;
  14000. this.next = next;
  14001. this.value_table = new Map();
  14002. this.type_table = new Map();
  14003. this.error_messages = new Map();
  14004. }
  14005. setVariableTypeError(name, msg) {
  14006. /* eslint-disable consistent-this */
  14007. let runner = this;
  14008. /* eslint-enable consistent-this */
  14009. while (runner.next) {
  14010. runner = runner.next;
  14011. }
  14012. runner.error_messages.set(name, msg);
  14013. }
  14014. insertLoad(name, type) {
  14015. const g = this.b.owningGraph();
  14016. const load = g.insertNode(g.createLoad(name, type));
  14017. if (torch._C.meaningfulName(name)) {
  14018. load.output().setDebugName(name);
  14019. }
  14020. return new torch._C.SimpleValue(load.output());
  14021. }
  14022. insertStore(name, loc, v, type) {
  14023. const g = this.b.owningGraph();
  14024. g.insertNode(g.createStore(name, v)).setSourceRange(loc);
  14025. this.type_table.set(name, type);
  14026. }
  14027. findInThisFrame(name) {
  14028. if (this.value_table.has(name)) {
  14029. return this.value_table.get(name);
  14030. }
  14031. if (this.type_table.has(name)) {
  14032. return this.insertLoad(name, this.type_table.get(name));
  14033. }
  14034. return null;
  14035. }
  14036. findInParentFrame(name) {
  14037. return this.next ? this.next.findInAnyFrame(name) : null;
  14038. }
  14039. setType(name, type) {
  14040. this.type_table.set(name, type);
  14041. }
  14042. findInAnyFrame(name) {
  14043. /* eslint-disable consistent-this */
  14044. const self = this;
  14045. /* eslint-enable consistent-this */
  14046. for (let runner = self; runner; runner = runner.next) {
  14047. const r = runner.findInThisFrame(name);
  14048. if (r) {
  14049. return r;
  14050. }
  14051. }
  14052. return null;
  14053. }
  14054. block() {
  14055. return this.b;
  14056. }
  14057. setVar(loc, name, value) {
  14058. this.setSugaredVar(loc, name, new torch._C.SimpleValue(value), null);
  14059. }
  14060. setSugaredVar(loc, name, value, annotated_type) {
  14061. let as_simple_value = torch._C.asSimple(value);
  14062. if (as_simple_value && !as_simple_value.hasDebugName() && torch._C.meaningfulName(name) && as_simple_value.node().owningBlock() === this.block()) {
  14063. as_simple_value.setDebugName(name);
  14064. }
  14065. const parent = this.findInParentFrame(name);
  14066. if (parent) {
  14067. if (annotated_type) {
  14068. throw new python.Error('Type already defined in an outer block.');
  14069. }
  14070. if (!as_simple_value) {
  14071. throw new python.Error('Only reassignments to first-class values are allowed.');
  14072. }
  14073. const simple_parent = torch._C.asSimple(parent);
  14074. if (!simple_parent) {
  14075. throw new python.Error('Only reassignments to first-class values are allowed.');
  14076. }
  14077. const parent_type = torch._C.unshapedType(simple_parent.type());
  14078. as_simple_value = torch._C.tryConvertToType(loc, this.b.owningGraph(), parent_type, as_simple_value, /*allow_conversions=*/true);
  14079. if (!as_simple_value.type().isSubtypeOf(parent_type)) {
  14080. throw new python.Error('Incompatible types.');
  14081. }
  14082. }
  14083. if (as_simple_value) {
  14084. if (annotated_type && !as_simple_value.type().isSubtypeOf(annotated_type)) {
  14085. throw new python.Error('Invalid type.');
  14086. }
  14087. const value_store_type = annotated_type ? annotated_type : as_simple_value.type();
  14088. this.insertStore(name, loc, as_simple_value, value_store_type);
  14089. } else {
  14090. this.value_table.set(name, value);
  14091. }
  14092. }
  14093. getSugaredVar(ident, range, required) {
  14094. required = required || true;
  14095. let retval = this.findInAnyFrame(ident);
  14096. if (!retval) {
  14097. torch._C.Environment.globals = torch._C.Environment.globals || new Map([
  14098. ['print', new torch._C.PrintValue()],
  14099. ['tuple', torch._C.SpecialFormValue.create('prim::TupleConstruct')],
  14100. ['float', new torch._C.MagicMethod('__float__', new torch._C.CastValue(torch.FloatType.get(), 'aten::Float'))],
  14101. ['int', new torch._C.MagicMethod('__int__', new torch._C.CastValue(torch.IntType.get(), 'aten::Int'))],
  14102. ['bool', new torch._C.MagicMethod('__bool__', new torch._C.CastValue(torch.BoolType.get(), 'aten::Bool'))],
  14103. ['str', new torch._C.MagicMethod('__str__', new torch._C.CastValue(torch.StringType.get(), 'aten::str'))],
  14104. ['getattr', torch._C.SpecialFormValue.create('prim::GetAttr')],
  14105. ['hasattr', torch._C.SpecialFormValue.create('prim::HasAttr')],
  14106. ['isinstance', torch._C.SpecialFormValue.create('prim::isinstance')],
  14107. ['range', torch._C.SpecialFormValue.create('prim::range')],
  14108. ['sorted', new torch._C.BuiltinFunction('aten::sorted', null)],
  14109. ]);
  14110. if (torch._C.Environment.globals.has(ident)) {
  14111. retval = torch._C.Environment.globals.get(ident);
  14112. }
  14113. }
  14114. if (!retval) {
  14115. const type = this.resolver.resolveType(ident, range);
  14116. if (type instanceof torch.TupleType) {
  14117. retval = new torch.jit.NamedTupleConstructor(type);
  14118. }
  14119. }
  14120. if (!retval) {
  14121. retval = this.resolver.resolveValue(ident, this.method, range);
  14122. }
  14123. if (!retval) {
  14124. const type = this.resolver.resolveType(ident, range);
  14125. if (type instanceof torch.ClassType) {
  14126. retval = new torch.jit.ClassValue(type);
  14127. }
  14128. }
  14129. if (!retval && required) {
  14130. throw new python.Error(`The name '${ident}' is not defined.`);
  14131. }
  14132. return retval;
  14133. }
  14134. getVar(ident, range) {
  14135. return this.getSugaredVar(ident, range).asValue(range, this.method);
  14136. }
  14137. definedVariables() {
  14138. return Array.from(this.type_table.keys());
  14139. }
  14140. });
  14141. this.registerType('torch._C.Refinement', class {
  14142. constructor(identifier, type) {
  14143. this._identifier = identifier;
  14144. this._type = type;
  14145. }
  14146. identifier() {
  14147. return this._identifier;
  14148. }
  14149. type() {
  14150. return this._type;
  14151. }
  14152. });
  14153. this.registerType('torch._C.RefinementSet', class {
  14154. constructor(...args) {
  14155. if (args.length === 1 && args[0] instanceof torch._C.Refinement) {
  14156. this._true_refinements = [args[0]];
  14157. this._false_refinements = [];
  14158. } else if (args.length === 2 && args[0] instanceof torch._C.Refinement && args[1] instanceof torch._C.Refinement) {
  14159. this._true_refinements = [args[0]];
  14160. this._false_refinements = [args[1]];
  14161. } else if (args.length === 2 && Array.isArray(args[0]) && Array.isArray(args[1])) {
  14162. [this._true_refinements, this._false_refinements] = args;
  14163. } else {
  14164. throw new python.Error('Not implemented.');
  14165. }
  14166. }
  14167. Not() {
  14168. return new torch._C.RefinementSet(this._false_refinements, this._true_refinements);
  14169. }
  14170. activeRefinements() {
  14171. return this._true_refinements;
  14172. }
  14173. });
  14174. this.registerFunction('torch._C.CondValue', class {
  14175. constructor(...args) {
  14176. if (args.length === 3) {
  14177. [this._value, this._refinements, this._static_if] = args;
  14178. } else if (args.length === 4) {
  14179. const [g, loc, static_value, refinements] = args;
  14180. this._value = g.insertConstant(static_value, loc);
  14181. this._refinements = refinements;
  14182. this._static_if = static_value;
  14183. } else {
  14184. throw new python.Error('Invalid number of arguments.');
  14185. }
  14186. }
  14187. value() {
  14188. return this._value;
  14189. }
  14190. staticIf() {
  14191. return this._static_if;
  14192. }
  14193. refinements() {
  14194. return this._refinements;
  14195. }
  14196. });
  14197. this.registerFunction('torch._C.asSimple', (value) => {
  14198. if (value instanceof torch._C.SimpleValue) {
  14199. return value.getValue();
  14200. }
  14201. return null;
  14202. });
  14203. this.registerFunction('torch._C.isNumber', (str) => {
  14204. return /^[0-9]+$/.test(str);
  14205. });
  14206. this.registerFunction('torch._C.normalizeAttrName', (field) => {
  14207. if (torch._C.isNumber(field)) {
  14208. return `_${field}`;
  14209. }
  14210. return field;
  14211. });
  14212. this.registerFunction('torch._C.meaningfulName', (name) => {
  14213. if (name.length === 0) {
  14214. return false;
  14215. }
  14216. if (name[0] === '$') {
  14217. return false;
  14218. }
  14219. if (name[0] !== '_') {
  14220. return true;
  14221. }
  14222. return !/\d+/.test(name.slice(1));
  14223. });
  14224. this.registerFunction('torch._C.materializeConstant', (val, graph, r, map) => {
  14225. const key = `${val.value}:${val.tag}`;
  14226. const existing_constant = map.get(key);
  14227. if (existing_constant) {
  14228. return existing_constant;
  14229. }
  14230. const guard = new torch._C.WithInsertPoint(graph.block().nodes().front());
  14231. const new_constant = graph.insertConstant(val, r);
  14232. map.set(key, new_constant);
  14233. guard.dispose();
  14234. return new_constant;
  14235. });
  14236. this.registerFunction('torch._C.getFullSchemaName', (schema) => {
  14237. if (schema.overload_name) {
  14238. return `${schema.name}.${schema.overload_name}`;
  14239. }
  14240. return schema.name;
  14241. });
  14242. this.registerFunction('torch._C.insertGraph', (g, callee, inputs, value_map) => {
  14243. const value_map_func = (v) => value_map.get(v);
  14244. torch._C.AT_ASSERT(callee.inputs().length === inputs.length);
  14245. for (let i = 0; i < inputs.length; i++) {
  14246. value_map.set(callee.inputs()[i], inputs[i]);
  14247. }
  14248. for (const node of callee.nodes()) {
  14249. const new_node = g.insertNode(g.createClone(node, value_map_func));
  14250. for (let i = 0; i < node.outputs().length; i++) {
  14251. value_map.set(node.outputs()[i], new_node.outputs()[i]);
  14252. }
  14253. }
  14254. const outputs = [];
  14255. for (const output of callee.outputs()) {
  14256. outputs.push(value_map_func(output));
  14257. }
  14258. return outputs;
  14259. });
  14260. this.registerType('TemplateEnv', class {
  14261. });
  14262. this.registerType('torch._C.BuiltinFunctionRegistry', class {
  14263. constructor() {
  14264. this.state = 'UNINITIALIZED';
  14265. this._builtins_by_name = new Map();
  14266. }
  14267. getAllBuiltinFunctionsFor(name) {
  14268. if (this.state === 'UNINITIALIZED') {
  14269. this.loadBuiltinFunctions();
  14270. this.state = 'INITIALIZED';
  14271. }
  14272. if (!this._builtins_by_name.has(name)) {
  14273. return [];
  14274. }
  14275. return this._builtins_by_name.get(name);
  14276. }
  14277. loadBuiltinFunctions() {
  14278. /*
  14279. for (const scalar of ['float', 'int', 'complex']) {
  14280. const env = new torch.C.TemplateEnv();
  14281. env.s('Scalar', scalar);
  14282. this.loadSource(scalar_operators_source.format(env), 'aten');
  14283. }
  14284. for (const scalar of ['float', 'int']) {
  14285. const env = new torch.C.TemplateEnv();
  14286. env.s('Scalar', scalar);
  14287. loadSource(scalar_operators_no_complex_source.format(env), 'aten');
  14288. }
  14289. using str_pair = std::pair<std::string, std::string>;
  14290. const std::vector<str_pair> name_len = {
  14291. str_pair('single', '1'),
  14292. str_pair('pair', '2'),
  14293. str_pair('triple', '3'),
  14294. str_pair('quadruple', '4'),
  14295. };
  14296. for (const auto scalar : {'float', 'int'}) {
  14297. for (const auto& pair : name_len) {
  14298. const env = new torch.C.TemplateEnv();
  14299. env.s('Scalar', scalar);
  14300. env.s('name', pair.first);
  14301. env.s('Length', pair.second);
  14302. this.loadSource(_ntuple_ops.format(env), 'aten');
  14303. }
  14304. }
  14305. for (auto rhs : {'number', 'Tensor'}) {
  14306. at::jit::TemplateEnv env;
  14307. env.s('Rhs_Type', rhs);
  14308. this.loadSource(floordiv.format(env), 'aten');
  14309. }
  14310. this.loadSource(aten_ops, 'aten');
  14311. this.loadSource(aten_ops_additional, 'aten');
  14312. this.loadSource(tensor_properties, 'prim');
  14313. */
  14314. }
  14315. loadSource(/* source, the_namespace */) {
  14316. }
  14317. });
  14318. this.registerFunction('torch._C.getAllBuiltinFunctionsFor', (name) => {
  14319. torch._C.registry = torch._C.registry || new torch._C.BuiltinFunctionRegistry();
  14320. return torch._C.registry.getAllBuiltinFunctionsFor(name);
  14321. });
  14322. this.registerFunction('torch._C.get_operator_version_map', () => {
  14323. return new Map();
  14324. });
  14325. this.registerFunction('torch._C.varargsCanBeUsedAsList', (schema, arg_index, arg) => {
  14326. const is_last_argument = arg_index + 1 === schema.arguments.length || schema.arguments[arg_index + 1].kwarg_only;
  14327. let arg_type = arg.type;
  14328. if (arg_type instanceof torch._C.DynamicType) {
  14329. arg_type = arg_type.fallback();
  14330. }
  14331. const argument_is_list = arg_type instanceof torch.ListType;
  14332. const typevar_list = argument_is_list && arg_type.getElementType() instanceof torch._C.VarType;
  14333. const arg_is_broadcasting_list = arg.N > 0;
  14334. return is_last_argument && argument_is_list && !arg_is_broadcasting_list && !typevar_list;
  14335. });
  14336. this.registerFunction('torch._C.isBlockListedSchema', (schema) => {
  14337. if ((schema.name === 'aten::view' && schema.overload_name === 'dtype') ||
  14338. (schema.name === 'aten::max' && schema.overload_name === 'unary_out') ||
  14339. (schema.name === 'aten::min' && schema.overload_name === 'unary_out')) {
  14340. return true;
  14341. }
  14342. return false;
  14343. });
  14344. this.registerFunction('torch._C.unwrapOptional', (opt_type) => {
  14345. if (opt_type instanceof torch._C.DynamicType) {
  14346. return torch._C.unwrapOptional(opt_type.fallback());
  14347. }
  14348. if (opt_type instanceof torch.OptionalType) {
  14349. return opt_type.getElementType();
  14350. }
  14351. return opt_type;
  14352. });
  14353. this.registerFunction('torch._C.loadPossibleHistoricOps', (name, version) => {
  14354. const possibleSchemas = [];
  14355. if (version === undefined) {
  14356. return possibleSchemas;
  14357. }
  14358. for (const entry of torch._C.get_operator_version_map()) {
  14359. const old_symbol_name = entry.first;
  14360. const base_name = old_symbol_name.substring(0, old_symbol_name.find('.'));
  14361. if (base_name === name) {
  14362. const possibleUpgrader = torch._C.findUpgrader(entry.second, version.value());
  14363. if (possibleUpgrader.has_value()) {
  14364. possibleSchemas.push_back(possibleUpgrader.value().old_schema);
  14365. }
  14366. }
  14367. }
  14368. return possibleSchemas;
  14369. });
  14370. this.registerFunction('torch._C.isOpCurrentBasedOnUpgraderEntries', (upgraders_for_schema, current_version) => {
  14371. const latest_update = upgraders_for_schema[upgraders_for_schema.length - 1].bumped_at_version;
  14372. return current_version < latest_update;
  14373. });
  14374. this.registerFunction('torch._C.isOpSymbolCurrent', (name, current_version) => {
  14375. const it = torch._C.get_operator_version_map().get(name);
  14376. if (it) {
  14377. return torch._C.isOpCurrentBasedOnUpgraderEntries(it, current_version);
  14378. }
  14379. return true;
  14380. });
  14381. this.registerFunction('torch._C.packOutputs', (g, values, field_names) => {
  14382. if (values.length === 1) {
  14383. return values[0];
  14384. }
  14385. let named_tuple = null;
  14386. if (field_names) {
  14387. const types = values.map((v) => v.type());
  14388. named_tuple = torch.TupleType.createNamed(null, field_names.value(), types);
  14389. }
  14390. return g.insertNode(g.createTuple(values, named_tuple)).output();
  14391. });
  14392. this.registerFunction('torch._C.isIntOrFloatUsedAsList', (value, arg) => {
  14393. const v_type = value.type();
  14394. if (v_type !== torch.FloatType.get() && v_type !== torch.IntType.get()) {
  14395. return false;
  14396. }
  14397. const arg_type = torch._C.unwrapOptional(arg.type);
  14398. return arg_type instanceof torch.ListType && arg_type.getElementType() === v_type && arg.N;
  14399. });
  14400. this.registerFunction('torch._C.convertibleToList', (type, list_type_) => {
  14401. const list_type = list_type_;
  14402. if (list_type instanceof torch.ListType === false) {
  14403. return false;
  14404. }
  14405. if (type.isSubtypeOf(list_type_)) {
  14406. return true;
  14407. }
  14408. if (type instanceof torch.TupleType) {
  14409. return type.elements().every((t) => t.isSubtypeOf(list_type.getElementType()));
  14410. }
  14411. return false;
  14412. });
  14413. this.registerFunction('torch._C.findInputWithName', (name, kwargs, is_aten) => {
  14414. for (let i = 0; i < kwargs.length; i++) {
  14415. if (is_aten && name === 'self' && kwargs[i].name() === 'input') {
  14416. return i;
  14417. }
  14418. if (kwargs[i].name() === name) {
  14419. return i;
  14420. }
  14421. }
  14422. return null;
  14423. });
  14424. this.registerFunction('torch._C.tryCreateList', (elem_type, graph, loc, varargs, failure_messages, err, convert_tensor_to_num, type_env) => {
  14425. const elem_arg = new torch.Argument('<varargs>', elem_type);
  14426. const list_elements = [];
  14427. for (const named_value of varargs) {
  14428. const matched_value = torch._C.tryMatchArgument(/*arg=*/elem_arg, graph, loc, named_value, failure_messages, err, /*allow_conversions=*/convert_tensor_to_num, type_env);
  14429. if (!matched_value) {
  14430. return null;
  14431. }
  14432. list_elements.push(matched_value);
  14433. }
  14434. return graph.insertNode(graph.createList(elem_type, list_elements)).output();
  14435. });
  14436. this.registerType('torch._C.MatchTypeReturn', class {
  14437. constructor(reason) {
  14438. this._reason = reason;
  14439. }
  14440. static Success() {
  14441. return new torch._C.MatchTypeReturn(null);
  14442. }
  14443. success() {
  14444. return this._reason === null;
  14445. }
  14446. });
  14447. this.registerFunction('torch._C.matchTypeVariables', (formal, actual, type_env) => {
  14448. if (!formal.hasFreeVariables()) {
  14449. if (formal instanceof torch._C.DynamicType) {
  14450. return torch._C.matchTypeVariables(formal.fallback(), actual, type_env);
  14451. }
  14452. return torch._C.MatchTypeReturn.Success();
  14453. }
  14454. if (formal instanceof torch._C.VarType) {
  14455. const it = type_env.has(formal.name()) ? type_env.get(formal.name()) : null;
  14456. if (it === null) {
  14457. type_env.set(formal.name(), actual);
  14458. return torch._C.MatchTypeReturn.Success();
  14459. } else if (torch._C.unifyTypes(it, actual)) {
  14460. return torch._C.MatchTypeReturn.Success();
  14461. }
  14462. return new torch._C.MatchTypeReturn('Cannot match var.');
  14463. } else if (formal instanceof torch.ListType) {
  14464. if (actual instanceof torch.ListType) {
  14465. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14466. if (!innerMatch.success()) {
  14467. return innerMatch;
  14468. }
  14469. return torch._C.MatchTypeReturn.Success();
  14470. } else if (actual instanceof torch.TupleType) {
  14471. const maybe_tuple_unified = torch._C.unifyTypeList(actual.elements(), '');
  14472. if (maybe_tuple_unified) {
  14473. return torch._C.matchTypeVariables(formal.getElementType(), maybe_tuple_unified, type_env);
  14474. }
  14475. }
  14476. return new torch._C.MatchTypeReturn('Cannot match list.');
  14477. } else if (formal instanceof torch.TupleType) {
  14478. if (actual instanceof torch.TupleType) {
  14479. if (formal.elements().length !== actual.elements().length) {
  14480. return torch._C.MatchTypeReturn('Cannot match tuples of mismatched size.');
  14481. }
  14482. for (let i = 0; i < formal.elements().length; i++) {
  14483. const result = torch._C.matchTypeVariables(formal.elements()[i], actual.elements()[i], type_env);
  14484. if (!result.success()) {
  14485. return result;
  14486. }
  14487. }
  14488. return torch._C.MatchTypeReturn.Success();
  14489. }
  14490. return new torch._C.MatchTypeReturn('Cannot match tuple.');
  14491. } else if (formal instanceof torch.FutureType) {
  14492. if (actual instanceof torch.FutureType) {
  14493. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14494. if (!innerMatch.success()) {
  14495. return innerMatch;
  14496. }
  14497. return torch._C.MatchTypeReturn.Success();
  14498. }
  14499. return new torch._C.MatchTypeReturn('Cannot match future.');
  14500. } else if (formal instanceof torch.AwaitType) {
  14501. if (actual instanceof torch.AwaitType) {
  14502. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14503. if (!innerMatch.success()) {
  14504. return innerMatch;
  14505. }
  14506. return torch._C.MatchTypeReturn.Success();
  14507. }
  14508. return new torch._C.MatchTypeReturn('Cannot match await.');
  14509. } else if (formal instanceof torch.RRefType) {
  14510. if (actual instanceof torch.RRefType) {
  14511. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14512. if (!innerMatch.success()) {
  14513. return innerMatch;
  14514. }
  14515. return torch._C.MatchTypeReturn.Success();
  14516. }
  14517. return new torch._C.MatchTypeReturn('Cannot match rref.');
  14518. } else if (formal instanceof torch.OptionalType) {
  14519. if (actual instanceof torch.OptionalType) {
  14520. const optionedMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14521. if (!optionedMatch.success()) {
  14522. return optionedMatch;
  14523. }
  14524. } else if (!actual.isSubtypeOf(torch.NoneType.get())) {
  14525. return torch._C.matchTypeVariables(formal.getElementType(), actual, type_env);
  14526. }
  14527. return torch._C.MatchTypeReturn.Success();
  14528. } else if (formal instanceof torch.DictType) {
  14529. if (actual instanceof torch.DictType) {
  14530. const key_match = torch._C.matchTypeVariables(formal.getKeyType(), actual.getKeyType(), type_env);
  14531. if (!key_match.success()) {
  14532. return key_match;
  14533. }
  14534. const value_match = torch._C.matchTypeVariables(formal.getValueType(), actual.getValueType(), type_env);
  14535. if (!value_match.success()) {
  14536. return value_match;
  14537. }
  14538. return torch._C.MatchTypeReturn.Success();
  14539. }
  14540. return new torch._C.MatchTypeReturn('Cannot match dict.');
  14541. }
  14542. throw new python.Error('Unhandled free variable container.');
  14543. });
  14544. this.registerFunction('torch._C.tryMatchArgument', (arg, graph, loc, named_value, failure_messages, err, allow_conversions, type_env) => {
  14545. let value = named_value.value(graph);
  14546. if (torch._C.isIntOrFloatUsedAsList(value, arg)) {
  14547. const repeated = Array(arg.N).fill(value);
  14548. value = graph.insertNode(graph.createList(value.type(), repeated)).output();
  14549. }
  14550. const matched = torch._C.matchTypeVariables(arg.type, value.type(), type_env);
  14551. if (!matched.success()) {
  14552. if (failure_messages) {
  14553. throw new python.Error(`Could not match type ${value.type().repr_str()} to ${arg.type().repr_str()} in argument '${arg.name()}'.`);
  14554. }
  14555. return null;
  14556. }
  14557. const concrete_type = torch._C.tryEvalTypeVariables(arg.type, type_env);
  14558. if (!concrete_type) {
  14559. if (failure_messages) {
  14560. throw new python.Error(`Could not infer type for argument '${arg.name}'.`);
  14561. }
  14562. return null;
  14563. }
  14564. value = torch._C.tryConvertToType(loc, graph, concrete_type, value, allow_conversions);
  14565. if (!value.type().isSubtypeOf(concrete_type)) {
  14566. if (failure_messages) {
  14567. throw new python.Error(`Could not match type in argument '${arg.name()}'.`);
  14568. }
  14569. return null;
  14570. }
  14571. return value;
  14572. });
  14573. this.registerFunction('torch._C.tryConvertToType', (loc, graph, concrete_type, value, allow_conversions) => {
  14574. if (concrete_type instanceof torch.OptionalType) {
  14575. const op = concrete_type;
  14576. if (value.type() instanceof torch.OptionalType === false && !value.type().isSubtypeOf(torch.NoneType.get())) {
  14577. return torch._C.tryConvertToType(loc, graph, op.getElementType(), value, allow_conversions);
  14578. }
  14579. }
  14580. if (value.node().kind() === 'prim::EmptyListLiteral' && concrete_type instanceof torch.ListType) {
  14581. value = graph.insertNode(graph.createList(concrete_type.getElementType(), [])).output();
  14582. }
  14583. if (value.type() instanceof torch.TupleType) {
  14584. const value_tuple = value.type();
  14585. if (torch._C.convertibleToList(value.type(), torch._C.unwrapOptional(concrete_type))) {
  14586. const unpacked = torch._C.createTupleUnpack(value);
  14587. const elem_type = torch._C.unwrapOptional(concrete_type).expect(torch.ListType).getElementType();
  14588. value = graph.insertNode(graph.createList(elem_type, unpacked)).output();
  14589. }
  14590. if (concrete_type instanceof torch.TupleType) {
  14591. const concrete_tuple = concrete_type;
  14592. if (!value_tuple.isSubtypeOf(concrete_tuple) &&
  14593. concrete_tuple.elements().length === value_tuple.elements().length) {
  14594. const unpacked = torch._C.createTupleUnpack(value);
  14595. const converted = [];
  14596. for (let i = 0; i < concrete_tuple.elements().length; i++) {
  14597. converted.push(torch._C.tryConvertToType(loc, graph, concrete_tuple.elements()[i], unpacked[i], allow_conversions));
  14598. }
  14599. value = graph.insertNode(graph.createTuple(converted)).output();
  14600. }
  14601. }
  14602. }
  14603. if (allow_conversions) {
  14604. const value_isa_tensor = value.type().isSubtypeOf(torch.TensorType.get());
  14605. const value_equals_number = value.type() === torch.NumberType.get();
  14606. const concrete_float = concrete_type === torch.FloatType.get();
  14607. const concrete_complex = concrete_type === torch.ComplexType.get();
  14608. const concrete_int = concrete_type === torch.IntType.get();
  14609. const concrete_number = concrete_type === torch.NumberType.get();
  14610. if (value_isa_tensor) {
  14611. if (concrete_float) {
  14612. value = graph.insert('aten::FloatImplicit', [new torch._C.NamedValue(value)], [], loc);
  14613. } else if (concrete_complex) {
  14614. value = graph.insert('aten::ComplexImplicit', [new torch._C.NamedValue(value)], [], loc);
  14615. } else if (concrete_int) {
  14616. value = graph.insert('aten::IntImplicit', [new torch._C.NamedValue(value)], [], loc);
  14617. } else if (concrete_number) {
  14618. value = graph.insert('aten::ScalarImplicit', [new torch._C.NamedValue(value)], [], loc);
  14619. }
  14620. } else if (value_equals_number) {
  14621. if (concrete_float) {
  14622. value = graph.insert('aten::Float', [new torch._C.NamedValue(value)], [], loc);
  14623. } else if (concrete_complex) {
  14624. value = graph.insert('aten::Complex', [new torch._C.NamedValue(value)], [], loc);
  14625. } else if (concrete_int) {
  14626. value = graph.insert('aten::Int', [new torch._C.NamedValue(value)], [], loc);
  14627. }
  14628. } else if (value.type() === torch.BoolType.get()) {
  14629. if (concrete_float) {
  14630. value = graph.insert('aten::Float', [new torch._C.NamedValue(value)], [], loc);
  14631. } else if (concrete_int || concrete_number) {
  14632. value = graph.insert('aten::Int', [new torch._C.NamedValue(value)], [], loc);
  14633. }
  14634. }
  14635. if (value.type().isSubtypeOf(torch.StringType.get()) && concrete_type.isSubtypeOf(torch.DeviceObjType.get())) {
  14636. return graph.insert('aten::device', [new torch._C.NamedValue(value)], [], loc);
  14637. }
  14638. }
  14639. return value;
  14640. });
  14641. this.registerFunction('torch._C.tryEvalTypeVariables', (type, type_env) => {
  14642. if (!type.hasFreeVariables()) {
  14643. if (type instanceof torch._C.DynamicType) {
  14644. return torch._C.tryEvalTypeVariables(type.fallback(), type_env);
  14645. }
  14646. return type;
  14647. }
  14648. if (type instanceof torch._C.VarType) {
  14649. return type_env.get(type.annotation_str);
  14650. }
  14651. const contained = type.containedTypes();
  14652. if (contained.length === 0) {
  14653. return type;
  14654. }
  14655. const new_contained = [];
  14656. for (const t of contained) {
  14657. const r = torch._C.tryEvalTypeVariables(t, type_env);
  14658. if (!r) {
  14659. return null;
  14660. }
  14661. new_contained.push(r);
  14662. }
  14663. return type.withContained(new_contained);
  14664. });
  14665. this.registerFunction('torch._C.tryMatchSchema', (schema, loc, graph, args, kwargs, self, failure_messages, allow_conversions) => {
  14666. if (torch._C.isBlockListedSchema(schema)) {
  14667. return null;
  14668. }
  14669. const err = null;
  14670. const type_env = new Map();
  14671. const positional_inputs = [];
  14672. const used_kwarg = kwargs.map(() => false);
  14673. const is_aten = schema.name.startsWith('aten::');
  14674. let used_args = 0;
  14675. for (let schema_i = 0; schema_i < schema.arguments.length; schema_i++) {
  14676. const arg = schema.arguments[schema_i];
  14677. let actual_named_value = null;
  14678. if (arg.name === 'self' && self) {
  14679. actual_named_value = self;
  14680. self = null;
  14681. } else if (!arg.kwarg_only && used_args < args.length) {
  14682. if (allow_conversions && torch._C.varargsCanBeUsedAsList(schema, schema_i, arg)) {
  14683. const value = args[used_args].value(graph);
  14684. const actual_type = value.type();
  14685. if (actual_type instanceof torch.ListType === false && !torch._C.convertibleToList(actual_type, torch._C.unwrapOptional(arg.type))) {
  14686. const formal_type = torch._C.unwrapOptional(arg.type).expect(torch.ListType).getElementType();
  14687. const list = torch._C.tryCreateList(formal_type, graph, loc, args.slice(used_args), failure_messages, err, allow_conversions, type_env);
  14688. if (!list) {
  14689. return null;
  14690. }
  14691. used_args = args.length;
  14692. positional_inputs.push(list);
  14693. continue;
  14694. }
  14695. }
  14696. actual_named_value = args[used_args];
  14697. used_args++;
  14698. } else {
  14699. const kwarg_idx = torch._C.findInputWithName(arg.name, kwargs, is_aten);
  14700. if (Number.isInteger(kwarg_idx)) {
  14701. const nv = kwargs[kwarg_idx];
  14702. if (used_kwarg[kwarg_idx]) {
  14703. if (failure_messages) {
  14704. throw new python.Error(`Argument '${nv.name()}' specified twice in schema.`);
  14705. }
  14706. return null;
  14707. }
  14708. used_kwarg[kwarg_idx] = true;
  14709. actual_named_value = nv;
  14710. } else if (arg.has_default_value()) {
  14711. actual_named_value = new torch._C.NamedValue(arg.default_value);
  14712. } else {
  14713. if (failure_messages) {
  14714. throw new python.Error(`Argument '${arg.name}' not provided.`);
  14715. }
  14716. return null;
  14717. }
  14718. }
  14719. const positional = torch._C.tryMatchArgument(arg, graph, loc, actual_named_value, failure_messages, err, allow_conversions, type_env);
  14720. if (!positional) {
  14721. return null;
  14722. }
  14723. positional_inputs.push(positional);
  14724. }
  14725. if (self !== null) {
  14726. if (failure_messages) {
  14727. throw new python.Error('Provided self argument not used in schema.');
  14728. }
  14729. return null;
  14730. }
  14731. if (schema.is_vararg) {
  14732. for (; used_args < args.length; used_args++) {
  14733. positional_inputs.push(args[used_args].value(graph));
  14734. }
  14735. }
  14736. if (used_args < args.length) {
  14737. if (failure_messages) {
  14738. throw new python.Error('Too many positional arguments.');
  14739. }
  14740. return null;
  14741. }
  14742. for (let i = 0; i < kwargs.length; i++) {
  14743. const nv = kwargs[i];
  14744. if (!used_kwarg[i]) {
  14745. if (failure_messages) {
  14746. if (schema.argumentIndexWithName(nv.name()) === null) {
  14747. throw new python.Error('Keyword argument unknown.');
  14748. } else {
  14749. throw new python.Error('Keyword argument specified twice.');
  14750. }
  14751. }
  14752. return null;
  14753. }
  14754. }
  14755. const returns = schema.returns;
  14756. const return_types = returns.map((r) => {
  14757. const result = torch._C.tryEvalTypeVariables(r.type, type_env);
  14758. if (!result) {
  14759. throw new python.Error('Unbound type variable.');
  14760. }
  14761. return result;
  14762. });
  14763. const return_has_field_names = returns.every((r) => !r.name);
  14764. let return_field_names = null;
  14765. if (return_has_field_names) {
  14766. return_field_names = returns.map((r) => r.name);
  14767. }
  14768. const schema_name = torch._C.getFullSchemaName(schema);
  14769. return new torch._C.MatchedSchema(positional_inputs, return_types, return_field_names, schema_name);
  14770. });
  14771. this.registerFunction('torch._C.matchSchema', (schema, loc, graph, args, kwargs, self) => {
  14772. self = self || null;
  14773. const result = torch._C.tryMatchSchema(schema, loc, graph, args, kwargs, self, null, true);
  14774. if (result) {
  14775. return result;
  14776. }
  14777. throw new python.Error(`No matching schema '${schema.name}' found.`);
  14778. });
  14779. this.registerFunction('torch._C.matchSchemas', (schemas, loc, graph, args, kwargs, self, render_errors) => {
  14780. self = self || null;
  14781. render_errors = render_errors || false;
  14782. torch._C.TORCH_INTERNAL_ASSERT(schemas.length > 0);
  14783. if (schemas.length === 1) {
  14784. return [0, torch._C.matchSchema(schemas[0], loc, graph, args, kwargs, self)];
  14785. }
  14786. for (const allow_conversions of [false, true]) {
  14787. for (let i = 0; i < schemas.length; i++) {
  14788. const matched_schema = torch._C.tryMatchSchema(schemas[i], loc, graph, args, kwargs, self, null, allow_conversions);
  14789. if (matched_schema) {
  14790. return [i, matched_schema];
  14791. }
  14792. }
  14793. }
  14794. if (!render_errors) {
  14795. return torch._C.matchSchemas(schemas, loc, graph, args, kwargs, self, /*render_errors=*/true);
  14796. }
  14797. throw new python.Error(`No matching schema '${schemas[0].name}' found.`);
  14798. });
  14799. this.registerFunction('torch._C.emitBuiltinCall', (loc, graph, name, args, kwargs, self) => {
  14800. const variants = torch._C.getAllOperatorsFor(name);
  14801. const builtin_functions = torch._C.getAllBuiltinFunctionsFor(name);
  14802. const graph_version = graph.get_op_version();
  14803. const schemas = [];
  14804. const upgrader_schemas = [];
  14805. for (const op of variants) {
  14806. let found_upgrader = false;
  14807. const op_name = torch._C.getFullSchemaName(op.schema());
  14808. if (Number.isInteger(graph_version)) {
  14809. const version_entry = torch._C.get_operator_version_map().get(op_name);
  14810. if (version_entry) {
  14811. const old_schema_entry = torch._C.findUpgrader(version_entry.second, graph_version.value());
  14812. if (old_schema_entry.has_value()) {
  14813. const old_schema = torch._C.parseSchema(old_schema_entry.value().old_schema);
  14814. upgrader_schemas.push(old_schema);
  14815. found_upgrader = true;
  14816. } else if (!torch._C.isOpCurrentBasedOnUpgraderEntries(version_entry.second, graph_version.value())) {
  14817. throw new python.Error('Valid upgrader must be present.');
  14818. }
  14819. }
  14820. }
  14821. if (!found_upgrader) {
  14822. schemas.push(op.schema());
  14823. }
  14824. }
  14825. if (variants.length === 0) {
  14826. const oldSchemas = torch._C.loadPossibleHistoricOps(name, graph_version);
  14827. for (const old_schema_entry of oldSchemas) {
  14828. const old_schema = torch._C.parseSchema(old_schema_entry);
  14829. upgrader_schemas.push(old_schema);
  14830. }
  14831. }
  14832. for (const schema of upgrader_schemas) {
  14833. schemas.push(schema);
  14834. }
  14835. for (const method of builtin_functions) {
  14836. method.ensure_defined();
  14837. schemas.push(method.getSchema());
  14838. }
  14839. if (schemas.length === 0) {
  14840. const inputs = args.map((arg) => arg.value(graph));
  14841. const n = graph.insertNode(graph.create(name, inputs, 0)).setSourceRange(loc);
  14842. n.addOutput().setType(torch.TensorType.get());
  14843. return n.output();
  14844. }
  14845. const matched = torch._C.matchSchemas(schemas, loc, graph, args, kwargs, self);
  14846. if (matched[0] < variants.length + upgrader_schemas.length) {
  14847. return torch._C.emitBuiltinNode(matched[1], loc, graph, name, graph_version);
  14848. }
  14849. const fn = builtin_functions[matched.first - variants.size()];
  14850. return torch._C.insertGraph(graph, torch._C.toGraphFunction(fn).graph(), matched.second.inputs, new Map())[0];
  14851. });
  14852. this.registerFunction('torch._C.emitBuiltinNode', (matched_schema, loc, graph, name, version) => {
  14853. const n = graph.insertNode(graph.create(name, matched_schema.inputs, 0)).setSourceRange(loc);
  14854. for (const ret of matched_schema.return_types) {
  14855. n.addOutput().setType(ret);
  14856. }
  14857. if (!Number.isInteger(version) || torch._C.isOpSymbolCurrent(matched_schema.schema_name, version)) {
  14858. n.getOperation();
  14859. } else {
  14860. n.setHistoricSchemaName(matched_schema.schema_name);
  14861. }
  14862. return torch._C.packOutputs(graph, n.outputs(), matched_schema.return_field_names);
  14863. });
  14864. this.registerFunction('torch._C.unshapedType', (type) => {
  14865. if (type.isSubtypeOf(torch.TensorType.get())) {
  14866. return torch.TensorType.get();
  14867. }
  14868. const contained = type.containedTypes();
  14869. if (contained.length === 0) {
  14870. return type;
  14871. }
  14872. return type.withContained(contained.map((t) => torch._C.unshapedType(t)));
  14873. });
  14874. this.registerFunction('torch._C.unifyTypesImpl', (t1, t2, default_to_union, type_hint) => {
  14875. default_to_union = default_to_union || false;
  14876. type_hint = type_hint || null;
  14877. if (t1.isSubtypeOf(t2)) {
  14878. return t2;
  14879. } else if (t2.isSubtypeOf(t1)) {
  14880. return t1;
  14881. }
  14882. if (t1.kind() === 'TensorType' && t2.kind() === 'TensorType') {
  14883. return t1.merge(t2);
  14884. }
  14885. if (t1.isSubtypeOf(torch.NoneType.get()) && !t2.isSubtypeOf(torch.NoneType.get())) {
  14886. return torch.OptionalType.create(t2);
  14887. } else if (t2.isSubtypeOf(torch.NoneType.get()) && !t1.isSubtypeOf(torch.NoneType.get())) {
  14888. return torch.OptionalType.create(t1);
  14889. }
  14890. if (t1 instanceof torch.OptionalType) {
  14891. const elem = torch._C.unifyTypes(t1.getElementType(), t2);
  14892. if (elem) {
  14893. return torch.OptionalType.create(elem);
  14894. }
  14895. } else if (t2 instanceof torch.OptionalType) {
  14896. const elem = torch._C.unifyTypes(t2.getElementType(), t1);
  14897. if (elem) {
  14898. return torch.OptionalType.create(elem);
  14899. }
  14900. }
  14901. if (t1 instanceof torch.TupleType && t2 instanceof torch.TupleType) {
  14902. if (t1.elements().size() !== t2.elements().size()) {
  14903. return null;
  14904. }
  14905. const elements = [];
  14906. for (let i = 0; i < t1.elements().length; i++) {
  14907. const elem = torch._C.unifyTypes(t1.elements()[i], t2.elements()[i], default_to_union);
  14908. if (elem) {
  14909. elements.push(elem);
  14910. } else {
  14911. return null;
  14912. }
  14913. }
  14914. return torch.TupleType.create(elements);
  14915. }
  14916. if (t1 instanceof torch.FutureType && t2 instanceof torch.FutureType) {
  14917. const elem = torch._C.unifyTypes(t1.getElementType(), t2.getElementType());
  14918. if (elem) {
  14919. return torch.FutureType.create(elem);
  14920. }
  14921. }
  14922. const t1_unshaped = torch._C.unshapedType(t1);
  14923. const t2_unshaped = torch._C.unshapedType(t2);
  14924. if (t1_unshaped.isSubtypeOf(t2_unshaped)) {
  14925. return t2_unshaped;
  14926. } else if (t2_unshaped.isSubtypeOf(t1_unshaped)) {
  14927. return t1_unshaped;
  14928. }
  14929. if (type_hint && t1.isSubtypeOf(type_hint) && t2.isSubtypeOf(type_hint)) {
  14930. return type_hint;
  14931. }
  14932. return null;
  14933. });
  14934. this.registerFunction('torch._C.unifyTypes', (t1, t2, default_to_union, type_hint) => {
  14935. const unified = torch._C.unifyTypesImpl(t1, t2, default_to_union, type_hint);
  14936. if (default_to_union && !unified) {
  14937. return torch.UnionType.create([t1, t2]);
  14938. }
  14939. return unified;
  14940. });
  14941. this.registerFunction('torch._C.unifyTypeList', (elements, why_not, default_to_union, type_hint) => {
  14942. if (elements.length === 0) {
  14943. return null;
  14944. }
  14945. let [ret_type] = elements;
  14946. for (let i = 1; i < elements.length && ret_type; i++) {
  14947. const maybe_unified = torch._C.unifyTypes(ret_type, elements[i], default_to_union, type_hint);
  14948. if (!maybe_unified) {
  14949. return null;
  14950. }
  14951. ret_type = maybe_unified;
  14952. }
  14953. return ret_type;
  14954. });
  14955. this.registerFunction('torch._C.insertableTensor', (ten) => {
  14956. return !ten.requires_grad() && ten.has_storage() && !ten.is_nested();
  14957. });
  14958. this.registerFunction('torch._C.insertableIValue', (ivalue) => {
  14959. if (ivalue.isInt() || ivalue.isNone() || ivalue.isBool() ||
  14960. ivalue.isDouble() || ivalue.isComplexDouble() || ivalue.isString() ||
  14961. ivalue.isDevice() || ivalue.isEnum()) {
  14962. return true;
  14963. }
  14964. if (ivalue.isTensor()) {
  14965. return torch._C.insertableTensor(ivalue.toTensor());
  14966. }
  14967. if (ivalue.isList() || ivalue.isTuple()) {
  14968. let elems = [];
  14969. if (ivalue.isTuple()) {
  14970. elems = ivalue.toTupleRef().elements();
  14971. } else {
  14972. elems = ivalue.toListRef();
  14973. }
  14974. return elems.every((tup_elem) => torch._C.insertableIValue(tup_elem));
  14975. }
  14976. if (ivalue.isGenericDict()) {
  14977. const dict = ivalue.toGenericDict();
  14978. return dict.every((entry) => torch._C.insertableIValue(entry.key()) && torch._C.insertableIValue(entry.value()));
  14979. }
  14980. return false;
  14981. });
  14982. this.registerFunction('torch._C.insertConstant', (g, val, loc, scope) => {
  14983. loc = loc || null;
  14984. scope = scope || null;
  14985. const value = torch._C.tryInsertConstant(g, val, loc, scope);
  14986. if (value !== undefined) {
  14987. return value;
  14988. }
  14989. throw new python.Error('Unsupported value kind.');
  14990. });
  14991. this.registerFunction('torch._C.tryInsertConstant', (g, val, loc, scope) => {
  14992. if (val instanceof torch._C.IValue) {
  14993. const n = g.create('prim::Constant');
  14994. if (val.isTensor()) {
  14995. const ref = val.toTensor();
  14996. if (!torch._C.insertableTensor(val.toTensor())) {
  14997. n.destroy();
  14998. return null;
  14999. }
  15000. if (!ref.defined()) {
  15001. n.destroy();
  15002. return g.insertNode(g.createNone()).output();
  15003. }
  15004. torch._C.TORCH_INTERNAL_ASSERT(!ref.requires_grad());
  15005. n.output().inferTypeFrom(ref); // note: before t_ because of std::move(ref)
  15006. n.t_('value', ref);
  15007. } else if (val.isInt()) {
  15008. n.i_('value', val.toInt());
  15009. n.output().setType(torch.IntType.get());
  15010. } else if (val.isDouble()) {
  15011. n.f_('value', val.toDouble());
  15012. n.output().setType(torch.FloatType.get());
  15013. } else if (val.isComplexDouble()) {
  15014. n.c_('value', val.toComplexDouble());
  15015. n.output().setType(torch.ComplexType.get());
  15016. } else if (val.isBool()) {
  15017. n.i_('value', val.toBool());
  15018. n.output().setType(torch.BoolType.get());
  15019. } else if (val.isList()) {
  15020. const fast_path_list = val.isBoolList() || val.isIntList() || val.isDoubleList();
  15021. if (fast_path_list || torch._C.insertableIValue(val)) {
  15022. n.ival_('value', val);
  15023. n.output().setType(val.type());
  15024. } else {
  15025. n.destroy();
  15026. return null;
  15027. }
  15028. } else if (val.isString()) {
  15029. n.s_('value', val.toStringRef());
  15030. n.output().setType(torch.StringType.get());
  15031. } else if (val.isDevice()) {
  15032. n.s_('value', val.toDevice().__str__());
  15033. n.output().setType(torch.DeviceObjType.get());
  15034. } else if (val.isGenerator()) {
  15035. n.ival_('value', val.toGenerator());
  15036. n.output().setType(torch._C_._GeneratorType.get());
  15037. } else if (val.isStream()) {
  15038. n.ival_('value', val);
  15039. n.output().setType(torch.StreamObjType.get());
  15040. } else if (val.isNone()) {
  15041. n.output().setType(torch.NoneType.get());
  15042. // n.ival_('value', null); // remove
  15043. } else if (val.isTuple()) {
  15044. if (torch._C.insertableIValue(val)) {
  15045. n.ival_('value', val);
  15046. n.output().setType(val.type());
  15047. } else {
  15048. n.destroy();
  15049. return null;
  15050. }
  15051. } else if (val.isObject()) {
  15052. const ref = val.toObjectRef();
  15053. // see: [Constant Object Weak CompilationUnit Reference]
  15054. if (!ref.type().is_module() && (ref.is_weak_compilation_ref() || ref.is_empty_strong_compilation_ref())) {
  15055. n.ival_('value', val);
  15056. n.output().setType(val.type());
  15057. } else {
  15058. n.destroy();
  15059. return null;
  15060. }
  15061. } else if ((val.isGenericDict() && torch._C.insertableIValue(val)) || (val.isEnum())) {
  15062. n.ival_('value', val);
  15063. n.output().setType(val.type());
  15064. } else {
  15065. n.destroy();
  15066. return null;
  15067. }
  15068. if (loc) {
  15069. n.setSourceRange(loc);
  15070. }
  15071. if (scope) {
  15072. n.setScope(scope);
  15073. }
  15074. return g.insertNode(n).output();
  15075. }
  15076. const n = g.create('prim::Constant');
  15077. let type = null;
  15078. if (val === null) {
  15079. n.ival_('value', val);
  15080. type = torch.NoneType.get();
  15081. } else if (typeof val === 'string') {
  15082. n.s_('value', val);
  15083. type = torch.StringType.get();
  15084. } else if (Array.isArray(val) && val.every((item) => typeof item === 'string')) {
  15085. n.ss_('value', val);
  15086. type = torch.ListType.create(torch.StringType.get());
  15087. } else if (typeof val === 'boolean') {
  15088. n.i_('value', val === true ? 1 : 0);
  15089. type = torch.BoolType.get();
  15090. } else if ((!val.type && Number.isInteger(val)) || val.type === 'int') {
  15091. n.i_('value', val);
  15092. type = torch.IntType.get();
  15093. } else if ((!val.type && typeof val === 'number') || val.type === 'float') {
  15094. n.f_('value', val);
  15095. type = torch.FloatType.get();
  15096. } else if (val instanceof torch.Tensor) {
  15097. n.t_('value', val);
  15098. type = torch.TensorType.get();
  15099. } else if (val instanceof torch.ScriptObject) {
  15100. n.ival_('value', val);
  15101. type = val.type();
  15102. } else if (Array.isArray(val) && val.every((item) => Number.isInteger(item))) {
  15103. n.ival_('value', val);
  15104. type = torch.ListType.create(torch.IntType.get());
  15105. } else {
  15106. throw new python.Error(`Unsupported value type '${typeof val}'.`);
  15107. }
  15108. if (type) {
  15109. n.output().setType(type);
  15110. }
  15111. if (loc) {
  15112. n.setSourceRange(loc);
  15113. }
  15114. if (scope) {
  15115. n.setScope(scope);
  15116. }
  15117. return g.insertNode(n).output();
  15118. });
  15119. this.registerFunction('torch._C.toIValue', (v) => {
  15120. if (v.node().kind() !== 'prim::Constant' || v.type() instanceof torch._C.FunctionType) {
  15121. return null;
  15122. }
  15123. const node = v.node();
  15124. const type = v.type();
  15125. if (type.isSubtypeOf(torch.TensorType.get())) {
  15126. return new torch._C.IValue(node.t('value'), 'Tensor');
  15127. } else if (type.isSubtypeOf(torch.BoolType.get())) {
  15128. return new torch._C.IValue(Boolean(node.i('value'), 'Bool'));
  15129. } else if (type.isSubtypeOf(torch.NumberType.get()) && node.kindOf('value') === 'i') {
  15130. return new torch._C.IValue(node.i('value'), 'Int');
  15131. } else if (type.isSubtypeOf(torch.NumberType.get()) && node.kindOf('value') === 'f') {
  15132. return new torch._C.IValue(node.f('value'), 'Double');
  15133. } else if (type.isSubtypeOf(torch.ComplexType.get()) && node.kindOf('value') === 'c') {
  15134. return new torch._C.IValue(node.c('value'), 'Complex');
  15135. } else if (type instanceof torch.ListType && node.kindOf('value') === 'ival') {
  15136. let list = node.ival('value');
  15137. list = list.isList ? list : new torch._C.IValue(list); // remove
  15138. torch._C.TORCH_INTERNAL_ASSERT(list.isList());
  15139. return list;
  15140. } else if (type instanceof torch.DictType && node.kindOf('value') === 'ival') {
  15141. const dict = node.ival('value');
  15142. torch._C.TORCH_INTERNAL_ASSERT(dict.isGenericDict());
  15143. return dict;
  15144. } else if (type instanceof torch.TupleType && node.kindOf('value') === 'ival') {
  15145. const tup = node.ival('value');
  15146. torch._C.TORCH_INTERNAL_ASSERT(tup.isTuple());
  15147. return tup;
  15148. } else if (type === torch.StringType.get()) {
  15149. const s = new torch._C.IValue(node.s('value'), 'String');
  15150. return s;
  15151. } else if (type === torch.DeviceObjType.get()) {
  15152. const d = new torch.device(node.s('value'));
  15153. return new torch._C.IValue(d);
  15154. } else if (type === torch._C._GeneratorType.get()) {
  15155. throw new python.Error('Not implemented.');
  15156. // const generator = node.ival('value').toGenerator();
  15157. // return generator;
  15158. } else if (type === torch.StreamObjType.get()) {
  15159. throw new python.Error('Not implemented.');
  15160. // const s = node.ival('value').toStream();
  15161. // return s;
  15162. } else if (node.mustBeNone()) {
  15163. return new torch._C.IValue();
  15164. } else if (type.kind() === 'EnumType') {
  15165. const enum_val = node.ival('value');
  15166. return enum_val;
  15167. } else if (type instanceof torch.ClassType && !type.is_module()) {
  15168. const class_val = node.ival('value');
  15169. return new torch._C.IValue(class_val, 'Object');
  15170. }
  15171. throw new python.Error('Unsupported constant literal.');
  15172. });
  15173. this.registerFunction('torch._C.constant_as', (v, target, default_value) => {
  15174. const ivalue = torch._C.toIValue(v);
  15175. if (ivalue) {
  15176. return ivalue[target]();
  15177. }
  15178. return default_value === undefined ? null : default_value;
  15179. });
  15180. this.registerType('torch._C.NamedValue', class {
  15181. constructor(...args) {
  15182. if (args.length === 1) {
  15183. if (args[0] instanceof torch.Value) {
  15184. [this._value] = args;
  15185. } else {
  15186. [this._ivalue] = args;
  15187. }
  15188. } else if (args.length === 3 && typeof args[1] === 'string' && args[2] instanceof torch.Value) {
  15189. [this._loc, this._name, this._value] = args;
  15190. } else {
  15191. throw new python.Error('Invalid argument.');
  15192. }
  15193. }
  15194. name() {
  15195. return this._name;
  15196. }
  15197. value(g) {
  15198. if (!this._value) {
  15199. return torch._C.insertConstant(g, this._ivalue);
  15200. }
  15201. return this._value;
  15202. }
  15203. type() {
  15204. if (this._value) {
  15205. return this._value.type();
  15206. }
  15207. return this._ivalue.type();
  15208. }
  15209. });
  15210. this.registerType('torch._C.SugaredValue', class {
  15211. kind() {
  15212. throw new python.Error('Not implemented.');
  15213. }
  15214. shouldEmitUnrolled() {
  15215. return this.staticLen() !== null;
  15216. }
  15217. });
  15218. this.registerType('torch._C.SimpleValue', class extends torch._C.SugaredValue {
  15219. constructor(value) {
  15220. super();
  15221. this._value = value;
  15222. }
  15223. kind() {
  15224. return `value of type '${this._value.type().annotation_str}'`;
  15225. }
  15226. asValue(/* range, m */) {
  15227. return this._value;
  15228. }
  15229. getValue() {
  15230. return this._value;
  15231. }
  15232. asTuple(loc, m, size_hint) {
  15233. const make_simple_value = (v) => new torch._C.SimpleValue(v);
  15234. if (this._value.type() instanceof torch.TupleType) {
  15235. const outputs = torch._C.createTupleUnpack(this._value);
  15236. return outputs.map((v) => make_simple_value(v));
  15237. } else if (this._value.type() instanceof torch.ListType) {
  15238. if (!size_hint) {
  15239. throw new python.Error('Cannot statically infer the expected size of a list in this context.');
  15240. }
  15241. const graph = this._value.owningGraph();
  15242. const unpack = graph.insertNode(graph.createListUnpack(this._value, size_hint));
  15243. return unpack.outputs().map((v) => make_simple_value(v));
  15244. } else if (this._value.type().kind() === 'AnyTupleType') {
  15245. throw new python.Error('Provided tuple is not fully defined including its element types.');
  15246. }
  15247. throw new python.Error(`Cannot use '${this._value.type().toString()}' as tuple.`);
  15248. }
  15249. attr(loc, m, field) {
  15250. if (this._value.type().isSubtypeOf(torch.TensorType.get())) {
  15251. if (torch._C.builtin_cast_method_to_scalar_type().has(field)) {
  15252. return new torch._C.TensorCastValue(torch._C.builtin_cast_method_to_scalar_type().get(field), new torch._C.NamedValue(loc, 'self', this._value));
  15253. }
  15254. }
  15255. if (this._value.type() instanceof torch.TupleType) {
  15256. throw new python.Error('Not implemented.');
  15257. }
  15258. if (this._value.type() instanceof torch.AwaitType) {
  15259. throw new python.Error('Not implemented.');
  15260. }
  15261. if (this._value.type() instanceof torch.ClassType) {
  15262. const classType = this._value.type();
  15263. if (classType.findMethod(field)) {
  15264. return new torch._C.MethodValue(this.getValue(), [field]);
  15265. }
  15266. if (classType.hasAttribute(field)) {
  15267. const g = m.graph();
  15268. const n = g.insertNode(g.createGetAttr(this._value, field));
  15269. return new torch._C.SimpleValue(n.output());
  15270. }
  15271. const prop = classType.getProperty(field);
  15272. if (prop) {
  15273. return new torch._C.MethodValue(this._value, [prop.getter.name()]).call(loc, m, {}, {}, /*n_binders=*/1);
  15274. }
  15275. } else if (this._value.type() instanceof torch.InterfaceType) {
  15276. throw new python.Error('Not implemented.');
  15277. } else if (this._value.type() instanceof torch.EnumType) {
  15278. const g = m.graph();
  15279. if (field === 'name') {
  15280. const n = g.insertNode(g.createEnumName(this._value));
  15281. return new torch._C.SimpleValue(n.output());
  15282. }
  15283. if (field === 'value') {
  15284. const n = g.insertNode(g.createEnumValue(this._value));
  15285. return new torch._C.SimpleValue(n.output());
  15286. }
  15287. }
  15288. if (field === 'type') {
  15289. const builtin = torch._C.BuiltinFunction.tryCreate('aten::to', new torch._C.NamedValue(loc, 'self', this._value));
  15290. if (builtin) {
  15291. return builtin;
  15292. }
  15293. }
  15294. const builtin = torch._C.BuiltinFunction.tryCreate(`aten::${field}`, new torch._C.NamedValue(loc, 'self', this._value));
  15295. if (builtin) {
  15296. return builtin;
  15297. }
  15298. if (this._value.type().isSubtypeOf(torch.TensorType.get()) && field === 'tolist') {
  15299. return torch._C.SpecialFormValue.create('prim::tolist');
  15300. }
  15301. if (this._value.type().isSubtypeOf(torch.TensorType.get()) && field === '__getitem__') {
  15302. return torch._C.SpecialFormValue.create('aten::index');
  15303. }
  15304. if (this._value.type() instanceof torch._C._GeneratorType && (field === 'manual_seed' || field === 'initial_seed' || field === 'seed')) {
  15305. const builtin = torch._C.BuiltinFunction.tryCreate(`aten::${field}`, new torch._C.NamedValue(loc, 'self', this._value));
  15306. if (builtin) {
  15307. return builtin;
  15308. }
  15309. }
  15310. throw new python.Error('Object has no attribute or method.');
  15311. }
  15312. setAttr(loc, m, field, newValue) {
  15313. const type = this._value.type();
  15314. if (type instanceof torch.ClassType === false) {
  15315. throw new python.Error('Cannot set attribute on non-class type.');
  15316. }
  15317. const classType = type;
  15318. let expectedType = classType.findAttribute(field);
  15319. if (!expectedType) {
  15320. const isInitializing = m.name() === '__init__' && m.graph().inputs().length > 0 && m.graph().inputs()[0].type() === classType;
  15321. if (isInitializing) {
  15322. if (this.isRecursive(classType, newValue.type())) {
  15323. throw new python.Error('Classes that recursively contain instances of themselves are not supported.');
  15324. }
  15325. classType.addAttribute(field, newValue.type());
  15326. expectedType = newValue.type();
  15327. const insertPoint = m.graph().insertPoint();
  15328. const topLevelBlock = m.graph().block();
  15329. if (insertPoint.owningBlock() !== topLevelBlock) {
  15330. throw new python.Error('First assignment cannot be in a control-flow block.');
  15331. }
  15332. } else {
  15333. const prop = classType.getProperty(field);
  15334. if (prop && prop.setter) {
  15335. new torch._C.MethodValue(this._value, prop.setter.name()).call(loc, m, [newValue], [], /*n_binders=*/1);
  15336. return;
  15337. }
  15338. if (prop && !prop.setter) {
  15339. throw new python.Error('Tried to set read-only attribute.');
  15340. }
  15341. throw new python.Error('Tried to set nonexistent attribute.');
  15342. }
  15343. }
  15344. torch._C.AT_ASSERT(expectedType);
  15345. const newType = newValue.type();
  15346. if (!newType.isSubtypeOf(expectedType)) {
  15347. throw new python.Error('Wrong type for attribute assignment.');
  15348. }
  15349. const g = m.graph();
  15350. g.insertNode(g.createSetAttr(this._value, field, newValue));
  15351. }
  15352. getitem(loc, m, idx, type_hint) {
  15353. const val = this.getValue();
  15354. const val_type = val.type();
  15355. const g = m.graph();
  15356. if (val_type instanceof torch.ListType || val_type instanceof torch.StringType) {
  15357. return new torch._C.SimpleValue(g.insert('aten::__getitem__', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc));
  15358. } else if (val_type instanceof torch.DictType) {
  15359. return new torch._C.SimpleValue(g.insert('aten::__getitem__', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc));
  15360. } else if (val_type.isSubtypeOf(torch.TensorType.get())) {
  15361. 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));
  15362. } else if (val_type instanceof torch.ClassType) {
  15363. const class_type = val_type;
  15364. if (class_type.is_module() && type_hint) {
  15365. const res = g.insert('prim::ModuleContainerIndex', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc);
  15366. res.setType(type_hint);
  15367. return new torch._C.SimpleValue(res);
  15368. }
  15369. return this.attr(loc, m, '__getitem__').call(loc, m, [new torch._C.NamedValue(idx)], [], 1);
  15370. }
  15371. throw new python.Error('Object is not subscriptable.');
  15372. }
  15373. });
  15374. this.registerType('torch._C.MethodValue', class extends torch._C.SugaredValue {
  15375. constructor(self, method_names) {
  15376. super();
  15377. this._self = self;
  15378. this._method_names = method_names;
  15379. }
  15380. call(loc, f, args, kwargs /*, n_binders */) {
  15381. const argsWithSelf = [new torch._C.NamedValue(this._self), ...args];
  15382. const schemas = [];
  15383. for (const method_name of this._method_names) {
  15384. const type = this._self.type();
  15385. if (type instanceof torch.ClassType) {
  15386. const class_type = type;
  15387. const method = class_type.getMethod(method_name);
  15388. method.ensure_defined();
  15389. schemas.push(method.getSchema());
  15390. } else if (type instanceof torch.InterfaceType) {
  15391. const interface_type = type;
  15392. schemas.push(interface_type.getMethod(method_name));
  15393. } else {
  15394. throw new python.Error('Method constructed that is not a class or interface.');
  15395. }
  15396. }
  15397. const match = torch._C.matchSchemas(schemas, loc, f.graph(), argsWithSelf, kwargs);
  15398. const output = f.graph().insertMethodCall(this._method_names[match[0]], match[1]);
  15399. output.node().setSourceRange(loc);
  15400. return new torch._C.SimpleValue(output);
  15401. }
  15402. });
  15403. this.registerType('torch._C.ClassValue', class extends torch._C.SugaredValue {
  15404. constructor(type) {
  15405. super();
  15406. this._type = type;
  15407. }
  15408. attr(loc, m, field) {
  15409. const hook = this._type.findHook(field);
  15410. if (hook) {
  15411. return new torch._C.FunctionValue(hook);
  15412. }
  15413. if (field !== '__new__') {
  15414. throw new python.Error('Tried to lookup unknown attribute on class.');
  15415. }
  15416. return torch._C.SpecialFormValue.create('prim::CreateObject');
  15417. }
  15418. });
  15419. this.registerType('torch._C.NamedTupleConstructor', class extends torch._C.SugaredValue {
  15420. constructor(type) {
  15421. super();
  15422. this._type = type;
  15423. }
  15424. call(loc, m, args, kwargs /*, n_binders */) {
  15425. const g = m.graph();
  15426. const schema = this._type.schema();
  15427. torch._C.TORCH_INTERNAL_ASSERT(schema);
  15428. const matched_schema = torch._C.matchSchema(schema, loc, g, args, kwargs);
  15429. const self = g.insertNode(g.createTuple(matched_schema.inputs, this._type).setSourceRange(loc)).output();
  15430. self.setType(this._type);
  15431. return new torch._C.SimpleValue(self);
  15432. }
  15433. });
  15434. this.registerType('torch._C.SugaredEnumClass', class extends torch._C.SugaredValue {
  15435. constructor(enum_type) {
  15436. super();
  15437. this._enum_type = enum_type;
  15438. }
  15439. attr(loc, m, field) {
  15440. const names_values = this._enum_type.enumNamesValues();
  15441. const it = names_values.find((nv) => nv[0] === field);
  15442. if (it === null) {
  15443. throw new python.Error(`Enum '${this._enum_type.name()}' has no attribute '${field}'.`);
  15444. }
  15445. const enum_holder = new torch._C.EnumHolder(this._enum_type, it[0], it[1]);
  15446. return new torch._C.SimpleValue(m.graph().insertConstant(new torch._C.IValue(enum_holder), loc));
  15447. }
  15448. });
  15449. this.registerType('torch._C.EnumHolder', class {
  15450. constructor(type, name, value) {
  15451. this._type = type;
  15452. this._name = name;
  15453. this._value = value;
  15454. }
  15455. name() {
  15456. return this._name;
  15457. }
  15458. type() {
  15459. return this._type;
  15460. }
  15461. });
  15462. this.registerType('torch._C.FunctionValue', class extends torch._C.SugaredValue {
  15463. constructor(...args) {
  15464. super();
  15465. if (args.length === 1 && args[0] instanceof torch._C.Function) {
  15466. this._callees = [args[0]];
  15467. } else {
  15468. throw new python.Error('Not implemented.');
  15469. }
  15470. }
  15471. call(loc, f, args, kwargs /*, n_binders */) {
  15472. const schemas = [];
  15473. for (const callee of this._callees) {
  15474. callee.ensure_defined();
  15475. schemas.push(callee.getSchema());
  15476. }
  15477. const match = torch._C.matchSchemas(schemas, loc, f.graph(), args, kwargs);
  15478. const output = f.graph().insertFunctionCall(this._callees[match[0]], match[1]);
  15479. output.node().setSourceRange(loc);
  15480. return new torch._C.SimpleValue(output);
  15481. }
  15482. });
  15483. this.registerType('torch._C.NoneValue', class extends torch._C.SugaredValue {
  15484. });
  15485. this.registerType('torch._C.PrintValue', class extends torch._C.SugaredValue {
  15486. call(loc, m, args, kwargs /*, n_binders */) {
  15487. const g = m.graph();
  15488. if (kwargs.length > 0) {
  15489. throw new python.Error(`Print doesn't accept any keyword arguments at ${loc}.`);
  15490. }
  15491. const lowered_inputs = torch._C.toValues(m.graph(), args);
  15492. g.insertNode(g.create('prim::Print', lowered_inputs, 0).setSourceRange(loc));
  15493. return new torch._C.NoneValue();
  15494. }
  15495. });
  15496. this.registerType('torch._C.SpecialFormValue', class extends torch._C.SugaredValue {
  15497. constructor(form) {
  15498. super();
  15499. this._form = form;
  15500. }
  15501. form() {
  15502. return this._form;
  15503. }
  15504. static create(form) {
  15505. return new torch._C.SpecialFormValue(form);
  15506. }
  15507. });
  15508. this.registerFunction('torch._C.makeMagic', (name, base) => {
  15509. return new torch._C.MagicMethod(name, base);
  15510. });
  15511. this.registerType('torch._C.BuiltinFunction', class extends torch._C.SugaredValue {
  15512. constructor(symbol, self) {
  15513. super();
  15514. this.symbol = symbol;
  15515. this.self = self;
  15516. }
  15517. call(loc, m, args, kwargs /*, n_binders */) {
  15518. return new torch._C.SimpleValue(torch._C.emitBuiltinCall(loc, m.graph(), this.symbol, args, kwargs, this.self));
  15519. }
  15520. static tryCreate(symbol, self) {
  15521. for (const op of torch._C.getAllOperatorsFor(symbol)) {
  15522. if (!self) {
  15523. return new torch._C.BuiltinFunction(symbol, null);
  15524. }
  15525. const index = op.schema().argumentIndexWithName('self');
  15526. if (index) {
  15527. const type_env = new Map();
  15528. const formal_type = op.schema().arguments()[index].type();
  15529. const matched = torch._C.matchTypeVariables(formal_type, self.type(), type_env);
  15530. if (!matched.success()) {
  15531. continue;
  15532. }
  15533. const concrete_type = torch._C.tryEvalTypeVariables(formal_type, type_env);
  15534. if (!concrete_type || !self.type().isSubtypeOf(concrete_type)) {
  15535. continue;
  15536. }
  15537. return new torch._C.BuiltinFunction(symbol, self);
  15538. }
  15539. }
  15540. return null;
  15541. }
  15542. });
  15543. this.registerType('torch._C.BuiltinModule', class extends torch._C.SugaredValue {
  15544. constructor(name, version) {
  15545. super();
  15546. this.name = name;
  15547. this.version = version || null;
  15548. }
  15549. attr(loc, m, field) {
  15550. if (field === 'autograd') {
  15551. return new torch._C.BuiltinModule('aten', this.version);
  15552. }
  15553. const sym = `${this.name}::${field}`;
  15554. return new torch._C.BuiltinFunction(sym, null);
  15555. }
  15556. });
  15557. this.registerType('torch._C.OpsValue', class extends torch._C.SugaredValue {
  15558. constructor(version) {
  15559. super();
  15560. this._version = version;
  15561. }
  15562. attr(loc, m, field) {
  15563. return new torch._C.BuiltinModule(field, this._version);
  15564. }
  15565. });
  15566. this.registerType('torch._C.ConstantTableValue', class extends torch._C.SugaredValue {
  15567. constructor(constants) {
  15568. super();
  15569. this._constants = constants;
  15570. this.non_holding_object_cache = new Map();
  15571. }
  15572. attr(loc, m, field) {
  15573. const offset = parseInt(field.substring(1), 10);
  15574. if (!Number.isInteger(offset)) {
  15575. throw new python.Error(`Invalid constant identifier '${field}.`);
  15576. }
  15577. if (offset < 0 || offset >= this._constants.length) {
  15578. throw new python.Error('Invalid constant index.');
  15579. }
  15580. const ivalue = new torch._C.IValue(this._constants[offset]); // remove IValue
  15581. let value = null;
  15582. if (ivalue.isObject() && !ivalue.toObject().is_weak_compilation_ref()) {
  15583. const obj = ivalue.toObject();
  15584. if (!this.non_holding_object_cache.has(obj)) {
  15585. this.non_holding_object_cache.set(obj, obj.copy_to_weak_compilation_ref());
  15586. }
  15587. value = m.graph().insertConstant(this.non_holding_object_cache[obj], loc);
  15588. } else {
  15589. value = m.graph().insertConstant(this._constants[offset], loc);
  15590. }
  15591. value.setType(torch._C.unshapedType(value.type()));
  15592. return new torch._C.SimpleValue(value);
  15593. }
  15594. });
  15595. this.registerType('torch._C.CastValue', class extends torch._C.BuiltinFunction {
  15596. constructor(type, method) {
  15597. super(method, null);
  15598. this._type = type;
  15599. }
  15600. call(loc, m, args, kwargs, n_binders) {
  15601. if (args.length === 1 && kwargs.length === 0) {
  15602. const len_op = new torch._C.BuiltinFunction('aten::len', null);
  15603. const gt_op = new torch._C.BuiltinFunction('aten::gt', null);
  15604. const zero = m.graph().insertConstant(new torch._C.IValue(0, 'Int'));
  15605. const v = args[0].value(m.graph());
  15606. if (v.type().isSubtypeOf(this._type)) {
  15607. return new torch._C.SimpleValue(v);
  15608. } 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)) {
  15609. const len = len_op.call(loc, m, [v], [], 1);
  15610. return gt_op.call(loc, m, [len.asValue(loc, m), zero], [], 1);
  15611. }
  15612. }
  15613. return super.call(loc, m, args, kwargs, n_binders);
  15614. }
  15615. });
  15616. this.registerType('torch._C.MagicMethod', class extends torch._C.SugaredValue {
  15617. constructor(desugared_name, base) {
  15618. super();
  15619. this._base_value = base;
  15620. this._desugared_name = desugared_name;
  15621. }
  15622. call(loc, m, args, kwargs, n_binders) {
  15623. if (args.length > 0) {
  15624. const self = args[0].value(m.graph());
  15625. if (self.type() instanceof torch.ClassType) {
  15626. return new torch._C.SimpleValue(self)
  15627. .attr(loc, m, this._desugared_name)
  15628. .call(loc, m, args.slice(1), kwargs, n_binders);
  15629. }
  15630. }
  15631. if (!this._base_value) {
  15632. throw new python.Error('Invalid magic method.');
  15633. }
  15634. return this._base_value.call(loc, m, args, kwargs, n_binders);
  15635. }
  15636. });
  15637. this.registerType('torch._C.RangeValue', class extends torch._C.SugaredValue {
  15638. constructor(loc, m, inputs, static_len) {
  15639. super();
  15640. static_len = static_len || null;
  15641. if (inputs.length === 0 || inputs.length > 3 || !inputs.every((value) => value.type() instanceof torch.IntType)) {
  15642. throw new python.Error('Invalid range inputs.');
  15643. }
  15644. const g = m.graph();
  15645. if (inputs.length === 1) {
  15646. [this._end] = inputs;
  15647. this._start = g.insertConstant(0, loc);
  15648. this._step = g.insertConstant(1, loc);
  15649. this._has_only_end = true;
  15650. } else {
  15651. [this._start, this._end] = inputs;
  15652. this._step = inputs.length === 3 ? inputs[2] : g.insertConstant(1, loc);
  15653. this._has_only_end = false;
  15654. }
  15655. this._static_len = static_len;
  15656. }
  15657. staticLen() {
  15658. return this._static_len;
  15659. }
  15660. iter() {
  15661. return this;
  15662. }
  15663. len(loc, m) {
  15664. if (this._static_len) {
  15665. return torch._C.insertConstant(m.graph(), this._static_len, loc);
  15666. }
  15667. if (this._has_only_end) {
  15668. return this._end;
  15669. }
  15670. const g = m.graph();
  15671. return g.insert('aten::__range_length', [this._start, this._end, this._step], [], loc);
  15672. }
  15673. getitem(loc, m, idx /*, type_hint */) {
  15674. if (this._has_only_end) {
  15675. return new torch._C.SimpleValue(idx);
  15676. }
  15677. const g = m.graph();
  15678. return new torch._C.SimpleValue(g.insert('aten::__derive_index', [idx, this._start, this._step], [], loc));
  15679. }
  15680. });
  15681. this.registerType('torch._C.SliceValue', class extends torch._C.SugaredValue {
  15682. });
  15683. this.registerType('torch._C.ClassNamespaceValue', class extends torch._C.SugaredValue {
  15684. constructor(name, si) {
  15685. super();
  15686. this._basename = name;
  15687. this._si = si;
  15688. }
  15689. attr(loc, m, name) {
  15690. const fullName = new torch._C.QualifiedName(this._basename, name);
  15691. const serializable_type = this._si.findNamedType(fullName);
  15692. if (serializable_type) {
  15693. if (serializable_type instanceof torch.ClassType) {
  15694. return new torch._C.ClassValue(serializable_type);
  15695. } else if (serializable_type instanceof torch.TupleType) {
  15696. return new torch._C.NamedTupleConstructor(serializable_type);
  15697. } else if (serializable_type instanceof torch.EnumType) {
  15698. return new torch._C.SugaredEnumClass(serializable_type);
  15699. }
  15700. }
  15701. const fn = this._si.findFunction(fullName);
  15702. if (fn) {
  15703. return new torch._C.FunctionValue(fn);
  15704. }
  15705. return new torch._C.ClassNamespaceValue(fullName, this._si);
  15706. }
  15707. });
  15708. this.registerType('torch.package.PackageImporter', class {
  15709. constructor(reader) {
  15710. this.zip_reader = reader;
  15711. }
  15712. load_pickle(module, resource) {
  15713. const name = `${module.replace(/\./, '/')}/${resource}`;
  15714. const stream = this.zip_reader.get_record(name);
  15715. const loaded_reduces = new Map();
  15716. this.storage_context = new torch._C.DeserializationStorageContext();
  15717. const unpickler = new pickle.Unpickler(stream);
  15718. unpickler.persistent_load = (saved_id) => {
  15719. switch (saved_id[0]) {
  15720. case 'storage': {
  15721. const [, storage_type, key, , size] = saved_id;
  15722. if (!this.storage_context.has_storage(key)) {
  15723. const storage = new storage_type(size);
  15724. if (!storage._set_cdata) {
  15725. throw new python.Error(`'${storage_type.__name__}._set_cdata' is not a function.`);
  15726. }
  15727. const stream = this.zip_reader.get_record(`.data/${key}.storage`);
  15728. const buffer = stream.peek();
  15729. storage._set_cdata(buffer);
  15730. this.storage_context.add_storage(key, storage);
  15731. }
  15732. return this.storage_context.get_storage(key);
  15733. }
  15734. case 'reduce_package': {
  15735. if (saved_id.length === 2) {
  15736. const [, func, args] = saved_id;
  15737. return execution.invoke(func, args);
  15738. }
  15739. const [, reduce_id, func, args] = saved_id;
  15740. if (!loaded_reduces.has(reduce_id)) {
  15741. const value = execution.invoke(func, [this].concat(args));
  15742. loaded_reduces.set(reduce_id, value);
  15743. }
  15744. return loaded_reduces.get(reduce_id);
  15745. }
  15746. default: {
  15747. throw new python.Error(`Unknown package typename '${saved_id[0]}'.`);
  15748. }
  15749. }
  15750. };
  15751. const obj = unpickler.load();
  15752. this.storage_context = null;
  15753. return obj;
  15754. }
  15755. import_module(name) {
  15756. return execution.import(name);
  15757. }
  15758. });
  15759. this.registerFunction('torch.jit.load', (file, map_location, extra_files) => {
  15760. const cu = new torch.jit.CompilationUnit();
  15761. cu.execution = execution;
  15762. const cpp_module = torch._C.import_ir_module(cu, file, map_location, extra_files);
  15763. const module = torch.jit._script.wrap_cpp_module(cpp_module);
  15764. module.forward = cpp_module.forward; // remove
  15765. return module;
  15766. });
  15767. this.registerFunction('torch._C.import_ir_module', function(cu, reader, ...args) {
  15768. switch (arguments.length) {
  15769. case 4: {
  15770. const [device, extra_files] = args;
  15771. const deserializer = new torch._C.ScriptModuleDeserializer(cu, reader);
  15772. return deserializer.deserialize(device, extra_files);
  15773. }
  15774. case 5: {
  15775. const [storage_context, device, ts_id] = args;
  15776. const deserializer = new torch._C.ScriptModuleDeserializer(cu, reader, `.data/ts_code/${ts_id}/`, '.data/', storage_context);
  15777. return deserializer.deserialize(device, null);
  15778. }
  15779. default: {
  15780. throw new python.Error("Invalid 'torch._C.import_ir_module' signature.");
  15781. }
  15782. }
  15783. });
  15784. this.registerFunction('torch._C._import_ir_module_from_package', (cu, reader, storage_context, map_location, ts_id) => {
  15785. return torch._C.import_ir_module(cu, reader, storage_context, null, ts_id);
  15786. });
  15787. this.registerFunction('torch._C.tryToGraphFunction', (value) => {
  15788. if (value instanceof torch.Node) {
  15789. const n = value;
  15790. if (n.kind() === 'prim::CallFunction') {
  15791. torch._C.AT_ASSERT(n.input(0).node().kind() === 'prim::Constant');
  15792. const function_constant = n.input(0).node();
  15793. const fun_type = function_constant.output().type().expect(torch._C.FunctionType);
  15794. return torch._C.tryToGraphFunction(fun_type.function());
  15795. }
  15796. if (n.kind() === 'prim::CallMethod') {
  15797. const name = n.s('name');
  15798. const class_type = n.input(0).type();
  15799. if (class_type instanceof torch.ClassType) {
  15800. const fn = class_type.getMethod(name);
  15801. return torch._C.tryToGraphFunction(fn);
  15802. }
  15803. }
  15804. return null;
  15805. } else if (value instanceof torch._C.Function) {
  15806. const fn = value;
  15807. if (!fn.isGraphFunction()) {
  15808. return null;
  15809. }
  15810. return fn;
  15811. }
  15812. throw new python.Error('Not implemented.');
  15813. });
  15814. this.registerType('torch._C.ModuleInstanceInfo', class {
  15815. constructor(module_type, instance_name) {
  15816. this._module_type = module_type;
  15817. this._instance_name = instance_name;
  15818. }
  15819. });
  15820. this.registerFunction('torch._C.slice_indices_adjust', (length, start, stop, step) => {
  15821. torch._C.TORCH_CHECK(step !== 0);
  15822. torch._C.TORCH_CHECK(step >= -Number.MAX_SAFE_INTEGER); // INT64_MAX
  15823. if (start._ === Number.MAX_SAFE_INTEGER) {
  15824. start._ = (step < 0) ? Number.MAX_SAFE_INTEGER : 0;
  15825. }
  15826. if (stop._ === Number.MAX_SAFE_INTEGER) {
  15827. stop._ = (step < 0) ? Number.MIN_SAFE_INTEGER : Number.MAX_SAFE_INTEGER;
  15828. }
  15829. if (start._ < 0) {
  15830. start._ += length;
  15831. if (start._ < 0) {
  15832. start._ = (step < 0) ? -1 : 0;
  15833. }
  15834. } else if (start._ >= length) {
  15835. start._ = (step < 0) ? length - 1 : length;
  15836. }
  15837. if (stop._ < 0) {
  15838. stop._ += length;
  15839. if (stop._ < 0) {
  15840. stop._ = (step < 0) ? -1 : 0;
  15841. }
  15842. } else if (stop._ >= length) {
  15843. stop._ = (step < 0) ? length - 1 : length;
  15844. }
  15845. if (step < 0) {
  15846. if (stop._ < start._) {
  15847. return Math.floor((start._ - stop._ - 1) / (-step) + 1);
  15848. }
  15849. } else if (start._ < stop._) {
  15850. return Math.floor((stop._ - start._ - 1) / step + 1);
  15851. }
  15852. return 0;
  15853. });
  15854. this.registerFunction('torch._C.createTupleUnpack', (v) => {
  15855. if (v.node().kind() === 'prim::TupleConstruct') {
  15856. return v.node().inputs();
  15857. }
  15858. const g = v.owningGraph();
  15859. return g.insertNode(g.createTupleUnpack(v)).outputs();
  15860. });
  15861. this.registerFunction('torch._C.inlineCallStackOfNode', (/* new_node, new_cs_entriesm, callee, to_replace, m_info */) => {
  15862. /*
  15863. const new_node_cs = new_node.callstack();
  15864. const raw_callstack_ptr = new_node_cs ? new_node_cs : nullptr;
  15865. if (!new_cs_entries.has(raw_callstack_ptr)) {
  15866. if (new_node_cs) {
  15867. new_cs_entries.set(raw_callstack_ptr, c10::make_intrusive<InlinedCallStack>(*new_node_cs, callee, to_replace.sourceRange(), m_info));
  15868. } else {
  15869. new_cs_entries.set(raw_callstack_ptr, c10::make_intrusive<InlinedCallStack>(callee, to_replace.sourceRange(), m_info);
  15870. }
  15871. }
  15872. new_node.setCallStack(new_cs_entries.at(raw_callstack_ptr));
  15873. for (const block of new_node.blocks()) {
  15874. torch._C.inlineCallStackOfBlock(block, new_cs_entries, callee, to_replace, m_info);
  15875. }
  15876. */
  15877. });
  15878. this.registerFunction('torch._C.inlineCallTo', (to_replace, callee, arg) => {
  15879. if (arg === undefined || typeof arg === 'boolean') {
  15880. const inline_optimized_graph = arg === undefined ? true : arg;
  15881. const graph = inline_optimized_graph ? callee.optimized_graph() : callee.graph();
  15882. return torch._C.inlineCallTo(to_replace, callee, graph);
  15883. }
  15884. if (arg instanceof torch.Graph === false) {
  15885. throw new python.Error('Invalid argument.');
  15886. }
  15887. const callee_graph = arg;
  15888. const guard = new torch._C.WithInsertPoint(to_replace);
  15889. const value_map = new Map();
  15890. const new_outputs = torch._C.insertGraph(to_replace.owningGraph(), callee_graph, to_replace.inputs(), value_map);
  15891. const new_callstack_entries = new Map();
  15892. let module_instance_info = null;
  15893. if (to_replace.kind() === 'prim::CallMethod') {
  15894. const class_type_ptr = to_replace.input(0).type();
  15895. if (to_replace.input(0).node().kind() === 'prim::GetAttr') {
  15896. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, to_replace.input(0).node().s('name'));
  15897. } else if (to_replace.owningGraph().inputs().length > 0 && to_replace.input(0) === to_replace.owningGraph().inputs()[0]) {
  15898. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, 'SELF');
  15899. } else {
  15900. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, 'INSTANCE_NAME_UNKNOWN');
  15901. }
  15902. }
  15903. const updated_nodes = new Set();
  15904. for (const kv of value_map) {
  15905. const is_graph_input = callee_graph.inputs().indexOf(kv[0]);
  15906. if (is_graph_input === -1) {
  15907. continue;
  15908. }
  15909. const new_node = kv[1].node();
  15910. if (updated_nodes.has(new_node)) {
  15911. continue;
  15912. }
  15913. updated_nodes.add(new_node);
  15914. torch._C.inlineCallStackOfNode(new_node, new_callstack_entries, callee, to_replace, module_instance_info);
  15915. }
  15916. const old_outputs = to_replace.outputs();
  15917. torch._C.AT_ASSERT(new_outputs.length === old_outputs.length);
  15918. for (let i = 0; i < old_outputs.length; i++) {
  15919. if (old_outputs[i].hasDebugName()) {
  15920. new_outputs[i].setDebugName(old_outputs[i].debugName());
  15921. }
  15922. old_outputs[i].replaceAllUsesWith(new_outputs[i]);
  15923. }
  15924. to_replace.destroy();
  15925. guard.dispose();
  15926. return new_outputs;
  15927. });
  15928. this.registerFunction('torch._C.inlineCalls', (block) => {
  15929. for (const cur of block.nodes()) {
  15930. switch (cur.kind()) {
  15931. case 'prim::CallFunction': {
  15932. const graphFunction = torch._C.tryToGraphFunction(cur);
  15933. if (graphFunction) {
  15934. const function_constant = cur.input(0).node();
  15935. // const fun_type = function_constant.output().type().expect(torch.FunctionType);
  15936. cur.removeInput(0);
  15937. let g = null;
  15938. const fallback = function_constant.hasAttribute('fallback');
  15939. if (fallback && graphFunction.get_executor().isOptimized()) {
  15940. const exec_plans = graphFunction.get_executor().getDebugState().execution_plans;
  15941. if (!exec_plans.empty()) {
  15942. g = exec_plans.begin().second.graph;
  15943. torch._C.Inline(g);
  15944. }
  15945. }
  15946. if (g === null) {
  15947. g = graphFunction.optimized_graph();
  15948. }
  15949. torch._C.inlineCallTo(cur, graphFunction, g);
  15950. }
  15951. break;
  15952. }
  15953. case 'prim::CallMethod': {
  15954. const graphFunction = torch._C.tryToGraphFunction(cur);
  15955. if (graphFunction) {
  15956. torch._C.inlineCallTo(cur, graphFunction);
  15957. }
  15958. break;
  15959. }
  15960. default: {
  15961. for (const b of cur.blocks()) {
  15962. torch._C.inlineCalls(b);
  15963. }
  15964. }
  15965. }
  15966. }
  15967. });
  15968. this.registerFunction('torch._C.Inline', (graph) => {
  15969. torch._C.inlineCalls(graph.block());
  15970. });
  15971. this.registerFunction('torch._C._jit_pass_inline', (graph) => {
  15972. torch._C.Inline(graph);
  15973. });
  15974. this.registerFunction('torch._C._set_tensor_metadata', (/* tensor, metadata */) => {
  15975. });
  15976. this.registerFunction('torch.jit._script.unpackage_script_module', (importer, script_module_id) => {
  15977. const cu = new torch.jit.CompilationUnit();
  15978. cu.execution = execution;
  15979. const cpp_module = torch._C._import_ir_module_from_package(cu, importer.zip_reader, importer.storage_context, importer.last_map_location, script_module_id);
  15980. return torch.jit._script.wrap_cpp_module(cpp_module);
  15981. });
  15982. this.registerFunction('torch.jit._script.wrap_cpp_module', (cpp_module) => {
  15983. const init_fn = (script_module) => {
  15984. for (const [name, module] of new torch.ModuleDict(script_module._c).items()) {
  15985. script_module.__setattr__(name, torch.jit._script.wrap_cpp_module(module));
  15986. }
  15987. };
  15988. return torch.jit._script.RecursiveScriptModule._construct(cpp_module, init_fn);
  15989. });
  15990. this.registerType('torch._C.DeserializationStorageContext', class extends Map {
  15991. has_storage(name) {
  15992. return this.has(name);
  15993. }
  15994. get_storage(name) {
  15995. return this.get(name);
  15996. }
  15997. add_storage(name, storage) {
  15998. return this.set(name, storage);
  15999. }
  16000. });
  16001. this.registerType('torch.ScriptFunction', class {
  16002. constructor(name, graph /*, function_creator */) {
  16003. this._name = name;
  16004. this._graph = graph;
  16005. }
  16006. });
  16007. this.registerType('torch.ScriptMethod', class {
  16008. constructor(owner, value) {
  16009. this._owner = owner;
  16010. this._function = value;
  16011. }
  16012. get name() {
  16013. return this._function.name();
  16014. }
  16015. get owner() {
  16016. return this._owner;
  16017. }
  16018. __call__(/* args, kwargs */) {
  16019. throw new python.Error("'torch.ScriptMethod.__call__' not implemented.");
  16020. }
  16021. get graph() {
  16022. return this._function.graph();
  16023. }
  16024. get schema() {
  16025. // return this.function().getSchema();
  16026. throw new python.Error("'torch.ScriptMethod.schema' not implemented.");
  16027. }
  16028. get code() {
  16029. throw new python.Error("'torch.ScriptMethod.code' not implemented.");
  16030. }
  16031. get code_with_constants() {
  16032. throw new python.Error("'torch.ScriptMethod.code_with_constants' not implemented.");
  16033. }
  16034. });
  16035. this.registerType('torch.ScriptObject', class {
  16036. constructor(type) {
  16037. this._typ = type;
  16038. this._ivalue = {};
  16039. }
  16040. static create(type) {
  16041. if (type.is_module()) {
  16042. return new torch.ScriptModule(type);
  16043. }
  16044. return new torch.ScriptObject(type);
  16045. }
  16046. type() {
  16047. return this._typ;
  16048. }
  16049. _type() {
  16050. return this._typ; // torch.ClassType
  16051. }
  16052. __setstate__(state) {
  16053. const [attrs, qualname] = state;
  16054. this._typ = torch._C.getCustomClass(qualname);
  16055. if (!this._typ) {
  16056. throw new python.Error(`Unsupported custom class '${qualname}'.`);
  16057. }
  16058. for (let i = 0; i < this._typ.numAttributes(); i++) {
  16059. const name = this._typ.getAttributeName(i);
  16060. this.__setattr__(name, attrs[i]);
  16061. }
  16062. }
  16063. find_method(basename) {
  16064. for (const fn of this.type().methods()) {
  16065. if (fn.name() === basename) {
  16066. return new torch.ScriptMethod(this /* _value() */, fn);
  16067. }
  16068. }
  16069. return null;
  16070. }
  16071. _get_method(name) {
  16072. const method = this.find_method(name);
  16073. if (method) {
  16074. return method;
  16075. }
  16076. torch._C.TORCH_CHECK(false, `Method '${name}' is not defined.`);
  16077. return null;
  16078. }
  16079. _has_method(name) {
  16080. return this.find_method(name) ? true : false;
  16081. }
  16082. _method_names() {
  16083. return this.type().methods().map((fn) => fn.name());
  16084. }
  16085. __setattr__(name, value) {
  16086. // if (this._type.hasContant(name))
  16087. this._ivalue[name] = value;
  16088. }
  16089. __getattr__(name) {
  16090. return this._ivalue[name];
  16091. }
  16092. hasattr(name) {
  16093. return this._typ.hasAttribute(name) || this._typ.hasConstant(name);
  16094. }
  16095. getattr(name) {
  16096. return this.__getattr__(name);
  16097. }
  16098. _properties() {
  16099. throw new python.Error("'torch.ScriptObject._properties' not implemented.");
  16100. }
  16101. is_weak_compilation_ref() {
  16102. return true; // not implemented
  16103. }
  16104. });
  16105. this.registerType('torch.ScriptModule', class extends torch.ScriptObject {
  16106. constructor(...args) {
  16107. if (args[0] instanceof torch._C.QualifiedName && args[1] instanceof torch.jit.CompilationUnit) {
  16108. const [class_name, cu, shouldMangle] = args;
  16109. super(...torch.ScriptModule.create_module_object(class_name, cu, shouldMangle));
  16110. } else {
  16111. super(...args);
  16112. }
  16113. }
  16114. get qualified_name() {
  16115. return this.type().qualified_name();
  16116. }
  16117. get code_with_constants() {
  16118. const const_map = {};
  16119. const_map.const_mapping = new Map(Object.entries(execution.builtins.CONSTANTS));
  16120. return [null, const_map];
  16121. }
  16122. get graph() {
  16123. if (!this._graph) {
  16124. const fn = this._typ.getMethod('forward');
  16125. this._graph = fn.graph();
  16126. }
  16127. return this._graph;
  16128. }
  16129. static create_module_object(class_name, cu, shouldMangle) {
  16130. shouldMangle = shouldMangle || false;
  16131. if (!class_name.prefix()) {
  16132. class_name = new torch._C.QualifiedName('__torch__', class_name.name());
  16133. }
  16134. if (shouldMangle && cu.get_class(class_name)) {
  16135. class_name = cu.mangle(class_name);
  16136. }
  16137. const cls = torch.ClassType.create(class_name, cu, true);
  16138. cu.register_type(cls);
  16139. return [cls, cu];
  16140. }
  16141. register_module(name, module) {
  16142. this.type().addOrCheckAttribute(name, module.type());
  16143. this.__setattr__(name, module); // _ivalue()->setAttr(name, module._ivalue());
  16144. }
  16145. register_buffer(name, v) {
  16146. this.type().addOrCheckAttribute(name, torch.TensorType.get(), false, true);
  16147. this.__setattr__(name, v); // _ivalue()->setAttr(name, std::move(v));
  16148. }
  16149. register_parameter(name, v, is_buffer) {
  16150. this.type().addOrCheckAttribute(name, torch.TensorType.get(), !is_buffer, is_buffer);
  16151. this.__setattr__(name, v); // _ivalue()->setAttr(name, std::move(v));
  16152. }
  16153. register_attribute(name, t, v, is_param, is_buffer) {
  16154. this.type().addOrCheckAttribute(name, t, is_param, is_buffer);
  16155. // _ivalue()->setAttr(name, v);
  16156. }
  16157. });
  16158. this.registerType('torch.ModuleDict', class {
  16159. constructor(mod) {
  16160. this._module = mod;
  16161. }
  16162. items() {
  16163. const result = new Map();
  16164. const type = this._module.type();
  16165. for (let i = 0; i < type.numAttributes(); i++) {
  16166. const k = type.getAttributeName(i);
  16167. const t = type.getAttribute(i);
  16168. if (t && t.is_module()) {
  16169. result.set(k, this._module.__getattr__(k));
  16170. }
  16171. }
  16172. return result;
  16173. }
  16174. });
  16175. this.registerType('torch.ParameterDict', class {
  16176. constructor(mod) {
  16177. this._module = mod;
  16178. }
  16179. items() {
  16180. const result = new Map();
  16181. const type = this._module.type();
  16182. for (let i = 0; i < type.numAttributes(); i++) {
  16183. if (type.is_parameter(i)) {
  16184. const k = type.getAttributeName(i);
  16185. const v = this._module.__getattr__(k);
  16186. if (v instanceof torch.Tensor) {
  16187. result.set(k, v);
  16188. }
  16189. }
  16190. }
  16191. return result;
  16192. }
  16193. });
  16194. this.registerType('torch.BufferDict', class {
  16195. constructor(mod) {
  16196. this._module = mod;
  16197. }
  16198. items() {
  16199. const result = new Map();
  16200. const type = this._module.type();
  16201. for (let i = 0; i < type.numAttributes(); i++) {
  16202. if (type.is_buffer(i)) {
  16203. const t = type.getAttribute(i);
  16204. if (t.isSubtypeOf(torch.TensorType.get())) {
  16205. const k = type.getAttributeName(i);
  16206. const v = this._module.__getattr__(k);
  16207. result.set(k, v);
  16208. }
  16209. }
  16210. }
  16211. return result;
  16212. }
  16213. });
  16214. this.registerType('torch._C.to_ir', class {
  16215. constructor(def, _resolver, self, method) {
  16216. this.method = method;
  16217. this.graph = method.graph();
  16218. this.resolver = _resolver;
  16219. this.integral_constants = new Map();
  16220. this.fp_constants = new Map();
  16221. this.complex_constants = new Map();
  16222. this.exit_blocks = new Set();
  16223. this._typeParser = new torch._C.ScriptTypeParser(this.resolver);
  16224. this._loop_status = 'NOT_IN_LOOP';
  16225. this.environment_stack = null;
  16226. this._def_stack = [];
  16227. this._temp_name_count = 0;
  16228. torch._C.AT_ASSERT(this.resolver);
  16229. this.pushFrame(this.graph.block(), true);
  16230. if (self && def && def.args.args.length === 0) {
  16231. throw new python.Error('Method must have a self argument.');
  16232. }
  16233. method.setSchema(this.emitDef(def, self, this.graph.block()));
  16234. // torch._C.ReplaceOldOperatorsWithUpgraders(this.graph);
  16235. torch._C.ConvertToSSA(this.graph);
  16236. torch._C.CanonicalizeModifiedLoops(this.graph);
  16237. torch._C.NormalizeOps(this.graph.block());
  16238. torch._C.runCleanupPasses(this.graph);
  16239. }
  16240. pushFrame(b, starts_def) {
  16241. starts_def = starts_def || false;
  16242. if (starts_def) {
  16243. this._def_stack.push({});
  16244. }
  16245. this.environment_stack = new torch._C.Environment(this.method, this.resolver, b, this.environment_stack);
  16246. }
  16247. popFrame(ends_def) {
  16248. const old_frame = this.environment_stack;
  16249. this.environment_stack = this.environment_stack.next;
  16250. if (ends_def) {
  16251. this._def_stack.pop();
  16252. }
  16253. return old_frame;
  16254. }
  16255. emitDef(def, self, block) {
  16256. const schema = this._typeParser.parseSchemaFromDef(def, self !== null);
  16257. if (schema.returns.length === 1) {
  16258. this._def_stack[this._def_stack.length - 1]._declared_return_type = schema.returns[0].type;
  16259. }
  16260. const args = this.emitFormalArguments(def, self, schema, block);
  16261. this.emitStatements(def.body);
  16262. this.handleMaybeNoReturn(def, block);
  16263. const returns = [this.emitOutput(def, schema, block)];
  16264. return new torch.FunctionSchema(def.name, '', args, returns);
  16265. }
  16266. emitFormalArguments(def, self, schema, block) {
  16267. const args = [];
  16268. const params = def.args.args;
  16269. const expected_annotation_size = self ? def.args.args.length - 1 : def.args.args.length;
  16270. if (schema.arguments.length !== expected_annotation_size) {
  16271. throw new python.Error('Invalid formal arguments.');
  16272. }
  16273. let it = 0;
  16274. if (self) {
  16275. const param = params[it];
  16276. const name = param.arg;
  16277. const new_input = block.addInput().setDebugName(name);
  16278. this.environment_stack.setSugaredVar(param.range(), name, self.makeSugared(new_input), null);
  16279. args.push(new torch.Argument(name, new_input.type()));
  16280. it++;
  16281. }
  16282. const shouldDeriveType = this.shouldDeriveSetStateType(def, schema);
  16283. let arg_annotation_idx = 0;
  16284. for (; it < params.length; it++) {
  16285. const param = params[it];
  16286. const name = param.arg;
  16287. const new_input = block.addInput();
  16288. if (torch._C.meaningfulName(name)) {
  16289. new_input.setDebugName(name);
  16290. }
  16291. let arg = schema.arguments[arg_annotation_idx++];
  16292. if (shouldDeriveType) {
  16293. if (schema.arguments.length === 1) {
  16294. throw new python.Error('Invalid schema.');
  16295. }
  16296. const inferredStateType = this.getTypeForSetStateArg(def, self);
  16297. arg = arg.cloneWithType(inferredStateType);
  16298. }
  16299. args.push(arg);
  16300. new_input.setType(arg.type);
  16301. this.environment_stack.setVar(param.range(), name, new_input);
  16302. }
  16303. return args;
  16304. }
  16305. emitOutput(range, schema, block) {
  16306. const ret_type = this._def_stack[this._def_stack.length - 1]._merged_return_type;
  16307. const placeholder_return = this.graph.insertNode(this.graph.createUninitialized(ret_type)).output();
  16308. block.registerOutput(placeholder_return);
  16309. return new torch.Argument('', this._def_stack[this._def_stack.length - 1]._merged_return_type);
  16310. }
  16311. emitStatements(stmts) {
  16312. for (let i = 0; i < stmts.length; i++) {
  16313. const stmt = stmts[i];
  16314. if (stmt instanceof ast.If) {
  16315. this.emitIf(stmt);
  16316. } else if (stmt instanceof ast.While) {
  16317. this.emitWhile(stmt);
  16318. } else if (stmt instanceof ast.For) {
  16319. this.emitFor(stmt);
  16320. } else if (stmt instanceof ast.Assign) {
  16321. this.emitAssignment(stmt);
  16322. } else if (stmt instanceof ast.AnnAssign) {
  16323. this.emitAssignment(stmt);
  16324. } else if (stmt instanceof ast.Expr) {
  16325. this.emitSugaredExpr(stmt.value, 0);
  16326. } else if (stmt instanceof ast.Return) {
  16327. this.emitReturn(stmt);
  16328. } else if (stmt instanceof ast.Pass) {
  16329. // pass
  16330. } else if (stmt instanceof ast.With) {
  16331. this.emitWith(stmt);
  16332. } else {
  16333. throw new python.Error(`Unrecognized statement kind '${stmt.__class__.__name__}'.`);
  16334. }
  16335. if (this.exit_blocks.has(this.environment_stack.block())) {
  16336. return;
  16337. }
  16338. }
  16339. }
  16340. emitWith(stmt) {
  16341. const targets = stmt.items;
  16342. const entered = [];
  16343. for (const target of targets) {
  16344. const e = target.context_expr;
  16345. const rhs = this.emitExpr(e);
  16346. const n = this.graph.insertNode(this.graph.create('prim::Enter', [rhs]));
  16347. entered.push(rhs);
  16348. if (rhs.type() instanceof torch.ClassType === false) {
  16349. throw new python.Error('With item expression must return an object.');
  16350. }
  16351. const rhsClass = rhs.type();
  16352. const enterMethod = rhsClass.findMethod('__enter__');
  16353. const exitMethod = rhsClass.findMethod('__exit__');
  16354. if (!enterMethod || !exitMethod) {
  16355. throw new python.Error('Object returned by with item expression does not define __enter__ and __exit__ methods.');
  16356. }
  16357. const enterSchema = enterMethod.getSchema();
  16358. if (enterSchema.arguments.length !== 1) {
  16359. throw new python.Error('__enter__ must have only one argument and one return value.');
  16360. }
  16361. const exitSchema = exitMethod.getSchema();
  16362. if (exitSchema.arguments.length === 4) {
  16363. for (let i = 1; i < 4; i++) {
  16364. if (exitSchema.arguments[i].type !== torch.AnyType.get()) {
  16365. throw new python.Error('Argument of __exit__ must have Any type.');
  16366. }
  16367. }
  16368. } else {
  16369. throw new python.Error('__exit__ must have four arguments');
  16370. }
  16371. n.output(0).setType(enterSchema.returns[0].type);
  16372. if (target.optional_vars) {
  16373. throw new python.Error('Not implemented.');
  16374. // Var i = target.var().get();
  16375. // this.environment_stack.setVar(i.range(), i.name().name(), n.output(0));
  16376. }
  16377. }
  16378. this.emitStatements(stmt.body);
  16379. while (entered.length > 0) {
  16380. const input = entered.pop();
  16381. const n = this.graph.create('prim::Exit');
  16382. this.graph.insertNode(n);
  16383. n.addInput(input);
  16384. }
  16385. }
  16386. emitLoopCommon(range, emit_body, iter_val, targets, cond) {
  16387. let max_trip_count_val = null;
  16388. if (iter_val === null) {
  16389. max_trip_count_val = torch._C.materializeConstant(Number.MAX_SAFE_INTEGER /*std::numeric_limits<int64_t>::max()*/, this.graph, range, this.integral_constants);
  16390. } else {
  16391. max_trip_count_val = iter_val.len(range, this.method);
  16392. }
  16393. const n = this.graph.insertNode(this.create('prim::Loop', range, 0));
  16394. const body_block = n.addBlock();
  16395. {
  16396. const condition_block = n.addBlock();
  16397. this.pushFrame(condition_block);
  16398. let out = null;
  16399. if (cond) {
  16400. const insert = new torch._C.WithInsertPoint(condition_block);
  16401. out = this.emitToBool(cond.range(), this.emitExpr(cond));
  16402. insert.dispose();
  16403. } else {
  16404. const insert = new torch._C.WithInsertPoint(n);
  16405. out = this.graph.insertConstant(true, range);
  16406. insert.dispose();
  16407. }
  16408. condition_block.registerOutput(out);
  16409. this.popFrame();
  16410. }
  16411. n.addInput(max_trip_count_val);
  16412. const loop_guard = new torch._C.WithLoopStatus(this, 'IN_LOOP');
  16413. const trip_count = body_block.addInput().setType(torch.IntType.get());
  16414. {
  16415. this.pushFrame(body_block);
  16416. const guard = new torch._C.WithInsertPoint(body_block);
  16417. if (iter_val !== null && targets) {
  16418. const cur_elem = iter_val.getitem(range, this.method, trip_count).asValue(range, this.method);
  16419. const sv = new torch._C.SimpleValue(cur_elem);
  16420. const target_exprs = targets;
  16421. this.validateAssignLhsExpr(target_exprs, range);
  16422. if (target_exprs.length > 1) {
  16423. throw new python.Error('Not implemented.');
  16424. // const tl = torch.TupleLiteral.create(range, target_exprs);
  16425. // target_exprs = ListExpr.create(range, [tl]);
  16426. }
  16427. this.emitExprsAssign(target_exprs, [sv], range, /*n_binders=*/1);
  16428. }
  16429. emit_body();
  16430. this.popFrame();
  16431. guard.dispose();
  16432. }
  16433. loop_guard.dispose();
  16434. }
  16435. emitFor(...args) {
  16436. if (args.length === 1 && args[0] instanceof ast.For) {
  16437. const [stmt] = args;
  16438. const emit_body = () => this.emitStatements(stmt.body);
  16439. this.emitFor(stmt.target, stmt.iter, stmt.range(), emit_body);
  16440. } else if (args.length === 4) {
  16441. const [targets, itrs, loc, emit_body] = args;
  16442. if (itrs instanceof ast.Tuple) {
  16443. throw new python.Error('List of iterables is not supported currently.');
  16444. }
  16445. const sv = this.emitSugaredExpr(itrs, 1);
  16446. const iterable = sv.iter(loc, this.method);
  16447. if (iterable.shouldEmitUnrolled()) {
  16448. this.emitUnrolledLoop(loc, emit_body, iterable, targets);
  16449. } else {
  16450. this.emitLoopCommon(loc, emit_body, iterable, [targets], null);
  16451. }
  16452. } else {
  16453. throw new python.Error('Not implemented.');
  16454. }
  16455. }
  16456. emitWhile(stmt) {
  16457. const cond = stmt.test;
  16458. const emit_body = () => this.emitStatements(stmt.body);
  16459. this.emitLoopCommon(stmt.range(), emit_body, null, [], cond);
  16460. }
  16461. emitIsInstance(obj, classinfo) {
  16462. const lhs_val = this.emitExpr(obj);
  16463. const lhs_types = [];
  16464. const rhs_types = [];
  16465. const gather_rhs = (expr) => {
  16466. if (expr instanceof ast.Tuple) {
  16467. for (const e of expr.elts) {
  16468. gather_rhs(e);
  16469. }
  16470. return;
  16471. }
  16472. const type = this._typeParser.parseTypeFromExpr(expr);
  16473. rhs_types.push(type);
  16474. };
  16475. lhs_types.push(lhs_val.type());
  16476. gather_rhs(classinfo);
  16477. torch._C.standardizeVectorForUnion(lhs_types);
  16478. torch._C.standardizeVectorForUnion(rhs_types);
  16479. let refinement = new torch._C.RefinementSet([], []);
  16480. let unified_true = null;
  16481. let unified_false = null;
  16482. const isinstance_types = [];
  16483. const not_isinstance_types = [];
  16484. let true_refinements = [];
  16485. let false_refinements = [];
  16486. let all_lhs_subtype_some_rhs = true;
  16487. for (const lhs_type of lhs_types) {
  16488. if (lhs_type === torch.AnyType.get()) {
  16489. isinstance_types.push(...rhs_types);
  16490. not_isinstance_types.push(torch.AnyType.get());
  16491. if (isinstance_types.length !== 1 || isinstance_types[0] !== torch.AnyType.get()) {
  16492. all_lhs_subtype_some_rhs = false;
  16493. }
  16494. break;
  16495. }
  16496. const get_smaller_type = (t1, t2) => {
  16497. if (t1.isSubtypeOf(t2)) {
  16498. return t1;
  16499. } else if (t2.isSubtypeOf(t1)) {
  16500. return t2;
  16501. }
  16502. return null;
  16503. };
  16504. let found_refinement = null;
  16505. for (const rhs_type of rhs_types) {
  16506. const maybe_smaller_type = get_smaller_type(lhs_type, rhs_type);
  16507. if (!maybe_smaller_type) {
  16508. continue;
  16509. } else if (maybe_smaller_type === lhs_type) {
  16510. found_refinement = lhs_type;
  16511. } else if (maybe_smaller_type === rhs_type) {
  16512. found_refinement = found_refinement ? torch._C.unifyTypes(found_refinement, rhs_type) : rhs_type;
  16513. }
  16514. }
  16515. if (found_refinement) {
  16516. if (found_refinement === lhs_type) {
  16517. all_lhs_subtype_some_rhs &= true;
  16518. }
  16519. isinstance_types.push(found_refinement);
  16520. } else {
  16521. not_isinstance_types.push(lhs_type);
  16522. all_lhs_subtype_some_rhs = false;
  16523. }
  16524. }
  16525. if (isinstance_types.length > 0) {
  16526. unified_true = torch._C.unifyTypeList(isinstance_types, null, /*default_to_union=*/true);
  16527. }
  16528. if (obj instanceof ast.Name && unified_true) {
  16529. const ident = obj.id;
  16530. true_refinements = [new torch._C.Refinement(ident, unified_true)];
  16531. }
  16532. if (not_isinstance_types.length > 0) {
  16533. unified_false = torch._C.unifyTypeList(not_isinstance_types, null, /*default_to_union=*/true);
  16534. }
  16535. if (obj instanceof ast.Name && unified_false) {
  16536. const ident = obj.id;
  16537. false_refinements = [new torch._C.Refinement(ident, unified_false)];
  16538. }
  16539. refinement = new torch._C.RefinementSet(true_refinements, false_refinements);
  16540. const is_statically_false = isinstance_types.length === 0;
  16541. if (all_lhs_subtype_some_rhs) {
  16542. return new torch._C.CondValue(this.graph, obj.range(), true, refinement);
  16543. }
  16544. if (is_statically_false) {
  16545. return new torch._C.CondValue(this.graph, obj.range(), false, refinement);
  16546. }
  16547. const result = this.graph.insertNode(this.graph.createIsInstance(lhs_val, rhs_types)).output();
  16548. return new torch._C.CondValue(result, refinement, null);
  16549. }
  16550. emitIf(stmt) {
  16551. const cond_value = this.emitCondExpr(stmt.test);
  16552. this.emitIfElseBlocks(stmt.range(), cond_value, stmt.body, stmt.orelse);
  16553. }
  16554. emitCondExpr(expr) {
  16555. /*
  16556. switch (expr.kind()) {
  16557. case TK_AND:
  16558. case TK_OR: {
  16559. const binop = BinOp(expr);
  16560. return emitShortCircuitLogical(
  16561. binop.range(), binop.lhs(), binop.rhs(), expr.kind() == TK_OR);
  16562. }
  16563. case TK_NOT: {
  16564. CondValue v = emitCondExpr(Expr(expr.tree().trees()[0]));
  16565. Value* result = emitBuiltinCall(
  16566. expr.range(), *graph, aten::__not__, {v.value()}, {});
  16567. std::optional<bool> static_if;
  16568. if (v.staticIf()) {
  16569. static_if = !*v.staticIf();
  16570. }
  16571. return CondValue(result, v.refinements().Not(), static_if);
  16572. } break;
  16573. case TK_IS:
  16574. case TK_ISNOT: {
  16575. // meta programming on AST for is/is not cases and emit branches base on
  16576. const cond_op = BinOp(expr);
  16577. Value* lhs_val = emitExpr(cond_op.lhs());
  16578. Value* rhs_val = emitExpr(cond_op.rhs());
  16579. const lhs_none = canBeNone(lhs_val);
  16580. const rhs_none = canBeNone(rhs_val);
  16581. // Dispatch logic (A: ALWAYS, N: NEVER, M: MAYBE):
  16582. // AA, -> statically IS always holds, IS_NOT never holds
  16583. // AN , NA-> statically IS_NOT always holds, IS never holds
  16584. // MA, MM, MN, NM, NN, AM -> cannot prove anything statically
  16585. bool its_is = expr.kind() == TK_IS;
  16586. if (lhs_none == ALWAYS && rhs_none == ALWAYS) {
  16587. return CondValue(*graph, expr.range(), its_is, {});
  16588. } else if (
  16589. (lhs_none == ALWAYS && rhs_none == NEVER) ||
  16590. (lhs_none == NEVER && rhs_none == ALWAYS)) {
  16591. // lhs_val/rhs_val with A/M: only emit never_none_branch
  16592. return CondValue(*graph, expr.range(), !its_is, {});
  16593. } else {
  16594. const kind = getNodeKind(expr.kind(), expr.get()->trees().size());
  16595. Value* cond_value = emitBuiltinCall(
  16596. expr.get()->range(),
  16597. *method.graph(),
  16598. kind,
  16599. {lhs_val, rhs_val},
  16600. {});
  16601. const refinements = RefinementSet(findIsNoneRefinements(
  16602. cond_op.lhs(), lhs_val, cond_op.rhs(), rhs_val, expr.kind()));
  16603. return CondValue(cond_value, refinements, null);
  16604. }
  16605. } break;
  16606. */
  16607. if (expr instanceof ast.UnaryOp) {
  16608. throw new python.Error('Not implemented.');
  16609. }
  16610. if (expr instanceof ast.Call) {
  16611. const apply = expr;
  16612. const callee = expr.func;
  16613. if (callee instanceof ast.Name) {
  16614. if (callee.id === 'isinstance') {
  16615. this.checkApplyNumInputs(apply, 2);
  16616. return this.emitIsInstance(apply.args[0], apply.args[1]);
  16617. }
  16618. if (callee.id === 'hasattr') {
  16619. this.checkApplyNumInputs(apply, 2);
  16620. return this.emitHasAttr(apply.args[0], apply.args[1]);
  16621. }
  16622. const sv = this.emitSugaredExpr(callee, 1);
  16623. if (sv instanceof torch._C.SpecialFormValue) {
  16624. if (sv.form() === 'prim::isinstance') {
  16625. this.checkApplyNumInputs(apply, 2);
  16626. return this.emitIsInstance(apply.inputs()[0], apply.inputs()[1]);
  16627. }
  16628. }
  16629. }
  16630. }
  16631. const expr_out = this.emitToBool(expr, this.emitExpr(expr));
  16632. let static_if = null;
  16633. const kind = expr_out.node().kind();
  16634. if (kind === 'aten::is_scripting') {
  16635. static_if = true;
  16636. } else if (kind === 'aten::has_torch_function') {
  16637. static_if = false;
  16638. }
  16639. const maybe_ivalue = torch._C.toIValue(expr_out);
  16640. if (maybe_ivalue) {
  16641. static_if = maybe_ivalue.toBool();
  16642. }
  16643. return new torch._C.CondValue(expr_out, new torch._C.RefinementSet([], []), static_if);
  16644. }
  16645. emitIfElseBlocks(loc, cond_value, trueBranch, falseBranch) {
  16646. if (cond_value.staticIf() !== null) {
  16647. if (cond_value.staticIf()) {
  16648. this.insertRefinements(loc, cond_value.refinements());
  16649. this.emitStatements(trueBranch);
  16650. } else {
  16651. this.insertRefinements(loc, cond_value.refinements().Not());
  16652. this.emitStatements(falseBranch);
  16653. }
  16654. return;
  16655. }
  16656. const n = this.graph.insertNode(this.create('prim::If', loc, 0));
  16657. n.addInput(cond_value.value());
  16658. const true_block = n.addBlock();
  16659. const false_block = n.addBlock();
  16660. const save_true = this.emitSingleIfBranch(true_block, trueBranch, cond_value.refinements());
  16661. const save_false = this.emitSingleIfBranch(false_block, falseBranch, cond_value.refinements().Not());
  16662. const true_exits = this.exit_blocks.has(true_block);
  16663. const false_exits = this.exit_blocks.has(false_block);
  16664. if (true_exits && false_exits) {
  16665. this.exit_blocks.add(n.owningBlock());
  16666. }
  16667. const mutated_variables = new Set();
  16668. for (const v of save_true.definedVariables()) {
  16669. const insert = new torch._C.WithInsertPoint(false_block);
  16670. if (save_false.findInAnyFrame(v) || false_exits) {
  16671. mutated_variables.add(v);
  16672. } else {
  16673. this.environment_stack.setVariableTypeError(v, () => 'Value is not defined in the false branch.');
  16674. }
  16675. insert.dispose();
  16676. }
  16677. for (const v of save_false.definedVariables()) {
  16678. const insert = new torch._C.WithInsertPoint(true_block);
  16679. if (save_true.findInAnyFrame(v) || true_exits) {
  16680. mutated_variables.add(v);
  16681. } else {
  16682. this.environment_stack.setVariableTypeError(v, () => 'Value is not defined in the true branch.');
  16683. }
  16684. insert.dispose();
  16685. }
  16686. for (const x of mutated_variables) {
  16687. let tv = null;
  16688. let fv = null;
  16689. {
  16690. const insert = new torch._C.WithInsertPoint(true_block);
  16691. if (!true_exits) {
  16692. tv = save_true.getVar(x, loc);
  16693. }
  16694. insert.dispose();
  16695. }
  16696. {
  16697. const insert = new torch._C.WithInsertPoint(false_block);
  16698. if (!false_exits) {
  16699. fv = save_false.getVar(x, loc);
  16700. }
  16701. insert.dispose();
  16702. }
  16703. if (true_exits && false_exits) {
  16704. continue;
  16705. } else if (true_exits) {
  16706. tv = this.graph.createUninitialized(fv.type()).insertBefore(true_block.return_node()).output();
  16707. this.graph.createStore(x, tv).insertBefore(true_block.return_node());
  16708. } else if (false_exits) {
  16709. fv = this.graph.createUninitialized(tv.type()).insertBefore(false_block.return_node()).output();
  16710. this.graph.createStore(x, fv).insertBefore(false_block.return_node());
  16711. }
  16712. const maybe_sugared_x = this.environment_stack.findInAnyFrame(x);
  16713. let full_type = null;
  16714. if (maybe_sugared_x) {
  16715. const maybe_simple = torch._C.asSimple(maybe_sugared_x);
  16716. if (maybe_simple) {
  16717. full_type = maybe_simple.type();
  16718. }
  16719. }
  16720. const default_to_union = full_type && (full_type instanceof torch.UnionType || full_type instanceof torch.OptionalType || full_type instanceof torch.NumberType);
  16721. const unified = torch._C.unifyTypes(tv.type(), fv.type(), /*default_to_union=*/default_to_union);
  16722. if (!unified) {
  16723. if (save_true.findInParentFrame(x) || save_false.findInParentFrame(x)) {
  16724. throw new python.Error('Type mismatch.');
  16725. } else {
  16726. this.environment_stack.setVariableTypeError(x, () => 'Type mismatch.');
  16727. continue;
  16728. }
  16729. }
  16730. this.environment_stack.setType(x, unified);
  16731. }
  16732. }
  16733. emitSingleIfBranch(b, branch, refinements) {
  16734. this.pushFrame(b);
  16735. const guard = new torch._C.WithInsertPoint(b);
  16736. this.insertRefinements(branch, refinements);
  16737. this.emitStatements(branch);
  16738. const frame = this.popFrame();
  16739. guard.dispose();
  16740. return frame;
  16741. }
  16742. create(kind, loc, n_outputs) {
  16743. return this.graph.create(kind, n_outputs).setSourceRange(loc);
  16744. }
  16745. refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint_ptr, all_candidates, match_repr, src, type_match, do_if_match, do_if_anytype, is_dict_constructor) {
  16746. is_dict_constructor = is_dict_constructor || false;
  16747. if (refined_type_hint_ptr._ instanceof torch.UnionType) {
  16748. const candidate_types = refined_type_hint_ptr._.containedTypes().filter((type_ptr) => type_match(type_ptr));
  16749. if (!is_dict_constructor && candidate_types.length === 0) {
  16750. throw new python.Error("No matching types found in Union type annotation.");
  16751. } else if (candidate_types.length === 1) {
  16752. [refined_type_hint_ptr._] = candidate_types;
  16753. } else {
  16754. all_candidates._ = candidate_types;
  16755. }
  16756. } else if (refined_type_hint_ptr._ instanceof torch.OptionalType) {
  16757. refined_type_hint_ptr._ = refined_type_hint_ptr._.getElementType();
  16758. }
  16759. if (is_dict_constructor) {
  16760. return;
  16761. }
  16762. if (all_candidates._.length === 0) {
  16763. if (type_match(refined_type_hint_ptr._)) {
  16764. do_if_match();
  16765. } else if (refined_type_hint_ptr._.kind() === 'AnyType') {
  16766. do_if_anytype();
  16767. } else {
  16768. throw new python.Error('Invalid annotation type.');
  16769. }
  16770. }
  16771. }
  16772. emitToBool(loc, v) {
  16773. let out = null;
  16774. const bool_cast = this.environment_stack.getSugaredVar('bool', loc);
  16775. out = torch._C.asSimple(bool_cast.call(loc, this.method, [new torch._C.NamedValue(v)], [], 0));
  16776. if (!out) {
  16777. throw new python.Error('Could not cast value to bool.');
  16778. }
  16779. if (!out.type().isSubtypeOf(torch.BoolType.get())) {
  16780. throw new python.Error('Expected a bool expression for condition.');
  16781. }
  16782. return out;
  16783. }
  16784. emitUnaryOp(tree, magicMethod, opSymbol) {
  16785. const inputs = [tree.operand];
  16786. const named_values = this.getNamedValues(inputs, /*maybe_unpack=*/false);
  16787. const val = torch._C.asSimple(torch._C.makeMagic(magicMethod, new torch._C.BuiltinFunction(opSymbol, null)).call(tree.range(), this.method, named_values, [], 0));
  16788. if (val.node().kind() !== opSymbol) {
  16789. return val;
  16790. }
  16791. const maybe_out_stack = torch._C.runNodeIfInputsAreConstant(val.node());
  16792. if (!maybe_out_stack) {
  16793. return val;
  16794. }
  16795. torch._C.TORCH_INTERNAL_ASSERT(maybe_out_stack.length === 1);
  16796. return this.graph.insertConstant(maybe_out_stack[0], tree);
  16797. }
  16798. emitAssignment(stmt) {
  16799. if (stmt instanceof ast.AnnAssign) {
  16800. return this.emitSingleAssignment(stmt);
  16801. }
  16802. if (stmt.targets.length === 1) {
  16803. const entries = Object.entries(stmt).filter(([key]) => key !== 'targets' && key !== 'value' && key !== 'ctx');
  16804. const assign = new ast.AnnAssign(stmt.targets[0], null, stmt.value, stmt.targets[0] instanceof ast.Name);
  16805. for (const [key, value] of entries) {
  16806. assign[key] = value;
  16807. }
  16808. return this.emitSingleAssignment(assign);
  16809. }
  16810. if (stmt.targets.length <= 1) {
  16811. throw new python.Error('Invalid assignment.');
  16812. }
  16813. throw new python.Error('Not implemented.');
  16814. /*
  16815. const tmp_name = this.createTempName('$tmp_assign_');
  16816. this.environment_stack.setSugaredVar(stmt.value, tmp_name, this.emitSugaredExpr(stmt.value, 1), annotated_type=null);
  16817. const ident = new ast.Name(tmp_name);
  16818. for (const expr of lhs_list) {
  16819. const assign = new ast.Assign(targets, value, ctx);
  16820. this.emitSingleAssignment(Assign.create(stmt,
  16821. List<Expr>.create(expr.range(), [expr]),
  16822. Maybe<Expr>::create(stmt.rhs().range(), ident),
  16823. Maybe<Expr>::create(stmt.range())));
  16824. }
  16825. */
  16826. }
  16827. emitSingleAssignment(stmt) {
  16828. torch._C.AT_ASSERT(stmt instanceof ast.AnnAssign);
  16829. const rhs = stmt.value;
  16830. const lhs = stmt.target;
  16831. if (lhs instanceof ast.Name) {
  16832. let type = null;
  16833. if (stmt.annotation) {
  16834. type = this._typeParser.parseTypeFromExpr(stmt.annotation);
  16835. }
  16836. const rhs_sugared_val = this.emitSugaredExpr(rhs, 1, type);
  16837. // BC HACK
  16838. this.environment_stack.setSugaredVar(stmt.range(), lhs.id, rhs_sugared_val, /*annotated_type=*/type);
  16839. } else if (lhs instanceof ast.Tuple) {
  16840. this.emitTupleAssign(lhs, rhs);
  16841. } else if (lhs instanceof ast.Attribute) {
  16842. this.emitSelectAssign(lhs, rhs, null, stmt.range());
  16843. } else {
  16844. throw new python.Error('Unexpected expression on left-hand side of assignment.');
  16845. }
  16846. }
  16847. emitSelectAssign(lhs, rhs, type, loc) {
  16848. if (!rhs) {
  16849. throw new python.Error('Expected RHS for assignment.');
  16850. }
  16851. let type_hint = null;
  16852. if (type) {
  16853. type_hint = this._typeParser.parseTypeFromExpr(type);
  16854. }
  16855. const lhsObject = this.emitSugaredExpr(lhs.value, 1);
  16856. const rhsValue = this.emitSugaredExpr(rhs, 1, type_hint).asValue(rhs.range(), this.method);
  16857. lhsObject.setAttr(loc, this.method, lhs.attr, rhsValue);
  16858. }
  16859. emitTupleAssign(...args) {
  16860. if (args.length === 2) {
  16861. const [tl, rhs] = args;
  16862. let n_binders = tl.elts.length;
  16863. const starred_unpack = this.validateAssignLhsExpr(tl.elts, tl);
  16864. if (starred_unpack) {
  16865. n_binders--;
  16866. }
  16867. const output = this.emitSugaredExpr(rhs, n_binders);
  16868. this.emitTupleAssign(tl, output, rhs.range(), n_binders, starred_unpack);
  16869. } else if (args.length === 5) {
  16870. const [tl, rhs_output, rhs_loc, n_binders, starred_unpack] = args;
  16871. const outputs = rhs_output.asTuple(rhs_loc, this.method, starred_unpack ? null : n_binders);
  16872. if (outputs.length < n_binders) {
  16873. throw new python.Error('Not enough values to unpack.');
  16874. }
  16875. if (outputs.length > n_binders && !starred_unpack) {
  16876. throw new python.Error('Too many values to unpack.');
  16877. }
  16878. this.emitExprsAssign(tl.elts, outputs, rhs_loc, n_binders);
  16879. } else {
  16880. throw new python.Error('Not implemented.');
  16881. }
  16882. }
  16883. emitExprsAssign(lhs_exprs, outputs /*, rhs_loc, n_binders */) {
  16884. let i = 0;
  16885. for (const assignee of lhs_exprs) {
  16886. if (assignee instanceof ast.Subscript) {
  16887. throw new python.Error('Not implemented.');
  16888. /*
  16889. this.emitSubscriptAssign(
  16890. rhs_loc,
  16891. Subscript(assignee),
  16892. NamedValue(rhs_loc, outputs.at(i).asValue(rhs_loc, method)));
  16893. i++;
  16894. */
  16895. } else if (assignee instanceof ast.Name) {
  16896. this.environment_stack.setSugaredVar(assignee.range(), assignee.id, outputs[i], /*annotated_type=*/null);
  16897. i++;
  16898. } else if (assignee instanceof ast.Starred) {
  16899. throw new python.Error('Not implemented.');
  16900. /*
  16901. const var = Starred(assignee).expr();
  16902. if (var.kind() != TK_VAR) {
  16903. throw(
  16904. ErrorReport(var) << 'Cannot pack a tuple into a non-variable');
  16905. }
  16906. size_t n_matched = outputs.size() - n_binders;
  16907. ArrayRef<std::shared_ptr<SugaredValue>> outputs_ref = outputs;
  16908. const values = fmap(
  16909. outputs_ref.slice(i, n_matched),
  16910. [&](const std::shared_ptr<SugaredValue>& v) {
  16911. return v.asValue(assignee.range(), method);
  16912. });
  16913. const tup = graph.insertNode(graph.createTuple(values)).output();
  16914. environment_stack.setVar(var.range(), Var(var).name().name(), tup);
  16915. i += n_matched;
  16916. */
  16917. } else if (assignee instanceof ast.Tuple) {
  16918. throw new python.Error('Not implemented.');
  16919. /*
  16920. // recursively emit tuple assignments on tuple literal input
  16921. TupleLiteral sub_tl = TupleLiteral(assignee);
  16922. size_t sub_n_binders = sub_tl.inputs().length;
  16923. bool sub_starred_unpack =
  16924. validateAssignLhsExpr(sub_tl.inputs(), sub_tl.range());
  16925. if (sub_starred_unpack)
  16926. sub_n_binders--;
  16927. emitTupleAssign(
  16928. sub_tl,
  16929. outputs.at(i),
  16930. rhs_loc,
  16931. sub_n_binders,
  16932. sub_starred_unpack);
  16933. i++;
  16934. */
  16935. } else if (assignee instanceof ast.Attribute) {
  16936. throw new python.Error('Not implemented.');
  16937. /*
  16938. emitSelectAssign(assignee, outputs.at(i), rhs_loc);
  16939. i++;
  16940. */
  16941. } else {
  16942. throw new python.Error('Unexpected expression on left-hand side of assignment.');
  16943. }
  16944. }
  16945. }
  16946. emitReturn(stmt) {
  16947. let declared_return_type = this._def_stack[this._def_stack.length - 1]._declared_return_type;
  16948. let actual_return = this.emitExpr(stmt.value, declared_return_type);
  16949. if (declared_return_type) {
  16950. if (!(actual_return.type().isSubtypeOf(torch.TensorType.get()) && actual_return.type().isSubtypeOf(torch.NoneType.get()))) {
  16951. actual_return = torch._C.tryConvertToType(stmt, this.graph, declared_return_type, actual_return, /*allow_conversions=*/true);
  16952. }
  16953. if (!actual_return.type().isSubtypeOf(declared_return_type)) {
  16954. throw new python.Error(`Invalid return type.`);
  16955. }
  16956. } else {
  16957. declared_return_type = this._def_stack[this._def_stack.length - 1]._merged_return_type;
  16958. if (!declared_return_type) {
  16959. declared_return_type = actual_return.type();
  16960. }
  16961. const merged_return_type = torch._C.unifyTypes(declared_return_type, actual_return.type());
  16962. if (!merged_return_type) {
  16963. throw new python.Error(`Invalid return type.`);
  16964. }
  16965. declared_return_type = merged_return_type;
  16966. }
  16967. this._def_stack[this._def_stack.length - 1]._merged_return_type = declared_return_type;
  16968. if (declared_return_type === torch.AnyType.get() && actual_return.type() !== torch.AnyType.get()) {
  16969. actual_return = this.graph.insertUncheckedCast(actual_return, declared_return_type);
  16970. }
  16971. this.graph.insertNode(this.graph.create('prim::ReturnStmt', [actual_return], 0));
  16972. this.exit_blocks.add(this.environment_stack.block());
  16973. }
  16974. getNamedValues(trees, maybe_unpack) {
  16975. const values = [];
  16976. for (const tree of trees) {
  16977. if (maybe_unpack && tree instanceof ast.Starred) {
  16978. throw new python.Error('Starred argument not supported.');
  16979. } else {
  16980. values.push(new torch._C.NamedValue(this.emitExpr(tree)));
  16981. }
  16982. }
  16983. return values;
  16984. }
  16985. getValues(trees, maybe_unpack) {
  16986. return this.getNamedValues(trees, maybe_unpack).map((value) => value.value(this.graph));
  16987. }
  16988. emitExpr(tree, type_hint) {
  16989. type_hint = type_hint || null;
  16990. let out_val = this.emitSugaredExpr(tree, 1, type_hint).asValue(tree, this.method);
  16991. if (type_hint === torch.AnyType.get() && out_val.type() !== torch.AnyType.get()) {
  16992. out_val = this.graph.insertUncheckedCast(out_val, type_hint);
  16993. }
  16994. return out_val;
  16995. }
  16996. emitSugaredExpr(tree, n_binders, type_hint) {
  16997. if (tree instanceof ast.Name) { // TK_VAR
  16998. return this.environment_stack.getSugaredVar(tree.id);
  16999. } else if (tree instanceof ast.Attribute) {
  17000. const sv = this.emitSugaredExpr(tree.value, 1);
  17001. return sv.attr(tree.range(), this.method, tree.attr);
  17002. } else if (tree instanceof ast.Call) { // TK_APPLY
  17003. return this.emitApplyExpr(tree, n_binders, type_hint);
  17004. } if (tree instanceof ast.Subscript) {
  17005. return this.emitSubscript(tree, type_hint);
  17006. }
  17007. return new torch._C.SimpleValue(this.emitSimpleExpr(tree, type_hint));
  17008. }
  17009. emitApplyExpr(apply, n_binders, type_hint) {
  17010. type_hint = type_hint || null;
  17011. const sv = this.emitSugaredExpr(apply.func, 1);
  17012. const loc = apply.func.range();
  17013. if (sv instanceof torch._C.SpecialFormValue) {
  17014. return this.emitApplySpecialForm(sv.form(), apply, sv, type_hint);
  17015. }
  17016. const args = this.getNamedValues(apply.args, true);
  17017. const kwargs = this.emitAttributes(apply.keywords);
  17018. return sv.call(loc, this.method, args, kwargs, n_binders);
  17019. }
  17020. emitAttributes(attributes) {
  17021. return attributes.map((attr) => new torch._C.NamedValue(attr.range(), attr.arg, this.emitExpr(attr.value)));
  17022. }
  17023. emitApplySpecialForm(form, apply, sv, type_hint) {
  17024. switch (form) {
  17025. case 'prim::fork': {
  17026. throw new python.Error('Not implemented.');
  17027. }
  17028. case 'prim::awaitable': {
  17029. throw new python.Error('Not implemented.');
  17030. }
  17031. case 'prim::annotate': {
  17032. this.checkApplyNumInputs(apply, 2);
  17033. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  17034. let expr = torch._C.tryConvertToType(apply.range(), this.graph, type, this.emitExpr(apply.args[1], type), /*allow_conversions=*/true);
  17035. if (!expr.type().isSubtypeOf(type)) {
  17036. throw new python.Error('Invalid expression type.');
  17037. }
  17038. if ((type instanceof torch.OptionalType || (type instanceof torch.UnionType && type.expect(torch.UnionType).canHoldType(torch.NoneType.get()))) && expr.type().isSubtypeOf(torch.NoneType.get())) {
  17039. const none = this.graph.createNone();
  17040. none.output().setType(type);
  17041. this.graph.insertNode(none);
  17042. expr = none.output();
  17043. }
  17044. return new torch._C.SimpleValue(expr);
  17045. }
  17046. case 'prim::unchecked_cast': {
  17047. this.checkApplyNumInputs(apply, 2);
  17048. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  17049. let v = this.emitExpr(apply.args[1]);
  17050. if (v.node().kind() !== 'prim::unchecked_cast' || v.type() !== type) {
  17051. v = this.graph.insertUncheckedCast(v, type);
  17052. }
  17053. return new torch._C.SimpleValue(v);
  17054. }
  17055. case 'prim::GetAttr': {
  17056. this.checkApplyNumInputsRange(apply, 2, 3);
  17057. const obj = this.emitSugaredExpr(apply.args[0], 1);
  17058. if (apply.args[1] instanceof ast.Constant === false || typeof apply.args[1].value !== 'string') {
  17059. throw new python.Error('Invalid argument.');
  17060. }
  17061. const name = apply.args[1].value;
  17062. if (apply.args.length === 2) {
  17063. return obj.attr(apply, this.method, name);
  17064. } else if (obj.hasAttr(apply, this.method, name)) {
  17065. return obj.attr(apply, this.method, name);
  17066. }
  17067. return this.emitSugaredExpr(apply.inputs()[2], 1);
  17068. }
  17069. case 'prim::Uninitialized': {
  17070. this.checkApplyNumInputs(apply, 1);
  17071. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  17072. const out = this.graph.insertNode(this.graph.createUninitialized(type)).setSourceRange(apply.range());
  17073. return new torch._C.SimpleValue(out.output());
  17074. }
  17075. case 'prim::TupleConstruct': {
  17076. throw new python.Error('Not implemented.');
  17077. }
  17078. case 'prim::isinstance': {
  17079. this.checkApplyNumInputs(apply, 2);
  17080. const result = this.emitIsInstance(apply.args[0], apply.args[1]);
  17081. return new torch._C.SimpleValue(result.value());
  17082. }
  17083. case 'prim::tolist': {
  17084. const value = apply.func.value;
  17085. const operand = this.emitSugaredExpr(value, 1);
  17086. if (!type_hint) {
  17087. throw new python.Error('Expected type hint for result of tolist().');
  17088. }
  17089. return new torch._C.SimpleValue(this.graph.insertToList(operand.asValue(value.range(), this.method), type_hint));
  17090. }
  17091. case 'prim::HasAttr': {
  17092. throw new python.Error('Not implemented.');
  17093. }
  17094. case 'prim::CreateObject': {
  17095. if (apply.args.length !== 1) {
  17096. throw python.Error('Only one argument to __new__ allowed.');
  17097. }
  17098. const arg = this.emitSugaredExpr(apply.args[0], 1);
  17099. if (arg instanceof torch._C.ClassValue === false) {
  17100. throw python.Error('Expected class value as argument to __new__.');
  17101. }
  17102. const class_arg = arg;
  17103. const createNode = this.graph.insertNode(this.graph.createObject(class_arg._type));
  17104. createNode.setSourceRange(apply.range());
  17105. return new torch._C.SimpleValue(createNode.output());
  17106. }
  17107. case 'prim::range': {
  17108. const input_vals = this.getValues(apply.args, true);
  17109. return new torch._C.RangeValue(apply.range(), this.method, input_vals);
  17110. }
  17111. case 'prim::enumerate': {
  17112. throw new python.Error('Not implemented.');
  17113. }
  17114. case 'prim::zip': {
  17115. throw new python.Error('Not implemented.');
  17116. }
  17117. case 'prim::list': {
  17118. throw new python.Error('Not implemented.');
  17119. }
  17120. case 'prim::dict': {
  17121. throw new python.Error('Not implemented.');
  17122. }
  17123. case 'aten::index': {
  17124. throw new python.Error('Not implemented.');
  17125. }
  17126. default: {
  17127. throw new python.Error(`Unsupported special form '${sv.from()}'.`);
  17128. }
  17129. }
  17130. }
  17131. emitSimpleExpr(tree, type_hint) {
  17132. if (tree instanceof ast.Constant) {
  17133. if (tree.value === true) {
  17134. return this.graph.insertConstant(new torch._C.IValue(true, 'Bool'), tree.range());
  17135. } else if (tree.value === false) {
  17136. return this.graph.insertConstant(new torch._C.IValue(false, 'Bool'), tree.range());
  17137. } else if (tree.value === null) {
  17138. return this.graph.insertConstant(new torch._C.IValue(), tree.range());
  17139. } else if (typeof tree.value === 'string') {
  17140. return this.emitStringLiteral(tree);
  17141. }
  17142. return this.emitConst(tree);
  17143. } else if (tree instanceof ast.List) {
  17144. return this.emitListLiteral(tree, type_hint);
  17145. } else if (tree instanceof ast.UnaryOp && tree.op instanceof ast.USub && tree.operand instanceof ast.Name && tree.operand.id === 'inf') {
  17146. return this.emitConst(new ast.Constant(-Infinity, 'float'));
  17147. } else if (tree instanceof ast.UnaryOp && tree.op instanceof ast.USub && tree.operand instanceof ast.Constant) {
  17148. const c = tree.operand;
  17149. if (c.type === 'complex') {
  17150. return this.emitConst(new ast.Constant(new builtins.complex(-c.value.real, -c.value.imag), 'complex'));
  17151. }
  17152. return this.emitConst(new ast.Constant(-c.value, c.type));
  17153. } else if (tree instanceof ast.UnaryOp && tree.op instanceof ast.USub) {
  17154. return this.emitUnaryOp(tree, '__neg__', 'aten::neg');
  17155. } else if (tree instanceof ast.BinOp) {
  17156. return this.emitBinaryOp(tree);
  17157. } else if (tree instanceof ast.Dict) {
  17158. return this.emitDictLiteral(tree, type_hint);
  17159. } else if (tree instanceof ast.Tuple) {
  17160. const values = this.getValues(tree.elts, /*maybe_unpack=*/true);
  17161. return this.graph.insertNode(this.graph.createTuple(values)).output();
  17162. }
  17163. throw new python.Error(`Simple expression '${tree.__class__.__name__}' not implemented.`);
  17164. }
  17165. getNodeKind(kind /*, ninputs */) {
  17166. if (kind instanceof ast.Add) {
  17167. return 'aten::add';
  17168. } else if (kind instanceof ast.Sub) {
  17169. return 'aten::sub';
  17170. } else if (kind instanceof ast.Mult) {
  17171. return 'aten::mul';
  17172. }
  17173. /*
  17174. case TK_UNARY_MINUS: return 'aten::neg';
  17175. case TK_POW: return 'aten::pow';
  17176. case '@': return 'aten::matmul';
  17177. case TK_STARRED: return 'prim::Starred';
  17178. case '/': return 'aten::div';
  17179. case '%': return 'aten::remainder';
  17180. case TK_NE: return 'aten::ne';
  17181. case TK_EQ: return 'aten::eq';
  17182. case '<': return 'aten::lt';
  17183. case '>': return 'aten::gt';
  17184. case TK_LE: return 'aten::le';
  17185. case TK_GE: return 'aten::ge';
  17186. case TK_AND: return 'aten::__and__';
  17187. case TK_OR: return 'aten::__or__';
  17188. case TK_IS: return 'aten::__is__';
  17189. case TK_ISNOT: return 'aten::__isnot__';
  17190. case TK_NOT: return 'aten::__not__';
  17191. case TK_FLOOR_DIV: return 'aten::floordiv';
  17192. case TK_LSHIFT: return 'aten::__lshift__';
  17193. case TK_RSHIFT: return 'aten::__rshift__';
  17194. case '&': return 'aten::__and__';
  17195. case '|': return 'aten::__or__';
  17196. case '^': return 'aten::__xor__';
  17197. case TK_IN: return 'aten::__contains__';
  17198. */
  17199. throw new python.Error(`Unknown kind '${kind.__class__.__name__}'.`);
  17200. }
  17201. getOperatorOverload(kind /*, ninputs */) {
  17202. if (kind instanceof ast.Add) {
  17203. return '__add__';
  17204. } else if (kind instanceof ast.Sub) {
  17205. return '__sub__';
  17206. } else if (kind instanceof ast.Mult) {
  17207. return '__mul__';
  17208. }
  17209. /*
  17210. case TK_UNARY_MINUS: return "__neg__";
  17211. case '~': return "__invert__";
  17212. case TK_POW: return "__pow__";
  17213. case '/': return "__truediv__";
  17214. case '%': return "__mod__";
  17215. case TK_NE: return "__ne__";
  17216. case TK_EQ: return "__eq__";
  17217. case '<': return "__lt__";
  17218. case '>': return "__gt__";
  17219. case TK_LE: return "__le__";
  17220. case TK_GE: return "__ge__";
  17221. case '&': return "__and__";
  17222. case '|': return "__or__";
  17223. case '^': return "__xor__";
  17224. case TK_IN: return "__contains__";
  17225. case TK_LSHIFT: return "__lshift__";
  17226. case TK_RSHIFT: return "__rshift__";
  17227. */
  17228. throw new python.Error(`Unknown kind '${kind.__class__.__name__}'.`);
  17229. }
  17230. emitBinaryOp(tree) {
  17231. const inputs = [tree.left, tree.right];
  17232. const kind = this.getNodeKind(tree.op, inputs.length);
  17233. const overload = this.getOperatorOverload(tree.op, inputs.length);
  17234. const named_values = this.getNamedValues(inputs, /*maybe_unpack=*/false);
  17235. if (tree.op instanceof ast.In) {
  17236. // std::iter_swap(named_values.begin() + 0, named_values.begin() + 1);
  17237. throw new python.Error('Not implemented.');
  17238. }
  17239. if (named_values[0].type() instanceof torch.TupleType &&
  17240. named_values[1].type() instanceof torch.TupleType &&
  17241. kind === 'aten::add') {
  17242. const first_tuple = torch._C.createTupleUnpack(named_values[0].value(this.graph)).vec();
  17243. const second_tuple = torch._C.createTupleUnpack(named_values[1].value(this.graph)).vec();
  17244. first_tuple.insert(first_tuple.end(), second_tuple.begin(), second_tuple.end());
  17245. return this.graph.insertNode(this.graph.createTuple(first_tuple)).output();
  17246. }
  17247. return torch._C.asSimple(torch._C.makeMagic(overload, new torch._C.BuiltinFunction(kind, null)).call(tree.range(), this.method, named_values, [], 0));
  17248. }
  17249. emitDictLiteral(dl, type_hint) {
  17250. const key_trees = dl.keys;
  17251. const value_trees = dl.values;
  17252. torch._C.AT_ASSERT(key_trees.length === value_trees.length);
  17253. const keys = [];
  17254. const values = [];
  17255. let rhs_value_type = null;
  17256. for (let i = 0; i < key_trees.length; i++) {
  17257. keys.push(this.emitExpr(key_trees[i]));
  17258. values.push(this.emitExpr(value_trees[i]));
  17259. if (i === 0) {
  17260. rhs_value_type = values[i].type();
  17261. } else {
  17262. if (keys[i - 1].type().kind() !== keys[i].type().kind()) {
  17263. throw new python.Error('Dict keys must contain only a single type.');
  17264. }
  17265. rhs_value_type = torch._C.unifyTypes(rhs_value_type, values[i].type(), /*default_to_union=*/true);
  17266. }
  17267. }
  17268. const refined_type_hint = { _: type_hint };
  17269. const annotated_union_type = type_hint && type_hint.isUnionType() ? type_hint : null;
  17270. const all_candidates = { _: [] };
  17271. const default_refined_type_hint_setter = () => {
  17272. if (keys.length === 0) {
  17273. refined_type_hint._ = torch.DictType.create(torch.StringType.get(), torch.TensorType.get());
  17274. } else {
  17275. refined_type_hint._ = torch.DictType.create(keys[0].type(), rhs_value_type);
  17276. if (rhs_value_type instanceof torch.UnionType) {
  17277. throw new python.Error('Dict values consist of heterogeneous types.');
  17278. }
  17279. }
  17280. };
  17281. if (type_hint) {
  17282. const type_match = (t) => t instanceof torch.DictType;
  17283. this.refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint, all_candidates, 'Dict', dl, type_match, () => [], default_refined_type_hint_setter);
  17284. if (all_candidates._.length > 0 && values.length === 0) {
  17285. throw new python.Error('Cannot assign an empty dict.');
  17286. }
  17287. } else {
  17288. default_refined_type_hint_setter();
  17289. }
  17290. torch._C.TORCH_INTERNAL_ASSERT(all_candidates._.length > 0 || refined_type_hint._);
  17291. if (values.length > 0) {
  17292. if (all_candidates._.length > 0) {
  17293. this.refineAndSetDictTypeHintFromCandidatesVector(all_candidates, type_hint, refined_type_hint, keys[0].type(), rhs_value_type, dl);
  17294. }
  17295. if (refined_type_hint._.getKeyType() !== keys[0].type()) {
  17296. throw new python.Error('Type annotation does not match key type.');
  17297. }
  17298. if (!rhs_value_type.isSubtypeOf(refined_type_hint._.getValueType())) {
  17299. throw new python.Error('Type annotation does not match value type.');
  17300. }
  17301. }
  17302. let result = this.graph.insertNode(this.graph.createDict(refined_type_hint._.getKeyType(), refined_type_hint._.getValueType(), keys, values));
  17303. if (annotated_union_type) {
  17304. const n = this.graph.insertNode(this.graph.create('prim::unchecked_cast', [result.output()]));
  17305. n.output().setType(annotated_union_type);
  17306. result = n;
  17307. }
  17308. return result.output();
  17309. }
  17310. emitStringLiteral(c) {
  17311. return torch._C.insertConstant(this.graph, c.value, c.range());
  17312. }
  17313. emitConst(c) {
  17314. if (c.type === 'int') {
  17315. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Int'), this.graph, c.range(), this.integral_constants);
  17316. } else if (c.type === 'complex') {
  17317. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Complex'), this.graph, c.range(), this.complex_constants);
  17318. } else if (c.type === 'float') {
  17319. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Double'), this.graph, c.range(), this.fp_constants);
  17320. }
  17321. throw new python.Error(`Unsupported constant type.`);
  17322. }
  17323. emitListLiteral(ll, type_hint) {
  17324. type_hint = type_hint || null;
  17325. const values = this.getValues(ll.elts, true);
  17326. if (values.length === 0 && type_hint === null) {
  17327. throw new python.Error('Not implemented.');
  17328. }
  17329. let inferred_elem_type = torch.TensorType.get();
  17330. const refined_type_hint = { _: type_hint };
  17331. const annotated_union_type = refined_type_hint._ && refined_type_hint._.isUnionType() ? refined_type_hint._ : null;
  17332. const all_candidates = { _: [] };
  17333. if (refined_type_hint._) {
  17334. const do_if_type_match = () => {
  17335. inferred_elem_type = refined_type_hint._.expect(torch.ListType).getElementType();
  17336. };
  17337. const type_match = (t) => t.isSubtypeOf(torch.Type.get('AnyListType'));
  17338. this.refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint, all_candidates, 'List', ll, type_match, do_if_type_match, do_if_type_match);
  17339. if (all_candidates._.length > 0 && values.len === 0) {
  17340. throw new python.Error('Cannot assign an empty list.');
  17341. }
  17342. }
  17343. if (values.length !== 0) {
  17344. const types = values.map((v) => v.type());
  17345. const elem_type_hint = refined_type_hint._ && refined_type_hint._.kind() === 'ListType' ? refined_type_hint._.getElementType() : null;
  17346. const unified_elem_type = torch._C.unifyTypeList(types, null /*nowhere*/, /*default_to_union=*/true, elem_type_hint);
  17347. if (!refined_type_hint._ && unified_elem_type.kind() === 'UnionType') {
  17348. throw new python.Error('Not implemented.');
  17349. }
  17350. if (all_candidates._.length === 0 && refined_type_hint._ && !unified_elem_type.isSubtypeOf(inferred_elem_type)) {
  17351. throw new python.Error('Not implemented.');
  17352. }
  17353. if (all_candidates._.length !== 0) {
  17354. this.refineAndSetListTypeHintFromCandidatesVector(all_candidates, type_hint, refined_type_hint._, unified_elem_type, ll);
  17355. inferred_elem_type = refined_type_hint._.expect(torch.ListType).getElementType();
  17356. }
  17357. if (!refined_type_hint._) {
  17358. inferred_elem_type = unified_elem_type;
  17359. }
  17360. }
  17361. let result = this.graph.insertNode(this.graph.createList(inferred_elem_type, values));
  17362. if (annotated_union_type) {
  17363. const n = this.graph.insertNode(this.graph.create('prim::unchecked_cast', [result.output()]));
  17364. n.output().setType(annotated_union_type);
  17365. result = n;
  17366. }
  17367. return result.output();
  17368. }
  17369. insertRefinements(loc, ref) {
  17370. for (const r of ref.activeRefinements()) {
  17371. const v = this.environment_stack.getVar(r.identifier(), loc);
  17372. const new_v = this.graph.insertUncheckedCast(v, r.type());
  17373. this.environment_stack.setVar(loc, r.identifier(), new_v);
  17374. }
  17375. }
  17376. shouldDeriveSetStateType(def, schema) {
  17377. const noTypeAnnotations = schema.arguments.every((arg) => arg.is_inferred_type());
  17378. const shouldInfer = def.name === '__setstate__' && noTypeAnnotations;
  17379. if (!shouldInfer) {
  17380. return false;
  17381. }
  17382. if (def.name !== '__setstate__' && def.args.args.length !== 2) {
  17383. throw new python.Error(`Invalid '__setstate' method.`);
  17384. }
  17385. return true;
  17386. }
  17387. checkApplyNumInputs(apply, expected_inputs) {
  17388. if (apply.args.length !== expected_inputs) {
  17389. throw new python.Error('Invalid number of arguments.');
  17390. }
  17391. if (apply.keywords.length > 0) {
  17392. throw new python.Error('Invalid number of keyword arguments.');
  17393. }
  17394. }
  17395. checkApplyNumInputsRange(apply, min_expected_inputs, max_expected_inputs) {
  17396. const position_arg_size = apply.args.length;
  17397. if (position_arg_size < min_expected_inputs || position_arg_size > max_expected_inputs) {
  17398. throw new python.Error('Invalid number of arguments.');
  17399. }
  17400. if (apply.keywords.length > 0) {
  17401. throw new python.Error('Invalid number of keyword arguments.');
  17402. }
  17403. }
  17404. validateAssignLhsExpr(lhs /*, r */) {
  17405. let num_normal_assign = 0;
  17406. let num_starred = 0;
  17407. for (const assignee of lhs) {
  17408. if (assignee instanceof ast.Name || assignee instanceof ast.Subscript || assignee instanceof ast.Tuple || assignee instanceof ast.Attribute) {
  17409. num_normal_assign++;
  17410. } else if (assignee instanceof ast.Starred) {
  17411. num_starred++;
  17412. } else {
  17413. throw new python.Error('Assignment must be a variable, subscript, or starred expression.');
  17414. }
  17415. }
  17416. if (num_starred > 1) {
  17417. throw new python.Error('Only one starred expression is allowed.');
  17418. }
  17419. if (num_starred > 0 && num_normal_assign === 0) {
  17420. throw new python.Error('Invalid starred expression.');
  17421. }
  17422. return num_starred;
  17423. }
  17424. createTempName(prefix) {
  17425. return `${prefix}${this._temp_name_count++}`;
  17426. }
  17427. handleMaybeNoReturn(def, block) {
  17428. const decl_ret = this._def_stack[this._def_stack.length - 1]._declared_return_type;
  17429. if (this.exit_blocks.size === 0) {
  17430. if (decl_ret && decl_ret !== torch.NoneType.get()) {
  17431. throw new python.Error('Function was not annotated as having type None, but does not return along all paths.');
  17432. }
  17433. const b = new torch._C.WithInsertPoint(block.nodes().end());
  17434. // this.emitReturn(Return::create(def.range(), Expr(Compound::create(TK_NONE, def.range(), {}))));
  17435. b.dispose();
  17436. throw new python.Error("'torch._C.to_ir.handleMaybeNoReturn' not implemented.");
  17437. } else if (this._def_stack[this._def_stack.length - 1]._merged_return_type === null) {
  17438. this._def_stack[this._def_stack.length - 1]._merged_return_type = decl_ret === null ? torch.NoneType.get() : decl_ret;
  17439. }
  17440. }
  17441. getAdjTupleIndex(loc, tuple_type, input_index, allow_out_of_bounds) {
  17442. let adj_index = input_index;
  17443. const tuple_len = tuple_type.elements().length;
  17444. if (input_index < 0) {
  17445. adj_index = tuple_len + input_index;
  17446. }
  17447. if (!allow_out_of_bounds && (adj_index >= tuple_len || adj_index < 0)) {
  17448. throw new python.Error(`Tuple index out of range at ${loc}.`);
  17449. }
  17450. return adj_index;
  17451. }
  17452. emitTupleIndex(loc, tuple_val, idx_val) {
  17453. const tuple_typ = tuple_val.type();
  17454. const elems = tuple_typ.elements();
  17455. let output_type = null;
  17456. if (idx_val.type() !== torch.IntType.get()) {
  17457. throw new python.Error('Tuple index must be an integer.');
  17458. }
  17459. const idx = torch._C.toIValue(idx_val);
  17460. if (idx) {
  17461. const adj_index = this.getAdjTupleIndex(loc, tuple_typ, idx.toInt(), /*allow_out_of_bounds*/ false);
  17462. output_type = elems[adj_index];
  17463. } else {
  17464. if (elems.length === 0 || !torch._C.convertibleToList(tuple_typ, torch.ListType.create(elems[0]))) {
  17465. throw new python.Error('Cannot index into a tuple with a non-integer literal.');
  17466. }
  17467. [output_type] = elems;
  17468. }
  17469. return this.graph.insertNode(this.graph.createTupleIndex(tuple_val, idx_val, output_type)).output();
  17470. }
  17471. getSliceInd(idx_val, loc) {
  17472. const ivalue = torch._C.toIValue(idx_val);
  17473. if (ivalue && ivalue.isInt()) {
  17474. return ivalue.toInt();
  17475. }
  17476. throw new python.Error(`Tuple slice indices must be integer constants at '${loc}'.`);
  17477. }
  17478. emitTupleSlice(loc, tuple_val, tuple_args) {
  17479. const tuple_type = tuple_val.value(this.graph).type().expect(torch.TupleType);
  17480. const tuple_len = tuple_type.elements().length;
  17481. const [beg_val, end_val, step] = tuple_args;
  17482. let step_size = 1;
  17483. if (step) {
  17484. const val = torch._C.toIValue(step.value(this.graph));
  17485. torch._C.TORCH_CHECK(val.isInt());
  17486. step_size = val.toInt();
  17487. }
  17488. let beg = { _: Number.MAX_SAFE_INTEGER }; // std::numeric_limits<int64_t>::max();
  17489. if (beg_val) {
  17490. beg = { _: this.getAdjTupleIndex(loc, tuple_type, this.getSliceInd(beg_val.value(this.graph), loc), true) };
  17491. }
  17492. let end = { _: Number.MAX_SAFE_INTEGER }; // std::numeric_limits<int64_t>::max();
  17493. if (end_val) {
  17494. end = { _: this.getAdjTupleIndex(loc, tuple_type, this.getSliceInd(end_val.value(this.graph), loc), true) };
  17495. }
  17496. const num_values = torch._C.slice_indices_adjust(tuple_len, beg, end, step_size);
  17497. return this.graph.insertNode(this.graph.createTupleSlice(tuple_val.value(this.graph), beg._, step_size, num_values)).output();
  17498. }
  17499. emitSliceOp(loc, sliceable, dim, start, end, step) {
  17500. const args = [];
  17501. args.push(new torch._C.NamedValue(loc, 'self', sliceable));
  17502. if (dim) {
  17503. torch._C.AT_ASSERT(sliceable.type().isSubtypeOf(torch.TensorType.get()));
  17504. args.emplace_back(new torch._C.NamedValue(dim));
  17505. } else {
  17506. torch._C.AT_ASSERT(!sliceable.type().isSubtypeOf(torch.TensorType.get()));
  17507. }
  17508. if (sliceable.type() instanceof torch.TupleType) {
  17509. const tuple_args = [];
  17510. tuple_args.push(start ? new torch._C.NamedValue(start) : null);
  17511. tuple_args.push(end ? new torch._C.NamedValue(end) : null);
  17512. tuple_args.push(step ? new torch._C.NamedValue(step) : null);
  17513. return this.emitTupleSlice(loc, args[0], tuple_args);
  17514. }
  17515. if (!step) {
  17516. step = this.graph.insertConstant(1, loc);
  17517. }
  17518. args.push(new torch._C.NamedValue(loc, 'start', start));
  17519. args.push(new torch._C.NamedValue(loc, 'end', end));
  17520. args.push(new torch._C.NamedValue(loc, 'step', step));
  17521. return this.emitBuiltinCall(loc, this.graph, 'aten::slice', args, []);
  17522. }
  17523. emitSlice(loc, input, dim, slice) {
  17524. let start = null;
  17525. let end = null;
  17526. let step = null;
  17527. if (slice.lower) {
  17528. start = this.emitExpr(slice.lower);
  17529. }
  17530. if (slice.upper) {
  17531. end = this.emitExpr(slice.upper);
  17532. }
  17533. if (slice.step) {
  17534. step = this.emitExpr(slice.step);
  17535. }
  17536. return this.emitSliceOp(loc, input, dim, start, end, step);
  17537. }
  17538. emitBasicSlice(loc, sliceable, subscript_exprs) {
  17539. torch._C.AT_ASSERT(subscript_exprs instanceof ast.Slice);
  17540. const slice_exp = subscript_exprs;
  17541. let maybe_dim = null;
  17542. if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  17543. maybe_dim = this.graph.insertConstant(0, loc);
  17544. }
  17545. return this.emitSlice(loc, sliceable, maybe_dim, slice_exp);
  17546. }
  17547. emitSubscript(subscript, type_hint) {
  17548. type_hint = type_hint === undefined ? null : type_hint;
  17549. const sv = this.emitSugaredExpr(subscript.value, 1);
  17550. const subscript_exprs = subscript.slice;
  17551. const range = subscript.range();
  17552. const val_range = subscript.value;
  17553. if (subscript_exprs instanceof ast.Tuple) {
  17554. return new torch._C.SimpleValue(this.emitMultidimSlicing(range, sv.asValue(val_range, this.method), subscript_exprs));
  17555. }
  17556. if (subscript_exprs instanceof ast.Slice) {
  17557. if (sv.kind() === 'module') {
  17558. const s_tuple_val = sv.asTupleValue(val_range, this.method).asValue(val_range, this.method);
  17559. const [slice] = subscript_exprs;
  17560. const tuple_args = [];
  17561. if (slice.start().present()) {
  17562. const begin = new torch._C.NamedValue(val_range, 'begin', this.emitExpr(slice.start().get()));
  17563. tuple_args.push(begin);
  17564. } else {
  17565. tuple_args.push(null);
  17566. }
  17567. if (slice.end().present()) {
  17568. const end = new torch._C.NamedValue(val_range, 'end', this.emitExpr(slice.end().get()));
  17569. tuple_args.push(end);
  17570. } else {
  17571. tuple_args.push(null);
  17572. }
  17573. if (slice.step().present()) {
  17574. const step = new torch._C.NamedValue(val_range, 'step', this.emitExpr(slice.step().get()));
  17575. tuple_args.push(step);
  17576. } else {
  17577. tuple_args.push(null);
  17578. }
  17579. const tupleSliceValue = this.emitTupleSlice(val_range, s_tuple_val, tuple_args);
  17580. return new torch._C.SimpleValue(tupleSliceValue);
  17581. }
  17582. return new torch._C.SimpleValue(this.emitBasicSlice(range, sv.asValue(val_range, this.method), subscript_exprs));
  17583. }
  17584. const sliceable = sv.asValue(val_range, this.method);
  17585. const subscript_sv = this.emitSugaredExpr(subscript_exprs, 1);
  17586. if (subscript_sv instanceof torch._C.SliceValue) {
  17587. const slice_value = subscript_sv;
  17588. let dim = null;
  17589. if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  17590. dim = this.method.graph().insertConstant(0, val_range);
  17591. }
  17592. const sliced = this.emitSliceOp(val_range, sliceable, dim, slice_value.start(), slice_value.stop(), slice_value.step());
  17593. return new torch._C.SimpleValue(sliced);
  17594. }
  17595. const idx = subscript_sv.asValue(val_range, this.method);
  17596. if (sliceable.type() instanceof torch.TupleType) {
  17597. return new torch._C.SimpleValue(this.emitTupleIndex(range, sv.asValue(val_range, this.method), idx));
  17598. } else if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  17599. return new torch._C.SimpleValue(this.emitMultidimSlicing(range, sliceable, subscript_exprs));
  17600. }
  17601. return sv.getitem(range, this.method, idx, type_hint);
  17602. }
  17603. });
  17604. this.registerType('torch.jit.CompilationUnit', class {
  17605. constructor() {
  17606. this._functions = new Map();
  17607. this._classes = new Map();
  17608. }
  17609. register_type(namedType) {
  17610. this._classes.set(namedType.annotation_str, namedType);
  17611. }
  17612. register_function(fn) {
  17613. const name = fn.qualname().qualifiedName();
  17614. torch._C.TORCH_CHECK(!this._functions.has(name));
  17615. this._functions.set(name, fn);
  17616. return fn;
  17617. }
  17618. define(...args) {
  17619. if (Array.isArray(args[1])) {
  17620. const [prefix, properties, propResolvers, definitions, defResolvers, self, shouldMangle, operator_set_version] = args;
  17621. torch._C.TORCH_INTERNAL_ASSERT(definitions.length === defResolvers.length);
  17622. torch._C.TORCH_INTERNAL_ASSERT(properties.length === propResolvers.length);
  17623. const functions = [];
  17624. const function_table = new Map();
  17625. const record_function = (fn) => {
  17626. function_table.set(fn.name(), fn);
  17627. functions.push(fn);
  17628. this.register_function(fn);
  17629. };
  17630. for (let i = 0; i < properties.length; i++) {
  17631. const property_fns = this.define_property(prefix, properties[i], propResolvers[i], self, function_table, shouldMangle);
  17632. const getter_fn = property_fns.getGetter();
  17633. const setter_fn = property_fns.getSetter();
  17634. record_function(getter_fn);
  17635. if (setter_fn) {
  17636. record_function(setter_fn);
  17637. }
  17638. }
  17639. for (let i = 0; i < definitions.length; i++) {
  17640. const fn = this.define(prefix, definitions[i], defResolvers[i], self, function_table, shouldMangle, 'Method', operator_set_version);
  17641. record_function(fn);
  17642. }
  17643. for (const [name, fn] of function_table) {
  17644. if (name === '__init__') {
  17645. fn.ensure_defined();
  17646. }
  17647. }
  17648. for (const fn of functions) {
  17649. fn.ensure_defined();
  17650. }
  17651. return functions;
  17652. } else if (args[1] instanceof ast.FunctionDef) {
  17653. const [prefix, def, resolver, self, function_table, shouldMangle, type, operator_set_version] = args;
  17654. const _resolver = self ? resolver : new torch._C.FunctionResolver(resolver, function_table);
  17655. const creator = (method) => {
  17656. return new torch._C.to_ir(def, _resolver, self, method);
  17657. };
  17658. let name = prefix ? new torch._C.QualifiedName(prefix, def.name) : new torch._C.QualifiedName(def.name);
  17659. if (shouldMangle && this.find_function(name)) {
  17660. name = this.mangle(name);
  17661. }
  17662. const graph = new torch.Graph();
  17663. graph.set_op_version(operator_set_version);
  17664. const fn = new torch._C.GraphFunction(name, graph, creator);
  17665. fn.__ast__ = def; // remove
  17666. if (self) {
  17667. if (type === 'hook') {
  17668. self.getClassType().addForwardHook(fn);
  17669. } else if (type === 'prehook') {
  17670. self.getClassType().addPreHook(fn);
  17671. } else {
  17672. self.getClassType().addMethod(fn);
  17673. }
  17674. }
  17675. return fn;
  17676. }
  17677. throw new python.Error('Invalid arguments.');
  17678. }
  17679. get_type(name) {
  17680. return this._classes.get(name.qualifiedName());
  17681. }
  17682. get_class(name) {
  17683. return this.get_type(name);
  17684. }
  17685. find_function(name) {
  17686. const key = name.qualifiedName();
  17687. return this._functions.get(key);
  17688. }
  17689. });
  17690. this.registerFunction('torch._C.ConvertToSSA', (graph) => {
  17691. const ctrl = new torch._C.ControlFlowLoadStores();
  17692. ctrl.run(graph);
  17693. const exit_vars = new torch._C.LoopContinuations();
  17694. exit_vars.run(graph);
  17695. torch._C.InlineLoopCondition(graph);
  17696. const erase_loads_stores = new torch._C.EraseLoadStores();
  17697. erase_loads_stores.run(graph);
  17698. torch._C.TransformExits(graph);
  17699. });
  17700. this.registerFunction('torch._C.canonicalizeModifiedLoop', (/* n */) => {
  17701. /*
  17702. LoopView loop(n);
  17703. if (loop.loopType() != LoopView::ModifiedLoop) {
  17704. return;
  17705. }
  17706. const g = n.owningGraph();
  17707. WithInsertPoint node_insert(n);
  17708. const zero = g.insertConstant(0);
  17709. const one = g.insertConstant(1);
  17710. const max_trip_count = loop.maxTripCount();
  17711. const condition = g.insert(aten::gt, {max_trip_count, zero});
  17712. loop.replaceMaxTripCount(g.insertConstant(std::numeric_limits<int64_t>::max()));
  17713. const inp_condition = toIValue(loop.inputCond());
  17714. if (inp_condition == null || inp_condition.toBool() == false) {
  17715. condition = g.insert(aten::__and__, {condition, loop.inputCond()});
  17716. }
  17717. loop.replaceInputCondition(condition);
  17718. n.addOutput().setType(IntType::get());
  17719. WithInsertPoint loop_insert(loop.bodyBlock());
  17720. n.addInput(zero);
  17721. const new_iter = loop.bodyBlock().addInput().setType(IntType::get());
  17722. // unset unique name for jitter, its replacement does not have a name
  17723. loop.currentTripCount().setDebugName('').replaceAllUsesWith(new_iter);
  17724. const inc_iter = g.insert(aten::add, {new_iter, one});
  17725. loop.bodyBlock().registerOutput(inc_iter);
  17726. const less_than_max_trip = g.insert(aten::lt, {inc_iter, max_trip_count});
  17727. const loop_continue = loop.nextCond();
  17728. const new_condition =
  17729. g.insert(aten::__and__, {less_than_max_trip, loop_continue});
  17730. loop.bodyBlock().eraseOutput(0);
  17731. loop.bodyBlock().insertOutput(0, new_condition);
  17732. */
  17733. });
  17734. this.registerFunction('torch._C.canonicalizeModifiedLoops', (block) => {
  17735. for (const n of block.nodes()) {
  17736. for (const b of n.blocks()) {
  17737. torch._C.canonicalizeModifiedLoops(b);
  17738. }
  17739. if (n.kind() === 'prim::Loop') {
  17740. torch._C.canonicalizeModifiedLoop(n);
  17741. }
  17742. }
  17743. });
  17744. this.registerFunction('torch._C.CanonicalizeModifiedLoops', (graph) => {
  17745. torch._C.canonicalizeModifiedLoops(graph.block());
  17746. });
  17747. this.registerType('torch._C.MiniEnvironment', class {
  17748. constructor(b, next) {
  17749. this.next = next || null;
  17750. this.table = new Map();
  17751. }
  17752. setVar(name, value) {
  17753. this.table.set(name, value);
  17754. }
  17755. definedVariables() {
  17756. const result = Array.from(this.table.keys());
  17757. return result.sort();
  17758. }
  17759. findInThisFrame(name) {
  17760. if (this.table.has(name)) {
  17761. return this.table.get(name);
  17762. }
  17763. return null;
  17764. }
  17765. findInAnyFrame(name) {
  17766. /* eslint-disable consistent-this */
  17767. const self = this;
  17768. /* eslint-enable consistent-this */
  17769. for (let runner = self; runner; runner = runner.next) {
  17770. const r = runner.findInThisFrame(name);
  17771. if (r) {
  17772. return r;
  17773. }
  17774. }
  17775. return null;
  17776. }
  17777. });
  17778. this.registerType('torch._C.ValueEnvironment', class extends torch._C.MiniEnvironment {
  17779. });
  17780. this.registerType('torch._C.TypeEnvironment', class extends torch._C.MiniEnvironment {
  17781. });
  17782. this.registerType('torch._C.ControlFlowLoadStores', class {
  17783. constructor() {
  17784. this.environment_stack = null;
  17785. }
  17786. pushFrame(b) {
  17787. this.environment_stack = new torch._C.TypeEnvironment(b, this.environment_stack);
  17788. }
  17789. popFrame() {
  17790. const old_frame = this.environment_stack;
  17791. this.environment_stack = this.environment_stack.next;
  17792. return old_frame;
  17793. }
  17794. addBlockInput(b, type, name) {
  17795. const g = b.owningGraph();
  17796. g.createStore(name, b.addInput(name).setType(type)).insertAfter(b.param_node());
  17797. }
  17798. addBlockOutput(exit_block, type, name) {
  17799. const insert = new torch._C.WithInsertPoint(exit_block);
  17800. const g = exit_block.owningGraph();
  17801. const block_exit = g.insertNode(g.createLoad(name, type)).output();
  17802. exit_block.registerOutput(block_exit);
  17803. insert.dispose();
  17804. }
  17805. addNodeOutput(n, type, name) {
  17806. const out = n.addOutput().setType(type);
  17807. if (torch._C.meaningfulName(name)) {
  17808. out.setDebugName(name);
  17809. }
  17810. const g = n.owningGraph();
  17811. g.createStore(name, out).insertAfter(n);
  17812. }
  17813. addNodeInput(n, type, name) {
  17814. const g = n.owningGraph();
  17815. const inp = g.createLoad(name, type).insertBefore(n).output();
  17816. n.addInput(inp);
  17817. }
  17818. addIfLoadStores(n) {
  17819. const [true_block, false_block] = n.blocks();
  17820. const true_vars = this.addControlFlowLoadStores(true_block);
  17821. const false_vars = this.addControlFlowLoadStores(false_block);
  17822. const mutated_variables = new Set();
  17823. for (const v of true_vars.definedVariables()) {
  17824. if (false_vars.findInAnyFrame(v)) {
  17825. mutated_variables.add(v);
  17826. }
  17827. }
  17828. for (const v of false_vars.definedVariables()) {
  17829. if (true_vars.findInAnyFrame(v)) {
  17830. mutated_variables.add(v);
  17831. }
  17832. }
  17833. for (const x of mutated_variables) {
  17834. const true_type = true_vars.findInAnyFrame(x);
  17835. const false_type = false_vars.findInAnyFrame(x);
  17836. const unified = torch._C.unifyTypes(true_type, false_type, /*default_to_union=*/true);
  17837. this.addBlockOutput(true_block, true_type, x);
  17838. this.addBlockOutput(false_block, false_type, x);
  17839. this.addNodeOutput(n, unified, x);
  17840. }
  17841. }
  17842. addLoopLoadStores(n) {
  17843. const [body_block] = n.blocks();
  17844. const loop_vars = this.addControlFlowLoadStores(body_block);
  17845. for (const name of loop_vars.definedVariables()) {
  17846. const parent_type = this.environment_stack.findInAnyFrame(name);
  17847. if (!parent_type) {
  17848. continue;
  17849. }
  17850. const block_type = loop_vars.findInThisFrame(name);
  17851. const unified_type = torch._C.unifyTypes(parent_type, block_type);
  17852. this.addNodeInput(n, parent_type, name);
  17853. this.addBlockInput(body_block, unified_type, name);
  17854. this.addBlockOutput(body_block, block_type, name);
  17855. this.addNodeOutput(n, unified_type, name);
  17856. }
  17857. }
  17858. addControlFlowLoadStores(block) {
  17859. this.pushFrame(block);
  17860. for (const n of block.nodes()) {
  17861. switch (n.kind()) {
  17862. case 'prim::If': {
  17863. this.addIfLoadStores(n);
  17864. break;
  17865. }
  17866. case 'prim::Loop': {
  17867. this.addLoopLoadStores(n);
  17868. break;
  17869. }
  17870. case 'prim::Closure': {
  17871. for (const b of n.blocks()) {
  17872. this.addControlFlowLoadStores(b);
  17873. }
  17874. break;
  17875. }
  17876. case 'prim::Store': {
  17877. this.environment_stack.setVar(n.s('name'), n.input().type());
  17878. break;
  17879. }
  17880. case 'prim::ComprehensionScope': {
  17881. this.addControlFlowLoadStores(n.blocks().at(0));
  17882. break;
  17883. }
  17884. default: {
  17885. break;
  17886. }
  17887. }
  17888. }
  17889. return this.popFrame();
  17890. }
  17891. run(graph) {
  17892. this.addControlFlowLoadStores(graph.block());
  17893. }
  17894. });
  17895. this.registerType('torch._C.LoopContinuations', class {
  17896. constructor() {
  17897. this._graph = null;
  17898. this._false_val = null;
  17899. this._curr_loop = null;
  17900. }
  17901. assignExitContinuations(block) {
  17902. for (const n of block.nodes()) {
  17903. switch (n.kind()) {
  17904. case 'prim::If': {
  17905. this.assignExitContinuations(n.blocks().at(0));
  17906. this.assignExitContinuations(n.blocks().at(1));
  17907. break;
  17908. }
  17909. case 'prim::Closure': {
  17910. const closure_block = new torch._C.LoopContinuations();
  17911. closure_block.run(n.blocks().at(0));
  17912. break;
  17913. }
  17914. case 'prim::Loop': {
  17915. const prev_loop = this._curr_loop;
  17916. this._curr_loop = n;
  17917. this.assignExitContinuations(n.blocks().at(0));
  17918. this._curr_loop = prev_loop;
  17919. break;
  17920. }
  17921. case 'prim::ContinueStmt': {
  17922. const loop_continuation = this._graph.create('prim::LoopContinuation', 0).insertAfter(n);
  17923. const header_block = loop_continuation.addBlock();
  17924. const [, pre_header] = this._curr_loop.blocks();
  17925. header_block.cloneFrom(pre_header, (v) => v);
  17926. this.InlineBlockBeforeNode(n, header_block);
  17927. loop_continuation.addInput(header_block.outputs()[0]);
  17928. loop_continuation.eraseBlock(0);
  17929. this.addLoopCarriedOutputs(loop_continuation);
  17930. n.destroy();
  17931. break;
  17932. }
  17933. case 'prim::BreakStmt': {
  17934. const loop_exit = this._graph.create('prim::LoopContinuation', 0).insertAfter(n);
  17935. loop_exit.addInput(this._false_val);
  17936. this.addLoopCarriedOutputs(loop_exit);
  17937. n.destroy();
  17938. break;
  17939. }
  17940. default: {
  17941. break;
  17942. }
  17943. }
  17944. }
  17945. }
  17946. run(...args) {
  17947. if (args.length === 1 && args[0] instanceof torch.Graph) {
  17948. const [graph] = args;
  17949. this.run(graph.block());
  17950. } else if (args.length === 1 && args[0] instanceof torch.Block) {
  17951. const [b] = args;
  17952. {
  17953. this._graph = b.owningGraph();
  17954. const guard = new torch._C.WithInsertPoint(b.nodes().front());
  17955. this._false_val = this._graph.insertConstant(false);
  17956. guard.dispose();
  17957. }
  17958. this.assignExitContinuations(b);
  17959. } else {
  17960. throw new python.Error('Not implemented.');
  17961. }
  17962. }
  17963. });
  17964. this.registerType('torch._C.LoopView', class {
  17965. constructor(node) {
  17966. torch._C.AT_ASSERT(node.kind() === 'prim::Loop' || node.kind() === 'onnx::Loop');
  17967. this._node = node;
  17968. }
  17969. bodyBlock() {
  17970. return this._node.blocks().at(0);
  17971. }
  17972. nextCond() {
  17973. return this.bodyBlock().outputs()[0];
  17974. }
  17975. carriedOutputs() {
  17976. return this._node.outputs();
  17977. }
  17978. bodyCarriedInputs() {
  17979. return this.bodyBlock().inputs().slice(1);
  17980. }
  17981. bodyCarriedOutputs() {
  17982. return this.bodyBlock().outputs().slice(1);
  17983. }
  17984. });
  17985. this.registerType('torch._C.WithLoopStatus', class {
  17986. constructor(to_ir, new_status) {
  17987. this._to_ir = to_ir;
  17988. this._prev = this._to_ir._loop_status;
  17989. this._to_ir._loop_status = new_status;
  17990. }
  17991. dispose() {
  17992. this._to_ir._loop_status = this._prev;
  17993. }
  17994. });
  17995. this.registerFunction('torch._C.InlineBlockBeforeNode', (before_node, block) => {
  17996. for (const block_node of block.nodes()) {
  17997. block_node.moveBefore(before_node);
  17998. }
  17999. });
  18000. this.registerFunction('torch._C.inlineLoopCondition', (...args) => {
  18001. if (args.length === 1 && args[0] instanceof torch.Block) {
  18002. const [block] = args;
  18003. for (const n of block.nodes()) {
  18004. for (const b of n.blocks()) {
  18005. torch._C.inlineLoopCondition(b);
  18006. }
  18007. if (n.kind() === 'prim::Loop') {
  18008. torch._C.inlineLoopCondition(n);
  18009. }
  18010. }
  18011. } else if (args.length === 1 && args[0] instanceof torch.Node) {
  18012. const [n] = args;
  18013. const [body_block, pre_header] = n.blocks();
  18014. const temp_block = n.addBlock();
  18015. temp_block.cloneFrom(pre_header, (v) => v);
  18016. torch._C.InlineBlockBeforeNode(n, temp_block);
  18017. n.insertInput(1, temp_block.outputs()[0]);
  18018. n.eraseBlock(2);
  18019. torch._C.InlineBlockBeforeNode(body_block.return_node(), pre_header);
  18020. body_block.return_node().insertInput(0, pre_header.outputs()[0]);
  18021. n.eraseBlock(1);
  18022. } else {
  18023. throw new python.Error('Not implemented.');
  18024. }
  18025. });
  18026. this.registerFunction('torch._C.InlineLoopCondition', (graph) => {
  18027. torch._C.inlineLoopCondition(graph.block());
  18028. });
  18029. this.registerType('torch._C.EraseLoadStores', class {
  18030. pushFrame(b) {
  18031. this.environment_stack = new torch._C.ValueEnvironment(b, this.environment_stack);
  18032. }
  18033. popFrame() {
  18034. const old_frame = this.environment_stack;
  18035. this.environment_stack = this.environment_stack.next;
  18036. return old_frame;
  18037. }
  18038. eraseBlockLoadStores(block) {
  18039. this.pushFrame(block);
  18040. for (const n of block.nodes()) {
  18041. switch (n.kind()) {
  18042. case 'prim::Store': {
  18043. this.environment_stack.setVar(n.s('name'), n.input());
  18044. n.destroy();
  18045. break;
  18046. }
  18047. case 'prim::Load': {
  18048. const name = n.s('name');
  18049. const value = this.environment_stack.findInAnyFrame(name);
  18050. torch._C.TORCH_INTERNAL_ASSERT(value);
  18051. n.output().replaceAllUsesWith(value);
  18052. n.destroy();
  18053. break;
  18054. }
  18055. case 'prim::ComprehensionScope': {
  18056. const [body] = n.blocks();
  18057. this.eraseBlockLoadStores(body);
  18058. for (const body_node of body.nodes()) {
  18059. body_node.moveBefore(n);
  18060. }
  18061. n.destroy();
  18062. break;
  18063. }
  18064. default: {
  18065. for (const b of n.blocks()) {
  18066. this.eraseBlockLoadStores(b);
  18067. }
  18068. break;
  18069. }
  18070. }
  18071. }
  18072. this.popFrame();
  18073. }
  18074. run(graph) {
  18075. this.eraseBlockLoadStores(graph.block());
  18076. }
  18077. });
  18078. this.registerFunction('torch._C.convertEnterExitNodesToWithBlocks', (/* graph */) => {
  18079. });
  18080. this.registerFunction('torch._C.inlineConsecutiveIfs', (/* graph */) => {
  18081. });
  18082. this.registerType('torch._C.ExitPair', class {
  18083. constructor(exit_v, exit_val_ref) {
  18084. const exit_vals = [];
  18085. for (const v of exit_val_ref) {
  18086. exit_vals.push(v);
  18087. }
  18088. if (exit_v.type() !== torch.BoolType.get()) {
  18089. throw new python.Error('Invalid exit value type.');
  18090. }
  18091. this.first = exit_v;
  18092. this.second = exit_vals;
  18093. }
  18094. hasExited() {
  18095. return this.first;
  18096. }
  18097. exitValues() {
  18098. return this.second;
  18099. }
  18100. });
  18101. this.registerType('torch._C.ExitTransformer', class {
  18102. constructor(graph) {
  18103. this._graph = graph;
  18104. this._target_block = null;
  18105. this._unit_values = new Map();
  18106. const guard = new torch._C.WithInsertPoint(this._graph.block().nodes().front());
  18107. this._true_val = this._graph.insertConstant(true);
  18108. this._false_val = this._graph.insertConstant(false);
  18109. this._throws_val = this.getUnitValue(torch.BoolType.get());
  18110. guard.dispose();
  18111. }
  18112. getUnitValue(type) {
  18113. const maybe_val = this._unit_values.get(type);
  18114. if (maybe_val) {
  18115. return maybe_val;
  18116. }
  18117. const unit = this._graph.createUninitialized(type).insertAfter(this._graph.param_node()).output();
  18118. this._unit_values.set(type, unit);
  18119. return unit;
  18120. }
  18121. transformReturnStmts() {
  18122. this._current_exit_kind = 'prim::ReturnStmt';
  18123. this.transformExits(this._graph.block());
  18124. }
  18125. transformLoopContinuations() {
  18126. this._current_exit_kind = 'prim::LoopContinuation';
  18127. this.transformExits(this._graph.block());
  18128. }
  18129. destroyNodeAfterExit(n) {
  18130. for (const output of n.outputs()) {
  18131. if (output.uses().length > 0) {
  18132. output.replaceAllUsesWith(this.getUnitValue(output.type()));
  18133. }
  18134. }
  18135. n.destroy();
  18136. }
  18137. deleteAfterExitNodes(block, iter) {
  18138. const nodes = block.nodes();
  18139. if (iter === nodes.end()) {
  18140. return;
  18141. }
  18142. const insert = new torch._C.WithInsertPoint(block.nodes().front());
  18143. for (const it of Array.from(nodes).reverse()) {
  18144. if (it === iter) {
  18145. break;
  18146. }
  18147. if (it !== block.return_node()) {
  18148. this.destroyNodeAfterExit(it);
  18149. }
  18150. }
  18151. this.destroyNodeAfterExit(iter);
  18152. insert.dispose();
  18153. }
  18154. updateTargetBlock(block) {
  18155. if (torch._C.ExitTransformer.owningNodeKind(block) === 'prim::Loop' && this._current_exit_kind === 'prim::LoopContinuation') {
  18156. this._target_block = block;
  18157. } else if (torch._C.ExitTransformer.isGraphOrClosureBlock(block) && this._current_exit_kind === 'prim::ReturnStmt') {
  18158. this._target_block = block;
  18159. }
  18160. }
  18161. transformLoop(node) {
  18162. const loop = new torch._C.LoopView(node);
  18163. const body = loop.bodyBlock();
  18164. const exit_pair = this.transformExits(body);
  18165. if (this.getExitStatus(exit_pair) === 'WONT' || this.getExitStatus(exit_pair) === 'THROWS') {
  18166. return this.constructWontExitPair();
  18167. }
  18168. const insert = new torch._C.WithInsertPoint(body);
  18169. const new_if = this._graph.insertNode(this._graph.create('prim::If', 0));
  18170. new_if.addInput(exit_pair.hasExited());
  18171. new_if.addBlock().registerOutput(this._false_val);
  18172. new_if.addBlock().registerOutput(loop.nextCond());
  18173. const new_condition = new_if.addOutput().setType(torch.BoolType.get());
  18174. loop.bodyBlock().eraseOutput(0);
  18175. loop.bodyBlock().insertOutput(0, new_condition);
  18176. node.addInput(this._false_val);
  18177. body.addInput().setType(torch.BoolType.get());
  18178. body.registerOutput(exit_pair.hasExited());
  18179. const new_has_exited = node.addOutput().setType(torch.BoolType.get());
  18180. for (const exit_value of exit_pair.exitValues()) {
  18181. const typ = exit_value.type();
  18182. node.addInput(this.getUnitValue(typ));
  18183. node.addOutput().setType(typ);
  18184. body.addInput().setType(typ);
  18185. body.registerOutput(exit_value);
  18186. }
  18187. const exit_vals = node.outputs().slice(node.outputs().length - exit_pair.exitValues().size());
  18188. const result = new torch._C.ExitPair(new_has_exited, exit_vals);
  18189. insert.dispose();
  18190. return result;
  18191. }
  18192. calcIfExitStatus(then_status, else_status) {
  18193. if (then_status === 'THROWS') {
  18194. return else_status;
  18195. } else if (else_status === 'THROWS') {
  18196. return then_status;
  18197. }
  18198. if (then_status === 'WONT' && else_status === 'WONT') {
  18199. return 'WONT';
  18200. }
  18201. if (then_status === 'WILL' && else_status === 'WILL') {
  18202. return 'WILL';
  18203. }
  18204. return 'MIGHT';
  18205. }
  18206. transformIf(node) {
  18207. const [then_block, else_block] = node.blocks();
  18208. let then_pair = this.transformExits(then_block);
  18209. let else_pair = this.transformExits(else_block);
  18210. const then_status = this.getExitStatus(then_pair);
  18211. const else_status = this.getExitStatus(else_pair);
  18212. const if_status = this.calcIfExitStatus(then_status, else_status);
  18213. if (if_status === 'THROWS') {
  18214. return this.constructThrowsExitPair();
  18215. }
  18216. if (if_status === 'WONT') {
  18217. return this.constructWontExitPair();
  18218. }
  18219. if (then_status === 'WONT' || then_status === 'THROWS') {
  18220. const exit_vals = this.matchValuesWithUnitialized(else_pair.exitValues());
  18221. then_pair = new torch._C.ExitPair(then_pair.hasExited(), exit_vals);
  18222. } else if (else_status === 'WONT' || else_status === 'THROWS') {
  18223. const exit_vals = this.matchValuesWithUnitialized(then_pair.exitValues());
  18224. else_pair = new torch._C.ExitPair(else_pair.hasExited(), exit_vals);
  18225. }
  18226. let has_exited = null;
  18227. if (if_status === 'WILL') {
  18228. has_exited = this._true_val;
  18229. } else {
  18230. this.addIfOutputs(node, [then_pair.hasExited()], [else_pair.hasExited()]);
  18231. has_exited = node.outputs().at(node.outputs().length - 1);
  18232. }
  18233. this.addIfOutputs(node, then_pair.exitValues(), else_pair.exitValues());
  18234. const num_exit_vals = then_pair.exitValues().size();
  18235. const exit_vals = node.outputs().slice(node.outputs().length - num_exit_vals);
  18236. return new torch._C.ExitPair(has_exited, exit_vals);
  18237. }
  18238. transformExits(block) {
  18239. const prev_target_block = this._target_block;
  18240. this.updateTargetBlock(block);
  18241. let exit_pair = this.constructWontExitPair();
  18242. for (const node of block.nodes()) {
  18243. const it = node.next;
  18244. switch (node.kind()) {
  18245. case 'prim::RaiseException': {
  18246. exit_pair = this.constructThrowsExitPair();
  18247. break;
  18248. }
  18249. case 'prim::ReturnStmt':
  18250. case 'prim::LoopContinuation': {
  18251. if (node.kind() === this._current_exit_kind) {
  18252. exit_pair = this.constructWillExitPair(node.inputs());
  18253. node.destroy();
  18254. }
  18255. break;
  18256. }
  18257. case 'prim::If': {
  18258. exit_pair = this.transformIf(node);
  18259. break;
  18260. }
  18261. case 'prim::With': {
  18262. exit_pair = this.transformWith(node);
  18263. break;
  18264. }
  18265. case 'prim::Closure': {
  18266. this.transformExits(node.blocks().at(0));
  18267. break;
  18268. }
  18269. case 'prim::Loop': {
  18270. exit_pair = this.transformLoop(node);
  18271. break;
  18272. }
  18273. default: {
  18274. break;
  18275. }
  18276. }
  18277. const status = this.getExitStatus(exit_pair);
  18278. if (status === 'WILL' || status === 'THROWS') {
  18279. this.deleteAfterExitNodes(block, it);
  18280. break;
  18281. }
  18282. if (status === 'MIGHT') {
  18283. throw new python.Error('Not implemented.');
  18284. // const nodes = block.nodes();
  18285. // if (node === nodes[nodes.length - 1]) {
  18286. // exit_pair = this.guardBlockNodes(block, exit_pair, it);
  18287. // }
  18288. // break;
  18289. }
  18290. }
  18291. if (this._target_block === block) {
  18292. if (this.getExitStatus(exit_pair) === 'MIGHT') {
  18293. const new_if = this._graph.create('prim::If', 0).insertBefore(block.return_node());
  18294. new_if.addBlock();
  18295. new_if.addBlock();
  18296. new_if.addInput(exit_pair.hasExited());
  18297. torch._C.ExistTransformer.addIfOutputs(new_if, exit_pair.exitValues(), block.outputs());
  18298. torch._C.ExistTransformer.replaceBlockOutputs(block, new_if.soutputs());
  18299. } else if (this.getExitStatus(exit_pair) === 'WILL') {
  18300. torch._C.ExitTransformer.replaceBlockOutputs(block, exit_pair.exitValues());
  18301. }
  18302. exit_pair = this.constructWontExitPair();
  18303. }
  18304. this._target_block = prev_target_block;
  18305. return exit_pair;
  18306. }
  18307. constructThrowsExitPair() {
  18308. return new torch._C.ExitPair(this._throws_val, []);
  18309. }
  18310. constructWontExitPair() {
  18311. return new torch._C.ExitPair(this._false_val, []);
  18312. }
  18313. constructWillExitPair(exit_val_ref) {
  18314. return new torch._C.ExitPair(this._true_val, exit_val_ref);
  18315. }
  18316. getExitStatus(exit_pair) {
  18317. const exit_v = exit_pair.hasExited();
  18318. if (exit_v === this._true_val) {
  18319. return 'WILL';
  18320. } else if (exit_v === this._false_val) {
  18321. return 'WONT';
  18322. } else if (exit_v === this._throws_val) {
  18323. return 'THROWS';
  18324. }
  18325. return 'MIGHT';
  18326. }
  18327. static owningNodeKind(block) {
  18328. if (block.owningNode()) {
  18329. return block.owningNode().kind();
  18330. }
  18331. return null;
  18332. }
  18333. static isGraphOrClosureBlock(block) {
  18334. return block.owningNode() === null || torch._C.ExitTransformer.owningNodeKind(block) === 'prim::Closure';
  18335. }
  18336. static removeOutputs(b) {
  18337. while (b.outputs().length > 0) {
  18338. b.eraseOutput(0);
  18339. }
  18340. }
  18341. static registerBlockOutputs(b, outs) {
  18342. for (const out of outs) {
  18343. b.registerOutput(out);
  18344. }
  18345. }
  18346. static replaceBlockOutputs(b, outs) {
  18347. torch._C.ExitTransformer.removeOutputs(b);
  18348. torch._C.ExitTransformer.registerBlockOutputs(b, outs);
  18349. }
  18350. });
  18351. this.registerFunction('torch._C.convertWithBlocksToEnterExitNodes', (/* graph */) => {
  18352. });
  18353. this.registerFunction('torch._C.TransformExits', (graph) => {
  18354. torch._C.convertEnterExitNodesToWithBlocks(graph);
  18355. const e_loop = new torch._C.ExitTransformer(graph);
  18356. e_loop.transformLoopContinuations();
  18357. const e_ret = new torch._C.ExitTransformer(graph);
  18358. e_ret.transformReturnStmts();
  18359. torch._C.inlineConsecutiveIfs(graph.block());
  18360. torch._C.convertWithBlocksToEnterExitNodes(graph);
  18361. });
  18362. this.registerFunction('torch._C.normalizeRSub', (iter) => {
  18363. if (iter.kind() === 'aten::rsub' && iter.schema() && iter.schema().overload === 'Tensor') {
  18364. const args = iter.inputs();
  18365. const newSub = iter.replaceWithNewSymbol('aten::sub');
  18366. newSub.replaceInput(0, args[1]);
  18367. newSub.replaceInput(1, args[0]);
  18368. iter.destroyCurrent();
  18369. return true;
  18370. }
  18371. return false;
  18372. });
  18373. this.registerFunction('torch._C.normalizeOpAliases', (/* iter */) => {
  18374. });
  18375. this.registerFunction('torch._C.normalizeIsBool', (iter) => {
  18376. const args = iter.inputs();
  18377. if (args.length === 2 && args[0].type() === torch.BoolType.get() && args[1].type() === torch.BoolType.get()) {
  18378. if (iter.kind() === 'aten::__is__') {
  18379. iter.replaceWithNewSymbol('aten::eq');
  18380. iter.destroyCurrent();
  18381. return true;
  18382. }
  18383. if (iter.kind() === 'aten::__isnot__') {
  18384. iter.replaceWithNewSymbol('aten::ne');
  18385. iter.destroyCurrent();
  18386. return true;
  18387. }
  18388. }
  18389. return false;
  18390. });
  18391. this.registerFunction('torch._C.NormalizeOps', (block) => {
  18392. for (const it of block.nodes()) {
  18393. for (const sub of it.blocks()) {
  18394. torch._C.NormalizeOps(sub);
  18395. }
  18396. if (torch._C.normalizeRSub(it)) {
  18397. continue;
  18398. }
  18399. if (torch._C.normalizeOpAliases(it)) {
  18400. continue;
  18401. }
  18402. if (torch._C.normalizeIsBool(it)) {
  18403. continue;
  18404. }
  18405. }
  18406. });
  18407. this.registerFunction('torch._C.getInlineEverythingMode', () => {
  18408. return false;
  18409. });
  18410. this.registerFunction('torch._C.runCleanupPasses', (to_clean) => {
  18411. /*
  18412. torch._C.liftClosures(to_clean);
  18413. torch._C.inlineForkedClosures(to_clean);
  18414. */
  18415. if (torch._C.getInlineEverythingMode()) {
  18416. torch._C.Inline(to_clean);
  18417. }
  18418. /*
  18419. torch._C.eraseListLiterals(to_clean);
  18420. */
  18421. torch._C.LowerSimpleTuples(to_clean);
  18422. torch._C.ConstantPropagationImmutableTypes(to_clean);
  18423. torch._C.ConstantPooling(to_clean);
  18424. /*
  18425. torch._C.CanonicalizeOutputs(to_clean);
  18426. torch._C.AnnotateWarns(to_clean);
  18427. */
  18428. });
  18429. this.registerType('torch.jit._script.ScriptModule', class extends torch.nn.modules.module.Module {});
  18430. this.registerType('torch.jit._trace.TracedModule', class extends torch.jit._script.ScriptModule {});
  18431. this.registerType('torch.jit._trace.TopLevelTracedModule', class extends torch.jit._trace.TracedModule {});
  18432. this.registerType('torch.jit._script.RecursiveScriptModule', class extends torch.jit._script.ScriptModule {
  18433. constructor(cpp_module) {
  18434. super();
  18435. this._initializing = true;
  18436. this._c = cpp_module;
  18437. }
  18438. static _construct(cpp_module, init_fn) {
  18439. const script_module = new torch.jit._script.RecursiveScriptModule(cpp_module);
  18440. init_fn(script_module);
  18441. torch.jit._script.RecursiveScriptModule._finalize_scriptmodule(script_module);
  18442. return script_module;
  18443. }
  18444. static _finalize_scriptmodule(script_module) {
  18445. script_module._parameters = new torch.ParameterDict(script_module._c).items();
  18446. script_module._buffers = new torch.BufferDict(script_module._c).items();
  18447. // script_module._modules = OrderedModuleDict(script_module._c, script_module._modules)
  18448. script_module._initializing = false;
  18449. }
  18450. get graph() {
  18451. // return this._c._get_method('forward').graph;
  18452. return this._c.graph;
  18453. }
  18454. get code_with_constants() {
  18455. // return this.forward.code_with_constants;
  18456. return this._c.code_with_constants;
  18457. }
  18458. __setattr__(name, value) {
  18459. if (this._initializing) {
  18460. super.__setattr__(name, value);
  18461. } else if (this._modules.has(name)) {
  18462. this._modules.set(name, value);
  18463. } else if (this._c.hasattr(name)) {
  18464. this._c.setattr(name, value);
  18465. } else {
  18466. //
  18467. }
  18468. }
  18469. __getattr__(name) {
  18470. if (this._initializing) {
  18471. return super.__getattr__(name);
  18472. }
  18473. if (this._modules.has(name)) {
  18474. return this._modules.get(name);
  18475. }
  18476. if (this._c.hasattr(name)) {
  18477. return this._c.getattr(name);
  18478. }
  18479. if (this._c._has_method(name)) {
  18480. //
  18481. }
  18482. return super.__getattr__(name);
  18483. }
  18484. });
  18485. torch.jit.ScriptModule = torch.jit._script.ScriptModule;
  18486. torch.jit.RecursiveScriptModule = torch.jit._script.RecursiveScriptModule;
  18487. torch.jit.TopLevelTracedModule = torch.jit._trace.TopLevelTracedModule;
  18488. torch.CompilationUnit = torch.jit.CompilationUnit;
  18489. torch._C.CompilationUnit = torch.jit.CompilationUnit;
  18490. torch._C.ScriptModule = torch.ScriptModule;
  18491. torch._C.ClassType = torch.ClassType;
  18492. this.registerType('torch._C.FlatBuffersLoader', class {
  18493. constructor(cu) {
  18494. this._cu = cu;
  18495. const torch = cu.execution.__import__('torch');
  18496. this._torch = torch;
  18497. const dtypes = Array.from(new Set(Object.values(torch).filter((obj) => obj instanceof torch.dtype)));
  18498. this._dtypes = new Map(dtypes.map((dtype) => [dtype.scalar_type(), dtype]));
  18499. this._ivalue_parsers = new Map();
  18500. this._ivalue_parsers.set(torch.mobile.serialization.Int, (ivalue) => ivalue.val.int_val);
  18501. this._ivalue_parsers.set(torch.mobile.serialization.Bool, (ivalue) => ivalue.val.bool_val);
  18502. this._ivalue_parsers.set(torch.mobile.serialization.Double, (ivalue) => ivalue.val.double_val);
  18503. this._ivalue_parsers.set(torch.mobile.serialization.TensorMetadata, (ivalue) => this.parseTensor(ivalue));
  18504. this._ivalue_parsers.set(torch.mobile.serialization.Object, (ivalue) => this.parseObject(ivalue));
  18505. }
  18506. parseModule(module) {
  18507. this._module = module;
  18508. this._all_functions = new Map();
  18509. this._all_ivalues = new Array(module.ivalues.length);
  18510. this._all_types = new Array(module.object_types.length);
  18511. const mobile_ivalue_size = module.mobile_ivalue_size ? module.mobile_ivalue_size : module.ivalues.length;
  18512. for (let i = 0; i < mobile_ivalue_size; i++) {
  18513. this.parseAndPopulate(i, module.ivalues[i]);
  18514. }
  18515. const m = this._all_ivalues[module.state_obj];
  18516. for (const [name, value] of this._all_functions) {
  18517. const class_index = module.ivalues[name].val.class_type;
  18518. const class_type = this._all_types[class_index];
  18519. if (value) {
  18520. class_type.addMethod(value);
  18521. }
  18522. }
  18523. m._min_operator_version = module.operator_version;
  18524. m._bytecode_version = module.bytecode_version;
  18525. return m;
  18526. }
  18527. parseAndPopulate(i, ivalue) {
  18528. if (ivalue.val instanceof torch.mobile.serialization.Function) {
  18529. this._all_functions.set(i, this.parseFunction(ivalue.val));
  18530. } else {
  18531. this._all_ivalues[i] = this.parseIValue(ivalue);
  18532. }
  18533. }
  18534. parseFunction(/* val */) {
  18535. return null;
  18536. }
  18537. parseIValue(ivalue) {
  18538. if (ivalue.val) {
  18539. const callback = this._ivalue_parsers.get(ivalue.val.constructor);
  18540. return callback(ivalue);
  18541. }
  18542. return null;
  18543. }
  18544. parseTensor(ivalue) {
  18545. return this.parseTensorFromMetadata(ivalue.val);
  18546. }
  18547. parseTensorFromMetadata(metadata) {
  18548. if (metadata.quantized_schema) {
  18549. throw new torch.Error('Quantized schema not implemented.');
  18550. }
  18551. const index = metadata.storage_location_index;
  18552. const data = this._module.storage_data[index].data;
  18553. const dtype = this._dtypes.get(metadata.scalar_type);
  18554. const size = data.length / dtype.itemsize();
  18555. const storage = new torch.storage.TypedStorage(size, dtype);
  18556. storage._set_cdata(data);
  18557. const tensor = new torch.Tensor();
  18558. const shape = Array.from(metadata.sizes);
  18559. const stride = Array.from(metadata.strides);
  18560. tensor.__setstate__([storage, metadata.storage_offset, shape, stride]);
  18561. return tensor;
  18562. }
  18563. parseObject(ivalue) {
  18564. const object = ivalue.val;
  18565. const obj_type = this._module.object_types[object.type_index];
  18566. const cls = this.getOrCreateClassTypeForObject(object);
  18567. switch (obj_type.type) {
  18568. case torch.mobile.serialization.TypeType.CLASS_WITH_FIELD: {
  18569. const torch = this._torch;
  18570. const obj = torch.ScriptObject.create(cls);
  18571. for (let i = 0; i < object.attrs.length; i++) {
  18572. const attr_name = obj_type.attr_names[i];
  18573. const val = this._all_ivalues[object.attrs[i]];
  18574. obj.__setattr__(attr_name, val);
  18575. }
  18576. return obj;
  18577. }
  18578. case torch.mobile.serialization.TypeType.CUSTOM_CLASS:
  18579. case torch.mobile.serialization.TypeType.CLASS_WITH_SETSTATE:
  18580. default: {
  18581. throw new python.Error(`Unknown object type type '${obj_type.type}'.`);
  18582. }
  18583. }
  18584. }
  18585. getOrCreateClassTypeForObject(object) {
  18586. let cls = this._all_types[object.type_index];
  18587. const obj_type = this._module.object_types[object.type_index];
  18588. if (!cls) {
  18589. const name = obj_type.type_name;
  18590. if (name.startsWith('__torch__') || name.startsWith('torch.jit')) {
  18591. cls = this._cu.get_class(new torch._C.QualifiedName(name));
  18592. if (!cls) {
  18593. const torch = this._torch;
  18594. cls = torch.ClassType.create(name, this._cu, true);
  18595. this._cu.register_type(cls);
  18596. }
  18597. } else {
  18598. // cls = c10::parseType(qn_str).cast<ClassType>();
  18599. }
  18600. this._all_types[object.type_index] = cls;
  18601. if (obj_type.type === torch.mobile.serialization.TypeType.CLASS_WITH_FIELD) {
  18602. for (let i = 0; i < object.attrs.length; i++) {
  18603. // const val = this._all_ivalues[object.attrs[i]];
  18604. cls.addAttribute(obj_type.attr_names[i] /*, null val.type(c10::DynamicType) */);
  18605. }
  18606. }
  18607. }
  18608. return cls;
  18609. }
  18610. });
  18611. this.registerType('torch.export.UnflattenedModule', class extends torch.nn.modules.module.Module {
  18612. constructor(export_module, flat_args_adapter) {
  18613. super();
  18614. const export_graph = copy.deepcopy(export_module.graph);
  18615. self.graph_signature = copy.deepcopy(export_module.graph_signature);
  18616. this.graph = torch.fx.Graph();
  18617. this.graph.owning_module = this;
  18618. this.module_call_graph = copy.deepcopy(export_module.module_call_graph);
  18619. this.flat_args_adapter = flat_args_adapter;
  18620. this.adapted = false;
  18621. // this._run_with_interpreter = RUN_WITH_INTERPRETER
  18622. this._inplace_buffer_mutations(export_graph, this.graph_signature);
  18623. }
  18624. });
  18625. this.registerType('torch.export.graph_signature.ExportGraphSignature', class {
  18626. constructor(input_specs, output_specs) {
  18627. this.input_specs = input_specs;
  18628. this.output_specs = output_specs;
  18629. }
  18630. get user_inputs() {
  18631. const user_inputs = [];
  18632. for (const s of this.input_specs) {
  18633. if (s.kind !== torch.export.graph_signature.InputKind.USER_INPUT) {
  18634. continue;
  18635. }
  18636. if (s.arg instanceof torch.export.graph_signature.TensorArgument ||
  18637. s.arg instanceof torch.export.graph_signature.SymIntArgument ||
  18638. s.arg instanceof torch.export.graph_signature.CustomObjArgument) {
  18639. user_inputs.push(s.arg.name);
  18640. } else if (s.arg instanceof torch.export.graph_signature.ConstantArgument) {
  18641. user_inputs.push(s.arg.value);
  18642. } else {
  18643. throw new python.Error(`Unsupported user input '${s.arg}'.`);
  18644. }
  18645. }
  18646. return user_inputs;
  18647. }
  18648. get user_outputs() {
  18649. const user_outputs = [];
  18650. for (const s of this.output_specs) {
  18651. if (s.kind !== torch.export.graph_signature.OutputKind.USER_OUTPUT) {
  18652. continue;
  18653. }
  18654. if (s.arg instanceof torch.export.graph_signature.TensorArgument ||
  18655. s.arg instanceof torch.export.graph_signature.SymIntArgument ||
  18656. s.arg instanceof torch.export.graph_signature.CustomObjArgument) {
  18657. user_outputs.push(s.arg.name);
  18658. } else if (s.arg instanceof torch.export.graph_signature.ConstantArgument) {
  18659. user_outputs.push(s.arg.value);
  18660. } else {
  18661. throw new python.Error(`Unsupported user output '${s.arg}'.`);
  18662. }
  18663. }
  18664. return user_outputs;
  18665. }
  18666. get inputs_to_parameters() {
  18667. return new Map(this.input_specs
  18668. .filter((s) => s.kind === torch.export.graph_signature.InputKind.PARAMETER && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  18669. .map((s) => [s.arg.name, s.target]));
  18670. }
  18671. get inputs_to_buffers() {
  18672. return new Map(this.input_specs
  18673. .filter((s) => s.kind === torch.export.graph_signature.InputKind.BUFFER && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  18674. .map((s) => [s.arg.name, s.target]));
  18675. }
  18676. get inputs_to_lifted_tensor_constants() {
  18677. return new Map(this.input_specs
  18678. .filter((s) => s.kind === torch.export.graph_signature.InputKind.CONSTANT_TENSOR && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  18679. .map((s) => [s.arg.name, s.target]));
  18680. }
  18681. });
  18682. torch.export.graph_signature.InputKind = {
  18683. USER_INPUT: 0,
  18684. PARAMETER: 1,
  18685. BUFFER: 2,
  18686. CONSTANT_TENSOR: 3,
  18687. CUSTOM_OBJ: 4,
  18688. TOKEN: 5
  18689. };
  18690. this.registerType('torch.export.graph_signature.InputSpec', class {
  18691. constructor(kind, arg, target, persistent) {
  18692. this.kind = kind;
  18693. this.arg = arg;
  18694. this.target = target;
  18695. this.persistent = persistent || null;
  18696. }
  18697. });
  18698. torch.export.graph_signature.OutputKind = {
  18699. USER_OUTPUT: 0,
  18700. LOSS_OUTPUT: 1,
  18701. BUFFER_MUTATION: 2,
  18702. GRADIENT_TO_PARAMETER: 3,
  18703. GRADIENT_TO_USER_INPUT: 4,
  18704. USER_INPUT_MUTATION: 5,
  18705. TOKEN: 6
  18706. };
  18707. this.registerType('torch.export.graph_signature.OutputSpec', class {
  18708. constructor(kind, arg, target) {
  18709. this.kind = kind;
  18710. this.arg = arg;
  18711. this.target = target;
  18712. }
  18713. });
  18714. this.registerType('torch.export.graph_signature.ConstantArgument', class {
  18715. constructor(name, value) {
  18716. this.name = name;
  18717. this.value = value; // Union[int, float, bool, str, None]
  18718. }
  18719. });
  18720. this.registerType('torch.export.graph_signature.TensorArgument', class {
  18721. constructor(name) {
  18722. this.name = name;
  18723. }
  18724. });
  18725. this.registerType('torch.export.graph_signature.SymIntArgument', class {
  18726. constructor(name) {
  18727. this.name = name;
  18728. }
  18729. });
  18730. this.registerType('torch.export.graph_signature.CustomObjArgument', class {
  18731. constructor(name, class_fqn, fake_val) {
  18732. this.name = name;
  18733. this.class_fqn = class_fqn;
  18734. this.fake_val = fake_val;
  18735. }
  18736. });
  18737. this.registerType('torch.export.exported_program.ExportedProgram', class {
  18738. constructor(root, graph, graph_signature, state_dict, range_constraints, module_call_graph, example_inputs, verifier, tensor_constants, constants) {
  18739. // graph._codegen = torch.fx.graph.CodeGen()
  18740. this._graph_module = this._create_graph_module_for_export(root, graph);
  18741. if (root instanceof torch.fx.GraphModule) {
  18742. // this._graph_module.meta.update(root.meta);
  18743. }
  18744. this._graph_signature = graph_signature;
  18745. this._state_dict = state_dict;
  18746. this._range_constraints = range_constraints;
  18747. this._module_call_graph = module_call_graph;
  18748. this._example_inputs = example_inputs;
  18749. this._constants = tensor_constants || constants || {};
  18750. }
  18751. _create_graph_module_for_export(root, graph) {
  18752. let gm = null;
  18753. try {
  18754. gm = new torch.fx.GraphModule(root, graph);
  18755. } catch {
  18756. const gm = new torch.fx.GraphModule(root, torch.fx.Graph());
  18757. gm._graph = graph;
  18758. }
  18759. return gm;
  18760. }
  18761. get graph_module() {
  18762. return this._graph_module;
  18763. }
  18764. get graph() {
  18765. return this._graph_module.graph;
  18766. }
  18767. get graph_signature() {
  18768. return this._graph_signature;
  18769. }
  18770. get state_dict() {
  18771. return this._state_dict;
  18772. }
  18773. get constants() {
  18774. return this._constants;
  18775. }
  18776. });
  18777. this.registerType('torch.export.exported_program.ModuleCallEntry', class {});
  18778. this.registerType('torch.export.exported_program.ModuleCallSignature', class {});
  18779. this.registerFunction('torch.export.exported_program._create_graph_module_for_export', (root, graph) => {
  18780. return new torch.fx.graph_module.GraphModule(root, graph);
  18781. });
  18782. this.registerFunction('torch.export.unflatten', (module, flat_args_adapter) => {
  18783. module = torch.export._remove_effect_tokens(module);
  18784. return new torch.export.UnflattenedModule(module, flat_args_adapter);
  18785. });
  18786. this.registerFunction('torch._export.exported_program._create_graph_module_for_export', (root, graph) => {
  18787. return new torch.fx.graph_module.GraphModule(root, graph);
  18788. });
  18789. this.registerType('torch._export.serde.serialize.SerializedArtifact', class {
  18790. constructor(exported_program, state_dict, constants, example_inputs) {
  18791. this.exported_program = exported_program;
  18792. this.state_dict = state_dict;
  18793. this.constants = constants;
  18794. this.example_inputs = example_inputs;
  18795. }
  18796. });
  18797. torch._export.serde.serialize._SYM_OPS = new Set([
  18798. operator.eq, operator.ne, operator.le, operator.ge, operator.lt, operator.gt,
  18799. operator.neg, operator.pos, operator.and_, operator.or_,
  18800. math.trunc, torch.sym_not,
  18801. operator.mul, operator.add, operator.sub, operator.floordiv, operator.mod, operator.pow,
  18802. torch.sym_int, torch.sym_float, torch.sym_ite, torch.sym_max, torch.sym_min, torch.sym_sqrt,
  18803. operator.truediv, operator.and_
  18804. ]);
  18805. this.registerType('torch._export.serde.union._Union', class {
  18806. constructor(obj) {
  18807. if (obj.$type) {
  18808. this.type = obj.$type;
  18809. this[obj.$type] = obj.$value;
  18810. delete obj.$type;
  18811. delete obj.$value;
  18812. } else if (obj.type) {
  18813. this.type = obj.type;
  18814. const entries = Object.entries(obj).filter(([key]) => key !== 'type');
  18815. this[obj.type] = Object.fromEntries(entries);
  18816. } else {
  18817. let entries = Object.entries(obj);
  18818. if (entries.length > 1) {
  18819. entries = entries.filter(([, value]) => value !== null);
  18820. }
  18821. if (entries.length !== 1) {
  18822. throw new python.Error(`Invalid union type '${entries.map(([key]) => key).join(',')}'.`);
  18823. }
  18824. const [entry] = entries;
  18825. const [type, value] = entry;
  18826. this.type = type;
  18827. this[type] = value;
  18828. }
  18829. }
  18830. get value() {
  18831. return this[this.type];
  18832. }
  18833. });
  18834. this.registerType('torch._export.serde.schema.NamedArgument', class {
  18835. constructor(obj) {
  18836. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  18837. this.name = obj.name;
  18838. }
  18839. });
  18840. this.registerType('torch._export.serde.schema.Argument', class extends torch._export.serde.union._Union {
  18841. constructor(obj) {
  18842. super(obj);
  18843. switch (this.type) {
  18844. case 'as_int':
  18845. case 'as_ints':
  18846. case 'as_float':
  18847. case 'as_floats':
  18848. case 'as_bool':
  18849. case 'as_bools':
  18850. case 'as_string':
  18851. case 'as_strings':
  18852. case 'as_scalar_type':
  18853. case 'as_device':
  18854. case 'as_memory_format':
  18855. case 'as_layout':
  18856. break;
  18857. case 'as_none':
  18858. this.as_none = null;
  18859. break;
  18860. case 'as_tensor':
  18861. this.as_tensor = new torch._export.serde.schema.TensorArgument(this.as_tensor);
  18862. break;
  18863. case 'as_tensors':
  18864. this.as_tensors = this.as_tensors.map((item) => new torch._export.serde.schema.TensorArgument(item));
  18865. break;
  18866. case 'as_graph':
  18867. this.as_graph = new torch._export.serde.schema.GraphArgument(this.as_graph);
  18868. break;
  18869. case 'as_sym_int':
  18870. this.as_sym_int = new torch._export.serde.schema.SymIntArgument(this.as_sym_int);
  18871. break;
  18872. case 'as_sym_ints':
  18873. this.as_sym_ints = this.as_sym_ints.map((item) => new torch._export.serde.schema.SymIntArgument(item));
  18874. break;
  18875. case 'as_sym_bool':
  18876. this.as_sym_bool = new torch._export.serde.schema.SymBoolArgument(this.as_sym_bool);
  18877. break;
  18878. case 'as_sym_bools':
  18879. this.as_sym_bools = this.as_sym_bools.map((item) => new torch._export.serde.schema.SymBoolArgument(item));
  18880. break;
  18881. case 'as_sym_float':
  18882. this.as_sym_float = new torch._export.serde.schema.SymFloatArgument(this.as_sym_float);
  18883. break;
  18884. case 'as_sym_floats':
  18885. this.as_sym_floats = this.as_sym_float.map((item) => new torch._export.serde.schema.SymFloatArgument(item));
  18886. break;
  18887. case 'as_optional_tensors':
  18888. this.as_optional_tensors = this.as_optional_tensors.map((item) => new torch._export.serde.schema.OptionalTensorArgument(item));
  18889. break;
  18890. case 'as_custom_obj':
  18891. this.as_custom_obj = new torch._export.serde.schema.CustomObjArgument(this.as_custom_obj);
  18892. break;
  18893. // case 'as_graph': GraphArgument
  18894. default:
  18895. throw new python.Error(`Unsupported argument '${this.type}'.`);
  18896. }
  18897. }
  18898. });
  18899. this.registerType('torch._export.serde.schema.Node', class {
  18900. constructor(obj) {
  18901. this.target = obj.target;
  18902. this.inputs = obj.inputs.map((input) => new torch._export.serde.schema.NamedArgument(input));
  18903. this.outputs = obj.outputs.map((output) => new torch._export.serde.schema.Argument(output));
  18904. this.metadata = new Map(Object.entries(obj.metadata));
  18905. }
  18906. });
  18907. torch._export.serde.schema.ScalarType = {
  18908. UNKNOWN: 0,
  18909. BYTE: 1,
  18910. CHAR: 2,
  18911. SHORT: 3,
  18912. INT: 4,
  18913. LONG: 5,
  18914. HALF: 6,
  18915. FLOAT: 7,
  18916. DOUBLE: 8,
  18917. COMPLEXHALF: 9,
  18918. COMPLEXFLOAT: 10,
  18919. COMPLEXDOUBLE: 11,
  18920. BOOL: 12,
  18921. BFLOAT16: 13,
  18922. UINT16: 28,
  18923. FLOAT8E4M3FN: 29,
  18924. FLOAT8E5M2: 30,
  18925. FLOAT8E4M3FNUZ: 31,
  18926. FLOAT8E5M2FNUZ: 32,
  18927. };
  18928. torch._export.serde.schema.Layout = {
  18929. Unknown: 0,
  18930. SparseCoo: 1,
  18931. SparseCsr: 2,
  18932. SparseCsc: 3,
  18933. SparseBsr: 4,
  18934. SparseBsc: 5,
  18935. _mkldnn: 6,
  18936. Strided: 7
  18937. };
  18938. torch._export.serde.schema.MemoryFormat = {
  18939. Unknown: 0,
  18940. ContiguousFormat: 1,
  18941. ChannelsLast: 2,
  18942. ChannelsLast3d: 3,
  18943. PreserveFormat: 4,
  18944. };
  18945. this.registerType('torch._export.serde.schema.Device', class {
  18946. constructor(obj) {
  18947. Object.assign(this, { ...obj });
  18948. }
  18949. });
  18950. this.registerType('torch._export.serde.schema.TensorMeta', class {
  18951. constructor(obj) {
  18952. obj = obj.meta || obj;
  18953. this.dtype = obj.dtype;
  18954. this.sizes = obj.sizes.map((size) => new torch._export.serde.schema.SymInt(size));
  18955. this.requires_grad = obj.requires_grad;
  18956. this.device = obj.device;
  18957. this.strides = obj.strides.map((stride) => new torch._export.serde.schema.SymInt(stride));
  18958. this.storage_offset = new torch._export.serde.schema.SymInt(Number.isInteger(obj.storage_offset) ? { as_int: obj.storage_offset } : obj.storage_offset);
  18959. this.layout = obj.layout;
  18960. }
  18961. });
  18962. this.registerType('torch._export.serde.schema.Graph', class {
  18963. constructor(obj) {
  18964. this.inputs = obj.inputs.map((input) => new torch._export.serde.schema.Argument(input));
  18965. this.outputs = obj.outputs.map((output) => new torch._export.serde.schema.Argument(output));
  18966. this.nodes = obj.nodes.map((node) => new torch._export.serde.schema.Node(node));
  18967. this.tensor_values = new Map(Object.entries(obj.tensor_values).map(([key, value]) => [key, new torch._export.serde.schema.TensorMeta(value)]));
  18968. this.sym_int_values = new Map(Object.entries(obj.sym_int_values).map(([key, value]) => [key, new torch._export.serde.schema.SymInt(value)]));
  18969. this.sym_bool_values = new Map(Object.entries(obj.sym_bool_values).map(([key, value]) => [key, new torch._export.serde.schema.SymBool(value)]));
  18970. this.is_single_tensor_return = obj.is_single_tensor_return;
  18971. this.custom_obj_values = new Map(Object.entries(obj.custom_obj_values || {}).map(([key, value]) => [key, new torch._export.serde.schema.CustomObjArgument(value)]));
  18972. if (obj.contants) {
  18973. // this.constants = new Map(Object.entries(serialized_graph.constants).map(([k, v]) => [k, torch.load(v)]));
  18974. // graph_signature -> input_specs -> tensor_constant
  18975. }
  18976. }
  18977. });
  18978. this.registerType('torch._export.serde.schema.ModuleCallSignature', class {
  18979. constructor(obj) {
  18980. Object.assign(this, { ...obj });
  18981. this.inputs = this.inputs.map((item) => new torch._export.serde.schema.Argument(item));
  18982. this.outputs = this.outputs.map((item) => new torch._export.serde.schema.Argument(item));
  18983. }
  18984. });
  18985. this.registerType('torch._export.serde.schema.ModuleCallEntry', class {
  18986. constructor(obj) {
  18987. Object.assign(this, { ...obj });
  18988. this.signature = this.signature ? new torch._export.serde.schema.ModuleCallSignature(this.signature) : null;
  18989. }
  18990. });
  18991. this.registerType('torch._export.serde.schema.GraphModule', class {
  18992. constructor(obj) {
  18993. this.graph = new torch._export.serde.schema.Graph(obj.graph);
  18994. this.signature = new torch._export.serde.schema.GraphSignature(obj.signature);
  18995. this.module_call_graph = obj.module_call_graph.map((item) => new torch._export.serde.schema.ModuleCallEntry(item));
  18996. this.metadata = new Map(Object.entries(obj.metadata || {}));
  18997. }
  18998. });
  18999. this.registerType('torch._export.serde.schema.ExportedProgram', class {
  19000. constructor(obj) {
  19001. Object.assign(this, { ...obj });
  19002. this.graph_module = new torch._export.serde.schema.GraphModule(obj.graph_module);
  19003. }
  19004. });
  19005. this.registerType('torch._export.serde.schema.SymExprHint', class extends torch._export.serde.union._Union {});
  19006. this.registerType('torch._export.serde.schema.SymExpr', class {
  19007. constructor(obj) {
  19008. this.expr_str = obj.expr_str;
  19009. this.hint = obj.hint ? new torch._export.serde.schema.SymExprHint(obj.hint) : null;
  19010. }
  19011. });
  19012. this.registerType('torch._export.serde.schema.SymInt', class extends torch._export.serde.union._Union {
  19013. constructor(obj) {
  19014. super(obj);
  19015. if (this.type === 'as_int') {
  19016. // continue
  19017. } else if (this.type === 'as_expr') {
  19018. this.as_expr = new torch._export.serde.schema.SymExpr(this.as_expr);
  19019. } else {
  19020. throw new python.Error(`Unsupported symbolic int '${this.type}'.`);
  19021. }
  19022. }
  19023. });
  19024. this.registerType('torch._export.serde.schema.SymBool', class extends torch._export.serde.union._Union {
  19025. constructor(obj) {
  19026. super(obj);
  19027. if (this.type === 'as_bool') {
  19028. // continue
  19029. } else if (this.type === 'as_expr') {
  19030. this.as_expr = new torch._export.serde.schema.SymExpr(this.as_expr);
  19031. } else {
  19032. throw new python.Error(`Unsupported symbolic bool '${this.type}'.`);
  19033. }
  19034. }
  19035. });
  19036. this.registerType('torch._export.serde.schema.SymIntArgument', class extends torch._export.serde.union._Union {
  19037. constructor(obj) {
  19038. super(obj);
  19039. Object.assign(this, { ...obj });
  19040. }
  19041. });
  19042. this.registerType('torch._export.serde.schema.SymFloatArgument', class extends torch._export.serde.union._Union {
  19043. constructor(obj) {
  19044. super(obj);
  19045. Object.assign(this, { ...obj });
  19046. }
  19047. });
  19048. this.registerType('torch._export.serde.schema.SymBoolArgument', class extends torch._export.serde.union._Union {
  19049. constructor(obj) {
  19050. super(obj);
  19051. Object.assign(this, { ...obj });
  19052. }
  19053. });
  19054. this.registerType('torch._export.serde.schema.CustomObjArgument', class {
  19055. constructor(obj) {
  19056. Object.assign(this, { ...obj });
  19057. }
  19058. });
  19059. this.registerType('torch._export.serde.schema.GraphSignature', class {
  19060. constructor(obj) {
  19061. this.input_specs = [];
  19062. if (Array.isArray(obj.input_specs)) {
  19063. this.input_specs = obj.input_specs.map((input_spec) => new torch._export.serde.schema.InputSpec(input_spec));
  19064. }
  19065. if (Array.isArray(obj.user_inputs)) {
  19066. for (const user_input of obj.user_inputs) {
  19067. this.input_specs.push(new torch._export.serde.schema.InputSpec({ user_input: { arg: { as_string: user_input } } }));
  19068. }
  19069. }
  19070. if (obj.inputs_to_parameters) {
  19071. for (const [input, parameter_name] of Object.entries(obj.inputs_to_parameters)) {
  19072. this.input_specs.push(new torch._export.serde.schema.InputSpec({ parameter: { arg: { name: input }, parameter_name } }));
  19073. }
  19074. }
  19075. this.output_specs = [];
  19076. if (Array.isArray(obj.output_specs)) {
  19077. this.output_specs = obj.output_specs.map((output_spec) => new torch._export.serde.schema.OutputSpec(output_spec));
  19078. }
  19079. }
  19080. });
  19081. this.registerType('torch._export.serde.schema.UserInputSpec', class {
  19082. constructor(obj) {
  19083. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  19084. }
  19085. });
  19086. this.registerType('torch._export.serde.schema.InputToParameterSpec', class {
  19087. constructor(obj) {
  19088. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  19089. this.parameter_name = obj.parameter_name;
  19090. }
  19091. });
  19092. this.registerType('torch._export.serde.schema.InputToBufferSpec', class {
  19093. constructor(obj) {
  19094. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  19095. this.buffer_name = obj.buffer_name;
  19096. }
  19097. });
  19098. this.registerType('torch._export.serde.schema.InputToTensorConstantSpec', class {
  19099. constructor(obj) {
  19100. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  19101. this.tensor_constant_name = obj.tensor_constant_name;
  19102. }
  19103. });
  19104. this.registerType('torch._export.serde.schema.InputToConstantInputSpec', class {
  19105. constructor(obj) {
  19106. this.name = obj.name;
  19107. this.value = new torch._export.serde.schema.ConstantValue(obj.value);
  19108. }
  19109. });
  19110. this.registerType('torch._export.serde.schema.ConstantValue', class extends torch._export.serde.union._Union {
  19111. constructor(obj) {
  19112. super(obj);
  19113. if (this.type === 'as_int' || this.type === 'as_float' || this.type === 'as_bool' || this.type === 'as_string' || this.type === 'as_strings') {
  19114. // continue
  19115. } else if (this.type === 'as_none') {
  19116. this.as_none = null;
  19117. } else {
  19118. throw new python.Error(`Unsupported constant value type '${this.type}'.`);
  19119. }
  19120. }
  19121. });
  19122. this.registerType('torch._export.serde.schema.InputSpec', class extends torch._export.serde.union._Union {
  19123. constructor(obj) {
  19124. super(obj);
  19125. if (this.type === 'user_input') {
  19126. this.user_input = new torch._export.serde.schema.UserInputSpec(this.user_input);
  19127. } else if (this.type === 'parameter') {
  19128. this.parameter = new torch._export.serde.schema.InputToParameterSpec(this.parameter);
  19129. } else if (this.type === 'buffer') {
  19130. this.buffer = new torch._export.serde.schema.InputToBufferSpec(this.buffer);
  19131. } else if (this.type === 'tensor_constant') {
  19132. this.tensor_constant = new torch._export.serde.schema.InputToTensorConstantSpec(this.tensor_constant);
  19133. } else if (this.type === 'constant_input') {
  19134. this.constant_input = new torch._export.serde.schema.InputToConstantInputSpec(this.constant_input);
  19135. } else {
  19136. throw new python.Error(`Unsupported input spec type '${this.type}'.`);
  19137. }
  19138. /*
  19139. custom_obj: InputToCustomObjSpec
  19140. token: InputTokenSpec
  19141. */
  19142. }
  19143. });
  19144. this.registerType('torch._export.serde.schema.UserOutputSpec', class {
  19145. constructor(obj) {
  19146. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  19147. }
  19148. });
  19149. this.registerType('torch._export.serde.schema.BufferMutationSpec', class {
  19150. constructor(obj) {
  19151. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  19152. this.buffer_name = obj.buffer_name;
  19153. }
  19154. });
  19155. this.registerType('torch._export.serde.schema.GradientToParameterSpec', class {
  19156. constructor(obj) {
  19157. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  19158. this.parameter_name = obj.parameter_name;
  19159. }
  19160. });
  19161. this.registerType('torch._export.serde.schema.GradientToUserInputSpec', class {
  19162. constructor(obj) {
  19163. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  19164. this.user_input_name = obj.user_input_name;
  19165. }
  19166. });
  19167. this.registerType('torch._export.serde.schema.UserInputMutationSpec', class {
  19168. constructor(obj) {
  19169. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  19170. this.user_input_name = obj.user_input_name;
  19171. }
  19172. });
  19173. this.registerType('torch._export.serde.schema.OutputTokenSpec', class {
  19174. constructor(obj) {
  19175. this.arg = new torch._export.serde.schema.TokenArgument(obj.arg);
  19176. }
  19177. });
  19178. this.registerType('torch._export.serde.schema.OutputSpec', class extends torch._export.serde.union._Union {
  19179. constructor(obj) {
  19180. super(obj);
  19181. if (this.type === 'user_output') {
  19182. this.user_output = new torch._export.serde.schema.UserOutputSpec(this.user_output);
  19183. } else if (this.type === 'loss_output') {
  19184. this.loss_output = new torch._export.serde.schema.LossOutputSpec(this.loss_output);
  19185. } else if (this.type === 'buffer_mutation') {
  19186. this.buffer_mutation = new torch._export.serde.schema.BufferMutationSpec(this.buffer_mutation);
  19187. } else if (this.type === 'gradient_to_parameter') {
  19188. this.gradient_to_parameter = new torch._export.serde.schema.GradientToParameterSpec(this.gradient_to_parameter);
  19189. } else if (this.type === 'gradient_to_user_input') {
  19190. this.gradient_to_user_input = new torch._export.serde.schema.GradientToUserInputSpec(this.gradient_to_user_input);
  19191. } else if (this.type === 'user_input_mutation') {
  19192. this.user_input_mutation = new torch._export.serde.schema.UserInputMutationSpec(this.user_input_mutation);
  19193. } else if (this.type === 'token') {
  19194. this.token = new torch._export.serde.schema.OutputTokenSpec(this.token);
  19195. }
  19196. }
  19197. });
  19198. this.registerType('torch._export.serde.schema.TensorArgument', class {
  19199. constructor(obj) {
  19200. this.name = obj.name;
  19201. }
  19202. });
  19203. this.registerType('torch._export.serde.schema.TokenArgument', class {
  19204. constructor(obj) {
  19205. this.name = obj.name;
  19206. }
  19207. });
  19208. this.registerType('torch._export.serde.schema.GraphArgument', class {
  19209. constructor(obj) {
  19210. this.name = obj.name;
  19211. this.graph = new torch._export.serde.schema.Graph(obj.graph);
  19212. }
  19213. });
  19214. this.registerType('torch._export.serde.schema.OptionalTensorArgument', class extends torch._export.serde.union._Union {
  19215. constructor(obj) {
  19216. super(obj);
  19217. if (this.type === 'as_tensor') {
  19218. this.as_tensor = new torch._export.serde.schema.TensorArgument({ name: this.as_tensor });
  19219. } else if (this.type === 'as_none') {
  19220. this.as_none = null;
  19221. } else {
  19222. throw new python.Error(`Unsupported optional tensor argument '${this.type}'.`);
  19223. }
  19224. }
  19225. });
  19226. this.registerFunction('torch.export.pt2_archive._package._load_state_dict', (f, model_name) => {
  19227. const legacy_file = `data/weights/${model_name}.pt`;
  19228. if (f.has(legacy_file)) {
  19229. return f.get(legacy_file);
  19230. }
  19231. const weights_config_file = `data/weights/${model_name}_weights_config.json`;
  19232. if (!f.has(weights_config_file)) {
  19233. return null;
  19234. }
  19235. const weights_config = f.get(weights_config_file);
  19236. const state_dict_file_map = torch.export.pt2_archive._package._build_file_map(f, weights_config, 'data/weights/');
  19237. const state_dict = new builtins.dict();
  19238. for (const [weight_fqn, payload_meta] of Object.entries(weights_config.config)) {
  19239. if (payload_meta.use_pickle) {
  19240. const weight_bytes = f.get(`data/weights/${payload_meta.path_name}`);
  19241. const weight_tensor = torch.load(weight_bytes);
  19242. state_dict.set(weight_fqn, weight_tensor);
  19243. } else {
  19244. const tensor_meta = payload_meta.tensor_meta;
  19245. const tensor = state_dict_file_map.get(payload_meta.path_name);
  19246. const sizes = tensor_meta.sizes.map((s) => s.as_int);
  19247. const strides = tensor_meta.strides.map((s) => s.as_int);
  19248. const storage_offset = tensor_meta.storage_offset.as_int;
  19249. const weight_tensor = new torch.Tensor();
  19250. weight_tensor.__setstate__([tensor.storage(), storage_offset, sizes, strides]);
  19251. weight_tensor.requires_grad = tensor_meta.requires_grad || false;
  19252. if (payload_meta.is_param) {
  19253. state_dict.set(weight_fqn, new torch.nn.parameter.Parameter(weight_tensor, tensor_meta.requires_grad));
  19254. } else {
  19255. state_dict.set(weight_fqn, weight_tensor);
  19256. }
  19257. }
  19258. }
  19259. return state_dict;
  19260. });
  19261. this.registerFunction('torch.export.pt2_archive._package._load_constants', (f, model_name) => {
  19262. const legacy_file = `data/constants/${model_name}.pt`;
  19263. if (f.has(legacy_file)) {
  19264. const entries = f.get(legacy_file);
  19265. return new builtins.dict(entries);
  19266. }
  19267. const constants_config_file = `data/constants/${model_name}_constants_config.json`;
  19268. if (!f.has(constants_config_file)) {
  19269. return null;
  19270. }
  19271. const constants_config = f.get(constants_config_file);
  19272. const constant_file_map = torch.export.pt2_archive._package._build_file_map(f, constants_config, 'data/constants/');
  19273. const constants = new builtins.dict();
  19274. for (const [constant_fqn, payload_meta] of Object.entries(constants_config.config)) {
  19275. const path_name = payload_meta.path_name;
  19276. if (path_name.startsWith('tensor_')) {
  19277. if (payload_meta.use_pickle) {
  19278. const constant_bytes = f.get(`data/constants/${payload_meta.path_name}`);
  19279. const constant_tensor = torch.load(constant_bytes);
  19280. constants.set(constant_fqn, constant_tensor);
  19281. } else {
  19282. const tensor_meta = payload_meta.tensor_meta;
  19283. const tensor = constant_file_map.get(payload_meta.path_name);
  19284. const sizes = tensor_meta.sizes.map((s) => s.as_int);
  19285. const strides = tensor_meta.strides.map((s) => s.as_int);
  19286. const storage_offset = tensor_meta.storage_offset.as_int;
  19287. const constant_tensor = new torch.Tensor();
  19288. constant_tensor.__setstate__([tensor.storage(), storage_offset, sizes, strides]);
  19289. constants.set(constant_fqn, constant_tensor);
  19290. }
  19291. } else if (payload_meta.path_name.startsWith('custom_obj_')) {
  19292. const custom_obj_bytes = f.get(`data/constants/${payload_meta.path_name}`);
  19293. const custom_obj = torch._C._pickle_load_obj(custom_obj_bytes);
  19294. constants.set(constant_fqn, custom_obj);
  19295. }
  19296. }
  19297. return constants;
  19298. });
  19299. this.registerFunction('torch._export.serde.serialize.deserialize_scalar_type', (st) => {
  19300. if (!torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE.has(st)) {
  19301. throw new python.Error(`Unsupported scalar type '${st}'.`);
  19302. }
  19303. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE.get(st);
  19304. });
  19305. this.registerFunction('torch.export.pt2_archive._package._build_file_map', (archive_reader, config, base_dir) => {
  19306. const file_map = new builtins.dict();
  19307. for (const payload_meta of Object.values(config.config)) {
  19308. if (payload_meta.use_pickle) {
  19309. continue;
  19310. }
  19311. if (file_map.has(payload_meta.path_name)) {
  19312. continue;
  19313. }
  19314. const tensor_bytes = archive_reader.get(`${base_dir}${payload_meta.path_name}`);
  19315. const tensor = torch.export.pt2_archive._package._create_flat_tensor_from_bytes(tensor_bytes, payload_meta.tensor_meta);
  19316. file_map.set(payload_meta.path_name, tensor);
  19317. }
  19318. return file_map;
  19319. });
  19320. this.registerFunction('torch.export.pt2_archive._package._create_flat_tensor_from_bytes', (tensor_bytes, tensor_meta) => {
  19321. const dtype = torch._export.serde.serialize.deserialize_scalar_type(tensor_meta.dtype);
  19322. const itemsize = dtype.itemsize();
  19323. const num_elements = tensor_bytes.length / itemsize;
  19324. const storage = new torch.storage.TypedStorage(num_elements, dtype);
  19325. storage._set_cdata(tensor_bytes);
  19326. const tensor = new torch.Tensor();
  19327. tensor.__setstate__([storage, 0, [num_elements], [1]]);
  19328. tensor.requires_grad = tensor_meta.requires_grad || false;
  19329. return tensor;
  19330. });
  19331. this.registerFunction('torch.export.pt2_archive._package.load_pt2', (f, expected_opset_version) => {
  19332. const exported_programs = new Map();
  19333. for (const name of f.keys()) {
  19334. const match = name.match(/^models\/([^/]+)\.json$/);
  19335. if (match) {
  19336. const [, model_name] = match;
  19337. const serialized_exported_program = f.get(`models/${model_name}.json`);
  19338. const serialized_state_dict = torch.export.pt2_archive._package._load_state_dict(f, model_name);
  19339. const serialized_constants = torch.export.pt2_archive._package._load_constants(f, model_name);
  19340. const serialized_example_inputs = f.get(`data/sample_inputs/${model_name}.pt`, 'zip');
  19341. const artifact = new torch._export.serde.serialize.SerializedArtifact(serialized_exported_program, serialized_state_dict, serialized_constants, serialized_example_inputs);
  19342. const exported_program = torch._export.serde.serialize.deserialize(artifact, expected_opset_version);
  19343. exported_programs.set(model_name, exported_program);
  19344. }
  19345. }
  19346. return { exported_programs };
  19347. });
  19348. this.registerFunction('torch._export.serde.serialize._dict_to_dataclass', (cls, data) => {
  19349. if (data === null) {
  19350. return data;
  19351. }
  19352. if (cls) {
  19353. return new cls(data);
  19354. }
  19355. throw new python.Error(`Unsupported data class '${cls.__name__}'.`);
  19356. });
  19357. this.registerFunction('torch._export.serde.serialize.deserialize', (artifact, expected_opset_version) => {
  19358. const serialized_exported_program = torch._export.serde.serialize._dict_to_dataclass(torch._export.serde.schema.ExportedProgram, artifact.exported_program);
  19359. return new torch._export.serde.serialize.ExportedProgramDeserializer(expected_opset_version).deserialize(serialized_exported_program, artifact.state_dict, artifact.constants, artifact.example_inputs);
  19360. });
  19361. this.registerType('torch._export.serde.serialize.ExportedProgramDeserializer', class {
  19362. constructor(expected_opset_version) {
  19363. this.expected_opset_version = expected_opset_version;
  19364. }
  19365. deserialize(exported_program, state_dict, constants, example_inputs) {
  19366. const symbol_name_to_range = new Map(Object.entries(exported_program.range_constraints));
  19367. /*
  19368. symbol_name_to_range = {
  19369. k: symbolic_shapes.ValueRanges(_int_to_sympy_int(v.min_val), _int_to_sympy_int(v.max_val))
  19370. for k, v in exported_program.range_constraints.items()
  19371. }
  19372. */
  19373. const deserializer = new torch._export.serde.serialize.GraphModuleDeserializer();
  19374. const res = deserializer.deserialize(
  19375. exported_program.graph_module,
  19376. state_dict,
  19377. constants,
  19378. example_inputs,
  19379. symbol_name_to_range);
  19380. const range_constraints = null;
  19381. /*
  19382. range_constraints = self.deserialize_range_constraints(
  19383. symbol_name_to_range, res.names_to_symbols,
  19384. )
  19385. model_opset_version: Optional[Dict[str, int]] = serialized_artifact.exported_program.opset_version
  19386. self._validate_model_opset_version(model_opset_version)
  19387. upgrader = GraphModuleOpUpgrader(self.expected_opset_version, model_opset_version)
  19388. */
  19389. return new torch.export.exported_program.ExportedProgram(
  19390. res.graph_module, res.graph_module.graph, res.signature,
  19391. res.state_dict, range_constraints, res.module_call_graph, res.example_inputs,
  19392. null, // verifier=load_verifier(serialized_artifact.exported_program.dialect),
  19393. res.constants);
  19394. // return upgrader.upgrade(exported_program)
  19395. }
  19396. });
  19397. this.registerFunction('torch._export.serde.serialize.deserialize_torch_artifact', (serialized) => {
  19398. if (serialized instanceof builtins.dict || serialized instanceof builtins.tuple) {
  19399. return serialized;
  19400. }
  19401. if (serialized === null || serialized.length === 0) {
  19402. return new builtins.dict();
  19403. }
  19404. const artifact = torch.load(serialized);
  19405. return artifact;
  19406. });
  19407. this.registerType('torch._export.serde.serialize.GraphModuleDeserializer', class {
  19408. constructor() {
  19409. this.serialized_name_to_node = new builtins.dict();
  19410. this.serialized_name_to_meta = new builtins.dict(); // torch._export.serde.serialize.LazyMap
  19411. this.graph = new torch.fx.Graph();
  19412. this.module = new torch.nn.Module();
  19413. }
  19414. save_graph_module() {
  19415. const Context = class {
  19416. constructor(self) {
  19417. this.self = self;
  19418. }
  19419. __enter__() {
  19420. this.saved = [
  19421. this.self.graph,
  19422. this.self.module,
  19423. this.self.serialized_name_to_node,
  19424. this.self.serialized_name_to_meta,
  19425. this.self.unbacked_symbols,
  19426. ];
  19427. this.self.graph = new torch.fx.graph.Graph();
  19428. this.self.module = new torch.nn.modules.module.Module();
  19429. this.self.serialized_name_to_node = new builtins.dict();
  19430. this.self.serialized_name_to_meta = new builtins.dict(); // torch._export.serde.serialize.LazyMap
  19431. this.self.unbacked_symbols = new Set();
  19432. }
  19433. __exit__(/* exc_type, exc_value, traceback */) {
  19434. const self = this.self;
  19435. [self.graph, self.module, self.serialized_name_to_node, self.serialized_name_to_meta, self.unbacked_symbols] = this.saved;
  19436. }
  19437. };
  19438. return new Context(this);
  19439. }
  19440. deserialize_graph_output(output) {
  19441. if (output.type === 'as_tensor') {
  19442. return this.serialized_name_to_node.get(output.as_tensor.name);
  19443. } else if (output.type === 'as_sym_int') {
  19444. return this.serialized_name_to_node.get(output.as_sym_int.as_name);
  19445. } else if (output.type === 'as_sym_bool') {
  19446. return this.serialized_name_to_node.get(output.as_sym_bool.as_name);
  19447. } else if (output.type === 'as_int') {
  19448. return this.serialized_name_to_node.get(output.as_int.as_name);
  19449. } else if (output.type === 'as_none') {
  19450. return this.serialized_name_to_node.get(output.as_sym_bool.as_name);
  19451. }
  19452. throw new python.Error(`Unsupported graph node ${output.type}.`);
  19453. }
  19454. deserialize_graph(serialized_graph) {
  19455. for (const [name, tensor_value] of serialized_graph.tensor_values) {
  19456. const meta_val = this.deserialize_tensor_meta(tensor_value.meta || tensor_value, this.fake_tensor_mode);
  19457. this.serialized_name_to_meta.set(name, meta_val);
  19458. }
  19459. for (const [name, sym_int_value] of serialized_graph.sym_int_values) {
  19460. this.serialized_name_to_meta.set(name, this.deserialize_sym_int(sym_int_value));
  19461. }
  19462. for (const [name, sym_bool_value] of serialized_graph.sym_bool_values) {
  19463. this.serialized_name_to_meta.set(name, this.deserialize_sym_bool(sym_bool_value));
  19464. }
  19465. for (const [name, script_obj_meta] of serialized_graph.custom_obj_values) {
  19466. this.serialized_name_to_meta.set(name, this.deserialize_script_obj_meta(script_obj_meta));
  19467. }
  19468. for (let i = 0; i < serialized_graph.inputs.length; i++) {
  19469. const input = serialized_graph.inputs[i];
  19470. if (input.type === 'as_tensor' || input.type === 'as_sym_int' || input.type === 'as_custom_obj') {
  19471. const node_name = input.value.name;
  19472. const placeholder_node = this.graph.placeholder(node_name);
  19473. placeholder_node.name = node_name;
  19474. this.sync_fx_node(node_name, placeholder_node);
  19475. } else if (input.type === 'as_int' || input.type === 'as_float' || input.type === 'as_bool' || input.type === 'as_none' || input.type === 'as_string') {
  19476. const node_name = this.signature.input_specs[i].arg.name;
  19477. const placeholder_node = this.graph.placeholder(node_name);
  19478. placeholder_node.meta.set('val', this.deserialize_input(input));
  19479. } else {
  19480. throw new python.Error(`Invalid input ${input.type}.`);
  19481. }
  19482. }
  19483. for (const serialized_node of serialized_graph.nodes) {
  19484. const target = this.deserialize_operator(serialized_node.target);
  19485. this.deserialize_node(serialized_node, target);
  19486. }
  19487. let outputs = [];
  19488. for (const output of serialized_graph.outputs) {
  19489. outputs.push(this.deserialize_graph_output(output));
  19490. }
  19491. if (serialized_graph.is_single_tensor_return) {
  19492. [outputs] = outputs;
  19493. } else {
  19494. outputs = new builtins.tuple(outputs);
  19495. }
  19496. const output_node = this.graph.output(outputs);
  19497. if (serialized_graph.is_single_tensor_return) {
  19498. output_node.meta.set('val', output_node.args[0].meta.get('val'));
  19499. } else {
  19500. /* output_node.meta['val'] = tuple(
  19501. arg.meta['val'] if isinstance(arg, torch.fx.Node) else arg
  19502. for arg in output_node.args[0]
  19503. ) */
  19504. }
  19505. return self.graph;
  19506. }
  19507. deserialize_operator(serialized_target) {
  19508. let module = null;
  19509. let serialized_target_names = null;
  19510. if (serialized_target.startsWith('_operator')) {
  19511. module = operator;
  19512. serialized_target_names = serialized_target.split('.').slice(1);
  19513. } else if (serialized_target.startsWith('torch')) {
  19514. module = torch;
  19515. serialized_target_names = serialized_target.split('.').slice(1);
  19516. } else if (serialized_target.startsWith('#')) {
  19517. return self.deserialize_extension_operator(serialized_target);
  19518. } else {
  19519. return serialized_target;
  19520. }
  19521. let target = module;
  19522. for (const name of serialized_target_names) {
  19523. target = builtins.getattr(target, name);
  19524. if (!target) {
  19525. return serialized_target;
  19526. }
  19527. }
  19528. return target;
  19529. }
  19530. deserialize_node(serialized_node, target) {
  19531. let fx_node = null;
  19532. if (torch._export.serde.serialize._SYM_OPS.has(target)) {
  19533. const name = serialized_node.outputs[0].value.as_name;
  19534. const args = this.deserialize_sym_op_inputs(serialized_node.inputs);
  19535. fx_node = this.graph.create_node('call_function', target, args, null, name);
  19536. this.deserialize_sym_op_outputs(serialized_node, fx_node);
  19537. } else if (builtins.isinstance(target, torch._ops.HigherOrderOperator)) {
  19538. const [args, kwargs] = this.deserialize_hoo_inputs(serialized_node.inputs);
  19539. const metadata = this.deserialize_metadata(serialized_node.metadata);
  19540. for (const x of [...args, ...kwargs.values()]) {
  19541. if (builtins.isinstance(x, torch.fx.Node) && x.op === 'get_attr') {
  19542. x.meta.update(metadata);
  19543. }
  19544. }
  19545. const name = serialized_node.outputs.length === 1 &&
  19546. builtins.hasattr(serialized_node.outputs[0], 'as_tensor') &&
  19547. builtins.getattr(serialized_node, 'is_hop_single_tensor_return', true) ?
  19548. serialized_node.outputs[0].as_tensor.name : null;
  19549. fx_node = this.graph.create_node('call_function', target, args, kwargs, name);
  19550. this.deserialize_outputs(serialized_node, fx_node);
  19551. fx_node.meta.update(metadata);
  19552. } else if (builtins.isinstance(target, torch._ops.OpOverload)) {
  19553. const name = this._is_single_tensor_return(target) ? serialized_node.outputs[0].as_tensor.name : null;
  19554. const [args, kwargs] = this.deserialize_inputs(target, serialized_node);
  19555. fx_node = this.graph.create_node('call_function', target, args, kwargs, name);
  19556. this.deserialize_outputs(serialized_node, fx_node);
  19557. } else if (typeof target === 'string') {
  19558. // Handle unresolved operators
  19559. execution.emit('resolve', target);
  19560. if (target.match(/^torch\.ops\.(aten|prim|quantized)\./)) {
  19561. throw new python.Error(`Unsupported node target type '${target}'.`);
  19562. }
  19563. const [args, kwargs] = this.deserialize_hoo_inputs(serialized_node.inputs);
  19564. const name = serialized_node.outputs.length === 1 && builtins.hasattr(serialized_node.outputs[0], 'as_tensor') ? serialized_node.outputs[0].as_tensor.name : null;
  19565. fx_node = this.graph.create_node('call_function', target, args, kwargs, name);
  19566. this.deserialize_outputs(serialized_node, fx_node);
  19567. } else {
  19568. throw new python.Error(`Unsupported node target type '${target}'.`);
  19569. }
  19570. fx_node.meta.update(this.deserialize_metadata(serialized_node.metadata));
  19571. if (fx_node.op !== 'placeholder' && fx_node.op !== 'output' && !fx_node.meta.has('nn_module_stack')) {
  19572. fx_node.meta.set('nn_module_stack', new builtins.dict());
  19573. }
  19574. }
  19575. deserialize_input_spec(i) {
  19576. if (i.type === 'user_input') {
  19577. return new torch.export.graph_signature.InputSpec(
  19578. torch.export.graph_signature.InputKind.USER_INPUT,
  19579. this.deserialize_argument_spec(i.user_input.arg),
  19580. null);
  19581. } else if (i.type === 'parameter') {
  19582. return new torch.export.graph_signature.InputSpec(
  19583. torch.export.graph_signature.InputKind.PARAMETER,
  19584. new torch.export.graph_signature.TensorArgument(i.parameter.arg.name),
  19585. i.parameter.parameter_name,
  19586. );
  19587. } else if (i.type === 'buffer') {
  19588. return new torch.export.graph_signature.InputSpec(
  19589. torch.export.graph_signature.InputKind.BUFFER,
  19590. new torch.export.graph_signature.TensorArgument(i.buffer.arg.name),
  19591. i.buffer.buffer_name,
  19592. i.buffer.persistent,
  19593. );
  19594. } else if (i.type === 'tensor_constant') {
  19595. return new torch.export.graph_signature.InputSpec(
  19596. torch.export.graph_signature.InputKind.CONSTANT_TENSOR,
  19597. new torch.export.graph_signature.TensorArgument(i.tensor_constant.arg.name),
  19598. i.tensor_constant.tensor_constant_name);
  19599. } else if (i.type === 'custom_obj') {
  19600. return new torch.export.graph_signature.InputSpec(
  19601. torch.export.graph_signature.InputKind.CUSTOM_OBJ,
  19602. new torch.export.graph_signature.CustomObjArgument(i.custom_obj.arg.name, i.custom_obj.arg.class_fqn),
  19603. i.custom_obj.custom_obj_name);
  19604. } else if (i.type === 'token') {
  19605. return new torch.export.graph_signature.InputSpec(
  19606. torch.export.graph_signature.InputKind.TOKEN,
  19607. new torch.export.graph_signature.TokenArgument(i.token.arg.name),
  19608. null);
  19609. } else if (i.type === 'constant_input') {
  19610. return new torch.export.graph_signature.InputSpec(
  19611. torch.export.graph_signature.InputKind.USER_INPUT,
  19612. new torch.export.graph_signature.ConstantArgument(i.constant_input.name, this.deserialize_constant_input(i.constant_input.value)),
  19613. null);
  19614. }
  19615. throw new python.Error(`Unknown input spec ${i}`);
  19616. }
  19617. deserialize_constant_input(inp) {
  19618. if (inp.type === 'as_int') {
  19619. return inp.as_int;
  19620. } else if (inp.type === 'as_float') {
  19621. return inp.as_float;
  19622. } else if (inp.type === 'as_string') {
  19623. return inp.as_string;
  19624. } else if (inp.type === 'as_bool') {
  19625. return inp.as_bool;
  19626. } else if (inp.type === 'as_none') {
  19627. return null;
  19628. }
  19629. throw new python.Error(`Unhandled constant argument ${inp} to deserialize.`);
  19630. }
  19631. deserialize_output_spec(o) {
  19632. if (o.type === 'user_output') {
  19633. return new torch.export.graph_signature.OutputSpec(
  19634. torch.export.graph_signature.OutputKind.USER_OUTPUT,
  19635. this.deserialize_argument_spec(o.user_output.arg),
  19636. null);
  19637. } else if (o.type === 'loss_output') {
  19638. return new torch.export.graph_signature.OutputSpec(
  19639. torch.export.graph_signature.OutputKind.LOSS_OUTPUT,
  19640. new torch.export.graph_signature.TensorArgument(o.loss_output.arg.name),
  19641. null);
  19642. } else if (o.type === 'buffer_mutation') {
  19643. return new torch.export.graph_signature.OutputSpec(
  19644. torch.export.graph_signature.OutputKind.BUFFER_MUTATION,
  19645. new torch.export.graph_signature.TensorArgument(o.buffer_mutation.arg.name),
  19646. o.buffer_mutation.buffer_name);
  19647. } else if (o.type === 'gradient_to_parameter') {
  19648. return new torch.export.graph_signature.OutputSpec(
  19649. torch.export.graph_signature.OutputKind.GRADIENT_TO_PARAMETER,
  19650. new torch.export.graph_signature.TensorArgument(o.gradient_to_parameter.arg.name),
  19651. o.gradient_to_parameter.parameter_name);
  19652. } else if (o.type === 'gradient_to_user_input') {
  19653. return new torch.export.graph_signature.OutputSpec(
  19654. torch.export.graph_signature.OutputKind.GRADIENT_TO_USER_INPUT,
  19655. new torch.export.graph_signature.TensorArgument(o.gradient_to_user_input.arg.name),
  19656. o.gradient_to_user_input.user_input_name);
  19657. } else if (o.type === 'user_input_mutation') {
  19658. return new torch.export.graph_signature.OutputSpec(
  19659. torch.export.graph_signature.OutputKind.USER_INPUT_MUTATION,
  19660. new torch.export.graph_signature.TensorArgument(o.user_input_mutation.arg.name),
  19661. o.user_input_mutation.user_input_name);
  19662. } else if (o.type === 'token') {
  19663. return new torch.export.graph_signature.OutputSpec(
  19664. torch.export.graph_signature.OutputKind.TOKEN,
  19665. new torch.export.graph_signature.TokenArgument(o.token.arg.name),
  19666. null);
  19667. }
  19668. throw new python.Error(`Unknown output spec ${o}.`);
  19669. }
  19670. deserialize_signature(sig) {
  19671. return new torch.export.graph_signature.ExportGraphSignature(
  19672. sig.input_specs.map((i) => this.deserialize_input_spec(i)),
  19673. sig.output_specs.map((o) => this.deserialize_output_spec(o)));
  19674. }
  19675. deserialize(serialized_graph_module, serialized_state_dict, constants, example_inputs, symbol_name_to_range) {
  19676. this.shape_env = new torch.fx.experimental.symbolic_shapes.ShapeEnv(/* assume_static_by_default = True */);
  19677. this.fake_tensor_mode = new torch._subclasses.fake_tensor.FakeTensorMode(false, true, this.shape_env);
  19678. this.sympy_functions = new Map([
  19679. ['FloorDiv', torch.utils._sympy.functions.FloorDiv],
  19680. ['ModularIndexing', torch.utils._sympy.functions.ModularIndexing],
  19681. ['Where', torch.utils._sympy.functions.Where],
  19682. ['PythonMod', torch.utils._sympy.functions.PythonMod],
  19683. ['Mod', torch.utils._sympy.functions.Mod],
  19684. ['CleanDiv', torch.utils._sympy.functions.CleanDiv],
  19685. ['CeilToInt', torch.utils._sympy.functions.CeilToInt],
  19686. ['FloorToInt', torch.utils._sympy.functions.FloorToInt],
  19687. ['CeilDiv', torch.utils._sympy.functions.CeilDiv],
  19688. ['LShift', torch.utils._sympy.functions.LShift],
  19689. ['RShift', torch.utils._sympy.functions.RShift],
  19690. ['PowByNatural', torch.utils._sympy.functions.PowByNatural],
  19691. ['FloatPow', torch.utils._sympy.functions.FloatPow],
  19692. ['FloatTrueDiv', torch.utils._sympy.functions.FloatTrueDiv],
  19693. ['IntTrueDiv', torch.utils._sympy.functions.IntTrueDiv],
  19694. ['IsNonOverlappingAndDenseIndicator', torch.utils._sympy.functions.IsNonOverlappingAndDenseIndicator],
  19695. ['TruncToFloat', torch.utils._sympy.functions.TruncToFloat],
  19696. ['TruncToInt', torch.utils._sympy.functions.TruncToInt],
  19697. ['RoundToInt', torch.utils._sympy.functions.RoundToInt],
  19698. ['RoundDecimal', torch.utils._sympy.functions.RoundDecimal],
  19699. ['ToFloat', torch.utils._sympy.functions.ToFloat],
  19700. ['Identity', torch.utils._sympy.functions.Identity],
  19701. ]);
  19702. this.symbol_name_to_symbol = new Map();
  19703. this.constants = torch._export.serde.serialize.deserialize_torch_artifact(constants);
  19704. this.signature = this.deserialize_signature(serialized_graph_module.signature);
  19705. this.symbol_name_to_range = symbol_name_to_range || new Map();
  19706. /*
  19707. if symbol_name_to_range:
  19708. for k, vr in symbol_name_to_range.items():
  19709. lower = int(vr.lower)
  19710. if vr.upper >= 2: # max is >= 2, not sym bool range
  19711. lower = max(2, lower)
  19712. this.symbol_name_to_range[k] = symbolic_shapes.ValueRanges(_int_to_sympy_int(lower), vr.upper)
  19713. */
  19714. this.example_inputs = null;
  19715. if (example_inputs) {
  19716. this.example_inputs = torch._export.serde.serialize.deserialize_torch_artifact(example_inputs);
  19717. }
  19718. this.deserialize_graph(serialized_graph_module.graph);
  19719. const module_call_graph = null; // this.deserialize_module_call_graph(serialized_graph_module.module_call_graph)
  19720. return {
  19721. graph_module: torch._export.exported_program._create_graph_module_for_export(this.module, this.graph),
  19722. signature: this.signature,
  19723. module_call_graph,
  19724. names_to_symbols: this.symbol_name_to_symbol,
  19725. state_dict: torch._export.serde.serialize.deserialize_torch_artifact(serialized_state_dict),
  19726. constants: this.constants,
  19727. example_inputs: this.example_inputs,
  19728. };
  19729. }
  19730. sync_fx_node(name, fx_node) {
  19731. if (this.serialized_name_to_node.has(name)) {
  19732. throw new python.Error(`Node ${name} has already been deserialized before.`);
  19733. }
  19734. this.serialized_name_to_node.set(name, fx_node);
  19735. fx_node.meta.set('val', this.serialized_name_to_meta.get(name));
  19736. }
  19737. deserialize_sym_op_inputs(inputs) {
  19738. return inputs.map((input) => this.deserialize_input(input.arg));
  19739. }
  19740. deserialize_inputs(target, serialized_node) {
  19741. const schema_args = this._get_schema_from_target(target).arguments;
  19742. const actual_args = new Map(serialized_node.inputs.map((input) => [input.name, this.deserialize_input(input.arg)]));
  19743. const args = new builtins.list();
  19744. const kwargs = new builtins.dict();
  19745. for (const schema_arg of schema_args) {
  19746. const is_positional = !schema_arg.has_default_value() && !schema_arg.kwarg_only;
  19747. if (is_positional) {
  19748. args.push(actual_args.get(schema_arg.name));
  19749. } else if (actual_args.has(schema_arg.name)) {
  19750. kwargs.set(schema_arg.name, actual_args.get(schema_arg.name));
  19751. }
  19752. }
  19753. return [args, kwargs];
  19754. }
  19755. deserialize_hoo_inputs(inputs) {
  19756. const args = [];
  19757. const kwargs = new builtins.dict();
  19758. for (const input_ of inputs) {
  19759. if (input_.name === '') {
  19760. args.push(this.deserialize_input(input_.arg));
  19761. } else {
  19762. kwargs.set(input_.name, this.deserialize_input(input_.arg));
  19763. }
  19764. }
  19765. return [new builtins.tuple(args), kwargs];
  19766. }
  19767. deserialize_input(inp) {
  19768. const value = inp.value;
  19769. const typ_ = inp.type;
  19770. if (typ_ === 'as_none') {
  19771. return null;
  19772. } else if (typ_ === 'as_tensor') {
  19773. return this.serialized_name_to_node.get(inp.as_tensor.name);
  19774. } else if (typ_ === 'as_scalar_type') {
  19775. return torch._export.serde.serialize.deserialize_scalar_type(inp.as_scalar_type);
  19776. } else if (typ_ === 'as_memory_format') {
  19777. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_MEMORY_FORMAT[inp.as_memory_format];
  19778. } else if (typ_ === 'as_layout') {
  19779. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_LAYOUT[inp.as_layout];
  19780. } else if (typ_ === 'as_graph') {
  19781. const context = this.save_graph_module();
  19782. context.__enter__();
  19783. this.deserialize_graph(value.graph);
  19784. const submodule = torch.export.exported_program._create_graph_module_for_export(this.module, this.graph);
  19785. context.__exit__(null, null, null);
  19786. this.module.register_module(value.name, submodule);
  19787. return this.graph.create_node('get_attr', value.name, null, null, value.name);
  19788. } else if (typ_ === 'as_device') {
  19789. return this.deserialize_device(inp.as_device);
  19790. } else if (typ_ === 'as_int') {
  19791. return inp.as_int;
  19792. } else if (typ_ === 'as_float') {
  19793. return inp.as_float;
  19794. } else if (typ_ === 'as_bool') {
  19795. return inp.as_bool;
  19796. } else if (typ_ === 'as_string') {
  19797. return inp.as_string;
  19798. } else if (typ_ === 'as_sym_int') {
  19799. return this.deserialize_sym_argument(inp.as_sym_int);
  19800. } else if (typ_ === 'as_sym_float') {
  19801. return this.deserialize_sym_argument(inp.as_sym_float);
  19802. } else if (typ_ === 'as_sym_bool') {
  19803. return this.deserialize_sym_argument(inp.as_sym_bool);
  19804. } else if (Array.isArray(value)) {
  19805. if (value.length === 0) {
  19806. return [];
  19807. } else if (typ_ === 'as_tensors') {
  19808. const result = [];
  19809. for (const arg of value) {
  19810. result.push(this.serialized_name_to_node.get(arg.name));
  19811. }
  19812. return result;
  19813. } else if (typ_ === 'as_ints' || typ_ === 'as_floats' || typ_ === 'as_bools' || typ_ === 'as_strings') {
  19814. return Array.from(value);
  19815. } else if (typ_ === 'as_sym_ints' || typ_ === 'as_sym_bools') {
  19816. return value.map((arg) => this.deserialize_sym_argument(arg));
  19817. } else if (typ_ === 'as_optional_tensors') {
  19818. const deserialize_optional_tensor_args = (a) => {
  19819. if (a.type === 'as_none') {
  19820. return null;
  19821. } else if (a.type === 'as_tensor') {
  19822. return this.serialized_name_to_node.get(a.value.name);
  19823. }
  19824. throw new python.Error(`Unsupported argument '${typ_}'.`);
  19825. };
  19826. return value.map((item) => deserialize_optional_tensor_args(item));
  19827. }
  19828. throw new python.Error(`Unsupported argument '${typ_}'.`);
  19829. } else if (typ_ === 'as_custom_obj') {
  19830. if (this.serialized_name_to_node.has(inp.as_custom_obj.name)) {
  19831. return this.serialized_name_to_node.get(inp.as_custom_obj.name);
  19832. }
  19833. return this.constants[inp.as_custom_obj.name];
  19834. } else if (typ_ === 'as_operator') {
  19835. return this.deserialize_operator(inp.as_operator);
  19836. }
  19837. throw new python.Error(`Unsupported argument '${typ_}'.`);
  19838. }
  19839. deserialize_sym_argument(sym_arg) {
  19840. if (sym_arg instanceof torch._export.serde.schema.SymIntArgument) {
  19841. if (sym_arg.type === 'as_int') {
  19842. return sym_arg.as_int;
  19843. } else if (sym_arg.type === 'as_name') {
  19844. return this.serialized_name_to_node.get(sym_arg.as_name);
  19845. }
  19846. } else if (sym_arg instanceof torch._export.serde.schema.SymFloatArgument) {
  19847. if (sym_arg.type === 'as_float') {
  19848. return sym_arg.as_float;
  19849. } else if (sym_arg.type === 'as_name') {
  19850. return this.serialized_name_to_node.get(sym_arg.as_name);
  19851. }
  19852. } else if (sym_arg instanceof torch._export.serde.schema.SymBoolArgument) {
  19853. if (sym_arg.type === 'as_bool') {
  19854. return sym_arg.as_bool;
  19855. } else if (sym_arg.type === 'as_name') {
  19856. return this.serialized_name_to_node.get(sym_arg.as_name);
  19857. }
  19858. }
  19859. throw new python.Error(`Unsupported symbolic argument type '${sym_arg.type}`);
  19860. }
  19861. deserialize_sym_op_outputs(serialized_node, fx_node) {
  19862. this.sync_fx_node(serialized_node.outputs[0].value.as_name, fx_node);
  19863. }
  19864. deserialize_outputs(serialized_node, fx_node) {
  19865. if (serialized_node.outputs.length === 0) {
  19866. return;
  19867. }
  19868. if (serialized_node.outputs.length === 1 &&
  19869. serialized_node.outputs[0].type === 'as_tensor') {
  19870. this.sync_fx_node(serialized_node.outputs[0].as_tensor.name, fx_node);
  19871. return;
  19872. } else if (serialized_node.outputs.length === 1 &&
  19873. (serialized_node.outputs[0].value instanceof torch._export.serde.schema.SymIntArgument ||
  19874. serialized_node.outputs[0].value instanceof torch._export.serde.schema.SymBoolArgument)) {
  19875. this.sync_fx_node(serialized_node.outputs[0].value.as_name, fx_node);
  19876. return;
  19877. }
  19878. this.deserialize_multiple_outputs(serialized_node, fx_node);
  19879. }
  19880. deserialize_multiple_outputs(serialized_node, fx_node) {
  19881. const deserialized_metadata = this.deserialize_metadata(serialized_node.metadata);
  19882. const generate_getitem = (meta_val, fx_node, arg, idx) => {
  19883. let name = '';
  19884. if (arg instanceof torch._export.serde.schema.TensorArgument) {
  19885. name = arg.name;
  19886. } else if (arg instanceof torch._export.serde.schema.SymIntArgument) {
  19887. name = arg.as_name;
  19888. } else {
  19889. throw new python.Error(`Unsupported argument type '${arg}'.`);
  19890. }
  19891. const individual_output = this.graph.create_node(
  19892. 'call_function',
  19893. operator.getitem,
  19894. new builtins.tuple([fx_node, idx]),
  19895. null,
  19896. name,
  19897. );
  19898. this.sync_fx_node(name, individual_output);
  19899. meta_val.push(this.serialized_name_to_meta.get(name));
  19900. individual_output.meta.update(deserialized_metadata);
  19901. };
  19902. const generate_getitems = (meta_val, fx_node, args) => {
  19903. for (let idx = 0; idx < args.length; idx++) {
  19904. let arg = args[idx];
  19905. if (arg instanceof torch._export.serde.schema.Argument) {
  19906. arg = arg.value;
  19907. }
  19908. if (arg instanceof torch._export.serde.schema.TensorArgument || arg instanceof torch._export.serde.schema.SymIntArgument) {
  19909. generate_getitem(meta_val, fx_node, arg, idx);
  19910. } else if (Array.isArray(arg)) { // arg instanceof (list, tuple))
  19911. const list_output = this.graph.create_node(
  19912. 'call_function',
  19913. operator.getitem,
  19914. (fx_node, idx),
  19915. );
  19916. meta_val.push([]);
  19917. generate_getitems(meta_val[meta_val.length - 1], list_output, arg);
  19918. list_output.meta.update(deserialized_metadata);
  19919. list_output.meta.set('val', meta_val[meta_val.length - 1]);
  19920. } else {
  19921. throw new python.Error(`Unsupported node output type: '${arg}'.`);
  19922. }
  19923. }
  19924. };
  19925. const meta_val = [];
  19926. if (serialized_node.outputs.length === 1) {
  19927. // assert isinstance(serialized_node.outputs[0].value, list)
  19928. // assert isinstance(serialized_node.outputs[0].value[0], TensorArgument)
  19929. generate_getitems(meta_val, fx_node, serialized_node.outputs[0].as_tensors);
  19930. } else {
  19931. generate_getitems(meta_val, fx_node, serialized_node.outputs);
  19932. }
  19933. fx_node.meta.set('val', new builtins.tuple(meta_val));
  19934. this.serialized_name_to_node.set(fx_node.name, fx_node);
  19935. }
  19936. deserialize_metadata(metadata) {
  19937. const ret = new builtins.dict();
  19938. const stack_trace = metadata.get('stack_trace');
  19939. if (stack_trace) {
  19940. ret.set('stack_trace', stack_trace);
  19941. }
  19942. const deserialize_meta_func = (serialized_target) => {
  19943. let module = null;
  19944. let serialized_target_names = [];
  19945. if (serialized_target.startsWith('torch.nn')) {
  19946. module = torch.nn;
  19947. serialized_target_names = serialized_target.split('.').slice(1);
  19948. } else if (serialized_target.startsWith('torch')) {
  19949. module = torch;
  19950. serialized_target_names = serialized_target.split('.').slice(1);
  19951. } else {
  19952. return this.deserialize_operator(serialized_target);
  19953. }
  19954. let target = module;
  19955. for (const name of serialized_target_names) {
  19956. if (!builtins.hasattr(target, name)) {
  19957. return serialized_target;
  19958. }
  19959. target = builtins.getattr(target, name);
  19960. }
  19961. return target;
  19962. };
  19963. const nn_module_stack_str = metadata.get('nn_module_stack');
  19964. if (nn_module_stack_str) {
  19965. const import_nn_module_stack = (key, path, ty) => {
  19966. return [key, [path, ty]];
  19967. };
  19968. const nn_module_stack = new Map(nn_module_stack_str.split(';').map((item) => import_nn_module_stack(...item.split(','))));
  19969. ret.set('nn_module_stack', nn_module_stack);
  19970. }
  19971. const source_fn_st_str = metadata.get('source_fn_stack');
  19972. if (source_fn_st_str) {
  19973. const source_fn_st = [];
  19974. for (const source_fn_str of source_fn_st_str.split(';')) {
  19975. const [name, target_str] = source_fn_str.split(',');
  19976. source_fn_st.push([name, deserialize_meta_func(target_str)]);
  19977. }
  19978. ret.set('source_fn_stack', source_fn_st);
  19979. }
  19980. const torch_fn = metadata.get('torch_fn');
  19981. if (torch_fn) {
  19982. ret.set('torch_fn', new builtins.tuple(torch_fn.split(';')));
  19983. }
  19984. const custom_str = metadata.get('custom');
  19985. if (custom_str) {
  19986. ret.set('custom', JSON.parse(custom_str));
  19987. }
  19988. return ret;
  19989. }
  19990. deserialize_argument_spec(x) {
  19991. if (x.type === 'as_tensor') {
  19992. return new torch.export.graph_signature.TensorArgument(x.as_tensor.name);
  19993. } else if (x.type === 'as_sym_int') {
  19994. return new torch.export.graph_signature.SymIntArgument(x.as_sym_int.as_name);
  19995. } else if (x.type === 'as_custom_obj') {
  19996. return new torch.export.graph_signature.ConstantArgument(x.as_custom_obj.name, this.deserialize_input(x));
  19997. }
  19998. return new torch.export.graph_signature.ConstantArgument('', this.deserialize_input(x));
  19999. }
  20000. deserialize_tensor_meta(tensor_meta) {
  20001. try {
  20002. this.fake_tensor_mode.__enter__();
  20003. const sizes = tensor_meta.sizes.map((val) => this.deserialize_sym_int(val));
  20004. const strides = tensor_meta.strides.map((val) => this.deserialize_sym_int(val));
  20005. const device = this.deserialize_device(tensor_meta.device);
  20006. const dtype = torch._export.serde.serialize.deserialize_scalar_type(tensor_meta.dtype);
  20007. return torch.empty_strided(sizes, strides, dtype, null, device);
  20008. } finally {
  20009. this.fake_tensor_mode.__exit__(null, null, null);
  20010. }
  20011. }
  20012. deserialize_script_obj_meta(script_obj_meta) {
  20013. return new torch.export.graph_signature.CustomObjArgument(script_obj_meta.name, script_obj_meta.class_fqn);
  20014. }
  20015. _parse_sym_expr(expr_str, hint) {
  20016. const _process_sym_expr = (sym, hint) => {
  20017. if (sym.is_Integer || sym.is_Float || sym.is_Boolean) {
  20018. return sym;
  20019. }
  20020. expr_str = sym.__str__();
  20021. for (const arg of sym.args) {
  20022. this._parse_sym_expr(arg);
  20023. }
  20024. if (this.symbol_name_to_symbol.has(expr_str)) {
  20025. sym = this.symbol_name_to_symbol.get(expr_str);
  20026. } else {
  20027. this.symbol_name_to_symbol.set(expr_str, sym);
  20028. 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])) {
  20029. this.unbacked_symbols.add(sym);
  20030. }
  20031. }
  20032. if (hint !== null && !this.shape_env.var_to_val.has(sym)) {
  20033. this.shape_env.add_var_to_val(sym, hint);
  20034. }
  20035. const vr = this.symbol_name_to_range.get(expr_str);
  20036. if (vr) {
  20037. this.shape_env.constrain_symbol_range(sym, vr.lower, vr.upper);
  20038. }
  20039. if (builtins.isinstance(sym, sympy.core.symbol.Symbol)) {
  20040. this.shape_env.var_to_stack.set(sym, torch.utils._traceback.CapturedTraceback.extract(false, false, 1));
  20041. }
  20042. return sym;
  20043. };
  20044. const locals = new Map([...this.sympy_functions, ...this.symbol_name_to_symbol]);
  20045. const expr = sympy.core.sympify.sympify(expr_str, locals);
  20046. return _process_sym_expr(expr, hint);
  20047. }
  20048. deserialize_sym_int(s) {
  20049. const val = s.value;
  20050. let hint = null;
  20051. if (s.type === 'as_expr') {
  20052. if (val.hint === null) {
  20053. hint = null;
  20054. } else {
  20055. // assert val.hint.type == "as_int"
  20056. hint = val.hint.value;
  20057. }
  20058. const sym = this._parse_sym_expr(val.expr_str, hint);
  20059. return this.shape_env.create_symintnode(sym, hint);
  20060. } else if (s.type === 'as_int') {
  20061. // assert type(val) is int
  20062. return val;
  20063. }
  20064. throw new python.Error(`SymInt has invalid field type ${s.type} with value ${s.value}.`);
  20065. }
  20066. deserialize_sym_bool(s) {
  20067. const val = s.value;
  20068. let hint = null;
  20069. if (s.type === 'as_expr') {
  20070. if (val.hint === null) {
  20071. hint = null;
  20072. } else {
  20073. // assert val.hint.type == "as_bool"
  20074. hint = val.hint.value;
  20075. }
  20076. const sym = this._parse_sym_expr(val.expr_str, hint);
  20077. return this.shape_env.create_symboolnode(sym, hint);
  20078. } else if (s.type === 'as_bool') {
  20079. // assert type(val) is bool
  20080. return val;
  20081. }
  20082. throw new python.Error(`SymBool has invalid field type ${s.type} with value ${s.value}.`);
  20083. }
  20084. deserialize_device(d) {
  20085. if (d.index === null) {
  20086. return new torch.device(d.type);
  20087. }
  20088. return new torch.device(d.type, d.index);
  20089. }
  20090. _get_schema_from_target(target) {
  20091. if (target instanceof torch._ops.OpOverload) {
  20092. return target._schema;
  20093. }
  20094. throw new python.Error(`Unsupported schema '${target.name}'.`);
  20095. }
  20096. _is_single_tensor_return(target) {
  20097. const schema = this._get_schema_from_target(target);
  20098. const returns = schema.returns;
  20099. return returns.length === 1 && returns[0].real_type instanceof torch.TensorType;
  20100. }
  20101. });
  20102. this.registerType('torch._export.verifier.Verifier', class {});
  20103. this.registerType('torch._dynamo.convert_frame.CatchErrorsWrapper', class {});
  20104. this.registerType('torch._dynamo.convert_frame.ConvertFrameAssert', class {});
  20105. this.registerType('torch._dynamo.convert_frame.ConvertFrame', class {});
  20106. this.registerType('torch._dynamo.convert_frame.ConvertFrameBox', class {});
  20107. this.registerType('torch._dynamo.eval_frame._TorchDynamoContext', class {});
  20108. this.registerType('torch._dynamo.eval_frame.OptimizedModule', class extends torch.nn.modules.module.Module {
  20109. constructor(mod, dynamo_ctx) {
  20110. builtins.object.__setattr__(self, '_orig_mod', mod);
  20111. // this._super_module_initialized = false;
  20112. super();
  20113. // this._super_module_initialized = true;
  20114. this._orig_mod = mod;
  20115. this.dynamo_ctx = dynamo_ctx;
  20116. // this._initialize();
  20117. this.training = this._orig_mod.training;
  20118. }
  20119. });
  20120. this.registerType('torch._dynamo.eval_frame.OptimizeContext', class extends torch._dynamo.eval_frame._TorchDynamoContext {});
  20121. this.registerType('torch._dynamo.hooks.Hooks', class {});
  20122. this.registerType('torch._dynamo.output_graph.GraphCompileReason', class {});
  20123. this.registerType('torch._dynamo.repro.after_dynamo.WrapBackendDebug', class {});
  20124. this.registerType('torch._TorchCompileInductorWrapper', class {});
  20125. this.registerFunction('torch._inductor.compile_fx.compile_fx');
  20126. this.registerFunction('torch_utils.persistence._reconstruct_persistent_obj', (meta) => {
  20127. const name = `_imported_module_${Math.floor(Math.random() * 10000)}`;
  20128. const module = new types.ModuleType(name);
  20129. execution.register('sys').modules.set(name, module);
  20130. const context = new python.Execution.Context(module, null);
  20131. execution.exec(meta.get('module_src'), context);
  20132. const obj = execution.invoke(`${name}.${meta.get('class_name')}`, []);
  20133. const state = meta.get('state');
  20134. if (state) {
  20135. if (obj.__setstate__) {
  20136. obj.__setstate__(state);
  20137. } else {
  20138. for (const [key, value] of state) {
  20139. obj[key] = value;
  20140. }
  20141. }
  20142. }
  20143. return obj;
  20144. });
  20145. this.registerFunction('torch_utils.misc.assert_shape', (/* tensor, ref_shape */) => {});
  20146. this.registerFunction('torch_utils.ops.conv2d_resample.conv2d_resample', (/* x, w, f, up, down, padding, groups, flip_weight, flip_filter */) => {});
  20147. this.registerFunction('torch_utils.ops.upfirdn2d.setup_filter', (/* x, f, up, down, padding, flip_filter, gain, impl */) => {});
  20148. this.registerFunction('torch_utils.ops.bias_act', (/* x, b, dim, act, alpha, gain, clamp, impl */) => {});
  20149. this.registerFunction('torch_utils.ops.fma.fma', (/* a, b, c */) => {});
  20150. this.registerType('torch.device', class {
  20151. constructor(type, index) {
  20152. this.type = type;
  20153. this.index = index ? index : null;
  20154. }
  20155. __str__() {
  20156. return this.index === null ? this.type : `${this.type}:${this.index}`;
  20157. }
  20158. toString() {
  20159. const index = this.index === null ? '' : `, index=${this.index}`;
  20160. return `device(type='${this.type}'${index})`;
  20161. }
  20162. });
  20163. this.registerType('torch.memory_format', class {
  20164. constructor(name) {
  20165. this.name = name;
  20166. }
  20167. __str__() {
  20168. return `torch.${this.name}`;
  20169. }
  20170. toString() {
  20171. return this.__str__();
  20172. }
  20173. });
  20174. this.registerType('torch.dtype', class {
  20175. constructor(scalar_type, name, itemsize) {
  20176. this._scalar_type = scalar_type;
  20177. this._name = name;
  20178. this._itemsize = itemsize;
  20179. }
  20180. scalar_type() {
  20181. return this._scalar_type;
  20182. }
  20183. itemsize() {
  20184. return this._itemsize;
  20185. }
  20186. __reduce__() {
  20187. return this._name;
  20188. }
  20189. __str__() {
  20190. return `torch.${this._name}`;
  20191. }
  20192. toString() {
  20193. return this.__str__();
  20194. }
  20195. });
  20196. this.registerType('torch.layout', class {
  20197. constructor(name) {
  20198. this._name = name;
  20199. }
  20200. __str__() {
  20201. return `torch.${this._name}`;
  20202. }
  20203. toString() {
  20204. return this.__str__();
  20205. }
  20206. });
  20207. this.registerType('torch.qscheme', class {
  20208. constructor(name) {
  20209. this._name = name;
  20210. }
  20211. __str__() {
  20212. return this._name;
  20213. }
  20214. toString() {
  20215. return this.__str__();
  20216. }
  20217. });
  20218. this.registerType('torch.utils.hooks.RemovableHandle', class {
  20219. __setstate__(state) {
  20220. [this.hooks_dict_ref, this.id] = state;
  20221. this.hooks_dict_ref = this.hooks_dict_ref || new Map();
  20222. }
  20223. });
  20224. this.registerType('torch.storage._StorageBase', class {
  20225. constructor(size, dtype) {
  20226. this._size = size;
  20227. this._dtype = dtype;
  20228. this._device = null;
  20229. }
  20230. get device() {
  20231. return this._device;
  20232. }
  20233. get dtype() {
  20234. return this._dtype;
  20235. }
  20236. element_size() {
  20237. return this._dtype.element_size;
  20238. }
  20239. size() {
  20240. return this._size;
  20241. }
  20242. get data() {
  20243. return this._cdata;
  20244. }
  20245. _set_cdata(data) {
  20246. const length = this.size() * this.dtype.itemsize();
  20247. if (length !== data.length) {
  20248. throw new python.Error('Typed storage data size mismatch.');
  20249. }
  20250. this._cdata = data;
  20251. }
  20252. _set_from_file(unpickler) {
  20253. const buffer = unpickler.read(8);
  20254. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20255. if (size !== this.size()) {
  20256. throw new python.Error('Typed storage size mismatch.');
  20257. }
  20258. const itemsize = this.dtype.itemsize();
  20259. const data = unpickler.stream(itemsize * size);
  20260. this._set_cdata(data);
  20261. }
  20262. static _new_with_file(unpickler) {
  20263. const buffer = unpickler.read(8);
  20264. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20265. const storage = new this(size);
  20266. const itemsize = storage.dtype.itemsize();
  20267. const data = unpickler.stream(itemsize * size);
  20268. storage._set_cdata(data);
  20269. return storage;
  20270. }
  20271. });
  20272. this.registerType('torch.storage.UntypedStorage', class {
  20273. constructor(size) {
  20274. this._size = size;
  20275. }
  20276. _set_cdata(data) {
  20277. if (this._size !== data.length) {
  20278. throw new python.Error('Untyped storage data size mismatch.');
  20279. }
  20280. this._cdata = data;
  20281. }
  20282. });
  20283. this.registerType('torch.storage.TypedStorage', class {
  20284. constructor(...args) {
  20285. if (args.length === 0) {
  20286. this._size = 0;
  20287. } else if (args.length === 1 && Number.isInteger(args[0])) {
  20288. [this._size] = args;
  20289. } else if (args.length >= 2 && Number.isInteger(args[0]) && args[1] instanceof torch.dtype) {
  20290. if (args[3] instanceof torch.device) {
  20291. [this._size, this.dtype, , this._device] = args;
  20292. } else {
  20293. [this._size, this.dtype] = args;
  20294. }
  20295. } else {
  20296. throw new python.Error(`Unsupported TypedStorage arguments '${JSON.stringify(args)}'.`);
  20297. }
  20298. }
  20299. get device() {
  20300. return this._device;
  20301. }
  20302. get dtype() {
  20303. return this._dtype;
  20304. }
  20305. set dtype(value) {
  20306. this._dtype = value;
  20307. }
  20308. element_size() {
  20309. return this._dtype.element_size;
  20310. }
  20311. size() {
  20312. return this._size;
  20313. }
  20314. get data() {
  20315. return this._cdata;
  20316. }
  20317. _set_cdata(data) {
  20318. const length = this.size() * this.dtype.itemsize();
  20319. if (length !== data.length) {
  20320. throw new python.Error('Storage data size mismatch.');
  20321. }
  20322. this._cdata = data;
  20323. }
  20324. _set_from_file(unpickler) {
  20325. const buffer = unpickler.read(8);
  20326. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20327. if (size !== this.size()) {
  20328. throw new python.Error('Storage size mismatch.');
  20329. }
  20330. const itemsize = this.dtype.itemsize();
  20331. const data = unpickler.stream(itemsize * size);
  20332. this._set_cdata(data);
  20333. }
  20334. static _new_with_file(unpickler) {
  20335. const buffer = unpickler.read(8);
  20336. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20337. const storage = new this(size);
  20338. const itemsize = storage.dtype.itemsize();
  20339. const data = unpickler.stream(itemsize * size);
  20340. storage._set_cdata(data);
  20341. return storage;
  20342. }
  20343. });
  20344. this.registerType('torch.storage._LegacyStorage', class extends torch.storage.TypedStorage {
  20345. });
  20346. this.registerType('torch.BoolStorage', class extends torch.storage._LegacyStorage {
  20347. constructor(...args) {
  20348. // eslint-disable-next-line no-constructor-return
  20349. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.BoolStorage.dtype);
  20350. }
  20351. });
  20352. this.registerType('torch.ByteStorage', class extends torch.storage._LegacyStorage {
  20353. constructor(...args) {
  20354. // eslint-disable-next-line no-constructor-return
  20355. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ByteStorage.dtype);
  20356. }
  20357. });
  20358. this.registerType('torch.CharStorage', class extends torch.storage._LegacyStorage {
  20359. constructor(...args) {
  20360. // eslint-disable-next-line no-constructor-return
  20361. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.CharStorage.dtype);
  20362. }
  20363. });
  20364. this.registerType('torch.ShortStorage', class extends torch.storage._LegacyStorage {
  20365. constructor(...args) {
  20366. // eslint-disable-next-line no-constructor-return
  20367. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ShortStorage.dtype);
  20368. }
  20369. });
  20370. this.registerType('torch.IntStorage', class extends torch.storage._LegacyStorage {
  20371. constructor(...args) {
  20372. // eslint-disable-next-line no-constructor-return
  20373. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.IntStorage.dtype);
  20374. }
  20375. });
  20376. this.registerType('torch.LongStorage', class extends torch.storage._LegacyStorage {
  20377. constructor(...args) {
  20378. // eslint-disable-next-line no-constructor-return
  20379. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.LongStorage.dtype);
  20380. }
  20381. });
  20382. this.registerType('torch.HalfStorage', class extends torch.storage._LegacyStorage {
  20383. constructor(...args) {
  20384. // eslint-disable-next-line no-constructor-return
  20385. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.HalfStorage.dtype);
  20386. }
  20387. });
  20388. this.registerType('torch.FloatStorage', class extends torch.storage._LegacyStorage {
  20389. constructor(...args) {
  20390. // eslint-disable-next-line no-constructor-return
  20391. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.FloatStorage.dtype);
  20392. }
  20393. });
  20394. this.registerType('torch.DoubleStorage', class extends torch.storage._LegacyStorage {
  20395. constructor(...args) {
  20396. // eslint-disable-next-line no-constructor-return
  20397. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.DoubleStorage.dtype);
  20398. }
  20399. });
  20400. this.registerType('torch.ComplexHalfStorage', class extends torch.storage._LegacyStorage {
  20401. constructor(...args) {
  20402. // eslint-disable-next-line no-constructor-return
  20403. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ComplexHalfStorage.dtype);
  20404. }
  20405. });
  20406. this.registerType('torch.ComplexFloatStorage', class extends torch.storage._LegacyStorage {
  20407. constructor(...args) {
  20408. // eslint-disable-next-line no-constructor-return
  20409. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ComplexFloatStorage.dtype);
  20410. }
  20411. });
  20412. this.registerType('torch.ComplexDoubleStorage', class extends torch.storage._LegacyStorage {
  20413. constructor(...args) {
  20414. // eslint-disable-next-line no-constructor-return
  20415. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ComplexDoubleStorage.dtype);
  20416. }
  20417. });
  20418. this.registerType('torch.QInt8Storage', class extends torch.storage._LegacyStorage {
  20419. constructor(...args) {
  20420. // eslint-disable-next-line no-constructor-return
  20421. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt8Storage.dtype);
  20422. }
  20423. });
  20424. this.registerType('torch.QUInt8Storage', class extends torch.storage._LegacyStorage {
  20425. constructor(...args) {
  20426. // eslint-disable-next-line no-constructor-return
  20427. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt8Storage.dtype);
  20428. }
  20429. });
  20430. this.registerType('torch.QInt32Storage', class extends torch.storage._LegacyStorage {
  20431. constructor(...args) {
  20432. // eslint-disable-next-line no-constructor-return
  20433. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QInt32Storage.dtype);
  20434. }
  20435. });
  20436. this.registerType('torch.BFloat16Storage', class extends torch.storage._LegacyStorage {
  20437. constructor(...args) {
  20438. // eslint-disable-next-line no-constructor-return
  20439. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.BFloat16Storage.dtype);
  20440. }
  20441. });
  20442. this.registerType('torch.QUInt4x2Storage', class extends torch.storage._LegacyStorage {
  20443. constructor(...args) {
  20444. // eslint-disable-next-line no-constructor-return
  20445. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt4x2Storage.dtype);
  20446. }
  20447. });
  20448. this.registerType('torch.QUInt2x4Storage', class extends torch.storage._LegacyStorage {
  20449. constructor(...args) {
  20450. // eslint-disable-next-line no-constructor-return
  20451. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt2x4Storage.dtype);
  20452. }
  20453. });
  20454. this.registerType('torch.UInt16Storage', class extends torch.storage._LegacyStorage {
  20455. constructor(...args) {
  20456. // eslint-disable-next-line
  20457. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.UInt16Storage.dtype);
  20458. }
  20459. });
  20460. this.registerType('torch.UInt32Storage', class extends torch.storage._LegacyStorage {
  20461. constructor(...args) {
  20462. // eslint-disable-next-line no-constructor-return
  20463. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.UInt32Storage.dtype);
  20464. }
  20465. });
  20466. this.registerType('torch.UInt64Storage', class extends torch.storage._LegacyStorage {
  20467. constructor(...args) {
  20468. // eslint-disable-next-line no-constructor-return
  20469. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.UInt64Storage.dtype);
  20470. }
  20471. });
  20472. this.registerType('torch.Size', class extends Array {
  20473. constructor(size) {
  20474. super(size.length);
  20475. for (let i = 0; i < size.length; i++) {
  20476. this[i] = size[i];
  20477. }
  20478. }
  20479. __len__() {
  20480. return this.length;
  20481. }
  20482. });
  20483. this.registerType('torch._C.TensorMeta', class {
  20484. });
  20485. this.registerType('torch._C.TensorBase', class extends torch._C.TensorMeta {
  20486. });
  20487. this.registerType('torch.Tensor', class extends torch._C.TensorBase {
  20488. constructor(storage, shape, dtype, layout, device, requires_grad) {
  20489. super();
  20490. if (storage) {
  20491. this._storage = storage;
  20492. }
  20493. if (shape !== null && shape !== undefined) {
  20494. this._shape = shape;
  20495. }
  20496. if (dtype) {
  20497. this._dtype = dtype;
  20498. }
  20499. this._layout = layout || torch.strided;
  20500. if (device) {
  20501. this._device = device;
  20502. }
  20503. if (requires_grad !== undefined) {
  20504. this.requires_grad = requires_grad;
  20505. }
  20506. }
  20507. clone() {
  20508. const tensor = new torch.Tensor(this._storage, this._shape, this._dtype, this._layout, this._device, this.requires_grad);
  20509. tensor._storage_offset = this._storage_offset;
  20510. tensor._stride = this._stride;
  20511. tensor._values = this._values;
  20512. tensor._indices = this._indices;
  20513. tensor.__quantized__ = this.__quantized__;
  20514. tensor.__nested__ = this.__nested__;
  20515. tensor.data = this.data;
  20516. tensor._backward_hooks = this._backward_hooks;
  20517. return tensor;
  20518. }
  20519. get device() {
  20520. if (this._device !== undefined) {
  20521. return this._device;
  20522. }
  20523. return this.storage().device;
  20524. }
  20525. get dtype() {
  20526. if (this._dtype !== undefined) {
  20527. return this._dtype;
  20528. }
  20529. if (this._layout === torch.sparse_coo) {
  20530. return this._values.dtype;
  20531. }
  20532. return this.storage().dtype;
  20533. }
  20534. get shape() {
  20535. return this._shape;
  20536. }
  20537. get layout() {
  20538. return this._layout;
  20539. }
  20540. get values() {
  20541. if (this._layout === torch.sparse_coo) {
  20542. return this._values;
  20543. }
  20544. throw new python.Error(`Unsupported values in layout'${this._layout.__str__()}'.`);
  20545. }
  20546. get indices() {
  20547. if (this._layout === torch.sparse_coo) {
  20548. return this._indices;
  20549. }
  20550. throw new python.Error(`Unsupported indices in layout'${this._indices.__str__()}'.`);
  20551. }
  20552. get is_quantized() {
  20553. return this.__quantized__ === true;
  20554. }
  20555. get is_nested() {
  20556. return this.__nested__ === true;
  20557. }
  20558. get is_sparse() {
  20559. return this.layout !== torch.strided;
  20560. }
  20561. size() {
  20562. return this._shape;
  20563. }
  20564. storage() {
  20565. return this._storage;
  20566. }
  20567. storage_offset() {
  20568. return this._storage_offset;
  20569. }
  20570. stride() {
  20571. return this._stride;
  20572. }
  20573. resize_(shape) {
  20574. this._shape = shape;
  20575. }
  20576. __len__() {
  20577. return this._shape[0];
  20578. }
  20579. __setstate__(state) {
  20580. switch (state.length) {
  20581. case 3:
  20582. break;
  20583. case 4:
  20584. [this._storage, this._storage_offset, this._shape, this._stride] = state;
  20585. break;
  20586. case 5:
  20587. [this.data, ,this._backward_hooks, this.requires_grad] = state;
  20588. break;
  20589. default:
  20590. throw new python.Error(`Unsupported tensor state length '${state.length}'.`);
  20591. }
  20592. }
  20593. set_(source, storage_offset, size, stride) {
  20594. this._storage = source;
  20595. this._storage_offset = storage_offset;
  20596. this._shape = size;
  20597. this._stride = stride;
  20598. }
  20599. __bool__() {
  20600. return true;
  20601. }
  20602. __int__() {
  20603. const storage = this.storage();
  20604. if (storage && storage.dtype.__reduce__() === 'int64' && storage.data.length === 8) {
  20605. const buffer = storage.data.peek ? storage.data.peek() : storage.data;
  20606. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  20607. return view.getBigInt64(0, true);
  20608. }
  20609. return NaN;
  20610. }
  20611. __float__() {
  20612. const storage = this.storage();
  20613. if (storage && storage.dtype.__reduce__() === 'float32') {
  20614. if (storage.size() !== undefined && storage.data.length === 4) {
  20615. const buffer = storage.data.peek ? storage.data.peek() : storage.data;
  20616. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  20617. return view.getFloat32(0, true);
  20618. }
  20619. }
  20620. return NaN;
  20621. }
  20622. __str__() {
  20623. return 'tensor(...)';
  20624. }
  20625. static _make_wrapper_subclass(cls, size, stride, dtype, storage_offset, layout, device, requires_grad) {
  20626. const t = new torch.Tensor(null, size, dtype, layout, device, requires_grad);
  20627. t.__setstate__([null, storage_offset, size, stride]);
  20628. return t;
  20629. }
  20630. });
  20631. this.registerType('torch.nn.parameter.Parameter', class extends torch.Tensor {
  20632. constructor(data, requires_grad) {
  20633. super();
  20634. this.data = data || new torch.Tensor([]);
  20635. this.requires_grad = requires_grad === undefined ? true : requires_grad;
  20636. }
  20637. });
  20638. this.registerType('torch._subclasses.fake_tensor.FakeTensor', class extends torch.Tensor {
  20639. });
  20640. this.registerType('torch._subclasses.fake_tensor.FakeTensorMode', class extends torch.utils._python_dispatch.TorchDispatchMode {
  20641. constructor(allow_fallback_kernels, allow_non_fake_inputs, shape_env) {
  20642. super();
  20643. this.allow_fallback_kernels = allow_fallback_kernels;
  20644. this.allow_non_fake_inputs = allow_non_fake_inputs;
  20645. this.shape_env = shape_env;
  20646. this.enter_stack = [];
  20647. this._mode_key = 0; // torch._C._TorchDispatchModeKey.FAKE
  20648. }
  20649. __enter__() {
  20650. const prev_only_lift_cpu_tensors = null;
  20651. const maybe_prev_fake_mode = torch._C._unset_dispatch_mode(this._mode_key);
  20652. if (this === maybe_prev_fake_mode) {
  20653. torch._C._set_dispatch_mode(this);
  20654. this.enter_stack.push([false, null, prev_only_lift_cpu_tensors]);
  20655. } else {
  20656. this.enter_stack.push([true, maybe_prev_fake_mode, prev_only_lift_cpu_tensors]);
  20657. return super.__enter__();
  20658. }
  20659. return this;
  20660. }
  20661. __exit__(exc_type, exc_value, traceback) {
  20662. const [live, maybe_prev_fake_mode, maybe_prev_only_lift_cpu_tensors] = this.enter_stack.pop();
  20663. if (live) {
  20664. super.__exit__(exc_type, exc_value, traceback);
  20665. if (maybe_prev_fake_mode !== null) {
  20666. torch._C._set_dispatch_mode(maybe_prev_fake_mode);
  20667. }
  20668. if (maybe_prev_only_lift_cpu_tensors !== null) {
  20669. torch._C._set_only_lift_cpu_tensors(maybe_prev_only_lift_cpu_tensors);
  20670. }
  20671. torch._C._set_dispatch_mode(maybe_prev_fake_mode);
  20672. }
  20673. }
  20674. });
  20675. this.registerType('torch.nn.parameter.UninitializedParameter', class extends torch.nn.parameter.Parameter {
  20676. constructor(requires_grad /*, device, dtype */) {
  20677. super(undefined, requires_grad);
  20678. }
  20679. });
  20680. this.registerType('torch.nn.parameter.UninitializedBuffer', class extends torch.Tensor {});
  20681. this.registerType('torch.BoolTensor', class extends torch.Tensor {
  20682. constructor(...args) {
  20683. // eslint-disable-next-line no-constructor-return
  20684. return new torch.Tensor(...args);
  20685. }
  20686. });
  20687. this.registerType('torch.ByteTensor', class extends torch.Tensor {
  20688. constructor(...args) {
  20689. // eslint-disable-next-line no-constructor-return
  20690. return new torch.Tensor(...args);
  20691. }
  20692. });
  20693. this.registerType('torch.CharTensor', class extends torch.Tensor {
  20694. constructor(...args) {
  20695. // eslint-disable-next-line no-constructor-return
  20696. return new torch.Tensor(...args);
  20697. }
  20698. });
  20699. this.registerType('torch.ShortTensor', class extends torch.Tensor {
  20700. constructor(...args) {
  20701. // eslint-disable-next-line no-constructor-return
  20702. return new torch.Tensor(...args);
  20703. }
  20704. });
  20705. this.registerType('torch.IntTensor', class extends torch.Tensor {
  20706. constructor(...args) {
  20707. // eslint-disable-next-line no-constructor-return
  20708. return new torch.Tensor(...args);
  20709. }
  20710. });
  20711. this.registerType('torch.LongTensor', class extends torch.Tensor {
  20712. constructor(...args) {
  20713. // eslint-disable-next-line no-constructor-return
  20714. return new torch.Tensor(...args);
  20715. }
  20716. });
  20717. this.registerType('torch.HalfTensor', class extends torch.Tensor {
  20718. constructor(...args) {
  20719. // eslint-disable-next-line no-constructor-return
  20720. return new torch.Tensor(...args);
  20721. }
  20722. });
  20723. this.registerType('torch.FloatTensor', class extends torch.Tensor {
  20724. constructor(...args) {
  20725. // eslint-disable-next-line no-constructor-return
  20726. return new torch.Tensor(...args);
  20727. }
  20728. });
  20729. this.registerType('torch.DoubleTensor', class extends torch.Tensor {
  20730. constructor(...args) {
  20731. // eslint-disable-next-line no-constructor-return
  20732. return new torch.Tensor(...args);
  20733. }
  20734. });
  20735. this.registerType('torch.ComplexFloatTensor', class extends torch.Tensor {
  20736. constructor(...args) {
  20737. // eslint-disable-next-line no-constructor-return
  20738. return new torch.Tensor(...args);
  20739. }
  20740. });
  20741. this.registerType('torch.ComplexDoubleTensor', class extends torch.Tensor {
  20742. constructor(...args) {
  20743. // eslint-disable-next-line no-constructor-return
  20744. return new torch.Tensor(...args);
  20745. }
  20746. });
  20747. this.registerType('torch.QInt8Tensor', class extends torch.Tensor {
  20748. constructor(...args) {
  20749. // eslint-disable-next-line no-constructor-return
  20750. return new torch.Tensor(...args);
  20751. }
  20752. });
  20753. this.registerType('torch.QUInt8Tensor', class extends torch.Tensor {
  20754. constructor(...args) {
  20755. // eslint-disable-next-line no-constructor-return
  20756. return new torch.Tensor(...args);
  20757. }
  20758. });
  20759. this.registerType('torch.QInt32Tensor', class extends torch.Tensor {
  20760. constructor(...args) {
  20761. // eslint-disable-next-line no-constructor-return
  20762. return new torch.Tensor(...args);
  20763. }
  20764. });
  20765. this.registerType('torch.BFloat16Tensor', class extends torch.Tensor {
  20766. constructor(...args) {
  20767. // eslint-disable-next-line no-constructor-return
  20768. return new torch.Tensor(...args);
  20769. }
  20770. });
  20771. this.registerType('torch.cuda._CudaLegacyStorage', class extends torch.storage._LegacyStorage {});
  20772. this.registerType('torch.cuda.FloatStorage', class extends torch.cuda._CudaLegacyStorage {});
  20773. this.registerType('torch.cuda.FloatTensor', class extends torch.Tensor {
  20774. constructor(...args) {
  20775. // eslint-disable-next-line no-constructor-return
  20776. return new torch.Tensor(...args);
  20777. }
  20778. });
  20779. this.registerType('torch.cuda.DoubleStorage', class extends torch.cuda._CudaLegacyStorage {});
  20780. this.registerType('torch.cuda.DoubleTensor', class extends torch.Tensor {
  20781. constructor(...args) {
  20782. // eslint-disable-next-line no-constructor-return
  20783. return new torch.Tensor(...args);
  20784. }
  20785. });
  20786. this.registerType('torch.cuda.amp.grad_scaler.GradScaler', class {});
  20787. this.registerType('torchao.utils.TorchAOBaseTensor', class extends torch.Tensor {
  20788. constructor(...args) {
  20789. // eslint-disable-next-line no-constructor-return
  20790. return new torch.Tensor(...args);
  20791. }
  20792. });
  20793. this.registerType('torchao.dtypes.affine_quantized_tensor.AffineQuantizedTensor', class extends torchao.utils.TorchAOBaseTensor {});
  20794. this.registerType('torchao.dtypes.utils.Layout', class {});
  20795. this.registerType('torchao.dtypes.uintx.plain_layout.PlainAQTTensorImpl', class {});
  20796. this.registerType('torchao.dtypes.floatx.float8_layout.Float8Layout', class extends torchao.dtypes.utils.Layout {});
  20797. this.registerType('torchao.dtypes.utils.AQTTensorImpl', class extends torchao.utils.TorchAOBaseTensor {});
  20798. this.registerType('torchao.dtypes.utils.PlainLayout', class extends torchao.dtypes.utils.Layout {});
  20799. this.registerType('torchao.dtypes.floatx.float8_layout.Float8AQTTensorImpl', class extends torchao.dtypes.utils.AQTTensorImpl {});
  20800. this.registerType('torchao.quantization.quant_primitives.ZeroPointDomain', class extends this.enum.Enum {});
  20801. this.registerFunction('torch.cuda.amp.grad_scaler._refresh_per_optimizer_state');
  20802. this.registerType('torch.SymBool', class {
  20803. constructor(node) {
  20804. this.node = node;
  20805. }
  20806. });
  20807. this.registerType('torch.SymInt', class {
  20808. constructor(node) {
  20809. this.node = node;
  20810. }
  20811. toString() {
  20812. return this.node.__str__();
  20813. }
  20814. });
  20815. this.register('torch.nn').Module = this.register('torch.nn.modules.module').Module;
  20816. this.register('torch.optim').Adam = this.register('torch.optim.adam').Adam;
  20817. this.register('torch.nn').ReLU = this.register('torch.nn.modules.activation').ReLU;
  20818. this.register('sklearn.utils').Bunch = this.register('sklearn.utils._bunch').Bunch;
  20819. /* eslint-disable no-multi-assign */
  20820. // https://github.com/pytorch/pytorch/blob/main/c10/core/ScalarType.h
  20821. torch.uint8 = torch.ByteStorage.dtype = new torch.dtype(0, 'uint8', 1);
  20822. torch.int8 = torch.CharStorage.dtype = new torch.dtype(1, 'int8', 1);
  20823. torch.int16 = torch.ShortStorage.dtype = new torch.dtype(2, 'int16', 2);
  20824. torch.int32 = torch.IntStorage.dtype = new torch.dtype(3, 'int32', 4);
  20825. torch.int64 = torch.LongStorage.dtype = new torch.dtype(4, 'int64', 8);
  20826. torch.float16 = torch.HalfStorage.dtype = new torch.dtype(5, 'float16', 2);
  20827. torch.float32 = torch.FloatStorage.dtype = new torch.dtype(6, 'float32', 4);
  20828. torch.float64 = torch.DoubleStorage.dtype = new torch.dtype(7, 'float64', 8);
  20829. torch.complex32 = torch.ComplexHalfStorage.dtype = new torch.dtype(8, 'complex<float16>', 4);
  20830. torch.complex64 = torch.ComplexFloatStorage.dtype = new torch.dtype(9, 'complex<float32>', 8);
  20831. torch.complex128 = torch.ComplexDoubleStorage.dtype = new torch.dtype(10, 'complex<float64>', 16);
  20832. torch.bool = torch.BoolStorage.dtype = new torch.dtype(11, 'boolean', 1);
  20833. torch.qint8 = torch.QInt8Storage.dtype = new torch.dtype(12, 'qint8', 1);
  20834. torch.quint8 = torch.QUInt8Storage.dtype = new torch.dtype(13, 'quint8', 1);
  20835. torch.qint32 = torch.QInt32Storage.dtype = new torch.dtype(14, 'qint32', 4);
  20836. torch.bfloat16 = torch.BFloat16Storage.dtype = new torch.dtype(15, 'bfloat16', 2);
  20837. torch.quint4x2 = torch.QUInt4x2Storage.dtype = new torch.dtype(16, 'quint4x2', 1);
  20838. torch.quint2x4 = torch.QUInt2x4Storage.dtype = new torch.dtype(17, 'quint2x4');
  20839. torch.bits1x8 = new torch.dtype(18, 'bits1x8');
  20840. torch.bits2x4 = new torch.dtype(19, 'bits2x4');
  20841. torch.bits4x2 = new torch.dtype(20, 'bits4x2');
  20842. torch.bits8 = new torch.dtype(21, 'bits8');
  20843. torch.bits16 = new torch.dtype(22, 'bits16');
  20844. torch.float8_e5m2 = new torch.dtype(23, 'float8_e5m2', 1);
  20845. torch.float8_e5m2fnuz = new torch.dtype(24, 'float8_e5m2fnuz', 1);
  20846. torch.float8_e4m3fn = new torch.dtype(25, 'float8_e4m3fn', 1);
  20847. torch.float8_e4m3fnuz = new torch.dtype(26, 'float8_e4m3fnuz', 1);
  20848. torch.uint16 = torch.UInt16Storage.dtype = new torch.dtype(27, 'uint16', 2);
  20849. torch.uint32 = torch.UInt32Storage.dtype = new torch.dtype(28, 'uint32', 4);
  20850. torch.uint64 = torch.UInt64Storage.dtype = new torch.dtype(29, 'uint64', 8);
  20851. torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE = new Map([
  20852. ['uint8', 'BYTE'],
  20853. ['int8', 'CHAR'], ['int16', 'SHORT'], ['int32', 'INT'], ['int64', 'LONG'],
  20854. ['float16', 'HALF'], ['float32', 'FLOAT'], ['float64', 'DOUBLE'],
  20855. ['complex32', 'COMPLEXHALF'], ['complex64', 'COMPLEXFLOAT'], ['complex128', 'COMPLEXDOUBLE'],
  20856. ['bool', 'BOOL'], ['bfloat16', 'BFLOAT16'], ['uint16', 'UINT16'],
  20857. ['float8_e4m3fn','FLOAT8E4M3FN'], ['float8_e5m2','FLOAT8E5M2'], ['float8_e4m3fnuz','FLOAT8E4M3FNUZ'], ['float8_e5m2fnuz','FLOAT8E5M2FNUZ']
  20858. ].map(([key, value]) => [torch._export.serde.schema.ScalarType[value], torch[key]]));
  20859. torch.contiguous_format = new torch.memory_format('contiguous_format');
  20860. torch.channels_last = new torch.memory_format('channels_last');
  20861. torch.channels_last_3d = new torch.memory_format('channels_last_3d');
  20862. torch.preserve_format = new torch.memory_format('preserve_format');
  20863. torch._export.serde.serialize._SERIALIZE_TO_TORCH_MEMORY_FORMAT = Object.fromEntries([
  20864. ['contiguous_format', 'ContiguousFormat'],
  20865. ['channels_last', 'ChannelsLast'],
  20866. ['channels_last_3d', 'ChannelsLast3d'],
  20867. ['preserve_format', 'PreserveFormat']
  20868. ].map(([key, value]) => [torch._export.serde.schema.MemoryFormat[value], torch[key]]));
  20869. /* eslint-enable no-multi-assign */
  20870. torch.strided = new torch.layout('strided');
  20871. torch.sparse_coo = new torch.layout('sparse_coo');
  20872. torch.sparse_csr = new torch.layout('sparse_csr');
  20873. torch.sparse_csc = new torch.layout('sparse_csc');
  20874. torch.sparse_bsr = new torch.layout('sparse_bsr');
  20875. torch.sparse_bsc = new torch.layout('sparse_bsc');
  20876. torch._mkldnn = new torch.layout('_mkldnn');
  20877. torch._export.serde.serialize._SERIALIZE_TO_TORCH_LAYOUT = Object.fromEntries([
  20878. ['sparse_coo', 'SparseCoo'],
  20879. ['sparse_csr', 'SparseCsr'],
  20880. ['sparse_csc', 'SparseCsc'],
  20881. ['sparse_bsr', 'SparseBsr'],
  20882. ['sparse_bsc', 'SparseBsc'],
  20883. ['_mkldnn', '_mkldnn'],
  20884. ['strided', 'Strided'],
  20885. ].map(([key, value]) => [torch._export.serde.schema.Layout[value], torch[key]]));
  20886. torch.per_tensor_affine = new torch.qscheme('torch.per_tensor_affine');
  20887. torch.per_channel_affine = new torch.qscheme('torch.per_channel_affine');
  20888. torch.per_tensor_symmetric = new torch.qscheme('torch.per_tensor_symmetric');
  20889. torch.per_channel_symmetric = new torch.qscheme('torch.per_channel_symmetric');
  20890. torch.per_channel_affine_float_qparams = new torch.qscheme('torch.per_channel_affine_float_qparams');
  20891. torch.inf = this.register('math').inf;
  20892. this.registerFunction('fastcore.basics._using_attr');
  20893. this.registerFunction('fastcore.imports.noop');
  20894. this.registerType('fastcore.basics.fastuple', class {});
  20895. this.registerType('fastcore.basics.GetAttr', class {});
  20896. this.registerType('fastcore.dispatch._TypeDict', class {});
  20897. this.registerType('fastcore.dispatch.TypeDispatch', class {});
  20898. this.registerType('fastcore.foundation.L', class {});
  20899. this.registerType('fastcore.transform.Pipeline', class extends builtins.object {});
  20900. this.registerType('fastcore.transform.Transform', class extends builtins.object {});
  20901. this.registerType('fastcore.transform.DisplayedTransform', class extends fastcore.transform.Transform {});
  20902. this.registerType('fastcore.transform.ItemTransform', class extends fastcore.transform.Transform {});
  20903. this.registerType('fastai.basic_train.Learner', class {});
  20904. this.registerType('fastai.basic_train.Recorder', class {});
  20905. this.registerFunction('fastai.torch_core._fa_rebuild_tensor', (cls, ...args) => {
  20906. const tensor = torch._utils._rebuild_tensor_v2(...args);
  20907. return self.invoke(cls, [tensor]);
  20908. });
  20909. this.registerFunction('fastai.torch_core.trainable_params');
  20910. this.registerFunction('fastai.torch_core._rebuild_from_type', (func, type, args, dict) => {
  20911. const tensor = self.invoke(type, [func(...args)]);
  20912. Object.assign(tensor, dict);
  20913. return tensor;
  20914. });
  20915. this.registerType('fastai.torch_core.Module', class extends torch.nn.modules.module.Module {});
  20916. this.registerType('fastai.torch_core.TensorBase', class extends torch.Tensor {
  20917. constructor(x) {
  20918. super();
  20919. Object.assign(this, x);
  20920. }
  20921. });
  20922. this.registerType('fastai.torch_core.TensorCategory', class extends fastai.torch_core.TensorBase {});
  20923. this.registerType('fastai.torch_core.TensorImageBase', class extends fastai.torch_core.TensorBase {});
  20924. this.registerType('fastai.torch_core.TensorImage', class extends fastai.torch_core.TensorImageBase {});
  20925. this.registerType('fastai.torch_core.TensorMask', class extends fastai.torch_core.TensorImageBase {});
  20926. this.registerType('fastai.torch_core.TensorMultiCategory', class extends fastai.torch_core.TensorCategory {});
  20927. this.registerFunction('fastai.torch_core.uniform');
  20928. this.registerType('fastai.callback.core.Callback', class extends fastcore.basics.GetAttr {});
  20929. this.registerType('fastai.callback.core.TrainEvalCallback', class extends fastai.callback.core.Callback {});
  20930. this.registerType('fastai.callback.fp16.AMPMode', class extends this.enum.Enum {});
  20931. this.registerType('fastai.callback.fp16.MixedPrecision', class {});
  20932. this.registerFunction('fastai.callback.hook._hook_inner');
  20933. this.registerType('fastai.callback.hook.Hook', class extends builtins.object {});
  20934. this.registerType('fastai.callback.hook.Hooks', class extends builtins.object {});
  20935. this.registerType('fastai.callback.mixup.MixHandler', class extends fastai.callback.core.Callback {});
  20936. this.registerType('fastai.callback.mixup.CutMix', class extends fastai.callback.mixup.MixHandler {});
  20937. this.registerType('fastai.callback.progress.ProgressCallback', class {});
  20938. this.registerType('fastai.callback.progress.ShowGraphCallback', class {});
  20939. this.registerType('fastai.callback.tracker.EarlyStoppingCallback', class {});
  20940. this.registerType('fastai.callback.tracker.TrackerCallback', class {});
  20941. this.registerType('fastai.callback.tracker.SaveModelCallback', class extends fastai.callback.tracker.TrackerCallback {});
  20942. this.registerType('fastai.data.core.DataLoaders', class extends fastcore.basics.GetAttr {});
  20943. this.registerType('fastai.data.core.Datasets', class {});
  20944. this.registerType('fastai.data.load.DataLoader', class extends fastcore.basics.GetAttr {});
  20945. this.registerType('fastai.data.core.FilteredBase', class {});
  20946. this.registerType('fastai.data.core.TfmdDL', class extends fastai.data.load.DataLoader {});
  20947. this.registerType('fastai.data.core.TfmdLists', class {});
  20948. this.registerType('fastai.data.load._FakeLoader', class {});
  20949. this.registerFunction('fastai.data.load._wif');
  20950. this.registerType('fastai.data.transforms.Categorize', class {});
  20951. this.registerType('fastai.data.transforms.Category', class {});
  20952. this.registerType('fastai.data.transforms.CategoryMap', class {});
  20953. this.registerType('fastai.data.transforms.ColReader', class {});
  20954. this.registerType('fastai.data.transforms.IntToFloatTensor', class {});
  20955. this.registerType('fastai.data.transforms.MultiCategorize', class {});
  20956. this.registerType('fastai.data.transforms.Normalize', class {});
  20957. this.registerType('fastai.data.transforms.parent_label', class {});
  20958. this.registerType('fastai.data.transforms.OneHotEncode', class {});
  20959. this.registerType('fastai.data.transforms.RegressionSetup', class {});
  20960. this.registerType('fastai.data.transforms.ToTensor', class {});
  20961. this.registerType('fastai.data_block.CategoryList', class {});
  20962. this.registerType('fastai.data_block.CategoryProcessor', class {});
  20963. this.registerType('fastai.imports.noop', class {});
  20964. this.registerType('fastai.layers.AdaptiveConcatPool2d', class {});
  20965. this.registerType('fastai.layers.ConvLayer', class {});
  20966. this.registerType('fastai.layers.Embedding', class {});
  20967. this.registerType('fastai.layers.Flatten', class {});
  20968. this.registerType('fastai.layers.FlattenedLoss', class {});
  20969. this.registerType('fastai.layers.LinBnDrop', class {});
  20970. this.registerType('fastai.layers.MergeLayer', class {});
  20971. this.registerType('fastai.layers.PixelShuffle_ICNR', class {});
  20972. this.registerType('fastai.layers.ResBlock', class {});
  20973. this.registerType('fastai.layers.SelfAttention', class {});
  20974. this.registerType('fastai.layers.SigmoidRange', class {});
  20975. this.registerType('fastai.layers.TimeDistributed', class {});
  20976. this.registerType('fastai.layers.ToTensorBase', class {});
  20977. this.registerType('fastai.learner._ConstantFunc', class {});
  20978. this.registerType('fastai.learner.Metric', class {});
  20979. this.registerType('fastai.learner.AvgLoss', class extends fastai.learner.Metric {});
  20980. this.registerType('fastai.learner.AvgMetric', class extends fastai.learner.Metric {});
  20981. this.registerType('fastai.learner.AvgSmoothLoss', class extends fastai.learner.Metric {});
  20982. this.registerType('fastai.learner.CastToTensor', class extends fastai.callback.core.Callback {});
  20983. this.registerType('fastai.learner.Dice', class extends fastai.learner.Metric {});
  20984. this.registerType('fastai.learner.Learner', class extends fastcore.basics.GetAttr {});
  20985. this.registerType('fastai.learner.Recorder', class {});
  20986. this.registerType('fastai.losses.BaseLoss', class {});
  20987. this.registerType('fastai.losses.BCEWithLogitsLossFlat', class {});
  20988. this.registerType('fastai.losses.CrossEntropyLossFlat', class extends fastai.losses.BaseLoss {});
  20989. this.registerType('fastai.losses.FocalLoss', class extends fastai.torch_core.Module {});
  20990. this.registerType('fastai.losses.FocalLossFlat', class extends fastai.losses.BaseLoss {});
  20991. this.registerType('fastai.losses.LabelSmoothingCrossEntropy', class extends fastai.torch_core.Module {});
  20992. this.registerType('fastai.metrics.AccumMetric', class extends fastai.learner.Metric {});
  20993. this.registerType('fastai.metrics.Dice', class {});
  20994. this.registerType('fastai.metrics.JaccardCoeff', class {});
  20995. this.registerFunction('fastai.metrics._rmse');
  20996. this.registerFunction('fastai.metrics.accuracy');
  20997. this.registerFunction('fastai.metrics.accuracy_multi');
  20998. this.registerFunction('fastai.metrics.foreground_acc');
  20999. this.registerFunction('fastai.metrics.mse');
  21000. this.registerFunction('fastai.metrics.error_rate');
  21001. this.registerType('fastai.optimizer._BaseOptimizer', class {});
  21002. this.registerType('fastai.optimizer.Optimizer', class extends fastai.optimizer._BaseOptimizer {});
  21003. this.registerFunction('fastai.optimizer.Adam');
  21004. this.registerFunction('fastai.optimizer.adam_step');
  21005. this.registerFunction('fastai.optimizer.average_grad');
  21006. this.registerFunction('fastai.optimizer.average_sqr_grad');
  21007. this.registerFunction('fastai.optimizer.RAdam');
  21008. this.registerFunction('fastai.optimizer.step_stat');
  21009. this.registerFunction('fastai.optimizer.weight_decay');
  21010. this.registerType('fastai.tabular.core.Categorify', class {});
  21011. this.registerType('fastai.tabular.core.FillMissing', class {});
  21012. this.registerType('fastai.tabular.core.FillStrategy', class {});
  21013. this.registerType('fastai.tabular.core.ReadTabBatch', class extends fastcore.transform.ItemTransform {});
  21014. this.registerType('fastai.tabular.core.TabDataLoader', class extends fastai.data.core.TfmdDL {});
  21015. this.registerType('fastai.tabular.data.TabularDataLoaders', class extends fastai.data.core.DataLoaders {});
  21016. this.registerType('fastai.tabular.core.Tabular', class {});
  21017. this.registerType('fastai.tabular.core.TabularPandas', class extends fastai.tabular.core.Tabular {});
  21018. this.registerType('fastai.tabular.core.TabWeightedDL', class {});
  21019. this.registerType('fastai.tabular.learner.TabularLearner', class extends fastai.learner.Learner {});
  21020. this.registerType('fastai.tabular.model.TabularModel', class {});
  21021. this.registerFunction('fastai.vision.augment.aug_transforms');
  21022. this.registerFunction('fastai.vision.augment.dihedral_mat');
  21023. this.registerType('fastai.vision.augment._BrightnessLogit', class {});
  21024. this.registerType('fastai.vision.augment._ContrastLogit', class {});
  21025. this.registerType('fastai.vision.augment._WarpCoord', class {});
  21026. this.registerType('fastai.vision.augment.RandTransform', class extends fastcore.transform.DisplayedTransform {});
  21027. this.registerType('fastai.vision.augment.AffineCoordTfm', class extends fastai.vision.augment.RandTransform {});
  21028. this.registerType('fastai.vision.augment.Brightness', class {});
  21029. this.registerType('fastai.vision.augment.flip_mat', class {});
  21030. this.registerType('fastai.vision.augment.Flip', class {});
  21031. this.registerType('fastai.vision.augment.RandomResizedCrop', class {});
  21032. this.registerType('fastai.vision.augment.RandomResizedCropGPU', class {});
  21033. this.registerType('fastai.vision.augment.Resize', class {});
  21034. this.registerType('fastai.vision.augment.rotate_mat', class {});
  21035. this.registerFunction('fastai.vision.augment.TensorImage.lighting');
  21036. this.registerType('fastai.vision.augment.Warp', class extends fastai.vision.augment.AffineCoordTfm {});
  21037. this.registerType('fastai.vision.augment.zoom_mat', class {});
  21038. this.registerType('fastai.vision.core.PILImage', class {});
  21039. this.registerType('fastai.vision.core.PILMask', class {});
  21040. this.registerType('fastai.vision.core.AddMaskCodes', class {});
  21041. this.registerType('fastai.vision.data.ImageList', class {});
  21042. this.registerType('fastai.vision.data.ImageItemList', class {});
  21043. this.registerType('fastai.vision.image.Image', class {});
  21044. this.registerType('fastai.vision.image.RandTransform', class {});
  21045. this.registerType('fastai.vision.image.TfmCrop', class {});
  21046. this.registerFunction('fastai.vision.learner._resnet_split');
  21047. this.registerFunction('fastai.vision.learner.default_split');
  21048. this.registerFunction('fastai.vision.learner.default_split');
  21049. this.registerType('fastai.vision.learner.TimmBody', class {});
  21050. this.registerType('fastai.vision.models.unet.DynamicUnet', class {});
  21051. this.registerType('fastai.vision.models.unet.ResizeToOrig', class {});
  21052. this.registerType('fastai.vision.models.unet.UnetBlock', class {});
  21053. this.registerType('fastai.vision.models.xresnet.XResNet', class {});
  21054. this.registerFunction('fastai.vision.transform._crop_pad');
  21055. }
  21056. exec(code , context) {
  21057. const ast = this.ast;
  21058. const program = ast.parse(code, '', null, null);
  21059. if (!program) {
  21060. throw new python.Error("Module '?' parse error.");
  21061. }
  21062. this.block(program.body, context);
  21063. }
  21064. debug(/* file */) {
  21065. }
  21066. source(file) {
  21067. if (this._sources.has(file)) {
  21068. return this._sources.get(file);
  21069. }
  21070. return null;
  21071. }
  21072. read(file) {
  21073. const buffer = this.source(file);
  21074. if (buffer) {
  21075. const debug = this.debug(file);
  21076. return this.parse(file, buffer, debug);
  21077. }
  21078. return null;
  21079. }
  21080. parse(filename, buffer, debug) {
  21081. const ast = this.ast;
  21082. const source = this._utf8Decoder.decode(buffer);
  21083. const program = ast.parse(source, filename, null, debug);
  21084. if (!program) {
  21085. throw new python.Error(`Module '${filename}' parse error.`);
  21086. }
  21087. return program;
  21088. }
  21089. import(name, current, level) {
  21090. if (level) {
  21091. let bits = current.split('.');
  21092. if (bits.length < level) {
  21093. throw new python.Error('Invalid relative import beyond top-level package.');
  21094. }
  21095. bits = bits.slice(0, bits.length - level);
  21096. const base = bits.join('.');
  21097. name = name ? [base, name].join('.') : base;
  21098. }
  21099. const index = name.lastIndexOf('.');
  21100. let parent = null;
  21101. let child = null;
  21102. if (index > 0) {
  21103. parent = name.substring(0, index);
  21104. child = name.substring(index + 1);
  21105. this.import(parent);
  21106. }
  21107. if (!this._modules.has(name)) {
  21108. const module = this._registry.get(name) || new this.builtins.module(name);
  21109. module.__package__ = name;
  21110. this._modules.set(name, module);
  21111. const path = name.split('.').join('/');
  21112. module.__path__ = [path];
  21113. const file = `${path}.py`;
  21114. const program = this.read(file);
  21115. if (program) {
  21116. module.__file__ = file;
  21117. for (const [name, value] of Object.entries(this.builtins)) {
  21118. switch (name) {
  21119. case '__class__':
  21120. case '__package__':
  21121. case '__module__':
  21122. case '__name__':
  21123. case '__path__':
  21124. case '__file__':
  21125. break;
  21126. default:
  21127. module[name] = value;
  21128. break;
  21129. }
  21130. }
  21131. const context = new python.Execution.Context(module, null);
  21132. if (name !== 'builtins') {
  21133. context.set('__builtins__', this._modules.get('builtins'));
  21134. }
  21135. this.block(program.body, context);
  21136. }
  21137. if (parent) {
  21138. const parent_module = this._modules.get(parent);
  21139. parent_module[child] = module;
  21140. }
  21141. }
  21142. return this._modules.get(name);
  21143. }
  21144. __import__(name, globals, locals, fromlist, level) {
  21145. let module = null;
  21146. level = level || 0;
  21147. if (level === 0) {
  21148. module = this.import(name);
  21149. } else {
  21150. globals = globals || {};
  21151. let current = globals.__package__;
  21152. if (!current) {
  21153. const spec = globals.__spec__;
  21154. if (spec) {
  21155. current = spec.parent;
  21156. } else {
  21157. const name = globals.__name__;
  21158. const bits = name.split('.');
  21159. bits.pop();
  21160. current = bits.join('.');
  21161. }
  21162. }
  21163. module = this.import(name, current, level);
  21164. }
  21165. if (!fromlist) {
  21166. if (level === 0) {
  21167. return this.import(name.split('.')[0]);
  21168. } else if (name) {
  21169. throw new python.Error(`Unsupported relative import '${name}'.`);
  21170. // cut_off = len(name) - len(name.partition('.')[0])
  21171. // return sys.modules[module.__name__[:len(module.__name__)-cut_off]]
  21172. }
  21173. } else if (module.__path__) {
  21174. const handle_fromlist = (module, fromlist, recursive) => {
  21175. for (const name of fromlist) {
  21176. if (name === '*') {
  21177. if (!recursive && module.__all__) {
  21178. handle_fromlist(module, module.__all__, true);
  21179. }
  21180. } else if (!module[name]) {
  21181. this.import(`${module.__name__}.${name}`);
  21182. }
  21183. }
  21184. return module;
  21185. };
  21186. handle_fromlist(module, fromlist);
  21187. }
  21188. return module;
  21189. }
  21190. module(name) {
  21191. return this._modules.get(name);
  21192. }
  21193. resolve(name) {
  21194. const index = name.lastIndexOf('.');
  21195. const memberName = index === -1 ? name : name.substring(index + 1, name.length);
  21196. const moduleName = index === -1 ? '' : name.substring(0, index);
  21197. const module = this.import(moduleName);
  21198. let type = module ? module[memberName] : null;
  21199. if (!type) {
  21200. if (!this._unresolved.has(name)) {
  21201. const moduleName = name.split('.').shift();
  21202. if (this._registry.has(moduleName) && moduleName !== '__main__' && moduleName !== '__torch__') {
  21203. this.emit('resolve', name);
  21204. }
  21205. const type = this._createType(name, class {});
  21206. this._unresolved.set(name, type);
  21207. }
  21208. type = this._unresolved.get(name);
  21209. }
  21210. return type;
  21211. }
  21212. invoke(target, args) {
  21213. const builtins = this.builtins;
  21214. if (typeof target === 'string') {
  21215. target = this.resolve(target);
  21216. }
  21217. if (target) {
  21218. if (target.__class__ === builtins.type) {
  21219. if (target.prototype && target.prototype.__class__ === target) {
  21220. return Reflect.construct(target, args);
  21221. }
  21222. const obj = Object.create(target);
  21223. if (obj.__init__ && typeof obj.__init__ === 'function') {
  21224. obj.__init__(...args);
  21225. }
  21226. return obj;
  21227. } else if (target.__class__ === builtins.function) {
  21228. if (target.__call__) {
  21229. return target.__call__(args);
  21230. }
  21231. return target(...args);
  21232. }
  21233. }
  21234. throw new python.Error('Unsupported invoke target.');
  21235. }
  21236. call(target, name, args, keywords, context) {
  21237. const builtins = this.builtins;
  21238. const callTarget = this.target(target, context);
  21239. const callArguments = args.map((arg) => this.expression(arg, context));
  21240. if (!callTarget || (name !== null && !callTarget[name])) {
  21241. if (name === '__new__' && callArguments.length === 1 && callArguments[0] === callTarget) {
  21242. name = null;
  21243. callArguments.shift();
  21244. } else {
  21245. const targetName = `${this.identifier(target)}.${name}`;
  21246. throw new python.Error(`Unknown function '${targetName}'.`);
  21247. }
  21248. }
  21249. const func = name ? callTarget[name] : callTarget;
  21250. if (func.__class__ === builtins.type) {
  21251. if (func.prototype && func.prototype.__class__ === func) {
  21252. return Reflect.construct(func, callArguments);
  21253. }
  21254. const obj = Object.create(func);
  21255. obj.__class__ = func;
  21256. if (obj.__init__ && typeof obj.__init__ === 'function') {
  21257. obj.__init__(...args);
  21258. }
  21259. return obj;
  21260. }
  21261. if (func.__class__ === builtins.function) {
  21262. if (func.__call__) {
  21263. return func.__call__(callArguments);
  21264. }
  21265. }
  21266. if (func.__class__ === builtins.method) {
  21267. if (func.__call__) {
  21268. return func.__call__([callTarget].concat(callArguments));
  21269. }
  21270. }
  21271. if (typeof func === 'function') {
  21272. return func.apply(callTarget, callArguments);
  21273. }
  21274. throw new python.Error('Unsupported call expression.');
  21275. }
  21276. apply(method, args, context) {
  21277. const locals = Array.prototype.slice.call(args);
  21278. context = new python.Execution.Context(context.globals, {});
  21279. args = method.args.posonlyargs.concat(method.args.args);
  21280. const default_pos = args.length - method.args.defaults.length;
  21281. for (let i = 0; i < method.args.args.length; i++) {
  21282. const arg = method.args.args[i];
  21283. let value = null;
  21284. if (locals.length > 0) {
  21285. value = locals.shift();
  21286. } else if (i >= default_pos) {
  21287. value = this.expression(method.args.defaults[i - default_pos], context);
  21288. } else {
  21289. throw new python.Error('Missing required positional argument.');
  21290. }
  21291. context.set(arg.arg, value);
  21292. }
  21293. return this.block(method.body, context);
  21294. }
  21295. block(statements, context) {
  21296. statements = Array.prototype.slice.call(statements);
  21297. while (statements.length > 0) {
  21298. const stmt = statements.shift();
  21299. const value = this.statement(stmt, context);
  21300. if (value !== undefined) {
  21301. return value;
  21302. }
  21303. }
  21304. return undefined;
  21305. }
  21306. statement(stmt, context) {
  21307. const ast = this.ast;
  21308. const builtins = this.builtins;
  21309. if (stmt instanceof ast.Pass) {
  21310. // pass
  21311. } else if (stmt instanceof ast.Constant) {
  21312. // pass
  21313. } else if (stmt instanceof ast.Return) {
  21314. return this.expression(stmt.value, context);
  21315. } else if (stmt instanceof ast.FunctionDef) {
  21316. const module = context.get('__name__');
  21317. /* eslint-disable consistent-this */
  21318. const self = this;
  21319. /* eslint-enable consistent-this */
  21320. const parent = context.get('__class__');
  21321. const type = (parent === builtins.module) ? builtins.function : builtins.method;
  21322. const func = {
  21323. __class__: type,
  21324. __globals__: context,
  21325. __module__: module,
  21326. __name__: stmt.name,
  21327. __code__: stmt,
  21328. __call__(args) {
  21329. return self.apply(this.__code__, args, this.__globals__);
  21330. }
  21331. };
  21332. context.set(stmt.name, func);
  21333. } else if (stmt instanceof ast.ClassDef) {
  21334. const bases = stmt.bases.map((base) => this.base(base, context));
  21335. if (bases.length > 1) {
  21336. throw new python.Error(`Unsupported multiple bases for class '${stmt.name}'.`);
  21337. }
  21338. const base = bases.length === 1 ? bases[0] : null;
  21339. const name = `${context.get('__name__')}.${stmt.name}`;
  21340. const value = this._createType(name, base ? class extends base {} : class {});
  21341. value.__bases__ = bases;
  21342. context.set(stmt.name, value);
  21343. this.block(stmt.body, new python.Execution.Context(context.globals, value.prototype));
  21344. } else if (stmt instanceof ast.AnnAssign) {
  21345. const target = this.identifier(stmt.target, context);
  21346. context.set(target, stmt.value ? this.expression(stmt.value, context) : undefined);
  21347. } else if (stmt instanceof ast.Assign) {
  21348. this.expression(stmt, context);
  21349. } else if (stmt instanceof ast.If) {
  21350. const test = this.expression(stmt.test, context);
  21351. if (test === true || test) {
  21352. const value = this.block(stmt.body, context);
  21353. if (value !== undefined) {
  21354. return value;
  21355. }
  21356. } else if (test === false) {
  21357. if (stmt.orelse) {
  21358. const value = this.block(stmt.orelse, context);
  21359. if (value !== undefined) {
  21360. return value;
  21361. }
  21362. }
  21363. } else {
  21364. throw new python.Error('Unsupported condition.');
  21365. }
  21366. } else if (stmt instanceof ast.For) {
  21367. if (stmt.target instanceof ast.Name && stmt.iter instanceof ast.Tuple === false) {
  21368. const range = this.expression(stmt.iter, context);
  21369. const variable = stmt.target;
  21370. for (const current of range) {
  21371. this.statement({ type: '=', target: variable, expression: { type: 'number', value: current } }, context);
  21372. const value = this.block(stmt.body.statements, context);
  21373. if (value !== undefined) {
  21374. return value;
  21375. }
  21376. }
  21377. } else {
  21378. throw new python.Error("Unsupported 'for' statement.");
  21379. }
  21380. } else if (stmt instanceof ast.While) {
  21381. const test = this.expression(stmt.test, context);
  21382. if (test) {
  21383. const value = this.block(stmt.body.statements, context);
  21384. if (value !== undefined) {
  21385. return value;
  21386. }
  21387. }
  21388. } else if (stmt instanceof ast.With) {
  21389. const items = [];
  21390. for (const item of stmt.items) {
  21391. items.push(this.expression(item.context_expr, context));
  21392. }
  21393. for (const item of items) {
  21394. if (item.__enter__ && item.__enter__.__call__) {
  21395. item.__enter__.__call__([item]);
  21396. }
  21397. }
  21398. const value = this.block(stmt.body, context);
  21399. for (const item of items) {
  21400. if (item.__exit__ && item.__exit__.__call__) {
  21401. item.__exit__.__call__([item]);
  21402. }
  21403. }
  21404. if (value !== undefined) {
  21405. return value;
  21406. }
  21407. } else if (stmt instanceof ast.Expr) {
  21408. this.expression(stmt.value, context);
  21409. } else if (stmt instanceof ast.Import) {
  21410. for (const alias of stmt.names) {
  21411. let module = this.__import__(alias.name, context);
  21412. if (alias.asname) {
  21413. const bits = alias.name.split('.').reverse();
  21414. bits.pop();
  21415. while (bits.length > 0) {
  21416. module = module[bits.pop()];
  21417. }
  21418. context.set(alias.asname, module);
  21419. } else {
  21420. context.set(alias.name.split('.')[0], module);
  21421. }
  21422. }
  21423. } else if (stmt instanceof ast.ImportFrom) {
  21424. const fromlist = stmt.names.map((name) => name.name);
  21425. const module = this.__import__(stmt.module, context.globals, context.locals, fromlist, stmt.level);
  21426. for (const entry of stmt.names) {
  21427. const name = entry.name;
  21428. const asname = entry.asname ? entry.asname : null;
  21429. if (!module[name]) {
  21430. throw new python.Error(`Cannot import '${name}' from '${stmt.module}'.`);
  21431. }
  21432. context.set(asname ? asname : name, module[name]);
  21433. }
  21434. } else {
  21435. throw new python.Error(`Unsupported statement '${stmt.__class__.__name__}'.`);
  21436. }
  21437. return undefined;
  21438. }
  21439. expression(expr, context) {
  21440. const ast = this.ast;
  21441. const builtins = this.builtins;
  21442. const typing = this.typing;
  21443. const self = context.get('self');
  21444. switch (expr.__class__.__name__) {
  21445. case 'Assign': {
  21446. const [target] = expr.targets;
  21447. if (target instanceof ast.Name) {
  21448. const value = this.expression(expr.value, context);
  21449. context.set(target.id, value);
  21450. return undefined;
  21451. } else if (target instanceof ast.Subscript) {
  21452. if (target.value instanceof ast.Name &&
  21453. target.slice instanceof ast.List &&
  21454. target.slice.elts.length === 1) {
  21455. const index = this.expression(target.slice.elts[0], context);
  21456. const id = target.value.id;
  21457. if (id === '__annotations__') {
  21458. context.set(id, context.get(id) || {});
  21459. }
  21460. const obj = context.get(id);
  21461. const value = this.expression(expr.value, context);
  21462. if (obj instanceof Map) {
  21463. obj.set(index, value);
  21464. } else {
  21465. obj[index] = value;
  21466. }
  21467. return undefined;
  21468. }
  21469. } else if (target instanceof ast.Attribute) {
  21470. const obj = this.expression(target.value, context);
  21471. const value = this.expression(expr.value, context);
  21472. obj[target.attr] = value;
  21473. return undefined;
  21474. } else if (target instanceof ast.Tuple) {
  21475. context.target.push(target.elts);
  21476. const value = this.expression(expr.value, context);
  21477. context.target.pop();
  21478. if (target.elts.every((elt) => elt instanceof ast.Name)) {
  21479. if (target.elts.length < value.length) {
  21480. throw new python.Error(`ValueError: too many values to unpack (expected ${target.value.length}, actual ${value.length}).`);
  21481. }
  21482. if (target.elts.length > value.length) {
  21483. throw new python.Error(`ValueError: not enough values to unpack (expected ${target.value.length}, actual ${value.length}).`);
  21484. }
  21485. for (let i = 0; i < value.length; i++) {
  21486. context.set(target.elts[i].id, value[i]);
  21487. }
  21488. return undefined;
  21489. }
  21490. }
  21491. break;
  21492. }
  21493. case 'List': {
  21494. return expr.elts.map((expr) => this.expression(expr, context));
  21495. }
  21496. case 'Constant': {
  21497. return expr.value;
  21498. }
  21499. case 'Subscript': {
  21500. if (expr.value instanceof ast.Name && expr.slice instanceof ast.Tuple === false) {
  21501. const id = expr.value.id;
  21502. if (context.get(id)) {
  21503. const index = this.expression(expr.slice, context);
  21504. const target = context.get(id);
  21505. if (target instanceof Map) {
  21506. return target.get(index);
  21507. }
  21508. return target[index < 0 ? target.length + index : index];
  21509. }
  21510. }
  21511. const value = this.expression(expr.value, context);
  21512. if (value && expr.slice instanceof ast.List &&
  21513. (value.__class__ === typing._TupleType ||
  21514. value.__class__ === typing._SpecialGenericAlias ||
  21515. value.__class__ === typing._SpecialForm)) {
  21516. const type = { ...value };
  21517. type.__args__ = expr.slice.elts.map((arg) => this.expression(arg, context));
  21518. return type;
  21519. }
  21520. if (expr.slice instanceof ast.List && expr.slice.elts.length === 1) {
  21521. const index = this.expression(expr.slice.elts[0], context);
  21522. if (value instanceof Map) {
  21523. return value.get(index);
  21524. }
  21525. return value[index < 0 ? value.length + index : index];
  21526. }
  21527. break;
  21528. }
  21529. case 'Attribute': {
  21530. const value = this.target(expr.value, context);
  21531. return value[expr.attr];
  21532. }
  21533. case 'Call': {
  21534. const func = expr.func;
  21535. if (func instanceof ast.Attribute) {
  21536. return this.call(func.value, func.attr, expr.args, expr.keywords, context, expr.range ? expr.range() : null);
  21537. }
  21538. return this.call(func, null, expr.args, expr.keywords, context, expr.range ? expr.range() : null);
  21539. }
  21540. case 'Name': {
  21541. const id = expr.id;
  21542. if (id === 'self') {
  21543. return self;
  21544. }
  21545. const type = (value) => {
  21546. return value &&
  21547. (value.__class__ === builtins.type ||
  21548. value.__class__ === typing._TupleType ||
  21549. value.__class__ === typing._SpecialGenericAlias ||
  21550. value.__class__ === typing._SpecialForm);
  21551. };
  21552. const builtin = builtins[id];
  21553. if (type(builtin)) {
  21554. return builtin;
  21555. }
  21556. const value = context.get(id);
  21557. if (value === undefined) {
  21558. const value = typing[id];
  21559. if (type(value)) {
  21560. return value;
  21561. }
  21562. }
  21563. return value;
  21564. }
  21565. case 'Tuple': {
  21566. return expr.elts.map((expr) => this.expression(expr, context));
  21567. }
  21568. case 'Dict': {
  21569. const dict = {};
  21570. for (let i = 0; i < expr.keys.length; i++) {
  21571. const key = this.expression(expr.keys[i], context);
  21572. const value = this.expression(expr.values[i], context);
  21573. dict[key] = value;
  21574. }
  21575. return dict;
  21576. }
  21577. case 'UnaryOp': {
  21578. if (expr.op instanceof ast.USub) {
  21579. return -this.expression(expr.operand, context);
  21580. }
  21581. throw new python.Error(`Unsupported unary expression '${expr.op}'.`);
  21582. }
  21583. case 'binary': {
  21584. switch (expr.op) {
  21585. case '==': {
  21586. return this.expression(expr.left, context) === this.expression(expr.right, context);
  21587. }
  21588. default: {
  21589. throw new python.Error(`Unsupported binary expression '${expr.op}'.`);
  21590. }
  21591. }
  21592. }
  21593. default: {
  21594. throw new python.Error(`Unsupported expression '${expr.type}'.`);
  21595. }
  21596. }
  21597. return undefined;
  21598. }
  21599. base(expr, context) {
  21600. return this.expression(expr, context);
  21601. }
  21602. identifier(expr) {
  21603. const ast = this.ast;
  21604. if (expr instanceof ast.Name) {
  21605. return expr.id;
  21606. }
  21607. if (expr instanceof ast.Attribute) {
  21608. return `${this.identifier(expr.value)}.${expr.attr}`;
  21609. }
  21610. return null;
  21611. }
  21612. target(expr, context) {
  21613. const ast = this.ast;
  21614. let current = expr;
  21615. let path = [];
  21616. for (;;) {
  21617. if (current instanceof ast.Attribute) {
  21618. path.push(current.attr);
  21619. current = current.value;
  21620. } else if (current instanceof ast.Name && current.id !== 'self' && current.id !== 'CONSTANTS') {
  21621. path.push(current.id);
  21622. break;
  21623. } else {
  21624. path = null;
  21625. break;
  21626. }
  21627. }
  21628. if (path) {
  21629. let target = null;
  21630. for (let i = path.length - 1; i >= 0; i--) {
  21631. const name = path[i];
  21632. if (target) {
  21633. target = target.__getattr__ ? target.__getattr__(name) : target[name];
  21634. } else {
  21635. target = context.get(name);
  21636. }
  21637. if (!target) {
  21638. break;
  21639. }
  21640. }
  21641. if (!target) {
  21642. path.reverse();
  21643. const name = path.join('.');
  21644. const file = `${path.join('/')}.py`;
  21645. if (this._sources.has(file)) {
  21646. target = this.import(name);
  21647. } else {
  21648. target = this.resolve(name);
  21649. }
  21650. }
  21651. return target;
  21652. }
  21653. return this.expression(expr, context);
  21654. }
  21655. add(name, source) {
  21656. this._sources.set(name, source);
  21657. }
  21658. on(event, listener) {
  21659. const value = this._events.get(event) || [];
  21660. value.push(listener);
  21661. this._events.set(event, value);
  21662. }
  21663. emit(event, ...args) {
  21664. if (this._events.has(event)) {
  21665. for (const callback of this._events.get(event)) {
  21666. callback(this, ...args);
  21667. }
  21668. }
  21669. }
  21670. register(name, value) {
  21671. if (!this._registry.has(name)) {
  21672. value = value || new (this._registry.get('builtins').module)(name);
  21673. this._registry.set(name, value);
  21674. let current = name;
  21675. for (;;) {
  21676. const index = current.lastIndexOf('.');
  21677. if (index === -1) {
  21678. break;
  21679. }
  21680. const child = current.substring(index + 1);
  21681. current = current.substring(0, index);
  21682. if (!value.__module__) {
  21683. value.__module__ = current;
  21684. }
  21685. const parent = this.register(current);
  21686. parent[child] = value;
  21687. value = parent;
  21688. }
  21689. }
  21690. return this._registry.get(name);
  21691. }
  21692. registerFunction(name, value) {
  21693. const builtins = this.builtins;
  21694. const index = name.lastIndexOf('.');
  21695. if (!value) {
  21696. value = () => {
  21697. throw new python.Error(`'${name}' is not implemented.`);
  21698. };
  21699. }
  21700. value.__class__ = builtins.function;
  21701. value.__name__ = index === -1 ? name : name.substring(index + 1);
  21702. value.__module__ = index === -1 ? '' : name.substring(0, index);
  21703. const module = this.register(value.__module__);
  21704. if (module[name]) {
  21705. throw new python.Error(`Function '${name}' is already registered.`);
  21706. }
  21707. module[value.__name__] = value;
  21708. return value;
  21709. }
  21710. registerOperator(name, value) {
  21711. this._operators.set(name, value);
  21712. }
  21713. _createType(name, value) {
  21714. const builtins = this.builtins;
  21715. const index = name.lastIndexOf('.');
  21716. value.__class__ = builtins.type;
  21717. value.__name__ = index === -1 ? name : name.substring(index + 1);
  21718. value.__module__ = index === -1 ? '' : name.substring(0, index);
  21719. value.prototype.__class__ = value;
  21720. return value;
  21721. }
  21722. registerType(name, value) {
  21723. value = this._createType(name, value);
  21724. const parts = name.split('.');
  21725. const memberName = parts.pop();
  21726. const moduleName = parts.join('.');
  21727. const module = this.register(moduleName);
  21728. if (module[memberName]) {
  21729. throw new python.Error(`Class '${memberName}' is already registered.`);
  21730. }
  21731. module[memberName] = value;
  21732. return value;
  21733. }
  21734. };
  21735. python.Execution.Context = class {
  21736. constructor(globals, locals) {
  21737. this.globals = globals;
  21738. this.locals = locals;
  21739. }
  21740. set(name, value) {
  21741. if (this.locals) {
  21742. this.locals[name] = value;
  21743. } else {
  21744. this.globals[name] = value;
  21745. }
  21746. }
  21747. get(name) {
  21748. if (this.locals && name in this.locals) {
  21749. return this.locals[name];
  21750. }
  21751. if (name in this.globals) {
  21752. return this.globals[name];
  21753. }
  21754. return undefined;
  21755. }
  21756. get target() {
  21757. this._target = this._target || [];
  21758. return this._target;
  21759. }
  21760. };
  21761. python.BinaryReader = class {
  21762. constructor(buffer) {
  21763. this._buffer = buffer;
  21764. this._length = buffer.length;
  21765. this._position = 0;
  21766. this._view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  21767. this._utf8Decoder = new TextDecoder('utf-8');
  21768. this._asciiDecoder = new TextDecoder('ascii');
  21769. }
  21770. get position() {
  21771. return this._position;
  21772. }
  21773. get length() {
  21774. return this._length;
  21775. }
  21776. seek(position) {
  21777. this._position = position >= 0 ? position : this._length + position;
  21778. if (this._position > this._buffer.length) {
  21779. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21780. }
  21781. }
  21782. skip(offset) {
  21783. this._position += offset;
  21784. if (this._position > this._buffer.length) {
  21785. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21786. }
  21787. }
  21788. stream(length) {
  21789. const buffer = this.read(length);
  21790. return new python.BinaryReader(buffer);
  21791. }
  21792. peek(length) {
  21793. const position = this._position;
  21794. length = length === undefined ? this._length - this._position : length;
  21795. this.skip(length);
  21796. const end = this._position;
  21797. this.skip(-length);
  21798. if (position === 0 && length === this._length) {
  21799. return this._buffer;
  21800. }
  21801. return this._buffer.subarray(position, end);
  21802. }
  21803. read(length) {
  21804. const position = this._position;
  21805. length = length === undefined ? this._length - this._position : length;
  21806. this.skip(length);
  21807. if (position === 0 && length === this._length) {
  21808. return this._buffer;
  21809. }
  21810. return this._buffer.subarray(position, this._position);
  21811. }
  21812. byte() {
  21813. const position = this._position;
  21814. this.skip(1);
  21815. return this._view.getUint8(position);
  21816. }
  21817. uint16() {
  21818. const position = this._position;
  21819. this.skip(2);
  21820. return this._view.getUint16(position, true);
  21821. }
  21822. int32() {
  21823. const position = this._position;
  21824. this.skip(4);
  21825. return this._view.getInt32(position, true);
  21826. }
  21827. uint32() {
  21828. const position = this._position;
  21829. this.skip(4);
  21830. return this._view.getUint32(position, true);
  21831. }
  21832. int64() {
  21833. const position = this._position;
  21834. this.skip(8);
  21835. return this._view.getBigInt64(position, true);
  21836. }
  21837. float64() {
  21838. const position = this._position;
  21839. this.skip(8);
  21840. return this._view.getFloat64(position, false);
  21841. }
  21842. string(size, encoding) {
  21843. const data = this.read(size);
  21844. return (encoding === 'utf-8') ?
  21845. this._utf8Decoder.decode(data) :
  21846. this._asciiDecoder.decode(data);
  21847. }
  21848. line() {
  21849. const index = this._buffer.indexOf(0x0A, this._position);
  21850. if (index === -1) {
  21851. throw new python.Error('Could not find end of line.');
  21852. }
  21853. const size = index - this._position;
  21854. const text = this.string(size, 'ascii');
  21855. this.skip(1);
  21856. return text;
  21857. }
  21858. };
  21859. python.StreamReader = class {
  21860. constructor(stream) {
  21861. this._stream = stream;
  21862. this._length = stream.length;
  21863. this._position = 0;
  21864. this._utf8Decoder = new TextDecoder('utf-8');
  21865. this._asciiDecoder = new TextDecoder('ascii');
  21866. }
  21867. get position() {
  21868. return this._position;
  21869. }
  21870. get length() {
  21871. return this._length;
  21872. }
  21873. seek(position) {
  21874. this._stream.seek(position);
  21875. this._position = this._stream.position;
  21876. }
  21877. skip(offset) {
  21878. this._position += offset;
  21879. if (this._position > this._length) {
  21880. throw new python.Error(`Expected ${this._position - this._length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21881. }
  21882. }
  21883. stream(length) {
  21884. this._stream.seek(this._position);
  21885. this.skip(length);
  21886. return this._stream.stream(length);
  21887. }
  21888. peek(length) {
  21889. this._stream.seek(this._position);
  21890. return this._stream.peek(length);
  21891. }
  21892. read(length) {
  21893. this._stream.seek(this._position);
  21894. this.skip(length);
  21895. return this._stream.read(length);
  21896. }
  21897. byte() {
  21898. const position = this._fill(1);
  21899. return this._view.getUint8(position);
  21900. }
  21901. uint16() {
  21902. const position = this._fill(2);
  21903. return this._view.getUint16(position, true);
  21904. }
  21905. int32() {
  21906. const position = this._fill(4);
  21907. return this._view.getInt32(position, true);
  21908. }
  21909. uint32() {
  21910. const position = this._fill(4);
  21911. return this._view.getUint32(position, true);
  21912. }
  21913. int64() {
  21914. const position = this._fill(8);
  21915. return this._view.getBigInt64(position, true);
  21916. }
  21917. float64() {
  21918. const position = this._fill(8);
  21919. return this._view.getFloat64(position, false);
  21920. }
  21921. string(size, encoding) {
  21922. const data = this.read(size);
  21923. return (encoding === 'utf-8') ?
  21924. this._utf8Decoder.decode(data) :
  21925. this._asciiDecoder.decode(data);
  21926. }
  21927. line() {
  21928. let position = this._fill(0);
  21929. let index = this._buffer.indexOf(0x0A, position);
  21930. if (index === -1) {
  21931. const size = Math.min(0x20000000, this._stream.length - this._position);
  21932. this._fill(size);
  21933. this.skip(-size);
  21934. position = this._fill(0);
  21935. index = this._buffer.indexOf(0x0A, position);
  21936. if (index === -1) {
  21937. throw new python.Error('Could not find end of line.');
  21938. }
  21939. }
  21940. const size = index - position;
  21941. const text = this.string(size, 'ascii');
  21942. this.skip(1);
  21943. return text;
  21944. }
  21945. _fill(length) {
  21946. if (this._position + length > this._length) {
  21947. throw new Error(`Expected ${this._position + length - this._length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21948. }
  21949. if (!this._buffer || this._position < this._offset || this._position + length > this._offset + this._buffer.length) {
  21950. this._offset = this._position;
  21951. this._stream.seek(this._offset);
  21952. const size = Math.max(length, Math.min(0x10000000, this._length - this._offset));
  21953. this._buffer = this._stream.read(size);
  21954. this._view = new DataView(this._buffer.buffer, this._buffer.byteOffset, this._buffer.byteLength);
  21955. }
  21956. const position = this._position;
  21957. this._position += length;
  21958. return position - this._offset;
  21959. }
  21960. };
  21961. python.Error = class extends Error {
  21962. constructor(message) {
  21963. super(message);
  21964. this.name = 'Python Error';
  21965. }
  21966. };
  21967. export const Execution = python.Execution;