python.js 496 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106
  1. // Experimental Python Execution
  2. const python = {};
  3. python.Parser = class {
  4. constructor(text, file, debug) {
  5. this._tokenizer = new python.Tokenizer(text, file);
  6. this._debug = debug;
  7. python.Parser._precedence = python.Parser._precedence || {
  8. 'or': 2, 'and': 3, 'not' : 4,
  9. 'in': 5, 'instanceof': 5, 'is': 5, '<': 5, '>': 5, '<=': 5, '>=': 5, '<>': 5, '==': 5, '!=': 5,
  10. '|': 6, '^' : 7, '&' : 8,
  11. '<<': 9, '>>': 9, '+': 10, '-': 10, '*': 11, '@': 11, '/': 11, '//': 11, '%': 11,
  12. // '+': 12, '-': 12,
  13. '~': 13, '**': 14
  14. };
  15. }
  16. parse() {
  17. const node = this._node('program');
  18. node.body = [];
  19. while (!this._tokenizer.match('eof')) {
  20. const statement = this._statement();
  21. if (statement) {
  22. node.body.push(statement);
  23. continue;
  24. }
  25. if (this._tokenizer.eat('\n') || this._tokenizer.eat(';') || this._tokenizer.peek().type === 'eof') {
  26. continue;
  27. }
  28. if (this._tokenizer.eat('indent') && this._tokenizer.peek().type === 'eof') {
  29. continue;
  30. }
  31. throw new python.Error(`Unsupported statement ${this._tokenizer.location()}`);
  32. }
  33. return node;
  34. }
  35. _suite() {
  36. const node = this._node('block');
  37. node.statements = [];
  38. let statement = null;
  39. if (this._tokenizer.eat('\n')) {
  40. if (this._tokenizer.eat('indent')) {
  41. while (!this._tokenizer.eat('eof') && !this._tokenizer.eat('dedent')) {
  42. if (this._tokenizer.eat(';')) {
  43. continue;
  44. }
  45. statement = this._statement();
  46. if (statement) {
  47. node.statements.push(statement);
  48. continue;
  49. }
  50. if (this._tokenizer.eat('\n')) {
  51. continue;
  52. }
  53. if (this._tokenizer.match('dedent') || this._tokenizer.match('eof')) {
  54. continue;
  55. }
  56. throw new python.Error(`Empty statement ${this._tokenizer.location()}`);
  57. }
  58. }
  59. } else if (!this._tokenizer.eat('eof')) {
  60. while (!this._tokenizer.match('\n') && !this._tokenizer.match('eof') && !this._tokenizer.match('dedent')) {
  61. if (this._tokenizer.eat(';')) {
  62. continue;
  63. }
  64. statement = this._statement();
  65. if (statement) {
  66. node.statements.push(statement);
  67. continue;
  68. }
  69. throw new python.Error(`Empty statement ${this._tokenizer.location()}`);
  70. }
  71. this._tokenizer.eat('\n');
  72. }
  73. return node;
  74. }
  75. _statement() {
  76. let node = this._eat('id', 'break');
  77. if (node) {
  78. return node;
  79. }
  80. node = this._eat('id', 'continue');
  81. if (node) {
  82. return node;
  83. }
  84. node = this._eat('id', 'return');
  85. if (node) {
  86. node.expression = this._expression(-1, [], true);
  87. return node;
  88. }
  89. node = this._eat('id', 'raise');
  90. if (node) {
  91. node.exception = this._expression(-1, ['from']);
  92. if (this._tokenizer.eat('id', 'from')) {
  93. node.from = this._expression();
  94. } else if (this._tokenizer.eat(',')) {
  95. node.exception = [node.exception];
  96. node.exception.push(this._expression());
  97. if (this._tokenizer.eat(',')) {
  98. node.exception.push(this._expression());
  99. }
  100. }
  101. return node;
  102. }
  103. node = this._eat('id', 'assert');
  104. if (node) {
  105. node.test = this._expression(-1, [',']);
  106. if (this._tokenizer.eat(',')) {
  107. node.msg = this._expression();
  108. }
  109. return node;
  110. }
  111. node = this._eat('id', 'exec');
  112. if (node) {
  113. node.variable = this._expression(-1, ['in']);
  114. if (this._tokenizer.eat('in')) {
  115. do {
  116. node.target = node.target || [];
  117. node.target.push(this._expression(-1, ['in'], false));
  118. }
  119. while (this._tokenizer.eat(','));
  120. }
  121. return node;
  122. }
  123. node = this._eat('id', 'global');
  124. if (node) {
  125. node.names = [];
  126. do {
  127. node.names.push(this._name(true).value);
  128. }
  129. while (this._tokenizer.eat(','));
  130. return node;
  131. }
  132. node = this._eat('id', 'nonlocal');
  133. if (node) {
  134. node.names = [];
  135. do {
  136. node.names.push(this._name(true).value);
  137. }
  138. while (this._tokenizer.eat(','));
  139. return node;
  140. }
  141. node = this._eat('id', 'import');
  142. if (node) {
  143. node.names = [];
  144. do {
  145. const alias = this._node('alias');
  146. alias.name = this._dottedName();
  147. if (this._tokenizer.eat('id', 'as')) {
  148. alias.asname = this._name(true).value;
  149. }
  150. node.names.push(alias);
  151. }
  152. while (this._tokenizer.eat(','));
  153. return node;
  154. }
  155. node = this._eat('id', 'from');
  156. if (node) {
  157. node.type = 'import_from';
  158. node.level = 0;
  159. const dots = this._tokenizer.peek();
  160. if (dots && Array.from(dots.type).every((c) => c === '.')) {
  161. this._eat(dots.type);
  162. node.level = Array.from(dots.type).length;
  163. }
  164. node.module = this._dottedName();
  165. this._tokenizer.expect('id', 'import');
  166. node.names = [];
  167. const close = this._tokenizer.eat('(');
  168. do {
  169. const alias = this._node('alias');
  170. alias.name = this._name(true).value;
  171. if (this._tokenizer.eat('id', 'as')) {
  172. alias.asname = this._name(true).value;
  173. }
  174. node.names.push(alias);
  175. }
  176. while (this._tokenizer.eat(','));
  177. if (close) {
  178. this._tokenizer.expect(')');
  179. }
  180. return node;
  181. }
  182. let decorator_list = this._decorator();
  183. node = this._eat('id', 'class');
  184. if (node) {
  185. node.name = this._name(true).value;
  186. if (decorator_list) {
  187. node.decorator_list = Array.from(decorator_list);
  188. decorator_list = null;
  189. }
  190. node.bases = this._tokenizer.peek().type === '(' ? this._arguments() : [];
  191. this._tokenizer.expect(':');
  192. node.body = this._suite();
  193. return node;
  194. }
  195. const async = this._eat('id', 'async');
  196. if (async &&
  197. !this._tokenizer.match('id', 'def') &&
  198. !this._tokenizer.match('id', 'with') &&
  199. !this._tokenizer.match('id', 'for')) {
  200. throw new python.Error(`Expected 'def', 'with' or 'for' ${this._tokenizer.location()}`);
  201. }
  202. node = this._eat('id', 'def');
  203. if (node) {
  204. if (async) {
  205. node.async = async;
  206. }
  207. node.name = this._name(true).value;
  208. if (decorator_list) {
  209. node.decorator_list = Array.from(decorator_list);
  210. decorator_list = null;
  211. }
  212. this._tokenizer.expect('(');
  213. node.args = this._parameters(')');
  214. if (this._tokenizer.eat('->')) {
  215. node.returnType = this._type();
  216. }
  217. this._tokenizer.expect(':');
  218. node.body = this._suite();
  219. return node;
  220. }
  221. if (decorator_list && decorator_list.length > 0) {
  222. throw new python.Error('Unexpected decorator.');
  223. }
  224. node = this._eat('id', 'del');
  225. if (node) {
  226. node.expression = this._expression(-1, [], true);
  227. return node;
  228. }
  229. // node = this._eat('id', 'print');
  230. // if (node) {
  231. // node.expression = this._expression(-1, [], true);
  232. // return node;
  233. // }
  234. node = this._eat('id', 'if');
  235. if (node) {
  236. node.test = this._expression();
  237. this._tokenizer.expect(':');
  238. node.body = this._suite();
  239. let current = node;
  240. this._tokenizer.eat('\n');
  241. while (this._tokenizer.eat('id', 'elif')) {
  242. current.orelse = this._node('if');
  243. current = current.orelse;
  244. current.test = this._expression();
  245. this._tokenizer.expect(':');
  246. current.body = this._suite();
  247. this._tokenizer.eat('\n');
  248. }
  249. if (this._tokenizer.eat('id', 'else')) {
  250. this._tokenizer.expect(':');
  251. current.orelse = this._suite();
  252. }
  253. return node;
  254. }
  255. node = this._eat('id', 'while');
  256. if (node) {
  257. node.test = this._expression();
  258. this._tokenizer.expect(':');
  259. node.body = this._suite();
  260. if (this._tokenizer.eat('id', 'else')) {
  261. this._tokenizer.expect(':');
  262. node.orelse = this._suite();
  263. }
  264. return node;
  265. }
  266. node = this._eat('id', 'pass');
  267. if (node) {
  268. return node;
  269. }
  270. node = this._eat('id', 'for');
  271. if (node) {
  272. node.target = [];
  273. node.target.push(this._expression(-1, ['in']));
  274. while (this._tokenizer.eat(',')) {
  275. if (this._tokenizer.match('id', 'in')) {
  276. node.target.push({});
  277. break;
  278. }
  279. node.target.push(this._expression(-1, ['in']));
  280. }
  281. this._tokenizer.expect('id', 'in');
  282. node.iter = [];
  283. node.iter.push(this._expression());
  284. while (this._tokenizer.eat(',')) {
  285. if (this._tokenizer.match(':')) {
  286. node.iter.push({});
  287. break;
  288. }
  289. node.iter.push(this._expression(-1, ['in']));
  290. }
  291. this._tokenizer.expect(':');
  292. node.body = this._suite();
  293. if (this._tokenizer.eat('id', 'else')) {
  294. this._tokenizer.expect(':');
  295. node.orelse = this._suite();
  296. }
  297. return node;
  298. }
  299. node = this._eat('id', 'with');
  300. if (node) {
  301. if (async) {
  302. node.async = async;
  303. }
  304. node.item = [];
  305. do {
  306. const item = this._node();
  307. item.type = 'with_item';
  308. item.expression = this._expression();
  309. if (this._tokenizer.eat('id', 'as')) {
  310. item.variable = this._expression();
  311. }
  312. node.item.push(item);
  313. }
  314. while (this._tokenizer.eat(','));
  315. this._tokenizer.expect(':');
  316. node.body = this._suite();
  317. return node;
  318. }
  319. node = this._eat('id', 'try');
  320. if (node) {
  321. this._tokenizer.expect(':');
  322. node.body = this._suite();
  323. node.except = [];
  324. while (this._tokenizer.match('id', 'except')) {
  325. const except = this._node('except');
  326. this._tokenizer.expect('id', 'except');
  327. except.clause = [];
  328. except.clause.push(this._expression());
  329. while (this._tokenizer.eat(',')) {
  330. if (this._tokenizer.match(':') || this._tokenizer.match('as')) {
  331. except.clause.push({});
  332. break;
  333. }
  334. except.clause.push(this._expression());
  335. }
  336. if (this._tokenizer.eat('id', 'as')) {
  337. except.variable = this._expression();
  338. }
  339. this._tokenizer.expect(':');
  340. except.body = this._suite();
  341. node.except.push(except);
  342. }
  343. if (this._tokenizer.match('id', 'else')) {
  344. node.orelse = this._node('else');
  345. this._tokenizer.expect('id', 'else');
  346. this._tokenizer.expect(':');
  347. node.orelse.body = this._suite();
  348. }
  349. if (this._tokenizer.match('id', 'finally')) {
  350. node.finally = this._node('finally');
  351. this._tokenizer.expect('id', 'finally');
  352. this._tokenizer.expect(':');
  353. node.finally.body = this._suite();
  354. }
  355. return node;
  356. }
  357. const expression = this._expression(-1, [], true);
  358. if (expression) {
  359. if (expression.type === 'id' && this._tokenizer.eat(':')) {
  360. node = this._node('var');
  361. node.name = expression.value;
  362. node.location = expression.location;
  363. node.variableType = this._expression(-1, ['=']);
  364. if (this._tokenizer.eat('=')) {
  365. node.initializer = this._expression();
  366. }
  367. return node;
  368. }
  369. switch (expression.type) {
  370. case '=':
  371. case ':=':
  372. case '==':
  373. case '!=':
  374. case '+=':
  375. case '-=':
  376. case '*=':
  377. case '@=':
  378. case '/=':
  379. case '//=':
  380. case '**=':
  381. case '&=':
  382. case '|=':
  383. case '%=':
  384. case '>>=':
  385. case '<<=':
  386. case '>>':
  387. case '<<':
  388. case '>=':
  389. case '<=':
  390. case '<':
  391. case '>':
  392. case '%':
  393. case '^=':
  394. case '...':
  395. case 'call':
  396. case 'assert':
  397. case 'raise':
  398. case 'string':
  399. case 'list':
  400. case 'var':
  401. case '.':
  402. case '[]':
  403. case 'yield':
  404. case '+':
  405. case '-':
  406. case '*':
  407. case '**':
  408. case '@':
  409. case '/':
  410. case '//':
  411. case '~':
  412. case '&':
  413. case '^':
  414. case '|':
  415. case 'not':
  416. case 'id':
  417. case 'number':
  418. case 'in':
  419. case 'and':
  420. case 'or':
  421. case 'if':
  422. case 'for':
  423. case 'tuple':
  424. case 'lambda':
  425. case 'await':
  426. return expression;
  427. default:
  428. throw new python.Error(`Unhandled expression ${this._tokenizer.location()}`);
  429. }
  430. }
  431. return null;
  432. }
  433. _expression(minPrecedence, terminal, tuple) {
  434. minPrecedence = minPrecedence || -1;
  435. const terminalSet = new Set(terminal);
  436. const stack = [];
  437. for (;;) {
  438. let node = this._node();
  439. const token = this._tokenizer.peek();
  440. if (stack.length === 1 && terminalSet.has(token.value)) {
  441. break;
  442. }
  443. const precedence = python.Parser._precedence[token.value];
  444. if (precedence) {
  445. if (precedence >= minPrecedence) {
  446. this._tokenizer.read();
  447. node.type = token.value;
  448. if (token.type === 'id' && (token.value === 'in' || token.value === 'not')) {
  449. if (token.value === 'in') {
  450. node.type = 'in';
  451. } else if (this._tokenizer.eat('id', 'in')) {
  452. node.type = 'not in';
  453. } else {
  454. node.type = 'not';
  455. node.expression = this._expression(precedence, terminal, tuple === false ? false : true);
  456. stack.push(node);
  457. continue;
  458. }
  459. } else if (token.value === '~') {
  460. node.type = '~';
  461. node.expression = this._expression(precedence, terminal, tuple === false ? false : true);
  462. stack.push(node);
  463. continue;
  464. } else if (token.type === 'id' && token.value === 'is') {
  465. if (this._tokenizer.eat('id', 'not')) {
  466. node.type = 'is not';
  467. }
  468. }
  469. if (stack.length > 0) {
  470. node.op = node.type;
  471. node.type = 'binary';
  472. node.left = stack.pop();
  473. node.right = this._expression(precedence, terminal, tuple === true ? true : false);
  474. } else {
  475. node.op = node.type;
  476. node.type = 'unary';
  477. node.operand = this._expression(precedence, terminal, tuple === true ? true : false);
  478. }
  479. stack.push(node);
  480. continue;
  481. }
  482. }
  483. if (this._tokenizer.eat(':=')) {
  484. node.type = ':=';
  485. node.target = stack.pop();
  486. node.expression = this._expression(-1, terminal, tuple === false ? false : true);
  487. stack.push(node);
  488. continue;
  489. }
  490. if (this._tokenizer.eat('=')) {
  491. node.type = '=';
  492. node.target = stack.pop();
  493. node.expression = this._expression(-1, terminal, tuple === false ? false : true);
  494. stack.push(node);
  495. continue;
  496. }
  497. switch (token.type) {
  498. case '-=':
  499. case '**=':
  500. case '*=':
  501. case '//=':
  502. case '/=':
  503. case '&=':
  504. case '%=':
  505. case '^=':
  506. case '+=':
  507. case '<<=':
  508. case '>>=':
  509. case '|=':
  510. case '@=':
  511. node = this._node(token.type);
  512. this._tokenizer.expect(token.type);
  513. node.target = stack.pop();
  514. node.expression = this._expression(-1, terminal, true);
  515. stack.push(node);
  516. continue;
  517. default:
  518. break;
  519. }
  520. node = this._eat('id', 'if');
  521. if (node) {
  522. node.body = stack.pop();
  523. node.test = this._expression();
  524. this._tokenizer.expect('id', 'else');
  525. node.orelse = this._expression();
  526. stack.push(node);
  527. continue;
  528. }
  529. while (this._tokenizer.match('id', 'for') || this._tokenizer.match('id', 'async')) {
  530. const async = this._eat('id', 'async');
  531. if (async && !this._tokenizer.match('id', 'for')) {
  532. throw new python.Error(`Expected 'for' ${this._tokenizer.location()}`);
  533. }
  534. node = this._eat('id', 'for');
  535. if (node) {
  536. if (async) {
  537. node.async = async;
  538. }
  539. node.expression = stack.pop();
  540. node.variable = this._expression(-1, ['in'], true);
  541. this._tokenizer.expect('id', 'in');
  542. node.target = this._expression(-1, ['for', 'if'], true);
  543. while (this._tokenizer.eat('id', 'if')) {
  544. node.test = node.test || [];
  545. node.test.push(this._expression(-1, ['for', 'if']));
  546. }
  547. stack.push(node);
  548. }
  549. }
  550. node = this._eat('id', 'lambda');
  551. if (node) {
  552. node.args = this._parameters(':');
  553. node.body = this._expression(-1, terminal, false);
  554. stack.push(node);
  555. continue;
  556. }
  557. node = this._eat('id', 'yield');
  558. if (node) {
  559. if (this._tokenizer.eat('id', 'from')) {
  560. node.from = this._expression(-1, [], true);
  561. } else {
  562. node.expression = [];
  563. do {
  564. node.expression.push(this._expression(-1, [], false));
  565. }
  566. while (this._tokenizer.eat(','));
  567. }
  568. stack.push(node);
  569. continue;
  570. }
  571. node = this._eat('id', 'await');
  572. if (node) {
  573. node.expression = this._expression(minPrecedence, terminal, tuple);
  574. stack.push(node);
  575. continue;
  576. }
  577. node = this._eat('.');
  578. if (node) {
  579. this._tokenizer.eat('\n');
  580. node.target = stack.pop();
  581. node.member = this._name();
  582. stack.push(node);
  583. continue;
  584. }
  585. if (this._tokenizer.peek().type === '(') {
  586. if (stack.length === 0) {
  587. node = this._node('tuple');
  588. const args = this._arguments();
  589. if (args.length === 1) {
  590. stack.push(args[0]);
  591. } else {
  592. node.value = args;
  593. stack.push(node);
  594. }
  595. } else {
  596. node = this._node('call');
  597. node.target = stack.pop();
  598. node.args = this._arguments();
  599. stack.push(node);
  600. }
  601. continue;
  602. }
  603. if (this._tokenizer.peek().type === '[') {
  604. if (stack.length === 0) {
  605. stack.push(this._expressions());
  606. } else {
  607. node = this._node('[]');
  608. node.target = stack.pop();
  609. node.arguments = this._slice();
  610. stack.push(node);
  611. }
  612. continue;
  613. }
  614. if (this._tokenizer.peek().type === '{') {
  615. stack.push(this._dictOrSetMaker());
  616. continue;
  617. }
  618. node = this._node();
  619. const literal = this._literal();
  620. if (literal) {
  621. if (stack.length > 0 && literal.type === 'number' &&
  622. (literal.value.startsWith('-') || literal.value.startsWith('+'))) {
  623. node.type = literal.value.substring(0, 1);
  624. literal.value = literal.value.substring(1);
  625. node.left = stack.pop();
  626. node.right = literal;
  627. stack.push(node);
  628. } else if (stack.length === 1 && literal.type === 'string' && stack[0].type === 'string') {
  629. stack[0].value += literal.value;
  630. } else {
  631. if (literal.type === 'number') {
  632. switch (literal.value) {
  633. case 'inf': literal.value = Infinity; break;
  634. case '-inf': literal.value = -Infinity; break;
  635. default: break;
  636. }
  637. }
  638. stack.push(literal);
  639. }
  640. continue;
  641. }
  642. if (this._tokenizer.peek().keyword) {
  643. break;
  644. }
  645. node = this._eat('...');
  646. if (node) {
  647. stack.push(node);
  648. continue;
  649. }
  650. const identifier = this._name();
  651. if (identifier) {
  652. stack.push(identifier);
  653. continue;
  654. }
  655. if (tuple === true && stack.length === 1 && this._tokenizer.eat(',')) {
  656. if (stack[0].type === 'tuple') {
  657. [node] = stack;
  658. } else {
  659. node = this._node('tuple');
  660. node.value = [stack.pop()];
  661. stack.push(node);
  662. }
  663. // for, bar, = <expr>
  664. if (this._tokenizer.peek().type === '=') {
  665. continue;
  666. }
  667. if (!this._tokenizer.match('=') && !terminalSet.has(this._tokenizer.peek().value)) {
  668. const nextTerminal = terminal.slice(0).concat([',', '=']);
  669. const expression = this._expression(minPrecedence, nextTerminal, tuple);
  670. if (expression) {
  671. node.value.push(expression);
  672. continue;
  673. }
  674. }
  675. break;
  676. }
  677. break;
  678. }
  679. if (stack.length === 1) {
  680. return stack.pop();
  681. }
  682. if (stack.length !== 0) {
  683. throw new python.Error(`Unexpected expression ${this._tokenizer.location()}`);
  684. }
  685. return null;
  686. }
  687. _decorator() {
  688. let list = null;
  689. while (this._tokenizer.eat('@')) {
  690. const node = this._node('decorator');
  691. node.value = this._expression();
  692. if (!node.value || (node.value.type !== 'call' && node.value.type !== 'id' && node.value.type !== '.')) {
  693. throw new python.Error(`Invalid decorator ${this._tokenizer.location()}`);
  694. }
  695. this._tokenizer.eat('\n');
  696. list = list === null ? [] : list;
  697. list.push(node);
  698. }
  699. return list;
  700. }
  701. _dictOrSetMaker() {
  702. const list = [];
  703. this._tokenizer.expect('{');
  704. let dict = true;
  705. while (!this._tokenizer.eat('}')) {
  706. const item = this._expression(-1, [], false);
  707. if (item === null) {
  708. throw new python.Error(`Expected expression ${this._tokenizer.location()}`);
  709. }
  710. if (!this._tokenizer.eat(':')) {
  711. dict = false;
  712. }
  713. if (dict) {
  714. const value = this._expression(-1, [], false);
  715. if (value === null) {
  716. throw new python.Error(`Expected expression ${this._tokenizer.location()}`);
  717. }
  718. list.push({ type: 'pair', key: item, value });
  719. } else {
  720. list.push(item);
  721. }
  722. this._tokenizer.eat(',');
  723. this._tokenizer.eat('\n');
  724. if (this._tokenizer.eat('}')) {
  725. break;
  726. }
  727. }
  728. if (dict) {
  729. return { type: 'dict', value: list };
  730. }
  731. return { type: 'set', value: list };
  732. }
  733. _expressions() {
  734. const list = [];
  735. this._tokenizer.expect('[');
  736. while (!this._tokenizer.eat(']')) {
  737. const expression = this._expression();
  738. if (expression === null) {
  739. throw new python.Error(`Expected expression ${this._tokenizer.location()}`);
  740. }
  741. list.push(expression);
  742. this._tokenizer.eat(',');
  743. while (this._tokenizer.eat('\n')) {
  744. // continue
  745. }
  746. if (this._tokenizer.eat(']')) {
  747. break;
  748. }
  749. }
  750. return { type: 'list', value: list };
  751. }
  752. _slice() {
  753. let node = { type: '::' };
  754. let list = [];
  755. const group = ['start', 'stop', 'step'];
  756. this._tokenizer.expect('[');
  757. while (!this._tokenizer.eat(']')) {
  758. if (this._tokenizer.eat(':')) {
  759. node[group.shift()] = { type: 'list', value: list };
  760. list = [];
  761. continue;
  762. }
  763. if (this._tokenizer.eat(',')) {
  764. // list.push({});
  765. continue;
  766. }
  767. if (this._tokenizer.peek().type !== ']') {
  768. const expression = this._expression();
  769. if (expression === null) {
  770. throw new python.Error(`Expected expression ${this._tokenizer.location()}`);
  771. }
  772. list.push(expression);
  773. }
  774. }
  775. if (list.length > 0) {
  776. node[group.shift()] = { type: 'list', value: list };
  777. }
  778. if (node.start && !node.stop && !node.step) {
  779. node = node.start;
  780. }
  781. return node;
  782. }
  783. _name(required) {
  784. const token = this._tokenizer.peek();
  785. if (token.type === 'id' && !token.keyword) {
  786. this._tokenizer.read();
  787. return token;
  788. }
  789. if (required) {
  790. throw new python.Error(`Invalid syntax ${this._tokenizer.location()}`);
  791. }
  792. return null;
  793. }
  794. _dottedName() {
  795. const list = [];
  796. do {
  797. list.push(this._name(true).value);
  798. }
  799. while (this._tokenizer.eat('.'));
  800. return list.join('.');
  801. }
  802. _literal() {
  803. const token = this._tokenizer.peek();
  804. if (token.type === 'string' || token.type === 'number' || token.type === 'boolean') {
  805. this._tokenizer.read();
  806. return token;
  807. }
  808. return null;
  809. }
  810. _typeArguments() {
  811. const list = [];
  812. this._tokenizer.expect('[');
  813. while (!this._tokenizer.eat(']')) {
  814. const type = this._type();
  815. if (type === null) {
  816. throw new python.Error(`Expected type ${this._tokenizer.location()}`);
  817. }
  818. list.push(type);
  819. if (!this._tokenizer.eat(',')) {
  820. this._tokenizer.expect(']');
  821. break;
  822. }
  823. }
  824. return list;
  825. }
  826. _type() {
  827. const target = this._expression(-1, ['[', '=']);
  828. if (target) {
  829. if (this._tokenizer.peek().value === '[') {
  830. const type = this._node();
  831. type.type = '[]';
  832. type.target = target;
  833. type.arguments = this._expressions();
  834. // type.arguments = this._typeArguments();
  835. return type;
  836. }
  837. return target;
  838. }
  839. return null;
  840. }
  841. _parameter(terminal) {
  842. const node = this._node('parameter');
  843. if (this._tokenizer.eat('/')) {
  844. node.name = '/';
  845. return node;
  846. }
  847. if (this._tokenizer.eat('**')) {
  848. node.parameterType = '**';
  849. }
  850. if (this._tokenizer.eat('*')) {
  851. node.parameterType = '*';
  852. }
  853. const identifier = this._name();
  854. if (identifier !== null) {
  855. node.name = identifier.value;
  856. if (terminal !== ':' && this._tokenizer.eat(':')) {
  857. node.parameterType = this._type();
  858. }
  859. if (this._tokenizer.eat('=')) {
  860. node.initializer = this._expression();
  861. }
  862. return node;
  863. }
  864. return null;
  865. }
  866. _parameters(terminal) {
  867. const list = [];
  868. while (!this._tokenizer.eat(terminal)) {
  869. this._tokenizer.eat('\n');
  870. if (this._tokenizer.eat('(')) {
  871. list.push(this._parameters(')'));
  872. } else {
  873. list.push(this._parameter(terminal));
  874. }
  875. this._tokenizer.eat('\n');
  876. if (!this._tokenizer.eat(',')) {
  877. this._tokenizer.expect(terminal);
  878. break;
  879. }
  880. }
  881. return list;
  882. }
  883. _arguments() {
  884. const list = [];
  885. this._tokenizer.expect('(');
  886. while (!this._tokenizer.eat(')')) {
  887. if (this._tokenizer.eat('\n')) {
  888. continue;
  889. }
  890. const expression = this._expression(-1, [], false);
  891. if (expression === null) {
  892. throw new python.Error(`Expected expression ${this._tokenizer.location()}`);
  893. }
  894. list.push(expression);
  895. if (!this._tokenizer.eat(',')) {
  896. this._tokenizer.eat('\n');
  897. this._tokenizer.expect(')');
  898. break;
  899. }
  900. }
  901. return list;
  902. }
  903. _node(type) {
  904. const node = {};
  905. node.location = this._tokenizer.location();
  906. if (type) {
  907. node.type = type;
  908. }
  909. return node;
  910. }
  911. _eat(type, value) {
  912. if (this._tokenizer.match(type, value)) {
  913. const node = this._node(type === 'id' ? value : type);
  914. this._tokenizer.expect(type, value);
  915. return node;
  916. }
  917. return null;
  918. }
  919. };
  920. python.Tokenizer = class {
  921. constructor(text, file) {
  922. this._text = text;
  923. this._file = file;
  924. this._position = 0;
  925. this._lineStart = 0;
  926. this._line = 0;
  927. this._token = { type: '', value: '' };
  928. this._brackets = 0;
  929. this._indentation = [];
  930. this._outdent = 0;
  931. if (!python.Tokenizer._whitespace) {
  932. python.Tokenizer._whitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  933. 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';
  934. 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';
  935. python.Tokenizer._identifierStart = new RegExp(`[${identifierStartChars}]`);
  936. /* eslint-disable no-misleading-character-class */
  937. python.Tokenizer._identifierChar = new RegExp(`[${identifierStartChars}${identifierChars}]`);
  938. /* eslint-enable no-misleading-character-class */
  939. }
  940. }
  941. peek() {
  942. if (!this._cache) {
  943. this._tokenize();
  944. this._cache = true;
  945. }
  946. return this._token;
  947. }
  948. read() {
  949. if (!this._cache) {
  950. this._tokenize();
  951. }
  952. const next = this._position + this._token.value.length;
  953. while (this._position < next) {
  954. if (python.Tokenizer._isNewline(this._get(this._position))) {
  955. this._position = this._newLine(this._position);
  956. this._lineStart = this._position;
  957. this._line++;
  958. } else {
  959. this._position++;
  960. }
  961. }
  962. this._cache = false;
  963. return this._token;
  964. }
  965. match(type, value) {
  966. const token = this.peek();
  967. if (token.type === type && (!value || token.value === value)) {
  968. return true;
  969. }
  970. return false;
  971. }
  972. eat(type, value) {
  973. const token = this.peek();
  974. if (token.type === type && (!value || token.value === value)) {
  975. this.read();
  976. return true;
  977. }
  978. return false;
  979. }
  980. expect(type, value) {
  981. const token = this.peek();
  982. if (token.type !== type) {
  983. throw new python.Error(`Unexpected '${token.value}' instead of '${type}' ${this.location()}`);
  984. }
  985. if (value && token.value !== value) {
  986. throw new python.Error(`Unexpected '${token.value}' instead of '${value}' ${this.location()}`);
  987. }
  988. this.read();
  989. }
  990. location() {
  991. const line = this._line + 1;
  992. const column = this._position - this._lineStart + 1;
  993. return `at ${this._file}:${line}:${column}.`;
  994. }
  995. static _isSpace(c) {
  996. switch (c) {
  997. case ' ':
  998. case '\t':
  999. case '\v': // 11
  1000. case '\f': // 12
  1001. case '\xA0': // 160
  1002. return true;
  1003. default:
  1004. if (c.charCodeAt(0) >= 0x1680) {
  1005. return python.Tokenizer._whitespace.test(c);
  1006. }
  1007. return false;
  1008. }
  1009. }
  1010. static _isNewline(c) {
  1011. switch (c) {
  1012. case '\n':
  1013. case '\r':
  1014. case '\u2028': // 8232
  1015. case '\u2029': // 8233
  1016. return true;
  1017. default:
  1018. return false;
  1019. }
  1020. }
  1021. static _isIdentifierStartChar(c) {
  1022. if (c < 'A') {
  1023. return c === '$';
  1024. }
  1025. if (c <= 'Z') {
  1026. return true;
  1027. }
  1028. if (c < 'a') {
  1029. return c === '_';
  1030. }
  1031. if (c <= 'z') {
  1032. return true;
  1033. }
  1034. const code = c.charCodeAt(0);
  1035. if (code >= 0xAA) {
  1036. return python.Tokenizer._identifierStart.test(c);
  1037. }
  1038. return false;
  1039. }
  1040. static _isIdentifierChar(c) {
  1041. if (c < '0') {
  1042. return c === '$';
  1043. }
  1044. if (c <= '9') {
  1045. return true;
  1046. }
  1047. if (c < 'A') {
  1048. return false;
  1049. }
  1050. if (c <= 'Z') {
  1051. return true;
  1052. }
  1053. if (c < 'a') {
  1054. return c === '_';
  1055. }
  1056. if (c <= 'z') {
  1057. return true;
  1058. }
  1059. const code = c.charCodeAt(0);
  1060. if (code >= 0xAA) {
  1061. return python.Tokenizer._identifierChar.test(c);
  1062. }
  1063. return false;
  1064. }
  1065. _get(position) {
  1066. return position >= this._text.length ? '\0' : this._text[position];
  1067. }
  1068. _skipLine() {
  1069. while (this._position < this._text.length) {
  1070. if (python.Tokenizer._isNewline(this._get(this._position))) {
  1071. break;
  1072. }
  1073. this._position++;
  1074. }
  1075. }
  1076. _skipWhitespace() {
  1077. while (this._position < this._text.length) {
  1078. const c = this._text[this._position];
  1079. if (c === '#') {
  1080. this._skipLine();
  1081. } else if (python.Tokenizer._isSpace(c)) {
  1082. this._position++;
  1083. } else if (c === '\\') {
  1084. // Explicit Line Continuation
  1085. this._position++;
  1086. if (python.Tokenizer._isNewline(this._get(this._position))) {
  1087. this._position = this._newLine(this._position);
  1088. this._lineStart = this._position;
  1089. this._line++;
  1090. } else {
  1091. throw new python.Error(`Unexpected '${this._text[this._position]}' after line continuation ${this.location()}`);
  1092. }
  1093. } else if (this._brackets > 0 && python.Tokenizer._isNewline(c)) {
  1094. // Implicit Line Continuation
  1095. this._position = this._newLine(this._position);
  1096. this._lineStart = this._position;
  1097. this._line++;
  1098. } else {
  1099. break;
  1100. }
  1101. }
  1102. }
  1103. _newLine(position) {
  1104. if ((this._get(position) === '\n' && this._get(position + 1) === '\r') ||
  1105. (this._get(position) === '\r' && this._get(position + 1) === '\n')) {
  1106. return position + 2;
  1107. }
  1108. return position + 1;
  1109. }
  1110. _tokenize() {
  1111. if (this._token.type !== '\n') {
  1112. this._skipWhitespace();
  1113. }
  1114. if (this._token.type === 'dedent') {
  1115. this._indentation.pop();
  1116. this._outdent--;
  1117. if (this._outdent > 0) {
  1118. this._token = { type: 'dedent', value: '' };
  1119. return;
  1120. }
  1121. }
  1122. if (this._token.type === '\n') {
  1123. let indent = '';
  1124. let i = this._position;
  1125. while (i < this._text.length) {
  1126. const c = this._text[i];
  1127. if (python.Tokenizer._isSpace(c)) {
  1128. indent += c;
  1129. i++;
  1130. } else if (python.Tokenizer._isNewline(c)) {
  1131. indent = '';
  1132. i = this._newLine(i);
  1133. this._position = i;
  1134. this._lineStart = i;
  1135. this._line++;
  1136. } else if (c === '#') {
  1137. indent = '';
  1138. while (i < this._text.length && !python.Tokenizer._isNewline(this._text[i])) {
  1139. i++;
  1140. }
  1141. continue;
  1142. } else {
  1143. break;
  1144. }
  1145. }
  1146. let type = null;
  1147. if (indent.length > 0) {
  1148. const current = this._indentation.length > 0 ? this._indentation[this._indentation.length - 1] : '';
  1149. if (indent.length > current.length) {
  1150. type = 'indent';
  1151. this._indentation.push(indent);
  1152. } else if (indent.length > 0 && indent.length < current.length) {
  1153. type = 'dedent';
  1154. this._outdent = 0;
  1155. for (let j = this._indentation.length - 1; j >= 0 && indent.length < this._indentation[j].length; j--) {
  1156. this._outdent++;
  1157. }
  1158. } else {
  1159. this._position += indent.length;
  1160. }
  1161. } else if (i >= this._text.length) {
  1162. this._token = { type: 'eof', value: '' };
  1163. return;
  1164. } else if (this._indentation.length > 0) {
  1165. type = 'dedent';
  1166. this._outdent = this._indentation.length;
  1167. }
  1168. if (type === 'indent' || type === 'dedent') {
  1169. this._token = { type, value: indent };
  1170. return;
  1171. }
  1172. }
  1173. if (this._position >= this._text.length) {
  1174. this._token = { type: 'eof', value: '' };
  1175. return;
  1176. }
  1177. const c = this._get(this._position);
  1178. const string = this._string();
  1179. if (string) {
  1180. this._token = string;
  1181. return;
  1182. }
  1183. switch (c) {
  1184. case '(':
  1185. case '[':
  1186. case '{':
  1187. this._brackets++;
  1188. this._token = { type: c, value: c };
  1189. return;
  1190. case ')':
  1191. case ']':
  1192. case '}':
  1193. if (this._brackets === 0) {
  1194. throw new python.Error(`Unexpected '${c}' ${this.location}`);
  1195. }
  1196. this._brackets--;
  1197. this._token = { type: c, value: c };
  1198. return;
  1199. case ',':
  1200. case ';':
  1201. case '?':
  1202. this._token = { type: c, value: c };
  1203. return;
  1204. default: {
  1205. const number = this._number();
  1206. if (number) {
  1207. this._token = number;
  1208. return;
  1209. }
  1210. if (c === '.') {
  1211. let end = this._position + 1;
  1212. while (this._get(end) === '.') {
  1213. end++;
  1214. }
  1215. const text = this._text.substring(this._position, end);
  1216. this._token = { type: text, value: text };
  1217. return;
  1218. }
  1219. const identifier = this._identifier();
  1220. if (identifier) {
  1221. this._token = identifier;
  1222. return;
  1223. }
  1224. const operator = this._operator();
  1225. if (operator) {
  1226. this._token = operator;
  1227. return;
  1228. }
  1229. break;
  1230. }
  1231. }
  1232. if (c === '.') {
  1233. this._token = { type: c, value: c };
  1234. return;
  1235. }
  1236. if (c === '\\') {
  1237. this._token = { type: '\\', value: c };
  1238. return;
  1239. }
  1240. if (python.Tokenizer._isNewline(c)) {
  1241. this._token = { type: '\n', value: this._text.substring(this._position, this._newLine(this._position)) };
  1242. return;
  1243. }
  1244. throw new python.Error(`Unexpected token '${c}' ${this.location()}`);
  1245. }
  1246. _number() {
  1247. const octal = (c) => c >= '0' && c <= '7' || c === '_';
  1248. const binary = (c) => c === '0' || c === '1' || c === '_';
  1249. const decimal = (c) => c >= '0' && c <= '9' || c === '_';
  1250. const hex = (c) => decimal(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') || c === '_';
  1251. let c = this._get(this._position);
  1252. const sign = (c === '-' || c === '+') ? 1 : 0;
  1253. let i = this._position + sign;
  1254. c = this._get(i);
  1255. if (c === '0') {
  1256. let radix = 0;
  1257. const n = this._get(i + 1);
  1258. if ((n === 'x' || n === 'X') && hex(this._get(i + 2))) {
  1259. i += 2;
  1260. while (hex(this._get(i))) {
  1261. i += 1;
  1262. }
  1263. if (this._get(i) === 'l' || this._get(i) === 'L') {
  1264. i += 1;
  1265. }
  1266. radix = 16;
  1267. } else if ((n === 'b' || n === 'B') && binary(this._get(i + 2))) {
  1268. i += 2;
  1269. while (binary(this._get(i))) {
  1270. i++;
  1271. }
  1272. radix = 2;
  1273. } else if ((n === 'o' || n === 'O') && octal(this._get(i + 2))) {
  1274. i += 2;
  1275. while (octal(this._get(i))) {
  1276. i++;
  1277. }
  1278. radix = 8;
  1279. } else if (n >= '0' && n <= '7') {
  1280. i++;
  1281. while (octal(this._get(i))) {
  1282. i += 1;
  1283. }
  1284. if (this._get(i) === 'l' || this._get(i) === 'L') {
  1285. i += 1;
  1286. }
  1287. radix = 8;
  1288. }
  1289. if (radix > 0 && this._get(i) !== '.') {
  1290. const radixText = this._text.substring(this._position, i);
  1291. const radixParseText = radixText.indexOf('_') === -1 ? radixText : radixText.split('_').join('');
  1292. if (!isNaN(parseInt(radixParseText, radix))) {
  1293. return { type: 'number', value: radixText };
  1294. }
  1295. }
  1296. }
  1297. i = this._position + sign;
  1298. let isDecimal = false;
  1299. if (this._get(i) >= '1' && this._get(i) <= '9') {
  1300. while (decimal(this._get(i))) {
  1301. i++;
  1302. }
  1303. c = this._get(i).toLowerCase();
  1304. isDecimal = c !== '.' && c !== 'e';
  1305. }
  1306. if (this._get(i) === '0') {
  1307. i++;
  1308. c = this._get(i).toLowerCase();
  1309. isDecimal = !decimal(c) && c !== '.' && c !== 'e' && c !== 'j';
  1310. }
  1311. if (isDecimal) {
  1312. if (this._get(i) === 'j' || this._get(i) === 'J' || this._get(i) === 'l' || this._get(i) === 'L') {
  1313. return { 'type': 'number', value: this._text.substring(this._position, i + 1) };
  1314. }
  1315. const intText = this._text.substring(this._position, i);
  1316. if (!isNaN(parseInt(intText, 10))) {
  1317. return { type: 'number', value: intText };
  1318. }
  1319. }
  1320. i = this._position + sign;
  1321. if ((this._get(i) >= '0' && this._get(i) <= '9') ||
  1322. (this._get(i) === '.' && this._get(i + 1) >= '0' && this._get(i + 1) <= '9')) {
  1323. while (decimal(this._get(i))) {
  1324. i++;
  1325. }
  1326. if (this._get(i) === '.') {
  1327. i++;
  1328. }
  1329. while (decimal(this._get(i))) {
  1330. i++;
  1331. }
  1332. if (i > (this._position + sign)) {
  1333. if (this._get(i) === 'e' || this._get(i) === 'E') {
  1334. i++;
  1335. if (this._get(i) === '-' || this._get(i) === '+') {
  1336. i++;
  1337. }
  1338. if (decimal(this._get(i))) {
  1339. while (decimal(this._get(i))) {
  1340. i++;
  1341. }
  1342. } else {
  1343. i = this._position;
  1344. }
  1345. } else {
  1346. while (decimal(this._get(i))) {
  1347. i++;
  1348. }
  1349. }
  1350. }
  1351. if (i > (this._position + sign)) {
  1352. if (this._get(i) === 'j' || this._get(i) === 'J') {
  1353. return { type: 'number', value: this._text.substring(this._position, i + 1) };
  1354. }
  1355. const floatText = this._text.substring(this._position, i);
  1356. const floatParseText = floatText.indexOf('_') === -1 ? floatText : floatText.split('_').join('');
  1357. if (!isNaN(parseFloat(floatParseText))) {
  1358. return { type: 'number', value: floatText };
  1359. }
  1360. }
  1361. }
  1362. return null;
  1363. }
  1364. _identifier() {
  1365. let i = this._position;
  1366. if (python.Tokenizer._isIdentifierStartChar(this._get(i))) {
  1367. i++;
  1368. while (python.Tokenizer._isIdentifierChar(this._get(i))) {
  1369. i++;
  1370. }
  1371. }
  1372. if (i > this._position) {
  1373. const text = this._text.substring(this._position, i);
  1374. let keyword = false;
  1375. switch (text) {
  1376. case 'and':
  1377. case 'as':
  1378. case 'else':
  1379. case 'for':
  1380. case 'if':
  1381. case 'import':
  1382. case 'in':
  1383. case 'is':
  1384. case 'not':
  1385. case 'or':
  1386. keyword = true;
  1387. break;
  1388. default:
  1389. keyword = false;
  1390. break;
  1391. }
  1392. return { type: 'id', value: text, keyword };
  1393. }
  1394. return null;
  1395. }
  1396. _operator() {
  1397. let length = 0;
  1398. const c0 = this._get(this._position);
  1399. const c1 = this._get(this._position + 1);
  1400. const c2 = this._get(this._position + 2);
  1401. switch (c0) {
  1402. case '+':
  1403. case '&':
  1404. case '|':
  1405. case '^':
  1406. case '=':
  1407. case '!':
  1408. case '%':
  1409. case '~':
  1410. length = c1 === '=' ? 2 : 1;
  1411. break;
  1412. case '-':
  1413. length = c1 === '=' || c1 === '>' ? 2 : 1;
  1414. break;
  1415. case '*':
  1416. switch (c1) {
  1417. case '*': length = c2 === '=' ? 3 : 2; break;
  1418. case '=': length = 2; break;
  1419. default: length = 1; break;
  1420. }
  1421. break;
  1422. case '/':
  1423. switch (c1) {
  1424. case '/': length = c2 === '=' ? 3 : 2; break;
  1425. case '=': length = 2; break;
  1426. default: length = 1; break;
  1427. }
  1428. break;
  1429. case '<':
  1430. switch (c1) {
  1431. case '>': length = 2; break;
  1432. case '<': length = c2 === '=' ? 3 : 2; break;
  1433. case '=': length = 2; break;
  1434. default: length = 1; break;
  1435. }
  1436. break;
  1437. case '>':
  1438. switch (c1) {
  1439. case '>': length = c2 === '=' ? 3 : 2; break;
  1440. case '=': length = 2; break;
  1441. default: length = 1; break;
  1442. }
  1443. break;
  1444. case '@':
  1445. length = c1 === '=' ? 2 : 1;
  1446. break;
  1447. case ':':
  1448. length = c1 === '=' ? 2 : 1;
  1449. break;
  1450. default:
  1451. return null;
  1452. }
  1453. const text = this._text.substring(this._position, this._position + length);
  1454. return { type: text, value: text };
  1455. }
  1456. _string() {
  1457. let i = this._position;
  1458. let prefix = -1;
  1459. if (this._get(i) === "'" || this._get(i) === '"') {
  1460. prefix = '';
  1461. } else if (this._get(i + 1) === "'" || this._get(i + 1) === '"') {
  1462. const c = this._get(i);
  1463. switch (c.toLowerCase()) {
  1464. case 'b':
  1465. case 'f':
  1466. case 'r':
  1467. case 'u':
  1468. prefix = c;
  1469. break;
  1470. default:
  1471. break;
  1472. }
  1473. } else if (this._get(i + 2) === "'" || this._get(i + 2) === '"') {
  1474. const cc = this._text.substr(this._position, 2);
  1475. switch (cc.toLowerCase()) {
  1476. case 'br':
  1477. case 'fr':
  1478. case 'rb':
  1479. case 'rf':
  1480. case 'ur':
  1481. prefix = cc;
  1482. break;
  1483. default:
  1484. break;
  1485. }
  1486. }
  1487. if (prefix.length >= 0) {
  1488. i += prefix.length;
  1489. let quote = '';
  1490. let count = 0;
  1491. const q0 = this._get(i);
  1492. const q1 = this._get(i + 1);
  1493. const q2 = this._get(i + 2);
  1494. switch (q0) {
  1495. case "'":
  1496. quote = q0;
  1497. count = (q1 === "'" && q2 === "'") ? 3 : 1;
  1498. break;
  1499. case '"':
  1500. quote = q0;
  1501. count = (q1 === '"' && q2 === '"') ? 3 : 1;
  1502. break;
  1503. default:
  1504. throw new python.Error(`Unsupported string quote '${q0}'.`);
  1505. }
  1506. i += count;
  1507. if (count === 1) {
  1508. while (i < this._text.length) {
  1509. if (this._text[i] === quote) {
  1510. return { type: 'string', value: this._text.substring(this._position, i + 1) };
  1511. } else if (this._text[i] === '\\' &&
  1512. (this._get(i + 1) === quote || this._get(i + 1) === '\n' || this._get(i + 1) === '\\')) {
  1513. i += 2;
  1514. } else if (this._text[i] === '\r' || this._text[i] === '\n') {
  1515. break;
  1516. } else {
  1517. i++;
  1518. }
  1519. }
  1520. } else if (count === 3) {
  1521. while (i < this._text.length) {
  1522. if (this._get(i) === quote && this._get(i + 1) === quote && this._get(i + 2) === quote) {
  1523. return { type: 'string', value: this._text.substring(this._position, i + 3) };
  1524. } else if (this._get(i) === '\\' && this._get(i + 1) === quote) {
  1525. i += 2;
  1526. continue;
  1527. }
  1528. i++;
  1529. }
  1530. }
  1531. }
  1532. i = this._position;
  1533. if (this._get(i) === '`') {
  1534. i++;
  1535. while (i < this._text.length) {
  1536. if (this._text[i] === '`') {
  1537. return { type: 'string', value: this._text.substring(this._position, i + 1) };
  1538. }
  1539. i++;
  1540. }
  1541. }
  1542. return null;
  1543. }
  1544. };
  1545. python.Execution = class {
  1546. constructor(sources) {
  1547. const self = this;
  1548. const execution = self;
  1549. this._sources = sources || new Map();
  1550. this._events = new Map();
  1551. this._utf8Decoder = new TextDecoder('utf-8');
  1552. this._unresolved = new Map();
  1553. const dict = class extends Map {
  1554. constructor(items) {
  1555. super();
  1556. if (items) {
  1557. for (const [name, value] of items) {
  1558. this.__setitem__(name, value);
  1559. }
  1560. }
  1561. }
  1562. __contains__(key) {
  1563. return this.has(key);
  1564. }
  1565. __setitem__(key, value) {
  1566. this.set(key, value);
  1567. }
  1568. __getitem__(key) {
  1569. return this.get(key);
  1570. }
  1571. get(key, defaultValue) {
  1572. return super.get(key) || defaultValue;
  1573. }
  1574. setdefault(key, defaultValue) {
  1575. if (this.has(key)) {
  1576. return this.get(key);
  1577. }
  1578. const value = defaultValue || null;
  1579. this.set(key, value);
  1580. return value;
  1581. }
  1582. update(other) {
  1583. for (const [key, value] of other) {
  1584. this.set(key, value);
  1585. }
  1586. }
  1587. };
  1588. this._modules = new dict();
  1589. this._registry = new Map();
  1590. const module = class {
  1591. constructor(name) {
  1592. this.__name__ = name;
  1593. }
  1594. };
  1595. const builtins = this.register('builtins', new module('builtins'));
  1596. this._builtins = builtins;
  1597. this._registry.set('__builtin__', builtins);
  1598. this.registerType('builtins.type', class {}).__class__ = builtins.type;
  1599. this.registerType('builtins.module', module);
  1600. this.registerType('builtins.method', class {});
  1601. this.registerType('builtins.function', class {});
  1602. this.registerType('builtins.code', class {});
  1603. this.import('builtins');
  1604. this.registerType('builtins.builtin_function_or_method', class {});
  1605. const typing = this.register('typing');
  1606. this._typing = typing;
  1607. const operator = this.register('operator');
  1608. this.register('_codecs');
  1609. this.register('argparse');
  1610. this._enum = this.register('enum');
  1611. this.register('collections');
  1612. this.register('copy_reg');
  1613. this.register('cuml');
  1614. const datetime = this.register('datetime');
  1615. this.register('gensim');
  1616. this.register('io');
  1617. const joblib = this.register('joblib');
  1618. const jax = this.register('jax');
  1619. this.register('jax.numpy');
  1620. this.register('jax._src.array');
  1621. this.register('jax._src.device_array');
  1622. const functools = this.register('functools');
  1623. this.registerType('functools.partial', class {});
  1624. const keras = this.register('keras');
  1625. const catboost = this.register('catboost');
  1626. this.register('lightgbm');
  1627. this.register('nolearn');
  1628. const fastcore = this.register('fastcore');
  1629. const fastai = this.register('fastai');
  1630. const math = this.register('math');
  1631. math.inf = Infinity;
  1632. const numpy = this.register('numpy');
  1633. this.register('numpy.core.multiarray');
  1634. this.register('numpy.core._multiarray_umath');
  1635. this.register('numpy.matrixlib.defmatrix');
  1636. const pandas = this.register('pandas');
  1637. this.register('pandas._libs.tslib');
  1638. this.register('pandas._libs.internals');
  1639. const pickle = this.register('pickle');
  1640. const shap = this.register('shap');
  1641. this.register('shap.explainers.linear');
  1642. const sklearn = this.register('sklearn');
  1643. this.register('sklearn.externals.joblib.numpy_pickle');
  1644. const torch = this.register('torch');
  1645. const torchvision = this.register('torchvision');
  1646. this.register('torch.storage');
  1647. this.register('torch.nn.parameter');
  1648. this.register('torch.ops');
  1649. this.register('torch._ops');
  1650. this.register('torch.ops.torchvision');
  1651. this.register('torch.ops.torchaudio');
  1652. this.register('torch.ops._caffe2');
  1653. this.register('torchvision');
  1654. this.register('__torch__');
  1655. this.register('sys').modules = this._modules;
  1656. this.register('xgboost');
  1657. this.registerType('builtins.dict', dict);
  1658. this.registerType('builtins.ellipsis', class {});
  1659. this.registerType('builtins.cell', class {});
  1660. this.registerType('builtins.list', class extends Array {});
  1661. this.registerType('builtins.number', class {});
  1662. this.registerFunction('builtins.__import__', (name, globals, locals, fromlist, level) => {
  1663. return execution.__import__(name, globals, locals, fromlist, level);
  1664. });
  1665. this.registerType('builtins.bool', class extends Boolean {
  1666. constructor(value) {
  1667. if (value && value.__bool__) {
  1668. value = value.__bool__();
  1669. } else if (value && value.__len__) {
  1670. value = value.__len__() > 0;
  1671. } else {
  1672. value = value ? true : false;
  1673. }
  1674. super(value);
  1675. }
  1676. });
  1677. this.registerType('builtins.int', class extends Number {
  1678. constructor(value) {
  1679. if (value && value.__int__) {
  1680. value = value.__int__();
  1681. } else if (!Number.isInteger(value)) {
  1682. value = NaN;
  1683. }
  1684. super(value);
  1685. }
  1686. });
  1687. this.registerType('builtins.float', class extends Number {
  1688. constructor(value) {
  1689. if (value && value.__float__) {
  1690. value = value.__float__();
  1691. } else if (Number(value) !== value) {
  1692. value = NaN;
  1693. }
  1694. super(value);
  1695. }
  1696. });
  1697. this.registerType('builtins.long', class extends Number {
  1698. constructor(value) {
  1699. if (value && value.__int__) {
  1700. value = value.__int__();
  1701. } else if (!Number.isInteger(value)) {
  1702. value = NaN;
  1703. }
  1704. super(value);
  1705. }
  1706. });
  1707. this.registerType('builtins.str', class extends String {
  1708. constructor(value) {
  1709. if (value && value.__str__) {
  1710. value = value.__str__();
  1711. } else if (typeof value !== 'string') {
  1712. value = JSON.stringify(value);
  1713. }
  1714. super(value);
  1715. }
  1716. });
  1717. this.registerType('builtins.complex', class {
  1718. constructor(real, imaginary) {
  1719. this.real = real;
  1720. this.imag = imaginary;
  1721. }
  1722. });
  1723. this.registerType('builtins.NoneType', class {});
  1724. this.registerType('builtins.object', class {
  1725. static __new__(cls, ...args) {
  1726. return execution.invoke(cls, args);
  1727. }
  1728. });
  1729. this.registerType('builtins.tuple', class extends Array {
  1730. constructor(items) {
  1731. super(items ? items.length : 0);
  1732. if (items) {
  1733. for (let i = 0; i < items.length; i++) {
  1734. this[i] = items[i];
  1735. }
  1736. }
  1737. }
  1738. });
  1739. this.registerType('builtins.staticmethod', class {});
  1740. this.registerType('builtins.Warning', class {});
  1741. this.registerType('builtins.FutureWarning', class extends builtins.Warning {});
  1742. this.registerType('builtins.BaseException', class {});
  1743. this.registerType('builtins.Exception', class extends builtins.BaseException {});
  1744. this.registerType('builtins.AttributeError', class extends builtins.Exception {});
  1745. this.registerType('builtins.SyntaxError', class extends builtins.Exception {});
  1746. this.registerFunction('builtins.print', () => {});
  1747. this.registerFunction('builtins.unicode');
  1748. builtins.Ellipsis = new builtins.ellipsis();
  1749. this.registerType('typing._Final', class {});
  1750. this.registerType('typing._SpecialForm', class extends typing._Final {});
  1751. this.registerType('typing._BaseGenericAlias', class extends typing._Final {});
  1752. this.registerType('typing._GenericAlias', class extends typing._BaseGenericAlias {});
  1753. this.registerType('typing._SpecialGenericAlias', class extends typing._BaseGenericAlias {});
  1754. this.registerType('typing._TupleType', class extends typing._SpecialGenericAlias {});
  1755. this.registerType('typing._CallableType', class {});
  1756. this.registerFunction('typing.cast');
  1757. typing.Any = Reflect.construct(typing._SpecialForm, []);
  1758. typing.Callable = Reflect.construct(typing._CallableType, []);
  1759. typing.Dict = Reflect.construct(typing._SpecialGenericAlias, []);
  1760. typing.List = Reflect.construct(typing._SpecialGenericAlias, []);
  1761. typing.Optional = Reflect.construct(typing._SpecialForm, []);
  1762. typing.OrderedDict = Reflect.construct(typing._SpecialGenericAlias, []);
  1763. typing.Sequence = Reflect.construct(typing._SpecialGenericAlias, []);
  1764. typing.Tuple = Reflect.construct(typing._TupleType, []);
  1765. typing.Union = Reflect.construct(typing._SpecialForm, []);
  1766. this.registerType('enum.Enum', class {});
  1767. this.registerFunction('operator.add');
  1768. this.registerFunction('operator.eq');
  1769. this.registerFunction('operator.ge');
  1770. this.registerFunction('operator.getitem');
  1771. this.registerFunction('operator.gt');
  1772. this.registerFunction('operator.mul');
  1773. this.registerFunction('operator.mod');
  1774. this.registerFunction('operator.le');
  1775. this.registerFunction('operator.lt');
  1776. this.registerFunction('operator.ne');
  1777. this.registerFunction('operator.floordiv');
  1778. this.registerFunction('operator.sub');
  1779. this.registerFunction('sys.path.append', () => {});
  1780. this.registerFunction('sys.path.insert', () => {});
  1781. this.registerType('argparse.Namespace', class {
  1782. constructor(args) {
  1783. this.args = args;
  1784. }
  1785. });
  1786. this.registerType('catboost._catboost._CatBoost', class {
  1787. _deserialize_model(/* serialized_model_str */) {
  1788. }
  1789. });
  1790. this.registerType('catboost.core._CatBoostBase', class {
  1791. constructor() {
  1792. this._object = new catboost._catboost._CatBoost();
  1793. }
  1794. __setstate__(state) {
  1795. for (const [key, value] of state) {
  1796. if (key === '__model') {
  1797. this._load_from_string(value);
  1798. continue;
  1799. }
  1800. this[key] = value;
  1801. }
  1802. }
  1803. _load_from_string(dump_model_str) {
  1804. this._deserialize_model(dump_model_str);
  1805. }
  1806. _deserialize_model(dump_model_str) {
  1807. this._object._deserialize_model(dump_model_str);
  1808. }
  1809. });
  1810. this.registerType('catboost.core.CatBoost', class extends catboost.core._CatBoostBase {
  1811. load_model(/* blob */) {
  1812. throw new python.Error("'catboost.core.CatBoostClassifier.load_model' not implemented.");
  1813. // this._load_from_string(blob);
  1814. }
  1815. });
  1816. this.registerType('catboost.core.CatBoostClassifier', class extends catboost.core.CatBoost {});
  1817. this.registerType('catboost.core.CatBoostRegressor', class extends catboost.core.CatBoost {});
  1818. catboost.CatBoostClassifier = catboost.core.CatBoostClassifier;
  1819. catboost.CatBoostRegressor = catboost.core.CatBoostRegressor;
  1820. catboost.CatBoost = catboost.core.CatBoost;
  1821. this.registerType('collections.deque', class extends Array {
  1822. constructor(iterable) {
  1823. super();
  1824. if (Array.isArray(iterable)) {
  1825. for (const value of iterable) {
  1826. this.push(value);
  1827. }
  1828. }
  1829. }
  1830. });
  1831. this.registerType('collections.OrderedDict', class extends dict {});
  1832. this.registerType('cuml.common.array_descriptor.CumlArrayDescriptorMeta', class {});
  1833. this.registerType('cuml.ensemble.randomforestclassifier.RandomForestClassifier', class {});
  1834. this.registerType('cuml.internals.array.CumlArray', class {});
  1835. this.registerType('cuml.internals.mem_type.MemoryType', class {});
  1836. this.registerType('cuml.raft.common.handle.Handle', class {
  1837. __setstate__(state) {
  1838. this._handle = state;
  1839. }
  1840. });
  1841. this.registerType('cuml.svm.svr.SVR', class {});
  1842. this.registerType('datetime.date', class {});
  1843. this.registerType('datetime.datetime', class extends datetime.date {});
  1844. this.registerType('datetime.timedelta', class {});
  1845. this.registerType('datetime.tzinfo', class {});
  1846. this.registerType('datetime.timezone', class extends datetime.tzinfo {});
  1847. this.registerType('dnnlib.tflib.network.Network', class {});
  1848. this.registerType('dnnlib.util.EasyDict', class extends dict {});
  1849. this.registerType('haiku._src.data_structures.FlatMapping', class {
  1850. constructor(dict) {
  1851. Object.assign(this, dict);
  1852. }
  1853. });
  1854. this.registerType('haiku._src.data_structures.frozendict', class {
  1855. constructor(obj) {
  1856. Object.assign(this, obj);
  1857. }
  1858. });
  1859. this.registerType('hmmlearn.hmm.GaussianHMM', class {});
  1860. this.registerType('hmmlearn.hmm.GMMHMM', class {});
  1861. this.registerType('hmmlearn.hmm.MultinomialHMM', class {});
  1862. this.registerType('hmmlearn.base.ConvergenceMonitor', class {});
  1863. this.registerType('io.BytesIO', class {
  1864. constructor(buf, mode) {
  1865. this.mode = mode || 'r';
  1866. this._buf = this.mode === 'w' ? null : buf;
  1867. this._point = 0;
  1868. }
  1869. seek(offset) {
  1870. this._point = offset;
  1871. }
  1872. read(size) {
  1873. const start = this._point;
  1874. this._point = size === undefined ? this._buf.length : start + size;
  1875. return this._buf.subarray(start, this._point);
  1876. }
  1877. write(data) {
  1878. const src = this._buf || new Uint8Array();
  1879. this._point = src.length + data.length;
  1880. this._buf = new Uint8Array(this._point);
  1881. this._buf.set(src, 0);
  1882. this._buf.set(data, src.length);
  1883. }
  1884. });
  1885. this.registerType('numpy.dtype', class {
  1886. constructor(obj, align, copy) {
  1887. if (typeof obj === 'string' && (obj.startsWith('<') || obj.startsWith('>') || obj.startsWith('|'))) {
  1888. this.byteorder = obj.substring(0, 1);
  1889. obj = obj.substring(1);
  1890. } else {
  1891. this.byteorder = '=';
  1892. }
  1893. switch (obj) {
  1894. case 'b1': case 'bool': this.itemsize = 1; this.kind = 'b'; break;
  1895. case 'i1': case 'int8': this.itemsize = 1; this.kind = 'i'; break;
  1896. case 'i2': case 'int16': this.itemsize = 2; this.kind = 'i'; break;
  1897. case 'i4': case 'int32': this.itemsize = 4; this.kind = 'i'; break;
  1898. case 'i8': case 'int64': case 'int': this.itemsize = 8; this.kind = 'i'; break;
  1899. case 'u1': case 'uint8': this.itemsize = 1; this.kind = 'u'; break;
  1900. case 'u2': case 'uint16': this.itemsize = 2; this.kind = 'u'; break;
  1901. case 'u4': case 'uint32': this.itemsize = 4; this.kind = 'u'; break;
  1902. case 'u8': case 'uint64': case 'uint': this.itemsize = 8; this.kind = 'u'; break;
  1903. case 'f1': case 'float8_e5m2': this.itemsize = 1; this.kind = 'f'; break;
  1904. case 'f2': case 'float16': this.itemsize = 2; this.kind = 'f'; break;
  1905. case 'f4': case 'float32': this.itemsize = 4; this.kind = 'f'; break;
  1906. case 'f8': case 'float64': case 'float': this.itemsize = 8; this.kind = 'f'; break;
  1907. case 'c8': case 'complex64': this.itemsize = 8; this.kind = 'c'; break;
  1908. case 'c16': case 'complex128': case 'complex': this.itemsize = 16; this.kind = 'c'; break;
  1909. case 'M8': case 'M': this.itemsize = 8; this.kind = 'M'; break;
  1910. case 'V': case 'void': this.itemsize = 0; this.kind = 'V'; break;
  1911. default:
  1912. if (obj.startsWith('V')) {
  1913. this.itemsize = parseInt(obj.substring(1), 10);
  1914. this.kind = 'V';
  1915. } else if (obj.startsWith('O')) {
  1916. this.itemsize = obj === 'O' ? 8 : parseInt(obj.substring(1), 10);
  1917. this.kind = 'O';
  1918. } else if (obj.startsWith('S')) {
  1919. this.itemsize = parseInt(obj.substring(1), 10);
  1920. this.kind = 'S';
  1921. } else if (obj.startsWith('U')) { // Unicode string
  1922. this.kind = 'U';
  1923. this.itemsize = 4 * parseInt(obj.substring(1), 10);
  1924. } else if (obj.startsWith('T')) {
  1925. this.kind = 'T';
  1926. this.itemsize = parseInt(obj.substring(1), 10);
  1927. } else {
  1928. throw new python.Error(`Unsupported dtype '${obj}'.`);
  1929. }
  1930. break;
  1931. }
  1932. if (align) {
  1933. this.align = align;
  1934. }
  1935. if (copy) {
  1936. this.copy = copy;
  1937. }
  1938. }
  1939. get str() {
  1940. return (this.byteorder === '=' ? '<' : this.byteorder) + this.kind + this.itemsize.toString();
  1941. }
  1942. get name() {
  1943. switch (this.kind) {
  1944. case 'V': return `void${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  1945. case 'S': return `bytes${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  1946. case 'U': return `str${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  1947. case 'T': return `StringDType${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  1948. case 'M': return 'datetime64';
  1949. case 'b': return 'bool';
  1950. default: return this.__name__;
  1951. }
  1952. }
  1953. __setstate__(state) {
  1954. switch (state.length) {
  1955. case 8:
  1956. [
  1957. this.version, this.byteorder, this.subarray, this.names,
  1958. this.fields, this.elsize, this.alignment, this.int_dtypeflags
  1959. ] = state;
  1960. break;
  1961. case 9:
  1962. [
  1963. this.version, this.byteorder, this.subarray, this.names,
  1964. this.fields, this.elsize, this.alignment, this.int_dtypeflags,
  1965. this.metadata
  1966. ] = state;
  1967. break;
  1968. default:
  1969. throw new python.Error(`Unsupported numpy.dtype setstate length '${state.length}'.`);
  1970. }
  1971. }
  1972. get __name__() {
  1973. switch (this.kind) {
  1974. case 'b':
  1975. switch (this.itemsize) {
  1976. case 1: return 'boolean';
  1977. default: throw new python.Error(`Unsupported boolean itemsize '${this.itemsize}'.`);
  1978. }
  1979. case 'i':
  1980. switch (this.itemsize) {
  1981. case 1: return 'int8';
  1982. case 2: return 'int16';
  1983. case 4: return 'int32';
  1984. case 8: return 'int64';
  1985. default: throw new python.Error(`Unsupported int itemsize '${this.itemsize}'.`);
  1986. }
  1987. case 'u':
  1988. switch (this.itemsize) {
  1989. case 1: return 'uint8';
  1990. case 2: return 'uint16';
  1991. case 4: return 'uint32';
  1992. case 8: return 'uint64';
  1993. default: throw new python.Error(`Unsupported uint itemsize '${this.itemsize}'.`);
  1994. }
  1995. case 'f':
  1996. switch (this.itemsize) {
  1997. case 1: return 'float8e5m2';
  1998. case 2: return 'float16';
  1999. case 4: return 'float32';
  2000. case 8: return 'float64';
  2001. default: throw new python.Error(`Unsupported float itemsize '${this.itemsize}'.`);
  2002. }
  2003. case 'c':
  2004. switch (this.itemsize) {
  2005. case 8: return 'complex64';
  2006. case 16: return 'complex128';
  2007. default: throw new python.Error(`Unsupported complex itemsize '${this.itemsize}'.`);
  2008. }
  2009. case 'S':
  2010. case 'T':
  2011. return 'string';
  2012. case 'U':
  2013. return 'string';
  2014. case 'M':
  2015. return 'datetime';
  2016. case 'O':
  2017. return 'object';
  2018. case 'V':
  2019. return 'void';
  2020. default:
  2021. throw new python.Error(`Unsupported dtype kind '${this.kind}'.`);
  2022. }
  2023. }
  2024. });
  2025. this.registerType('numpy.generic', class {});
  2026. this.registerType('numpy.inexact', class {});
  2027. this.registerType('numpy.bool_', class extends numpy.generic {});
  2028. this.registerType('numpy.number', class extends numpy.generic {});
  2029. this.registerType('numpy.integer', class extends numpy.number {});
  2030. this.registerType('numpy.floating', class extends numpy.inexact {});
  2031. this.registerType('numpy.float16', class extends numpy.floating {});
  2032. this.registerType('numpy.float32', class extends numpy.floating {});
  2033. this.registerType('numpy.float64', class extends numpy.floating {});
  2034. this.registerType('numpy.signedinteger', class extends numpy.integer {});
  2035. this.registerType('numpy.int8', class extends numpy.signedinteger {});
  2036. this.registerType('numpy.int16', class extends numpy.signedinteger {});
  2037. this.registerType('numpy.int32', class extends numpy.signedinteger {});
  2038. this.registerType('numpy.int64', class extends numpy.signedinteger {});
  2039. this.registerType('numpy.unsignedinteger', class extends numpy.integer {});
  2040. this.registerType('numpy.uint8', class extends numpy.unsignedinteger {});
  2041. this.registerType('numpy.uint16', class extends numpy.unsignedinteger {});
  2042. this.registerType('numpy.uint32', class extends numpy.unsignedinteger {});
  2043. this.registerType('numpy.uint64', class extends numpy.unsignedinteger {});
  2044. this.registerType('numpy.datetime64', class extends numpy.generic {});
  2045. this.registerType('numpy.dtypes.StringDType', class extends numpy.dtype {
  2046. constructor() {
  2047. super('|T16');
  2048. }
  2049. });
  2050. this.registerType('gensim.models.doc2vec.Doctag', class {});
  2051. this.registerType('gensim.models.doc2vec.Doc2Vec', class {});
  2052. this.registerType('gensim.models.doc2vec.Doc2VecTrainables', class {});
  2053. this.registerType('gensim.models.doc2vec.Doc2VecVocab', class {});
  2054. this.registerType('gensim.models.fasttext.FastText', class {});
  2055. this.registerType('gensim.models.fasttext.FastTextTrainables', class {});
  2056. this.registerType('gensim.models.fasttext.FastTextVocab', class {});
  2057. this.registerType('gensim.models.fasttext.FastTextKeyedVectors', class {});
  2058. this.registerType('gensim.models.keyedvectors.Doc2VecKeyedVectors', class {});
  2059. this.registerType('gensim.models.keyedvectors.FastTextKeyedVectors', class {});
  2060. this.registerType('gensim.models.keyedvectors.KeyedVectors', class {});
  2061. this.registerType('gensim.models.keyedvectors.Vocab', class {});
  2062. this.registerType('gensim.models.keyedvectors.Word2VecKeyedVectors', class {});
  2063. this.registerType('gensim.models.ldamodel.LdaState', class {});
  2064. this.registerType('gensim.models.ldamulticore.LdaMulticore', class {});
  2065. this.registerType('gensim.models.phrases.Phrases', class {});
  2066. this.registerType('gensim.models.tfidfmodel.TfidfModel', class {});
  2067. this.registerType('gensim.models.word2vec.Vocab', class {});
  2068. this.registerType('gensim.models.word2vec.Word2Vec', class {});
  2069. this.registerType('gensim.models.word2vec.Word2VecTrainables', class {});
  2070. this.registerType('gensim.models.word2vec.Word2VecVocab', class {});
  2071. this.registerFunction('gensim.models.tfidfmodel.df2idf');
  2072. this.registerFunction('gensim.utils.call_on_class_only', () => {
  2073. throw new builtins.AttributeError('This method should be called on a class object.');
  2074. });
  2075. this.registerFunction('gensim.utils.identity');
  2076. this.registerType('google3.learning.deepmind.research.nbr.pbl_jax.clean_jaxline.utils.optimizers.ScaleByLarsState', class {
  2077. constructor(obj) {
  2078. Object.assign(this, obj);
  2079. }
  2080. });
  2081. this.registerType('joblib._store_backends.FileSystemStoreBackend', class {});
  2082. this.registerType('joblib.memory.NotMemorizedFunc', class {});
  2083. this.registerType('joblib.numpy_pickle.NumpyArrayWrapper', class {
  2084. __read__(unpickler) {
  2085. if (this.dtype.__name__ === 'object') {
  2086. return unpickler.load();
  2087. }
  2088. if (this.numpy_array_alignment_bytes) {
  2089. const [size] = unpickler.read(1);
  2090. unpickler.read(size);
  2091. }
  2092. if (this.order === 'F') {
  2093. throw new python.Error('Fortran order not implemented.');
  2094. }
  2095. const size = this.dtype.itemsize * this.shape.reduce((a, b) => a * b, 1);
  2096. this.data = unpickler.read(size);
  2097. return execution.invoke(this.subclass, [this.shape, this.dtype, this.data]);
  2098. }
  2099. });
  2100. this.registerType('joblib.numpy_pickle.NDArrayWrapper', class {
  2101. __setstate__(state) {
  2102. this.subclass = state.get('subclass');
  2103. this.filename = state.get('state');
  2104. this.allow_mmap = state.get('allow_mmap');
  2105. }
  2106. __read__(/* unpickler */) {
  2107. return this; // return execution.invoke(this.subclass, [ this.shape, this.dtype, this.data ]);
  2108. }
  2109. });
  2110. sklearn.externals.joblib.numpy_pickle.NDArrayWrapper = joblib.numpy_pickle.NDArrayWrapper;
  2111. sklearn.externals.joblib.numpy_pickle.NumpyArrayWrapper = joblib.numpy_pickle.NumpyArrayWrapper;
  2112. this.registerType('keras.engine.sequential.Sequential', class {});
  2113. this.registerType('keras.src.legacy.preprocessing.text.Tokenizer', class {});
  2114. this.registerType('lasagne.layers.conv.Conv2DLayer', class {});
  2115. this.registerType('lasagne.layers.dense.DenseLayer', class {});
  2116. this.registerType('lasagne.layers.input.InputLayer', class {});
  2117. this.registerType('lasagne.layers.pool.MaxPool2DLayer', class {});
  2118. this.registerType('lightgbm.sklearn.LGBMRegressor', class {});
  2119. this.registerType('lightgbm.sklearn.LGBMClassifier', class {});
  2120. this.registerType('lightgbm.basic.Booster', class {
  2121. constructor() {
  2122. this.average_output = false;
  2123. this.models = [];
  2124. this.loaded_parameter = '';
  2125. }
  2126. __setstate__(state) {
  2127. const model_str = state.get('_handle', state.get('handle', null));
  2128. if (model_str) {
  2129. this.LoadModelFromString(model_str);
  2130. return;
  2131. }
  2132. for (const [key, value] of state) {
  2133. this[key] = value;
  2134. }
  2135. }
  2136. LoadModelFromString(model_str) {
  2137. const lines = model_str.split('\n');
  2138. const signature = lines.shift() || '?';
  2139. if (signature.trim() !== 'tree') {
  2140. throw new python.Error(`Invalid signature '${signature.trim()}'.`);
  2141. }
  2142. // GBDT::LoadModelFromString() in https://github.com/microsoft/LightGBM/blob/master/src/boosting/gbdt_model_text.cpp
  2143. const key_vals = new Map();
  2144. while (lines.length > 0 && !lines[0].startsWith('Tree=')) {
  2145. const cur_line = lines.shift().trim();
  2146. if (cur_line.length > 0) {
  2147. const strs = cur_line.split('=');
  2148. if (strs.length === 1) {
  2149. key_vals.set(strs[0], '');
  2150. } else if (strs.length === 2) {
  2151. key_vals.set(strs[0], strs[1]);
  2152. } else if (strs.length > 2) {
  2153. if (strs[0] === "feature_names") {
  2154. key_vals.set(strs[0], cur_line.substring("feature_names=".length));
  2155. } else if (strs[0] === 'monotone_constraints') {
  2156. key_vals.set(strs[0], cur_line.substring('monotone_constraints='.length));
  2157. } else {
  2158. throw new python.Error(`Wrong line: ${cur_line.substring(0, Math.min(128, cur_line.length))}`);
  2159. }
  2160. }
  2161. }
  2162. }
  2163. const atoi = (key, value) => {
  2164. if (key_vals.has(key)) {
  2165. return parseInt(key_vals.get(key), 10);
  2166. }
  2167. if (value !== undefined) {
  2168. return value;
  2169. }
  2170. throw new python.Error(`Model file does not specify ${key}.`);
  2171. };
  2172. const list = (key, size) => {
  2173. if (key_vals.has(key)) {
  2174. const value = key_vals.get(key).split(' ');
  2175. if (value.length !== size) {
  2176. throw new python.Error(`Wrong size of ${key}.`);
  2177. }
  2178. return value;
  2179. }
  2180. throw new python.Error(`Model file does not contain ${key}.`);
  2181. };
  2182. this.version = key_vals.get('version') || '';
  2183. this.num_class = atoi('num_class');
  2184. this.num_tree_per_iteration = atoi('num_tree_per_iteration', this.num_class);
  2185. this.label_index = atoi('label_index');
  2186. this.max_feature_idx = atoi('max_feature_idx');
  2187. if (key_vals.has('average_output')) {
  2188. this.average_output = true;
  2189. }
  2190. this.feature_names = list('feature_names', this.max_feature_idx + 1);
  2191. this.feature_infos = list('feature_infos', this.max_feature_idx + 1);
  2192. if (key_vals.has('monotone_constraints')) {
  2193. this.monotone_constraints = list('monotone_constraints', this.max_feature_idx + 1);
  2194. }
  2195. if (key_vals.has('objective')) {
  2196. this.objective = key_vals.get('objective');
  2197. }
  2198. let tree = null;
  2199. while (lines.length > 0) {
  2200. const text = lines.shift();
  2201. const line = text.trim();
  2202. if (line.length === 0) {
  2203. continue;
  2204. }
  2205. if (line.startsWith('Tree=')) {
  2206. tree = { index: parseInt(line.split('=').pop(), 10) };
  2207. this.models.push(tree);
  2208. continue;
  2209. }
  2210. if (line === 'end of trees') {
  2211. break;
  2212. }
  2213. const param = line.split('=');
  2214. if (param.length !== 2) {
  2215. throw new python.Error(`Invalid property '${line}'.`);
  2216. }
  2217. const name = param[0].trim();
  2218. const value = param[1].trim();
  2219. tree[name] = value;
  2220. }
  2221. const ss = [];
  2222. let is_inparameter = false;
  2223. while (lines.length > 0) {
  2224. const text = lines.shift();
  2225. const line = text.trim();
  2226. if (line === 'parameters:') {
  2227. is_inparameter = true;
  2228. continue;
  2229. } else if (line === 'end of parameters') {
  2230. break;
  2231. } else if (is_inparameter) {
  2232. ss.push(line);
  2233. }
  2234. }
  2235. if (ss.length > 0) {
  2236. this.loaded_parameter = ss.join('\n');
  2237. }
  2238. }
  2239. });
  2240. this.registerFunction('megengine.functional.elemwise.clip', () => {});
  2241. this.registerFunction('megengine.functional.elemwise.sqrt', () => {});
  2242. this.registerFunction('megengine.functional.nn.conv2d', () => {});
  2243. this.registerFunction('megengine.functional.nn.relu', () => {});
  2244. this.registerFunction('megengine.functional.nn.sigmoid', () => {});
  2245. this.registerFunction('megengine.functional.tensor.arange', () => {});
  2246. this.registerFunction('megengine.functional.tensor.broadcast_to', () => {});
  2247. this.registerFunction('megengine.functional.tensor.concat', () => {});
  2248. this.registerFunction('megengine.functional.tensor.expand_dims', () => {});
  2249. this.registerFunction('megengine.functional.tensor.flatten', () => {});
  2250. this.registerFunction('megengine.functional.tensor.full', () => {});
  2251. this.registerFunction('megengine.functional.tensor.reshape', () => {});
  2252. this.registerFunction('megengine.functional.tensor.split', () => {});
  2253. this.registerFunction('megengine.functional.tensor.stack', () => {});
  2254. this.registerFunction('megengine.functional.tensor.transpose', () => {});
  2255. this.registerFunction('megengine.functional.vision.interpolate', () => {});
  2256. this.registerFunction('megengine.module.qat.module.QATModule._apply_fakequant_with_observer', () => {});
  2257. this.registerType('megengine.core._imperative_rt.common.CompNode', class {});
  2258. this.registerType('megengine.core._imperative_rt.ops.ElemwiseMultiType', class {});
  2259. this.registerType('megengine.core._imperative_rt.ops.FakeQuant', class {});
  2260. this.registerType('megengine.core._imperative_rt.ops.GetVarShape', class {});
  2261. this.registerType('megengine.core._imperative_rt.ops.Resize', class {});
  2262. this.registerType('megengine.core.ops._internal.param_defs.ConvolutionV0.Mode', class {});
  2263. this.registerType('megengine.core.ops._internal.param_defs.Convolution.ComputeMode', class {});
  2264. this.registerType('megengine.distributed.group.Group', class {});
  2265. this.registerType('megengine.module.activation.ReLU', class {});
  2266. this.registerType('megengine.module.activation.Softmax', class {});
  2267. this.registerType('megengine.module.adaptive_pooling.AdaptiveAvgPool2d', class {});
  2268. this.registerType('megengine.module.batchnorm.BatchNorm1d', class {});
  2269. this.registerType('megengine.module.batchnorm.BatchNorm2d', class {});
  2270. this.registerType('megengine.module.conv.Conv2d', class {});
  2271. this.registerType('megengine.module.conv.ConvTranspose2d', class {});
  2272. this.registerType('megengine.module.conv_bn.ConvBn2d', class {});
  2273. this.registerType('megengine.module.dropout.Dropout', class {});
  2274. this.registerType('megengine.module.identity.Identity', class {});
  2275. this.registerType('megengine.module.linear.Linear', class {});
  2276. this.registerType('megengine.module.module.Module', class {});
  2277. this.registerType('megengine.module.normalization.InstanceNorm', class {});
  2278. this.registerType('megengine.module.normalization.GroupNorm', class {});
  2279. this.registerType('megengine.module.normalization.LayerNorm', class {});
  2280. this.registerType('megengine.module.pooling.AvgPool2d', class {});
  2281. this.registerType('megengine.module.pooling.MaxPool2d', class {});
  2282. this.registerType('megengine.module.qat.concat.Concat', class {});
  2283. this.registerType('megengine.module.qat.elemwise.Elemwise', class {});
  2284. this.registerType('megengine.module.sequential.Sequential', class {});
  2285. this.registerType('megengine.quantization.fake_quant.FakeQuantize', class {});
  2286. this.registerType('megengine.quantization.fake_quant.LSQ', class {});
  2287. this.registerType('megengine.quantization.fake_quant.TQT', class {});
  2288. this.registerType('megengine.quantization.utils.QParams', class {});
  2289. this.registerType('megengine.quantization.utils.QuantMode', class {});
  2290. this.registerType('megengine.quantization.observer.ExponentialMovingAverageObserver', class {});
  2291. this.registerType('megengine.quantization.observer.HistogramObserver', class {});
  2292. this.registerType('megengine.quantization.observer.MinMaxObserver', class {});
  2293. this.registerType('megengine.quantization.observer.PassiveObserver', class {});
  2294. this.registerType('megengine.quantization.observer.SyncExponentialMovingAverageObserver', class {});
  2295. this.registerType('megengine.quantization.observer.SyncMinMaxObserver', class {});
  2296. this.registerType('megengine.traced_module.expr.Apply', class {});
  2297. this.registerType('megengine.traced_module.expr.CallFunction', class {});
  2298. this.registerType('megengine.traced_module.expr.CallMethod', class {});
  2299. this.registerType('megengine.traced_module.expr.Constant', class {});
  2300. this.registerType('megengine.traced_module.expr.GetAttr', class {});
  2301. this.registerType('megengine.traced_module.expr.Input', class {});
  2302. this.registerType('megengine.traced_module.fake_quant.FakeQuantize', class {});
  2303. this.registerType('megengine.traced_module.node.ModuleNode', class {});
  2304. this.registerType('megengine.traced_module.node.NodeMixin', class {});
  2305. this.registerType('megengine.traced_module.node.TensorNode', class {});
  2306. this.registerType('megengine.traced_module.pytree.ArgsIndex', class {});
  2307. this.registerType('megengine.traced_module.serialization._ModuleState', class {});
  2308. this.registerType('megengine.traced_module.traced_module.InternalGraph', class {});
  2309. this.registerType('megengine.traced_module.traced_module.NameSpace', class {});
  2310. this.registerType('megengine.traced_module.traced_module.TracedModule', class {});
  2311. this.registerType('megengine.tensor.Parameter', class {
  2312. constructor(data, dtype, device) {
  2313. this.data = data;
  2314. this.dtype = dtype;
  2315. this.device = device;
  2316. }
  2317. });
  2318. this.registerType('megengine.traced_module.pytree.TreeDef', class {
  2319. toString() {
  2320. let content = '';
  2321. for (const child of this.children_defs) {
  2322. content += `${child},`;
  2323. }
  2324. if (typeof this.type === "string") {
  2325. return `${this.type.split(".").slice(-1)}(${content})`;
  2326. }
  2327. return `${this.type.__name__}(${content})`;
  2328. }
  2329. });
  2330. this.registerType('megengine.traced_module.pytree.LeafDef', class {
  2331. toString() {
  2332. let content = '';
  2333. if (this.const_val === null) {
  2334. content += '[';
  2335. } else {
  2336. content += this.const_val;
  2337. }
  2338. for (const t of Object.values(this.type)) {
  2339. content += t.__name__;
  2340. }
  2341. content += ']';
  2342. return content;
  2343. }
  2344. });
  2345. this.registerType('megengine.tensor.Tensor', class {
  2346. constructor(data, dtype, device) {
  2347. this.data = data;
  2348. this.dtype = dtype;
  2349. this.device = device;
  2350. }
  2351. });
  2352. this.registerType('megengine.core.tensor.dtype.QuantDtypeMeta', class {
  2353. constructor(name, cname, np_dtype, qmin, qmax, is_signed) {
  2354. this.name = name;
  2355. this.cname = cname;
  2356. this.np_dtype = np_dtype;
  2357. this.qmin = qmin;
  2358. this.qmax = qmax;
  2359. this.is_signed = is_signed;
  2360. }
  2361. });
  2362. this.registerType('nolearn.lasagne.base.BatchIterator', class {});
  2363. this.registerType('nolearn.lasagne.base.Layers', class {});
  2364. this.registerType('nolearn.lasagne.base.NeuralNet', class {});
  2365. this.registerType('nolearn.lasagne.base.TrainSplit', class {});
  2366. this.registerType('nolearn.lasagne.handlers.PrintLayerInfo', class {});
  2367. this.registerType('nolearn.lasagne.handlers.PrintLog', class {});
  2368. this.registerType('numpy.ndarray', class {
  2369. constructor(shape, dtype, buffer, offset, strides, order) {
  2370. this.shape = shape;
  2371. this.dtype = dtype;
  2372. this.data = buffer === undefined ? null : buffer;
  2373. this.offset = offset === undefined ? 0 : offset;
  2374. this._strides = strides === undefined ? null : strides;
  2375. this.order = order === undefined ? null : order;
  2376. this.flags = {};
  2377. this._read();
  2378. }
  2379. static __new__(cls, shape, dtype, buffer, offset, strides, order) {
  2380. return new cls(shape, dtype, buffer, offset, strides, order);
  2381. }
  2382. __setstate__(state) {
  2383. [this.version, this.shape, this.dtype, this.flags.fn, this.data] = state;
  2384. this._read();
  2385. }
  2386. flatten() {
  2387. const size = this.shape.reduce((a, b) => a * b, 1);
  2388. const value = execution.invoke('numpy.ndarray', [
  2389. [size], this.dtype, this.data, this.offset, this.strides, this.order
  2390. ]);
  2391. value.flags = this.flags;
  2392. return value;
  2393. }
  2394. tobytes() {
  2395. return this.data;
  2396. }
  2397. tolist() {
  2398. if (this.shape.length < 0 || this.shape.length > 1) {
  2399. throw new python.Error(`Unsupported shape '${JSON.stringify(this.shape)}'.`);
  2400. }
  2401. const size = this.shape.reduce((a, b) => a * b, 1);
  2402. const list = new Array(size);
  2403. switch (this.dtype.kind) {
  2404. case 'U': {
  2405. const data = new Uint32Array(new Uint8Array(this.data).buffer);
  2406. const itemsize = this.dtype.itemsize >> 2;
  2407. let offset = 0;
  2408. for (let i = 0; i < size; i++) {
  2409. const buffer = data.subarray(offset, offset + itemsize);
  2410. const index = buffer.indexOf(0);
  2411. list[i] = Array.from(index >= 0 ? buffer.subarray(0, index) : buffer).map((c) => String.fromCodePoint(c)).join('');
  2412. offset += itemsize;
  2413. }
  2414. return list;
  2415. }
  2416. case 'S': {
  2417. const data = this.data;
  2418. const itemsize = this.dtype.itemsize;
  2419. const decoder = new TextDecoder('utf-8');
  2420. let offset = 0;
  2421. for (let i = 0; i < size; i++) {
  2422. const buffer = data.subarray(offset, offset + itemsize);
  2423. const index = buffer.indexOf(0);
  2424. list[i] = decoder.decode(index >= 0 ? buffer.subarray(0, index) : buffer);
  2425. offset += itemsize;
  2426. }
  2427. return list;
  2428. }
  2429. case 'V': {
  2430. const data = this.data;
  2431. const itemsize = this.dtype.itemsize;
  2432. let offset = 0;
  2433. for (let i = 0; i < size; i++) {
  2434. list[i] = data.slice(offset, offset + itemsize);
  2435. offset += itemsize;
  2436. }
  2437. return list;
  2438. }
  2439. case 'T': {
  2440. return this.data;
  2441. }
  2442. case 'O': {
  2443. return this.data;
  2444. }
  2445. default: {
  2446. throw new python.Error(`Type kind '${this.dtype.kind}' not implemented.`);
  2447. }
  2448. }
  2449. }
  2450. get itemsize() {
  2451. return this.dtype.itemsize;
  2452. }
  2453. get size() {
  2454. return (this.shape || []).reduce((a, b) => a * b, 1);
  2455. }
  2456. get strides() {
  2457. if (!this._strides) {
  2458. const shape = this.shape;
  2459. const strides = new Array(shape.length);
  2460. let stride = this.itemsize;
  2461. for (let i = shape.length - 1; i >= 0; i--) {
  2462. strides[i] = stride;
  2463. stride *= shape[i];
  2464. }
  2465. return strides;
  2466. }
  2467. return this._strides;
  2468. }
  2469. _read() {
  2470. if (this.data) {
  2471. const length = this.dtype.itemsize * this.size;
  2472. if (typeof this.data === 'string') {
  2473. this.data = this._unescape(this.data, length);
  2474. if (this.data.length !== length) {
  2475. throw new python.Error('Invalid string array data size.');
  2476. }
  2477. } else if (this.data.length !== length) {
  2478. // throw new python.Error('Invalid array data size.');
  2479. }
  2480. }
  2481. }
  2482. _unescape(token, size) {
  2483. const length = token.length;
  2484. const a = new Uint8Array(length);
  2485. if (size && size === length) {
  2486. for (let p = 0; p < size; p++) {
  2487. a[p] = token.charCodeAt(p);
  2488. }
  2489. return a;
  2490. }
  2491. let i = 0;
  2492. let o = 0;
  2493. while (i < length) {
  2494. let c = token.charCodeAt(i++);
  2495. if (c !== 0x5C || i >= length) {
  2496. a[o++] = c;
  2497. } else {
  2498. c = token.charCodeAt(i++);
  2499. switch (c) {
  2500. case 0x27: a[o++] = 0x27; break; // '
  2501. case 0x5C: a[o++] = 0x5C; break; // \\
  2502. case 0x22: a[o++] = 0x22; break; // "
  2503. case 0x72: a[o++] = 0x0D; break; // \r
  2504. case 0x6E: a[o++] = 0x0A; break; // \n
  2505. case 0x74: a[o++] = 0x09; break; // \t
  2506. case 0x62: a[o++] = 0x08; break; // \b
  2507. case 0x58: // x
  2508. case 0x78: { // X
  2509. const xsi = i - 1;
  2510. const xso = o;
  2511. for (let xi = 0; xi < 2; xi++) {
  2512. if (i >= length) {
  2513. i = xsi;
  2514. o = xso;
  2515. a[o] = 0x5c;
  2516. break;
  2517. }
  2518. let c = token.charCodeAt(i++);
  2519. if (c >= 65 && c <= 70) {
  2520. c -= 55;
  2521. } else if (c >= 97 && c <= 102) {
  2522. c -= 87;
  2523. } else if (c >= 48 && c <= 57) {
  2524. c -= 48;
  2525. } else {
  2526. c = -1;
  2527. }
  2528. if (c === -1) {
  2529. i = xsi;
  2530. o = xso;
  2531. a[o] = 0x5c;
  2532. break;
  2533. }
  2534. a[o] = a[o] << 4 | c;
  2535. }
  2536. o++;
  2537. break;
  2538. }
  2539. default:
  2540. if (c < 48 || c > 57) { // 0-9
  2541. a[o++] = 0x5c;
  2542. a[o++] = c;
  2543. } else {
  2544. i--;
  2545. const osi = i;
  2546. const oso = o;
  2547. for (let oi = 0; oi < 3; oi++) {
  2548. if (i >= length) {
  2549. i = osi;
  2550. o = oso;
  2551. a[o] = 0x5c;
  2552. break;
  2553. }
  2554. const od = token.charCodeAt(i++);
  2555. if (od < 48 || od > 57) {
  2556. i = osi;
  2557. o = oso;
  2558. a[o] = 0x5c;
  2559. break;
  2560. }
  2561. a[o] = a[o] << 3 | od - 48;
  2562. }
  2563. o++;
  2564. }
  2565. break;
  2566. }
  2567. }
  2568. }
  2569. return a.slice(0, o);
  2570. }
  2571. });
  2572. this.registerType('numpy.matrix', class extends numpy.ndarray {
  2573. static __new__(/* subtype, data, dtype, copy */) {
  2574. throw new Error("'numpy.matrix.__new__' not implemented.");
  2575. }
  2576. });
  2577. numpy.matrixlib.defmatrix.matrix = numpy.matrix;
  2578. this.registerType('numpy.ma.core.MaskedArray', class extends numpy.ndarray {
  2579. constructor(data /*, mask, dtype, copy, subok, ndmin, fill_value, keep_mask, hard_mask, shrink, order */) {
  2580. super(data.shape, data.dtype, data.data);
  2581. }
  2582. });
  2583. this.registerType('numpy.core.memmap.memmap', class extends numpy.ndarray {
  2584. });
  2585. this.registerType('pandas.core.arrays.categorical.Categorical', class {});
  2586. this.registerType('pandas.core.arrays.datetimes.DatetimeArray', class {});
  2587. this.registerType('pandas.core.arrays.integer.IntegerArray', class {});
  2588. this.registerType('pandas.core.frame.DataFrame', class {});
  2589. this.registerFunction('pandas.core.indexes.base._new_Index', (cls, d) => {
  2590. return new cls(d);
  2591. });
  2592. this.registerType('pandas.core.indexes.datetimes._new_DatetimeIndex', class {});
  2593. this.registerType('pandas.core.indexes.datetimes.DatetimeIndex', class {});
  2594. this.registerType('pandas.core.indexes.base.Index', class {});
  2595. this.registerType('pandas.core.indexes.range.RangeIndex', class {});
  2596. this.registerType('pandas.core.indexes.multi.MultiIndex', class {});
  2597. this.registerType('pandas.core.indexes.numeric.Int64Index', class {});
  2598. this.registerType('pandas.core.index.Int64Index', class {});
  2599. pandas.core.index.Index = pandas.core.indexes.base.Index;
  2600. pandas.core.index._new_Index = pandas.core.indexes.base._new_Index;
  2601. this.registerFunction('pandas.core.internals.blocks.Block', class {
  2602. });
  2603. this.registerFunction('pandas.core.internals.blocks.NumpyBlock', class extends pandas.core.internals.blocks.Block {
  2604. });
  2605. this.registerFunction('pandas.core.internals.blocks.get_block_type', (/* dtype */) => {
  2606. return pandas.core.internals.blocks.NumpyBlock;
  2607. });
  2608. this.registerFunction('pandas.core.internals.blocks.maybe_coerce_values', (values) => {
  2609. return values;
  2610. });
  2611. this.registerFunction('pandas.core.internals.blocks.new_block', (values, placement, ndim, refs) => {
  2612. const klass = execution.invoke('pandas.core.internals.blocks.get_block_type', [values.dtype]);
  2613. return new klass(values, ndim, placement, refs);
  2614. });
  2615. this.registerType('pandas.core.internals.managers.SingleBlockManager', class {});
  2616. this.registerType('pandas.core.internals.managers.BlockManager', class {});
  2617. pandas.core.internals.BlockManager = pandas.core.internals.managers.BlockManager;
  2618. this.registerType('pandas.core.series.Series', class {});
  2619. this.registerFunction('pandas._libs.arrays.__pyx_unpickle_NDArrayBacked');
  2620. this.registerFunction('pandas._libs.internals._unpickle_block', (values, placement, ndim) => {
  2621. values = execution.invoke('pandas.core.internals.blocks.maybe_coerce_values', [values]);
  2622. // if not isinstance(placement, BlockPlacement):
  2623. // placement = BlockPlacement(placement)
  2624. return execution.invoke('pandas.core.internals.blocks.new_block', [values, placement, ndim]);
  2625. });
  2626. this.registerType('pandas._libs.tslibs.base.ABCTimestamp', class extends datetime.datetime {});
  2627. this.registerType('pandas._libs.tslibs.offsets.BaseOffset', class {});
  2628. this.registerType('pandas._libs.tslibs.offsets.SingleConstructorOffset', class extends pandas._libs.tslibs.offsets.BaseOffset {});
  2629. this.registerType('pandas._libs.tslibs.offsets.Tick', class extends pandas._libs.tslibs.offsets.SingleConstructorOffset {});
  2630. this.registerType('pandas._libs.tslibs.offsets.Day', class extends pandas._libs.tslibs.offsets.Tick {});
  2631. this.registerType('pandas._libs.tslibs.offsets.Minute', class extends datetime.datetime {});
  2632. this.registerFunction('pandas._libs.tslibs.timestamps._unpickle_timestamp');
  2633. this.registerType('pandas._libs.tslibs.timestamps._Timestamp', class extends pandas._libs.tslibs.base.ABCTimestamp {});
  2634. this.registerType('pandas._libs.tslibs.timestamps.Timestamp', class extends pandas._libs.tslibs.timestamps._Timestamp {});
  2635. pandas._libs.tslib.Timestamp = pandas._libs.tslibs.timestamps.Timestamp;
  2636. this.registerType('pathlib.Path', class {});
  2637. this.registerType('pathlib.PosixPath', class {});
  2638. this.registerType('pathlib.WindowsPath', class {});
  2639. this.registerType('shap._serializable.Serializable', class {});
  2640. this.registerType('shap.explainers._explainer.Explainer', class extends shap._serializable.Serializable {});
  2641. this.registerType('shap.explainers._linear.LinearExplainer', class extends shap.explainers._explainer.Explainer {});
  2642. shap.explainers.LinearExplainer = shap.explainers._linear.LinearExplainer;
  2643. shap.explainers.linear.LinearExplainer = shap.explainers._linear.LinearExplainer;
  2644. this.registerType('sklearn._loss.link.BaseLink', class {});
  2645. this.registerType('sklearn._loss._loss.__pyx_unpickle_CyHalfBinomialLoss', class {});
  2646. this.registerType('sklearn._loss._loss.__pyx_unpickle_CyHalfMultinomialLoss', class {});
  2647. this.registerType('sklearn._loss._loss.CyLossFunction', class {});
  2648. this.registerType('sklearn._loss._loss.CyHalfBinomialLoss', class {});
  2649. this.registerType('sklearn._loss._loss.CyHalfMultinomialLoss', class {});
  2650. this.registerType('sklearn._loss._loss.CyHalfSquaredError', class extends sklearn._loss._loss.CyLossFunction {});
  2651. this.registerType('sklearn._loss.link.IdentityLink', class extends sklearn._loss.link.BaseLink {});
  2652. this.registerType('sklearn._loss.link.Interval', class {});
  2653. this.registerType('sklearn._loss.link.LogitLink', class {});
  2654. this.registerType('sklearn._loss.link.MultinomialLogit', class extends sklearn._loss.link.BaseLink {});
  2655. this.registerFunction('sklearn._loss._loss.__pyx_unpickle_CyHalfSquaredError');
  2656. this.registerType('sklearn._loss.loss.BaseLoss', class {});
  2657. this.registerType('sklearn._loss.loss.HalfBinomialLoss', class {});
  2658. this.registerType('sklearn._loss.loss.HalfMultinomialLoss', class extends sklearn._loss.loss.BaseLoss {});
  2659. this.registerType('sklearn._loss.loss.HalfSquaredError', class extends sklearn._loss.loss.BaseLoss {});
  2660. this.registerType('sklearn.base.BaseEstimator', class {});
  2661. this.registerType('sklearn.base.TransformerMixin', class {});
  2662. this.registerType('sklearn.calibration._CalibratedClassifier', class {});
  2663. this.registerType('sklearn.calibration._SigmoidCalibration', class {});
  2664. this.registerType('sklearn.calibration.CalibratedClassifierCV', class {});
  2665. this.registerType('sklearn.cluster._agglomerative.FeatureAgglomeration', class {});
  2666. this.registerType('sklearn.cluster._dbscan.DBSCAN', class {});
  2667. this.registerType('sklearn.cluster._kmeans.KMeans', class {});
  2668. this.registerType('sklearn.cluster._kmeans.MiniBatchKMeans', class {});
  2669. this.registerType('sklearn.cluster.k_means_.MiniBatchKMeans', class {});
  2670. this.registerType('sklearn.compose._column_transformer._RemainderColsList', class {});
  2671. this.registerType('sklearn.compose._column_transformer.ColumnTransformer', class {});
  2672. this.registerType('sklearn.compose._column_transformer.make_column_selector', class {});
  2673. this.registerType('sklearn.compose._target.TransformedTargetRegressor', class {});
  2674. this.registerType('sklearn.cross_decomposition._pls.PLSRegression', class {});
  2675. this.registerType('sklearn.decomposition._fastica.FastICA', class {});
  2676. this.registerType('sklearn.decomposition._pca.PCA', class {});
  2677. this.registerType('sklearn.decomposition._truncated_svd.TruncatedSVD', class {});
  2678. this.registerType('sklearn.decomposition.pca.PCA', class {});
  2679. this.registerType('sklearn.decomposition.PCA', class {});
  2680. this.registerType('sklearn.decomposition.truncated_svd.TruncatedSVD', class {});
  2681. this.registerType('sklearn.discriminant_analysis.LinearDiscriminantAnalysis', class {});
  2682. this.registerType('sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis', class {});
  2683. this.registerType('sklearn.dummy.DummyClassifier', class {});
  2684. this.registerType('sklearn.dummy.DummyRegressor', class {});
  2685. this.registerType('sklearn.ensemble._bagging.BaggingClassifier', class {});
  2686. this.registerType('sklearn.ensemble._bagging.BaggingRegressor', class {});
  2687. this.registerType('sklearn.ensemble._forest.RandomForestClassifier', class {});
  2688. this.registerType('sklearn.ensemble._forest.RandomForestRegressor', class {});
  2689. this.registerType('sklearn.ensemble._forest.ExtraTreesClassifier', class {});
  2690. this.registerType('sklearn.ensemble._forest.ExtraTreesRegressor', class {});
  2691. this.registerType('sklearn.ensemble._gb_losses.BinomialDeviance', class {});
  2692. this.registerType('sklearn.ensemble._gb_losses.ExponentialLoss', class {});
  2693. this.registerType('sklearn.ensemble._gb_losses.LeastAbsoluteError', class {});
  2694. this.registerType('sklearn.ensemble._gb_losses.LeastSquaresError', class {});
  2695. this.registerType('sklearn.ensemble._gb_losses.MultinomialDeviance', class {});
  2696. this.registerType('sklearn.ensemble._gb.GradientBoostingClassifier', class {});
  2697. this.registerType('sklearn.ensemble._gb.GradientBoostingRegressor', class {});
  2698. this.registerType('sklearn.ensemble._hist_gradient_boosting.binning._BinMapper', class {});
  2699. this.registerType('sklearn.ensemble._hist_gradient_boosting.gradient_boosting.HistGradientBoostingRegressor', class {});
  2700. this.registerType('sklearn.ensemble._hist_gradient_boosting.loss.LeastSquares', class {});
  2701. this.registerType('sklearn.ensemble._hist_gradient_boosting.predictor.TreePredictor', class {});
  2702. this.registerType('sklearn.ensemble._iforest.IsolationForest', class {});
  2703. this.registerType('sklearn.ensemble._stacking.StackingClassifier', class {});
  2704. this.registerType('sklearn.ensemble._voting.VotingClassifier', class {});
  2705. this.registerType('sklearn.ensemble._voting.VotingRegressor', class {});
  2706. this.registerType('sklearn.ensemble._weight_boosting.AdaBoostClassifier', class {});
  2707. this.registerType('sklearn.ensemble._weight_boosting.AdaBoostRegressor', class {});
  2708. this.registerType('sklearn.ensemble.forest.RandomForestClassifier', class {});
  2709. this.registerType('sklearn.ensemble.forest.RandomForestRegressor', class {});
  2710. this.registerType('sklearn.ensemble.forest.ExtraTreesClassifier', class {});
  2711. this.registerType('sklearn.ensemble.gradient_boosting.BinomialDeviance', class {});
  2712. this.registerType('sklearn.ensemble.gradient_boosting.GradientBoostingClassifier', class {});
  2713. this.registerType('sklearn.ensemble.gradient_boosting.LogOddsEstimator', class {});
  2714. this.registerType('sklearn.ensemble.gradient_boosting.MultinomialDeviance', class {});
  2715. this.registerType('sklearn.ensemble.gradient_boosting.PriorProbabilityEstimator', class {});
  2716. this.registerType('sklearn.ensemble.voting_classifier.VotingClassifier', class {});
  2717. this.registerType('sklearn.ensemble.weight_boosting.AdaBoostClassifier', class {});
  2718. this.registerType('sklearn.feature_extraction._hashing.FeatureHasher', class {});
  2719. this.registerType('sklearn.feature_extraction.text.CountVectorizer', class {});
  2720. this.registerType('sklearn.feature_extraction.text.HashingVectorizer', class {});
  2721. this.registerType('sklearn.feature_extraction.text.TfidfTransformer', class {});
  2722. this.registerType('sklearn.feature_extraction.text.TfidfVectorizer', class {});
  2723. this.registerType('sklearn.feature_selection._from_model.SelectFromModel', class {});
  2724. this.registerFunction('sklearn.feature_selection._mutual_info.mutual_info_classif');
  2725. this.registerFunction('sklearn.feature_selection._univariate_selection.chi2');
  2726. this.registerType('sklearn.feature_selection._univariate_selection.GenericUnivariateSelect', class {});
  2727. this.registerType('sklearn.feature_selection._univariate_selection.SelectKBest', class {});
  2728. this.registerType('sklearn.feature_selection._univariate_selection.SelectPercentile', class {});
  2729. this.registerType('sklearn.feature_selection._variance_threshold.VarianceThreshold', class {});
  2730. this.registerType('sklearn.feature_selection._rfe.RFE', class {});
  2731. this.registerType('sklearn.feature_selection.univariate_selection.SelectKBest', class {});
  2732. this.registerType('sklearn.feature_selection.variance_threshold.VarianceThreshold', class {});
  2733. this.registerType('sklearn.gaussian_process._gpc.GaussianProcessClassifier', class {});
  2734. this.registerType('sklearn.gaussian_process._gpr.GaussianProcessRegressor', class {});
  2735. this.registerType('sklearn.gaussian_process.gpc.GaussianProcessClassifier', class {});
  2736. this.registerType('sklearn.gaussian_process.kernels.ConstantKernel', class {});
  2737. this.registerType('sklearn.gaussian_process.kernels.DotProduct', class {});
  2738. this.registerType('sklearn.gaussian_process.kernels.Product', class {});
  2739. this.registerType('sklearn.gaussian_process.kernels.RBF', class {});
  2740. this.registerType('sklearn.gaussian_process.kernels.Sum', class {});
  2741. this.registerType('sklearn.gaussian_process.kernels.WhiteKernel', class {});
  2742. this.registerType('sklearn.grid_search._CVScoreTuple', class {});
  2743. this.registerType('sklearn.grid_search.GridSearchCV', class {});
  2744. this.registerType('sklearn.impute._base.SimpleImputer', class {});
  2745. this.registerType('sklearn.impute._iterative.IterativeImputer', class {});
  2746. this.registerType('sklearn.impute._iterative._ImputerTriplet', class {});
  2747. this.registerType('sklearn.impute.SimpleImputer', class {});
  2748. this.registerType('sklearn.isotonic.IsotonicRegression', class {});
  2749. this.registerType('sklearn.kernel_ridge.KernelRidge', class {});
  2750. this.registerType('sklearn.linear_model._base.LinearRegression', class {});
  2751. this.registerType('sklearn.linear_model._bayes.BayesianRidge', class {});
  2752. this.registerType('sklearn.linear_model._coordinate_descent.ElasticNetCV', class {});
  2753. this.registerType('sklearn.linear_model._coordinate_descent.ElasticNet', class {});
  2754. this.registerType('sklearn.linear_model._coordinate_descent.Lasso', class {});
  2755. this.registerType('sklearn.linear_model._least_angle.LassoLarsCV', class {});
  2756. this.registerType('sklearn.linear_model._logistic.LogisticRegression', class {});
  2757. this.registerType('sklearn.linear_model._logistic.LogisticRegressionCV', class {});
  2758. this.registerType('sklearn.linear_model._quantile.QuantileRegressor', class {});
  2759. this.registerType('sklearn.linear_model._ridge.Ridge', class {});
  2760. this.registerType('sklearn.linear_model._ridge.RidgeClassifier', class {});
  2761. this.registerType('sklearn.linear_model._sgd_fast.Hinge', class {});
  2762. this.registerType('sklearn.linear_model._sgd_fast.Log', class {});
  2763. this.registerType('sklearn.linear_model._sgd_fast.ModifiedHuber', class {});
  2764. this.registerType('sklearn.linear_model._sgd_fast.SquaredHinge', class {});
  2765. this.registerType('sklearn.linear_model._stochastic_gradient.SGDClassifier', class {});
  2766. this.registerType('sklearn.linear_model.base.LinearRegression', class {});
  2767. this.registerType('sklearn.linear_model.sgd_fast.Hinge', class {});
  2768. this.registerType('sklearn.linear_model.LogisticRegression', class {});
  2769. this.registerType('sklearn.linear_model.logistic.LogisticRegression', class {});
  2770. this.registerType('sklearn.linear_model.logistic.LogisticRegressionCV', class {});
  2771. this.registerType('sklearn.linear_model.LassoLars​', class {});
  2772. this.registerType('sklearn.linear_model.ridge.Ridge', class {});
  2773. this.registerType('sklearn.linear_model.sgd_fast.Log', class {});
  2774. this.registerType('sklearn.linear_model.stochastic_gradient.SGDClassifier', class {});
  2775. this.registerType('sklearn.manifold._t_sne.TSNE', class {});
  2776. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric', class extends builtins.object {});
  2777. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric32', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  2778. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric64', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  2779. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  2780. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance32', class extends sklearn.metrics._dist_metrics.DistanceMetric32 {});
  2781. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance64', class extends sklearn.metrics._dist_metrics.DistanceMetric64 {});
  2782. this.registerType('sklearn.metrics._dist_metrics.ManhattanDistance', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  2783. this.registerType('sklearn.metrics._dist_metrics.ManhattanDistance64', class extends sklearn.metrics._dist_metrics.DistanceMetric64 {});
  2784. this.registerType('sklearn.metrics._scorer._PassthroughScorer', class {});
  2785. this.registerType('sklearn.metrics._scorer._PredictScorer', class {});
  2786. this.registerType('sklearn.metrics.scorer._PredictScorer', class {});
  2787. this.registerType('sklearn.metrics._scorer._ThresholdScorer', class {});
  2788. this.registerType('sklearn.mixture._bayesian_mixture.BayesianGaussianMixture', class {});
  2789. this.registerType('sklearn.mixture._gaussian_mixture.GaussianMixture', class {});
  2790. this.registerType('sklearn.model_selection._search.GridSearchCV', class {});
  2791. this.registerType('sklearn.model_selection._search.RandomizedSearchCV', class {});
  2792. this.registerType('sklearn.model_selection._split.KFold', class {});
  2793. this.registerType('sklearn.model_selection._split.RepeatedKFold', class {});
  2794. this.registerType('sklearn.model_selection._split.StratifiedKFold', class {});
  2795. this.registerType('sklearn.model_selection._split.StratifiedShuffleSplit', class {});
  2796. this.registerType('sklearn.multiclass.OneVsRestClassifier', class {});
  2797. this.registerType('sklearn.multioutput.ClassifierChain', class {});
  2798. this.registerType('sklearn.multioutput.MultiOutputClassifier', class {});
  2799. this.registerType('sklearn.multioutput.MultiOutputRegressor', class {});
  2800. this.registerType('sklearn.naive_bayes.BernoulliNB', class {});
  2801. this.registerType('sklearn.naive_bayes.ComplementNB', class {});
  2802. this.registerType('sklearn.naive_bayes.GaussianNB', class {});
  2803. this.registerType('sklearn.naive_bayes.MultinomialNB', class {});
  2804. this.registerType('sklearn.neighbors.ball_tree.BallTree', class {});
  2805. this.registerFunction('sklearn.neighbors.ball_tree.newObj', (obj) => {
  2806. return obj.__new__(obj);
  2807. });
  2808. this.registerType('sklearn.neighbors._classification.KNeighborsClassifier', class {});
  2809. this.registerFunction('sklearn.neighbors._dist_metrics.newObj');
  2810. this.registerType('sklearn.neighbors._dist_metrics.EuclideanDistance', class {});
  2811. this.registerType('sklearn.neighbors._kd_tree.BinaryTree64', class extends builtins.object {});
  2812. this.registerType('sklearn.neighbors._kd_tree.KDTree64', class extends sklearn.neighbors._kd_tree.BinaryTree64 {});
  2813. this.registerType('sklearn.neighbors._kd_tree.KDTree', class extends sklearn.neighbors._kd_tree.KDTree64 {});
  2814. this.registerFunction('sklearn.neighbors._kd_tree.newObj', (obj) => {
  2815. return obj.__new__(obj);
  2816. });
  2817. this.registerType('sklearn.neighbors._regression.KNeighborsRegressor', class {});
  2818. this.registerType('sklearn.neighbors._unsupervised.NearestNeighbors', class {});
  2819. this.registerType('sklearn.neighbors.classification.KNeighborsClassifier', class {});
  2820. this.registerFunction('sklearn.neighbors.dist_metrics.newObj', (obj) => {
  2821. return obj.__new__(obj);
  2822. });
  2823. this.registerType('sklearn.neighbors.dist_metrics.EuclideanDistance', class {});
  2824. this.registerFunction('sklearn.neighbors.kd_tree.newObj', (obj) => {
  2825. return obj.__new__(obj);
  2826. });
  2827. this.registerType('sklearn.neighbors.kd_tree.KDTree', class {});
  2828. this.registerType('sklearn.neighbors.KNeighborsClassifier', class {});
  2829. this.registerType('sklearn.neighbors.KNeighborsRegressor', class {});
  2830. this.registerType('sklearn.neighbors.regression.KNeighborsRegressor', class {});
  2831. this.registerType('sklearn.neighbors.unsupervised.NearestNeighbors', class {});
  2832. this.registerType('sklearn.neural_network._multilayer_perceptron.MLPClassifier', class {});
  2833. this.registerType('sklearn.neural_network._multilayer_perceptron.MLPRegressor', class {});
  2834. this.registerType('sklearn.neural_network._stochastic_optimizers.AdamOptimizer', class {});
  2835. this.registerType('sklearn.neural_network._stochastic_optimizers.SGDOptimizer', class {});
  2836. this.registerType('sklearn.neural_network.rbm.BernoulliRBM', class {});
  2837. this.registerType('sklearn.neural_network.multilayer_perceptron.MLPClassifier', class {});
  2838. this.registerType('sklearn.neural_network.multilayer_perceptron.MLPRegressor', class {});
  2839. this.registerType('sklearn.neural_network.stochastic_gradient.SGDClassifier', class {});
  2840. this.registerType('sklearn.pipeline.Pipeline', class {});
  2841. this.registerType('sklearn.pipeline.FeatureUnion', class {});
  2842. this.registerType('sklearn.preprocessing._data.MinMaxScaler', class {});
  2843. this.registerType('sklearn.preprocessing._data.MaxAbsScaler', class {});
  2844. this.registerType('sklearn.preprocessing._data.Normalizer', class {});
  2845. this.registerType('sklearn.preprocessing._data.PolynomialFeatures', class {});
  2846. this.registerType('sklearn.preprocessing._data.PowerTransformer', class {});
  2847. this.registerType('sklearn.preprocessing._data.QuantileTransformer', class {});
  2848. this.registerType('sklearn.preprocessing._data.RobustScaler', class {});
  2849. this.registerType('sklearn.preprocessing._data.StandardScaler', class {});
  2850. this.registerType('sklearn.preprocessing._discretization.KBinsDiscretizer', class {});
  2851. this.registerType('sklearn.preprocessing._encoders.OneHotEncoder', class {});
  2852. this.registerType('sklearn.preprocessing._encoders.OrdinalEncoder', class {});
  2853. this.registerType('sklearn.preprocessing._function_transformer.FunctionTransformer', class {});
  2854. this.registerType('sklearn.preprocessing._label.LabelBinarizer', class {});
  2855. this.registerType('sklearn.preprocessing._label.LabelEncoder', class {});
  2856. this.registerType('sklearn.preprocessing._label.MultiLabelBinarizer', class {});
  2857. this.registerType('sklearn.preprocessing._polynomial.PolynomialFeatures', class {});
  2858. this.registerType('sklearn.preprocessing.data.Binarizer', class {});
  2859. this.registerType('sklearn.preprocessing.data.MaxAbsScaler', class {});
  2860. this.registerType('sklearn.preprocessing.data.MinMaxScaler', class {});
  2861. this.registerType('sklearn.preprocessing.data.Normalizer', class {});
  2862. this.registerType('sklearn.preprocessing.data.OneHotEncoder', class {});
  2863. this.registerType('sklearn.preprocessing.data.PolynomialFeatures', class {});
  2864. this.registerType('sklearn.preprocessing.data.PowerTransformer', class {});
  2865. this.registerType('sklearn.preprocessing.data.RobustScaler', class {});
  2866. this.registerType('sklearn.preprocessing.data.QuantileTransformer', class {});
  2867. this.registerType('sklearn.preprocessing.data.StandardScaler', class {});
  2868. this.registerType('sklearn.preprocessing.imputation.Imputer', class {});
  2869. this.registerType('sklearn.preprocessing.label.LabelBinarizer', class {});
  2870. this.registerType('sklearn.preprocessing.label.LabelEncoder', class {});
  2871. this.registerType('sklearn.preprocessing.label.MultiLabelBinarizer', class {});
  2872. this.registerType('sklearn.random_projection.GaussianRandomProjection', class {});
  2873. this.registerType('sklearn.svm._classes.LinearSVC', class {});
  2874. this.registerType('sklearn.svm._classes.NuSVC', class {});
  2875. this.registerType('sklearn.svm._classes.OneClassSVM', class {});
  2876. this.registerType('sklearn.svm._classes.SVC', class {});
  2877. this.registerType('sklearn.svm._classes.SVR', class {});
  2878. this.registerType('sklearn.svm.classes.LinearSVC', class {});
  2879. this.registerType('sklearn.svm.classes.OneClassSVM', class {});
  2880. this.registerType('sklearn.svm.classes.SVC', class {});
  2881. this.registerType('sklearn.svm.classes.SVR', class {});
  2882. this.registerType('sklearn.tree._classes.DecisionTreeClassifier', class {});
  2883. this.registerType('sklearn.tree._classes.DecisionTreeRegressor', class {});
  2884. this.registerType('sklearn.tree._classes.ExtraTreeClassifier', class {});
  2885. this.registerType('sklearn.tree._classes.ExtraTreeRegressor', class {});
  2886. this.registerType('sklearn.tree._tree.Tree', class {
  2887. constructor(n_features, n_classes, n_outputs) {
  2888. this.n_features = n_features;
  2889. this.n_classes = n_classes;
  2890. this.n_outputs = n_outputs;
  2891. }
  2892. __setstate__(state) {
  2893. this.max_depth = state.get('max_depth');
  2894. this.node_count = state.get('node_count');
  2895. this.nodes = state.get('nodes');
  2896. this.values = state.get('values');
  2897. }
  2898. });
  2899. this.registerType('sklearn.tree.tree.DecisionTreeClassifier', class {});
  2900. this.registerType('sklearn.tree.tree.DecisionTreeRegressor', class {});
  2901. this.registerType('sklearn.tree.tree.ExtraTreeClassifier', class {});
  2902. this.registerType('sklearn.utils._bunch.Bunch', class {});
  2903. this.registerType('sklearn.utils._metadata_requests.MetadataRequest', class {});
  2904. this.registerType('sklearn.utils._metadata_requests.MethodMetadataRequest', class {});
  2905. this.registerType('sklearn.utils.deprecation.DeprecationDict', class {});
  2906. this.registerType('pickle.Unpickler', class {
  2907. constructor(data) {
  2908. this._reader = data instanceof Uint8Array ? new python.BinaryReader(data) : new python.StreamReader(data);
  2909. this.persistent_load = () => {
  2910. throw new python.Error('Unsupported persistent id.');
  2911. };
  2912. }
  2913. load() {
  2914. const reader = this._reader;
  2915. const marker = [];
  2916. let stack = [];
  2917. const memo = {};
  2918. let size = 0;
  2919. while (reader.position < reader.length) {
  2920. const opcode = reader.byte();
  2921. // console.log(`${(reader.position - 1).toString()} ${opcode}`);
  2922. // https://svn.python.org/projects/python/trunk/Lib/pickletools.py
  2923. // https://github.com/python/cpython/blob/master/Lib/pickle.py
  2924. switch (opcode) {
  2925. case 128: { // PROTO
  2926. const version = reader.byte();
  2927. if (version > 5) {
  2928. throw new python.Error(`Unsupported protocol version '${version}'.`);
  2929. }
  2930. break;
  2931. }
  2932. case 99: { // GLOBAL 'c'
  2933. const module = reader.line();
  2934. const name = reader.line();
  2935. stack.push(this.find_class(module, name));
  2936. break;
  2937. }
  2938. case 147: { // STACK_GLOBAL '\x93' (Protocol 4)
  2939. const name = stack.pop();
  2940. const module = stack.pop();
  2941. stack.push(this.find_class(module, name));
  2942. break;
  2943. }
  2944. case 111: { // OBJ 'o'
  2945. const args = stack;
  2946. const cls = args.pop();
  2947. stack = marker.pop();
  2948. const obj = this._instantiate(cls, args);
  2949. stack.push(obj);
  2950. break;
  2951. }
  2952. case 112 : { // PUT 'p'
  2953. const index = parseInt(reader.line(), 10);
  2954. memo[index] = stack[stack.length - 1];
  2955. size++;
  2956. break;
  2957. }
  2958. case 103: { // GET 'g'
  2959. const index = parseInt(reader.line(), 10);
  2960. stack.push(memo[index]);
  2961. break;
  2962. }
  2963. case 48: // POP '0'
  2964. stack.pop();
  2965. break;
  2966. case 49: // POP_MARK '1'
  2967. stack = marker.pop();
  2968. break;
  2969. case 50: // DUP '2'
  2970. stack.push(stack[stack.length - 1]);
  2971. break;
  2972. case 80: // PERSID 'P'
  2973. stack.push(this.persistent_load(reader.line()));
  2974. break;
  2975. case 81: // BINPERSID 'Q'
  2976. stack.push(this.persistent_load(stack.pop()));
  2977. break;
  2978. case 82: { // REDUCE 'R'
  2979. const args = stack.pop();
  2980. const func = stack.pop();
  2981. stack.push(this._reduce(func, args));
  2982. break;
  2983. }
  2984. case 129: { // NEWOBJ
  2985. const args = stack.pop();
  2986. const cls = stack.pop();
  2987. const obj = this._newobj(cls, args);
  2988. stack.push(obj);
  2989. break;
  2990. }
  2991. case 146: { // NEWOBJ_EX '\x92' (Protocol 4)
  2992. const kwargs = stack.pop();
  2993. const args = stack.pop();
  2994. const cls = stack.pop();
  2995. if (Object.entries(kwargs).length > 0) {
  2996. throw new python.Error("Unpickle 'NEWOBJ_EX' not implemented.");
  2997. }
  2998. const obj = this._newobj(cls, args);
  2999. stack.push(obj);
  3000. break;
  3001. }
  3002. case 104: // BINGET 'h'
  3003. stack.push(memo[reader.byte()]);
  3004. break;
  3005. case 105: { // INST 'i'
  3006. const module = reader.line();
  3007. const name = reader.line();
  3008. const args = stack;
  3009. const cls = `${module}.${name}`;
  3010. stack = marker.pop();
  3011. // cls = this.find_class(module, name)
  3012. const obj = this._instantiate(cls, args);
  3013. stack.push(obj);
  3014. break;
  3015. }
  3016. case 106: // LONG_BINGET 'j'
  3017. stack.push(memo[reader.uint32()]);
  3018. break;
  3019. case 113: // BINPUT 'q'
  3020. memo[reader.byte()] = stack[stack.length - 1];
  3021. size++;
  3022. break;
  3023. case 114: // LONG_BINPUT 'r'
  3024. memo[reader.uint32()] = stack[stack.length - 1];
  3025. size++;
  3026. break;
  3027. case 74: // BININT 'J'
  3028. stack.push(reader.int32());
  3029. break;
  3030. case 75: // BININT1 'K'
  3031. stack.push(reader.byte());
  3032. break;
  3033. case 76: // LONG 'L'
  3034. stack.push(parseInt(reader.line(), 10));
  3035. break;
  3036. case 77: // BININT2 'M'
  3037. stack.push(reader.uint16());
  3038. break;
  3039. case 66: // BINBYTES 'B' (Protocol 3)
  3040. stack.push(reader.read(reader.int32()));
  3041. break;
  3042. case 67: // SHORT_BINBYTES 'C' (Protocol 3)
  3043. stack.push(reader.read(reader.byte()));
  3044. break;
  3045. case 142: // BINBYTES8 '\x8e' (Protocol 4)
  3046. stack.push(reader.read(reader.int64().toNumber()));
  3047. break;
  3048. case 70: // FLOAT 'F'
  3049. stack.push(parseFloat(reader.line()));
  3050. break;
  3051. case 71: // BINFLOAT 'G'
  3052. stack.push(reader.float64());
  3053. break;
  3054. case 73: { // INT 'I'
  3055. const value = reader.line();
  3056. if (value === '01') {
  3057. stack.push(true);
  3058. } else if (value === '00') {
  3059. stack.push(false);
  3060. } else {
  3061. stack.push(parseInt(value, 10));
  3062. }
  3063. break;
  3064. }
  3065. case 93: // EMPTY_LIST ']'
  3066. stack.push(new builtins.list());
  3067. break;
  3068. case 41: // EMPTY_TUPLE ')'
  3069. stack.push([]);
  3070. break;
  3071. case 143: // EMPTY_SET '\x8f' (Protocol 4)
  3072. stack.push([]);
  3073. break;
  3074. case 144: { // ADDITEMS '\x90' (Protocol 4)
  3075. const items = stack;
  3076. stack = marker.pop();
  3077. const obj = stack[stack.length - 1];
  3078. for (let i = 0; i < items.length; i++) {
  3079. obj.push(items[i]);
  3080. }
  3081. break;
  3082. }
  3083. case 145: { // FROZENSET '\x91' (Protocol 4)
  3084. const items = stack;
  3085. stack = marker.pop();
  3086. stack.push(items);
  3087. break;
  3088. }
  3089. case 100: { // DICT 'd'
  3090. const items = stack;
  3091. stack = marker.pop();
  3092. const dict = new builtins.dict();
  3093. for (let i = 0; i < items.length; i += 2) {
  3094. dict.__setitem__(items[i], items[i + 1]);
  3095. }
  3096. stack.push(dict);
  3097. break;
  3098. }
  3099. case 108: { // LIST 'l'
  3100. const items = stack;
  3101. stack = marker.pop();
  3102. stack.push(items);
  3103. break;
  3104. }
  3105. case 116: { // TUPLE 't'
  3106. const items = stack;
  3107. stack = marker.pop();
  3108. stack.push(items);
  3109. break;
  3110. }
  3111. case 133: { // TUPLE1 // '\x85'
  3112. stack.push([stack.pop()]);
  3113. break;
  3114. }
  3115. case 134: { // TUPLE2 '\x86'
  3116. const b = stack.pop();
  3117. const a = stack.pop();
  3118. stack.push([a, b]);
  3119. break;
  3120. }
  3121. case 135: { // TUPLE3 '\x87'
  3122. const c = stack.pop();
  3123. const b = stack.pop();
  3124. const a = stack.pop();
  3125. stack.push([a, b, c]);
  3126. break;
  3127. }
  3128. case 115: { // SETITEM 's'
  3129. const value = stack.pop();
  3130. const key = stack.pop();
  3131. const obj = stack[stack.length - 1];
  3132. if (obj.__setitem__) {
  3133. obj.__setitem__(key, value);
  3134. } else {
  3135. obj[key] = value;
  3136. }
  3137. break;
  3138. }
  3139. case 117: { // SETITEMS 'u'
  3140. const items = stack;
  3141. stack = marker.pop();
  3142. const obj = stack[stack.length - 1];
  3143. if (obj.__setitem__) {
  3144. for (let i = 0; i < items.length; i += 2) {
  3145. obj.__setitem__(items[i], items[i + 1]);
  3146. }
  3147. } else {
  3148. for (let i = 0; i < items.length; i += 2) {
  3149. obj[items[i]] = items[i + 1];
  3150. }
  3151. }
  3152. break;
  3153. }
  3154. case 125: // EMPTY_DICT '}'
  3155. stack.push(new builtins.dict());
  3156. break;
  3157. case 97: { // APPEND 'a'
  3158. const append = stack.pop();
  3159. stack[stack.length - 1].push(append);
  3160. break;
  3161. }
  3162. case 101: { // APPENDS 'e'
  3163. const appends = stack;
  3164. stack = marker.pop();
  3165. const list = stack[stack.length - 1];
  3166. list.push(...appends);
  3167. break;
  3168. }
  3169. case 83: { // STRING 'S'
  3170. const str = reader.line();
  3171. stack.push(str.substr(1, str.length - 2));
  3172. break;
  3173. }
  3174. case 84: // BINSTRING 'T'
  3175. stack.push(reader.string(reader.uint32()));
  3176. break;
  3177. case 85 : // SHORT_BINSTRING 'U'
  3178. stack.push(reader.string(reader.byte()));
  3179. break;
  3180. case 86: // UNICODE 'V'
  3181. stack.push(reader.line());
  3182. break;
  3183. case 88: // BINUNICODE 'X
  3184. stack.push(reader.string(reader.uint32(), 'utf-8'));
  3185. break;
  3186. case 140: // SHORT_BINUNICODE '\x8c' (Protocol 4)
  3187. stack.push(reader.string(reader.byte(), 'utf-8'));
  3188. break;
  3189. case 98: { // BUILD 'b'
  3190. const state = stack.pop();
  3191. let obj = stack.pop();
  3192. if (obj.__setstate__) {
  3193. if (obj.__setstate__.__call__) {
  3194. obj.__setstate__.__call__([obj, state]);
  3195. } else {
  3196. obj.__setstate__(state);
  3197. }
  3198. } else if (ArrayBuffer.isView(state) || Object(state) !== state) {
  3199. obj.__state__ = state;
  3200. } else if (obj instanceof Map && state instanceof Map) {
  3201. for (const [key, value] of state) {
  3202. obj.set(key, value);
  3203. }
  3204. } else if (obj instanceof Map) {
  3205. for (const key in state) {
  3206. obj.set(key, state[key]);
  3207. }
  3208. } else if (state instanceof Map) {
  3209. for (const [key, value] of state) {
  3210. obj[key] = value;
  3211. }
  3212. } else {
  3213. Object.assign(obj, state);
  3214. }
  3215. if (obj.__read__) {
  3216. obj = obj.__read__(this);
  3217. }
  3218. stack.push(obj);
  3219. break;
  3220. }
  3221. case 40: // MARK '('
  3222. marker.push(stack);
  3223. stack = [];
  3224. break;
  3225. case 136: // NEWTRUE '\x88'
  3226. stack.push(true);
  3227. break;
  3228. case 137: // NEWFALSE '\x89'
  3229. stack.push(false);
  3230. break;
  3231. case 138: { // LONG1 '\x8a'
  3232. const data = reader.read(reader.byte());
  3233. let number = 0;
  3234. switch (data.length) {
  3235. case 0: number = 0; break;
  3236. /* eslint-disable prefer-destructuring */
  3237. case 1: number = data[0]; break;
  3238. /* eslint-enable prefer-destructuring */
  3239. case 2: number = data[1] << 8 | data[0]; break;
  3240. case 3: number = data[2] << 16 | data[1] << 8 | data[0]; break;
  3241. case 4: number = data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]; break;
  3242. case 5: number = data[4] * 0x100000000 + ((data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]) >>> 0); break;
  3243. default: number = Array.prototype.slice.call(data, 0); break;
  3244. }
  3245. stack.push(number);
  3246. break;
  3247. }
  3248. case 139: // LONG4 '\x8b'
  3249. // decode LONG4
  3250. stack.push(reader.read(reader.uint32()));
  3251. break;
  3252. case 148: // MEMOIZE '\x94' (Protocol 4)
  3253. memo[size++] = stack[stack.length - 1];
  3254. break;
  3255. case 149: // FRAME '\x95' (Protocol 4)
  3256. reader.read(8);
  3257. break;
  3258. case 150: { // BYTEARRAY8 '\x96' (Protocol 5)
  3259. stack.push(reader.read(reader.int64().toNumber()));
  3260. break;
  3261. }
  3262. case 78: // NONE 'N'
  3263. stack.push(null);
  3264. break;
  3265. case 46: // STOP '.'
  3266. return stack.pop();
  3267. case 141: // BINUNICODE8 '\x8d' (Protocol 4)
  3268. case 151: // NEXT_BUFFER '\x97' (Protocol 5)
  3269. case 152: // READONLY_BUFFER '\x98' (Protocol 5)
  3270. default:
  3271. throw new python.Error(`Unknown opcode ${opcode} at position ${(reader.position - 1)}.`);
  3272. }
  3273. }
  3274. throw new python.Error('Unexpected end of file.');
  3275. }
  3276. find_class(module, name) {
  3277. execution.__import__(module);
  3278. return execution.resolve(`${module}.${name}`);
  3279. }
  3280. _instantiate(cls, args) {
  3281. return execution.invoke(cls, args);
  3282. }
  3283. _newobj(cls, args) {
  3284. // cls.__new__(cls, args)
  3285. return execution.invoke(cls, args);
  3286. }
  3287. _reduce(func, args) {
  3288. return execution.invoke(func, args);
  3289. }
  3290. read(size) {
  3291. return this._reader.read(size);
  3292. }
  3293. stream(size) {
  3294. return this._reader.stream(size);
  3295. }
  3296. });
  3297. this.registerType('random.Random', class {});
  3298. this.registerType('re.Pattern', class {
  3299. constructor(pattern, flags) {
  3300. this.pattern = pattern;
  3301. this.flags = flags;
  3302. }
  3303. });
  3304. this.registerType('spacy._ml.PrecomputableAffine', class {
  3305. __setstate__(state) {
  3306. Object.assign(this, new pickle.Unpickler(state).load());
  3307. }
  3308. });
  3309. this.registerType('spacy.syntax._parser_model.ParserModel', class {
  3310. __setstate__(state) {
  3311. Object.assign(this, new pickle.Unpickler(state).load());
  3312. }
  3313. });
  3314. this.registerType('theano.compile.function_module._constructor_Function', class {});
  3315. this.registerType('theano.compile.function_module._constructor_FunctionMaker', class {});
  3316. this.registerType('theano.compile.function_module.Function', class {});
  3317. this.registerType('theano.compile.function_module.Supervisor', class {});
  3318. this.registerType('theano.compile.io.In', class {});
  3319. this.registerType('theano.compile.io.SymbolicOutput', class {});
  3320. this.registerType('theano.compile.mode.Mode', class {});
  3321. this.registerType('theano.compile.ops.OutputGuard', class {});
  3322. this.registerType('theano.compile.ops.Shape', class {});
  3323. this.registerType('theano.compile.ops.Shape_i', class {});
  3324. this.registerType('theano.gof.destroyhandler.DestroyHandler', class {});
  3325. this.registerType('theano.gof.fg.FunctionGraph', class {});
  3326. this.registerType('theano.gof.graph.Apply', class {});
  3327. this.registerType('theano.gof.link.Container', class {});
  3328. this.registerType('theano.gof.opt._metadict', class {});
  3329. this.registerType('theano.gof.opt.ChangeTracker', class {});
  3330. this.registerType('theano.gof.opt.MergeFeature', class {});
  3331. this.registerType('theano.gof.optdb.Query', class {});
  3332. this.registerType('theano.gof.toolbox.PreserveVariableAttributes', class {});
  3333. this.registerType('theano.gof.toolbox.ReplaceValidate', class {});
  3334. this.registerType('theano.gof.utils.scratchpad', class {});
  3335. this.registerType('theano.misc.ordered_set.Link', class {});
  3336. this.registerType('theano.misc.ordered_set.OrderedSet', class {});
  3337. this.registerType('theano.sandbox.cuda.basic_ops.HostFromGpu', class {});
  3338. this.registerType('theano.sandbox.cuda.type.CudaNdarray_unpickler', class {});
  3339. this.registerType('theano.sandbox.cuda.type.CudaNdarrayType', class {});
  3340. this.registerType('theano.sandbox.cuda.var.CudaNdarraySharedVariable', class {});
  3341. this.registerType('theano.scalar.basic.Abs', class {});
  3342. this.registerType('theano.scalar.basic.Add', class {});
  3343. this.registerType('theano.scalar.basic.Cast', class {});
  3344. this.registerType('theano.scalar.basic.Composite', class {});
  3345. this.registerType('theano.scalar.basic.EQ', class {});
  3346. this.registerType('theano.scalar.basic.GE', class {});
  3347. this.registerType('theano.scalar.basic.Identity', class {});
  3348. this.registerType('theano.scalar.basic.IntDiv', class {});
  3349. this.registerType('theano.scalar.basic.Inv', class {});
  3350. this.registerType('theano.scalar.basic.LE', class {});
  3351. this.registerType('theano.scalar.basic.LT', class {});
  3352. this.registerType('theano.scalar.basic.Mul', class {});
  3353. this.registerType('theano.scalar.basic.Neg', class {});
  3354. this.registerType('theano.scalar.basic.Pow', class {});
  3355. this.registerType('theano.scalar.basic.Scalar', class {});
  3356. this.registerType('theano.scalar.basic.ScalarConstant', class {});
  3357. this.registerType('theano.scalar.basic.ScalarVariable', class {});
  3358. this.registerType('theano.scalar.basic.Second', class {});
  3359. this.registerType('theano.scalar.basic.Sgn', class {});
  3360. this.registerType('theano.scalar.basic.specific_out', class {});
  3361. this.registerType('theano.scalar.basic.Sub', class {});
  3362. this.registerType('theano.scalar.basic.Switch', class {});
  3363. this.registerType('theano.scalar.basic.Tanh', class {});
  3364. this.registerType('theano.scalar.basic.transfer_type', class {});
  3365. this.registerType('theano.scalar.basic.TrueDiv', class {});
  3366. this.registerType('theano.tensor.basic.Alloc', class {});
  3367. this.registerType('theano.tensor.basic.Dot', class {});
  3368. this.registerType('theano.tensor.basic.MaxAndArgmax', class {});
  3369. this.registerType('theano.tensor.basic.Reshape', class {});
  3370. this.registerType('theano.tensor.basic.ScalarFromTensor', class {});
  3371. this.registerType('theano.tensor.blas.Dot22', class {});
  3372. this.registerType('theano.tensor.blas.Dot22Scalar', class {});
  3373. this.registerType('theano.tensor.blas.Gemm', class {});
  3374. this.registerType('theano.tensor.elemwise.DimShuffle', class {});
  3375. this.registerType('theano.tensor.elemwise.Elemwise', class {});
  3376. this.registerType('theano.tensor.elemwise.Sum', class {});
  3377. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d', class {});
  3378. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d_gradInputs', class {});
  3379. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d_gradWeights', class {});
  3380. this.registerType('theano.tensor.nnet.corr.CorrMM', class {});
  3381. this.registerType('theano.tensor.nnet.corr.CorrMM_gradInputs', class {});
  3382. this.registerType('theano.tensor.nnet.corr.CorrMM_gradWeights', class {});
  3383. this.registerType('theano.tensor.nnet.nnet.CrossentropyCategorical1Hot', class {});
  3384. this.registerType('theano.tensor.nnet.nnet.CrossentropyCategorical1HotGrad', class {});
  3385. this.registerType('theano.tensor.nnet.nnet.CrossentropySoftmax1HotWithBiasDx', class {});
  3386. this.registerType('theano.tensor.nnet.nnet.CrossentropySoftmaxArgmax1HotWithBias', class {});
  3387. this.registerType('theano.tensor.nnet.nnet.Softmax', class {});
  3388. this.registerType('theano.tensor.nnet.nnet.SoftmaxGrad', class {});
  3389. this.registerType('theano.tensor.nnet.nnet.SoftmaxWithBias', class {});
  3390. this.registerType('theano.tensor.opt.MakeVector', class {});
  3391. this.registerType('theano.tensor.opt.ShapeFeature', class {});
  3392. this.registerType('theano.tensor.sharedvar.TensorSharedVariable', class {});
  3393. this.registerType('theano.tensor.signal.pool.MaxPoolGrad', class {});
  3394. this.registerType('theano.tensor.signal.pool.Pool', class {});
  3395. this.registerType('theano.tensor.subtensor.Subtensor', class {});
  3396. this.registerType('theano.tensor.type.TensorType', class {});
  3397. this.registerType('theano.tensor.var.TensorConstant', class {});
  3398. this.registerType('theano.tensor.var.TensorConstantSignature', class {});
  3399. this.registerType('theano.tensor.var.TensorVariable', class {});
  3400. this.registerType('thinc.describe.Biases', class {});
  3401. this.registerType('thinc.describe.Dimension', class {});
  3402. this.registerType('thinc.describe.Gradient', class {});
  3403. this.registerType('thinc.describe.Weights', class {});
  3404. this.registerType('thinc.describe.Synapses', class {});
  3405. this.registerType('thinc.neural._classes.affine.Affine', class {
  3406. __setstate__(state) {
  3407. Object.assign(this, new pickle.Unpickler(state).load());
  3408. }
  3409. });
  3410. this.registerType('thinc.neural._classes.convolution.ExtractWindow', class {
  3411. __setstate__(state) {
  3412. Object.assign(this, new pickle.Unpickler(state).load());
  3413. }
  3414. });
  3415. this.registerType('thinc.neural._classes.feature_extracter.FeatureExtracter', class {
  3416. __setstate__(state) {
  3417. Object.assign(this, new pickle.Unpickler(state).load());
  3418. }
  3419. });
  3420. this.registerType('thinc.neural._classes.feed_forward.FeedForward', class {
  3421. __setstate__(state) {
  3422. Object.assign(this, new pickle.Unpickler(state).load());
  3423. }
  3424. });
  3425. this.registerType('thinc.neural._classes.function_layer.FunctionLayer', class {
  3426. __setstate__(state) {
  3427. Object.assign(this, new pickle.Unpickler(state).load());
  3428. }
  3429. });
  3430. this.registerType('thinc.neural._classes.hash_embed.HashEmbed', class {
  3431. __setstate__(state) {
  3432. Object.assign(this, new pickle.Unpickler(state).load());
  3433. }
  3434. });
  3435. this.registerType('thinc.neural._classes.layernorm.LayerNorm', class {
  3436. __setstate__(state) {
  3437. Object.assign(this, new pickle.Unpickler(state).load());
  3438. }
  3439. });
  3440. this.registerType('thinc.neural._classes.maxout.Maxout', class {
  3441. __setstate__(state) {
  3442. Object.assign(this, new pickle.Unpickler(state).load());
  3443. }
  3444. });
  3445. this.registerType('thinc.neural._classes.resnet.Residual', class {
  3446. __setstate__(state) {
  3447. Object.assign(this, new pickle.Unpickler(state).load());
  3448. }
  3449. });
  3450. this.registerType('thinc.neural._classes.softmax.Softmax', class {
  3451. __setstate__(state) {
  3452. Object.assign(this, new pickle.Unpickler(state).load());
  3453. }
  3454. });
  3455. this.registerType('thinc.neural.mem.Memory', class {
  3456. });
  3457. this.registerType('thinc.neural.ops.NumpyOps', class {
  3458. });
  3459. this.registerType('__main__.BYOLState', class {
  3460. constructor(dict) {
  3461. Object.assign(this, dict);
  3462. }
  3463. });
  3464. this.registerType('types.GenericAlias', class {});
  3465. this.registerType('types.SimpleNamespace', class {});
  3466. const types = this.register('types');
  3467. types.ObjectType = builtins.object;
  3468. types.ModuleType = builtins.module;
  3469. types.MethodType = builtins.method;
  3470. types.FunctionType = builtins.function;
  3471. types.TypeType = builtins.type;
  3472. types.CodeType = builtins.code;
  3473. this.registerType('xgboost.compat.XGBoostLabelEncoder', class {});
  3474. this.registerType('xgboost.core.Booster', class {});
  3475. this.registerType('xgboost.sklearn.XGBClassifier', class {});
  3476. this.registerType('xgboost.sklearn.XGBRegressor', class {});
  3477. this.registerFunction('_codecs.encode', (obj, encoding) => {
  3478. return execution.invoke('builtins.bytearray', [obj, encoding]);
  3479. });
  3480. this.registerType('builtins.bytearray', class extends Uint8Array {
  3481. constructor(source, encoding /*, errors */) {
  3482. source = builtins.bytes.__encode__(source, encoding);
  3483. super(Number.isInteger(source) ? source : source.length);
  3484. if (Array.isArray(source)) {
  3485. for (let i = 0; i < source.length; i++) {
  3486. this[i] = source;
  3487. }
  3488. } else if (source instanceof Uint8Array) {
  3489. this.set(source, 0);
  3490. } else if (typeof source === 'string') {
  3491. for (let i = 0; i < source.length; i++) {
  3492. this[i] = source.charCodeAt(i);
  3493. }
  3494. }
  3495. }
  3496. static __encode__(source, encoding) {
  3497. if (source === undefined) {
  3498. return 0;
  3499. }
  3500. if (Number.isInteger(source)) {
  3501. return source;
  3502. }
  3503. if (Array.isArray(source) || source instanceof Uint8Array) {
  3504. return source;
  3505. }
  3506. if (typeof source === 'string') {
  3507. switch (encoding) {
  3508. case 'latin1':
  3509. case 'latin-1':
  3510. return source;
  3511. case 'utf8':
  3512. case 'utf-8':
  3513. return new TextEncoder('utf-8').encode(source);
  3514. case undefined:
  3515. throw new python.Error('Unsupported string argument without an encoding.');
  3516. default:
  3517. throw new python.Error(`Unsupported encoding '${encoding}'.`);
  3518. }
  3519. }
  3520. throw new python.Error('Unsupported source.');
  3521. }
  3522. });
  3523. this.registerType('builtins.bytes', class extends Uint8Array {
  3524. constructor(source, encoding /*, errors */) {
  3525. source = builtins.bytes.__encode__(source, encoding);
  3526. super(Number.isInteger(source) ? source : source.length);
  3527. if (Array.isArray(source)) {
  3528. for (let i = 0; i < source.length; i++) {
  3529. this[i] = source;
  3530. }
  3531. } else if (source instanceof Uint8Array) {
  3532. this.set(source, 0);
  3533. } else if (typeof source === 'string') {
  3534. for (let i = 0; i < source.length; i++) {
  3535. this[i] = source.charCodeAt(i);
  3536. }
  3537. }
  3538. }
  3539. static __encode__(source, encoding) {
  3540. if (source === undefined) {
  3541. return 0;
  3542. }
  3543. if (Number.isInteger(source)) {
  3544. return source;
  3545. }
  3546. if (Array.isArray(source) || source instanceof Uint8Array) {
  3547. return source;
  3548. }
  3549. if (typeof source === 'string') {
  3550. switch (encoding) {
  3551. case 'latin1':
  3552. case 'latin-1':
  3553. return source;
  3554. case 'utf8':
  3555. case 'utf-8':
  3556. return new TextEncoder('utf-8').encode(source);
  3557. case undefined:
  3558. throw new python.Error('Unsupported string argument without an encoding.');
  3559. default:
  3560. throw new python.Error(`Unsupported encoding '${encoding}'.`);
  3561. }
  3562. }
  3563. throw new python.Error('Unsupported source.');
  3564. }
  3565. });
  3566. this.registerType('builtins.frozenset', class extends Set {
  3567. constructor(iterable) {
  3568. super();
  3569. if (iterable) {
  3570. for (const item of iterable) {
  3571. this.add(item);
  3572. }
  3573. }
  3574. }
  3575. });
  3576. this.registerFunction('builtins.exec');
  3577. this.registerFunction('builtins.issubclass', (obj, type) => {
  3578. const name = `${type.__module__}.${type.__name__}`;
  3579. if (obj.__module__ && obj.__name__) {
  3580. if (name === `${obj.__module__}.${obj.__name__}`) {
  3581. return true;
  3582. }
  3583. }
  3584. if (obj.__bases__) {
  3585. for (const base of obj.__bases__) {
  3586. if (builtins.issubclass(base, type)) {
  3587. return true;
  3588. }
  3589. }
  3590. }
  3591. return false;
  3592. });
  3593. this.registerFunction('builtins.isinstance', (obj, type) => {
  3594. return obj.__class__ ? builtins.issubclass(obj.__class__, type) : false;
  3595. });
  3596. this.registerFunction('builtins.hasattr', (obj, name) => {
  3597. if (obj instanceof Map && obj.__contains__) {
  3598. return obj.__contains__(name);
  3599. }
  3600. return Object.prototype.hasOwnProperty.call(obj, name);
  3601. });
  3602. this.registerFunction('builtins.getattr', (obj, name, defaultValue) => {
  3603. if (Object.prototype.hasOwnProperty.call(obj, name)) {
  3604. return obj[name];
  3605. }
  3606. if (obj && obj.__getattr__) {
  3607. return obj.__getattr__(name);
  3608. }
  3609. return defaultValue;
  3610. });
  3611. this.registerFunction('builtins.setattr', (obj, name, value) => {
  3612. obj[name] = value;
  3613. });
  3614. this.registerType('builtins.set', class extends Set {});
  3615. this.registerType('builtins.slice', class {
  3616. constructor(start, stop, step) {
  3617. this.start = start;
  3618. this.stop = stop;
  3619. this.step = step;
  3620. }
  3621. });
  3622. this.registerFunction('builtins.hash');
  3623. this.registerFunction('cloudpickle.cloudpickle._builtin_type', (name) => {
  3624. return name;
  3625. });
  3626. this.registerFunction('cloudpickle.cloudpickle._fill_function');
  3627. this.registerFunction('cloudpickle.cloudpickle._make_cell');
  3628. this.registerFunction('cloudpickle.cloudpickle._make_empty_cell');
  3629. this.registerFunction('cloudpickle.cloudpickle._make_function');
  3630. this.registerFunction('cloudpickle.cloudpickle._make_skel_func');
  3631. this.registerFunction('cloudpickle.cloudpickle._make_skeleton_class');
  3632. this.registerFunction('cloudpickle.cloudpickle.subimport');
  3633. this.registerFunction('cloudpickle.cloudpickle_fast._class_setstate');
  3634. this.registerFunction('cloudpickle.cloudpickle_fast._function_setstate');
  3635. this.registerType('collections.Counter', class {});
  3636. this.registerFunction('collections.defaultdict', (/* default_factory */) => {
  3637. return {};
  3638. });
  3639. this.registerFunction('copy_reg._reconstructor', (cls, base, state) => {
  3640. // copyreg._reconstructor in Python 3
  3641. if (base === '__builtin__.object' || base === self._builtins.object) {
  3642. return self.invoke(cls, []);
  3643. } else if (base === '__builtin__.tuple' || base === self._builtins.tuple) {
  3644. const obj = self.invoke(cls, []);
  3645. for (let i = 0; i < state.length; i++) {
  3646. obj[i] = state[i];
  3647. }
  3648. return obj;
  3649. }
  3650. throw new python.Error(`Unsupported copy_reg._reconstructor base type '${base}'.`);
  3651. });
  3652. this.registerFunction('copy.deepcopy', (/* x */) => {
  3653. throw new python.Error('Unsupported copy.deepcopy().');
  3654. });
  3655. this.registerFunction('dill._dill._create_array', (f, args, state, npdict) => {
  3656. const array = f(...args);
  3657. if (array.__setstate__) {
  3658. array.__setstate__(state);
  3659. }
  3660. if (npdict) {
  3661. throw new python.Error("'dill._dill._create_array::npdict' not implemented.");
  3662. }
  3663. return array;
  3664. });
  3665. this.registerFunction('dill._dill._create_cell', (/* args */) => {
  3666. return function() {
  3667. };
  3668. });
  3669. this.registerFunction('dill._dill._create_code', (args) => {
  3670. return self.invoke('types.CodeType', [args]);
  3671. });
  3672. this.registerFunction('dill._dill._create_function', (/* fcode, fglobals, fname, fdefaults, fclosure, fdict, fkwdefaults */) => {
  3673. return function() {
  3674. };
  3675. });
  3676. this.registerFunction('dill._dill._create_namedtuple', (name, fieldnames, modulename /*, defaults */) => {
  3677. const obj = execution.invoke('dill._dill._import_module', [`${modulename}.${name}`]);
  3678. if (obj) {
  3679. return obj;
  3680. }
  3681. return undefined;
  3682. });
  3683. this.registerFunction('dill._dill._create_type', (typeobj, ...args) => {
  3684. const [name, bases, dict] = args;
  3685. const type = class extends bases[0] {};
  3686. const identifier = dict.__contains__('__module__') ? `${dict.__getitem__('__module__')}.${name}` : name;
  3687. return self.registerType(identifier, Object.assign(type, dict));
  3688. });
  3689. this.registerFunction('dill._dill._eval_repr');
  3690. this.registerFunction('dill._dill._get_attr', (self, name) => {
  3691. if (Object.prototype.hasOwnProperty.call(self, name)) {
  3692. return self[name];
  3693. }
  3694. return undefined;
  3695. });
  3696. this.registerFunction('dill._dill._import_module', (import_name, safe) => {
  3697. try {
  3698. if (import_name.startsWith('__runtime__.')) {
  3699. return execution.module(import_name);
  3700. } else if (import_name.indexOf('.') === -1) {
  3701. return execution.__import__(import_name);
  3702. }
  3703. return execution.resolve(import_name);
  3704. } catch (error) {
  3705. if (safe) {
  3706. return null;
  3707. }
  3708. throw error;
  3709. }
  3710. });
  3711. this.registerFunction('dill._dill._load_type', (name) => {
  3712. const _dill = self.register('dill._dill');
  3713. if (!_dill._reverse_typemap) {
  3714. _dill._reverse_typemap = new Map();
  3715. for (const name of ['__builtin__', 'types']) {
  3716. const module = self.register(name);
  3717. for (const [name, obj] of Object.entries(module)) {
  3718. if (obj.__module__ === 'builtins' && obj.__class__ === builtins.type) {
  3719. _dill._reverse_typemap.set(name, obj);
  3720. }
  3721. }
  3722. }
  3723. _dill._reverse_typemap.set('PartialType', functools.partial);
  3724. _dill._reverse_typemap.set('CellType', builtins.cell);
  3725. }
  3726. if (!_dill._reverse_typemap.has(name)) {
  3727. throw new python.Error(`Unknown type name '${name}' in 'dill._dill._load_type'.`);
  3728. }
  3729. return _dill._reverse_typemap.get(name);
  3730. });
  3731. this.registerFunction('dill._dill.loads');
  3732. this.registerFunction('jax._src.array._reconstruct_array', (fun, args, arr_state, aval_state) => {
  3733. const np_value = fun(...args);
  3734. np_value.__setstate__(arr_state);
  3735. const jnp_value = jax.device_put(np_value);
  3736. jnp_value.aval = jnp_value.aval.update(aval_state);
  3737. return jnp_value;
  3738. });
  3739. jax._src.device_array.reconstruct_device_array = jax._src.array._reconstruct_array;
  3740. this.registerFunction('jax.device_put', (x) => {
  3741. const aval = new jax._src.core.ShapedArray(x.shape, x.dtype);
  3742. return new jax.Array(aval, x.data);
  3743. });
  3744. this.registerType('jax._src.core.AbstractValue', class {});
  3745. this.registerType('jax._src.core.UnshapedArray', class extends jax._src.core.AbstractValue {});
  3746. this.registerType('jax._src.core.ShapedArray', class extends jax._src.core.UnshapedArray {
  3747. constructor(shape, dtype, weak_type) {
  3748. super();
  3749. this.shape = shape;
  3750. this.dtype = dtype;
  3751. this.weak_type = weak_type || false;
  3752. }
  3753. update(dict) {
  3754. const shape = dict.get('shape') || this.shape;
  3755. const dtype = dict.get('dtype') || this.dtype;
  3756. const weak_type = dict.get('weak_type') || this.weak_type;
  3757. return new jax._src.core.ShapedArray(shape, dtype, weak_type);
  3758. }
  3759. });
  3760. this.registerType('jax.Array', class {
  3761. constructor(aval, data) {
  3762. this.aval = aval;
  3763. this.data = data;
  3764. }
  3765. get dtype() {
  3766. return this.aval.dtype;
  3767. }
  3768. get shape() {
  3769. return this.aval.shape;
  3770. }
  3771. tobytes() {
  3772. return this.data;
  3773. }
  3774. });
  3775. jax.numpy.ndarray = jax.Array;
  3776. this.registerFunction('keras.saving.pickle_utils.deserialize_model_from_bytecode', (/* serialized_model */) => {
  3777. return null; // throw new python.Error("'keras.saving.pickle_utils.deserialize_model_from_bytecode' not implemented.");
  3778. });
  3779. this.registerFunction('keras.src.saving.pickle_utils.deserialize_model_from_bytecode', keras.saving.pickle_utils.deserialize_model_from_bytecode);
  3780. this.registerFunction('lasagne.nonlinearities.rectify');
  3781. this.registerFunction('lasagne.nonlinearities.softmax');
  3782. this.registerFunction('lasagne.objectives.categorical_crossentropy');
  3783. this.registerFunction('lasagne.updates.nesterov_momentum');
  3784. this.registerFunction('msgpack.unpackb', (packed, ext_hook) => {
  3785. const BinaryReader = class {
  3786. constructor(buffer, ext_hook) {
  3787. // https://github.com/msgpack/msgpack-javascript/blob/master/src/Decoder.ts
  3788. // https://github.com/msgpack/msgpack-python/blob/main/msgpack/_unpacker.pyx
  3789. this._buffer = buffer;
  3790. this._position = 0;
  3791. this._view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  3792. this._ext_hook = ext_hook;
  3793. }
  3794. value() {
  3795. const c = this._view.getUint8(this.skip(1));
  3796. if (c >= 0xe0) {
  3797. return c - 0x100;
  3798. }
  3799. if (c < 0xC0) {
  3800. if (c < 0x80) {
  3801. return c;
  3802. }
  3803. if (c < 0x90) {
  3804. return this.map(c - 0x80);
  3805. }
  3806. if (c < 0xa0) {
  3807. return this.array(c - 0x90);
  3808. }
  3809. return this.string(c - 0xa0);
  3810. }
  3811. switch (c) {
  3812. case 0xC0: return null;
  3813. case 0xC2: return false;
  3814. case 0xC3: return true;
  3815. case 0xC4: return this.read(this._view.getUint8(this.skip(1)));
  3816. case 0xC5: return this.read(this._view.getUint16(this.skip(2)));
  3817. case 0xC6: return this.read(this._view.getUint32(this.skip(4)));
  3818. case 0xC7: return this.extension(this._view.getUint8(this.skip(1)));
  3819. case 0xC8: return this.extension(this._view.getUint16(this.skip(2)));
  3820. case 0xC9: return this.extension(this._view.getUint32(this.skip(4)));
  3821. case 0xCA: return this._view.getFloat32(this.skip(4));
  3822. case 0xCB: return this._view.getFloat64(this.skip(8));
  3823. case 0xCC: return this._view.getUint8(this.skip(1));
  3824. case 0xCD: return this._view.getUint16(this.skip(2));
  3825. case 0xCE: return this._view.getUint32(this.skip(4));
  3826. case 0xCF: return this._view.getBitUint64(this.skip(8));
  3827. case 0xD0: return this._view.getInt8(this.skip(1));
  3828. case 0xD1: return this._view.getInt16(this.skip(2));
  3829. case 0xD2: return this._view.getInt32(this.skip(4));
  3830. case 0xD3: return this._view.getBigInt64(this.skip(8));
  3831. case 0xD4: return this.extension(1);
  3832. case 0xD5: return this.extension(2);
  3833. case 0xD6: return this.extension(4);
  3834. case 0xD7: return this.extension(8);
  3835. case 0xD8: return this.extension(16);
  3836. case 0xD9: return this.string(this._view.getUint8(this.skip(1)));
  3837. case 0xDA: return this.string(this._view.getUint16(this.skip(2)));
  3838. case 0xDB: return this.string(this._view.getUint32(this.skip(4)));
  3839. case 0xDC: return this.array(this._view.getUint16(this.skip(2)));
  3840. case 0xDD: return this.array(this._view.getUint32(this.skip(4)));
  3841. case 0xDE: return this.map(this._view.getUint16(this.skip(2)));
  3842. case 0xDF: return this.map(this._view.getUint32(this.skip(4)));
  3843. default: throw new python.Error(`Invalid code '${c}'.`);
  3844. }
  3845. }
  3846. map(size) {
  3847. const map = {};
  3848. for (let i = 0; i < size; i++) {
  3849. const key = this.value();
  3850. const value = this.value();
  3851. map[key] = value;
  3852. }
  3853. return map;
  3854. }
  3855. array(size) {
  3856. const array = new Array(size);
  3857. for (let i = 0; i < size; i++) {
  3858. array[i] = this.value();
  3859. }
  3860. return array;
  3861. }
  3862. extension(size) {
  3863. const code = this._view.getUint8(this.skip(1));
  3864. const data = this.read(size);
  3865. return this._ext_hook(code, data);
  3866. }
  3867. skip(offset) {
  3868. const position = this._position;
  3869. this._position += offset;
  3870. if (this._position > this._buffer.length) {
  3871. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  3872. }
  3873. return position;
  3874. }
  3875. read(size) {
  3876. const data = this._buffer.subarray(this._position, this._position + size);
  3877. this._position += size;
  3878. return data;
  3879. }
  3880. string(size) {
  3881. const buffer = this.read(size);
  3882. this._decoder = this._decoder || new TextDecoder('utf8');
  3883. return this._decoder.decode(buffer);
  3884. }
  3885. };
  3886. return new BinaryReader(packed, ext_hook).value();
  3887. });
  3888. this.registerFunction('nolearn.lasagne.base.objective');
  3889. this.registerFunction('numpy.core._DType_reconstruct');
  3890. this.registerFunction('numpy.core._ufunc_reconstruct');
  3891. this.registerFunction('numpy.core.numeric._frombuffer', (/* buf, dtype, shape, order */) => {
  3892. return {};
  3893. });
  3894. this.registerFunction('numpy._core.multiarray._reconstruct', (subtype, shape, dtype) => {
  3895. return numpy.ndarray.__new__(subtype, shape, dtype);
  3896. });
  3897. this.registerFunction('numpy._core.numeric._frombuffer');
  3898. this.registerFunction('numpy._core._internal._convert_to_stringdtype_kwargs', () => {
  3899. return new numpy.dtypes.StringDType();
  3900. });
  3901. this.registerFunction('numpy._core.multiarray.scalar', (dtype, rawData) => {
  3902. let data = rawData;
  3903. if (typeof rawData === 'string' || rawData instanceof String) {
  3904. data = new Uint8Array(rawData.length);
  3905. for (let i = 0; i < rawData.length; i++) {
  3906. data[i] = rawData.charCodeAt(i);
  3907. }
  3908. }
  3909. switch (dtype.kind) {
  3910. case 'b': {
  3911. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  3912. switch (dtype.itemsize) {
  3913. case 1: return view.getInt8(0) ? true : false;
  3914. default: throw new python.Error(`Unsupported scalar dtype boolean itemsize '${dtype.itemsize}'.`);
  3915. }
  3916. }
  3917. case 'f': {
  3918. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  3919. switch (dtype.itemsize) {
  3920. case 2: return view.getFloat16(0, dtype.byteorder === '<');
  3921. case 4: return view.getFloat32(0, dtype.byteorder === '<');
  3922. case 8: return view.getFloat64(0, dtype.byteorder === '<');
  3923. default: throw new python.Error(`Unsupported scalar dtype float itemsize '${dtype.itemsize}'.`);
  3924. }
  3925. }
  3926. case 'i': {
  3927. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  3928. switch (dtype.itemsize) {
  3929. case 1: return view.getInt8(0);
  3930. case 2: return view.getInt16(0, dtype.byteorder === '<');
  3931. case 4: return view.getInt32(0, dtype.byteorder === '<');
  3932. case 8: return view.getBigInt64(0, dtype.byteorder === '<');
  3933. default: throw new python.Error(`Unsupported scalar dtype int itemsize '${dtype.itemsize}'.`);
  3934. }
  3935. }
  3936. case 'u': {
  3937. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  3938. switch (dtype.itemsize) {
  3939. case 1: return view.getUint8(0);
  3940. case 2: return view.getUint16(0, dtype.byteorder === '<');
  3941. case 4: return view.getUint32(0, dtype.byteorder === '<');
  3942. case 8: return view.getBigUint64(0, dtype.byteorder === '<');
  3943. default: throw new python.Error(`Unsupported scalar dtype uint itemsize '${dtype.itemsize}'.`);
  3944. }
  3945. }
  3946. case 'U': {
  3947. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  3948. const list = [];
  3949. for (let i = 0; i < dtype.itemsize; i += 4) {
  3950. list.push(String.fromCodePoint(view.getUint32(i, true)));
  3951. }
  3952. return list.join('');
  3953. }
  3954. default: {
  3955. throw new python.Error(`Unsupported scalar dtype kind '${dtype.kind}'.`);
  3956. }
  3957. }
  3958. });
  3959. numpy.core.multiarray._reconstruct = numpy._core.multiarray._reconstruct;
  3960. numpy.core.multiarray.scalar = numpy._core.multiarray.scalar;
  3961. numpy.core._multiarray_umath._reconstruct = numpy.core.multiarray._reconstruct;
  3962. this.registerFunction('numpy.core._multiarray_umath.cbrt');
  3963. this.registerFunction('numpy.core._multiarray_umath.greater');
  3964. this.registerFunction('numpy.core._multiarray_umath.less');
  3965. this.registerFunction('numpy.core._multiarray_umath.log');
  3966. this.registerFunction('numpy.core._multiarray_umath.scalar', (dtype, rawData) => {
  3967. let data = rawData;
  3968. if (typeof rawData === 'string') {
  3969. data = new Uint8Array(rawData.length);
  3970. for (let i = 0; i < rawData.length; i++) {
  3971. data[i] = rawData.charCodeAt(i);
  3972. }
  3973. }
  3974. const dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
  3975. switch (dtype.__name__) {
  3976. case 'uint8':
  3977. return dataView.getUint8(0);
  3978. case 'float32':
  3979. return dataView.getFloat32(0, true);
  3980. case 'float64':
  3981. return dataView.getFloat64(0, true);
  3982. case 'int8':
  3983. return dataView.getInt8(0, true);
  3984. case 'int16':
  3985. return dataView.getInt16(0, true);
  3986. case 'int32':
  3987. return dataView.getInt32(0, true);
  3988. case 'int64':
  3989. return dataView.getBigInt64(0, true);
  3990. default:
  3991. throw new python.Error(`Unsupported scalar type '${dtype.__name__}'.`);
  3992. }
  3993. });
  3994. this.registerFunction('numpy.core._multiarray_umath.sqrt');
  3995. this.registerFunction('numpy.load', (file) => {
  3996. // https://github.com/numpy/numpy/blob/main/numpy/lib/format.py
  3997. const signature = [0x93, 0x4E, 0x55, 0x4D, 0x50, 0x59];
  3998. if (!file.read(6).every((v, i) => v === signature[i])) {
  3999. throw new python.Error('Invalid signature.');
  4000. }
  4001. const version = file.read(2);
  4002. const [major, minor] = version;
  4003. if (major > 3) {
  4004. throw new python.Error(`Invalid version '${[major, minor].join('.')}'.`);
  4005. }
  4006. const buffer = new Uint8Array([0, 0, 0, 0]);
  4007. buffer.set(file.read(major >= 2 ? 4 : 2), 0);
  4008. const header_length = buffer[3] << 24 | buffer[2] << 16 | buffer[1] << 8 | buffer[0];
  4009. let header = file.read(header_length);
  4010. const decoder = new TextDecoder(major >= 3 ? 'utf-8' : 'ascii');
  4011. header = decoder.decode(header);
  4012. header = JSON.parse(header.replace(/\(/,'[').replace(/\)/,']').replace('[,','[1,]').replace(',]',']').replace(/'/g, '"').replace(/:\s*False\s*,/,':false,').replace(/:\s*True\s*,/,':true,').replace(/,\s*\}/, ' }'));
  4013. if (!header.descr || header.descr.length < 2) {
  4014. throw new python.Error("Missing property 'descr'.");
  4015. }
  4016. if (!header.shape) {
  4017. throw new python.Error("Missing property 'shape'.");
  4018. }
  4019. const shape = header.shape;
  4020. const dtype = self.invoke('numpy.dtype', [header.descr.substring(1)]);
  4021. dtype.byteorder = header.descr.substring(0, 1);
  4022. let data = null;
  4023. switch (dtype.byteorder) {
  4024. case '|': {
  4025. data = file.read();
  4026. if (dtype.kind === 'O') {
  4027. const unpickler = execution.invoke('pickle.Unpickler', [data]);
  4028. return unpickler.load();
  4029. }
  4030. break;
  4031. }
  4032. case '>':
  4033. case '<': {
  4034. if (header.descr.length !== 3 && header.descr[1] !== 'U' && header.descr.substring(1) !== 'c16') {
  4035. throw new python.Error(`Unsupported data type '${header.descr}'.`);
  4036. }
  4037. const count = shape.length === 0 ? 1 : shape.reduce((a, b) => a * b, 1);
  4038. data = file.read(dtype.itemsize * count);
  4039. break;
  4040. }
  4041. default: {
  4042. throw new python.Error(`Unsupported data type '${header.descr}'.`);
  4043. }
  4044. }
  4045. if (header.fortran_order) {
  4046. data = null;
  4047. }
  4048. return self.invoke('numpy.ndarray', [shape, dtype, data]);
  4049. });
  4050. this.registerFunction('numpy.save', (file, arr) => {
  4051. const descr = arr.dtype.str;
  4052. if (descr[0] !== '<' && descr[0] !== '>') {
  4053. throw new python.Error(`Unsupported byte order '${descr}'.`);
  4054. }
  4055. if ((descr.length !== 3 && descr.substring(1) !== 'c16') || (descr[1] !== 'f' && descr[1] !== 'i' && descr[1] !== 'u' && descr[1] !== 'c' && descr.substring(1) !== 'b1')) {
  4056. throw new python.Error(`Unsupported data type '${descr}'.`);
  4057. }
  4058. let shape = '';
  4059. switch (arr.shape.length) {
  4060. case 0: shape = '()'; break;
  4061. case 1: shape = `(${arr.shape[0]},)`; break;
  4062. default: shape = `(${arr.shape.map((dimension) => dimension.toString()).join(', ')})`; break;
  4063. }
  4064. const properties = [
  4065. `'descr': '${descr}'`,
  4066. "'fortran_order': False",
  4067. `'shape': ${shape}`
  4068. ];
  4069. let header = `{ ${properties.join(', ')} }`;
  4070. header += `${' '.repeat(64 - ((header.length + 2 + 8 + 1) & 0x3f))}\n`;
  4071. const encoder = new TextEncoder('ascii');
  4072. file.write([0x93, 0x4E, 0x55, 0x4D, 0x50, 0x59, 0x01, 0x00]); // '\\x93NUMPY' + version
  4073. file.write([header.length & 0xff, (header.length >> 8) & 0xff]);
  4074. file.write(encoder.encode(header));
  4075. file.write(arr.tobytes());
  4076. });
  4077. this.registerFunction('numpy.amin');
  4078. this.registerFunction('numpy.amax');
  4079. this.registerFunction('numpy.std');
  4080. this.registerFunction('numpy.asarray', (a, dtype) => {
  4081. const encode = (context, data, dim) => {
  4082. const size = context.shape[dim];
  4083. const littleendian = context.littleendian;
  4084. if (dim === context.shape.length - 1) {
  4085. for (let i = 0; i < size; i++) {
  4086. switch (context.dtype) {
  4087. case 'f2':
  4088. context.view.setFloat16(context.position, data[i], littleendian);
  4089. break;
  4090. case 'f4':
  4091. context.view.setFloat32(context.position, data[i], littleendian);
  4092. break;
  4093. case 'f8':
  4094. context.view.setFloat64(context.position, data[i], littleendian);
  4095. break;
  4096. case 'i1':
  4097. context.view.setInt8(context.position, data[i], littleendian);
  4098. break;
  4099. case 'i2':
  4100. context.view.setInt16(context.position, data[i], littleendian);
  4101. break;
  4102. case 'i4':
  4103. context.view.setInt32(context.position, data[i], littleendian);
  4104. break;
  4105. case 'i8':
  4106. context.view.setBigInt64(context.position, data[i], littleendian);
  4107. break;
  4108. case 'u1':
  4109. context.view.setUint8(context.position, data[i], littleendian);
  4110. break;
  4111. case 'u2':
  4112. context.view.setUint16(context.position, data[i], littleendian);
  4113. break;
  4114. case 'u4':
  4115. context.view.setUint32(context.position, data[i], littleendian);
  4116. break;
  4117. case 'u8':
  4118. context.view.setBigUint64(context.position, data[i], littleendian);
  4119. break;
  4120. case 'c8':
  4121. context.view.setComplex64(context.position, data[i], littleendian);
  4122. break;
  4123. case 'c16':
  4124. context.view.setComplex128(context.position, data[i], littleendian);
  4125. break;
  4126. case 'b1':
  4127. context.view.setInt8(context.position, data[i] ? 1 : 0);
  4128. break;
  4129. default:
  4130. throw new python.Error(`Unsupported tensor data type '${context.dtype}'.`);
  4131. }
  4132. context.position += context.itemsize;
  4133. }
  4134. } else {
  4135. for (let j = 0; j < size; j++) {
  4136. encode(context, data[j], dim + 1);
  4137. }
  4138. }
  4139. };
  4140. const array_size = (value) => {
  4141. if (value.every((item) => Array.isArray(item))) {
  4142. const dims = value.map((item) => array_size(item));
  4143. const [dim] = dims;
  4144. for (let i = 1; i < dims.length; i++) {
  4145. if (dim.length === dims[i].length) {
  4146. if (!dims[i].every((value, i) => value === dim[i])) {
  4147. throw new python.Error('Invalid array shape.');
  4148. }
  4149. }
  4150. }
  4151. return [value.length].concat(dim);
  4152. }
  4153. return [value.length];
  4154. };
  4155. const shape = Array.isArray(a) ? array_size(a) : [];
  4156. const size = dtype.itemsize * shape.reduce((a, b) => a * b, 1);
  4157. const context = {
  4158. position: 0,
  4159. itemsize: dtype.itemsize,
  4160. dtype: dtype.str.substring(1),
  4161. littleendian: dtype.str[0],
  4162. shape,
  4163. data: new Uint8Array(size)
  4164. };
  4165. context.view = new DataView(context.data.buffer, context.data.byteOffset, size);
  4166. encode(context, a, 0);
  4167. return self.invoke('numpy.ndarray', [shape, dtype, context.data]);
  4168. });
  4169. this.registerFunction('numpy.max');
  4170. this.registerFunction('numpy.mean');
  4171. this.registerFunction('numpy.min');
  4172. this.registerFunction('numpy.ma.core._mareconstruct', (subtype, baseclass, baseshape, basetype) => {
  4173. const data = self.invoke(baseclass, [baseshape, basetype]);
  4174. // = ndarray.__new__(ndarray, baseshape, make_mask_descr(basetype))
  4175. const mask = self.invoke('numpy.ndarray', [baseshape, '']);
  4176. return self.invoke(subtype, [data, mask, basetype]);
  4177. });
  4178. this.registerFunction('numpy.random.__RandomState_ctor', () => {
  4179. return {};
  4180. });
  4181. this.registerFunction('numpy.random._pickle.__randomstate_ctor', () => {
  4182. return {};
  4183. });
  4184. this.registerType('numpy.random.bit_generator.BitGenerator', class {});
  4185. this.registerType('numpy.random.bit_generator.SeedSequence', class {});
  4186. this.registerFunction('numpy.random.bit_generator.__pyx_unpickle_SeedSequence');
  4187. this.registerType('numpy.random._mt19937.MT19937', class extends numpy.random.bit_generator.BitGenerator {});
  4188. this.registerType('numpy.random._pcg64.PCG64', class extends numpy.random.bit_generator.BitGenerator {});
  4189. this.registerType('numpy.random._pcg64.PCG64DXSM', class extends numpy.random.bit_generator.BitGenerator {});
  4190. this.registerType('numpy.random._philox.Philox', class extends numpy.random.bit_generator.BitGenerator {});
  4191. this.registerType('numpy.random._sfc64.SFC64', class extends numpy.random.bit_generator.BitGenerator {});
  4192. numpy.random._pickle.BitGenerators = {
  4193. 'MT19937': numpy.random._mt19937.MT19937,
  4194. 'PCG64': numpy.random._pcg64.PCG64,
  4195. 'PCG64DXSM': numpy.random._pcg64.PCG64DXSM,
  4196. 'Philox': numpy.random._philox.Philox,
  4197. 'SFC64': numpy.random._sfc64.SFC64,
  4198. };
  4199. this.registerType('numpy.random._generator.Generator', class {
  4200. constructor(bit_generator) {
  4201. this.bit_generator = bit_generator;
  4202. }
  4203. });
  4204. this.registerFunction('numpy.random._pickle.__bit_generator_ctor', (bit_generator_name) => {
  4205. bit_generator_name = bit_generator_name || 'MT19937';
  4206. const bit_generator = numpy.random._pickle.BitGenerators[bit_generator_name];
  4207. if (bit_generator) {
  4208. return new bit_generator();
  4209. }
  4210. throw new python.Error(`Unknown bit generator '${bit_generator_name}'.`);
  4211. });
  4212. this.registerFunction('numpy.random._pickle.__generator_ctor', (bit_generator_name, bit_generator_ctor) => {
  4213. bit_generator_ctor = bit_generator_ctor || numpy.random._pickle.__bit_generator_ctor;
  4214. return new numpy.random._generator.Generator(bit_generator_ctor(bit_generator_name));
  4215. });
  4216. this.registerFunction('numpy.reshape');
  4217. this.registerFunction('sklearn.feature_selection._univariate_selection.f_classif');
  4218. this.registerFunction('sklearn.feature_selection._univariate_selection.f_regression');
  4219. this.registerFunction('sklearn.metrics.scorer._passthrough_scorer');
  4220. this.registerFunction('sklearn.metrics._classification.accuracy_score');
  4221. this.registerFunction('sklearn.metrics._classification.balanced_accuracy_score');
  4222. this.registerFunction('sklearn.metrics._classification.f1_score');
  4223. this.registerFunction('sklearn.metrics._classification.log_loss');
  4224. this.registerFunction('sklearn.metrics._classification.precision_score');
  4225. this.registerFunction('sklearn.metrics._classification.recall_score');
  4226. this.registerFunction('sklearn.metrics._dist_metrics.newObj', (obj) => {
  4227. return obj.__new__(obj);
  4228. });
  4229. this.registerFunction('sklearn.metrics._ranking.roc_auc_score');
  4230. this.registerFunction('sklearn.metrics._regression.mean_absolute_error');
  4231. this.registerFunction('sklearn.metrics._regression.mean_squared_error');
  4232. this.registerFunction('sklearn.metrics._regression.r2_score');
  4233. sklearn.metrics.regression = sklearn.metrics._regression;
  4234. sklearn.metrics.r2_score = sklearn.metrics._regression.r2_score;
  4235. this.registerFunction('sklearn.metrics._regression.root_mean_squared_error');
  4236. this.registerFunction('sklearn.metrics._scorer._passthrough_scorer');
  4237. this.registerFunction('re._compile', (pattern, flags) => {
  4238. return self.invoke('re.Pattern', [pattern, flags]);
  4239. });
  4240. this.registerFunction('srsly.cloudpickle.cloudpickle._builtin_type', (...args) => {
  4241. return function() {
  4242. return self.invoke(`types.${args[0]}`, args);
  4243. };
  4244. });
  4245. this.registerFunction('theano.scalar.basic.same_out');
  4246. this.registerFunction('theano.scalar.basic.same_out_nocomplex');
  4247. this.registerFunction('theano.scalar.basic.upcast_out');
  4248. this.registerFunction('theano.scalar.basic.upgrade_to_float');
  4249. this.registerFunction('theano.tensor.nnet.conv2d');
  4250. this.registerFunction('theano.tensor.type.values_eq_approx_remove_inf_nan');
  4251. this.registerFunction('theano.tensor.type.values_eq_approx_remove_nan');
  4252. this.registerType('torch.nn.modules.module.Module', class {
  4253. constructor() {
  4254. this._modules = execution.invoke('collections.OrderedDict', []);
  4255. this._parameters = execution.invoke('collections.OrderedDict', []);
  4256. this._buffers = execution.invoke('collections.OrderedDict', []);
  4257. }
  4258. __setattr__(name, value) {
  4259. if (value instanceof torch.nn.modules.module.Module) {
  4260. this._modules.set(name, value);
  4261. } else {
  4262. this[name] = value;
  4263. }
  4264. }
  4265. __getattr__(name) {
  4266. if (this._modules.has(name)) {
  4267. return this._modules.get(name);
  4268. }
  4269. return this[name];
  4270. }
  4271. });
  4272. torch.nn.Module = torch.nn.modules.module.Module;
  4273. torch.nn.modules.Module = torch.nn.modules.module.Module;
  4274. this.registerType('torch._C._TensorBase', class extends builtins.object {});
  4275. this.registerType('torch._C._TensorMeta', class extends builtins.type {});
  4276. this.registerType('torch._C._VariableFunctionsClass', class extends builtins.object {});
  4277. this.registerType('torch._C.OperatorRegistry', class {
  4278. constructor() {
  4279. this._operators = new Map();
  4280. }
  4281. registerOperator(op) {
  4282. const key = op.schema().name;
  4283. if (!this._operators.has(key)) {
  4284. this._operators.set(key, []);
  4285. }
  4286. this._operators.get(key).push(op);
  4287. }
  4288. getAllOperators() {
  4289. const values = [];
  4290. for (const [, ops] of this._operators) {
  4291. values.push(...ops);
  4292. }
  4293. return values;
  4294. }
  4295. getAllOperatorsFor(name) {
  4296. return this._operators.get(name) || [];
  4297. }
  4298. });
  4299. this.registerType('torch._C.Operator', class {
  4300. constructor(schema) {
  4301. this._schema = schema;
  4302. }
  4303. schema() {
  4304. return this._schema;
  4305. }
  4306. });
  4307. this.registerFunction('torch._C._get_registry', () => {
  4308. this._operators = this._operators || new torch._C.OperatorRegistry();
  4309. return this._operators;
  4310. });
  4311. this.registerFunction('torch._C._get_schema', (op_name, overload_name) => {
  4312. const registry = torch._C._get_registry();
  4313. const operations = registry.getAllOperatorsFor(op_name);
  4314. for (const op of operations) {
  4315. if (op.schema().overload_name === overload_name) {
  4316. return op.schema();
  4317. }
  4318. }
  4319. throw new python.Error(`Schema '${op_name}.${overload_name}' not found.`);
  4320. });
  4321. this.registerFunction('torch._C._jit_get_schemas_for_operator', (op_name) => {
  4322. const registry = torch._C._get_registry();
  4323. return registry.getAllOperatorsFor(op_name).map((op) => op.schema());
  4324. });
  4325. this.registerFunction('torch._C._jit_get_operation', (op_name) => {
  4326. const registry = torch._C._get_registry();
  4327. const sortedOps = registry.getAllOperatorsFor(op_name);
  4328. if (sortedOps.length === 0) {
  4329. return [null, null];
  4330. }
  4331. const overload_names = sortedOps.map((op) => op.schema().overload_name);
  4332. return [{}, overload_names];
  4333. });
  4334. this.registerFunction('torch._C._get_operation_overload', (op_name, overload_name) => {
  4335. const registry = torch._C._get_registry();
  4336. const operations = registry.getAllOperatorsFor(op_name);
  4337. for (const op of operations) {
  4338. if (op.schema().overload_name === overload_name) {
  4339. return [{}, {}, null];
  4340. }
  4341. }
  4342. return null;
  4343. });
  4344. this.registerType('torch.ao.quantization.fake_quantize.FakeQuantize', class {});
  4345. this.registerType('torch.ao.quantization.fake_quantize.FusedMovingAvgObsFakeQuantize', class {});
  4346. this.registerType('torch.ao.quantization.observer._PartialWrapper', class {});
  4347. this.registerType('torch.ao.quantization.observer.HistogramObserver', class {});
  4348. this.registerType('torch.ao.quantization.observer.MovingAverageMinMaxObserver', class {});
  4349. this.registerType('torch.ao.quantization.observer.MovingAveragePerChannelMinMaxObserver', class {});
  4350. this.registerType('torch.ao.quantization.observer.MinMaxObserver', class {});
  4351. this.registerType('torch.ao.quantization.observer.PerChannelMinMaxObserver', class {});
  4352. this.registerType('torch.ao.quantization.observer.PlaceholderObserver', class {});
  4353. this.registerType('torch.ao.quantization.qconfig.QConfig', class {});
  4354. this.registerType('torch.ao.quantization.qconfig.QConfigDynamic', class {});
  4355. this.registerType('torch.ao.quantization.stubs.DeQuantStub', class {});
  4356. this.registerType('torch.ao.quantization.stubs.QuantStub', class {});
  4357. this.registerType('torch.ao.quantization.stubs.QuantWrapper', class {});
  4358. this.registerFunction('torch.ao.quantization.qconfig._activation_is_memoryless');
  4359. this.registerFunction('torch.ao.quantization.qconfig._add_module_to_qconfig_obs_ctr');
  4360. this.registerFunction('torch.ao.quantization.fx.graph_module._save_packed_weight');
  4361. this.registerFunction('torch.ao.quantization.fx._lower_to_native_backend._load_packed_weight');
  4362. this.registerFunction('torch.ao.quantization.fx._lower_to_native_backend._save_packed_weight');
  4363. this.registerFunction('torch.ao.quantization.observer._is_activation_post_process');
  4364. this.registerFunction('torch.ao.quantization.quantize._observer_forward_hook');
  4365. this.registerFunction('torch.ao.quantization.quantization_mappings._get_special_act_post_process');
  4366. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_dynamic_quant_module_mappings');
  4367. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_qat_module_mappings');
  4368. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_qconfig_propagation_list');
  4369. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_static_quant_module_mappings');
  4370. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_static_quant_reference_module_mappings');
  4371. this.registerFunction('torch.ao.quantization.quantization_mappings.no_observer_set');
  4372. this.registerFunction('torch.ao.quantization.quantization_mappings._has_special_act_post_process');
  4373. this.registerFunction('torch.ao.quantization.utils.get_qparam_dict');
  4374. this.registerFunction('torch.ao.quantization.utils.has_no_children_ignoring_parametrizations');
  4375. this.registerFunction('torch.amp.grad_scaler._refresh_per_optimizer_state');
  4376. this.registerType('torch.autograd.variable.Variable', class {});
  4377. this.registerType('torch.backends.cudnn.rnn.Unserializable', class {});
  4378. this.registerFunction('torch.distributed._shard.sharded_tensor.pre_load_state_dict_hook');
  4379. this.registerFunction('torch.distributed._shard.sharded_tensor.state_dict_hook');
  4380. this.registerType('torch.distributed.algorithms.join._JoinConfig', class {});
  4381. this.registerFunction('torch.distributed._sharded_tensor.state_dict_hook');
  4382. this.registerFunction('torch.distributed._sharded_tensor.pre_load_state_dict_hook');
  4383. this.registerType('torch.distributed._tensor.api.DTensor', class extends torch._C._TensorMeta {});
  4384. this.registerType('torch.distributed._tensor.placement_types.DTensorSpec', class {});
  4385. this.registerType('torch.distributed._tensor.placement_types.Shard', class {});
  4386. this.registerType('torch.distributed._tensor.placement_types.TensorMeta', class {});
  4387. this.registerType('torch.distributed.device_mesh.DeviceMesh', class {});
  4388. this.registerType('torch.distributions.bernoulli.Bernoulli', class {});
  4389. this.registerType('torch.distributions.beta.Beta', class {});
  4390. this.registerType('torch.distributions.binomial.Binomial', class {});
  4391. this.registerType('torch.distributions.categorical.Categorical', class {});
  4392. this.registerType('torch.distributions.constraints._LowerCholesky', class {});
  4393. this.registerType('torch.distributions.constraints._Real', class {});
  4394. this.registerType('torch.distributions.dirichlet.Dirichlet', class {});
  4395. this.registerType('torch.distributions.mixture_same_family.MixtureSameFamily', class {});
  4396. this.registerType('torch.distributions.multivariate_normal.MultivariateNormal', class {});
  4397. this.registerType('torch.distributions.normal.Normal', class {});
  4398. this.registerType('torch.distributions.transforms._InverseTransform', class {});
  4399. this.registerType('torch.distributions.transforms.AffineTransform', class {});
  4400. this.registerType('torch.distributions.transforms.ComposeTransform', class {});
  4401. this.registerType('torch.distributions.transforms.ExpTransform', class {});
  4402. this.registerType('torch.distributions.transforms.LowerCholeskyTransform', class {});
  4403. this.registerType('torch.distributions.uniform.Uniform', class {});
  4404. this.registerType('torch.nn.backends.thnn._get_thnn_function_backend', class {});
  4405. this.registerType('torch.nn.intrinsic.modules.fused._FusedModule', class {});
  4406. this.registerType('torch.nn.intrinsic.modules.fused.ConvBnReLU2d', class {});
  4407. this.registerType('torch.nn.intrinsic.modules.fused.ConvReLU2d', class {});
  4408. this.registerType('torch.nn.intrinsic.modules.fused.BNReLU2d', class {});
  4409. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvBn2d', class {});
  4410. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU2d', class {});
  4411. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvReLU2d', class {});
  4412. this.registerType('torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU1d', class {});
  4413. this.registerType('torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', class {});
  4414. this.registerType('torch.nn.intrinsic.quantized.modules.linear_relu.LinearReLU', class {});
  4415. this.registerType('torch.nn.modules.activation.CELU', class extends torch.nn.modules.module.Module {});
  4416. this.registerType('torch.nn.modules.activation.ELU', class extends torch.nn.modules.module.Module {});
  4417. this.registerType('torch.nn.modules.activation.GELU', class extends torch.nn.modules.module.Module {});
  4418. this.registerType('torch.nn.modules.activation.GLU', class extends torch.nn.modules.module.Module {});
  4419. this.registerType('torch.nn.modules.activation.Hardtanh', class extends torch.nn.modules.module.Module {});
  4420. this.registerType('torch.nn.modules.activation.Hardshrink', class extends torch.nn.modules.module.Module {});
  4421. this.registerType('torch.nn.modules.activation.Hardsigmoid', class extends torch.nn.modules.module.Module {});
  4422. this.registerType('torch.nn.modules.activation.Hardswish', class extends torch.nn.modules.module.Module {});
  4423. this.registerType('torch.nn.modules.activation.LeakyReLU', class extends torch.nn.modules.module.Module {});
  4424. this.registerType('torch.nn.modules.activation.LogSigmoid', class extends torch.nn.modules.module.Module {});
  4425. this.registerType('torch.nn.modules.activation.LogSoftmax', class extends torch.nn.modules.module.Module {});
  4426. this.registerType('torch.nn.modules.activation.Mish', class extends torch.nn.modules.module.Module {});
  4427. this.registerType('torch.nn.modules.activation.MultiheadAttention', class extends torch.nn.modules.module.Module {});
  4428. this.registerType('torch.nn.modules.activation.ReLU', class extends torch.nn.modules.module.Module {});
  4429. this.registerType('torch.nn.modules.activation.ReLU6', class extends torch.nn.modules.module.Module {});
  4430. this.registerType('torch.nn.modules.activation.PReLU', class extends torch.nn.modules.module.Module {});
  4431. this.registerType('torch.nn.modules.activation.RReLU', class extends torch.nn.modules.module.Module {});
  4432. this.registerType('torch.nn.modules.activation.SELU', class extends torch.nn.modules.module.Module {});
  4433. this.registerType('torch.nn.modules.activation.Sigmoid', class extends torch.nn.modules.module.Module {});
  4434. this.registerType('torch.nn.modules.activation.SiLU', class extends torch.nn.modules.module.Module {});
  4435. this.registerType('torch.nn.modules.activation.Softmax', class extends torch.nn.modules.module.Module {});
  4436. this.registerType('torch.nn.modules.activation.Softmax2d', class extends torch.nn.modules.module.Module {});
  4437. this.registerType('torch.nn.modules.activation.Softmin', class extends torch.nn.modules.module.Module {});
  4438. this.registerType('torch.nn.modules.activation.Softplus', class extends torch.nn.modules.module.Module {});
  4439. this.registerType('torch.nn.modules.activation.Softshrink', class extends torch.nn.modules.module.Module {});
  4440. this.registerType('torch.nn.modules.activation.Softsign', class extends torch.nn.modules.module.Module {});
  4441. this.registerType('torch.nn.modules.activation.Tanh', class extends torch.nn.modules.module.Module {});
  4442. this.registerType('torch.nn.modules.activation.Tanhshrink', class extends torch.nn.modules.module.Module {});
  4443. this.registerType('torch.nn.modules.activation.Threshold', class extends torch.nn.modules.module.Module {});
  4444. this.registerType('torch.nn.modules.adaptive.AdaptiveLogSoftmaxWithLoss', class {});
  4445. this.registerType('torch.nn.modules.batchnorm._NormBase', class extends torch.nn.modules.module.Module {});
  4446. this.registerType('torch.nn.modules.batchnorm._BatchNorm', class extends torch.nn.modules.batchnorm._NormBase {});
  4447. this.registerType('torch.nn.modules.batchnorm.BatchNorm1d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  4448. this.registerType('torch.nn.modules.batchnorm.BatchNorm2d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  4449. this.registerType('torch.nn.modules.batchnorm.BatchNorm3d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  4450. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm1d', class {});
  4451. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm2d', class {});
  4452. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm3d', class {});
  4453. this.registerType('torch.nn.modules.batchnorm.SyncBatchNorm', class {});
  4454. this.registerType('torch.nn.modules.byted_batchnorm.BytedBatchNorm2d', class {});
  4455. this.registerType('torch.nn.modules.channelshuffle.ChannelShuffle', class {});
  4456. this.registerType('torch.nn.modules.container.ModuleDict', class extends torch.nn.modules.module.Module {});
  4457. this.registerType('torch.nn.modules.container.ModuleList', class extends torch.nn.modules.module.Module {});
  4458. this.registerType('torch.nn.modules.container.ParameterDict', class extends torch.nn.modules.module.Module {});
  4459. this.registerType('torch.nn.modules.container.ParameterList', class extends torch.nn.modules.module.Module {});
  4460. this.registerType('torch.nn.modules.container.Sequential', class extends torch.nn.modules.module.Module {});
  4461. this.registerType('torch.nn.modules.conv._ConvNd', class extends torch.nn.modules.module.Module {});
  4462. this.registerType('torch.nn.modules.conv.Conv1d', class extends torch.nn.modules.conv._ConvNd {});
  4463. this.registerType('torch.nn.modules.conv.Conv2d', class extends torch.nn.modules.conv._ConvNd {});
  4464. this.registerType('torch.nn.modules.conv.Conv3d', class extends torch.nn.modules.conv._ConvNd {});
  4465. this.registerType('torch.nn.modules.conv._ConvTransposeNd', class extends torch.nn.modules.module.Module {});
  4466. this.registerType('torch.nn.modules.conv.ConvTranspose1d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  4467. this.registerType('torch.nn.modules.conv.ConvTranspose2d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  4468. this.registerType('torch.nn.modules.conv.ConvTranspose3d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  4469. this.registerType('torch.nn.modules.conv.LazyConv1d', class {});
  4470. this.registerType('torch.nn.modules.conv.LazyConv2d', class {});
  4471. this.registerType('torch.nn.modules.conv.LazyConv3d', class {});
  4472. this.registerType('torch.nn.modules.conv.LazyConvTranspose2d', class {});
  4473. this.registerType('torch.nn.modules.distance.CosineSimilarity', class extends torch.nn.modules.module.Module {});
  4474. this.registerType('torch.nn.modules.distance.PairwiseDistance', class extends torch.nn.modules.module.Module {});
  4475. this.registerType('torch.nn.modules.dropout._DropoutNd', class extends torch.nn.modules.module.Module {});
  4476. this.registerType('torch.nn.modules.dropout.AlphaDropout', class extends torch.nn.modules.dropout._DropoutNd {});
  4477. this.registerType('torch.nn.modules.dropout.Dropout', class extends torch.nn.modules.dropout._DropoutNd {});
  4478. this.registerType('torch.nn.modules.dropout.Dropout1d', class extends torch.nn.modules.dropout._DropoutNd {});
  4479. this.registerType('torch.nn.modules.dropout.Dropout2d', class extends torch.nn.modules.dropout._DropoutNd {});
  4480. this.registerType('torch.nn.modules.dropout.Dropout3d', class extends torch.nn.modules.dropout._DropoutNd {});
  4481. this.registerType('torch.nn.modules.dropout.FeatureAlphaDropout', class extends torch.nn.modules.dropout._DropoutNd {});
  4482. this.registerType('torch.nn.modules.fold.Fold', class extends torch.nn.modules.module.Module {});
  4483. this.registerType('torch.nn.modules.fold.Unfold', class extends torch.nn.modules.module.Module {});
  4484. this.registerType('torch.nn.modules.flatten.Flatten', class extends torch.nn.modules.module.Module {});
  4485. this.registerType('torch.nn.modules.flatten.Unflatten', class extends torch.nn.modules.module.Module {});
  4486. this.registerType('torch.nn.modules.instancenorm.InstanceNorm1d', class {});
  4487. this.registerType('torch.nn.modules.instancenorm.InstanceNorm2d', class {});
  4488. this.registerType('torch.nn.modules.instancenorm.InstanceNorm3d', class {});
  4489. this.registerType('torch.nn.modules.instancenorm.LazyInstanceNorm2d', class {});
  4490. this.registerType('torch.nn.modules.linear._LinearWithBias', class {});
  4491. this.registerType('torch.nn.modules.linear.Bilinear', class extends torch.nn.modules.module.Module {});
  4492. this.registerType('torch.nn.modules.linear.Identity', class extends torch.nn.modules.module.Module {});
  4493. this.registerType('torch.nn.modules.linear.LazyLinear', class extends torch.nn.modules.module.Module {});
  4494. this.registerType('torch.nn.modules.linear.Linear', class extends torch.nn.modules.module.Module {});
  4495. this.registerType('torch.nn.modules.linear.NonDynamicallyQuantizableLinear', class extends torch.nn.modules.linear.Linear {});
  4496. this.registerType('torch.nn.modules.loss._Loss', class extends torch.nn.modules.module.Module {});
  4497. this.registerType('torch.nn.modules.loss._WeightedLoss', class extends torch.nn.modules.loss._Loss {});
  4498. this.registerType('torch.nn.modules.loss.BCELoss', class extends torch.nn.modules.loss._WeightedLoss {});
  4499. this.registerType('torch.nn.modules.loss.BCEWithLogitsLoss', class extends torch.nn.modules.loss._Loss {});
  4500. this.registerType('torch.nn.modules.loss.CrossEntropyLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  4501. this.registerType('torch.nn.modules.loss.CosineEmbeddingLoss', class extends torch.nn.modules.loss._Loss {});
  4502. this.registerType('torch.nn.modules.loss.CTCLoss', class extends torch.nn.modules.loss._Loss {});
  4503. this.registerType('torch.nn.modules.loss.GaussianNLLLoss', class extends torch.nn.modules.loss._Loss {});
  4504. this.registerType('torch.nn.modules.loss.HuberLoss', class extends torch.nn.modules.loss._Loss {});
  4505. this.registerType('torch.nn.modules.loss.HingeEmbeddingLoss', class extends torch.nn.modules.loss._Loss {});
  4506. this.registerType('torch.nn.modules.loss.KLDivLoss', class extends torch.nn.modules.loss._Loss {});
  4507. this.registerType('torch.nn.modules.loss.L1Loss', class extends torch.nn.modules.loss._Loss {});
  4508. this.registerType('torch.nn.modules.loss.MarginRankingLoss', class extends torch.nn.modules.loss._Loss {});
  4509. this.registerType('torch.nn.modules.loss.MultiLabelMarginLoss', class extends torch.nn.modules.loss._Loss {});
  4510. this.registerType('torch.nn.modules.loss.MultiLabelSoftMarginLoss', class extends torch.nn.modules.loss._Loss {});
  4511. this.registerType('torch.nn.modules.loss.MultiMarginLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  4512. this.registerType('torch.nn.modules.loss.MSELoss', class extends torch.nn.modules.loss._Loss {});
  4513. this.registerType('torch.nn.modules.loss.NLLLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  4514. this.registerType('torch.nn.modules.loss.NLLLoss2d', class extends torch.nn.modules.loss.NLLLoss {});
  4515. this.registerType('torch.nn.modules.loss.PoissonNLLLoss', class {});
  4516. this.registerType('torch.nn.modules.loss.SmoothL1Loss', class {});
  4517. this.registerType('torch.nn.modules.loss.SoftMarginLoss', class {});
  4518. this.registerType('torch.nn.modules.loss.TripletMarginLoss', class {});
  4519. this.registerType('torch.nn.modules.loss.TripletMarginWithDistanceLoss', class {});
  4520. this.registerType('torch.nn.modules.module._IncompatibleKeys', class {});
  4521. this.registerType('torch.nn.modules.module._WrappedHook', class {});
  4522. this.registerType('torch.nn.modules.module.PatchForward', class {});
  4523. this.registerType('torch.nn.modules.normalization.CrossMapLRN2d', class {});
  4524. this.registerType('torch.nn.modules.normalization.GroupNorm', class extends torch.nn.modules.module.Module {});
  4525. this.registerType('torch.nn.modules.normalization.LayerNorm', class extends torch.nn.modules.module.Module {});
  4526. this.registerType('torch.nn.modules.normalization.LocalResponseNorm', class {});
  4527. this.registerType('torch.nn.modules.padding._ReflectionPadNd', class extends torch.nn.modules.module.Module {});
  4528. this.registerType('torch.nn.modules.padding.ReflectionPad1d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  4529. this.registerType('torch.nn.modules.padding.ReflectionPad2d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  4530. this.registerType('torch.nn.modules.padding.ReflectionPad3d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  4531. this.registerType('torch.nn.modules.padding._ReplicationPadNd', class extends torch.nn.modules.module.Module {});
  4532. this.registerType('torch.nn.modules.padding.ReplicationPad1d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  4533. this.registerType('torch.nn.modules.padding.ReplicationPad2d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  4534. this.registerType('torch.nn.modules.padding.ReplicationPad3d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  4535. this.registerType('torch.nn.modules.padding.ZeroPad2d', class {});
  4536. this.registerType('torch.nn.modules.padding.ConstantPad1d', class {});
  4537. this.registerType('torch.nn.modules.padding.ConstantPad2d', class {});
  4538. this.registerType('torch.nn.modules.padding.ConstantPad3d', class {});
  4539. this.registerType('torch.nn.modules.pixelshuffle.PixelShuffle', class {});
  4540. this.registerType('torch.nn.modules.pixelshuffle.PixelUnshuffle', class {});
  4541. this.registerType('torch.nn.modules.pooling._AdaptiveAvgPoolNd', class extends torch.nn.modules.module.Module {});
  4542. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool1d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  4543. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool2d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  4544. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool3d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  4545. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool1d', class {});
  4546. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool2d', class {});
  4547. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool3d', class {});
  4548. this.registerType('torch.nn.modules.pooling.AvgPool1d', class {});
  4549. this.registerType('torch.nn.modules.pooling.AvgPool2d', class {});
  4550. this.registerType('torch.nn.modules.pooling.AvgPool3d', class {});
  4551. this.registerType('torch.nn.modules.pooling.FractionalMaxPool2d', class {});
  4552. this.registerType('torch.nn.modules.pooling.LPPool2d', class {});
  4553. this.registerType('torch.nn.modules.pooling.MaxPool1d', class {});
  4554. this.registerType('torch.nn.modules.pooling.MaxPool2d', class {});
  4555. this.registerType('torch.nn.modules.pooling.MaxPool3d', class {});
  4556. this.registerType('torch.nn.modules.pooling.MaxUnpool1d', class {});
  4557. this.registerType('torch.nn.modules.pooling.MaxUnpool2d', class {});
  4558. this.registerType('torch.nn.modules.pooling.MaxUnpool3d', class {});
  4559. this.registerType('torch.nn.modules.rnn.GRU', class {});
  4560. this.registerType('torch.nn.modules.rnn.GRUCell', class {});
  4561. this.registerType('torch.nn.modules.rnn.LSTM', class {});
  4562. this.registerType('torch.nn.modules.rnn.LSTMCell', class {});
  4563. this.registerType('torch.nn.modules.rnn.RNNBase', class extends torch.nn.modules.module.Module {});
  4564. this.registerType('torch.nn.modules.rnn.RNN', class extends torch.nn.modules.rnn.RNNBase {});
  4565. this.registerType('torch.nn.modules.rnn.RNNCellBase', class extends torch.nn.modules.module.Module {});
  4566. this.registerType('torch.nn.modules.rnn.RNNCell', class extends torch.nn.modules.rnn.RNNCellBase {});
  4567. this.registerType('torch.nn.modules.sparse.Embedding', class {});
  4568. this.registerType('torch.nn.modules.sparse.EmbeddingBag', class {});
  4569. this.registerType('torch.nn.modules.transformer.Transformer', class {});
  4570. this.registerType('torch.nn.modules.transformer.TransformerDecoder', class {});
  4571. this.registerType('torch.nn.modules.transformer.TransformerDecoderLayer', class {});
  4572. this.registerType('torch.nn.modules.transformer.TransformerEncoder', class {});
  4573. this.registerType('torch.nn.modules.transformer.TransformerEncoderLayer', class {});
  4574. this.registerType('torch.nn.modules.upsampling.Upsample', class {});
  4575. this.registerType('torch.nn.modules.upsampling.UpsamplingBilinear2d', class {});
  4576. this.registerType('torch.nn.modules.upsampling.UpsamplingNearest2d', class {});
  4577. this.registerType('torch.nn.parallel.data_parallel.DataParallel', class {});
  4578. this.registerType('torch.nn.parallel.distributed._DDPUnevenInputsConfig', class {});
  4579. this.registerType('torch.nn.parallel.distributed.DistributedDataParallel', class {});
  4580. this.registerType('torch.nn.qat.modules.conv.Conv2d', class {});
  4581. this.registerType('torch.nn.qat.modules.linear.Linear', class {});
  4582. this.registerType('torch.nn.quantized.modules.activation.ReLU', class {});
  4583. this.registerType('torch.nn.quantized.modules.activation.LeakyReLU', class {});
  4584. this.registerType('torch.nn.quantized.modules.activation.Softmax', class {});
  4585. this.registerType('torch.nn.quantized.dynamic.modules.linear.Linear', class {});
  4586. this.registerType('torch.nn.quantized.dynamic.modules.rnn.GRU', class {});
  4587. this.registerType('torch.nn.quantized.dynamic.modules.rnn.LSTM', class {});
  4588. this.registerType('torch.nn.quantized.dynamic.modules.rnn.LSTMCell', class {});
  4589. this.registerType('torch.nn.quantized.dynamic.modules.rnn.PackedParameter', class {});
  4590. this.registerType('torch.nn.quantized.modules.activation.ReLU6', class {});
  4591. this.registerType('torch.nn.quantized.modules.batchnorm.BatchNorm2d', class {});
  4592. this.registerType('torch.nn.quantized.modules.conv.Conv1d', class {});
  4593. this.registerType('torch.nn.quantized.modules.conv.Conv2d', class {});
  4594. this.registerType('torch.nn.quantized.modules.conv.ConvTranspose2d', class {});
  4595. this.registerType('torch.nn.quantized.modules.DeQuantize', class {});
  4596. this.registerType('torch.nn.quantized.modules.dropout.Dropout', class {});
  4597. this.registerType('torch.nn.quantized.modules.embedding_ops.Embedding', class {});
  4598. this.registerType('torch.nn.quantized.modules.embedding_ops.EmbeddingPackedParams', class {});
  4599. this.registerType('torch.nn.quantized.modules.functional_modules.FloatFunctional', class {});
  4600. this.registerType('torch.nn.quantized.modules.functional_modules.QFunctional', class {});
  4601. this.registerType('torch.nn.quantized.modules.linear.Linear', class {});
  4602. this.registerType('torch.nn.quantized.modules.linear.LinearPackedParams', class {});
  4603. this.registerType('torch.nn.quantized.modules.normalization.InstanceNorm2d', class {});
  4604. this.registerType('torch.nn.quantized.modules.normalization.GroupNorm', class extends torch.nn.modules.normalization.GroupNorm {});
  4605. this.registerType('torch.nn.quantized.modules.normalization.LayerNorm', class extends torch.nn.modules.normalization.LayerNorm {});
  4606. this.registerType('torch.nn.quantized.modules.Quantize', class {});
  4607. this.registerType('torch.ao.nn.quantizable.modules.activation.MultiheadAttention', class extends torch.nn.modules.activation.MultiheadAttention {});
  4608. this.registerType('torch.ao.nn.quantizable.modules.rnn._LSTMLayer', class {});
  4609. this.registerType('torch.ao.nn.quantizable.modules.rnn._LSTMSingleLayer', class {});
  4610. this.registerType('torch.ao.nn.quantizable.modules.rnn.LSTM', class {});
  4611. this.registerType('torch.ao.nn.quantizable.modules.rnn.LSTMCell', class {});
  4612. this.registerType('torch.ao.nn.quantized.modules.activation.Hardswish', class extends torch.nn.modules.activation.Hardswish {});
  4613. this.registerType('torch.ao.nn.quantized.modules.activation.MultiheadAttention', class extends torch.ao.nn.quantizable.modules.activation.MultiheadAttention {});
  4614. this.registerType('torch.ao.nn.quantized.modules.activation.PReLU', class extends torch.nn.modules.module.Module {});
  4615. this.registerType('torch.ao.nn.quantized.modules.activation.ReLU6', class extends torch.nn.modules.activation.ReLU {});
  4616. this.registerType('torch.ao.nn.quantized.modules.activation.LeakyReLU', class extends torch.nn.modules.activation.LeakyReLU {});
  4617. this.registerType('torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule', class extends torch.nn.modules.module.Module {});
  4618. this.registerType('torch.ao.nn.quantized.modules.batchnorm._BatchNorm', class extends torch.nn.modules.batchnorm._BatchNorm {});
  4619. this.registerType('torch.ao.nn.quantized.modules.batchnorm.BatchNorm2d', class extends torch.ao.nn.quantized.modules.batchnorm._BatchNorm {});
  4620. this.registerType('torch.ao.nn.quantized.modules.conv.Conv1d', class extends torch.nn.modules.module.Module {});
  4621. this.registerType('torch.ao.nn.quantized.modules.conv.Conv2d', class extends torch.nn.modules.module.Module {});
  4622. this.registerType('torch.ao.nn.quantized.modules.conv._ConvNd', class extends torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule {});
  4623. this.registerType('torch.ao.nn.quantized.modules.conv._ConvTransposeNd', class extends torch.ao.nn.quantized.modules.conv._ConvNd {});
  4624. this.registerType('torch.ao.nn.quantized.modules.conv.ConvTranspose1d', class extends torch.ao.nn.quantized.modules.conv._ConvTransposeNd {});
  4625. this.registerType('torch.ao.nn.quantized.modules.conv.ConvTranspose2d', class extends torch.ao.nn.quantized.modules.conv._ConvTransposeNd {});
  4626. this.registerType('torch.ao.nn.quantized.modules.Quantize', class extends torch.nn.modules.module.Module {});
  4627. this.registerType('torch.ao.nn.quantized.modules.DeQuantize', class extends torch.nn.modules.module.Module {});
  4628. this.registerType('torch.ao.nn.quantized.modules.dropout.Dropout', class extends torch.nn.modules.dropout.Dropout {});
  4629. this.registerType('torch.ao.nn.quantized.modules.embedding_ops.Embedding', class extends torch.nn.modules.module.Module {});
  4630. this.registerType('torch.ao.nn.quantized.modules.embedding_ops.EmbeddingPackedParams', class extends torch.nn.modules.module.Module {});
  4631. this.registerType('torch.ao.nn.quantized.modules.functional_modules.FloatFunctional', class extends torch.nn.modules.module.Module {});
  4632. this.registerType('torch.ao.nn.quantized.modules.functional_modules.QFunctional', class extends torch.nn.modules.module.Module {});
  4633. this.registerType('torch.ao.nn.quantized.modules.functional_modules.FXFloatFunctional', class extends torch.nn.modules.module.Module {});
  4634. this.registerType('torch.ao.nn.quantized.modules.linear.Linear', class extends torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule {});
  4635. this.registerType('torch.ao.nn.quantized.modules.linear.LinearPackedParams', class extends torch.nn.modules.module.Module {});
  4636. this.registerType('torch.ao.nn.quantized.modules.normalization.LayerNorm', class extends torch.nn.modules.normalization.LayerNorm {});
  4637. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm1d', class extends torch.nn.modules.instancenorm.InstanceNorm1d {});
  4638. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm2d', class extends torch.nn.modules.instancenorm.InstanceNorm2d {});
  4639. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm3d', class extends torch.nn.modules.instancenorm.InstanceNorm3d {});
  4640. this.registerType('torch.ao.nn.quantized.modules.rnn.LSTM', class {});
  4641. this.registerType('torch.ao.nn.quantized.dynamic.modules.linear.Linear', class extends torch.ao.nn.quantized.modules.linear.Linear {});
  4642. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.PackedParameter', class extends torch.nn.modules.module.Module {});
  4643. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase', class extends torch.nn.modules.module.Module {});
  4644. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.GRU', class extends torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase {});
  4645. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.LSTM', class extends torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase {});
  4646. this.registerType('torch.ao.nn.quantized.reference.modules.conv.Conv1d', class {});
  4647. this.registerType('torch.ao.nn.quantized.reference.modules.conv.Conv2d', class {});
  4648. this.registerType('torch.ao.nn.quantized.reference.modules.linear.Linear', class {});
  4649. this.registerType('torch.ao.nn.qat.modules.conv.Conv2d', class {});
  4650. this.registerType('torch.ao.nn.qat.modules.linear.Linear', class {});
  4651. this.registerType('torch.ao.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', class extends torch.ao.nn.quantized.modules.conv.Conv2d {});
  4652. this.registerType('torch.ao.nn.intrinsic.quantized.modules.linear_relu.LinearReLU', class extends torch.ao.nn.quantized.modules.linear.Linear {});
  4653. this.registerType('torch.ao.nn.intrinsic.modules.fused._FusedModule', class extends torch.nn.modules.container.Sequential {});
  4654. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvBn2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  4655. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvReLU1d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  4656. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvReLU2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  4657. this.registerType('torch.ao.nn.intrinsic.modules.fused.LinearReLU', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  4658. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvBnReLU2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  4659. this.registerType('torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU2d', class {});
  4660. this.registerType('torch.nn.utils.prune.CustomFromMask', class {});
  4661. this.registerType('torch.nn.utils.prune.L1Unstructured', class {});
  4662. this.registerType('torch.nn.utils.prune.LnStructured', class {});
  4663. this.registerType('torch.nn.utils.prune.PruningContainer', class {});
  4664. this.registerType('torch.nn.utils.spectral_norm.SpectralNorm', class {});
  4665. this.registerType('torch.nn.utils.spectral_norm.SpectralNormStateDictHook', class {});
  4666. this.registerType('torch.nn.utils.spectral_norm.SpectralNormLoadStateDictPreHook', class {});
  4667. this.registerType('torch.nn.utils.weight_norm.WeightNorm', class {});
  4668. this.registerFunction('torch.nn.utils.parametrize.type_before_parametrizations');
  4669. this.registerType('torch.nn.utils.parametrize.ParametrizationList', class extends torch.nn.modules.container.ModuleList {});
  4670. this.registerType('torch.torch_version.TorchVersion', class extends String {});
  4671. this.registerType('torch.optim.optimizer.Optimizer', class {});
  4672. this.registerType('torch.optim.adam.Adam', class extends torch.optim.optimizer.Optimizer {});
  4673. this.registerType('torch.optim.adamw.AdamW', class {});
  4674. this.registerType('torch.optim.adagrad.Adagrad', class {});
  4675. this.registerType('torch.optim.adadelta.Adadelta', class {});
  4676. this.registerType('torch.optim.lbfgs.LBFGS', class {});
  4677. this.registerType('torch.optim.lr_scheduler.CosineAnnealingLR', class {});
  4678. this.registerType('torch.optim.lr_scheduler.CosineAnnealingWarmRestarts', class {});
  4679. this.registerType('torch.optim.lr_scheduler.CyclicLR', class {});
  4680. this.registerType('torch.optim.lr_scheduler.ExponentialLR', class {});
  4681. this.registerType('torch.optim.lr_scheduler.LambdaLR', class {});
  4682. this.registerType('torch.optim.lr_scheduler.LinearLR', class {});
  4683. this.registerType('torch.optim.lr_scheduler.MultiStepLR', class {});
  4684. this.registerType('torch.optim.lr_scheduler.OneCycleLR', class {});
  4685. this.registerType('torch.optim.lr_scheduler.ReduceLROnPlateau', class {});
  4686. this.registerType('torch.optim.lr_scheduler.StepLR', class {});
  4687. this.registerType('torch.optim.optimizer._RequiredParameter', class {});
  4688. this.registerType('torch.optim.radam.RAdam', class extends torch.optim.optimizer.Optimizer {});
  4689. this.registerType('torch.optim.rmsprop.RMSprop', class {});
  4690. this.registerType('torch.optim.sgd.SGD', class {});
  4691. this.registerType('torch.optim.sparse_adam.SparseAdam', class {});
  4692. this.registerType('torch.optim.swa_utils.SWALR', class {});
  4693. torch.optim.RAdam = torch.optim.radam.RAdam;
  4694. this.registerType('torch.quantization.fake_quantize.FakeQuantize', class {});
  4695. this.registerFunction('torch.quantization.fx.graph_module._save_packed_weight');
  4696. this.registerType('torch.quantization.observer._PartialWrapper', class {});
  4697. this.registerType('torch.quantization.observer.HistogramObserver', class {});
  4698. this.registerType('torch.quantization.observer.MinMaxObserver', class {});
  4699. this.registerType('torch.quantization.observer.MovingAverageMinMaxObserver', class {});
  4700. this.registerType('torch.quantization.observer.MovingAveragePerChannelMinMaxObserver', class {});
  4701. this.registerFunction('torch.quantization.observer._with_args');
  4702. this.registerType('torch.quantization.qconfig.QConfig', class {});
  4703. this.registerType('torch.quantization.stubs.DeQuantStub', class {});
  4704. this.registerType('torch.quantization.stubs.QuantStub', class {});
  4705. this.registerType('torch.utils._pytree.LeafSpec', class {});
  4706. this.registerType('torch.utils._pytree.TreeSpec', class {});
  4707. this.registerFunction('torch.utils._pytree.tree_map');
  4708. this.registerFunction('torch.utils.checkpoint.checkpoint');
  4709. this.registerType('torch.utils.data.dataloader._MultiProcessingDataLoaderIter', class {});
  4710. this.registerType('torch.utils.data.dataloader.DataLoader', class {});
  4711. this.registerFunction('torch.utils.data._utils.collate.default_collate');
  4712. torch.utils.data.dataloader.default_collate = torch.utils.data._utils.collate.default_collate;
  4713. this.registerType('torch.utils.data.dataset.Subset', class {});
  4714. this.registerType('torch.utils.data.dataset.ConcatDataset', class {});
  4715. this.registerType('torch.utils.data.dataset.TensorDataset', class {});
  4716. this.registerType('torch.utils.data.sampler.BatchSampler', class {});
  4717. this.registerType('torch.utils.data.sampler.RandomSampler', class {});
  4718. this.registerType('torch.utils.data.sampler.SequentialSampler', class {});
  4719. this.registerType('torch.utils.data.sampler.SubsetRandomSampler', class {});
  4720. this.registerType('torch.fx.experimental.symbolic_shapes.ShapeEnv', class {
  4721. create_symintnode(/* sym, hint, source */) {
  4722. return new torch.SymInt();
  4723. }
  4724. });
  4725. this.registerType('torch.fx.proxy.TracerBase', class {});
  4726. this.registerType('torch.fx._symbolic_trace.Tracer', class extends torch.fx.proxy.TracerBase {});
  4727. this.registerType('torch.fx.experimental.proxy_tensor.PythonKeyTracer', class extends torch.fx._symbolic_trace.Tracer {});
  4728. this.registerType('torch.fx.experimental.proxy_tensor._ModuleStackTracer', class extends torch.fx.experimental.proxy_tensor.PythonKeyTracer {});
  4729. this.registerFunction('torch.fx.graph_module._deserialize_graph_module', (/* forward, body */) => {
  4730. return execution.invoke('torch.fx.graph_module.GraphModule', []);
  4731. });
  4732. this.registerFunction('torch.fx.graph_module._forward_from_src', (src, globals /*, co_fields */) => {
  4733. globals = { ...globals };
  4734. const context = new python.Execution.Context(globals, null);
  4735. execution.exec(src, context);
  4736. const forward_fn = globals.forward;
  4737. delete globals.forward;
  4738. return forward_fn;
  4739. });
  4740. this.registerFunction('torch.fx.graph_module.reduce_graph_module', (body, import_block) => {
  4741. // https://github.com/pytorch/pytorch/blob/master/torch/fx/graph_module.py
  4742. const fn_src = body._code || body.code;
  4743. const forward = execution.invoke('torch.fx.graph_module._forward_from_src', [import_block + fn_src, {}]);
  4744. return execution.invoke('torch.fx.graph_module._deserialize_graph_module', [forward, body]);
  4745. });
  4746. this.registerFunction('torch.fx.graph_module.reduce_package_graph_module', (importer, body, generated_module_name) => {
  4747. const forward = importer.import_module(generated_module_name).forward;
  4748. return execution.invoke('torch.fx.graph_module._deserialize_graph_module', [forward, body]);
  4749. });
  4750. this.registerType('torch.fx.graph.CodeGen', class {});
  4751. this.registerType('torch.fx.graph._Namespace', class {
  4752. constructor() {
  4753. this._obj_to_name = new Map();
  4754. this._unassociated_names = new Set();
  4755. this._used_names = new Set();
  4756. this._base_count = {};
  4757. }
  4758. create_name(candidate, obj) {
  4759. if (obj && this._obj_to_name.has(obj)) {
  4760. return self._obj_to_name.get(obj);
  4761. }
  4762. candidate = candidate || '_unnamed';
  4763. candidate = /^\d+$/.test(candidate) ? `_${candidate}` : candidate;
  4764. candidate = candidate.replace(/[^0-9a-zA-Z_]+/, '_');
  4765. const match = candidate.match(/(.*)_(\d+)$"/);
  4766. let base = candidate;
  4767. let num = null;
  4768. if (match) {
  4769. [, base] = match;
  4770. num = parseInt(match[2], 10);
  4771. }
  4772. candidate = num ? `${base}_${num}` : base;
  4773. if (!num) {
  4774. num = this._base_count[base] || 0;
  4775. }
  4776. while (this._used_names.has(candidate) || this._is_illegal_name(candidate, obj)) {
  4777. num += 1;
  4778. candidate = `${base}_${num}`;
  4779. }
  4780. this._used_names.add(candidate);
  4781. this._base_count[base] = num;
  4782. if (obj) {
  4783. this._obj_to_name[obj] = candidate;
  4784. } else {
  4785. this._unassociated_names.add(candidate);
  4786. }
  4787. return candidate;
  4788. }
  4789. _is_illegal_name(/* name, obj */) {
  4790. /*
  4791. if name in keyword.kwlist:
  4792. return True
  4793. if name in builtins.__dict__:
  4794. return obj is not builtins.__dict__[name]
  4795. if name in _custom_builtins:
  4796. return obj is not _custom_builtins[name].obj
  4797. */
  4798. return false;
  4799. }
  4800. associate_name_with_obj() {
  4801. }
  4802. });
  4803. this.registerType('torch.fx.node.Node', class {
  4804. constructor(graph, name, op, target, args, kwargs, return_type) {
  4805. this.graph = graph;
  4806. this.name = name;
  4807. this.op = op;
  4808. this.target = target;
  4809. this._input_nodes = new builtins.dict();
  4810. this.__update_args_kwargs(args, kwargs);
  4811. this.users = new builtins.dict();
  4812. this.type = return_type;
  4813. this._prev = this;
  4814. this._next = this;
  4815. this._erased = false;
  4816. this._repr_fn = null;
  4817. this.meta = new builtins.dict();
  4818. }
  4819. get args() {
  4820. return this._args;
  4821. }
  4822. get kwargs() {
  4823. return this._kwargs;
  4824. }
  4825. get next() {
  4826. return this._next;
  4827. }
  4828. prepend(x) {
  4829. x._remove_from_list();
  4830. const p = this._prev;
  4831. [p._next, x._prev] = [x, p];
  4832. [x._next, this._prev] = [this, x];
  4833. }
  4834. _remove_from_list() {
  4835. const [p, n] = [this._prev, this._next];
  4836. [p._next, n._prev] = [n, p];
  4837. }
  4838. __update_args_kwargs(new_args, new_kwargs) {
  4839. const update_users_and_input_nodes = (n) => {
  4840. if (n instanceof torch.fx.node.Node) {
  4841. this._input_nodes.setdefault(n);
  4842. n.users.setdefault(this);
  4843. }
  4844. return n;
  4845. };
  4846. const map_aggregate = (a, fn) => {
  4847. if (a instanceof builtins.tuple) {
  4848. const t = new builtins.tuple(a.map((elem) => map_aggregate(elem, fn)));
  4849. if (!builtins.hasattr(a, '_fields')) {
  4850. return t;
  4851. }
  4852. throw new python.Error('Not implemented.');
  4853. // return type(a)(*t);
  4854. } else if (Array.isArray(a)) {
  4855. return a.map((elem) => map_aggregate(elem, fn));
  4856. } else if (a instanceof builtins.dict) {
  4857. const rv = new builtins.dict();
  4858. for (const [k, v] of a) {
  4859. rv.__setitem__(k, map_aggregate(v, fn));
  4860. }
  4861. return rv;
  4862. } else if (a instanceof builtins.slice) {
  4863. throw new python.Error('Not implemented.');
  4864. // return slice(map_aggregate(a.start, fn), map_aggregate(a.stop, fn), map_aggregate(a.step, fn))
  4865. }
  4866. return fn(a);
  4867. };
  4868. for (const old_use of this._input_nodes.keys()) {
  4869. old_use.users.pop(this);
  4870. }
  4871. // object.__setattr__(self, "_input_nodes", {})
  4872. this._input_nodes = new builtins.dict();
  4873. // object.__setattr__(self, "_args", map_aggregate(new_args, update_users_and_input_nodes))
  4874. this._args = map_aggregate(new_args, update_users_and_input_nodes);
  4875. // object.__setattr__(self, "_kwargs", map_aggregate(new_kwargs, update_users_and_input_nodes))
  4876. this._kwargs = map_aggregate(new_kwargs, update_users_and_input_nodes);
  4877. }
  4878. });
  4879. torch.fx.Node = torch.fx.node.Node;
  4880. torch.fx.graph.Node = torch.fx.node.Node;
  4881. this.registerType('torch.fx.graph.Graph', class {
  4882. constructor() {
  4883. this._root = new torch.fx.node.Node(self, '', 'root', '', new builtins.list(), new builtins.dict());
  4884. this._used_names = new Map();
  4885. this._len = 0;
  4886. this._graph_namespace = new torch.fx.graph._Namespace();
  4887. // this._owning_module = owning_module
  4888. // this._tracer_cls = tracer_cls
  4889. // this._tracer_extras = tracer_extras
  4890. // this._codegen = CodeGen()
  4891. // this._co_fields = {}
  4892. }
  4893. get nodes() {
  4894. const array = new Array(this._len);
  4895. let node = this._root.next;
  4896. for (let i = 0; node !== this._root; i++) {
  4897. array[i] = node;
  4898. node = node.next;
  4899. }
  4900. return array;
  4901. }
  4902. placeholder(name, type_expr /*, default_value */) {
  4903. const args = []; // () if default_value is inspect.Signature.empty else (default_value,)
  4904. const kwargs = new builtins.dict();
  4905. return this.create_node('placeholder', name, args, kwargs, type_expr);
  4906. }
  4907. create_node(op, target, args, kwargs, name, type_expr) {
  4908. args = args || new builtins.tuple();
  4909. kwargs = kwargs || new builtins.dict();
  4910. const candidate = name || this._target_to_str(target);
  4911. name = this._graph_namespace.create_name(candidate, null);
  4912. const n = new torch.fx.node.Node(this, name, op, target, args, kwargs, type_expr);
  4913. this._graph_namespace.associate_name_with_obj(name, n);
  4914. this._insert(n);
  4915. this._len += 1;
  4916. return n;
  4917. }
  4918. _insert(n) {
  4919. this._root.prepend(n);
  4920. }
  4921. output(result, type_expr) {
  4922. return this.create_node('output', 'output', new builtins.tuple(result), null, type_expr);
  4923. }
  4924. _target_to_str(target) {
  4925. if (typeof target === 'string') {
  4926. if (target.startsWith('__') && target.endswith('__')) {
  4927. target = target.substring(2, target.length - 2);
  4928. }
  4929. } else {
  4930. target = target.__name__;
  4931. }
  4932. return this._snake_case(target);
  4933. }
  4934. _snake_case(s) {
  4935. const chars = [];
  4936. let prev_lower = false;
  4937. for (const c of s) {
  4938. const x = c.toLowerCase();
  4939. if (prev_lower && x !== c) {
  4940. chars.push('_');
  4941. } else {
  4942. prev_lower = true;
  4943. }
  4944. chars.push(x);
  4945. }
  4946. return chars.join('');
  4947. }
  4948. });
  4949. this.registerType('torch.fx.graph_module.GraphModule', class extends torch.nn.modules.module.Module {
  4950. constructor(root, graph, class_name) {
  4951. super();
  4952. this.__class__.__name__ = class_name || 'GraphModule';
  4953. this.graph = graph;
  4954. }
  4955. });
  4956. torch.fx.Graph = torch.fx.graph.Graph;
  4957. torch.fx.GraphModule = torch.fx.graph_module.GraphModule;
  4958. this.registerType('torch.fx.immutable_collections.immutable_dict', class extends builtins.dict {});
  4959. this.registerFunction('torch.fx._symbolic_trace.wrap', (fn_or_name) => {
  4960. return fn_or_name;
  4961. });
  4962. this.registerFunction('torchvision.datasets.folder.default_loader');
  4963. this.registerType('torchvision.datasets.folder.ImageFolder', class {});
  4964. this.registerType('torchvision.datasets.mnist.FashionMNIST', class {});
  4965. this.registerType('torchvision.datasets.mnist.MNIST', class {});
  4966. this.registerType('torchvision.datasets.video_utils.VideoClips', class {});
  4967. this.registerType('torchvision.datasets.vision.StandardTransform', class {});
  4968. this.registerType('torchvision.ops.deform_conv.DeformConv2d', class {});
  4969. this.registerType('torchvision.ops.feature_pyramid_network.FeaturePyramidNetwork', class {});
  4970. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelMaxPool', class {});
  4971. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelP6P7', class {});
  4972. this.registerType('torchvision.ops.misc.Conv2dNormActivation', class {});
  4973. this.registerType('torchvision.ops.misc.ConvNormActivation', class {});
  4974. this.registerType('torchvision.ops.misc.MLP', class extends torch.nn.modules.container.Sequential {});
  4975. this.registerType('torchvision.ops.misc.ConvTranspose2d', class {});
  4976. this.registerType('torchvision.ops.misc.FrozenBatchNorm2d', class {});
  4977. this.registerType('torchvision.ops.misc.Permute', class {});
  4978. this.registerType('torchvision.ops.misc.SqueezeExcitation', class {});
  4979. this.registerType('torchvision.ops.poolers.LevelMapper', class {});
  4980. this.registerType('torchvision.ops.poolers.MultiScaleRoIAlign', class {});
  4981. this.registerType('torchvision.ops.roi_align.RoIAlign', class {});
  4982. this.registerType('torchvision.ops.stochastic_depth.StochasticDepth', class {});
  4983. this.registerType('torchvision.models._api.Weights', class {});
  4984. this.registerType('torchvision.models.alexnet.AlexNet', class {});
  4985. this.registerType('torchvision.models.convnext.ConvNeXt', class {});
  4986. this.registerType('torchvision.models.convnext.CNBlock', class {});
  4987. this.registerType('torchvision.models.convnext.LayerNorm2d', class {});
  4988. this.registerType('torchvision.models.densenet.DenseNet', class extends torch.nn.modules.module.Module {});
  4989. this.registerType('torchvision.models.densenet._DenseBlock', class extends torch.nn.modules.container.ModuleDict {});
  4990. this.registerType('torchvision.models.densenet._DenseLayer', class extends torch.nn.modules.module.Module {});
  4991. this.registerType('torchvision.models.densenet._Transition', class extends torch.nn.modules.container.Sequential {});
  4992. this.registerType('torchvision.models.detection._utils.BalancedPositiveNegativeSampler', class {});
  4993. this.registerType('torchvision.models.detection._utils.BoxCoder', class {});
  4994. this.registerType('torchvision.models.detection._utils.Matcher', class {});
  4995. this.registerType('torchvision.models.detection._utils.SSDMatcher', class {});
  4996. this.registerType('torchvision.models.detection.anchor_utils.AnchorGenerator', class {});
  4997. this.registerType('torchvision.models.detection.anchor_utils.DefaultBoxGenerator', class {});
  4998. this.registerType('torchvision.models.detection.backbone_utils.BackboneWithFPN', class {});
  4999. this.registerType('torchvision.models.detection.faster_rcnn.FasterRCNN', class {});
  5000. this.registerType('torchvision.models.detection.faster_rcnn.FastRCNNConvFCHead', class {});
  5001. this.registerType('torchvision.models.detection.faster_rcnn.FastRCNNPredictor', class {});
  5002. this.registerType('torchvision.models.detection.faster_rcnn.TwoMLPHead', class {});
  5003. this.registerType('torchvision.models.detection.fcos.FCOS', class {});
  5004. this.registerType('torchvision.models.detection.fcos.FCOSHead', class {});
  5005. this.registerType('torchvision.models.detection.fcos.FCOSClassificationHead', class {});
  5006. this.registerType('torchvision.models.detection.fcos.FCOSRegressionHead', class {});
  5007. this.registerType('torchvision.models.detection._utils.BoxLinearCoder', class {});
  5008. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNN', class {});
  5009. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNHeads', class {});
  5010. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNPredictor', class {});
  5011. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNN', class {});
  5012. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNHeads', class {});
  5013. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNPredictor', class {});
  5014. this.registerType('torchvision.models.detection.retinanet.RetinaNet', class {});
  5015. this.registerType('torchvision.models.detection.retinanet.RetinaNetClassificationHead', class {});
  5016. this.registerType('torchvision.models.detection.retinanet.RetinaNetHead', class {});
  5017. this.registerType('torchvision.models.detection.retinanet.RetinaNetRegressionHead', class {});
  5018. this.registerType('torchvision.models.detection.roi_heads.RoIHeads', class {});
  5019. this.registerType('torchvision.models.detection.rpn.AnchorGenerator', class {});
  5020. this.registerType('torchvision.models.detection.rpn.RegionProposalNetwork', class {});
  5021. this.registerType('torchvision.models.detection.rpn.RPNHead', class {});
  5022. this.registerType('torchvision.models.detection.ssd.SSD', class {});
  5023. this.registerType('torchvision.models.detection.ssd.SSDClassificationHead', class {});
  5024. this.registerType('torchvision.models.detection.ssd.SSDHead', class {});
  5025. this.registerType('torchvision.models.detection.ssd.SSDFeatureExtractorVGG', class {});
  5026. this.registerType('torchvision.models.detection.ssd.SSDRegressionHead', class {});
  5027. this.registerType('torchvision.models.detection.ssdlite.SSDLiteClassificationHead', class {});
  5028. this.registerType('torchvision.models.detection.ssdlite.SSDLiteFeatureExtractorMobileNet', class {});
  5029. this.registerType('torchvision.models.detection.ssdlite.SSDLiteHead', class {});
  5030. this.registerType('torchvision.models.detection.ssdlite.SSDLiteRegressionHead', class {});
  5031. this.registerType('torchvision.models.detection.transform.GeneralizedRCNNTransform', class {});
  5032. this.registerType('torchvision.models.efficientnet.EfficientNet', class {});
  5033. this.registerType('torchvision.models.efficientnet.EfficientNet_B3_Weights', class {});
  5034. this.registerType('torchvision.models.efficientnet.FusedMBConv', class {});
  5035. this.registerType('torchvision.models.efficientnet.MBConv', class {});
  5036. this.registerType('torchvision.models.feature_extraction.LeafModuleAwareTracer', class extends torch.fx._symbolic_trace.Tracer {});
  5037. this.registerType('torchvision.models.feature_extraction.NodePathTracer', class extends torchvision.models.feature_extraction.LeafModuleAwareTracer {});
  5038. this.registerType('torchvision.models.googlenet.BasicConv2d', class {});
  5039. this.registerType('torchvision.models.googlenet.GoogLeNet', class {});
  5040. this.registerType('torchvision.models.googlenet.Inception', class {});
  5041. this.registerType('torchvision.models.googlenet.InceptionAux', class {});
  5042. this.registerType('torchvision.models.inception.BasicConv2d', class {});
  5043. this.registerType('torchvision.models.inception.Inception3', class {});
  5044. this.registerType('torchvision.models.inception.InceptionAux', class {});
  5045. this.registerType('torchvision.models.inception.InceptionA', class {});
  5046. this.registerType('torchvision.models.inception.InceptionB', class {});
  5047. this.registerType('torchvision.models.inception.InceptionC', class {});
  5048. this.registerType('torchvision.models.inception.InceptionD', class {});
  5049. this.registerType('torchvision.models.inception.InceptionE', class {});
  5050. this.registerType('torchvision.models.mnasnet._InvertedResidual', class {});
  5051. this.registerType('torchvision.models.mnasnet.MNASNet', class {});
  5052. this.registerType('torchvision.models.maxvit.MaxVit', class {});
  5053. this.registerType('torchvision.models.maxvit.MaxVitBlock', class {});
  5054. this.registerType('torchvision.models.maxvit.MaxVitLayer', class {});
  5055. this.registerType('torchvision.models.maxvit.MBConv', class {});
  5056. this.registerType('torchvision.models.maxvit.PartitionAttentionLayer', class {});
  5057. this.registerType('torchvision.models.maxvit.RelativePositionalMultiHeadAttention', class {});
  5058. this.registerType('torchvision.models.maxvit.SwapAxes', class {});
  5059. this.registerType('torchvision.models.maxvit.WindowDepartition', class {});
  5060. this.registerType('torchvision.models.mobilenet.ConvBNReLU', class {});
  5061. this.registerType('torchvision.models.mobilenet.MobileNetV2', class {});
  5062. this.registerType('torchvision.models.mobilenet.InvertedResidual', class {});
  5063. this.registerType('torchvision.models.mobilenetv2.ConvBNActivation', class {});
  5064. this.registerType('torchvision.models.mobilenetv2.InvertedResidual', class {});
  5065. this.registerType('torchvision.models.mobilenetv2.MobileNetV2', class {});
  5066. this.registerType('torchvision.models.mobilenetv3.InvertedResidual', class {});
  5067. this.registerType('torchvision.models.mobilenetv3.MobileNetV3', class {});
  5068. this.registerType('torchvision.models.mobilenetv3.SqueezeExcitation', class {});
  5069. this.registerType('torchvision.models.regnet.AnyStage', class extends torch.nn.modules.container.Sequential {});
  5070. this.registerType('torchvision.models.regnet.BottleneckTransform', class {});
  5071. this.registerType('torchvision.models.regnet.ResBottleneckBlock', class {});
  5072. this.registerType('torchvision.models.regnet.RegNet', class {});
  5073. this.registerType('torchvision.models.regnet.SimpleStemIN', class {});
  5074. this.registerType('torchvision.models.resnet.Bottleneck', class {});
  5075. this.registerType('torchvision.models.resnet.BasicBlock', class {});
  5076. this.registerType('torchvision.models.quantization.mobilenet.QuantizableInvertedResidual', class {});
  5077. this.registerType('torchvision.models.quantization.mobilenet.QuantizableMobileNetV2', class {});
  5078. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableInvertedResidual', class {});
  5079. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableMobileNetV2', class {});
  5080. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableMobileNetV3', class {});
  5081. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableInvertedResidual', class {});
  5082. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableSqueezeExcitation', class {});
  5083. this.registerType('torchvision.models.quantization.resnet.QuantizableBasicBlock', class {});
  5084. this.registerType('torchvision.models.quantization.resnet.QuantizableBottleneck', class {});
  5085. this.registerType('torchvision.models.quantization.resnet.QuantizableResNet', class {});
  5086. this.registerType('torchvision.models.segmentation.deeplabv3.ASPP', class {});
  5087. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPConv', class {});
  5088. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPPooling', class {});
  5089. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabHead', class {});
  5090. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabV3', class {});
  5091. this.registerType('torchvision.models.segmentation.fcn.FCN', class {});
  5092. this.registerType('torchvision.models.segmentation.fcn.FCNHead', class {});
  5093. this.registerType('torchvision.models.segmentation.lraspp.LRASPP', class {});
  5094. this.registerType('torchvision.models.segmentation.lraspp.LRASPPHead', class {});
  5095. this.registerType('torchvision.models.shufflenetv2.ShuffleNetV2', class {});
  5096. this.registerType('torchvision.models.shufflenetv2.InvertedResidual', class {});
  5097. this.registerType('torchvision.models.squeezenet.Fire', class {});
  5098. this.registerType('torchvision.models.squeezenet.SqueezeNet', class {});
  5099. this.registerType('torchvision.models.swin_transformer.PatchMerging', class {});
  5100. this.registerType('torchvision.models.swin_transformer.PatchMergingV2', class {});
  5101. this.registerType('torchvision.models.swin_transformer.ShiftedWindowAttention', class {});
  5102. this.registerType('torchvision.models.swin_transformer.ShiftedWindowAttentionV2', class {});
  5103. this.registerType('torchvision.models.swin_transformer.SwinTransformer', class {});
  5104. this.registerType('torchvision.models.swin_transformer.SwinTransformerBlock', class {});
  5105. this.registerType('torchvision.models.swin_transformer.SwinTransformerBlockV2', class {});
  5106. this.registerType('torchvision.models.resnet.ResNet', class {});
  5107. this.registerType('torchvision.models.vgg.VGG', class {});
  5108. this.registerType('torchvision.models.video.resnet.BasicBlock', class {});
  5109. this.registerType('torchvision.models.video.resnet.BasicStem', class {});
  5110. this.registerType('torchvision.models.video.resnet.Conv2Plus1D', class {});
  5111. this.registerType('torchvision.models.video.resnet.Conv3DNoTemporal', class {});
  5112. this.registerType('torchvision.models.video.resnet.Conv3DSimple', class {});
  5113. this.registerType('torchvision.models.video.resnet.R2Plus1dStem', class {});
  5114. this.registerType('torchvision.models.video.resnet.VideoResNet', class {});
  5115. this.registerType('torchvision.models.vision_transformer.Encoder', class extends torch.nn.modules.module.Module {});
  5116. this.registerType('torchvision.models.vision_transformer.EncoderBlock', class extends torch.nn.modules.module.Module {});
  5117. this.registerType('torchvision.models.vision_transformer.MLPBlock', class extends torchvision.ops.misc.MLP {});
  5118. this.registerType('torchvision.models.vision_transformer.VisionTransformer', class extends torch.nn.modules.module.Module {});
  5119. this.registerType('torchvision.models._utils.IntermediateLayerGetter', class {});
  5120. this.registerType('torchvision.transforms._presets.ImageClassification', class extends torch.nn.modules.module.Module {});
  5121. this.registerType('torchvision.transforms.autoaugment.AutoAugment', class {});
  5122. this.registerType('torchvision.transforms.autoaugment.AutoAugmentPolicy', class {});
  5123. this.registerType('torchvision.transforms.functional.InterpolationMode', class {});
  5124. this.registerFunction('torchvision.transforms.functional.adjust_brightness');
  5125. this.registerFunction('torchvision.transforms.functional.adjust_contrast');
  5126. this.registerFunction('torchvision.transforms.functional.adjust_brightness');
  5127. this.registerFunction('torchvision.transforms.functional.adjust_contrast');
  5128. this.registerFunction('torchvision.transforms.functional.adjust_gamma');
  5129. this.registerFunction('torchvision.transforms.functional.adjust_hue');
  5130. this.registerFunction('torchvision.transforms.functional.adjust_saturation');
  5131. this.registerType('torchvision.transforms.transforms.ColorJitter', class extends torch.nn.modules.module.Module {});
  5132. this.registerType('torchvision.transforms.transforms.Compose', class {});
  5133. this.registerType('torchvision.transforms.transforms.CenterCrop', class extends torch.nn.modules.module.Module {});
  5134. this.registerType('torchvision.transforms.transforms.GaussianBlur', class extends torch.nn.modules.module.Module {});
  5135. this.registerType('torchvision.transforms.transforms.Grayscale', class extends torch.nn.modules.module.Module {});
  5136. this.registerType('torchvision.transforms.transforms.Lambda', class {});
  5137. this.registerType('torchvision.transforms.transforms.Normalize', class extends torch.nn.modules.module.Module {});
  5138. this.registerType('torchvision.transforms.transforms.RandomAffine', class extends torch.nn.modules.module.Module {});
  5139. this.registerType('torchvision.transforms.transforms.RandomApply', class extends torch.nn.modules.module.Module {});
  5140. this.registerType('torchvision.transforms.transforms.RandomCrop', class extends torch.nn.modules.module.Module {});
  5141. this.registerType('torchvision.transforms.transforms.RandomHorizontalFlip', class extends torch.nn.modules.module.Module {});
  5142. this.registerType('torchvision.transforms.transforms.RandomVerticalFlip', class extends torch.nn.modules.module.Module {});
  5143. this.registerType('torchvision.transforms.transforms.RandomResizedCrop', class extends torch.nn.modules.module.Module {});
  5144. this.registerType('torchvision.transforms.transforms.RandomRotation', class extends torch.nn.modules.module.Module {});
  5145. this.registerType('torchvision.transforms.transforms.Resize', class extends torch.nn.modules.module.Module {});
  5146. this.registerType('torchvision.transforms.transforms.Scale', class extends torch.nn.modules.module.Module {});
  5147. this.registerType('torchvision.transforms.transforms.ToPILImage', class {});
  5148. this.registerType('torchvision.transforms.transforms.ToTensor', class {});
  5149. this.registerType('torchvision.transforms.v2._container.Compose', class {});
  5150. this.registerType('torchvision.transforms.v2._misc.Normalize', class {});
  5151. this.registerType('torchvision.transforms.v2._misc.ToDtype', class {});
  5152. this.registerType('torchvision.transforms.v2._geometry.CenterCrop', class {});
  5153. this.registerType('torchvision.transforms.v2._geometry.Resize', class {});
  5154. this.registerType('torchvision.transforms.v2._geometry.Pad', class {});
  5155. this.registerType('torchvision.transforms.v2._geometry.RandomCrop', class {});
  5156. this.registerType('torchvision.transforms.v2._transform.Transform', class extends torch.nn.modules.module.Module {});
  5157. this.registerType('torchvision.transforms.v2._type_conversion.ToImage', class extends torchvision.transforms.v2._transform.Transform {});
  5158. this.registerFunction('torchvision.models.resnet.resnet18', () => {});
  5159. this.registerFunction('torchvision.models.resnet.resnet34', () => {});
  5160. this.registerFunction('torchvision.models.resnet.resnet50', () => {});
  5161. this.registerFunction('torchvision.models.resnet.resnet101', () => {});
  5162. this.registerFunction('torchvision.models.resnet.resnet152', () => {});
  5163. this.registerFunction('torchvision.models.vision_transformer.vit_h_14', () => {});
  5164. this.registerFunction('torchvision.ops.boxes.box_iou');
  5165. this.registerFunction('builtins.annotate', (type, value) => {
  5166. if (type === self._builtins.int) {
  5167. return Number.isInteger(value) ? value : NaN;
  5168. }
  5169. if (type === self._builtins.float) {
  5170. return typeof value === 'number' ? value : NaN;
  5171. }
  5172. if (type === self._builtins.number) {
  5173. // if (pytorch.Utility.isTensor(value)) {
  5174. // value.resize_([]);
  5175. // }
  5176. }
  5177. return value;
  5178. });
  5179. this.registerFunction('builtins.unchecked_cast', (type, value) => {
  5180. return value;
  5181. });
  5182. this.registerFunction('builtins.uninitialized', (/* type */) => {
  5183. return undefined;
  5184. });
  5185. this.registerFunction('ops.prim.data', (tensor) => {
  5186. return tensor;
  5187. });
  5188. this.registerFunction('ops.prim.device', (tensor) => {
  5189. return tensor.device;
  5190. });
  5191. this.registerFunction('ops.prim.dtype', (tensor) => {
  5192. return tensor.dtype.scalar_type();
  5193. });
  5194. this.registerFunction('ops.prim.is_quantized', (tensor) => {
  5195. return tensor.is_quantized;
  5196. });
  5197. this.registerFunction('ops.prim.is_cuda', (/* tensor */) => {
  5198. return false;
  5199. });
  5200. this.registerFunction('ops.prim.is_nested', (tensor) => {
  5201. return tensor.is_nested;
  5202. });
  5203. this.registerFunction('ops.prim.is_sparse', (tensor) => {
  5204. return tensor.is_sparse;
  5205. });
  5206. this.registerFunction('ops.prim.unchecked_unwrap_optional', (value) => {
  5207. return value;
  5208. });
  5209. this.registerFunction('ops.prim.NumToTensor', (value) => {
  5210. const tensor = self.invoke('torch.Tensor', []);
  5211. tensor.value = value;
  5212. return tensor;
  5213. });
  5214. this.registerFunction('ops.prim.min', (...args) => {
  5215. if (Array.isArray(args[0])) {
  5216. return Math.min.apply(null, args[0]);
  5217. }
  5218. return Math.min.apply(null, args);
  5219. });
  5220. this.registerFunction('ops.prim.max', (...args) => {
  5221. if (Array.isArray(args[0])) {
  5222. return Math.max.apply(null, args[0]);
  5223. }
  5224. return Math.max.apply(null, args);
  5225. });
  5226. this.registerFunction('ops.prim.shape', (tensor) => {
  5227. return tensor && tensor.size ? tensor.size() : undefined;
  5228. });
  5229. this.registerFunction('ops.quantized.conv_prepack', (weight, bias, stride, padding, dilation, groups) => {
  5230. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  5231. params.weight = weight;
  5232. params.bias = bias;
  5233. params.stride = stride;
  5234. params.padding = padding;
  5235. params.dilation = dilation;
  5236. params.groups = groups;
  5237. return params;
  5238. });
  5239. this.registerFunction('ops.quantized.conv1d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  5240. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  5241. params.weight = weight;
  5242. params.bias = bias;
  5243. params.stride = stride;
  5244. params.padding = padding;
  5245. params.dilation = dilation;
  5246. params.groups = groups;
  5247. return params;
  5248. });
  5249. this.registerFunction('ops.quantized.conv2d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  5250. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  5251. params.weight = weight;
  5252. params.bias = bias;
  5253. params.stride = stride;
  5254. params.padding = padding;
  5255. params.dilation = dilation;
  5256. params.groups = groups;
  5257. return params;
  5258. });
  5259. this.registerFunction('ops.quantized.conv3d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  5260. const params = self.invoke('__torch__.torch.classes.quantized.Conv3dPackedParamsBase', []);
  5261. params.weight = weight;
  5262. params.bias = bias;
  5263. params.stride = stride;
  5264. params.padding = padding;
  5265. params.dilation = dilation;
  5266. params.groups = groups;
  5267. return params;
  5268. });
  5269. this.registerFunction('ops.quantized.conv_transpose1d_prepack', (weight, bias, stride, padding, output_padding, dilation, groups) => {
  5270. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  5271. params.weight = weight;
  5272. params.bias = bias;
  5273. params.stride = stride;
  5274. params.padding = padding;
  5275. params.output_padding = output_padding;
  5276. params.dilation = dilation;
  5277. params.groups = groups;
  5278. return params;
  5279. });
  5280. this.registerFunction('ops.quantized.conv_transpose2d_prepack', (weight, bias, stride, padding, output_padding, dilation, groups) => {
  5281. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  5282. params.weight = weight;
  5283. params.bias = bias;
  5284. params.stride = stride;
  5285. params.padding = padding;
  5286. params.output_padding = output_padding;
  5287. params.dilation = dilation;
  5288. params.groups = groups;
  5289. return params;
  5290. });
  5291. this.registerFunction('ops.quantized.linear_prepack', (weight, bias) => {
  5292. const params = self.invoke('__torch__.torch.classes.quantized.LinearPackedParamsBase', []);
  5293. params.weight = weight;
  5294. params.bias = bias;
  5295. return params;
  5296. });
  5297. this.registerFunction('ops.prim.RaiseException', (message) => {
  5298. throw new python.Error(message);
  5299. });
  5300. this.registerFunction('builtins.range', (start, stop, step) => {
  5301. if (stop === undefined && step === undefined) {
  5302. if (Number.isInteger(start)) {
  5303. return Array(start).keys();
  5304. }
  5305. if (isNaN(start)) {
  5306. return [];
  5307. }
  5308. }
  5309. throw new python.Error(`Unsupported range(${JSON.stringify(start)}, ${JSON.stringify(stop)}, ${JSON.stringify(step)})`);
  5310. });
  5311. builtins.xrange = builtins.range;
  5312. this.registerFunction('torch._C._nn.gelu');
  5313. this.registerFunction('torch._C._nn.avg_pool2d');
  5314. this.registerFunction('torch._C._nn.scaled_dot_product_attention');
  5315. this.registerFunction('torch._native_multi_head_attention');
  5316. this.registerFunction('torch._utils._rebuild_sparse_tensor', (layout, data) => {
  5317. if (layout === torch.sparse_coo) {
  5318. return self.invoke('torch._sparse_coo_tensor_unsafe', data);
  5319. }
  5320. throw new python.Error(`Unsupported sparse tensor layout '${layout ? layout.__str__() : ''}'.`);
  5321. });
  5322. this.registerFunction('torch._utils._rebuild_wrapper_subclass');
  5323. this.registerFunction('torch.from_numpy', (obj) => {
  5324. const dtypes = new Map([
  5325. ['<f2', torch.float16],
  5326. ['<f4', torch.float32],
  5327. ['<f8', torch.float64],
  5328. ['<i2', torch.int16],
  5329. ['<i4', torch.int32],
  5330. ['<i8', torch.int64],
  5331. ]);
  5332. if (!dtypes.has(obj.dtype.str)) {
  5333. throw new python.Error(`Unsupported numpy.ndarray type '${obj.dtype.str}'.`);
  5334. }
  5335. const dtype = dtypes.get(obj.dtype.str);
  5336. const strides = obj.strides.map((stride) => stride / obj.itemsize);
  5337. const storage = execution.invoke('torch.storage.TypedStorage', [obj.size, dtype]);
  5338. storage._set_cdata(obj.data);
  5339. const tensor = execution.invoke('torch.Tensor', []);
  5340. tensor.__setstate__([storage, 0, obj.shape, strides]);
  5341. return tensor;
  5342. });
  5343. this.registerFunction('torch._utils._rebuild_device_tensor_from_numpy', (data, dtype, device, requires_grad) => {
  5344. const tensor = execution.invoke('torch.from_numpy', [data]);
  5345. // tensor = tensor.to(dtype, device)
  5346. tensor.requires_grad = requires_grad;
  5347. return tensor;
  5348. });
  5349. this.registerFunction('torch._sparse_coo_tensor_unsafe', (indices, values, size) => {
  5350. const tensor = self.invoke('torch.Tensor', []);
  5351. tensor._layout = torch.sparse_coo;
  5352. tensor._indices = indices;
  5353. tensor._values = values;
  5354. tensor._shape = size;
  5355. return tensor;
  5356. });
  5357. this.registerFunction('torch._utils._rebuild_meta_tensor_no_storage', (dtype, size, stride, requires_grad) => {
  5358. return torch.empty_strided(size, stride, dtype, null, 'meta', false, requires_grad);
  5359. });
  5360. this.registerFunction('torch._utils._rebuild_tensor', (storage, storage_offset, size, stride) => {
  5361. if (Array.isArray(storage) && storage.length === 5 && storage[0] === 'storage') {
  5362. const [, storage_type, , ,size] = storage;
  5363. storage = new storage_type(size);
  5364. }
  5365. const name = `${storage.__class__.__module__}.${storage.__class__.__name__.replace('Storage', 'Tensor')}`;
  5366. const tensor = self.invoke(name, []);
  5367. tensor.__setstate__([storage, storage_offset, size, stride]);
  5368. return tensor;
  5369. });
  5370. this.registerFunction('torch._utils._rebuild_tensor_v2', (storage, storage_offset, size, stride, requires_grad, backward_hooks) => {
  5371. const tensor = execution.invoke('torch._utils._rebuild_tensor', [storage, storage_offset, size, stride]);
  5372. tensor.requires_grad = requires_grad;
  5373. tensor.backward_hooks = backward_hooks;
  5374. return tensor;
  5375. });
  5376. this.registerFunction('torch._utils._rebuild_tensor_v3');
  5377. this.registerFunction('torch._utils._rebuild_parameter', (data, requires_grad, backward_hooks) => {
  5378. const param = self.invoke('torch.nn.parameter.Parameter', [data, requires_grad]);
  5379. param.backward_hooks = backward_hooks;
  5380. return param;
  5381. });
  5382. this.registerFunction('torch._utils._rebuild_parameter_v2', (data, requires_grad, backward_hooks, state) => {
  5383. const param = self.invoke('torch.nn.parameter.Parameter', [data, requires_grad]);
  5384. param.backward_hooks = backward_hooks;
  5385. execution.invoke('torch._utils._set_obj_state', [param, state]);
  5386. return param;
  5387. });
  5388. this.registerFunction('torch._utils._rebuild_parameter_with_state', (data, requires_grad, backward_hooks, state) => {
  5389. const _set_obj_state = (obj, state) => {
  5390. const [dict_state, slots_state] = Array.isArray(state) ? state : [state, null];
  5391. if (dict_state) {
  5392. for (const [k, v] of Object.entries(dict_state)) {
  5393. self.invoke('builtins.setattr', [obj, k, v]);
  5394. }
  5395. }
  5396. if (slots_state) {
  5397. for (const [k, v] of Object.entries(slots_state)) {
  5398. self.invoke('builtins.setattr', [obj, k, v]);
  5399. }
  5400. }
  5401. };
  5402. const param = self.invoke('torch.nn.parameter.Parameter', [data, requires_grad]);
  5403. param._backward_hooks = backward_hooks;
  5404. _set_obj_state(param, state);
  5405. return param;
  5406. });
  5407. this.registerFunction('torch._utils._rebuild_qtensor', (storage, storage_offset, size, stride, quantizer_params, requires_grad, backward_hooks) => {
  5408. const tensor = execution.invoke('torch._utils._rebuild_tensor_v2', [storage, storage_offset, size, stride, requires_grad, backward_hooks]);
  5409. tensor.quantizer_params = quantizer_params;
  5410. return tensor;
  5411. });
  5412. this.registerFunction('torch._utils._set_obj_state', (obj, state) => {
  5413. let dict_state = state;
  5414. let slots_state = null;
  5415. if (state instanceof self.builtins.tuple) {
  5416. if (state.length !== 2) {
  5417. throw new python.Error(`Invalid serialized state: '${state}'.`);
  5418. }
  5419. [dict_state, slots_state] = state;
  5420. }
  5421. if (dict_state) {
  5422. for (const [name, value] of Object.entries(dict_state)) {
  5423. execution.invoke('builtins.setattr', [obj, name, value]);
  5424. }
  5425. }
  5426. if (slots_state) {
  5427. for (const [name, value] of Object.entries(slots_state)) {
  5428. execution.invoke('builtins.setattr', [obj, name, value]);
  5429. }
  5430. }
  5431. return obj;
  5432. });
  5433. this.registerFunction('torch._set_item', (dict, key, value) => {
  5434. dict[key] = value;
  5435. });
  5436. this.registerFunction('torch._tensor._rebuild_from_type_v2', (func, new_type, args, state) => {
  5437. let ret = func(...args);
  5438. if (ret.__class__ !== new_type) {
  5439. // ret = ret.as_subclass(new_type);
  5440. }
  5441. const setstate = execution.invoke('builtins.getattr', [ret.__class__, '__setstate__', torch.Tensor.__setstate__]);
  5442. if (setstate === torch.Tensor.__setstate__) {
  5443. ret = execution.invoke('torch._utils._set_obj_state', [ret, state]);
  5444. } else {
  5445. ret.__setstate__(state);
  5446. }
  5447. return ret;
  5448. });
  5449. this.registerFunction('torch.__and__', (left, right) => {
  5450. return left && right;
  5451. });
  5452. this.registerFunction('torch.__contains__', (dict, key) => {
  5453. return builtins.hasattr(dict, key);
  5454. });
  5455. this.registerFunction('torch.__derive_index', (index, start, step) => {
  5456. return start + index * step;
  5457. });
  5458. this.registerFunction('torch.__is__', (left, right) => {
  5459. if (left === null && right === null) {
  5460. return true;
  5461. }
  5462. if ((left !== null && right === null) || (left === null && right !== null)) {
  5463. return false;
  5464. }
  5465. throw new python.Error("Unsupported 'torch.__is__' expression type.");
  5466. });
  5467. this.registerFunction('torch.__isnot__', (left, right) => {
  5468. if (left === null && right === null) {
  5469. return false;
  5470. }
  5471. if ((left !== null && right === null) || (left === null && right !== null)) {
  5472. return true;
  5473. }
  5474. throw new python.Error("Unsupported 'torch.__isnot__' expression type.");
  5475. });
  5476. this.registerFunction('torch.__not__', (value) => {
  5477. if (typeof value === 'boolean') {
  5478. return !value;
  5479. }
  5480. throw new python.Error("Unsupported 'torch.__not__' expression type.");
  5481. });
  5482. this.registerFunction('torch.__range_length', (lo, hi, step) => {
  5483. if (step === 0) {
  5484. throw new python.Error('range() arg 3 must not be zero');
  5485. }
  5486. if (step > 0 && lo < hi) {
  5487. return 1 + (hi - 1 - lo) / step;
  5488. } else if (step < 0 && lo > hi) {
  5489. return 1 + (lo - 1 - hi) / (0 - step);
  5490. }
  5491. return 0;
  5492. });
  5493. this.registerFunction('torch._nested_tensor_from_mask_left_aligned');
  5494. this.registerFunction('torch._unwrap_optional', (value) => {
  5495. return value;
  5496. });
  5497. this.registerFunction('torch.get_default_dtype', () => {
  5498. torch._default_type = torch._default_type || torch.float32;
  5499. return torch._default_type;
  5500. });
  5501. this.registerFunction('torch.set_default_dtype', (value) => {
  5502. torch._default_type = value;
  5503. });
  5504. this.registerFunction('torch._prims_common.dtype_or_default', (value) => {
  5505. return value || torch.get_default_dtype();
  5506. });
  5507. this.registerFunction('torch.empty_strided', (size, stride, dtype /*, layout, device, pin_memory, requires_grad */) => {
  5508. const shape = size;
  5509. dtype = torch._prims_common.dtype_or_default(dtype);
  5510. size = shape.reduce((a, b) => a * b, 1);
  5511. const storage = execution.invoke('torch.storage.TypedStorage', [size, dtype]);
  5512. const tensor = execution.invoke('torch.Tensor', []);
  5513. tensor.__setstate__([storage, 0, shape, stride]);
  5514. return tensor;
  5515. });
  5516. this.registerFunction('torch.add', (left, right) => {
  5517. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  5518. return left + right;
  5519. }
  5520. if (Array.isArray(left) && Array.isArray(right)) {
  5521. return left.concat(right);
  5522. }
  5523. if (typeof left === 'string' && typeof right === 'string') {
  5524. return left + right;
  5525. }
  5526. throw new python.Error('Unsupported torch.add expression type.');
  5527. });
  5528. this.registerFunction('torch.append', (list, value) => {
  5529. list.push(value);
  5530. return value;
  5531. });
  5532. this.registerFunction('torch.clear', (value) => {
  5533. if (Object(value) === value) {
  5534. for (const key of Object.keys(value)) {
  5535. delete value[key];
  5536. }
  5537. }
  5538. });
  5539. this.registerFunction('torch.cosine_similarity');
  5540. this.registerFunction('torch.extend', (list, value) => {
  5541. list.push(...value);
  5542. });
  5543. this.registerFunction('torch.insert', (list, index, value) => {
  5544. list.splice(index, 0, value);
  5545. return value;
  5546. });
  5547. this.registerFunction('torch.replace', (value, oldvalue, newvalue /*, max */) => {
  5548. return value.replace(oldvalue, newvalue);
  5549. });
  5550. this.registerFunction('torch.dict', (args) => {
  5551. const obj = {};
  5552. if (args) {
  5553. if (Array.isArray(args)) {
  5554. for (const [key, value] of args) {
  5555. obj[key] = value;
  5556. }
  5557. } else {
  5558. throw new python.Error("'torch.dict' arguments not supported.");
  5559. }
  5560. }
  5561. return obj;
  5562. });
  5563. this.registerFunction('torch.dim', (tensor) => {
  5564. if (tensor && tensor.size) {
  5565. const size = tensor.size();
  5566. if (size) {
  5567. return size.length;
  5568. }
  5569. }
  5570. return NaN;
  5571. });
  5572. this.registerFunction('torch.numel', (tensor) => {
  5573. if (tensor && tensor.size) {
  5574. const size = tensor.size();
  5575. if (size) {
  5576. return size.reduce((a, b) => a * b, 1);
  5577. }
  5578. }
  5579. return NaN;
  5580. });
  5581. this.registerFunction('torch.eq', (left, right) => {
  5582. const value = (x) => x && x.__class__ && x.__class__.__module__ === 'torch' && x.__class__.__name__ === 'Value' ? x.value : x;
  5583. left = value(left);
  5584. right = value(right);
  5585. if (typeof left === 'string' && typeof right === 'string') {
  5586. return left === right;
  5587. }
  5588. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  5589. if (isNaN(left) && isNaN(right)) {
  5590. return true;
  5591. }
  5592. return left === right;
  5593. }
  5594. if (left === undefined || right === undefined) {
  5595. return true;
  5596. }
  5597. if (Array.isArray(left) && Array.isArray(right)) {
  5598. return left.length === right.length && left.every((item, index) => item === right[index]);
  5599. }
  5600. throw new python.Error("Unsupported 'torch.eq' expression type.");
  5601. });
  5602. this.registerFunction('torch.floor', (value) => {
  5603. return Math.floor(value);
  5604. });
  5605. this.registerFunction('torch.ceil', (value) => {
  5606. return Math.ceil(value);
  5607. });
  5608. this.registerFunction('torch.floordiv', (left, right) => {
  5609. return Math.floor(left / right);
  5610. });
  5611. this.registerFunction('torch.format', (...args) => {
  5612. const list = args.shift().split(/({}D?)/);
  5613. return list.map((text) => {
  5614. if (text === '{}' || text === '{}D') {
  5615. const arg = args.shift();
  5616. if (Array.isArray(arg)) {
  5617. return `[${arg.map((item) => item.toString()).join(', ')}]`;
  5618. }
  5619. return arg ? arg.toString() : '?';
  5620. }
  5621. return text;
  5622. }).join('');
  5623. });
  5624. this.registerFunction('torch.strip', (self, chars) => {
  5625. chars = chars || '\\n\\t\\f\\v';
  5626. const regex = new RegExp(`[${chars}]`, 'g');
  5627. return self.replace(regex, '');
  5628. });
  5629. this.registerFunction('torch.gt', (left, right) => {
  5630. const value = (x) => x && x.__class__ && x.__class__.__module__ === 'torch' && x.__class__.__name__ === 'Value' ? x.value : x;
  5631. left = value(left);
  5632. right = value(right);
  5633. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  5634. if (!isNaN(left) && !isNaN(right)) {
  5635. return left > right;
  5636. }
  5637. }
  5638. if (isNaN(left) && !isNaN(right)) {
  5639. return true;
  5640. }
  5641. throw new python.Error("Unsupported 'torch.gt' expression type.");
  5642. });
  5643. this.registerFunction('torch.ge', (left, right) => {
  5644. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  5645. if (!isNaN(left) && !isNaN(right)) {
  5646. return left > right;
  5647. }
  5648. }
  5649. if (isNaN(left) && !isNaN(right)) {
  5650. return true;
  5651. }
  5652. throw new python.Error("Unsupported 'torch.ge' expression type.");
  5653. });
  5654. this.registerFunction('torch.is_floating_point', (tensor) => {
  5655. const type = tensor.dtype.scalar_type();
  5656. return (type === 5 || type === 6 || type === 7);
  5657. });
  5658. this.registerFunction('torch.is_grad_enabled', () => {
  5659. return false;
  5660. });
  5661. this.registerFunction('torch.isfinite');
  5662. this.registerFunction('torch.set_grad_enabled', (/* value */) => {
  5663. });
  5664. this.registerFunction('torch.serialization._get_layout', (name) => {
  5665. const value = name.startsWith('torch.') ? torch[name.split('.')[1]] : null;
  5666. return value instanceof torch.layout ? value : null;
  5667. });
  5668. this.registerFunction('torch.storage._load_from_bytes', (b) => {
  5669. return torch.load(b);
  5670. });
  5671. this.registerFunction('torch.jit._pickle.build_boollist', (data) => {
  5672. return data;
  5673. });
  5674. this.registerFunction('torch.jit._pickle.build_doublelist', (data) => {
  5675. return data;
  5676. });
  5677. this.registerFunction('torch.jit._pickle.build_intlist', (data) => {
  5678. return data;
  5679. });
  5680. this.registerFunction('torch.jit._pickle.build_tensorlist', (data) => {
  5681. return data;
  5682. });
  5683. this.registerFunction('torch.jit._pickle.build_tensor_from_id', (data) => {
  5684. return self.builtins.CONSTANTS[`c${data}`];
  5685. });
  5686. this.registerFunction('torch.jit._pickle.restore_type_tag', (value /*, type_str */) => {
  5687. return value;
  5688. });
  5689. this.registerFunction('torch.keys', (dict) => {
  5690. return Object.keys(dict);
  5691. });
  5692. this.registerFunction('torch.len', (value) => {
  5693. if (Array.isArray(value)) {
  5694. return value.length;
  5695. }
  5696. if (value && value.shape && value.__len__) {
  5697. return value.__len__();
  5698. }
  5699. return NaN;
  5700. });
  5701. this.registerFunction('torch.le', (left, right) => {
  5702. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  5703. if (isNaN(left) || isNaN(right)) {
  5704. return false;
  5705. }
  5706. return left <= right;
  5707. }
  5708. if (left === undefined || right === undefined) {
  5709. return true;
  5710. }
  5711. throw new python.Error("Unsupported 'torch.le' expression type.");
  5712. });
  5713. this.registerFunction('torch.list', (args) => {
  5714. return args;
  5715. });
  5716. this.registerFunction('torch.list_with_default', (size /*, defaults */) => {
  5717. return size;
  5718. });
  5719. this.registerType('torch.PyTorchFileReader', class {
  5720. constructor(entries) {
  5721. let prefix = 0;
  5722. const paths = Array.from(entries.keys()).map((path) => path.replace(/\\/g, '/').split('/').reverse());
  5723. for (let set = new Set(); set && paths.length > 0;) {
  5724. set = new Set(paths.map((path) => path.length > 1 ? path.pop() : null));
  5725. set = set.size > 1 || set.keys().next().value === null ? null : set;
  5726. prefix += set ? set.keys().next().value.length + 1 : 0;
  5727. }
  5728. this._records = new Map(Array.from(entries).map(([name, value]) => [name.substring(prefix), value]));
  5729. this._version = '0';
  5730. const stream = this.get_record('.data/version') || this.get_record('version') || null;
  5731. if (stream) {
  5732. const decoder = new TextDecoder('utf-8');
  5733. const buffer = stream.peek();
  5734. const text = decoder.decode(buffer);
  5735. this._version = text.split('\n').shift().trim();
  5736. }
  5737. }
  5738. has_record(name) {
  5739. return this._records.has(name);
  5740. }
  5741. get_record(name) {
  5742. return this._records.get(name);
  5743. }
  5744. get_all_records() {
  5745. return Array.from(this._records.keys());
  5746. }
  5747. version() {
  5748. return this._version;
  5749. }
  5750. });
  5751. this.registerFunction('torch.load', (f) => {
  5752. const legacy_load = (entries) => {
  5753. const deserialized_objects = {};
  5754. if (entries.has('storages')) {
  5755. const data = entries.get('storages');
  5756. const unpickler = execution.invoke('pickle.Unpickler', [data]);
  5757. const num_storages = unpickler.load();
  5758. for (let i = 0; i < num_storages; i++) {
  5759. const args = unpickler.load();
  5760. const [key, , storage_type] = args;
  5761. const obj = storage_type._new_with_file(unpickler);
  5762. deserialized_objects[key] = obj;
  5763. }
  5764. /*
  5765. let storage_views = unpickler.load();
  5766. for target_cdata, root_cdata, offset, size in storage_views:
  5767. root = deserialized_objects[root_cdata]
  5768. deserialized_objects[target_cdata] = root[offset:offset + size]
  5769. */
  5770. }
  5771. if (entries.has('tensors')) {
  5772. const data = entries.get('tensors');
  5773. const unpickler = execution.invoke('pickle.Unpickler', [data]);
  5774. const num_tensors = unpickler.load();
  5775. const int32 = (unpickler) => {
  5776. const buffer = unpickler.read(4);
  5777. return buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24);
  5778. };
  5779. const int64 = (unpickler) => {
  5780. const buffer = unpickler.read(8);
  5781. if (buffer[6] !== 0 && buffer[7] !== 0) {
  5782. throw new python.Error('Unsigned 64-bit value exceeds 32-bit range.');
  5783. }
  5784. return buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24) + (buffer[4] * 4294967296) + (buffer[5] * 1099511627776);
  5785. };
  5786. for (let i = 0; i < num_tensors; i++) {
  5787. const args = unpickler.load();
  5788. const [key, storage_id] = args;
  5789. const storage = deserialized_objects[storage_id];
  5790. const ndim = int32(unpickler);
  5791. unpickler.read(4);
  5792. const shape = Array.from(new Array(ndim)).map(() => int64(unpickler));
  5793. const stride = Array.from(new Array(ndim)).map(() => int64(unpickler));
  5794. const storage_offset = int64(unpickler);
  5795. const tensor = execution.invoke('torch._utils._rebuild_tensor', [storage, storage_offset, shape, stride]);
  5796. deserialized_objects[key] = tensor;
  5797. }
  5798. }
  5799. const data = entries.get('pickle');
  5800. const unpickler = execution.invoke('pickle.Unpickler', [data]);
  5801. unpickler.persistent_load = (saved_id) => deserialized_objects[saved_id];
  5802. return unpickler.load();
  5803. };
  5804. const _legacy_load = () => {
  5805. const unpickler = execution.invoke('pickle.Unpickler', [f]);
  5806. unpickler.load(); // magic_number
  5807. const protocol_version = unpickler.load();
  5808. if (protocol_version !== 1001) {
  5809. throw new python.Error(`Unsupported protocol version '${protocol_version}'.`);
  5810. }
  5811. const sys_info = unpickler.load();
  5812. if (sys_info.get('protocol_version') !== 1001) {
  5813. throw new python.Error(`Unsupported protocol version '${sys_info.protocol_version}'.`);
  5814. }
  5815. if (sys_info.get('little_endian') === false) {
  5816. throw new python.Error("Unsupported big-endian storage data.");
  5817. }
  5818. const module_source_map = new Map();
  5819. const deserialized_objects = new Map();
  5820. unpickler.persistent_load = (saved_id) => {
  5821. switch (saved_id[0]) {
  5822. case 'module': {
  5823. const [, module, ,source] = saved_id;
  5824. module_source_map.set(module, source);
  5825. return saved_id[1];
  5826. }
  5827. case 'storage': {
  5828. const [, storage_type, key, , size, view_metadata] = saved_id;
  5829. if (!deserialized_objects.has(key)) {
  5830. const obj = new storage_type(size);
  5831. deserialized_objects.set(key, obj);
  5832. }
  5833. if (view_metadata) {
  5834. const view_key = view_metadata.shift();
  5835. view_metadata.shift(); // view_offset
  5836. view_metadata.shift(); // view_size
  5837. if (!deserialized_objects.has(view_key)) {
  5838. const view = null; // storage.slice(view_offset, view_offset + view_size);
  5839. deserialized_objects.set(view_key, view);
  5840. }
  5841. return deserialized_objects.get(view_key);
  5842. }
  5843. return deserialized_objects.get(key);
  5844. }
  5845. default: {
  5846. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  5847. }
  5848. }
  5849. };
  5850. const obj = unpickler.load();
  5851. const deserialized_storage_keys = unpickler.load();
  5852. for (const deserialized_storage_key of deserialized_storage_keys) {
  5853. const storage = deserialized_objects.get(deserialized_storage_key);
  5854. storage._set_from_file(unpickler);
  5855. }
  5856. if (!obj) {
  5857. throw new python.Error('File format is not PyTorch.');
  5858. }
  5859. if (obj === 'None') {
  5860. throw new python.Error("File contains 'None' root object.");
  5861. }
  5862. return obj;
  5863. };
  5864. const _load = (entries) => {
  5865. if (f.has('constant.pkl')) {
  5866. throw python.Error("TorchScript 'torch.load' not supported.");
  5867. }
  5868. const loaded_storages = new Map();
  5869. const persistent_load = (saved_id) => {
  5870. switch (saved_id[0]) {
  5871. case 'storage': {
  5872. const [, storage_type, key, , numel] = saved_id;
  5873. if (!loaded_storages.has(key)) {
  5874. const storage = new storage_type(numel);
  5875. const name = `data/${key}`;
  5876. const stream = entries.get(name);
  5877. storage._set_cdata(stream);
  5878. loaded_storages.set(key, storage);
  5879. }
  5880. return loaded_storages.get(key);
  5881. }
  5882. default: {
  5883. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  5884. }
  5885. }
  5886. };
  5887. const data_file = entries.get('data.pkl');
  5888. const unpickler = execution.invoke('pickle.Unpickler', [data_file]);
  5889. unpickler.persistent_load = persistent_load;
  5890. const result = unpickler.load();
  5891. return result;
  5892. };
  5893. if (f instanceof Map) {
  5894. const reader = new torch.PyTorchFileReader(f);
  5895. const records = reader.get_all_records().map((name) => [name, reader.get_record(name)]);
  5896. f = new Map(records);
  5897. if (f.has('pickle')) {
  5898. return legacy_load(f);
  5899. }
  5900. if (f.has('data.pkl')) {
  5901. return _load(f);
  5902. }
  5903. throw new python.Error(`Unsupported 'torch.load' input '${JSON.stringify(Array.from(f.keys()))}'.`);
  5904. }
  5905. return _legacy_load(f);
  5906. });
  5907. this.registerFunction('torch.log10');
  5908. this.registerFunction('torch.lt', (left, right) => {
  5909. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  5910. return left < right;
  5911. }
  5912. throw new python.Error("Unsupported 'torch.lt' expression type.");
  5913. });
  5914. this.registerFunction('torch.mul', (left, right) => {
  5915. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  5916. return left * right;
  5917. }
  5918. if (isNaN(left) || isNaN(right)) {
  5919. return NaN;
  5920. }
  5921. if (Array.isArray(left) && left.every((value) => typeof value === 'number' || value instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  5922. return left.map((value) => value * right);
  5923. }
  5924. throw new python.Error("Unsupported 'torch.mul' expression type.");
  5925. });
  5926. this.registerFunction('torch.div', (left, right) => {
  5927. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  5928. return left / right;
  5929. }
  5930. if (isNaN(left) || isNaN(right)) {
  5931. return NaN;
  5932. }
  5933. throw new python.Error("Unsupported 'torch.div' expression type.");
  5934. });
  5935. this.registerFunction('torch.round', (value) => {
  5936. if (typeof value === 'number' || value instanceof Number) {
  5937. return Math.round(value);
  5938. }
  5939. if (isNaN(value)) {
  5940. return value;
  5941. }
  5942. throw new python.Error("Unsupported 'torch.round' expression type.");
  5943. });
  5944. this.registerFunction('torch.remainder', (left, right) => {
  5945. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  5946. return left % right;
  5947. }
  5948. if (isNaN(left) || isNaN(right)) {
  5949. return NaN;
  5950. }
  5951. throw new python.Error("Unsupported 'torch.remainder' expression type.");
  5952. });
  5953. this.registerFunction('torch.ne', (left, right) => {
  5954. const value = (x) => x && x.__class__ && x.__class__.__module__ === 'torch' && x.__class__.__name__ === 'Value' ? x.value : x;
  5955. left = value(left);
  5956. right = value(right);
  5957. if (typeof left === 'boolean' && typeof right === 'boolean') {
  5958. return left !== right;
  5959. }
  5960. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  5961. if (isNaN(left) || isNaN(right)) {
  5962. return false;
  5963. }
  5964. return left !== right;
  5965. }
  5966. if (Array.isArray(left) && Array.isArray(right) && left.length === right.length) {
  5967. return false;
  5968. }
  5969. if (typeof left === 'string' && typeof right === 'string') {
  5970. return left !== right;
  5971. }
  5972. if (left === undefined || right === undefined) {
  5973. return true;
  5974. }
  5975. throw new python.Error("Unsupported 'torch.ne' expression type.");
  5976. });
  5977. this.registerFunction('torch.neg', (value) => {
  5978. if (typeof value === 'number') {
  5979. return -value;
  5980. }
  5981. throw new python.Error("Unsupported 'torch.neg' expression type.");
  5982. });
  5983. this.registerFunction('torch.pow', (left, right) => {
  5984. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  5985. return Math.pow(left, right);
  5986. }
  5987. throw new python.Error("Unsupported 'torch.pow' expression type.");
  5988. });
  5989. this.registerFunction('torch.q_scale', (/* tensor */) => {
  5990. return -1;
  5991. });
  5992. this.registerFunction('torch.t', (tensor) => {
  5993. return tensor;
  5994. });
  5995. this.registerFunction('torch.size', (tensor, dim) => {
  5996. if (tensor && tensor.size) {
  5997. const size = tensor.size();
  5998. if (Array.isArray(size)) {
  5999. if (dim === undefined) {
  6000. return size;
  6001. }
  6002. if (Number.isInteger(dim)) {
  6003. if (dim >= 0 && dim < size.length) {
  6004. return size[dim];
  6005. }
  6006. if (dim < 0 && -dim < size.length) {
  6007. return size[size.length + dim];
  6008. }
  6009. }
  6010. throw new python.Error(`Dimension out of range (expected to be in range of ${JSON.stringify(size)}, but got ${JSON.stringify(dim)}).`);
  6011. }
  6012. }
  6013. if (Number.isInteger(dim)) {
  6014. return NaN;
  6015. }
  6016. return [];
  6017. });
  6018. this.registerFunction('torch.sqrt', (x) => {
  6019. return Math.sqrt(x);
  6020. });
  6021. this.registerFunction('torch.slice', (l, start, end, step) => {
  6022. if (!Array.isArray(l)) {
  6023. throw new python.Error('Slicing expected array');
  6024. }
  6025. step = step || 1;
  6026. if (step !== 1) {
  6027. throw new python.Error('Slicing only supports step=1');
  6028. }
  6029. start = Math.max(0, start >= 0 ? start : l.length + start);
  6030. end = Math.min(l.length, end || Number.MAX_SAFE_INTEGER);
  6031. return l.slice(start, end);
  6032. });
  6033. this.registerFunction('torch.sub', (left, right) => {
  6034. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  6035. return left - right;
  6036. }
  6037. throw new python.Error("Unsupported 'torch.sub' expression type.");
  6038. });
  6039. this.registerFunction('torch.sym_int');
  6040. this.registerFunction('torch.sym_ite');
  6041. this.registerFunction('torch.sym_max');
  6042. this.registerFunction('torch.sym_min');
  6043. this.registerFunction('torch.sym_not');
  6044. this.registerFunction('torch.sym_sqrt');
  6045. this.registerFunction('torch.sym_sqrt');
  6046. this.registerFunction('torch.functional.einsum');
  6047. this.registerFunction('torch.functional.norm');
  6048. this.registerFunction('torch.functional.split');
  6049. this.registerFunction('torch.nn.init.constant_');
  6050. this.registerFunction('torch.nn.init.xavier_uniform_');
  6051. this.registerFunction('torch.nn.functional.adaptive_avg_pool2d');
  6052. this.registerFunction('torch.nn.functional.binary_cross_entropy');
  6053. this.registerFunction('torch.nn.functional.binary_cross_entropy_with_logits');
  6054. this.registerFunction('torch.nn.functional.cross_entropy');
  6055. this.registerFunction('torch.nn.functional.elu');
  6056. this.registerFunction('torch.nn.functional.gelu');
  6057. this.registerFunction('torch.nn.functional.hardsigmoid');
  6058. this.registerFunction('torch.nn.functional.hardswish');
  6059. this.registerFunction('torch.nn.functional.hardtanh');
  6060. this.registerFunction('torch.nn.functional.interpolate');
  6061. this.registerFunction('torch.nn.functional.leaky_relu');
  6062. this.registerFunction('torch.nn.functional.l1_loss');
  6063. this.registerFunction('torch.nn.functional.linear');
  6064. this.registerFunction('torch.nn.functional.log_softmax');
  6065. this.registerFunction('torch.nn.functional._max_pool2d');
  6066. this.registerFunction('torch.nn.functional.max_pool2d_with_indices');
  6067. this.registerFunction('torch.nn.functional.mse_loss');
  6068. this.registerFunction('torch.nn.functional.pad');
  6069. this.registerFunction('torch.nn.functional.relu');
  6070. this.registerFunction('torch.nn.functional.relu6');
  6071. this.registerFunction('torch.nn.functional.sigmoid');
  6072. this.registerFunction('torch.nn.functional.silu');
  6073. this.registerFunction('torch.nn.functional.softmax');
  6074. this.registerFunction('torch.nn.functional.tanh');
  6075. this.registerFunction('torch.values', (dict) => {
  6076. return Object.values(dict);
  6077. });
  6078. this.registerFunction('torch.warn', () => {
  6079. });
  6080. this.registerType('torch._ops.OperatorBase', class {
  6081. constructor() {
  6082. this.functorch_table = {};
  6083. }
  6084. });
  6085. this.registerType('torch._ops.HigherOrderOperator', class extends torch._ops.OperatorBase {
  6086. constructor(name, cacheable) {
  6087. super();
  6088. this._name = name;
  6089. this.__name__ = name;
  6090. // _higher_order_ops[name] = this;
  6091. this._ns = 'higher_order';
  6092. this.__module__ = 'torch.ops.higher_order';
  6093. this._cacheable = cacheable;
  6094. }
  6095. });
  6096. this.registerType('torch.Type', class {
  6097. constructor(kind, annotation_str) {
  6098. this._kind = kind;
  6099. if (annotation_str) {
  6100. this._annotation_str = annotation_str;
  6101. }
  6102. }
  6103. static get(kind, annotation_str) {
  6104. return new torch.Type(kind, annotation_str);
  6105. }
  6106. kind() {
  6107. return this._kind;
  6108. }
  6109. annotation_str() {
  6110. return this._annotation_str;
  6111. }
  6112. equals(/* rhs */) {
  6113. throw new python.Error(`Not implemented '${this.kind()}'.`);
  6114. }
  6115. isSubtypeOf(/* rhs */) {
  6116. throw new python.Error(`Not implemented '${this.kind()}'.`);
  6117. }
  6118. str() {
  6119. if (this._kind === 'VarType' && this._annotation_str) {
  6120. return this._annotation_str;
  6121. } else if (this._kind === 'ScalarTypeType') {
  6122. return 'ScalarType';
  6123. } else if (this._kind === 'QSchemeType') {
  6124. return 'QScheme';
  6125. } else if (this._kind) {
  6126. return this._kind;
  6127. }
  6128. throw new python.Error(`Not implemented '${this.kind()}'.`);
  6129. }
  6130. __str__() {
  6131. return this.str();
  6132. }
  6133. toString() {
  6134. return this.__str__();
  6135. }
  6136. });
  6137. this.registerType('torch.ClassType', class extends torch.Type {
  6138. constructor(qualified_name, cu, is_module) {
  6139. super('ClassType');
  6140. this._qualified_name = qualified_name;
  6141. this._is_module = is_module;
  6142. this._attributes = new Map();
  6143. this._methods = new Map();
  6144. this._staticmethods = new Map();
  6145. }
  6146. qualified_name() {
  6147. return this._qualified_name;
  6148. }
  6149. name() {
  6150. return this._qualified_name.split('.').pop();
  6151. }
  6152. is_module() {
  6153. return this._is_module;
  6154. }
  6155. addMethod(func) {
  6156. this._methods.set(func.name, func);
  6157. }
  6158. findMethod(name) {
  6159. return this._methods.get(name);
  6160. }
  6161. addStaticMethod(func) {
  6162. this._staticmethods.set(func.name, func);
  6163. }
  6164. findStaticMethod(name) {
  6165. return this._staticmethods.get(name);
  6166. }
  6167. addAttribute(name, type) {
  6168. this._attributes.set(name, type);
  6169. }
  6170. findAttribute(name) {
  6171. return this._attributes.get(name);
  6172. }
  6173. hasConstant(/* name */) {
  6174. }
  6175. methods() {
  6176. }
  6177. str() {
  6178. return this.qualified_name();
  6179. }
  6180. });
  6181. this.registerType('torch.OptionalType', class extends torch.Type {
  6182. constructor(elem) {
  6183. super('OptionalType');
  6184. this._elem = elem;
  6185. }
  6186. static get(elem) {
  6187. return new torch.OptionalType(elem);
  6188. }
  6189. getElementType() {
  6190. return this._elem;
  6191. }
  6192. str() {
  6193. return `${this.getElementType().str()}?`;
  6194. }
  6195. __str__() {
  6196. return `Optional[${this.getElementType().__str__()}]`;
  6197. }
  6198. });
  6199. this.registerType('torch.ListType', class extends torch.Type {
  6200. constructor(elem) {
  6201. super('ListType');
  6202. this._elem = elem;
  6203. }
  6204. static get(elem) {
  6205. return new torch.ListType(elem);
  6206. }
  6207. getElementType() {
  6208. return this._elem;
  6209. }
  6210. str() {
  6211. return `${this.getElementType().str()}[]`;
  6212. }
  6213. __str__() {
  6214. return `List[${this.getElementType().__str__()}]`;
  6215. }
  6216. });
  6217. this.registerType('torch.FutureType', class extends torch.Type {
  6218. constructor(elem) {
  6219. super('FutureType');
  6220. this._elem = elem;
  6221. }
  6222. static get(elem) {
  6223. return new torch.FutureType(elem);
  6224. }
  6225. getElementType() {
  6226. return this._elem;
  6227. }
  6228. str() {
  6229. return `Future(${this.getElementType().str()})`;
  6230. }
  6231. __str__() {
  6232. return `Future[${this.getElementType().__str__()}]`;
  6233. }
  6234. });
  6235. this.registerType('torch.RRefType', class extends torch.Type {
  6236. constructor(elem) {
  6237. super('RRefType');
  6238. this._elem = elem;
  6239. }
  6240. get(elem) {
  6241. return new torch.RRefType(elem);
  6242. }
  6243. getElementType() {
  6244. return this._elem;
  6245. }
  6246. str() {
  6247. return `RRef(${this.getElementType().str()})`;
  6248. }
  6249. __str__() {
  6250. return `RRef[${this.getElementType().__str__()}]`;
  6251. }
  6252. });
  6253. this.registerType('torch.AwaitType', class extends torch.Type {
  6254. constructor(elem) {
  6255. super('AwaitType');
  6256. this._elem = elem;
  6257. }
  6258. static get(elem) {
  6259. return new torch.AwaitType(elem);
  6260. }
  6261. getElementType() {
  6262. return this._elem;
  6263. }
  6264. str() {
  6265. return `Await(${this.getElementType().str()})`;
  6266. }
  6267. __str__() {
  6268. return `Await[${this.getElementType().__str__()}]`;
  6269. }
  6270. });
  6271. this.registerType('torch.TupleType', class extends torch.Type {
  6272. constructor(elements) {
  6273. super('TupleType');
  6274. this._elements = elements;
  6275. }
  6276. static get(elements) {
  6277. return new torch.TupleType(elements);
  6278. }
  6279. elements() {
  6280. return this._elements;
  6281. }
  6282. str() {
  6283. return `(${this.elements().map((elem) => elem.str()).join(', ')})`;
  6284. }
  6285. __str__() {
  6286. return `Tuple[${this.elements().map((elem) => elem.__str__()).join(', ')}]`;
  6287. }
  6288. });
  6289. this.registerType('torch.AnyType', class extends torch.Type {
  6290. constructor() {
  6291. super('AnyType');
  6292. }
  6293. static get() {
  6294. torch.AnyType.value = torch.AnyType.value || new torch.AnyType();
  6295. return torch.AnyType.value;
  6296. }
  6297. str() {
  6298. return 'AnyType';
  6299. }
  6300. });
  6301. this.registerType('torch.NoneType', class extends torch.Type {
  6302. constructor() {
  6303. super('NoneType');
  6304. }
  6305. static get() {
  6306. torch.NoneType.value = torch.NoneType.value || new torch.NoneType();
  6307. return torch.NoneType.value;
  6308. }
  6309. str() {
  6310. return 'NoneType';
  6311. }
  6312. __str__() {
  6313. return 'NoneType';
  6314. }
  6315. });
  6316. this.registerType('torch.TensorType', class extends torch.Type {
  6317. constructor() {
  6318. super('TensorType');
  6319. }
  6320. static get() {
  6321. torch.TensorType.value = torch.TensorType.value || new torch.TensorType();
  6322. return torch.TensorType.value;
  6323. }
  6324. str() {
  6325. return 'Tensor';
  6326. }
  6327. __str__() {
  6328. return 'Tensor';
  6329. }
  6330. });
  6331. this.registerType('torch.NumberType', class extends torch.Type {
  6332. constructor() {
  6333. super('NumberType');
  6334. }
  6335. static get() {
  6336. torch.NumberType.value = torch.NumberType.value || new torch.NumberType();
  6337. return torch.NumberType.value;
  6338. }
  6339. str() {
  6340. return 'Scalar';
  6341. }
  6342. __str__() {
  6343. return 'number';
  6344. }
  6345. });
  6346. this.registerType('torch.BoolType', class extends torch.Type {
  6347. constructor() {
  6348. super('BoolType');
  6349. }
  6350. static get() {
  6351. torch.BoolType.value = torch.BoolType.value || new torch.BoolType();
  6352. return torch.BoolType.value;
  6353. }
  6354. equals(rhs) {
  6355. return this.kind() === rhs.kind();
  6356. }
  6357. str() {
  6358. return 'bool';
  6359. }
  6360. __str__() {
  6361. return 'bool';
  6362. }
  6363. });
  6364. this.registerType('torch.IntType', class extends torch.Type {
  6365. constructor() {
  6366. super('IntType');
  6367. }
  6368. static get() {
  6369. torch.IntType.value = torch.IntType.value || new torch.IntType();
  6370. return torch.IntType.value;
  6371. }
  6372. equals(rhs) {
  6373. return this.kind() === rhs.kind();
  6374. }
  6375. isSubtypeOf(rhs) {
  6376. return this.kind() === 'NumberType' || super.isSubtypeOf(rhs);
  6377. }
  6378. str() {
  6379. return 'int';
  6380. }
  6381. __str__() {
  6382. return 'int';
  6383. }
  6384. });
  6385. this.registerType('torch.SymIntType', class extends torch.Type {
  6386. constructor() {
  6387. super('SymIntType');
  6388. }
  6389. static get() {
  6390. torch.SymIntType.value = torch.SymIntType.value || new torch.SymIntType();
  6391. return torch.SymIntType.value;
  6392. }
  6393. equals(rhs) {
  6394. return this.kind() === rhs.kind();
  6395. }
  6396. str() {
  6397. return 'SymInt';
  6398. }
  6399. __str__() {
  6400. return 'int';
  6401. }
  6402. });
  6403. this.registerType('torch.FloatType', class extends torch.Type {
  6404. constructor() {
  6405. super('FloatType');
  6406. }
  6407. static get() {
  6408. torch.FloatType.value = torch.FloatType.value || new torch.FloatType();
  6409. return torch.FloatType.value;
  6410. }
  6411. equals(rhs) {
  6412. return this.kind() === rhs.kind();
  6413. }
  6414. isSubtypeOf(rhs) {
  6415. return this.kind() === 'NumberType' || super.isSubtypeOf(rhs);
  6416. }
  6417. str() {
  6418. return 'float';
  6419. }
  6420. __str__() {
  6421. return 'float';
  6422. }
  6423. });
  6424. this.registerType('torch.StringType', class extends torch.Type {
  6425. constructor() {
  6426. super('StringType');
  6427. }
  6428. static get() {
  6429. torch.StringType.value = torch.StringType.value || new torch.StringType();
  6430. return torch.StringType.value;
  6431. }
  6432. equals(rhs) {
  6433. return this.kind() === rhs.kind();
  6434. }
  6435. str() {
  6436. return 'str';
  6437. }
  6438. __str__() {
  6439. return 'str';
  6440. }
  6441. });
  6442. this.registerType('torch.ComplexType', class extends torch.Type {
  6443. constructor() {
  6444. super('ComplexType');
  6445. }
  6446. static get() {
  6447. torch.ComplexType.value = torch.ComplexType.value || new torch.ComplexType();
  6448. return torch.ComplexType.value;
  6449. }
  6450. equals(rhs) {
  6451. return this.kind() === rhs.kind();
  6452. }
  6453. isSubtypeOf(rhs) {
  6454. return this.kind() === 'NumberType' || super.isSubtypeOf(rhs);
  6455. }
  6456. str() {
  6457. return 'complex';
  6458. }
  6459. __str__() {
  6460. return 'complex';
  6461. }
  6462. });
  6463. this.registerType('torch.DictType', class extends torch.Type {
  6464. constructor(key, value) {
  6465. super('DictType');
  6466. this._key = key;
  6467. this._value = value;
  6468. }
  6469. static get(key, value) {
  6470. return new torch.DictType(key, value);
  6471. }
  6472. getKeyType() {
  6473. return this._key;
  6474. }
  6475. getValueType() {
  6476. return this._value;
  6477. }
  6478. str() {
  6479. return `Dict(${this.getKeyType().str()}, ${this.getValueType().str()})`;
  6480. }
  6481. __str__() {
  6482. return `Dict(${this.getKeyType().__str__()}, ${this.getValueType().__str__()})`;
  6483. }
  6484. });
  6485. this.registerType('torch.DeviceObjType', class extends torch.Type {
  6486. constructor() {
  6487. super('DeviceObjType');
  6488. }
  6489. static get() {
  6490. torch.DeviceObjType.value ||= new torch.DeviceObjType();
  6491. return torch.DeviceObjType.value;
  6492. }
  6493. str() {
  6494. return 'Device';
  6495. }
  6496. __str__() {
  6497. return 'Device';
  6498. }
  6499. });
  6500. this.registerType('torch.StreamObjType', class extends torch.Type {
  6501. constructor() {
  6502. super('StreamObjType');
  6503. }
  6504. str() {
  6505. return 'Stream';
  6506. }
  6507. __str__() {
  6508. return 'Stream';
  6509. }
  6510. });
  6511. this.registerType('torch._C._GeneratorType', class extends torch.Type {
  6512. constructor() {
  6513. super('GeneratorType');
  6514. }
  6515. static get() {
  6516. torch._C._GeneratorType.value = torch._C._GeneratorType.value || new torch._C._GeneratorType();
  6517. return torch._C._GeneratorType.value;
  6518. }
  6519. str() {
  6520. return 'Generator';
  6521. }
  6522. __str__() {
  6523. return 'Generator';
  6524. }
  6525. });
  6526. this.registerType('torch._C.AliasInfo', class {
  6527. constructor() {
  6528. this.is_write = false;
  6529. this.before_set = [];
  6530. this.after_set = [];
  6531. this.containedTypes = [];
  6532. }
  6533. addBeforeSet(value) {
  6534. this.before_set.push(value);
  6535. }
  6536. addAfterSet(value) {
  6537. this.after_set.push(value);
  6538. }
  6539. addContainedType(alias_info) {
  6540. this.containedTypes.push(alias_info);
  6541. }
  6542. str() {
  6543. const list = ['('];
  6544. list.push(this.before_set.join('|'));
  6545. if (this.after_set.length > 0) {
  6546. list.push(' -> ');
  6547. list.push(this.after_set.join('|'));
  6548. }
  6549. if (this.is_write) {
  6550. list.push('!');
  6551. }
  6552. list.push(')');
  6553. return list.join('');
  6554. }
  6555. });
  6556. this.registerType('torch._C.SchemaLexer', class {
  6557. constructor(buffer) {
  6558. this.buffer = buffer;
  6559. this.position = 0;
  6560. this.value = '';
  6561. this.next();
  6562. }
  6563. eat(kind) {
  6564. if (this.kind !== kind) {
  6565. return null;
  6566. }
  6567. const value = this.value;
  6568. this.next();
  6569. return value;
  6570. }
  6571. expect(kind) {
  6572. if (this.kind !== kind) {
  6573. throw new python.Error(`Unexpected '${this.kind}' instead of '${kind}'.`);
  6574. }
  6575. const value = this.value;
  6576. this.next();
  6577. return value;
  6578. }
  6579. whitespace(count) {
  6580. if (this.kind !== ' ') {
  6581. if (count > this.value.length) {
  6582. throw new python.Error();
  6583. }
  6584. return false;
  6585. }
  6586. this.next();
  6587. return true;
  6588. }
  6589. next() {
  6590. this.position += this.value.length;
  6591. let i = this.position;
  6592. if (i >= this.buffer.length) {
  6593. this.kind = '\0';
  6594. this.value = '';
  6595. } else if (this.buffer[i] === ' ') {
  6596. while (this.buffer[i] === ' ') {
  6597. i += 1;
  6598. }
  6599. this.kind = ' ';
  6600. this.value = this.buffer.slice(this.position, i);
  6601. } else if (this.buffer[i] === '.' && this.buffer[i + 1] === '.' && this.buffer[i + 2] === '.') {
  6602. this.kind = '...';
  6603. this.value = '...';
  6604. } else if (this.buffer[i] === '[' && this.buffer[i + 1] === ']') {
  6605. this.kind = '[]';
  6606. this.value = '[]';
  6607. } 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] === '|') {
  6608. this.kind = this.buffer[i];
  6609. this.value = this.buffer[i];
  6610. } else if ((this.buffer[i] >= 'a' && this.buffer[i] <= 'z') || (this.buffer[i] >= 'A' && this.buffer[i] <= 'Z') || this.buffer[i] === '_') {
  6611. i += 1;
  6612. 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] === '_')) {
  6613. i += 1;
  6614. }
  6615. this.kind = 'id';
  6616. this.value = this.buffer.slice(this.position, i);
  6617. } else if (this.buffer[i] === '-' && this.buffer[i + 1] === '>') {
  6618. this.kind = '->';
  6619. this.value = '->';
  6620. } else if ((this.buffer[i] >= '0' && this.buffer[i] <= '9') || this.buffer[i] === '-') {
  6621. i += 1;
  6622. while (i < this.buffer.length && ((this.buffer[i] >= '0' && this.buffer[i] <= '9') || this.buffer[i] === '.' || this.buffer[i] === 'e' || this.buffer[i] === '-')) {
  6623. i += 1;
  6624. }
  6625. this.kind = '#';
  6626. this.value = this.buffer.slice(this.position, i);
  6627. } else if (this.buffer[i] === "'" || this.buffer[i] === '"') {
  6628. const quote = this.buffer[i];
  6629. i += 1;
  6630. while (i < this.buffer.length && this.buffer[i] !== quote) {
  6631. i += (this.buffer[i] === '\\' && (this.buffer[i + 1] === "'" || this.buffer[i + 1] === '"' || this.buffer[i + 1] === '\\')) ? 2 : 1;
  6632. }
  6633. i += 1;
  6634. this.kind = 'string';
  6635. this.value = this.buffer.slice(this.position, i);
  6636. } else {
  6637. throw new python.Error(`Unsupported token at '${this.position}'.`);
  6638. }
  6639. }
  6640. });
  6641. this.registerType('torch._C.SchemaTypeParser', class {
  6642. constructor(L) {
  6643. this.L = L;
  6644. }
  6645. parseType() {
  6646. const r = this.parseFakeAndRealType();
  6647. return { first: r[0], second: r[2] };
  6648. }
  6649. parseBaseType() {
  6650. const L = this.L;
  6651. const value = L.value;
  6652. L.next();
  6653. switch (value) {
  6654. case 'Tensor': return torch.TensorType.get();
  6655. case 'bool': return torch.BoolType.get();
  6656. case 'int': return torch.IntType.get();
  6657. case 'float': return torch.FloatType.get();
  6658. case 'complex': return torch.ComplexType.get();
  6659. case 'str': return torch.StringType.get();
  6660. case 'SymInt': return torch.SymIntType.get();
  6661. case 'Scalar': return torch.NumberType.get();
  6662. case 'ScalarType': return torch.Type.get('ScalarTypeType');
  6663. case 'Device': return torch.DeviceObjType.get();
  6664. case 'Layout': return torch.Type.get('Layout');
  6665. case 'MemoryFormat': return torch.Type.get('MemoryFormat');
  6666. case 'Generator': return torch._C._GeneratorType.get();
  6667. case 't': case 't1': case 't2': case 'tVal': return torch.Type.get('VarType', value);
  6668. case 'Any': return torch.AnyType.get();
  6669. case 'AnyEnumType': return torch.Type.get('AnyEnumType');
  6670. case 'Dimname': return torch.StringType.get();
  6671. case 'QScheme': return torch.Type.get('QSchemeType');
  6672. case 'Stream': return torch.StreamObjType.get();
  6673. case 'Storage': return torch.Type.get('Storage');
  6674. case 'AnyClassType': return torch.Type.get('AnyClassType');
  6675. case 'NoneType': return torch.NoneType.get();
  6676. default: throw new python.Error(`Unsupported type '${value}'.`);
  6677. }
  6678. }
  6679. parseFakeAndRealType() {
  6680. const L = this.L;
  6681. let fake_value = null;
  6682. let real_value = null;
  6683. let alias_info = null;
  6684. if (L.eat('(')) {
  6685. const types = [];
  6686. L.whitespace(0);
  6687. while (!L.eat(')')) {
  6688. const r = this.parseType();
  6689. types.push(r.first);
  6690. if (alias_info && r.second) {
  6691. alias_info.addContainedType(r.second);
  6692. }
  6693. L.whitespace(0);
  6694. L.eat(',');
  6695. L.whitespace(0);
  6696. }
  6697. real_value = torch.TupleType.get(types);
  6698. fake_value = real_value;
  6699. } else if (L.value === 'Future') {
  6700. L.next();
  6701. L.expect('(');
  6702. const p = this.parseType();
  6703. const subtype = p.first;
  6704. // const subalias = p.second;
  6705. L.expect(')');
  6706. real_value = torch.FutureType.get(subtype);
  6707. fake_value = real_value;
  6708. } else if (L.value === 'Await') {
  6709. L.next();
  6710. L.expect('(');
  6711. const p = this.parseType();
  6712. const subtype = p.first;
  6713. // const subalias = p.second;
  6714. L.expect(')');
  6715. real_value = torch.AwaitType.get(subtype);
  6716. fake_value = real_value;
  6717. } else if (L.value === 'RRef') {
  6718. L.next();
  6719. L.expect('(');
  6720. const p = this.parseType();
  6721. const subtype = p.first;
  6722. // const subalias = p.second;
  6723. L.expect(')');
  6724. real_value = torch.RRefType.get(subtype);
  6725. fake_value = real_value;
  6726. } else if (L.value === 'Tensor') {
  6727. L.next();
  6728. real_value = torch.TensorType.get();
  6729. fake_value = real_value;
  6730. alias_info = this.parseAliasAnnotation();
  6731. } else if (L.value === 'Dict') {
  6732. L.next();
  6733. L.expect('(');
  6734. const key_type = this.parseType().first;
  6735. L.expect(',');
  6736. L.whitespace(0);
  6737. const value_type = this.parseType().first;
  6738. L.expect(')');
  6739. alias_info = this.parseAliasAnnotation();
  6740. real_value = torch.DictType.get(key_type, value_type);
  6741. fake_value = real_value;
  6742. } else if (L.eat('Union')) {
  6743. L.next();
  6744. L.expect('(');
  6745. const types = [];
  6746. types.push(this.parseType().first);
  6747. while (L.cur().kind !== ')') {
  6748. L.expect(',');
  6749. types.emplace_back(this.parseType().first);
  6750. }
  6751. L.expect(')');
  6752. alias_info = this.parseAliasAnnotation();
  6753. real_value = new torch.UnionType(types);
  6754. fake_value = real_value;
  6755. /* } else if (complete_tensor_types && L.cur().kind == TK_IDENT && parseTensorDType(L.cur().text())) {
  6756. fake_value = real_value = parseRefinedTensor();
  6757. alias_info = parseAliasAnnotation(); */
  6758. } else if (L.value === "__torch__") {
  6759. let name = L.expect('id');
  6760. while (L.eat('.')) {
  6761. name = `${name}.${L.expect('id')}`;
  6762. }
  6763. real_value = new torch.ClassType(name); // getCustomClass
  6764. fake_value = real_value;
  6765. } else {
  6766. real_value = this.parseBaseType();
  6767. fake_value = real_value;
  6768. if (real_value.kind() === 'ScalarTypeType' ||
  6769. real_value.kind() === 'MemoryFormat' ||
  6770. real_value.kind() === 'Layout' ||
  6771. real_value.kind() === 'SymInt') {
  6772. fake_value = torch.IntType.get();
  6773. }
  6774. alias_info = this.parseAliasAnnotation();
  6775. }
  6776. while (true) {
  6777. if (L.kind === '[]') {
  6778. L.expect('[]');
  6779. fake_value = torch.ListType.get(fake_value);
  6780. real_value = torch.ListType.get(real_value);
  6781. let container = this.parseAliasAnnotation();
  6782. if (alias_info) {
  6783. if (!container) {
  6784. container = new torch._C.AliasInfo();
  6785. container.is_write = alias_info.is_write;
  6786. }
  6787. container.addContainedType(alias_info);
  6788. }
  6789. alias_info = container;
  6790. } else if (L.eat('?')) {
  6791. fake_value = torch.OptionalType.get(fake_value);
  6792. real_value = torch.OptionalType.get(real_value);
  6793. } else {
  6794. break;
  6795. }
  6796. }
  6797. return [fake_value, real_value, alias_info];
  6798. }
  6799. parseAliasAnnotation() {
  6800. const L = this.L;
  6801. let alias_info = null;
  6802. if (L.eat('(')) {
  6803. alias_info = new torch._C.AliasInfo();
  6804. do {
  6805. alias_info.addBeforeSet(L.value);
  6806. L.next();
  6807. if (L.eat('!')) {
  6808. alias_info.is_write = true;
  6809. }
  6810. L.whitespace(0);
  6811. }
  6812. while (L.eat('|'));
  6813. if (L.eat('->')) {
  6814. L.whitespace(0);
  6815. do {
  6816. alias_info.addAfterSet(L.value);
  6817. L.next();
  6818. L.whitespace(0);
  6819. }
  6820. while (L.eat('|'));
  6821. }
  6822. L.expect(')');
  6823. }
  6824. return alias_info;
  6825. }
  6826. });
  6827. this.registerType('torch.Argument', class {
  6828. constructor(name, type, real_type, N, default_value, kwarg_only, alias_info) {
  6829. // torch/aten/src/ATen/core/function_schema.h
  6830. this.name = name;
  6831. this.type = type;
  6832. this.real_type = real_type;
  6833. this.N = N;
  6834. this.default_value = default_value;
  6835. this.kwarg_only = kwarg_only;
  6836. this.alias_info = alias_info;
  6837. const is_alias = alias_info && alias_info.is_write;
  6838. this.is_out = this.kwarg_only && is_alias;
  6839. }
  6840. has_default_value() {
  6841. return this.default_value !== undefined;
  6842. }
  6843. static parse(L, is_return, kwarg_only) {
  6844. const type_parser = new torch._C.SchemaTypeParser(L);
  6845. let [fake_type, real_type, alias_info] = type_parser.parseFakeAndRealType();
  6846. L.whitespace(0);
  6847. let N = null;
  6848. if (L.eat('[')) {
  6849. fake_type = torch.ListType.get(fake_type);
  6850. real_type = torch.ListType.get(real_type);
  6851. if (L.kind === '#') {
  6852. N = Number(L.value);
  6853. L.next();
  6854. }
  6855. L.expect(']');
  6856. let container = type_parser.parseAliasAnnotation();
  6857. if (alias_info) {
  6858. if (!container) {
  6859. container = new torch._C.AliasInfo();
  6860. container.is_write = alias_info.is_write;
  6861. }
  6862. container.addContainedType(alias_info);
  6863. }
  6864. alias_info = container;
  6865. if (L.eat('?')) {
  6866. /* eslint-disable no-unused-vars */
  6867. fake_type = torch.OptionalType.get(fake_type);
  6868. /* eslint-enable no-unused-vars */
  6869. real_type = torch.OptionalType.get(real_type);
  6870. }
  6871. }
  6872. let name = null;
  6873. /* eslint-disable no-undef-init */
  6874. let default_value = undefined;
  6875. /* eslint-enable no-undef-init */
  6876. const type = null;
  6877. if (is_return) {
  6878. L.whitespace(0);
  6879. kwarg_only = false;
  6880. if (L.kind === 'id') {
  6881. name = L.expect('id');
  6882. }
  6883. } else {
  6884. L.whitespace(1);
  6885. name = L.expect('id');
  6886. L.whitespace(0);
  6887. if (L.eat('=')) {
  6888. L.whitespace(0);
  6889. default_value = torch.Argument._parse_value(L);
  6890. }
  6891. }
  6892. return new torch.Argument(name, type, real_type, N, default_value, kwarg_only, alias_info);
  6893. }
  6894. static _parse_value(L) {
  6895. /* eslint-disable no-undef-init */
  6896. let value = undefined;
  6897. /* eslint-enable no-undef-init */
  6898. if (L.kind === 'id') {
  6899. if (L.value === 'True' || L.value === 'False') {
  6900. value = L.value === 'True';
  6901. } else if (L.value === 'None') {
  6902. value = null;
  6903. } else if (L.value === 'Mean' || L.value === 'contiguous_format' || L.value === 'long') {
  6904. value = L.value;
  6905. } else if (typeof L.value === 'string') {
  6906. value = L.value;
  6907. } else if (typeof L.value === 'number') {
  6908. value = L.value;
  6909. } else {
  6910. throw new python.Error(`Unsupported default value '${L.value}'.`);
  6911. }
  6912. } else if (L.kind === '#') {
  6913. value = Number(L.value);
  6914. } else if (L.kind === 'string') {
  6915. value = L.value.slice(1, -1);
  6916. } else if (L.kind === '[]') {
  6917. value = [];
  6918. } else if (L.eat('[')) {
  6919. value = [];
  6920. if (!L.eat(']')) {
  6921. while (true) {
  6922. L.whitespace(0);
  6923. value.push(torch.Argument._parse_value(L));
  6924. L.whitespace(0);
  6925. if (!L.eat(',')) {
  6926. break;
  6927. }
  6928. }
  6929. L.expect(']');
  6930. }
  6931. return value;
  6932. } else {
  6933. throw new python.Error(`Unsupported default value '${L.kind}'.`);
  6934. }
  6935. L.next();
  6936. return value;
  6937. }
  6938. str() {
  6939. const list = [];
  6940. const type = this.real_type;
  6941. const is_opt = type instanceof torch.OptionalType;
  6942. const unopt_type = is_opt ? type.getElementType() : type;
  6943. if (unopt_type instanceof torch.ListType) {
  6944. list.push(unopt_type.getElementType().str());
  6945. if (this.alias_info && this.alias_info.containedTypes.length > 0) {
  6946. list.push(this.alias_info.containedTypes[0].str());
  6947. }
  6948. list.push(this.N === null ? `[]` : `[${this.N}]`);
  6949. } else {
  6950. list.push(unopt_type.str());
  6951. }
  6952. if (this.alias_info && this.alias_info.before_set.length > 0) {
  6953. list.push(this.alias_info.str());
  6954. }
  6955. if (is_opt) {
  6956. list.push('?');
  6957. }
  6958. if (this.name) {
  6959. list.push(' ');
  6960. list.push(this.name);
  6961. }
  6962. if (this.default_value !== undefined) {
  6963. const value = this.default_value;
  6964. if (value === null) {
  6965. list.push('=None');
  6966. } else if (typeof value === 'boolean') {
  6967. list.push('=');
  6968. list.push(value ? 'True' : 'False');
  6969. } else if (typeof value === 'string') {
  6970. list.push(`="${value}"`);
  6971. } else if (typeof value === 'number') {
  6972. list.push(`=${value}`);
  6973. if (Number.isInteger(value) && this.real_type instanceof torch.FloatType) {
  6974. list.push(`.`);
  6975. }
  6976. } else if (Array.isArray(value)) {
  6977. list.push(`=[${value.join(', ')}]`);
  6978. }
  6979. }
  6980. return list.join('');
  6981. }
  6982. });
  6983. this.registerType('torch.FunctionSchema', class {
  6984. constructor(name, overload_name, args, returns, is_vararg, is_varret) {
  6985. const index = name.indexOf('(');
  6986. if (index === -1) {
  6987. this._name = name;
  6988. this._overload_name = overload_name;
  6989. this._arguments = args;
  6990. this._returns = returns;
  6991. this._is_vararg = is_vararg;
  6992. this._is_varret = is_varret;
  6993. } else {
  6994. const value = name.substring(0, index).trim();
  6995. const dot = value.indexOf('.');
  6996. if (dot === -1) {
  6997. this._name = value;
  6998. this._overload_name = '';
  6999. } else {
  7000. this._name = value.substring(0, dot);
  7001. this._overload_name = value.substring(dot + 1, value.length);
  7002. }
  7003. this._buffer = name.substring(index, name.length);
  7004. }
  7005. }
  7006. static parse(schema) {
  7007. return new torch.FunctionSchema(schema);
  7008. }
  7009. get name() {
  7010. return this._name;
  7011. }
  7012. get overload_name() {
  7013. return this._overload_name;
  7014. }
  7015. get arguments() {
  7016. this._parse();
  7017. return this._arguments;
  7018. }
  7019. get returns() {
  7020. this._parse();
  7021. return this._returns;
  7022. }
  7023. get is_vararg() {
  7024. this._parse();
  7025. return this._is_vararg;
  7026. }
  7027. get is_varret() {
  7028. this._parse();
  7029. return this._is_varret;
  7030. }
  7031. _parse() {
  7032. if (this._buffer) {
  7033. const L = new torch._C.SchemaLexer(this._buffer);
  7034. this._arguments = [];
  7035. this._is_vararg = false;
  7036. this._kwarg_only = false;
  7037. L.expect('(');
  7038. if (!L.eat(')')) {
  7039. while (true) {
  7040. L.whitespace(0);
  7041. if (this._is_vararg) {
  7042. throw new python.Error();
  7043. }
  7044. if (L.eat('*')) {
  7045. this._kwarg_only = true;
  7046. } else if (L.eat('...')) {
  7047. this._is_vararg = true;
  7048. } else {
  7049. const argument = torch.Argument.parse(L, false, this._kwarg_only);
  7050. this._arguments.push(argument);
  7051. }
  7052. L.whitespace(0);
  7053. if (!L.eat(',')) {
  7054. break;
  7055. }
  7056. }
  7057. L.expect(')');
  7058. }
  7059. L.whitespace(0);
  7060. L.expect('->');
  7061. L.whitespace(0);
  7062. this._returns = [];
  7063. this._is_varret = false;
  7064. if (L.eat('...')) {
  7065. this._is_varret = true;
  7066. } else if (L.eat('(')) {
  7067. L.whitespace(0);
  7068. if (!L.eat(')')) {
  7069. while (true) {
  7070. L.whitespace(0);
  7071. if (this._is_varret) {
  7072. throw new python.Error();
  7073. }
  7074. if (L.eat('...')) {
  7075. this._is_varret = true;
  7076. } else {
  7077. const argument = torch.Argument.parse(L, true, false);
  7078. this._returns.push(argument);
  7079. }
  7080. L.whitespace(0);
  7081. if (!L.eat(',')) {
  7082. break;
  7083. }
  7084. }
  7085. L.expect(')');
  7086. }
  7087. L.whitespace(0);
  7088. } else {
  7089. this._returns.push(torch.Argument.parse(L, true, false));
  7090. }
  7091. delete this._buffer;
  7092. }
  7093. }
  7094. __str__() {
  7095. const list = [this.name];
  7096. const overload_name = this.overload_name;
  7097. if (overload_name !== '' && overload_name !== 'default') {
  7098. list.push(`.${this.overload_name}`);
  7099. }
  7100. list.push('(');
  7101. let first = true;
  7102. let kwarg_only = false;
  7103. for (const argument of this.arguments) {
  7104. if (!first) {
  7105. list.push(', ');
  7106. }
  7107. if (argument.kwarg_only && !kwarg_only) {
  7108. list.push('*, ');
  7109. kwarg_only = true;
  7110. }
  7111. first = false;
  7112. list.push(argument.str());
  7113. }
  7114. if (this.is_vararg) {
  7115. if (!first) {
  7116. list.push(', ');
  7117. }
  7118. first = true;
  7119. list.push('...');
  7120. }
  7121. list.push(') -> ');
  7122. const returns = this.returns;
  7123. const braces = !this.is_varret &&
  7124. (returns.length !== 1 ||
  7125. returns[0].name ||
  7126. returns[0].real_type instanceof torch.TupleType ||
  7127. returns[0].real_type instanceof torch.ListType && returns[0].real_type.getElementType() instanceof torch.TupleType);
  7128. if (braces) {
  7129. list.push('(');
  7130. }
  7131. first = true;
  7132. for (const argument of this.returns) {
  7133. if (!first) {
  7134. list.push(', ');
  7135. }
  7136. first = false;
  7137. list.push(argument.str());
  7138. }
  7139. if (this.is_varret) {
  7140. if (!first) {
  7141. list.push(', ');
  7142. }
  7143. first = true;
  7144. list.push('...');
  7145. }
  7146. if (braces) {
  7147. list.push(')');
  7148. }
  7149. return list.join('');
  7150. }
  7151. });
  7152. this.registerType('torch._ops.OpOverload', class extends torch._ops.OperatorBase {
  7153. constructor(overloadpacket, op, op_dk, schema, tags) {
  7154. super();
  7155. this._op = op;
  7156. this._op_dk = op_dk;
  7157. this._schema = schema;
  7158. this._overloadpacket = overloadpacket;
  7159. this._tags = tags;
  7160. this._overloadname = schema.overload_name === '' ? 'default' : schema.overload_name;
  7161. this._name = this._schema.name;
  7162. this._name = schema.overload_name ? `${this._name}.${schema.overload_name}` : this._name;
  7163. this.__name__ = `${this._schema.name.split('::')[1]}.${this._overloadname}`;
  7164. this.__module__ = overloadpacket.__module__;
  7165. op.__module__ = overloadpacket.__module__;
  7166. this.__qualname__ = self._name;
  7167. this.__annotations__ = {};
  7168. // this._defined_in_python = this.__qualname__ in torch.library._defs
  7169. let is_write = null;
  7170. for (const a of this._schema.arguments) {
  7171. if (a.alias_info) {
  7172. is_write = is_write === null ? a.alias_info.is_write : a.alias_info.is_write || is_write;
  7173. }
  7174. }
  7175. this.is_view = is_write !== null && !is_write;
  7176. }
  7177. get name() {
  7178. return this._name;
  7179. }
  7180. });
  7181. this.registerType('torch._ops.OpOverloadPacket', class {
  7182. constructor(qualified_op_name, op_name, op, overload_names) {
  7183. this._qualified_op_name = qualified_op_name;
  7184. this.__name__ = op_name;
  7185. this._op = op;
  7186. this._overload_names = overload_names;
  7187. this._dir = [];
  7188. this._has_torchbind_op_overload = this._schemas.some((schema) => this._has_script_object_arg(schema));
  7189. }
  7190. get _schemas() {
  7191. return this._overload_names.map((overload_name) => torch._C._get_schema(this._qualified_op_name, overload_name));
  7192. }
  7193. __getattr__(key) {
  7194. key = key === 'default' ? '' : key;
  7195. const op_dk_tags = torch._C._get_operation_overload(this._qualified_op_name, key);
  7196. const [op_, op_dk_, tags] = op_dk_tags;
  7197. const schema = torch._C._get_schema(this._qualified_op_name, key);
  7198. const overload = this._has_script_object_arg(schema) ?
  7199. new torch._ops.TorchBindOpOverload(this, op_, op_dk_, schema, tags) :
  7200. new torch._ops.OpOverload(this, op_, op_dk_, schema, tags);
  7201. builtins.setattr(self, key, overload);
  7202. this._dir.push(key);
  7203. return overload;
  7204. }
  7205. _has_script_object_arg(/* schema */) {
  7206. return false;
  7207. // return any(isinstance(arg.type, torch.ClassType) for arg in schema.arguments)
  7208. }
  7209. });
  7210. this.registerType('torch._ops._OpNamespace', class extends types.ModuleType {
  7211. constructor(name) {
  7212. super(`torch.ops.${name}`);
  7213. this.name = name;
  7214. this._dir = [];
  7215. }
  7216. __getattr__(op_name) {
  7217. const namespace_name = this.name;
  7218. const qualified_op_name = `${namespace_name}::${op_name}`;
  7219. const module_name = `${this.__module__}.${namespace_name}`;
  7220. let op = null;
  7221. let overload_names = null;
  7222. try {
  7223. [op, overload_names] = this._get_packet(qualified_op_name, module_name);
  7224. } catch {
  7225. // continue regardless of error
  7226. }
  7227. if (!op) {
  7228. throw new python.Error(`Unknown operator type '${qualified_op_name}'.`);
  7229. }
  7230. op.__module__ = module_name;
  7231. const opoverloadpacket = new torch._ops.OpOverloadPacket(qualified_op_name, op_name, op, overload_names);
  7232. opoverloadpacket.__module__ = `${this.__module__}.${namespace_name}`;
  7233. builtins.setattr(this, op_name, opoverloadpacket);
  7234. this._dir.push(op_name);
  7235. return opoverloadpacket;
  7236. }
  7237. _get_packet(qualname, op_module) {
  7238. const [op, overload_names] = torch._C._jit_get_operation(qualname);
  7239. if (op) {
  7240. // torch.jit._builtins._register_builtin(op, qualname);
  7241. }
  7242. op.__module__ = op_module;
  7243. return [op, overload_names];
  7244. }
  7245. });
  7246. this.registerType('torch.export.unflatten.UnflattenedModule', class extends torch.nn.modules.module.Module {});
  7247. this.registerType('torch.export.graph_signature.ExportGraphSignature', class {
  7248. constructor(input_specs, output_specs) {
  7249. this.input_specs = input_specs;
  7250. this.output_specs = output_specs;
  7251. }
  7252. user_inputs() {
  7253. const user_inputs = [];
  7254. for (const s of this.input_specs) {
  7255. if (s.kind !== torch.export.graph_signature.InputKind.USER_INPUT) {
  7256. continue;
  7257. }
  7258. if (s.arg instanceof torch.export.graph_signature.TensorArgument ||
  7259. s.arg instanceof torch.export.graph_signature.SymIntArgument ||
  7260. s.arg instanceof torch.export.graph_signature.CustomObjArgument) {
  7261. user_inputs.push(s.arg.name);
  7262. } else if (s.arg instanceof torch.export.graph_signature.ConstantArgument) {
  7263. user_inputs.push(s.arg.value);
  7264. } else {
  7265. throw new python.Error(`Unsupported user input '${s.arg}'.`);
  7266. }
  7267. }
  7268. return user_inputs;
  7269. }
  7270. user_outputs() {
  7271. const user_outputs = [];
  7272. for (const s of this.output_specs) {
  7273. if (s.kind !== torch.export.graph_signature.OutputKind.USER_OUTPUT) {
  7274. continue;
  7275. }
  7276. if (s.arg instanceof torch.export.graph_signature.TensorArgument ||
  7277. s.arg instanceof torch.export.graph_signature.SymIntArgument ||
  7278. s.arg instanceof torch.export.graph_signature.CustomObjArgument) {
  7279. user_outputs.push(s.arg.name);
  7280. } else if (s.arg instanceof torch.export.graph_signature.ConstantArgument) {
  7281. user_outputs.push(s.arg.value);
  7282. } else {
  7283. throw new python.Error(`Unsupported user output '${s.arg}'.`);
  7284. }
  7285. }
  7286. return user_outputs;
  7287. }
  7288. inputs_to_parameters() {
  7289. return new Map(this.input_specs
  7290. .filter((s) => s.kind === torch.export.graph_signature.InputKind.PARAMETER && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  7291. .map((s) => [s.arg.name, s.target]));
  7292. }
  7293. inputs_to_buffers() {
  7294. return new Map(this.input_specs
  7295. .filter((s) => s.kind === torch.export.graph_signature.InputKind.BUFFER && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  7296. .map((s) => [s.arg.name, s.target]));
  7297. }
  7298. });
  7299. torch.export.graph_signature.InputKind = {
  7300. USER_INPUT: 0,
  7301. PARAMETER: 1,
  7302. BUFFER: 2,
  7303. CONSTANT_TENSOR: 3,
  7304. CUSTOM_OBJ: 4,
  7305. TOKEN: 5
  7306. };
  7307. this.registerType('torch.export.graph_signature.InputSpec', class {
  7308. constructor(kind, arg, target, persistent) {
  7309. this.kind = kind;
  7310. this.arg = arg;
  7311. this.target = target;
  7312. this.persistent = persistent;
  7313. }
  7314. });
  7315. torch.export.graph_signature.OutputKind = {
  7316. USER_OUTPUT: 0,
  7317. LOSS_OUTPUT: 1,
  7318. BUFFER_MUTATION: 2,
  7319. GRADIENT_TO_PARAMETER: 3,
  7320. GRADIENT_TO_USER_INPUT: 4,
  7321. USER_INPUT_MUTATION: 5,
  7322. TOKEN: 6
  7323. };
  7324. this.registerType('torch.export.graph_signature.OutputSpec', class {
  7325. constructor(kind, arg, target) {
  7326. this.kind = kind;
  7327. this.arg = arg;
  7328. this.target = target;
  7329. }
  7330. });
  7331. this.registerType('torch.export.graph_signature.ConstantArgument', class {
  7332. constructor(name, value) {
  7333. this.name = name;
  7334. this.value = value; // Union[int, float, bool, str, None]
  7335. }
  7336. });
  7337. this.registerType('torch.export.graph_signature.TensorArgument', class {
  7338. constructor(name) {
  7339. this.name = name;
  7340. }
  7341. });
  7342. this.registerType('torch.export.graph_signature.SymIntArgument', class {
  7343. constructor(name) {
  7344. this.name = name;
  7345. }
  7346. });
  7347. this.registerType('torch.export.graph_signature.CustomObjArgument', class {
  7348. constructor(name, class_fqn, fake_val) {
  7349. this.name = name;
  7350. this.class_fqn = class_fqn;
  7351. this.fake_val = fake_val;
  7352. }
  7353. });
  7354. this.registerType('torch.export.exported_program.ExportedProgram', class {
  7355. constructor(root, graph, graph_signature, state_dict, range_constraints, module_call_graph, example_inputs, verifier, tensor_constants, constants) {
  7356. // graph._codegen = torch.fx.graph.CodeGen()
  7357. this._graph_module = this._create_graph_module_for_export(root, graph);
  7358. if (root instanceof torch.fx.GraphModule) {
  7359. // this._graph_module.meta.update(root.meta);
  7360. }
  7361. this._graph_signature = graph_signature;
  7362. this._state_dict = state_dict;
  7363. this._range_constraints = range_constraints;
  7364. this._module_call_graph = module_call_graph;
  7365. this._example_inputs = example_inputs;
  7366. this._constants = tensor_constants || constants || {};
  7367. }
  7368. _create_graph_module_for_export(root, graph) {
  7369. let gm = null;
  7370. try {
  7371. gm = new torch.fx.GraphModule(root, graph);
  7372. } catch {
  7373. const gm = new torch.fx.GraphModule(root, torch.fx.Graph());
  7374. gm._graph = graph;
  7375. }
  7376. return gm;
  7377. }
  7378. get graph_module() {
  7379. return this._graph_module;
  7380. }
  7381. get graph() {
  7382. return this._graph_module.graph;
  7383. }
  7384. get graph_signature() {
  7385. return this._graph_signature;
  7386. }
  7387. get state_dict() {
  7388. return this._state_dict;
  7389. }
  7390. });
  7391. this.registerType('torch.export.exported_program.ModuleCallEntry', class {});
  7392. this.registerType('torch.export.exported_program.ModuleCallSignature', class {});
  7393. this.registerFunction('torch.export.unflatten');
  7394. this.registerFunction('torch._export.exported_program._create_graph_module_for_export', (root, graph) => {
  7395. return new torch.fx.graph_module.GraphModule(root, graph);
  7396. });
  7397. this.registerType('torch._export.serde.serialize.SerializedArtifact', class {
  7398. constructor(exported_program, state_dict, constants, example_inputs) {
  7399. this.exported_program = exported_program;
  7400. this.state_dict = state_dict;
  7401. this.constants = constants;
  7402. this.example_inputs = example_inputs;
  7403. }
  7404. });
  7405. torch._export.serde.serialize._SYM_INT_OPS = new Set([
  7406. operator.mul, operator.add, operator.sub, operator.floordiv, operator.mod,
  7407. torch.sym_sqrt, torch.sym_int, torch.sym_ite, torch.sym_max, torch.sym_min, torch.sym_sqrt
  7408. ]);
  7409. torch._export.serde.serialize._SYM_BOOL_OPS = new Set([
  7410. operator.eq, operator.ne, operator.le, operator.ge, operator.lt, operator.gt,
  7411. torch.sym_not
  7412. ]);
  7413. this.registerType('torch._export.serde.union._Union', class {
  7414. constructor(obj) {
  7415. if (obj.$type) {
  7416. this.type = obj.$type;
  7417. this[obj.$type] = obj.$value;
  7418. delete obj.$type;
  7419. delete obj.$value;
  7420. } else {
  7421. let entries = Object.entries(obj);
  7422. if (entries.length > 1) {
  7423. entries = entries.filter(([, value]) => value !== null);
  7424. }
  7425. if (entries.length !== 1) {
  7426. throw new Error();
  7427. }
  7428. const [entry] = entries;
  7429. const [type, value] = entry;
  7430. this.type = type;
  7431. this[type] = value;
  7432. }
  7433. }
  7434. get value() {
  7435. return this[this.type];
  7436. }
  7437. });
  7438. this.registerType('torch._export.serde.schema.NamedArgument', class {
  7439. constructor(obj) {
  7440. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  7441. this.name = obj.name;
  7442. }
  7443. });
  7444. this.registerType('torch._export.serde.schema.Argument', class extends torch._export.serde.union._Union {
  7445. constructor(obj) {
  7446. super(obj);
  7447. if (this.type === 'as_int' || this.type === 'as_ints' ||
  7448. this.type === 'as_float' || this.type === 'as_floats' ||
  7449. this.type === 'as_bool' || this.type === 'as_bools' ||
  7450. this.type === 'as_string' || this.type === 'as_strings' ||
  7451. this.type === 'as_scalar_type' || this.type === 'as_device' ||
  7452. this.type === 'as_memory_format' || this.type === 'as_layout') {
  7453. // continue
  7454. } else if (this.type === 'as_none') {
  7455. this.as_none = null;
  7456. } else if (this.type === 'as_tensor') {
  7457. this.as_tensor = new torch._export.serde.schema.TensorArgument(this.as_tensor);
  7458. } else if (this.type === 'as_tensors') {
  7459. this.as_tensors = this.as_tensors.map((item) => new torch._export.serde.schema.TensorArgument(item));
  7460. } else if (this.type === 'as_sym_int') {
  7461. this.as_sym_int = new torch._export.serde.schema.SymIntArgument(this.as_sym_int);
  7462. } else if (this.type === 'as_sym_ints') {
  7463. this.as_sym_ints = this.as_sym_ints.map((item) => new torch._export.serde.schema.SymIntArgument(item));
  7464. } else if (this.type === 'as_optional_tensors') {
  7465. this.as_optional_tensors = this.as_optional_tensors.map((item) => new torch._export.serde.schema.OptionalTensorArgument(item));
  7466. } else {
  7467. throw new python.Error(`Unsupported argument '${this.type}'.`);
  7468. }
  7469. /*
  7470. as_tensors: List[TensorArgument]
  7471. as_string: str
  7472. as_strings: List[str]
  7473. as_sym_int: SymIntArgument
  7474. as_sym_ints: List[SymIntArgument]
  7475. as_scalar_type: ScalarType
  7476. as_memory_format: MemoryFormat
  7477. as_layout: Layout
  7478. as_bools: List[bool]
  7479. as_sym_bool: SymBoolArgument
  7480. as_sym_bools: List[SymBoolArgument]
  7481. as_graph: GraphArgument
  7482. as_optional_tensors: List[OptionalTensorArgument]
  7483. as_custom_obj: CustomObjArgument
  7484. */
  7485. }
  7486. });
  7487. this.registerType('torch._export.serde.schema.Node', class {
  7488. constructor(obj) {
  7489. this.target = obj.target;
  7490. this.inputs = obj.inputs.map((input) => new torch._export.serde.schema.NamedArgument(input));
  7491. this.outputs = obj.outputs.map((output) => new torch._export.serde.schema.Argument(output));
  7492. this.metadata = new Map(Object.entries(obj.metadata));
  7493. }
  7494. });
  7495. torch._export.serde.schema.ScalarType = {
  7496. UNKNOWN: 0,
  7497. BYTE: 1,
  7498. CHAR: 2,
  7499. SHORT: 3,
  7500. INT: 4,
  7501. LONG: 5,
  7502. HALF: 6,
  7503. FLOAT: 7,
  7504. DOUBLE: 8,
  7505. COMPLEXHALF: 9,
  7506. COMPLEXFLOAT: 10,
  7507. COMPLEXDOUBLE: 11,
  7508. BOOL: 12,
  7509. BFLOAT16: 13
  7510. };
  7511. torch._export.serde.schema.Layout = {
  7512. Unknown: 0,
  7513. SparseCoo: 1,
  7514. SparseCsr: 2,
  7515. SparseCsc: 3,
  7516. SparseBsr: 4,
  7517. SparseBsc: 5,
  7518. _mkldnn: 6,
  7519. Strided: 7
  7520. };
  7521. torch._export.serde.schema.MemoryFormat = {
  7522. Unknown: 0,
  7523. ContiguousFormat: 1,
  7524. ChannelsLast: 2,
  7525. ChannelsLast3d: 3,
  7526. PreserveFormat: 4,
  7527. };
  7528. this.registerType('torch._export.serde.schema.Device', class {
  7529. constructor(obj) {
  7530. Object.assign(this, { ...obj });
  7531. }
  7532. });
  7533. this.registerType('torch._export.serde.schema.TensorMeta', class {
  7534. constructor(obj) {
  7535. obj = obj.meta || obj;
  7536. this.dtype = obj.dtype;
  7537. this.sizes = obj.sizes.map((size) => new torch._export.serde.schema.SymInt(size));
  7538. this.requires_grad = obj.requires_grad;
  7539. this.device = obj.device;
  7540. this.strides = obj.strides.map((stride) => new torch._export.serde.schema.SymInt(stride));
  7541. this.storage_offset = new torch._export.serde.schema.SymInt(Number.isInteger(obj.storage_offset) ? { as_int: obj.storage_offset } : obj.storage_offset);
  7542. this.layout = obj.layout;
  7543. }
  7544. });
  7545. this.registerType('torch._export.serde.schema.Graph', class {
  7546. constructor(obj) {
  7547. this.inputs = obj.inputs.map((input) => new torch._export.serde.schema.Argument(input));
  7548. this.outputs = obj.outputs.map((output) => new torch._export.serde.schema.Argument(output));
  7549. this.nodes = obj.nodes.map((node) => new torch._export.serde.schema.Node(node));
  7550. this.tensor_values = new Map(Object.entries(obj.tensor_values).map(([key, value]) => [key, new torch._export.serde.schema.TensorMeta(value)]));
  7551. this.sym_int_values = new Map(Object.entries(obj.sym_int_values).map(([key, value]) => [key, new torch._export.serde.schema.SymInt(value)]));
  7552. this.sym_bool_values = new Map(Object.entries(obj.sym_bool_values).map(([key, value]) => [key, new torch._export.serde.schema.SymBool(value)]));
  7553. this.is_single_tensor_return = obj.is_single_tensor_return;
  7554. this.custom_obj_values = new Map(Object.entries(obj.custom_obj_values || {}).map(([key, value]) => [key, new torch._export.serde.schema.CustomObjArgument(value)]));
  7555. if (obj.contants) {
  7556. // this.constants = new Map(Object.entries(serialized_graph.constants).map(([k, v]) => [k, torch.load(v)]));
  7557. // graph_signature -> input_specs -> tensor_constant
  7558. }
  7559. }
  7560. });
  7561. this.registerType('torch._export.serde.schema.ModuleCallSignature', class {
  7562. constructor(obj) {
  7563. Object.assign(this, { ...obj });
  7564. this.inputs = this.inputs.map((item) => new torch._export.serde.schema.Argument(item));
  7565. this.outputs = this.outputs.map((item) => new torch._export.serde.schema.Argument(item));
  7566. }
  7567. });
  7568. this.registerType('torch._export.serde.schema.ModuleCallEntry', class {
  7569. constructor(obj) {
  7570. Object.assign(this, { ...obj });
  7571. this.signature = this.signature ? new torch._export.serde.schema.ModuleCallSignature(this.signature) : null;
  7572. }
  7573. });
  7574. this.registerType('torch._export.serde.schema.GraphModule', class {
  7575. constructor(obj) {
  7576. this.graph = new torch._export.serde.schema.Graph(obj.graph);
  7577. this.signature = new torch._export.serde.schema.GraphSignature(obj.signature);
  7578. this.module_call_graph = obj.module_call_graph.map((item) => new torch._export.serde.schema.ModuleCallEntry(item));
  7579. this.metadata = new Map(Object.entries(obj.metadata || {}));
  7580. }
  7581. });
  7582. this.registerType('torch._export.serde.schema.ExportedProgram', class {
  7583. constructor(obj) {
  7584. Object.assign(this, { ...obj });
  7585. this.graph_module = new torch._export.serde.schema.GraphModule(obj.graph_module);
  7586. }
  7587. });
  7588. this.registerType('torch._export.serde.schema.SymExprHint', class extends torch._export.serde.union._Union {});
  7589. this.registerType('torch._export.serde.schema.SymExpr', class {
  7590. constructor(obj) {
  7591. this.expr_str = obj.expr_str;
  7592. this.hint = obj.hint ? new torch._export.serde.schema.SymExprHint(obj.hint) : null;
  7593. }
  7594. });
  7595. this.registerType('torch._export.serde.schema.SymInt', class extends torch._export.serde.union._Union {
  7596. constructor(obj) {
  7597. super(obj);
  7598. if (this.type === 'as_int') {
  7599. // continue
  7600. } else if (this.type === 'as_expr') {
  7601. this.as_expr = new torch._export.serde.schema.SymExpr(this.as_expr);
  7602. } else {
  7603. throw new python.Error(`Unsupported symbolic int '${this.type}'.`);
  7604. }
  7605. }
  7606. });
  7607. this.registerType('torch._export.serde.schema.SymIntArgument', class extends torch._export.serde.union._Union {
  7608. constructor(obj) {
  7609. super(obj);
  7610. Object.assign(this, { ...obj });
  7611. }
  7612. });
  7613. this.registerType('torch._export.serde.schema.SymBoolArgument', class extends torch._export.serde.union._Union {
  7614. constructor(obj) {
  7615. super(obj);
  7616. Object.assign(this, { ...obj });
  7617. }
  7618. });
  7619. this.registerType('torch._export.serde.schema.GraphSignature', class {
  7620. constructor(obj) {
  7621. this.input_specs = [];
  7622. if (Array.isArray(obj.input_specs)) {
  7623. this.input_specs = obj.input_specs.map((input_spec) => new torch._export.serde.schema.InputSpec(input_spec));
  7624. }
  7625. if (Array.isArray(obj.user_inputs)) {
  7626. for (const user_input of obj.user_inputs) {
  7627. this.input_specs.push(new torch._export.serde.schema.InputSpec({ user_input: { arg: { as_string: user_input } } }));
  7628. }
  7629. }
  7630. if (obj.inputs_to_parameters) {
  7631. for (const [input, parameter_name] of Object.entries(obj.inputs_to_parameters)) {
  7632. this.input_specs.push(new torch._export.serde.schema.InputSpec({ parameter: { arg: { name: input }, parameter_name } }));
  7633. }
  7634. }
  7635. this.output_specs = [];
  7636. if (Array.isArray(obj.output_specs)) {
  7637. this.output_specs = obj.output_specs.map((output_spec) => new torch._export.serde.schema.OutputSpec(output_spec));
  7638. }
  7639. }
  7640. });
  7641. this.registerType('torch._export.serde.schema.UserInputSpec', class {
  7642. constructor(obj) {
  7643. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  7644. }
  7645. });
  7646. this.registerType('torch._export.serde.schema.InputToParameterSpec', class {
  7647. constructor(obj) {
  7648. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  7649. this.parameter_name = obj.parameter_name;
  7650. }
  7651. });
  7652. this.registerType('torch._export.serde.schema.InputToBufferSpec', class {
  7653. constructor(obj) {
  7654. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  7655. this.buffer_name = obj.buffer_name;
  7656. }
  7657. });
  7658. this.registerType('torch._export.serde.schema.InputToTensorConstantSpec', class {
  7659. constructor(obj) {
  7660. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  7661. this.tensor_constant_name = obj.tensor_constant_name;
  7662. }
  7663. });
  7664. this.registerType('torch._export.serde.schema.InputSpec', class extends torch._export.serde.union._Union {
  7665. constructor(obj) {
  7666. super(obj);
  7667. if (this.type === 'user_input') {
  7668. this.user_input = new torch._export.serde.schema.UserInputSpec(this.user_input);
  7669. } else if (this.type === 'parameter') {
  7670. this.parameter = new torch._export.serde.schema.InputToParameterSpec(this.parameter);
  7671. } else if (this.type === 'buffer') {
  7672. this.buffer = new torch._export.serde.schema.InputToBufferSpec(this.buffer);
  7673. } else if (this.type === 'tensor_constant') {
  7674. this.tensor_constant = new torch._export.serde.schema.InputToTensorConstantSpec(this.tensor_constant);
  7675. } else {
  7676. throw new python.Error(`Unsupported input spec type '${this.type}'.`);
  7677. }
  7678. /*
  7679. tensor_constant: InputToTensorConstantSpec
  7680. custom_obj: InputToCustomObjSpec
  7681. token: InputTokenSpec
  7682. constant_input: ConstantInputSpec
  7683. */
  7684. }
  7685. });
  7686. this.registerType('torch._export.serde.schema.UserOutputSpec', class {
  7687. constructor(obj) {
  7688. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  7689. }
  7690. });
  7691. this.registerType('torch._export.serde.schema.OutputSpec', class extends torch._export.serde.union._Union {
  7692. constructor(obj) {
  7693. super(obj);
  7694. if (this.type === 'user_output') {
  7695. this.user_output = new torch._export.serde.schema.UserOutputSpec(this.user_output);
  7696. } else if (this.type === 'loss_output') {
  7697. this.loss_output = new torch._export.serde.schema.LossOutputSpec(this.loss_output);
  7698. } else if (this.type === 'buffer_mutation') {
  7699. this.buffer_mutation = new torch._export.serde.schema.BufferMutationSpec(this.buffer_mutation);
  7700. } else if (this.type === 'gradient_to_parameter') {
  7701. this.gradient_to_parameter = new torch._export.serde.schema.GradientToParameterSpec(this.gradient_to_parameter);
  7702. } else if (this.type === 'gradient_to_user_input') {
  7703. this.gradient_to_user_input = new torch._export.serde.schema.GradientToUserInputSpec(this.gradient_to_user_input);
  7704. } else if (this.type === 'user_input_mutation') {
  7705. this.user_input_mutation = new torch._export.serde.schema.UserInputMutationSpec(this.user_input_mutation);
  7706. } else if (this.type === 'token') {
  7707. this.token = new torch._export.serde.schema.OutputTokenSpec(this.token);
  7708. }
  7709. }
  7710. });
  7711. this.registerType('torch._export.serde.schema.TensorArgument', class {
  7712. constructor(obj) {
  7713. this.name = obj.name;
  7714. }
  7715. });
  7716. this.registerType('torch._export.serde.schema.OptionalTensorArgument', class extends torch._export.serde.union._Union {
  7717. constructor(obj) {
  7718. super(obj);
  7719. if (this.type === 'as_tensor') {
  7720. this.as_tensor = new torch._export.serde.schema.TensorArgument({ name: this.as_tensor });
  7721. } else if (this.type === 'as_none') {
  7722. this.as_none = null;
  7723. } else {
  7724. throw new python.Error(`Unsupported optional tensor argument '${this.type}'.`);
  7725. }
  7726. }
  7727. });
  7728. this.registerFunction('torch._export.load', (f, expected_opset_version) => {
  7729. const serialized_exported_program = f.get('serialized_exported_program.json');
  7730. const serialized_state_dict = f.get('serialized_state_dict.pt');
  7731. const serialized_constants = f.get('serialized_constants.pt');
  7732. const serialized_example_inputs = f.get('serialized_example_inputs.pt');
  7733. const artifact = new torch._export.serde.serialize.SerializedArtifact(serialized_exported_program, serialized_state_dict, serialized_constants, serialized_example_inputs);
  7734. return torch._export.serde.serialize.deserialize(artifact, expected_opset_version);
  7735. });
  7736. this.registerFunction('torch._export.serde.serialize._dict_to_dataclass', (cls, data) => {
  7737. if (data === null) {
  7738. return data;
  7739. }
  7740. if (cls) {
  7741. return new cls(data);
  7742. }
  7743. throw new python.Error(`Unsupported data class '${cls.__name__}'.`);
  7744. });
  7745. this.registerFunction('torch._export.serde.serialize.deserialize', (artifact, expected_opset_version) => {
  7746. const serialized_exported_program = torch._export.serde.serialize._dict_to_dataclass(torch._export.serde.schema.ExportedProgram, artifact.exported_program);
  7747. return new torch._export.serde.serialize.ExportedProgramDeserializer(expected_opset_version).deserialize(serialized_exported_program, artifact.state_dict, artifact.constants, artifact.example_inputs);
  7748. });
  7749. this.registerType('torch._export.serde.serialize.ExportedProgramDeserializer', class {
  7750. constructor(expected_opset_version) {
  7751. this.expected_opset_version = expected_opset_version;
  7752. }
  7753. deserialize(exported_program, state_dict, constants, example_inputs) {
  7754. const symbol_name_to_range = new Map(Object.entries(exported_program.range_constraints));
  7755. /*
  7756. symbol_name_to_range = {
  7757. k: symbolic_shapes.ValueRanges(_int_to_sympy_int(v.min_val), _int_to_sympy_int(v.max_val))
  7758. for k, v in exported_program.range_constraints.items()
  7759. }
  7760. */
  7761. const deserializer = new torch._export.serde.serialize.GraphModuleDeserializer();
  7762. const res = deserializer.deserialize(
  7763. exported_program.graph_module,
  7764. state_dict,
  7765. constants,
  7766. example_inputs,
  7767. symbol_name_to_range);
  7768. const range_constraints = null;
  7769. /*
  7770. range_constraints = self.deserialize_range_constraints(
  7771. symbol_name_to_range, res.names_to_symbols,
  7772. )
  7773. model_opset_version: Optional[Dict[str, int]] = serialized_artifact.exported_program.opset_version
  7774. self._validate_model_opset_version(model_opset_version)
  7775. upgrader = GraphModuleOpUpgrader(self.expected_opset_version, model_opset_version)
  7776. */
  7777. return new torch.export.exported_program.ExportedProgram(
  7778. res.graph_module, res.graph_module.graph, res.signature,
  7779. res.state_dict, range_constraints, res.module_call_graph, res.example_inputs,
  7780. null, // verifier=load_verifier(serialized_artifact.exported_program.dialect),
  7781. res.constants);
  7782. // return upgrader.upgrade(exported_program)
  7783. }
  7784. });
  7785. this.registerFunction('torch._export.serde.serialize.deserialize_torch_artifact', (serialized) => {
  7786. if (!serialized) {
  7787. return new builtins.dict();
  7788. }
  7789. const artifact = torch.load(serialized);
  7790. return artifact;
  7791. });
  7792. this.registerType('torch._export.serde.serialize.GraphModuleDeserializer', class {
  7793. constructor() {
  7794. this.serialized_name_to_node = new Map();
  7795. this.serialized_name_to_meta = new Map();
  7796. this.graph = new torch.fx.Graph();
  7797. this.module = new torch.nn.Module();
  7798. }
  7799. deserialize_graph_output(output) {
  7800. if (output.type === 'as_tensor') {
  7801. return this.serialized_name_to_node.get(output.as_tensor.name);
  7802. } else if (output.type === 'as_sym_int') {
  7803. return this.serialized_name_to_node.get(output.as_sym_int.as_name);
  7804. } else if (output.type === 'as_sym_bool') {
  7805. return this.serialized_name_to_node.get(output.as_sym_bool.as_name);
  7806. } else if (output.type === 'as_int') {
  7807. return this.serialized_name_to_node.get(output.as_int.as_name);
  7808. } else if (output.type === 'as_none') {
  7809. return this.serialized_name_to_node.get(output.as_sym_bool.as_name);
  7810. }
  7811. throw new python.Error(`Unsupported graph node ${output.type}.`);
  7812. }
  7813. deserialize_graph(serialized_graph) {
  7814. for (const [name, tensor_value] of serialized_graph.tensor_values) {
  7815. const meta_val = this.deserialize_tensor_meta(tensor_value.meta || tensor_value, this.fake_tensor_mode);
  7816. this.serialized_name_to_meta.set(name, meta_val);
  7817. }
  7818. for (const [name, sym_int_value] of serialized_graph.sym_int_values) {
  7819. this.serialized_name_to_meta.set(name, this.deserialize_sym_int(sym_int_value));
  7820. }
  7821. for (const [name, sym_bool_value] of serialized_graph.sym_bool_values) {
  7822. this.serialized_name_to_meta.set(name, this.deserialize_sym_bool(sym_bool_value));
  7823. }
  7824. for (const [name, script_obj_meta] of serialized_graph.custom_obj_values) {
  7825. this.serialized_name_to_meta.set(name, this.deserialize_script_obj_meta(script_obj_meta));
  7826. }
  7827. for (let i = 0; i < serialized_graph.inputs.length; i++) {
  7828. const input = serialized_graph.inputs[i];
  7829. if (input.type === 'as_tensor' || input.type === 'as_sym_int' || input.type === 'as_custom_obj') {
  7830. const node_name = input.value.name;
  7831. const placeholder_node = this.graph.placeholder(node_name);
  7832. placeholder_node.name = node_name;
  7833. this.sync_fx_node(node_name, placeholder_node);
  7834. } else if (input.type === 'as_int' || input.type === 'as_float' || input.type === 'as_bool' || input.type === 'as_none' || input.type === 'as_string') {
  7835. const node_name = this.signature.input_specs[i].arg.name;
  7836. const placeholder_node = this.graph.placeholder(node_name);
  7837. placeholder_node.meta.set('val', this.deserialize_input(input));
  7838. } else {
  7839. throw new python.Error(`Invalid input ${input.type}.`);
  7840. }
  7841. }
  7842. for (const serialized_node of serialized_graph.nodes) {
  7843. const target = this.deserialize_operator(serialized_node.target);
  7844. this.deserialize_node(serialized_node, target);
  7845. }
  7846. let outputs = [];
  7847. for (const output of serialized_graph.outputs) {
  7848. outputs.push(this.deserialize_graph_output(output));
  7849. }
  7850. if (serialized_graph.is_single_tensor_return) {
  7851. [outputs] = outputs;
  7852. } else {
  7853. outputs = new builtins.tuple(outputs);
  7854. }
  7855. const output_node = this.graph.output(outputs);
  7856. if (serialized_graph.is_single_tensor_return) {
  7857. output_node.meta.set("val", output_node.args[0].meta.get('val'));
  7858. } else {
  7859. /* output_node.meta["val"] = tuple(
  7860. arg.meta["val"] if isinstance(arg, torch.fx.Node) else arg
  7861. for arg in output_node.args[0]
  7862. ) */
  7863. }
  7864. return self.graph;
  7865. }
  7866. deserialize_operator(serialized_target) {
  7867. let module = null;
  7868. let serialized_target_names = null;
  7869. if (serialized_target.startsWith('_operator')) {
  7870. module = operator;
  7871. serialized_target_names = serialized_target.split(".").slice(1);
  7872. } else if (serialized_target.startsWith('torch')) {
  7873. module = torch;
  7874. serialized_target_names = serialized_target.split(".").slice(1);
  7875. } else if (serialized_target.startsWith('#')) {
  7876. return self.deserialize_extension_operator(serialized_target);
  7877. } else {
  7878. return serialized_target;
  7879. }
  7880. let target = module;
  7881. for (const name of serialized_target_names) {
  7882. target = builtins.getattr(target, name);
  7883. if (!target) {
  7884. return serialized_target;
  7885. }
  7886. }
  7887. return target;
  7888. }
  7889. deserialize_node(serialized_node, target) {
  7890. let fx_node = null;
  7891. if (torch._export.serde.serialize._SYM_BOOL_OPS.has(target) || torch._export.serde.serialize._SYM_INT_OPS.has(target)) {
  7892. const name = serialized_node.outputs[0].value.as_name;
  7893. const args = this.deserialize_sym_op_inputs(serialized_node.inputs);
  7894. fx_node = this.graph.create_node('call_function', target, args, null, name);
  7895. this.deserialize_sym_op_outputs(serialized_node, fx_node);
  7896. } else if (builtins.isinstance(target, torch._ops.HigherOrderOperator)) {
  7897. // assert(len(serialized_node.outputs) === 1 && serialized_node.outputs[0].type in ('as_tensors', 'as_tensor')), 'Only single tensor output or list of tensor output is supported for higher order operators.')
  7898. const [output] = serialized_node.outputs;
  7899. const name = output.type === 'as_tensor' ? output.value.name : null;
  7900. const args = serialized_node.inputs.map((input) => this.deserialize_input(input.arg));
  7901. fx_node = this.graph.create_node('call_function', target, args, {}, name);
  7902. if (output.as_tensor !== null) {
  7903. this.sync_fx_node(name, fx_node);
  7904. }
  7905. if (output.as_tensors !== null) {
  7906. this.deserialize_multiple_outputs(serialized_node, fx_node);
  7907. }
  7908. } else if (builtins.isinstance(target, torch._ops.OpOverload)) {
  7909. const name = this._is_single_tensor_return(target) ? serialized_node.outputs[0].as_tensor.name : null;
  7910. const [args, kwargs] = this.deserialize_inputs(target, serialized_node);
  7911. fx_node = this.graph.create_node('call_function', target, args, kwargs, name);
  7912. this.deserialize_outputs(serialized_node, fx_node);
  7913. } else {
  7914. throw new python.Error(`Unsupported node target type '${target}'.`);
  7915. }
  7916. fx_node.meta.update(this.deserialize_metadata(serialized_node.metadata));
  7917. if (fx_node.op !== 'placeholder' && fx_node.op !== 'output' && !fx_node.meta.has('nn_module_stack')) {
  7918. fx_node.meta.set('nn_module_stack', new builtins.dict());
  7919. }
  7920. }
  7921. deserialize_input_spec(i) {
  7922. if (i.type === 'user_input') {
  7923. return new torch.export.graph_signature.InputSpec(
  7924. torch.export.graph_signature.InputKind.USER_INPUT,
  7925. this.deserialize_argument_spec(i.user_input.arg),
  7926. null);
  7927. } else if (i.type === 'parameter') {
  7928. return new torch.export.graph_signature.InputSpec(
  7929. torch.export.graph_signature.InputKind.PARAMETER,
  7930. new torch.export.graph_signature.TensorArgument(i.parameter.arg.name),
  7931. i.parameter.parameter_name,
  7932. );
  7933. } else if (i.type === 'buffer') {
  7934. return new torch.export.graph_signature.InputSpec(
  7935. torch.export.graph_signature.InputKind.BUFFER,
  7936. new torch.export.graph_signature.TensorArgument(i.buffer.arg.name),
  7937. i.buffer.buffer_name,
  7938. i.buffer.persistent,
  7939. );
  7940. } else if (i.type === 'tensor_constant') {
  7941. return new torch.export.graph_signature.InputSpec(
  7942. torch.export.graph_signature.InputKind.CONSTANT_TENSOR,
  7943. new torch.export.graph_signature.TensorArgument(i.tensor_constant.arg.name),
  7944. i.tensor_constant.tensor_constant_name);
  7945. } else if (i.type === 'custom_obj') {
  7946. return new torch.export.graph_signature.InputSpec(
  7947. torch.export.graph_signature.InputKind.CUSTOM_OBJ,
  7948. new torch.export.graph_signature.CustomObjArgument(i.custom_obj.arg.name, i.custom_obj.arg.class_fqn),
  7949. i.custom_obj.custom_obj_name);
  7950. } else if (i.type === 'token') {
  7951. return new torch.export.graph_signature.InputSpec(
  7952. torch.export.graph_signature.InputKind.TOKEN,
  7953. new torch.export.graph_signature.TokenArgument(i.token.arg.name),
  7954. null);
  7955. } else if (i.type === 'constant_input') {
  7956. return new torch.export.graph_signature.InputSpec(
  7957. torch.export.graph_signature.InputKind.USER_INPUT,
  7958. new torch.export.graph_signature.ConstantArgument(i.constant_input.name, this.deserialize_constant_input(i.constant_input.value)),
  7959. null);
  7960. }
  7961. throw new python.Error(`Unknown input spec ${i}`);
  7962. }
  7963. deserialize_output_spec(o) {
  7964. if (o.type === 'user_output') {
  7965. return new torch.export.graph_signature.OutputSpec(
  7966. torch.export.graph_signature.OutputKind.USER_OUTPUT,
  7967. this.deserialize_argument_spec(o.user_output.arg),
  7968. null);
  7969. } else if (o.type === 'loss_output') {
  7970. return new torch.export.graph_signature.OutputSpec(
  7971. torch.export.graph_signature.OutputKind.LOSS_OUTPUT,
  7972. new torch.export.graph_signature.TensorArgument(o.loss_output.arg.name),
  7973. null);
  7974. } else if (o.type === 'buffer_mutation') {
  7975. return new torch.export.graph_signature.OutputSpec(
  7976. torch.export.graph_signature.OutputKind.BUFFER_MUTATION,
  7977. new torch.export.graph_signature.TensorArgument(o.buffer_mutation.arg.name),
  7978. o.buffer_mutation.buffer_name);
  7979. } else if (o.type === 'gradient_to_parameter') {
  7980. return new torch.export.graph_signature.OutputSpec(
  7981. torch.export.graph_signature.OutputKind.GRADIENT_TO_PARAMETER,
  7982. new torch.export.graph_signature.TensorArgument(o.gradient_to_parameter.arg.name),
  7983. o.gradient_to_parameter.parameter_name);
  7984. } else if (o.type === 'gradient_to_user_input') {
  7985. return new torch.export.graph_signature.OutputSpec(
  7986. torch.export.graph_signature.OutputKind.GRADIENT_TO_USER_INPUT,
  7987. new torch.export.graph_signature.TensorArgument(o.gradient_to_user_input.arg.name),
  7988. o.gradient_to_user_input.user_input_name);
  7989. } else if (o.type === 'user_input_mutation') {
  7990. return new torch.export.graph_signature.OutputSpec(
  7991. torch.export.graph_signature.OutputKind.USER_INPUT_MUTATION,
  7992. new torch.export.graph_signature.TensorArgument(o.user_input_mutation.arg.name),
  7993. o.user_input_mutation.user_input_name);
  7994. } else if (o.type === 'token') {
  7995. return new torch.export.graph_signature.OutputSpec(
  7996. torch.export.graph_signature.OutputKind.TOKEN,
  7997. new torch.export.graph_signature.TokenArgument(o.token.arg.name),
  7998. null);
  7999. }
  8000. throw new python.Error(`Unknown output spec ${o}.`);
  8001. }
  8002. deserialize_signature(sig) {
  8003. return new torch.export.graph_signature.ExportGraphSignature(
  8004. sig.input_specs.map((i) => this.deserialize_input_spec(i)),
  8005. sig.output_specs.map((o) => this.deserialize_output_spec(o)));
  8006. }
  8007. deserialize(serialized_graph_module, serialized_state_dict, constants, example_inputs, symbol_name_to_range) {
  8008. this.shape_env = new torch.fx.experimental.symbolic_shapes.ShapeEnv(/* assume_static_by_default = True */);
  8009. /*
  8010. this.fake_tensor_mode = FakeTensorMode(
  8011. allow_fallback_kernels=False,
  8012. allow_non_fake_inputs=True,
  8013. shape_env=this.shape_env,
  8014. )
  8015. */
  8016. this.symbol_name_to_symbol = new Map();
  8017. this.constants = torch._export.serde.serialize.deserialize_torch_artifact(constants);
  8018. this.signature = this.deserialize_signature(serialized_graph_module.signature);
  8019. this.symbol_name_to_range = symbol_name_to_range || new Map();
  8020. /*
  8021. if symbol_name_to_range:
  8022. for k, vr in symbol_name_to_range.items():
  8023. lower = int(vr.lower)
  8024. if vr.upper >= 2: # max is >= 2, not sym bool range
  8025. lower = max(2, lower)
  8026. this.symbol_name_to_range[k] = symbolic_shapes.ValueRanges(_int_to_sympy_int(lower), vr.upper)
  8027. */
  8028. this.example_inputs = null;
  8029. if (example_inputs && example_inputs.length > 0) {
  8030. torch._export.serde.serialize.deserialize_torch_artifact(example_inputs);
  8031. }
  8032. this.deserialize_graph(serialized_graph_module.graph);
  8033. const module_call_graph = null; // this.deserialize_module_call_graph(serialized_graph_module.module_call_graph)
  8034. return {
  8035. graph_module: torch._export.exported_program._create_graph_module_for_export(this.module, this.graph),
  8036. signature: this.signature,
  8037. module_call_graph,
  8038. names_to_symbols: this.symbol_name_to_symbol,
  8039. state_dict: torch._export.serde.serialize.deserialize_torch_artifact(serialized_state_dict),
  8040. constants: this.constants,
  8041. example_inputs: this.example_inputs,
  8042. };
  8043. }
  8044. sync_fx_node(name, fx_node) {
  8045. if (this.serialized_name_to_node.has(name)) {
  8046. throw new python.Error(`Node ${name} has already been deserialized before.`);
  8047. }
  8048. this.serialized_name_to_node.set(name, fx_node);
  8049. fx_node.meta.set('val', this.serialized_name_to_meta.get(name));
  8050. }
  8051. deserialize_sym_op_inputs(inputs) {
  8052. return inputs.map((input) => this.deserialize_input(input.arg));
  8053. }
  8054. deserialize_inputs(target, serialized_node) {
  8055. const schema_args = this._get_schema_from_target(target).arguments;
  8056. const actual_args = new Map(serialized_node.inputs.map((input) => [input.name, this.deserialize_input(input.arg)]));
  8057. const args = new builtins.list();
  8058. const kwargs = new builtins.dict();
  8059. for (const schema_arg of schema_args) {
  8060. const is_positional = !schema_arg.has_default_value() && !schema_arg.kwarg_only;
  8061. if (is_positional) {
  8062. args.push(actual_args.get(schema_arg.name));
  8063. } else if (actual_args.has(schema_arg.name)) {
  8064. kwargs.set(schema_arg.name, actual_args.get(schema_arg.name));
  8065. }
  8066. }
  8067. return [args, kwargs];
  8068. }
  8069. deserialize_input(inp) {
  8070. const value = inp.value;
  8071. const typ_ = inp.type;
  8072. if (typ_ === 'as_none') {
  8073. return null;
  8074. } else if (typ_ === 'as_tensor') {
  8075. return this.serialized_name_to_node.get(inp.as_tensor.name);
  8076. } else if (typ_ === 'as_scalar_type') {
  8077. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE[inp.as_scalar_type];
  8078. } else if (typ_ === 'as_memory_format') {
  8079. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_MEMORY_FORMAT[inp.as_memory_format];
  8080. } else if (typ_ === 'as_layout') {
  8081. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_LAYOUT[inp.as_layout];
  8082. } else if (typ_ === 'as_graph') {
  8083. /* assert isinstance(value, GraphArgument)
  8084. with this.save_graph_module():
  8085. this.deserialize_graph(value.graph)
  8086. submodule = ep._create_graph_module_for_export(this.module, this.graph)
  8087. this.module.register_module(value.name, submodule)
  8088. return this.graph.create_node(
  8089. 'get_attr',
  8090. value.name,
  8091. name=value.name,
  8092. )*/
  8093. throw new Error();
  8094. } else if (typ_ === 'as_device') {
  8095. return this.deserialize_device(inp.as_device);
  8096. } else if (typ_ === 'as_int') {
  8097. return inp.as_int;
  8098. } else if (typ_ === 'as_float') {
  8099. return inp.as_float;
  8100. } else if (typ_ === 'as_bool') {
  8101. return inp.as_bool;
  8102. } else if (typ_ === 'as_string') {
  8103. return inp.as_string;
  8104. } else if (typ_ === 'as_sym_int') {
  8105. return this.deserialize_sym_argument(inp.as_sym_int);
  8106. } else if (typ_ === 'as_sym_bool') {
  8107. return this.deserialize_sym_argument(inp.as_sym_bool);
  8108. } else if (Array.isArray(value)) {
  8109. if (value.length === 0) {
  8110. return [];
  8111. } else if (typ_ === 'as_tensors') {
  8112. const result = [];
  8113. for (const arg of value) {
  8114. result.push(this.serialized_name_to_node.get(arg.name));
  8115. }
  8116. return result;
  8117. } else if (typ_ === 'as_ints' || typ_ === 'as_floats' || typ_ === 'as_bools' || typ_ === 'as_strings') {
  8118. return Array.from(value);
  8119. } else if (typ_ === 'as_sym_ints' || typ_ === 'as_sym_bools') {
  8120. return value.map((arg) => this.deserialize_sym_argument(arg));
  8121. } else if (typ_ === 'as_optional_tensors') {
  8122. const deserialize_optional_tensor_args = (a) => {
  8123. if (a.type === 'as_none') {
  8124. return null;
  8125. } else if (a.type === 'as_tensor') {
  8126. return this.serialized_name_to_node.get(a.value.name);
  8127. }
  8128. throw new python.Error(`Unsupported argument '${typ_}'.`);
  8129. };
  8130. return value.map((item) => deserialize_optional_tensor_args(item));
  8131. }
  8132. throw new python.Error(`Unsupported argument '${typ_}'.`);
  8133. } else if (typ_ === 'as_custom_obj') {
  8134. if (this.serialized_name_to_node.has(inp.as_custom_obj.name)) {
  8135. return this.serialized_name_to_node.get(inp.as_custom_obj.name);
  8136. }
  8137. return this.constants[inp.as_custom_obj.name];
  8138. } else if (typ_ === 'as_operator') {
  8139. return this.deserialize_operator(inp.as_operator);
  8140. }
  8141. throw new python.Error(`Unsupported argument '${typ_}'.`);
  8142. }
  8143. deserialize_sym_argument(sym_arg) {
  8144. if (sym_arg instanceof torch._export.serde.schema.SymIntArgument) {
  8145. if (sym_arg.type === 'as_int') {
  8146. return sym_arg.as_int;
  8147. } else if (sym_arg.type === 'as_name') {
  8148. return this.serialized_name_to_node.get(sym_arg.as_name);
  8149. }
  8150. } else if (sym_arg instanceof torch._export.serde.schema.SymBoolArgument) {
  8151. if (sym_arg.type === 'as_bool') {
  8152. return sym_arg.as_bool;
  8153. } else if (sym_arg.type === 'as_name') {
  8154. return self.serialized_name_to_node.get(sym_arg.as_name);
  8155. }
  8156. }
  8157. throw new python.Error(`Unsupported symbolic argument type '${sym_arg.type}`);
  8158. }
  8159. deserialize_sym_op_outputs(serialized_node, fx_node) {
  8160. this.sync_fx_node(serialized_node.outputs[0].value.as_name, fx_node);
  8161. }
  8162. deserialize_outputs(serialized_node, fx_node) {
  8163. if (serialized_node.outputs.length === 0) {
  8164. return;
  8165. }
  8166. if (serialized_node.outputs.length === 1 &&
  8167. serialized_node.outputs[0].type === 'as_tensor') {
  8168. this.sync_fx_node(serialized_node.outputs[0].as_tensor.name, fx_node);
  8169. return;
  8170. } else if (serialized_node.outputs.length === 1 &&
  8171. (serialized_node.outputs[0].value instanceof torch._export.serde.schema.SymIntArgument ||
  8172. serialized_node.outputs[0].value instanceof torch._export.serde.schema.SymBoolArgument)) {
  8173. this.sync_fx_node(serialized_node.outputs[0].value.as_name, fx_node);
  8174. return;
  8175. }
  8176. this.deserialize_multiple_outputs(serialized_node, fx_node);
  8177. }
  8178. deserialize_multiple_outputs(serialized_node, fx_node) {
  8179. const deserialized_metadata = this.deserialize_metadata(serialized_node.metadata);
  8180. const generate_getitem = (meta_val, fx_node, arg, idx) => {
  8181. let name = '';
  8182. if (arg instanceof torch._export.serde.schema.TensorArgument) {
  8183. name = arg.name;
  8184. } else if (arg instanceof torch._export.serde.schema.SymIntArgument) {
  8185. name = arg.as_name;
  8186. } else {
  8187. throw new python.Error(`Unsupported argument type '${arg}'.`);
  8188. }
  8189. const individual_output = this.graph.create_node(
  8190. 'call_function',
  8191. operator.getitem,
  8192. new builtins.tuple([fx_node, idx]),
  8193. null,
  8194. name,
  8195. );
  8196. this.sync_fx_node(name, individual_output);
  8197. meta_val.push(this.serialized_name_to_meta.get(name));
  8198. individual_output.meta.update(deserialized_metadata);
  8199. };
  8200. const generate_getitems = (meta_val, fx_node, args) => {
  8201. for (let idx = 0; idx < args.length; idx++) {
  8202. let arg = args[idx];
  8203. if (arg instanceof torch._export.serde.schema.Argument) {
  8204. arg = arg.value;
  8205. }
  8206. if (arg instanceof torch._export.serde.schema.TensorArgument || arg instanceof torch._export.serde.schema.SymIntArgument) {
  8207. generate_getitem(meta_val, fx_node, arg, idx);
  8208. } else if (Array.isArray(arg)) { // arg instanceof (list, tuple))
  8209. const list_output = this.graph.create_node(
  8210. 'call_function',
  8211. operator.getitem,
  8212. (fx_node, idx),
  8213. );
  8214. meta_val.append([]);
  8215. generate_getitems(meta_val[-1], list_output, arg);
  8216. list_output.meta.update(deserialized_metadata);
  8217. list_output.meta.set('val', meta_val[-1]);
  8218. } else {
  8219. throw new python.Error(`Unsupported node output type: '${arg}'.`);
  8220. }
  8221. }
  8222. };
  8223. const meta_val = [];
  8224. if (serialized_node.outputs.length === 1) {
  8225. // assert isinstance(serialized_node.outputs[0].value, list)
  8226. // assert isinstance(serialized_node.outputs[0].value[0], TensorArgument)
  8227. generate_getitems(meta_val, fx_node, serialized_node.outputs[0].as_tensors);
  8228. } else {
  8229. generate_getitems(meta_val, fx_node, serialized_node.outputs);
  8230. }
  8231. fx_node.meta.set('val', new builtins.tuple(meta_val));
  8232. this.serialized_name_to_node.set(fx_node.name, fx_node);
  8233. }
  8234. deserialize_metadata(metadata) {
  8235. const ret = new builtins.dict();
  8236. const stack_trace = metadata.get('stack_trace');
  8237. if (stack_trace) {
  8238. ret.set('stack_trace', stack_trace);
  8239. }
  8240. const deserialize_meta_func = (serialized_target) => {
  8241. let module = null;
  8242. let serialized_target_names = [];
  8243. if (serialized_target.startsWith('torch.nn')) {
  8244. module = torch.nn;
  8245. serialized_target_names = serialized_target.split('.').slice(1);
  8246. } else if (serialized_target.startsWith('torch')) {
  8247. module = torch;
  8248. serialized_target_names = serialized_target.split('.').slice(1);
  8249. } else {
  8250. return this.deserialize_operator(serialized_target);
  8251. }
  8252. let target = module;
  8253. for (const name of serialized_target_names) {
  8254. if (!builtins.hasattr(target, name)) {
  8255. return serialized_target;
  8256. }
  8257. target = builtins.getattr(target, name);
  8258. }
  8259. return target;
  8260. };
  8261. const nn_module_stack_str = metadata.get('nn_module_stack');
  8262. if (nn_module_stack_str) {
  8263. const import_nn_module_stack = (key, path, ty) => {
  8264. return [key, [path, ty]];
  8265. };
  8266. const nn_module_stack = new Map(nn_module_stack_str.split(';').map((item) => import_nn_module_stack(...item.split(','))));
  8267. ret.set('nn_module_stack', nn_module_stack);
  8268. }
  8269. const source_fn_st_str = metadata.get('source_fn_stack');
  8270. if (source_fn_st_str) {
  8271. const source_fn_st = [];
  8272. for (const source_fn_str of source_fn_st_str.split(';')) {
  8273. const [name, target_str] = source_fn_str.split(',');
  8274. source_fn_st.push([name, deserialize_meta_func(target_str)]);
  8275. }
  8276. ret.set('source_fn_stack', source_fn_st);
  8277. }
  8278. const torch_fn = metadata.get('torch_fn');
  8279. if (torch_fn) {
  8280. ret.set('torch_fn', new builtins.tuple(torch_fn.split(';')));
  8281. }
  8282. const custom_str = metadata.get('custom');
  8283. if (custom_str) {
  8284. ret.set('custom', JSON.parse(custom_str));
  8285. }
  8286. return ret;
  8287. }
  8288. deserialize_argument_spec(x) {
  8289. if (x.type === 'as_tensor') {
  8290. return new torch.export.graph_signature.TensorArgument(x.as_tensor.name);
  8291. } else if (x.type === 'as_sym_int') {
  8292. return new torch.export.graph_signature.SymIntArgument(x.as_sym_int.as_name);
  8293. } else if (x.type === 'as_custom_obj') {
  8294. return new torch.export.graph_signature.ConstantArgument(x.as_custom_obj.name, this.deserialize_input(x));
  8295. }
  8296. return new torch.export.graph_signature.ConstantArgument('', this.deserialize_input(x));
  8297. }
  8298. deserialize_tensor_meta(tensor_meta) {
  8299. const sizes = tensor_meta.sizes.map((val) => this.deserialize_sym_int(val));
  8300. const strides = tensor_meta.strides.map((val) => this.deserialize_sym_int(val));
  8301. const device = this.deserialize_device(tensor_meta.device);
  8302. const dtype = torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE[tensor_meta.dtype];
  8303. return torch.empty_strided(sizes, strides, dtype, null, device);
  8304. }
  8305. deserialize_sym_int(s) {
  8306. if (s.as_expr !== undefined && s.as_expr !== null) {
  8307. let sym = {};
  8308. if (this.symbol_name_to_symbol.has(s.as_expr.expr_str)) {
  8309. sym = this.symbol_name_to_symbol.get(s.as_expr.expr_str);
  8310. } else {
  8311. sym = {};
  8312. /*
  8313. sym = sympy.sympify(val.expr_str, locals=this.symbol_name_to_symbol)
  8314. if isinstance(sym, sympy.Symbol) {
  8315. this.symbol_name_to_symbol[val.expr_str] = sym
  8316. if vr := this.symbol_name_to_range.get(val.expr_str):
  8317. symbolic_shapes._constrain_symbol_range(
  8318. this.shape_env,
  8319. sym,
  8320. compiler_min=vr.lower, # type: ignore[arg-type]
  8321. compiler_max=vr.upper, # type: ignore[arg-type]
  8322. runtime_min=vr.lower, # type: ignore[arg-type]
  8323. runtime_max=vr.upper # type: ignore[arg-type]
  8324. )
  8325. }
  8326. */
  8327. }
  8328. const hint = s.as_expr.hint || null;
  8329. if (hint && (hint.$type === 'as_int' || hint.as_int !== undefined)) {
  8330. return this.deserialize_sym_int(hint);
  8331. }
  8332. return this.shape_env.create_symintnode(sym, hint);
  8333. } else if (s.as_int !== undefined && s.as_int !== null) {
  8334. return s.as_int;
  8335. } else if (s.$type === 'as_int') {
  8336. return s.$value;
  8337. }
  8338. throw new python.Error('SymInt has invalid field type.');
  8339. }
  8340. deserialize_device(d) {
  8341. if (d.index === null) {
  8342. return new torch.device(d.type);
  8343. }
  8344. return new torch.device(d.type, d.index);
  8345. }
  8346. _get_schema_from_target(target) {
  8347. if (target instanceof torch._ops.OpOverload) {
  8348. return target._schema;
  8349. }
  8350. throw new python.Error(`Unsupported schema '${target.name}'.`);
  8351. }
  8352. _is_single_tensor_return(target) {
  8353. const schema = this._get_schema_from_target(target);
  8354. const returns = schema.returns;
  8355. return returns.length === 1 && returns[0].real_type instanceof torch.TensorType;
  8356. }
  8357. });
  8358. this.registerType('torch._export.verifier.Verifier', class {});
  8359. this.registerType('torch._dynamo.convert_frame.CatchErrorsWrapper', class {});
  8360. this.registerType('torch._dynamo.convert_frame.ConvertFrameAssert', class {});
  8361. this.registerType('torch._dynamo.convert_frame.ConvertFrame', class {});
  8362. this.registerType('torch._dynamo.eval_frame._TorchDynamoContext', class {});
  8363. this.registerType('torch._dynamo.eval_frame.OptimizedModule', class extends torch.nn.modules.module.Module {});
  8364. this.registerType('torch._dynamo.eval_frame.OptimizeContext', class extends torch._dynamo.eval_frame._TorchDynamoContext {});
  8365. this.registerType('torch._dynamo.hooks.Hooks', class {});
  8366. this.registerType('torch._dynamo.repro.after_dynamo.WrapBackendDebug', class {});
  8367. this.registerType('torch._TorchCompileInductorWrapper', class {});
  8368. this.registerFunction('torch._inductor.compile_fx.compile_fx');
  8369. this.registerFunction('torch_utils.persistence._reconstruct_persistent_obj', (meta) => {
  8370. const name = `_imported_module_${Math.floor(Math.random() * 10000)}`;
  8371. const module = execution.invoke('types.ModuleType', [name]);
  8372. execution.register('sys').modules.set(name, module);
  8373. const context = new python.Execution.Context(module, null);
  8374. execution.exec(meta.get('module_src'), context);
  8375. const obj = execution.invoke(`${name}.${meta.get('class_name')}`, []);
  8376. const state = meta.get('state');
  8377. if (state) {
  8378. if (obj.__setstate__) {
  8379. obj.__setstate__(state);
  8380. } else {
  8381. for (const [key, value] of state) {
  8382. obj[key] = value;
  8383. }
  8384. }
  8385. }
  8386. return obj;
  8387. });
  8388. this.registerFunction('torch_utils.misc.assert_shape', (/* tensor, ref_shape */) => {});
  8389. this.registerFunction('torch_utils.ops.conv2d_resample.conv2d_resample', (/* x, w, f, up, down, padding, groups, flip_weight, flip_filter */) => {});
  8390. this.registerFunction('torch_utils.ops.upfirdn2d.setup_filter', (/* x, f, up, down, padding, flip_filter, gain, impl */) => {});
  8391. this.registerFunction('torch_utils.ops.bias_act', (/* x, b, dim, act, alpha, gain, clamp, impl */) => {});
  8392. this.registerFunction('torch_utils.ops.fma.fma', (/* a, b, c */) => {});
  8393. this.registerType('torch.device', class {
  8394. constructor(type, index) {
  8395. this.type = type;
  8396. this.index = index ? index : null;
  8397. }
  8398. __str__() {
  8399. return this.index === null ? this.type : `${this.type}:${this.index}`;
  8400. }
  8401. toString() {
  8402. const index = this.index === null ? '' : `, index=${this.index}`;
  8403. return `device(type='${this.type}'${index})`;
  8404. }
  8405. });
  8406. this.registerType('torch.memory_format', class {
  8407. constructor(name) {
  8408. this.name = name;
  8409. }
  8410. __str__() {
  8411. return `torch.${this.name}`;
  8412. }
  8413. toString() {
  8414. return this.__str__();
  8415. }
  8416. });
  8417. this.registerType('torch.dtype', class {
  8418. constructor(scalar_type, name, itemsize) {
  8419. this._scalar_type = scalar_type;
  8420. this._name = name;
  8421. this._itemsize = itemsize;
  8422. }
  8423. scalar_type() {
  8424. return this._scalar_type;
  8425. }
  8426. itemsize() {
  8427. return this._itemsize;
  8428. }
  8429. __reduce__() {
  8430. return this._name;
  8431. }
  8432. __str__() {
  8433. return `torch.${this._name}`;
  8434. }
  8435. toString() {
  8436. return this.__str__();
  8437. }
  8438. });
  8439. this.registerType('torch.layout', class {
  8440. constructor(name) {
  8441. this._name = name;
  8442. }
  8443. __str__() {
  8444. return `torch.${this._name}`;
  8445. }
  8446. toString() {
  8447. return this.__str__();
  8448. }
  8449. });
  8450. this.registerType('torch.qscheme', class {
  8451. constructor(name) {
  8452. this._name = name;
  8453. }
  8454. __str__() {
  8455. return this._name;
  8456. }
  8457. toString() {
  8458. return this.__str__();
  8459. }
  8460. });
  8461. this.registerType('torch.utils.hooks.RemovableHandle', class {
  8462. __setstate__(state) {
  8463. [this.hooks_dict_ref, this.id] = state;
  8464. this.hooks_dict_ref = this.hooks_dict_ref || new Map();
  8465. }
  8466. });
  8467. this.registerType('torch.storage._StorageBase', class {
  8468. constructor(size, dtype) {
  8469. this._size = size;
  8470. this._dtype = dtype;
  8471. this._device = null;
  8472. }
  8473. get device() {
  8474. return this._device;
  8475. }
  8476. get dtype() {
  8477. return this._dtype;
  8478. }
  8479. element_size() {
  8480. return this._dtype.element_size;
  8481. }
  8482. size() {
  8483. return this._size;
  8484. }
  8485. get data() {
  8486. return this._cdata;
  8487. }
  8488. _set_cdata(data) {
  8489. const length = this.size() * this.dtype.itemsize();
  8490. if (length !== data.length) {
  8491. throw new python.Error('Storage data size mismatch.');
  8492. }
  8493. this._cdata = data;
  8494. }
  8495. _set_from_file(unpickler) {
  8496. const buffer = unpickler.read(8);
  8497. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  8498. if (size !== this.size()) {
  8499. throw new python.Error('Storage size mismatch.');
  8500. }
  8501. const itemsize = this.dtype.itemsize();
  8502. const data = unpickler.stream(itemsize * size);
  8503. this._set_cdata(data);
  8504. }
  8505. static _new_with_file(unpickler) {
  8506. const buffer = unpickler.read(8);
  8507. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  8508. const storage = new this(size);
  8509. const itemsize = storage.dtype.itemsize();
  8510. const data = unpickler.stream(itemsize * size);
  8511. storage._set_cdata(data);
  8512. return storage;
  8513. }
  8514. });
  8515. this.registerType('torch.storage.UntypedStorage', class extends torch.storage._StorageBase {
  8516. constructor() {
  8517. super();
  8518. throw new python.Error('UntypedStorage not implemented.');
  8519. }
  8520. });
  8521. this.registerType('torch.storage.TypedStorage', class {
  8522. constructor(...args) {
  8523. if (args.length >= 2 && Number.isInteger(args[0]) && args[1] instanceof torch.dtype) {
  8524. if (args[3] instanceof torch.device) {
  8525. [this._size, this._dtype, , this._device] = args;
  8526. } else {
  8527. [this._size, this._dtype] = args;
  8528. }
  8529. } else {
  8530. throw new python.Error(`Unsupported TypedStorage arguments '${JSON.stringify(args)}'.`);
  8531. }
  8532. }
  8533. get device() {
  8534. return this._device;
  8535. }
  8536. get dtype() {
  8537. return this._dtype;
  8538. }
  8539. element_size() {
  8540. return this._dtype.element_size;
  8541. }
  8542. size() {
  8543. return this._size;
  8544. }
  8545. get data() {
  8546. return this._cdata;
  8547. }
  8548. _set_cdata(data) {
  8549. const length = this.size() * this.dtype.itemsize();
  8550. if (length !== data.length) {
  8551. throw new python.Error('Storage data size mismatch.');
  8552. }
  8553. this._cdata = data;
  8554. }
  8555. _set_from_file(unpickler) {
  8556. const buffer = unpickler.read(8);
  8557. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  8558. if (size !== this.size()) {
  8559. throw new python.Error('Storage size mismatch.');
  8560. }
  8561. const itemsize = this.dtype.itemsize();
  8562. const data = unpickler.stream(itemsize * size);
  8563. this._set_cdata(data);
  8564. }
  8565. static _new_with_file(unpickler) {
  8566. const buffer = unpickler.read(8);
  8567. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  8568. const storage = new this(size);
  8569. const itemsize = storage.dtype.itemsize();
  8570. const data = unpickler.stream(itemsize * size);
  8571. storage._set_cdata(data);
  8572. return storage;
  8573. }
  8574. });
  8575. this.registerType('torch.storage._LegacyStorage', class extends torch.storage.TypedStorage {
  8576. constructor() {
  8577. super();
  8578. throw new python.Error('_LegacyStorage not implemented.');
  8579. }
  8580. });
  8581. this.registerType('torch.BoolStorage', class extends torch.storage._StorageBase {
  8582. constructor(size) {
  8583. super(size, torch.bool);
  8584. }
  8585. });
  8586. this.registerType('torch.ByteStorage', class extends torch.storage._StorageBase {
  8587. constructor(size) {
  8588. super(size, torch.uint8);
  8589. }
  8590. });
  8591. this.registerType('torch.CharStorage', class extends torch.storage._StorageBase {
  8592. constructor(size) {
  8593. super(size, torch.int8);
  8594. }
  8595. });
  8596. this.registerType('torch.ShortStorage', class extends torch.storage._StorageBase {
  8597. constructor(size) {
  8598. super(size, torch.int16);
  8599. }
  8600. });
  8601. this.registerType('torch.IntStorage', class extends torch.storage._StorageBase {
  8602. constructor(size) {
  8603. super(size, torch.int32);
  8604. }
  8605. });
  8606. this.registerType('torch.LongStorage', class extends torch.storage._StorageBase {
  8607. constructor(size) {
  8608. super(size, torch.int64);
  8609. }
  8610. });
  8611. this.registerType('torch.HalfStorage', class extends torch.storage._StorageBase {
  8612. constructor(size) {
  8613. super(size, torch.float16);
  8614. }
  8615. });
  8616. this.registerType('torch.FloatStorage', class extends torch.storage._StorageBase {
  8617. constructor(size) {
  8618. super(size, torch.float32);
  8619. }
  8620. });
  8621. this.registerType('torch.DoubleStorage', class extends torch.storage._StorageBase {
  8622. constructor(size) {
  8623. super(size, torch.float64);
  8624. }
  8625. });
  8626. this.registerType('torch.ComplexHalfStorage', class extends torch.storage._StorageBase {
  8627. constructor(size) {
  8628. super(size, torch.complex32);
  8629. }
  8630. });
  8631. this.registerType('torch.ComplexFloatStorage', class extends torch.storage._StorageBase {
  8632. constructor(size) {
  8633. super(size, torch.complex64);
  8634. }
  8635. });
  8636. this.registerType('torch.ComplexDoubleStorage', class extends torch.storage._StorageBase {
  8637. constructor(size) {
  8638. super(size, torch.complex128);
  8639. }
  8640. });
  8641. this.registerType('torch.QInt8Storage', class extends torch.storage._StorageBase {
  8642. constructor(size) {
  8643. super(size, torch.qint8);
  8644. }
  8645. });
  8646. this.registerType('torch.QUInt8Storage', class extends torch.storage._StorageBase {
  8647. constructor(size) {
  8648. super(size, torch.quint8);
  8649. }
  8650. });
  8651. this.registerType('torch.QInt32Storage', class extends torch.storage._StorageBase {
  8652. constructor(size) {
  8653. super(size, torch.qint32);
  8654. }
  8655. });
  8656. this.registerType('torch.BFloat16Storage', class extends torch.storage._StorageBase {
  8657. constructor(size) {
  8658. super(size, torch.bfloat16);
  8659. }
  8660. });
  8661. this.registerType('torch.Size', class extends Array {
  8662. constructor(size) {
  8663. super(size.length);
  8664. for (let i = 0; i < size.length; i++) {
  8665. this[i] = size[i];
  8666. }
  8667. }
  8668. __len__() {
  8669. return this.length;
  8670. }
  8671. });
  8672. this.registerType('torch.Tensor', class {
  8673. constructor() {
  8674. this._layout = torch.strided;
  8675. }
  8676. get device() {
  8677. return this.storage().device;
  8678. }
  8679. get dtype() {
  8680. if (this._layout === torch.sparse_coo) {
  8681. return this._values.dtype();
  8682. }
  8683. return this.storage().dtype;
  8684. }
  8685. get shape() {
  8686. return this._shape;
  8687. }
  8688. get layout() {
  8689. return this._layout;
  8690. }
  8691. get values() {
  8692. if (this._layout === torch.sparse_coo) {
  8693. return this._values;
  8694. }
  8695. throw new python.Error(`Unsupported values in layout'${this._layout.__str__()}'.`);
  8696. }
  8697. get indices() {
  8698. if (this._layout === torch.sparse_coo) {
  8699. return this._indices;
  8700. }
  8701. throw new python.Error(`Unsupported indices in layout'${this._indices.__str__()}'.`);
  8702. }
  8703. get is_quantized() {
  8704. return this.__quantized__ === true;
  8705. }
  8706. get is_nested() {
  8707. return this.__nested__ === true;
  8708. }
  8709. get is_sparse() {
  8710. return this.layout !== torch.strided;
  8711. }
  8712. size() {
  8713. return this._shape;
  8714. }
  8715. storage() {
  8716. if (!this._storage) {
  8717. const name = this.__class__.__name__ === 'Tensor' ? 'FloatStorage' : this.__storage__.__name__.replace('Tensor', 'Storage');
  8718. this._storage = self.invoke(`${this.__class__.__module__}.${name}`, []);
  8719. }
  8720. return this._storage;
  8721. }
  8722. storage_offset() {
  8723. return this._storage_offset;
  8724. }
  8725. stride() {
  8726. return this._stride;
  8727. }
  8728. resize_(shape) {
  8729. this._shape = shape;
  8730. }
  8731. __len__() {
  8732. return this._shape[0];
  8733. }
  8734. __setstate__(state) {
  8735. switch (state.length) {
  8736. case 3:
  8737. break;
  8738. case 4:
  8739. [this._storage, this._storage_offset, this._shape, this._stride] = state;
  8740. break;
  8741. case 5:
  8742. [this.data, ,this._backward_hooks, this.requires_grad] = state;
  8743. break;
  8744. default:
  8745. throw new python.Error(`Unsupported tensor state length '${state.length}'.`);
  8746. }
  8747. }
  8748. __bool__() {
  8749. return true;
  8750. }
  8751. __int__() {
  8752. const storage = this.storage();
  8753. if (storage && storage.dtype.__reduce__() === 'int64' && storage.data.length === 8) {
  8754. const buffer = storage.data.peek ? storage.data.peek() : storage.data;
  8755. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  8756. return view.getBigInt64(0, true);
  8757. }
  8758. return NaN;
  8759. }
  8760. __float__() {
  8761. const storage = this.storage();
  8762. if (storage && storage.dtype.__reduce__() === 'float32') {
  8763. if (storage.size() !== undefined && storage.data.length === 4) {
  8764. const buffer = storage.data.peek ? storage.data.peek() : storage.data;
  8765. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  8766. return view.getFloat32(0, true);
  8767. }
  8768. }
  8769. return NaN;
  8770. }
  8771. __str__() {
  8772. return 'tensor(...)';
  8773. }
  8774. });
  8775. this.registerType('torch.nn.parameter.Parameter', class extends torch.Tensor {
  8776. constructor(data, requires_grad) {
  8777. super();
  8778. if (!data) {
  8779. data = self.invoke('torch.Tensor', [[]]);
  8780. }
  8781. this.data = data;
  8782. this.requires_grad = requires_grad === undefined ? true : requires_grad;
  8783. }
  8784. });
  8785. this.registerType('torch.nn.parameter.UninitializedParameter', class extends torch.nn.parameter.Parameter {
  8786. constructor(requires_grad /*, device, dtype */) {
  8787. super(undefined, requires_grad);
  8788. }
  8789. });
  8790. this.registerType('torch.nn.parameter.UninitializedBuffer', class extends torch.Tensor {});
  8791. this.registerType('torch.BoolTensor', class extends torch.Tensor {});
  8792. this.registerType('torch.ByteTensor', class extends torch.Tensor {});
  8793. this.registerType('torch.CharTensor', class extends torch.Tensor {});
  8794. this.registerType('torch.ShortTensor', class extends torch.Tensor {});
  8795. this.registerType('torch.IntTensor', class extends torch.Tensor {});
  8796. this.registerType('torch.LongTensor', class extends torch.Tensor {});
  8797. this.registerType('torch.HalfTensor', class extends torch.Tensor {});
  8798. this.registerType('torch.FloatTensor', class extends torch.Tensor {});
  8799. this.registerType('torch.DoubleTensor', class extends torch.Tensor {});
  8800. this.registerType('torch.ComplexFloatTensor', class extends torch.Tensor {});
  8801. this.registerType('torch.ComplexDoubleTensor', class extends torch.Tensor {});
  8802. this.registerType('torch.QInt8Tensor', class extends torch.Tensor {});
  8803. this.registerType('torch.QUInt8Tensor', class extends torch.Tensor {});
  8804. this.registerType('torch.QInt32Tensor', class extends torch.Tensor {});
  8805. this.registerType('torch.BFloat16Tensor', class extends torch.Tensor {});
  8806. this.registerType('torch.cuda._CudaLegacyStorage', class extends torch.storage._LegacyStorage {});
  8807. this.registerType('torch.cuda.FloatStorage', class extends torch.cuda._CudaLegacyStorage {});
  8808. this.registerType('torch.cuda.FloatTensor', class extends torch.Tensor {});
  8809. this.registerType('torch.cuda.DoubleStorage', class extends torch.cuda._CudaLegacyStorage {});
  8810. this.registerType('torch.cuda.DoubleTensor', class extends torch.Tensor {});
  8811. this.registerType('torch.cuda.amp.grad_scaler.GradScaler', class {});
  8812. this.registerFunction('torch.cuda.amp.grad_scaler._refresh_per_optimizer_state');
  8813. this.registerType('torch.SymBool', class {
  8814. constructor(node) {
  8815. this.node = node;
  8816. }
  8817. });
  8818. this.registerType('torch.SymInt', class {
  8819. constructor(node) {
  8820. this.node = node;
  8821. }
  8822. });
  8823. this.register('torch.nn').Module = this.register('torch.nn.modules.module').Module;
  8824. this.register('torch.optim').Adam = this.register('torch.optim.adam').Adam;
  8825. this.register('torch.nn').ReLU = this.register('torch.nn.modules.activation').ReLU;
  8826. this.register('sklearn.utils').Bunch = this.register('sklearn.utils._bunch').Bunch;
  8827. /* eslint-disable no-multi-assign */
  8828. // https://github.com/pytorch/pytorch/blob/main/c10/core/ScalarType.h
  8829. torch.uint8 = torch.ByteStorage.dtype = new torch.dtype(0, 'uint8', 1);
  8830. torch.int8 = torch.CharStorage.dtype = new torch.dtype(1, 'int8', 1);
  8831. torch.int16 = torch.ShortStorage.dtype = new torch.dtype(2, 'int16', 2);
  8832. torch.int32 = torch.IntStorage.dtype = new torch.dtype(3, 'int32', 4);
  8833. torch.int64 = torch.LongStorage.dtype = new torch.dtype(4, 'int64', 8);
  8834. torch.float16 = torch.HalfStorage.dtype = new torch.dtype(5, 'float16', 2);
  8835. torch.float32 = torch.FloatStorage.dtype = new torch.dtype(6, 'float32', 4);
  8836. torch.float64 = torch.DoubleStorage.dtype = new torch.dtype(7, 'float64', 8);
  8837. torch.complex32 = torch.ComplexHalfStorage.dtype = new torch.dtype(8, 'complex32', 4);
  8838. torch.complex64 = torch.ComplexFloatStorage.dtype = new torch.dtype(9, 'complex64', 8);
  8839. torch.complex128 = torch.ComplexDoubleStorage.dtype = new torch.dtype(10, 'complex128', 16);
  8840. torch.bool = torch.BoolStorage.dtype = new torch.dtype(11, 'boolean', 1);
  8841. torch.qint8 = torch.QInt8Storage.dtype = new torch.dtype(12, 'qint8', 1);
  8842. torch.quint8 = torch.QUInt8Storage.dtype = new torch.dtype(13, 'quint8', 1);
  8843. torch.qint32 = torch.QInt32Storage.dtype = new torch.dtype(14, 'qint32', 4);
  8844. torch.bfloat16 = torch.BFloat16Storage.dtype = new torch.dtype(15, 'bfloat16', 2);
  8845. torch.quint4x2 = new torch.dtype(16, 'quint4x2');
  8846. torch.quint2x4 = new torch.dtype(17, 'quint2x4');
  8847. torch.bits1x8 = new torch.dtype(18, 'bits1x8');
  8848. torch.bits2x4 = new torch.dtype(19, 'bits2x4');
  8849. torch.bits2x4 = new torch.dtype(20, 'bits2x4');
  8850. torch.bits8 = new torch.dtype(21, 'bits8');
  8851. torch.bits16 = new torch.dtype(22, 'bits16');
  8852. torch.float8_e5m2 = new torch.dtype(23, 'float8_e5m2', 1);
  8853. torch.float8_e5m2fnuz = new torch.dtype(24, 'float8_e5m2fnuz', 1);
  8854. torch.float8_e4m3fn = new torch.dtype(25, 'float8_e4m3fn', 1);
  8855. torch.float8_e4m3fnuz = new torch.dtype(26, 'float8_e4m3fnuz', 1);
  8856. torch.uint16 = new torch.dtype(27, 'uint16', 2);
  8857. torch.uint32 = new torch.dtype(28, 'uint32', 4);
  8858. torch.uint64 = new torch.dtype(29, 'uint64', 8);
  8859. torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE = Object.fromEntries([
  8860. ['uint8', 'BYTE'],
  8861. ['int8', 'CHAR'], ['int16', 'SHORT'], ['int32', 'INT'], ['int64', 'LONG'],
  8862. ['float16', 'HALF'], ['float32', 'FLOAT'], ['float64', 'DOUBLE'],
  8863. ['complex32', 'COMPLEXHALF'], ['complex64', 'COMPLEXFLOAT'], ['complex128', 'COMPLEXDOUBLE'],
  8864. ['bool', 'BOOL'],
  8865. ['bfloat16', 'BFLOAT16']
  8866. ].map(([key, value]) => [torch._export.serde.schema.ScalarType[value], torch[key]]));
  8867. torch.contiguous_format = new torch.memory_format('contiguous_format');
  8868. torch.channels_last = new torch.memory_format('channels_last');
  8869. torch.channels_last_3d = new torch.memory_format('channels_last_3d');
  8870. torch.preserve_format = new torch.memory_format('preserve_format');
  8871. torch._export.serde.serialize._SERIALIZE_TO_TORCH_MEMORY_FORMAT = Object.fromEntries([
  8872. ['contiguous_format', 'ContiguousFormat'],
  8873. ['channels_last', 'ChannelsLast'],
  8874. ['channels_last_3d', 'ChannelsLast3d'],
  8875. ['preserve_format', 'PreserveFormat']
  8876. ].map(([key, value]) => [torch._export.serde.schema.MemoryFormat[value], torch[key]]));
  8877. /* eslint-enable no-multi-assign */
  8878. torch.strided = new torch.layout('strided');
  8879. torch.sparse_coo = new torch.layout('sparse_coo');
  8880. torch.sparse_csr = new torch.layout('sparse_csr');
  8881. torch.sparse_csc = new torch.layout('sparse_csc');
  8882. torch.sparse_bsr = new torch.layout('sparse_bsr');
  8883. torch.sparse_bsc = new torch.layout('sparse_bsc');
  8884. torch._mkldnn = new torch.layout('_mkldnn');
  8885. torch._export.serde.serialize._SERIALIZE_TO_TORCH_LAYOUT = Object.fromEntries([
  8886. ['sparse_coo', 'SparseCoo'],
  8887. ['sparse_csr', 'SparseCsr'],
  8888. ['sparse_csc', 'SparseCsc'],
  8889. ['sparse_bsr', 'SparseBsr'],
  8890. ['sparse_bsc', 'SparseBsc'],
  8891. ['_mkldnn', '_mkldnn'],
  8892. ['strided', 'Strided'],
  8893. ].map(([key, value]) => [torch._export.serde.schema.Layout[value], torch[key]]));
  8894. torch.per_tensor_affine = new torch.qscheme('torch.per_tensor_affine');
  8895. torch.per_channel_affine = new torch.qscheme('torch.per_channel_affine');
  8896. torch.per_tensor_symmetric = new torch.qscheme('torch.per_tensor_symmetric');
  8897. torch.per_channel_symmetric = new torch.qscheme('torch.per_channel_symmetric');
  8898. torch.per_channel_affine_float_qparams = new torch.qscheme('torch.per_channel_affine_float_qparams');
  8899. torch.inf = this.register('math').inf;
  8900. this.registerFunction('fastcore.basics._using_attr');
  8901. this.registerFunction('fastcore.imports.noop');
  8902. this.registerType('fastcore.basics.fastuple', class {});
  8903. this.registerType('fastcore.basics.GetAttr', class {});
  8904. this.registerType('fastcore.dispatch._TypeDict', class {});
  8905. this.registerType('fastcore.dispatch.TypeDispatch', class {});
  8906. this.registerType('fastcore.foundation.L', class {});
  8907. this.registerType('fastcore.transform.Pipeline', class extends builtins.object {});
  8908. this.registerType('fastcore.transform.Transform', class extends builtins.object {});
  8909. this.registerType('fastcore.transform.DisplayedTransform', class extends fastcore.transform.Transform {});
  8910. this.registerType('fastcore.transform.ItemTransform', class extends fastcore.transform.Transform {});
  8911. this.registerType('fastai.basic_train.Learner', class {});
  8912. this.registerType('fastai.basic_train.Recorder', class {});
  8913. this.registerFunction('fastai.torch_core._fa_rebuild_tensor', (cls, ...args) => {
  8914. const tensor = self.invoke('torch._utils._rebuild_tensor_v2', args);
  8915. return self.invoke(cls, tensor);
  8916. });
  8917. this.registerFunction('fastai.torch_core.trainable_params');
  8918. this.registerFunction('fastai.torch_core._rebuild_from_type', (func, type, args, dict) => {
  8919. const tensor = self.invoke(type, [func(...args)]);
  8920. Object.assign(tensor, dict);
  8921. return tensor;
  8922. });
  8923. this.registerType('fastai.torch_core.Module', class extends torch.nn.modules.module.Module {});
  8924. this.registerType('fastai.torch_core.TensorBase', class extends torch.Tensor {
  8925. constructor(x) {
  8926. super();
  8927. Object.assign(this, x);
  8928. }
  8929. });
  8930. this.registerType('fastai.torch_core.TensorCategory', class extends fastai.torch_core.TensorBase {});
  8931. this.registerType('fastai.torch_core.TensorImageBase', class extends fastai.torch_core.TensorBase {});
  8932. this.registerType('fastai.torch_core.TensorImage', class extends fastai.torch_core.TensorImageBase {});
  8933. this.registerType('fastai.torch_core.TensorMask', class extends fastai.torch_core.TensorImageBase {});
  8934. this.registerType('fastai.torch_core.TensorMultiCategory', class extends fastai.torch_core.TensorCategory {});
  8935. this.registerFunction('fastai.torch_core.uniform');
  8936. this.registerType('fastai.callback.core.Callback', class extends fastcore.basics.GetAttr {});
  8937. this.registerType('fastai.callback.core.TrainEvalCallback', class extends fastai.callback.core.Callback {});
  8938. this.registerType('fastai.callback.fp16.AMPMode', class extends this._enum.Enum {});
  8939. this.registerType('fastai.callback.fp16.MixedPrecision', class {});
  8940. this.registerFunction('fastai.callback.hook._hook_inner');
  8941. this.registerType('fastai.callback.hook.Hook', class extends builtins.object {});
  8942. this.registerType('fastai.callback.hook.Hooks', class extends builtins.object {});
  8943. this.registerType('fastai.callback.mixup.MixHandler', class extends fastai.callback.core.Callback {});
  8944. this.registerType('fastai.callback.mixup.CutMix', class extends fastai.callback.mixup.MixHandler {});
  8945. this.registerType('fastai.callback.progress.ProgressCallback', class {});
  8946. this.registerType('fastai.callback.progress.ShowGraphCallback', class {});
  8947. this.registerType('fastai.callback.tracker.EarlyStoppingCallback', class {});
  8948. this.registerType('fastai.callback.tracker.TrackerCallback', class {});
  8949. this.registerType('fastai.callback.tracker.SaveModelCallback', class extends fastai.callback.tracker.TrackerCallback {});
  8950. this.registerType('fastai.data.core.DataLoaders', class extends fastcore.basics.GetAttr {});
  8951. this.registerType('fastai.data.core.Datasets', class {});
  8952. this.registerType('fastai.data.load.DataLoader', class extends fastcore.basics.GetAttr {});
  8953. this.registerType('fastai.data.core.FilteredBase', class {});
  8954. this.registerType('fastai.data.core.TfmdDL', class extends fastai.data.load.DataLoader {});
  8955. this.registerType('fastai.data.core.TfmdLists', class {});
  8956. this.registerType('fastai.data.load._FakeLoader', class {});
  8957. this.registerFunction('fastai.data.load._wif');
  8958. this.registerType('fastai.data.transforms.Categorize', class {});
  8959. this.registerType('fastai.data.transforms.Category', class {});
  8960. this.registerType('fastai.data.transforms.CategoryMap', class {});
  8961. this.registerType('fastai.data.transforms.ColReader', class {});
  8962. this.registerType('fastai.data.transforms.IntToFloatTensor', class {});
  8963. this.registerType('fastai.data.transforms.MultiCategorize', class {});
  8964. this.registerType('fastai.data.transforms.Normalize', class {});
  8965. this.registerType('fastai.data.transforms.parent_label', class {});
  8966. this.registerType('fastai.data.transforms.OneHotEncode', class {});
  8967. this.registerType('fastai.data.transforms.RegressionSetup', class {});
  8968. this.registerType('fastai.data.transforms.ToTensor', class {});
  8969. this.registerType('fastai.data_block.CategoryList', class {});
  8970. this.registerType('fastai.data_block.CategoryProcessor', class {});
  8971. this.registerType('fastai.imports.noop', class {});
  8972. this.registerType('fastai.layers.AdaptiveConcatPool2d', class {});
  8973. this.registerType('fastai.layers.ConvLayer', class {});
  8974. this.registerType('fastai.layers.Embedding', class {});
  8975. this.registerType('fastai.layers.Flatten', class {});
  8976. this.registerType('fastai.layers.FlattenedLoss', class {});
  8977. this.registerType('fastai.layers.LinBnDrop', class {});
  8978. this.registerType('fastai.layers.MergeLayer', class {});
  8979. this.registerType('fastai.layers.PixelShuffle_ICNR', class {});
  8980. this.registerType('fastai.layers.ResBlock', class {});
  8981. this.registerType('fastai.layers.SelfAttention', class {});
  8982. this.registerType('fastai.layers.SigmoidRange', class {});
  8983. this.registerType('fastai.layers.TimeDistributed', class {});
  8984. this.registerType('fastai.layers.ToTensorBase', class {});
  8985. this.registerType('fastai.learner._ConstantFunc', class {});
  8986. this.registerType('fastai.learner.Metric', class {});
  8987. this.registerType('fastai.learner.AvgLoss', class extends fastai.learner.Metric {});
  8988. this.registerType('fastai.learner.AvgMetric', class extends fastai.learner.Metric {});
  8989. this.registerType('fastai.learner.AvgSmoothLoss', class extends fastai.learner.Metric {});
  8990. this.registerType('fastai.learner.CastToTensor', class extends fastai.callback.core.Callback {});
  8991. this.registerType('fastai.learner.Dice', class extends fastai.learner.Metric {});
  8992. this.registerType('fastai.learner.Learner', class extends fastcore.basics.GetAttr {});
  8993. this.registerType('fastai.learner.Recorder', class {});
  8994. this.registerType('fastai.losses.BaseLoss', class {});
  8995. this.registerType('fastai.losses.BCEWithLogitsLossFlat', class {});
  8996. this.registerType('fastai.losses.CrossEntropyLossFlat', class extends fastai.losses.BaseLoss {});
  8997. this.registerType('fastai.losses.FocalLoss', class extends fastai.torch_core.Module {});
  8998. this.registerType('fastai.losses.FocalLossFlat', class extends fastai.losses.BaseLoss {});
  8999. this.registerType('fastai.losses.LabelSmoothingCrossEntropy', class extends fastai.torch_core.Module {});
  9000. this.registerType('fastai.metrics.AccumMetric', class extends fastai.learner.Metric {});
  9001. this.registerType('fastai.metrics.Dice', class {});
  9002. this.registerType('fastai.metrics.JaccardCoeff', class {});
  9003. this.registerFunction('fastai.metrics._rmse');
  9004. this.registerFunction('fastai.metrics.accuracy');
  9005. this.registerFunction('fastai.metrics.accuracy_multi');
  9006. this.registerFunction('fastai.metrics.foreground_acc');
  9007. this.registerFunction('fastai.metrics.mse');
  9008. this.registerFunction('fastai.metrics.error_rate');
  9009. this.registerType('fastai.optimizer._BaseOptimizer', class {});
  9010. this.registerType('fastai.optimizer.Optimizer', class extends fastai.optimizer._BaseOptimizer {});
  9011. this.registerFunction('fastai.optimizer.Adam');
  9012. this.registerFunction('fastai.optimizer.adam_step');
  9013. this.registerFunction('fastai.optimizer.average_grad');
  9014. this.registerFunction('fastai.optimizer.average_sqr_grad');
  9015. this.registerFunction('fastai.optimizer.RAdam');
  9016. this.registerFunction('fastai.optimizer.step_stat');
  9017. this.registerFunction('fastai.optimizer.weight_decay');
  9018. this.registerType('fastai.tabular.core.Categorify', class {});
  9019. this.registerType('fastai.tabular.core.FillMissing', class {});
  9020. this.registerType('fastai.tabular.core.FillStrategy', class {});
  9021. this.registerType('fastai.tabular.core.ReadTabBatch', class extends fastcore.transform.ItemTransform {});
  9022. this.registerType('fastai.tabular.core.TabDataLoader', class extends fastai.data.core.TfmdDL {});
  9023. this.registerType('fastai.tabular.data.TabularDataLoaders', class extends fastai.data.core.DataLoaders {});
  9024. this.registerType('fastai.tabular.core.Tabular', class {});
  9025. this.registerType('fastai.tabular.core.TabularPandas', class extends fastai.tabular.core.Tabular {});
  9026. this.registerType('fastai.tabular.core.TabWeightedDL', class {});
  9027. this.registerType('fastai.tabular.learner.TabularLearner', class extends fastai.learner.Learner {});
  9028. this.registerType('fastai.tabular.model.TabularModel', class {});
  9029. this.registerFunction('fastai.vision.augment.aug_transforms');
  9030. this.registerFunction('fastai.vision.augment.dihedral_mat');
  9031. this.registerType('fastai.vision.augment._BrightnessLogit', class {});
  9032. this.registerType('fastai.vision.augment._ContrastLogit', class {});
  9033. this.registerType('fastai.vision.augment._WarpCoord', class {});
  9034. this.registerType('fastai.vision.augment.RandTransform', class extends fastcore.transform.DisplayedTransform {});
  9035. this.registerType('fastai.vision.augment.AffineCoordTfm', class extends fastai.vision.augment.RandTransform {});
  9036. this.registerType('fastai.vision.augment.Brightness', class {});
  9037. this.registerType('fastai.vision.augment.flip_mat', class {});
  9038. this.registerType('fastai.vision.augment.Flip', class {});
  9039. this.registerType('fastai.vision.augment.RandomResizedCropGPU', class {});
  9040. this.registerType('fastai.vision.augment.Resize', class {});
  9041. this.registerType('fastai.vision.augment.rotate_mat', class {});
  9042. this.registerFunction('fastai.vision.augment.TensorImage.lighting');
  9043. this.registerType('fastai.vision.augment.Warp', class extends fastai.vision.augment.AffineCoordTfm {});
  9044. this.registerType('fastai.vision.augment.zoom_mat', class {});
  9045. this.registerType('fastai.vision.core.PILImage', class {});
  9046. this.registerType('fastai.vision.core.PILMask', class {});
  9047. this.registerType('fastai.vision.core.AddMaskCodes', class {});
  9048. this.registerType('fastai.vision.data.ImageList', class {});
  9049. this.registerType('fastai.vision.image.Image', class {});
  9050. this.registerType('fastai.vision.image.RandTransform', class {});
  9051. this.registerType('fastai.vision.image.TfmCrop', class {});
  9052. this.registerFunction('fastai.vision.learner._resnet_split');
  9053. this.registerFunction('fastai.vision.learner.default_split');
  9054. this.registerFunction('fastai.vision.learner.default_split');
  9055. this.registerType('fastai.vision.learner.TimmBody', class {});
  9056. this.registerType('fastai.vision.models.unet.DynamicUnet', class {});
  9057. this.registerType('fastai.vision.models.unet.ResizeToOrig', class {});
  9058. this.registerType('fastai.vision.models.unet.UnetBlock', class {});
  9059. this.registerFunction('fastai.vision.transform._crop_pad');
  9060. }
  9061. get builtins() {
  9062. return this._builtins;
  9063. }
  9064. source(file) {
  9065. return this._sources.has(file) ? this._sources.get(file) : null;
  9066. }
  9067. debug(/* file */) {
  9068. }
  9069. exec(code , context) {
  9070. const reader = new python.Parser(code, '', null);
  9071. const program = reader.parse();
  9072. if (!program) {
  9073. throw new python.Error("Module '?' parse error.");
  9074. }
  9075. this.block(program.body, context);
  9076. }
  9077. parse(file) {
  9078. const buffer = this.source(file);
  9079. if (buffer) {
  9080. const debug = this.debug(file);
  9081. const code = this._utf8Decoder.decode(buffer);
  9082. const parser = new python.Parser(code, file, debug);
  9083. const program = parser.parse();
  9084. if (!program) {
  9085. throw new python.Error(`Module '${file}' parse error.`);
  9086. }
  9087. return program;
  9088. }
  9089. return null;
  9090. }
  9091. import(name, current, level) {
  9092. if (level) {
  9093. let bits = current.split('.');
  9094. if (bits.length < level) {
  9095. throw new python.Error('Invalid relative import beyond top-level package.');
  9096. }
  9097. bits = bits.slice(0, bits.length - level);
  9098. const base = bits.join('.');
  9099. name = name ? [base, name].join('.') : base;
  9100. }
  9101. const index = name.lastIndexOf('.');
  9102. let parent = null;
  9103. let child = null;
  9104. if (index > 0) {
  9105. parent = name.substring(0, index);
  9106. child = name.substring(index + 1);
  9107. this.import(parent);
  9108. }
  9109. if (!this._modules.has(name)) {
  9110. const module = this._registry.get(name) || new this._builtins.module(name);
  9111. module.__package__ = name;
  9112. this._modules.set(name, module);
  9113. const path = name.split('.').join('/');
  9114. module.__path__ = [path];
  9115. const file = `${path}.py`;
  9116. const program = this.parse(file);
  9117. if (program) {
  9118. module.__file__ = file;
  9119. for (const [name, value] of Object.entries(this.builtins)) {
  9120. switch (name) {
  9121. case '__class__':
  9122. case '__package__':
  9123. case '__module__':
  9124. case '__name__':
  9125. case '__path__':
  9126. case '__file__':
  9127. break;
  9128. default:
  9129. module[name] = value;
  9130. break;
  9131. }
  9132. }
  9133. const context = new python.Execution.Context(module, null);
  9134. if (name !== 'builtins') {
  9135. context.set('__builtins__', this._modules.get('builtins'));
  9136. }
  9137. this.block(program.body, context);
  9138. }
  9139. if (parent) {
  9140. const parent_module = this._modules.get(parent);
  9141. parent_module[child] = module;
  9142. }
  9143. }
  9144. return this._modules.get(name);
  9145. }
  9146. __import__(name, globals, locals, fromlist, level) {
  9147. let module = null;
  9148. level = level || 0;
  9149. if (level === 0) {
  9150. module = this.import(name);
  9151. } else {
  9152. globals = globals || {};
  9153. let current = globals.__package__;
  9154. if (!current) {
  9155. const spec = globals.__spec__;
  9156. if (spec) {
  9157. current = spec.parent;
  9158. } else {
  9159. const name = globals.__name__;
  9160. const bits = name.split('.');
  9161. bits.pop();
  9162. current = bits.join('.');
  9163. }
  9164. }
  9165. module = this.import(name, current, level);
  9166. }
  9167. if (!fromlist) {
  9168. if (level === 0) {
  9169. return this.import(name.split('.')[0]);
  9170. } else if (name) {
  9171. throw new python.Error(`Unsupported relative import '${name}'.`);
  9172. // cut_off = len(name) - len(name.partition('.')[0])
  9173. // return sys.modules[module.__name__[:len(module.__name__)-cut_off]]
  9174. }
  9175. } else if (module.__path__) {
  9176. const handle_fromlist = (module, fromlist, recursive) => {
  9177. for (const name of fromlist) {
  9178. if (name === '*') {
  9179. if (!recursive && module.__all__) {
  9180. handle_fromlist(module, module.__all__, true);
  9181. }
  9182. } else if (!module[name]) {
  9183. this.import(`${module.__name__}.${name}`);
  9184. }
  9185. }
  9186. return module;
  9187. };
  9188. handle_fromlist(module, fromlist);
  9189. }
  9190. return module;
  9191. }
  9192. module(name) {
  9193. return this._modules.get(name);
  9194. }
  9195. resolve(name) {
  9196. const index = name.lastIndexOf('.');
  9197. const memberName = index === -1 ? name : name.substring(index + 1, name.length);
  9198. const moduleName = index === -1 ? '' : name.substring(0, index);
  9199. const module = this.import(moduleName);
  9200. let type = module ? module[memberName] : null;
  9201. if (!type) {
  9202. if (!this._unresolved.has(name)) {
  9203. const moduleName = name.split('.').shift();
  9204. if (this._registry.has(moduleName) && moduleName !== '__main__') {
  9205. this.emit('resolve', name);
  9206. }
  9207. const type = this._createType(name, class {});
  9208. this._unresolved.set(name, type);
  9209. }
  9210. type = this._unresolved.get(name);
  9211. }
  9212. return type;
  9213. }
  9214. invoke(target, args) {
  9215. if (typeof target === 'string') {
  9216. target = this.resolve(target);
  9217. }
  9218. if (target) {
  9219. if (target.__class__ === this._builtins.type) {
  9220. if (target.prototype && target.prototype.__class__ === target) {
  9221. return Reflect.construct(target, args);
  9222. }
  9223. const obj = Object.create(target);
  9224. if (obj.__init__ && typeof obj.__init__ === 'function') {
  9225. obj.__init__(...args);
  9226. }
  9227. return obj;
  9228. } else if (target.__class__ === this._builtins.function) {
  9229. if (target.__call__) {
  9230. return target.__call__(args);
  9231. }
  9232. return target(...args);
  9233. }
  9234. }
  9235. throw new python.Error('Unsupported invoke target.');
  9236. }
  9237. call(target, name, args, context) {
  9238. const callTarget = this.target(target, context);
  9239. const callArguments = args.map((argument) => this.expression(argument, context));
  9240. if (!callTarget || (name !== null && !callTarget[name])) {
  9241. if (name === '__new__' && callArguments.length === 1 && callArguments[0] === callTarget) {
  9242. name = null;
  9243. callArguments.shift();
  9244. } else {
  9245. const format = (expression) => {
  9246. if (expression.type === 'id') {
  9247. return expression.value;
  9248. }
  9249. if (expression.type === '.') {
  9250. return `${format(expression.target)}.${format(expression.member)}`;
  9251. }
  9252. return null;
  9253. };
  9254. const targetName = `${format(target)}.${name}`;
  9255. throw new python.Error(`Unknown function '${targetName}'.`);
  9256. }
  9257. }
  9258. const func = name ? callTarget[name] : callTarget;
  9259. if (func.__class__ === this._builtins.type) {
  9260. if (func.prototype && func.prototype.__class__ === func) {
  9261. return Reflect.construct(func, callArguments);
  9262. }
  9263. const obj = Object.create(func);
  9264. obj.__class__ = func;
  9265. if (obj.__init__ && typeof obj.__init__ === 'function') {
  9266. obj.__init__(...args);
  9267. }
  9268. return obj;
  9269. }
  9270. if (func.__class__ === this._builtins.function) {
  9271. if (func.__call__) {
  9272. return func.__call__(callArguments);
  9273. }
  9274. }
  9275. if (func.__class__ === this._builtins.method) {
  9276. if (func.__call__) {
  9277. return func.__call__([callTarget].concat(callArguments));
  9278. }
  9279. }
  9280. if (typeof func === 'function') {
  9281. return func.apply(callTarget, callArguments);
  9282. }
  9283. throw new python.Error("Unsupported call expression.");
  9284. }
  9285. apply(method, args, context) {
  9286. const locals = Array.prototype.slice.call(args);
  9287. context = new python.Execution.Context(context.globals, {});
  9288. for (const argument of method.args) {
  9289. let value = locals.shift();
  9290. if (value === undefined && argument.initializer) {
  9291. value = this.expression(argument.initializer, context);
  9292. }
  9293. context.set(argument.name, value);
  9294. }
  9295. return this.block(method.body.statements, context);
  9296. }
  9297. block(statements, context) {
  9298. statements = Array.prototype.slice.call(statements);
  9299. while (statements.length > 0) {
  9300. const statement = statements.shift();
  9301. const value = this.statement(statement, context);
  9302. if (value !== undefined) {
  9303. return value;
  9304. }
  9305. }
  9306. return undefined;
  9307. }
  9308. statement(statement, context) {
  9309. switch (statement.type) {
  9310. case 'pass': {
  9311. break;
  9312. }
  9313. case 'return': {
  9314. return this.expression(statement.expression, context);
  9315. }
  9316. case 'def': {
  9317. const module = context.get('__name__');
  9318. const self = this;
  9319. const parent = context.get('__class__');
  9320. const type = (parent === this._builtins.module) ? this._builtins.function : this._builtins.method;
  9321. const func = {
  9322. __class__: type,
  9323. __globals__: context,
  9324. __module__: module,
  9325. __name__: statement.name,
  9326. __code__: statement,
  9327. __call__(args) {
  9328. return self.apply(this.__code__, args, this.__globals__);
  9329. }
  9330. };
  9331. context.set(statement.name, func);
  9332. break;
  9333. }
  9334. case 'class': {
  9335. const bases = statement.bases.map((arg) => this.expression(arg, context));
  9336. if (bases.length > 1) {
  9337. throw new python.Error(`Unsupported multiple bases for class '${statement.name}'.`);
  9338. }
  9339. const base = bases.length === 1 ? bases[0] : null;
  9340. const name = `${context.get('__name__')}.${statement.name}`;
  9341. const value = this._createType(name, base ? class extends base {} : class {});
  9342. value.__bases__ = bases;
  9343. context.set(statement.name, value);
  9344. this.block(statement.body.statements, new python.Execution.Context(context.globals, value.prototype));
  9345. break;
  9346. }
  9347. case 'var': {
  9348. context.set(statement.name, statement.initializer ? this.expression(statement.initializer, context) : undefined);
  9349. break;
  9350. }
  9351. case '=': {
  9352. this.expression(statement, context);
  9353. break;
  9354. }
  9355. case 'if': {
  9356. const test = this.expression(statement.test, context);
  9357. if (test === true || test) {
  9358. const value = this.block(statement.body.statements, context);
  9359. if (value !== undefined) {
  9360. return value;
  9361. }
  9362. break;
  9363. } else if (test === false) {
  9364. if (statement.orelse) {
  9365. const value = this.block(statement.orelse.statements, context);
  9366. if (value !== undefined) {
  9367. return value;
  9368. }
  9369. }
  9370. break;
  9371. }
  9372. throw new python.Error("Unsupported condition.");
  9373. }
  9374. case 'for': {
  9375. if (statement.iter.length === 1 &&
  9376. statement.target.length === 1 && statement.target[0].type === 'id') {
  9377. const range = this.expression(statement.iter[0], context);
  9378. const [variable] = statement.target;
  9379. for (const current of range) {
  9380. this.statement({ type: '=', target: variable, expression: { type: 'number', value: current } }, context);
  9381. const value = this.block(statement.body.statements, context);
  9382. if (value !== undefined) {
  9383. return value;
  9384. }
  9385. }
  9386. break;
  9387. }
  9388. throw new python.Error("Unsupported 'for' statement.");
  9389. }
  9390. case 'while': {
  9391. const test = this.expression(statement.test, context);
  9392. if (test) {
  9393. const value = this.block(statement.body.statements, context);
  9394. if (value !== undefined) {
  9395. return value;
  9396. }
  9397. }
  9398. break;
  9399. }
  9400. case 'with': {
  9401. const items = [];
  9402. for (const item of statement.item) {
  9403. items.push(this.expression(item.expression, context));
  9404. }
  9405. for (const item of items) {
  9406. if (item.__enter__ && item.__enter__.__call__) {
  9407. item.__enter__.__call__([item]);
  9408. }
  9409. }
  9410. const value = this.block(statement.body.statements, context);
  9411. for (const item of items) {
  9412. if (item.__exit__ && item.__exit__.__call__) {
  9413. item.__exit__.__call__([item]);
  9414. }
  9415. }
  9416. if (value !== undefined) {
  9417. return value;
  9418. }
  9419. break;
  9420. }
  9421. case 'call': {
  9422. this.expression(statement, context);
  9423. break;
  9424. }
  9425. case 'import': {
  9426. for (const alias of statement.names) {
  9427. let module = this.__import__(alias.name, context);
  9428. if (alias.asname) {
  9429. const bits = alias.name.split('.').reverse();
  9430. bits.pop();
  9431. while (bits.length > 0) {
  9432. module = module[bits.pop()];
  9433. }
  9434. context.set(alias.asname, module);
  9435. } else {
  9436. context.set(alias.name.split('.')[0], module);
  9437. }
  9438. }
  9439. break;
  9440. }
  9441. case 'import_from': {
  9442. const fromlist = statement.names.map((name) => name.name);
  9443. const module = this.__import__(statement.module, context.globals, context.locals, fromlist, statement.level);
  9444. for (const entry of statement.names) {
  9445. const name = entry.name;
  9446. const asname = entry.asname ? entry.asname : null;
  9447. if (!module[name]) {
  9448. throw new python.Error(`Cannot import '${name}' from '${statement.module}'.`);
  9449. }
  9450. context.set(asname ? asname : name, module[name]);
  9451. }
  9452. break;
  9453. }
  9454. case 'string': {
  9455. break;
  9456. }
  9457. default: {
  9458. throw new python.Error(`Unsupported statement '${statement.type}'.`);
  9459. }
  9460. }
  9461. return undefined;
  9462. }
  9463. expression(expression, context) {
  9464. const self = context.get('self');
  9465. switch (expression.type) {
  9466. case '=': {
  9467. const target = expression.target;
  9468. if (target.type === 'id') {
  9469. context.set(target.value, this.expression(expression.expression, context));
  9470. return undefined;
  9471. } else if (target.type === '[]') {
  9472. if (target.target.type === 'id' &&
  9473. target.arguments.type === 'list' &&
  9474. target.arguments.value.length === 1) {
  9475. const index = this.expression(target.arguments.value[0], context);
  9476. if (target.target.value === '__annotations__') {
  9477. context.set(target.target.value, context.get(target.target.value) || {});
  9478. }
  9479. const obj = context.get(target.target.value);
  9480. const value = this.expression(expression.expression, context);
  9481. if (obj instanceof Map) {
  9482. obj.set(index, value);
  9483. } else {
  9484. obj[index] = value;
  9485. }
  9486. return undefined;
  9487. }
  9488. } else if (target.type === '.' &&
  9489. target.member.type === 'id') {
  9490. this.expression(target.target, context)[target.member.value] = this.expression(expression.expression, context);
  9491. return undefined;
  9492. } else if (target.type === 'tuple') {
  9493. context.target.push(target.value);
  9494. const value = this.expression(expression.expression, context);
  9495. context.target.pop();
  9496. if (target.value.every((item) => item.type === 'id')) {
  9497. if (target.value.length < value.length) {
  9498. throw new python.Error(`ValueError: too many values to unpack (expected ${target.value.length}, actual ${value.length}).`);
  9499. }
  9500. if (target.value.length > value.length) {
  9501. throw new python.Error(`ValueError: not enough values to unpack (expected ${target.value.length}, actual ${value.length}).`);
  9502. }
  9503. for (let i = 0; i < value.length; i++) {
  9504. context.set(target.value[i].value, value[i]);
  9505. }
  9506. return undefined;
  9507. }
  9508. }
  9509. break;
  9510. }
  9511. case 'list': {
  9512. return expression.value.map((item) => this.expression(item, context));
  9513. }
  9514. case 'string': {
  9515. return expression.value.substring(1, expression.value.length - 1);
  9516. }
  9517. case 'number': {
  9518. return Number(expression.value);
  9519. }
  9520. case '[]': {
  9521. if (expression.target.type === 'id' &&
  9522. expression.arguments.type === 'list' &&
  9523. expression.arguments.value.length === 1) {
  9524. if (context.get(expression.target.value)) {
  9525. const index = this.expression(expression.arguments.value[0], context);
  9526. const target = context.get(expression.target.value);
  9527. if (target instanceof Map) {
  9528. return target.get(index);
  9529. }
  9530. return target[index < 0 ? target.length + index : index];
  9531. }
  9532. }
  9533. const target = this.expression(expression.target, context);
  9534. if (target && expression.arguments.type === 'list' &&
  9535. (target.__class__ === this._typing._TupleType ||
  9536. target.__class__ === this._typing._SpecialGenericAlias ||
  9537. target.__class__ === this._typing._SpecialForm)) {
  9538. const type = { ...target };
  9539. type.__args__ = expression.arguments.value.map((arg) => this.expression(arg, context));
  9540. return type;
  9541. }
  9542. if (expression.arguments.type === 'list' && expression.arguments.value.length === 1) {
  9543. const index = this.expression(expression.arguments.value[0], context);
  9544. if (target instanceof Map) {
  9545. return target.get(index);
  9546. }
  9547. return target[index < 0 ? target.length + index : index];
  9548. }
  9549. break;
  9550. }
  9551. case '.': {
  9552. if (expression.member.type === 'id') {
  9553. const target = this.target(expression.target, context);
  9554. return target[expression.member.value];
  9555. }
  9556. throw new python.Error("Unsupported field expression.");
  9557. }
  9558. case 'call': {
  9559. if (expression.target.type === '.') {
  9560. return this.call(expression.target.target, expression.target.member.value, expression.args, context);
  9561. }
  9562. return this.call(expression.target, null, expression.args, context);
  9563. }
  9564. case 'id': {
  9565. switch (expression.value) {
  9566. case 'self': return self;
  9567. case 'None': return null;
  9568. case 'True': return true;
  9569. case 'False': return false;
  9570. default: {
  9571. const type = (value) => {
  9572. return value &&
  9573. (value.__class__ === this._builtins.type ||
  9574. value.__class__ === this._typing._TupleType ||
  9575. value.__class__ === this._typing._SpecialGenericAlias ||
  9576. value.__class__ === this._typing._SpecialForm);
  9577. };
  9578. const builtin = this._builtins[expression.value];
  9579. if (type(builtin)) {
  9580. return builtin;
  9581. }
  9582. const value = context.get(expression.value);
  9583. if (value === undefined) {
  9584. const typing = this._typing[expression.value];
  9585. if (type(typing)) {
  9586. return typing;
  9587. }
  9588. }
  9589. return value;
  9590. }
  9591. }
  9592. }
  9593. case 'tuple': {
  9594. return expression.value.map((expression) => this.expression(expression, context));
  9595. }
  9596. case 'dict': {
  9597. const dict = {};
  9598. for (const pair of expression.value) {
  9599. if (pair.type !== 'pair') {
  9600. throw new python.Error(`Unsupported dict item type '${pair.type}'.`);
  9601. }
  9602. const key = this.expression(pair.key, context);
  9603. const value = this.expression(pair.value, context);
  9604. dict[key] = value;
  9605. }
  9606. return dict;
  9607. }
  9608. case 'unary': {
  9609. switch (expression.op) {
  9610. case '-': {
  9611. return -this.expression(expression.operand, context);
  9612. }
  9613. default: {
  9614. throw new python.Error(`Unsupported unary expression '${expression.op}'.`);
  9615. }
  9616. }
  9617. }
  9618. case 'binary': {
  9619. switch (expression.op) {
  9620. case '==': {
  9621. return this.expression(expression.left, context) === this.expression(expression.right, context);
  9622. }
  9623. default: {
  9624. throw new python.Error(`Unsupported binary expression '${expression.op}'.`);
  9625. }
  9626. }
  9627. }
  9628. default: {
  9629. throw new python.Error(`Unsupported expression '${expression.type}'.`);
  9630. }
  9631. }
  9632. return undefined;
  9633. }
  9634. target(expression, context) {
  9635. let current = expression;
  9636. let path = [];
  9637. for (;;) {
  9638. if (current.type === '.' && current.member && current.member.type === 'id') {
  9639. path.push(current.member.value);
  9640. current = current.target;
  9641. } else if (current.type === 'id' && current.value !== 'self' && current.value !== 'CONSTANTS') {
  9642. path.push(current.value);
  9643. break;
  9644. } else {
  9645. path = null;
  9646. break;
  9647. }
  9648. }
  9649. if (path) {
  9650. let target = null;
  9651. for (let i = path.length - 1; i >= 0; i--) {
  9652. target = target ? target[path[i]] : context.get(path[i]);
  9653. if (!target) {
  9654. break;
  9655. }
  9656. }
  9657. if (!target) {
  9658. path.reverse();
  9659. const name = path.join('.');
  9660. const file = `${path.join('/')}.py`;
  9661. if (this._sources.has(file)) {
  9662. target = this.import(name);
  9663. } else {
  9664. target = this.resolve(name);
  9665. }
  9666. }
  9667. return target;
  9668. }
  9669. return this.expression(expression, context);
  9670. }
  9671. add(name, source) {
  9672. this._sources.set(name, source);
  9673. }
  9674. on(event, listener) {
  9675. const value = this._events.get(event) || [];
  9676. value.push(listener);
  9677. this._events.set(event, value);
  9678. }
  9679. emit(event, ...args) {
  9680. if (this._events.has(event)) {
  9681. for (const callback of this._events.get(event)) {
  9682. callback(this, ...args);
  9683. }
  9684. }
  9685. }
  9686. register(name, value) {
  9687. if (!this._registry.has(name)) {
  9688. value = value || new (this._registry.get('builtins').module)(name);
  9689. this._registry.set(name, value);
  9690. let current = name;
  9691. for (;;) {
  9692. const index = current.lastIndexOf('.');
  9693. if (index === -1) {
  9694. break;
  9695. }
  9696. const child = current.substring(index + 1);
  9697. current = current.substring(0, index);
  9698. if (!value.__module__) {
  9699. value.__module__ = current;
  9700. }
  9701. const parent = this.register(current);
  9702. parent[child] = value;
  9703. value = parent;
  9704. }
  9705. }
  9706. return this._registry.get(name);
  9707. }
  9708. registerFunction(name, value) {
  9709. const index = name.lastIndexOf('.');
  9710. if (!value) {
  9711. value = () => {
  9712. throw new python.Error(`'${name}' is not implemented.`);
  9713. };
  9714. }
  9715. value.__class__ = this._builtins.function;
  9716. value.__name__ = index === -1 ? name : name.substring(index + 1);
  9717. value.__module__ = index === -1 ? '' : name.substring(0, index);
  9718. const module = this.register(value.__module__);
  9719. if (module[name]) {
  9720. throw new python.Error(`Function '${name}' is already registered.`);
  9721. }
  9722. module[value.__name__] = value;
  9723. return value;
  9724. }
  9725. _createType(name, value) {
  9726. const index = name.lastIndexOf('.');
  9727. value.__class__ = this._builtins.type;
  9728. value.__name__ = index === -1 ? name : name.substring(index + 1);
  9729. value.__module__ = index === -1 ? '' : name.substring(0, index);
  9730. value.prototype.__class__ = value;
  9731. return value;
  9732. }
  9733. registerType(name, value) {
  9734. value = this._createType(name, value);
  9735. const parts = name.split('.');
  9736. const memberName = parts.pop();
  9737. const moduleName = parts.join('.');
  9738. const module = this.register(moduleName);
  9739. if (module[memberName]) {
  9740. throw new python.Error(`Class '${memberName}' is already registered.`);
  9741. }
  9742. module[memberName] = value;
  9743. return value;
  9744. }
  9745. };
  9746. python.Execution.Context = class {
  9747. constructor(globals, locals) {
  9748. this.globals = globals;
  9749. this.locals = locals;
  9750. }
  9751. set(name, value) {
  9752. if (this.locals) {
  9753. this.locals[name] = value;
  9754. } else {
  9755. this.globals[name] = value;
  9756. }
  9757. }
  9758. get(name) {
  9759. if (this.locals && name in this.locals) {
  9760. return this.locals[name];
  9761. }
  9762. if (name in this.globals) {
  9763. return this.globals[name];
  9764. }
  9765. return undefined;
  9766. }
  9767. get target() {
  9768. this._target = this._target || [];
  9769. return this._target;
  9770. }
  9771. };
  9772. python.BinaryReader = class {
  9773. constructor(buffer) {
  9774. this._buffer = buffer;
  9775. this._length = buffer.length;
  9776. this._position = 0;
  9777. this._view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  9778. this._utf8Decoder = new TextDecoder('utf-8');
  9779. this._asciiDecoder = new TextDecoder('ascii');
  9780. }
  9781. get position() {
  9782. return this._position;
  9783. }
  9784. get length() {
  9785. return this._length;
  9786. }
  9787. seek(position) {
  9788. this._position = position >= 0 ? position : this._length + position;
  9789. if (this._position > this._buffer.length) {
  9790. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  9791. }
  9792. }
  9793. skip(offset) {
  9794. this._position += offset;
  9795. if (this._position > this._buffer.length) {
  9796. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  9797. }
  9798. }
  9799. stream(length) {
  9800. const buffer = this.read(length);
  9801. return new python.BinaryReader(buffer);
  9802. }
  9803. peek(length) {
  9804. const position = this._position;
  9805. length = length === undefined ? this._length - this._position : length;
  9806. this.skip(length);
  9807. const end = this._position;
  9808. this.skip(-length);
  9809. if (position === 0 && length === this._length) {
  9810. return this._buffer;
  9811. }
  9812. return this._buffer.subarray(position, end);
  9813. }
  9814. read(length) {
  9815. const position = this._position;
  9816. length = length === undefined ? this._length - this._position : length;
  9817. this.skip(length);
  9818. if (position === 0 && length === this._length) {
  9819. return this._buffer;
  9820. }
  9821. return this._buffer.subarray(position, this._position);
  9822. }
  9823. byte() {
  9824. const position = this._position;
  9825. this.skip(1);
  9826. return this._view.getUint8(position);
  9827. }
  9828. uint16() {
  9829. const position = this._position;
  9830. this.skip(2);
  9831. return this._view.getUint16(position, true);
  9832. }
  9833. int32() {
  9834. const position = this._position;
  9835. this.skip(4);
  9836. return this._view.getInt32(position, true);
  9837. }
  9838. uint32() {
  9839. const position = this._position;
  9840. this.skip(4);
  9841. return this._view.getUint32(position, true);
  9842. }
  9843. int64() {
  9844. const position = this._position;
  9845. this.skip(8);
  9846. return this._view.getBigInt64(position, true);
  9847. }
  9848. float64() {
  9849. const position = this._position;
  9850. this.skip(8);
  9851. return this._view.getFloat64(position, false);
  9852. }
  9853. string(size, encoding) {
  9854. const data = this.read(size);
  9855. return (encoding === 'utf-8') ?
  9856. this._utf8Decoder.decode(data) :
  9857. this._asciiDecoder.decode(data);
  9858. }
  9859. line() {
  9860. const index = this._buffer.indexOf(0x0A, this._position);
  9861. if (index === -1) {
  9862. throw new python.Error("Could not find end of line.");
  9863. }
  9864. const size = index - this._position;
  9865. const text = this.string(size, 'ascii');
  9866. this.skip(1);
  9867. return text;
  9868. }
  9869. };
  9870. python.StreamReader = class {
  9871. constructor(stream) {
  9872. this._stream = stream;
  9873. this._length = stream.length;
  9874. this._position = 0;
  9875. this._utf8Decoder = new TextDecoder('utf-8');
  9876. this._asciiDecoder = new TextDecoder('ascii');
  9877. }
  9878. get position() {
  9879. return this._position;
  9880. }
  9881. get length() {
  9882. return this._length;
  9883. }
  9884. seek(position) {
  9885. this._stream.seek(position);
  9886. this._position = this._stream.position;
  9887. }
  9888. skip(offset) {
  9889. this._position += offset;
  9890. if (this._position > this._length) {
  9891. throw new python.Error(`Expected ${this._position - this._length} more bytes. The file might be corrupted. Unexpected end of file.`);
  9892. }
  9893. }
  9894. stream(length) {
  9895. this._stream.seek(this._position);
  9896. this.skip(length);
  9897. return this._stream.stream(length);
  9898. }
  9899. peek(length) {
  9900. this._stream.seek(this._position);
  9901. return this._stream.peek(length);
  9902. }
  9903. read(length) {
  9904. this._stream.seek(this._position);
  9905. this.skip(length);
  9906. return this._stream.read(length);
  9907. }
  9908. byte() {
  9909. const position = this._fill(1);
  9910. return this._view.getUint8(position);
  9911. }
  9912. uint16() {
  9913. const position = this._fill(2);
  9914. return this._view.getUint16(position, true);
  9915. }
  9916. int32() {
  9917. const position = this._fill(4);
  9918. return this._view.getInt32(position, true);
  9919. }
  9920. uint32() {
  9921. const position = this._fill(4);
  9922. return this._view.getUint32(position, true);
  9923. }
  9924. int64() {
  9925. const position = this._fill(8);
  9926. return this._view.getBigInt64(position, true);
  9927. }
  9928. float64() {
  9929. const position = this._fill(8);
  9930. return this._view.getFloat64(position, false);
  9931. }
  9932. string(size, encoding) {
  9933. const data = this.read(size);
  9934. return (encoding === 'utf-8') ?
  9935. this._utf8Decoder.decode(data) :
  9936. this._asciiDecoder.decode(data);
  9937. }
  9938. line() {
  9939. let position = this._fill(0);
  9940. let index = this._buffer.indexOf(0x0A, position);
  9941. if (index === -1) {
  9942. const size = Math.min(0x20000000, this._stream.length - this._position);
  9943. this._fill(size);
  9944. this.skip(-size);
  9945. position = this._fill(0);
  9946. index = this._buffer.indexOf(0x0A, position);
  9947. if (index === -1) {
  9948. throw new python.Error("Could not find end of line.");
  9949. }
  9950. }
  9951. const size = index - position;
  9952. const text = this.string(size, 'ascii');
  9953. this.skip(1);
  9954. return text;
  9955. }
  9956. _fill(length) {
  9957. if (this._position + length > this._length) {
  9958. throw new Error(`Expected ${this._position + length - this._length} more bytes. The file might be corrupted. Unexpected end of file.`);
  9959. }
  9960. if (!this._buffer || this._position < this._offset || this._position + length > this._offset + this._buffer.length) {
  9961. this._offset = this._position;
  9962. this._stream.seek(this._offset);
  9963. const size = Math.max(length, Math.min(0x10000000, this._length - this._offset));
  9964. this._buffer = this._stream.read(size);
  9965. this._view = new DataView(this._buffer.buffer, this._buffer.byteOffset, this._buffer.byteLength);
  9966. }
  9967. const position = this._position;
  9968. this._position += length;
  9969. return position - this._offset;
  9970. }
  9971. };
  9972. python.Error = class extends Error {
  9973. constructor(message) {
  9974. super(message);
  9975. this.name = 'Python Error';
  9976. }
  9977. };
  9978. export const Execution = python.Execution;