pytorch.js 199 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526
  1. // Experimental
  2. var pytorch = pytorch || {};
  3. var python = python || require('./python');
  4. var base = base || require('./base');
  5. pytorch.ModelFactory = class {
  6. match(context) {
  7. return pytorch.Container.open(context);
  8. }
  9. open(context, match) {
  10. const identifier = context.identifier;
  11. return pytorch.Metadata.open(context).then((metadata) => {
  12. const container = match;
  13. try {
  14. container.metadata = metadata;
  15. container.exception = (error, fatal) => {
  16. const message = error && error.message ? error.message : error.toString();
  17. context.exception(new pytorch.Error(message.replace(/\.$/, '') + " in '" + identifier + "'."), fatal);
  18. };
  19. }
  20. catch (error) {
  21. const message = error && error.message ? error.message : error.toString();
  22. throw new pytorch.Error('File format is not PyTorch (' + message.replace(/\.$/, '') + ').');
  23. }
  24. return new pytorch.Model(metadata, container);
  25. });
  26. }
  27. };
  28. pytorch.Model = class {
  29. constructor(metadata, container) {
  30. this._format = container.format;
  31. this._producer = container.producer || '';
  32. this._graphs = [];
  33. const type = container.type;
  34. switch (type) {
  35. case 'script':
  36. this._graphs.push(new pytorch.Graph(metadata, type, container.data, container));
  37. break;
  38. case 'module':
  39. case 'weights':
  40. for (const data of container.data) {
  41. this._graphs.push(new pytorch.Graph(metadata, type, data, container));
  42. }
  43. break;
  44. default:
  45. throw new pytorch.Error("Unsupported container type '" + type + "'.");
  46. }
  47. }
  48. get format() {
  49. return this._format;
  50. }
  51. get graphs() {
  52. return this._graphs;
  53. }
  54. };
  55. pytorch.Graph = class {
  56. constructor(metadata, type, data, container) {
  57. this._nodes = [];
  58. this._inputs = [];
  59. this._outputs = [];
  60. this._groups = true;
  61. this._littleEndian = container.littleEndian;
  62. switch (type) {
  63. case 'script': {
  64. this._name = container.name;
  65. const traced = container.trace();
  66. const initializers = new Map();
  67. if (container.constants) {
  68. for (const constant of container.constants) {
  69. if (pytorch.Utility.isTensor(constant)) {
  70. constant.initializer = pytorch.Utility.createTensor(constant.__variable__, constant, this._littleEndian);
  71. initializers.set(constant.__variable__, constant);
  72. }
  73. else if (constant && constant.__class__ && constant.__class__.__module__ && constant.__class__.__name__) {
  74. const type = constant.__class__.__module__ + '.' + constant.__class__.__name__;
  75. switch (type) {
  76. case '__torch__.torch.classes.xnnpack.LinearOpContext':
  77. case '__torch__.torch.classes.xnnpack.Conv2dOpContext':
  78. case '__torch__.torch.classes.quantized.LinearPackedParamsBase':
  79. case '__torch__.torch.classes.quantized.Conv2dPackedParamsBase':
  80. for (const key of Object.keys(constant)) {
  81. const value = constant[key];
  82. if (pytorch.Utility.isTensor(value)) {
  83. value.initializer = pytorch.Utility.createTensor(value.__variable__, value, this._littleEndian);
  84. initializers.set(value.__variable__, value);
  85. }
  86. }
  87. break;
  88. default:
  89. throw new pytorch.Error("Unsupported constant context '" + type + "'.");
  90. }
  91. }
  92. else {
  93. throw new pytorch.Error('Unsupported constant.');
  94. }
  95. }
  96. }
  97. if (data) {
  98. const queue = [ data ];
  99. while (queue.length > 0) {
  100. const module = queue.shift();
  101. if (module.__class__ && module.__class__.__module__ === '__torch__.torch.classes._nnapi' && module.__class__.__name__ === 'Compilation') {
  102. continue;
  103. }
  104. for (const key of Object.keys(module)) {
  105. if (key !== '__module__' && key !== '__name__' && key !== '__class__' && key !== '__parent__') {
  106. const obj = module[key];
  107. if (!Array.isArray(obj) && obj === Object(obj)) {
  108. if (pytorch.Utility.isTensor(obj)) {
  109. const parameter = obj;
  110. parameter.__parent__ = module;
  111. if (!parameter.initializer && parameter.storage()) {
  112. parameter.initializer = pytorch.Utility.createTensor(parameter.name, parameter, this._littleEndian);
  113. }
  114. if (parameter.__variable__ && parameter.__count__ === 1) {
  115. initializers.set(parameter.__variable__, parameter);
  116. }
  117. }
  118. else if (obj && obj.__class__) {
  119. obj.__parent__ = module;
  120. if (!obj.__id__) {
  121. obj.__id__ = key;
  122. }
  123. queue.push(obj);
  124. }
  125. }
  126. }
  127. }
  128. }
  129. }
  130. if (traced) {
  131. if (container.inputs) {
  132. for (const input of container.inputs) {
  133. this._inputs.push(new pytorch.Parameter(input, true, [
  134. new pytorch.Argument(input, null, null)
  135. ]));
  136. }
  137. }
  138. if (container.outputs) {
  139. for (const output of container.outputs) {
  140. this._outputs.push(new pytorch.Parameter(output, true, [
  141. new pytorch.Argument(output, null, null)
  142. ]));
  143. }
  144. }
  145. if (container.nodes) {
  146. for (const node of container.nodes) {
  147. const item = {
  148. type: node.type,
  149. node: node
  150. };
  151. this._nodes.push(new pytorch.Node(metadata, '', item, initializers));
  152. }
  153. }
  154. }
  155. if (data) {
  156. this._loadScriptModule(metadata, container, data, initializers);
  157. }
  158. break;
  159. }
  160. case 'module': {
  161. this._name = data.name || '';
  162. this._type = (data.obj.__module__ && data.obj.__name__) ? (data.obj.__module__ + '.' + data.obj.__name__) : '';
  163. this._loadModule(metadata, data.obj, [], []);
  164. break;
  165. }
  166. case 'weights': {
  167. this._name = data.name || '';
  168. for (const state_group of data.layers) {
  169. const attributes = state_group.attributes || [];
  170. const inputs = state_group.states.map((parameter) => {
  171. return new pytorch.Parameter(parameter.name, true,
  172. parameter.arguments.map((state) => {
  173. const tensor = pytorch.Utility.createTensor(state.id, pytorch.Utility.toTensor(state.value), this._littleEndian);
  174. return new pytorch.Argument(state.id, null, tensor);
  175. }));
  176. });
  177. const obj = {
  178. name: state_group.name,
  179. type: state_group.type || 'torch.nn.Module',
  180. attributes: attributes,
  181. inputs: inputs,
  182. outputs: []
  183. };
  184. this._nodes.push(new pytorch.Node(metadata, '', obj, null));
  185. }
  186. break;
  187. }
  188. default: {
  189. throw new pytorch.Error("Unsupported container type '" + type + "'.");
  190. }
  191. }
  192. }
  193. _loadModule(metadata, current, groups, inputs) {
  194. if (current.__class__ && current.__class__.__module__ !== 'torch.nn.modules.container' && (!current._modules || current._modules.size == 0)) {
  195. this._createNode(metadata, groups, '', current, inputs, false);
  196. return [];
  197. }
  198. if (!current._modules) {
  199. throw new pytorch.Error('Module does not contain modules.');
  200. }
  201. const sequential = current.__class__ && current.__class__.__module__ === 'torch.nn.modules.container' && current.__class__.__name__ === 'Sequential';
  202. for (const pair of current._modules) {
  203. const key = pair[0];
  204. const value = pair[1];
  205. if (value) {
  206. const type = value.__class__.__module__ + '.' + value.__class__.__name__;
  207. switch (type) {
  208. case 'torch.nn.modules.container.Sequential':
  209. groups.push(key);
  210. inputs = this._loadModule(metadata, value, groups, sequential ? inputs : []);
  211. groups.pop(key);
  212. break;
  213. default: {
  214. inputs = this._createNode(metadata, groups, key, value, sequential ? inputs : [], sequential);
  215. break;
  216. }
  217. }
  218. }
  219. }
  220. return inputs;
  221. }
  222. _createNode(metadata, groups, key, obj, args, output) {
  223. const type = obj.__class__.__module__ + '.' + obj.__class__.__name__;
  224. const schema = metadata.type(type);
  225. let inputSchema = [ { name: 'input'} ];
  226. if (schema && schema.inputs && schema.inputs.length > 0) {
  227. inputSchema = schema.inputs.slice();
  228. }
  229. const inputName = inputSchema.shift().name;
  230. const inputs = [];
  231. if (args.length > 0) {
  232. inputs.push(new pytorch.Parameter(inputName, true, args.map((argument) => {
  233. return new pytorch.Argument(argument, null, null);
  234. })));
  235. }
  236. const parameters = obj._parameters || obj._buffers || [];
  237. for (const parameter of parameters) {
  238. const key = parameter[0];
  239. const value = pytorch.Utility.toTensor(parameter[1]);
  240. let visible = true;
  241. let inputName = '';
  242. if (inputSchema.length > 0) {
  243. const input = inputSchema.shift();
  244. inputName = input.name;
  245. visible = input.visible === false ? false : true;
  246. }
  247. if (value) {
  248. const initializer = pytorch.Utility.createTensor('', value, this._littleEndian);
  249. inputs.push(new pytorch.Parameter(inputName || key, visible, [ new pytorch.Argument('', null, initializer) ]));
  250. }
  251. }
  252. const group = groups.join('/');
  253. const name = group ? (group + '/' + key) : key;
  254. const outputs = output ? [ new pytorch.Parameter('output', true, [ new pytorch.Argument(name, null, null) ]) ] : [];
  255. const attributes = [];
  256. for (const name of Object.keys(obj)) {
  257. if (name.startsWith('_')) {
  258. continue;
  259. }
  260. attributes.push({ name: name, value: obj[name] });
  261. }
  262. const item = {
  263. name: name,
  264. type: type,
  265. attributes: attributes,
  266. children: obj._modules && obj._modules.size > 0 ? true : false,
  267. inputs: inputs,
  268. outputs: outputs
  269. };
  270. const node = new pytorch.Node(metadata, group, item, {});
  271. this._nodes.push(node);
  272. return [ node.name ];
  273. }
  274. _loadScriptModule(metadata, container, module, initializers) {
  275. if (module) {
  276. if (pytorch.Graph._getParameters(module).length > 0 && !module.__hide__) {
  277. const item = { module: module };
  278. this._nodes.push(new pytorch.Node(metadata, '', item, initializers));
  279. }
  280. const submodules = pytorch.Graph._getSubmodules(module);
  281. for (const submodule of submodules) {
  282. this._loadScriptModule(metadata, container, submodule, initializers);
  283. }
  284. }
  285. }
  286. static _getParameters(module) {
  287. const parameters = [];
  288. if (module && module.__class__.__module__ && module.__class__.__name__) {
  289. for (const key of Object.keys(module)) {
  290. if (pytorch.Utility.isTensor(module[key])) {
  291. const parameter = module[key];
  292. parameter.__id__ = key;
  293. parameters.push(parameter);
  294. }
  295. }
  296. }
  297. return parameters;
  298. }
  299. static _getSubmodules(module) {
  300. const submodules = [];
  301. if (module && module.__class__ && module.__class__.__module__ && module.__class__.__name__) {
  302. for (const key of Object.keys(module)) {
  303. if (!key.startsWith('__')) {
  304. const value = module[key];
  305. if (value && value.__class__ && value.__module__ && value.__name__ && !pytorch.Utility.isTensor(value)) {
  306. submodules.push(value);
  307. }
  308. }
  309. }
  310. }
  311. return submodules;
  312. }
  313. get type() {
  314. return this._type;
  315. }
  316. get name() {
  317. return this._name;
  318. }
  319. get groups() {
  320. return this._groups;
  321. }
  322. get inputs() {
  323. return this._inputs;
  324. }
  325. get outputs() {
  326. return this._outputs;
  327. }
  328. get nodes() {
  329. return this._nodes;
  330. }
  331. };
  332. pytorch.Parameter = class {
  333. constructor(name, visible, args) {
  334. this._name = name;
  335. this._visible = visible;
  336. this._arguments = args;
  337. }
  338. get name() {
  339. return this._name;
  340. }
  341. get visible() {
  342. return this._visible;
  343. }
  344. get arguments() {
  345. return this._arguments;
  346. }
  347. };
  348. pytorch.Argument = class {
  349. constructor(name, type, initializer) {
  350. if (typeof name !== 'string') {
  351. throw new pytorch.Error("Invalid argument identifier '" + JSON.stringify(name) + "'.");
  352. }
  353. this._name = name;
  354. this._type = type;
  355. this._initializer = initializer;
  356. }
  357. get name() {
  358. return this._name;
  359. }
  360. get type() {
  361. if (this._initializer) {
  362. return this._initializer.type;
  363. }
  364. return this._type;
  365. }
  366. get initializer() {
  367. return this._initializer;
  368. }
  369. };
  370. pytorch.Node = class {
  371. constructor(metadata, group, item, initializers) {
  372. this._group = group || '';
  373. this._name = item.name || '';
  374. const type = (metadata, name) => {
  375. if (name instanceof pytorch.nnapi.Graph) {
  376. this._type = name;
  377. return;
  378. }
  379. this._type = Object.assign({}, metadata.type(name) || { name: name });
  380. const identifier = this._type.name;
  381. this._type.identifier = identifier;
  382. const index = identifier.indexOf(':');
  383. this._type.name = index === -1 ? identifier : identifier.substring(0, index);
  384. };
  385. if (!item.module && !item.node) {
  386. type(metadata, item.type);
  387. this._nodes = item.children;
  388. this._inputs = item.inputs;
  389. this._outputs = item.outputs;
  390. this._attributes = item.attributes.map((attribute) => {
  391. const schema = metadata.attribute(this._type.identifier, attribute.name);
  392. return new pytorch.Attribute(schema, attribute.name, attribute.value);
  393. });
  394. }
  395. else {
  396. this._attributes = [];
  397. this._inputs = [];
  398. this._outputs = [];
  399. let module = item.module;
  400. if (module) {
  401. this._type = { name: 'torch.nn.modules.module.Module' };
  402. for (const parameter of pytorch.Graph._getParameters(module)) {
  403. this._inputs.push(new pytorch.Parameter(parameter.__id__, true, [
  404. new pytorch.Argument('', null, parameter.initializer || null)
  405. ]));
  406. if (parameter.__variable__) {
  407. this._outputs.push(new pytorch.Parameter(parameter.__id__, true, [
  408. new pytorch.Argument(parameter.__variable__, null, null)
  409. ]));
  410. }
  411. }
  412. }
  413. if (item.node) {
  414. type(metadata, item.type);
  415. module = null;
  416. let match = true;
  417. let count = 0;
  418. for (const input of item.node.inputs) {
  419. for (const argument of input) {
  420. const parameter = initializers.get(argument.id);
  421. if (parameter) {
  422. if (parameter.__parent__ && (module == null || module == parameter.__parent__)) {
  423. module = parameter.__parent__;
  424. count++;
  425. }
  426. else if (parameter.__variable__.startsWith('CONSTANTS.c')) {
  427. argument.initializer = parameter.initializer;
  428. count++;
  429. }
  430. else {
  431. match = false;
  432. break;
  433. }
  434. }
  435. }
  436. if (!match) {
  437. break;
  438. }
  439. }
  440. if (module) {
  441. const params = pytorch.Graph._getParameters(module).filter((p) => p.__id__ !== 'num_batches_tracked');
  442. if (params.length == count && match) {
  443. module.__hide__ = true;
  444. for (const input of item.node.inputs) {
  445. for (const argument of input) {
  446. const parameter = initializers.get(argument.id);
  447. if (parameter && parameter.initializer) {
  448. argument.initializer = parameter.initializer;
  449. }
  450. }
  451. }
  452. }
  453. else {
  454. module = null;
  455. }
  456. }
  457. for (let inputIndex = 0; inputIndex < item.node.inputs.length; inputIndex++) {
  458. let inputName = inputIndex.toString();
  459. if (this._type && this._type.inputs && this._type.inputs.length > inputIndex) {
  460. inputName = this._type.inputs[inputIndex].name;
  461. }
  462. this._inputs.push(new pytorch.Parameter(inputName, true,
  463. item.node.inputs[inputIndex].map((input) => new pytorch.Argument(input.id, null, input.initializer || null))
  464. ));
  465. }
  466. for (let outputIndex = 0; outputIndex < item.node.outputs.length; outputIndex++) {
  467. let outputName = outputIndex.toString();
  468. if (this._type && this._type.outputs && this._type.outputs.length > outputIndex) {
  469. outputName = this._type.outputs[outputIndex].name;
  470. }
  471. this._outputs.push(new pytorch.Parameter(outputName, true,
  472. item.node.outputs[outputIndex].map((output) => new pytorch.Argument(output.id, null, null))
  473. ));
  474. }
  475. for (const attribute of item.node.attributes) {
  476. const name = attribute.name;
  477. const value = attribute.value;
  478. const schema = metadata.attribute(this._type.identifier, name);
  479. this._attributes.push(new pytorch.Attribute(schema, name, value));
  480. }
  481. }
  482. if (module) {
  483. if (module.__id__) {
  484. let current = module;
  485. this._name = current.__id__;
  486. while (current.__parent__ != null) {
  487. current = current.__parent__;
  488. if (!current.__parent__ && !current.__id__) {
  489. break;
  490. }
  491. this._name = [ current.__id__, this._name ].join('.');
  492. }
  493. }
  494. }
  495. }
  496. }
  497. get name() {
  498. return this._name;
  499. }
  500. get group() {
  501. return this._group;
  502. }
  503. get type() {
  504. return this._type;
  505. }
  506. get attributes() {
  507. return this._attributes;
  508. }
  509. get inputs() {
  510. return this._inputs;
  511. }
  512. get outputs() {
  513. return this._outputs;
  514. }
  515. get nodes() {
  516. return this._nodes;
  517. }
  518. };
  519. pytorch.Attribute = class {
  520. constructor(metadata, name, value) {
  521. this._name = name;
  522. this._value = value;
  523. if (this._name === 'training') {
  524. this._visible = false;
  525. this._type = 'boolean';
  526. }
  527. else if (metadata) {
  528. if (metadata.type) {
  529. this._type = metadata.type;
  530. }
  531. if (metadata.visible === false) {
  532. this._visible = false;
  533. }
  534. else if (metadata.default !== undefined) {
  535. if (Array.isArray(value)) {
  536. if (Array.isArray(metadata.default)) {
  537. this._visible = value.length !== metadata.default || !this.value.every((item, index) => item == metadata.default[index]);
  538. }
  539. else {
  540. this._visible = !this.value.every((item) => item == metadata.default);
  541. }
  542. }
  543. else {
  544. this._visible = this.value !== metadata.default;
  545. }
  546. }
  547. }
  548. if (Array.isArray(value) && value.length > 0 && value.every((obj) => obj && obj.__class__ && obj.__class__.__module__ && obj.__class__.__module__.startsWith('torch.nn'))) {
  549. this._value = '?';
  550. }
  551. }
  552. get type() {
  553. return this._type;
  554. }
  555. get name() {
  556. return this._name;
  557. }
  558. get value() {
  559. return this._value;
  560. }
  561. get visible() {
  562. return this._visible == false ? false : true;
  563. }
  564. };
  565. pytorch.Tensor = class {
  566. constructor(name, type, data, littleEndian) {
  567. this._name = name || '';
  568. this._type = type;
  569. this._data = data;
  570. this._littleEndian = littleEndian;
  571. }
  572. get kind() {
  573. return 'Tensor';
  574. }
  575. get name() {
  576. return this._name;
  577. }
  578. get type() {
  579. return this._type;
  580. }
  581. get state() {
  582. return this._context().state;
  583. }
  584. get value() {
  585. const context = this._context();
  586. if (context.state) {
  587. return null;
  588. }
  589. context.limit = Number.MAX_SAFE_INTEGER;
  590. return this._decode(context, 0);
  591. }
  592. toString() {
  593. const context = this._context();
  594. if (context.state) {
  595. return '';
  596. }
  597. context.limit = 10000;
  598. const value = this._decode(context, 0);
  599. return pytorch.Tensor._stringify(value, '', ' ');
  600. }
  601. _context() {
  602. const context = {};
  603. context.state = null;
  604. context.index = 0;
  605. context.count = 0;
  606. if (!this._type.dataType) {
  607. context.state = 'Tensor has no data type.';
  608. return context;
  609. }
  610. switch (this._type.dataType) {
  611. case 'boolean':
  612. case 'uint8':
  613. case 'qint8':
  614. case 'int8':
  615. case 'int16':
  616. case 'int32':
  617. case 'int64':
  618. case 'float16':
  619. case 'float32':
  620. case 'float64':
  621. case 'bfloat16':
  622. break;
  623. default:
  624. context.state = "Tensor data type '" + this._type.dataType + "' is not supported.";
  625. return context;
  626. }
  627. if (!this._type.shape) {
  628. context.state = 'Tensor has no dimensions.';
  629. return context;
  630. }
  631. if (!this._data) {
  632. context.state = 'Tensor data is empty.';
  633. return context;
  634. }
  635. try {
  636. context.data = this._data instanceof Uint8Array ? this._data : this._data.peek();
  637. }
  638. catch (err) {
  639. context.state = err.message;
  640. return context;
  641. }
  642. context.dataType = this._type.dataType;
  643. context.dimensions = this._type.shape.dimensions;
  644. context.dataView = new DataView(context.data.buffer, context.data.byteOffset, context.data.byteLength);
  645. return context;
  646. }
  647. _decode(context, dimension) {
  648. const results = [];
  649. const dimensions = (context.dimensions.length == 0) ? [ 1 ] : context.dimensions;
  650. const size = dimensions[dimension];
  651. if (dimension == dimensions.length - 1) {
  652. for (let i = 0; i < size; i++) {
  653. if (context.count > context.limit) {
  654. results.push('...');
  655. return results;
  656. }
  657. switch (context.dataType) {
  658. case 'boolean':
  659. results.push(context.dataView.getUint8(context.index) === 0 ? false : true);
  660. context.index++;
  661. context.count++;
  662. break;
  663. case 'uint8':
  664. results.push(context.dataView.getUint8(context.index));
  665. context.index++;
  666. context.count++;
  667. break;
  668. case 'qint8':
  669. case 'int8':
  670. results.push(context.dataView.getInt8(context.index));
  671. context.index++;
  672. context.count++;
  673. break;
  674. case 'int16':
  675. results.push(context.dataView.getInt16(context.index, this._littleEndian));
  676. context.index += 2;
  677. context.count++;
  678. break;
  679. case 'int32':
  680. results.push(context.dataView.getInt32(context.index, this._littleEndian));
  681. context.index += 4;
  682. context.count++;
  683. break;
  684. case 'int64':
  685. results.push(context.dataView.getInt64(context.index, this._littleEndian));
  686. context.index += 8;
  687. context.count++;
  688. break;
  689. case 'float16':
  690. results.push(context.dataView.getFloat16(context.index, this._littleEndian));
  691. context.index += 2;
  692. context.count++;
  693. break;
  694. case 'float32':
  695. results.push(context.dataView.getFloat32(context.index, this._littleEndian));
  696. context.index += 4;
  697. context.count++;
  698. break;
  699. case 'float64':
  700. results.push(context.dataView.getFloat64(context.index, this._littleEndian));
  701. context.index += 8;
  702. context.count++;
  703. break;
  704. case 'bfloat16':
  705. results.push(context.dataView.getBfloat16(context.index, this._littleEndian));
  706. context.index += 2;
  707. context.count++;
  708. break;
  709. default:
  710. throw new pytorch.Error("Unsupported tensor data type '" + context.dataType + "'.");
  711. }
  712. }
  713. }
  714. else {
  715. for (let j = 0; j < size; j++) {
  716. if (context.count > context.limit) {
  717. results.push('...');
  718. return results;
  719. }
  720. results.push(this._decode(context, dimension + 1));
  721. }
  722. }
  723. if (context.dimensions.length == 0) {
  724. return results[0];
  725. }
  726. return results;
  727. }
  728. static _stringify(value, indentation, indent) {
  729. if (Array.isArray(value)) {
  730. const result = [];
  731. result.push(indentation + '[');
  732. const items = value.map((item) => pytorch.Tensor._stringify(item, indentation + indent, indent));
  733. if (items.length > 0) {
  734. result.push(items.join(',\n'));
  735. }
  736. result.push(indentation + ']');
  737. return result.join('\n');
  738. }
  739. if (value && (value instanceof base.Int64 || value instanceof base.Uint64)) {
  740. return indentation + value.toString();
  741. }
  742. if (typeof value == 'string') {
  743. return indentation + value;
  744. }
  745. if (value == Infinity) {
  746. return indentation + 'Infinity';
  747. }
  748. if (value == -Infinity) {
  749. return indentation + '-Infinity';
  750. }
  751. if (isNaN(value)) {
  752. return indentation + 'NaN';
  753. }
  754. return indentation + value.toString();
  755. }
  756. };
  757. pytorch.TensorType = class {
  758. constructor(dataType, shape) {
  759. this._dataType = dataType;
  760. this._shape = shape;
  761. }
  762. get dataType() {
  763. return this._dataType;
  764. }
  765. get shape() {
  766. return this._shape;
  767. }
  768. toString() {
  769. return this._dataType + this._shape.toString();
  770. }
  771. };
  772. pytorch.TensorShape = class {
  773. constructor(dimensions) {
  774. this._dimensions = dimensions || [];
  775. }
  776. get dimensions() {
  777. return this._dimensions;
  778. }
  779. toString() {
  780. if (this._dimensions && this._dimensions.length > 0) {
  781. return '[' + this._dimensions.map((dimension) => dimension.toString()).join(',') + ']';
  782. }
  783. return '';
  784. }
  785. };
  786. pytorch.Execution = class extends python.Execution {
  787. constructor(sources, exceptionCallback) {
  788. super(sources, exceptionCallback);
  789. this.registerModule('ops');
  790. this.registerModule('ops.torchvision');
  791. this.registerModule('ops.torchaudio');
  792. this.registerModule('torch');
  793. this.registerModule('torchvision');
  794. this.registerModule('__torch__');
  795. this.context.scope.ops._caffe2 = { __name__: 'torch', __class__: this.context.scope.builtins.module };
  796. const self = this;
  797. const torch = this.context.scope.torch;
  798. this.registerType('builtins.number', class {});
  799. this.registerType('__torch__.torch.classes._nnapi.Compilation', class {
  800. constructor() {
  801. this.__hide__ = true;
  802. }
  803. __init__() {
  804. }
  805. init(serialized_model_tensor, parameter_buffers) {
  806. this.serialized_model_tensor = serialized_model_tensor;
  807. this.parameter_buffers = parameter_buffers;
  808. const buffers = parameter_buffers.map((buffer) => buffer.__source__.storage().data);
  809. const serialized_model = serialized_model_tensor.storage().data;
  810. this.serialized_model = new pytorch.nnapi.SerializedModel(serialized_model, buffers);
  811. }
  812. run(inputs, outputs) {
  813. this.serialized_model_tensor.__variable__ = this.serialized_model_tensor.__variable__ || self.variable();
  814. this.serialized_model_tensor.__count__ = (this.serialized_model_tensor.__count__ || 0) + 1;
  815. self.push({
  816. type: new pytorch.nnapi.Graph(this.serialized_model),
  817. attributes: [],
  818. inputs: [
  819. inputs.map((input) => { return { id: input.__variable__ }; }),
  820. // [ { id: this.serialized_model_tensor.__variable__ } ] //,
  821. // this.parameter_buffers.map((buffer) => { return { id: buffer.__variable__ }; })
  822. ],
  823. outputs: [
  824. outputs.map((output) => { return { id: output.__variable__ }; })
  825. ],
  826. });
  827. }
  828. });
  829. this.registerType('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', class {
  830. __setstate__(state) {
  831. const pack_version = state[0];
  832. if (pack_version !== '2') {
  833. throw new pytorch.Error("Unsupported pack version '" + pack_version.toString() + "'.");
  834. }
  835. const tensors = state[1];
  836. const opt_tensors = state[2];
  837. const packed_config = pytorch.Utility.createTensor('', tensors[0], true).value;
  838. this.weight = tensors[1];
  839. this.bias = opt_tensors[0];
  840. this.stride = [ packed_config[1], packed_config[2] ];
  841. this.padding = [ packed_config[3], packed_config[4] ];
  842. this.dilation = [ packed_config[5], packed_config[6] ];
  843. this.output_padding = [ packed_config[7], packed_config[8] ];
  844. this.groups = packed_config[9];
  845. }
  846. });
  847. this.registerType('__torch__.torch.classes.quantized.Conv3dPackedParamsBase', class {
  848. __setstate__(state) {
  849. const pack_version = state[0];
  850. if (pack_version !== '2') {
  851. throw new pytorch.Error("Unsupported pack version '" + pack_version.toString() + "'.");
  852. }
  853. const tensors = state[1];
  854. const opt_tensors = state[2];
  855. const packed_config = pytorch.Utility.createTensor('', tensors[0], true).value;
  856. this.weight = tensors[1];
  857. this.bias = opt_tensors[0];
  858. this.stride = [ packed_config[1], packed_config[2] ];
  859. this.padding = [ packed_config[3], packed_config[4] ];
  860. this.dilation = [ packed_config[5], packed_config[6] ];
  861. this.output_padding = [ packed_config[7], packed_config[8] ];
  862. this.groups = packed_config[9];
  863. }
  864. });
  865. this.registerType('__torch__.torch.classes.quantized.LinearPackedParamsBase', class {
  866. __setstate__(state) {
  867. this.weight = state[0];
  868. this.bias = state[1];
  869. }
  870. });
  871. this.registerType('__torch__.torch.classes.xnnpack.Conv2dOpContext', class {
  872. __setstate__(state) {
  873. this.weight = state[0];
  874. this.bias = state[1];
  875. this.stride = state[2];
  876. this.padding = state[3];
  877. this.dilation = state[4];
  878. this.groups = state[5];
  879. this.output_min = state[6];
  880. this.output_max = state[7];
  881. }
  882. });
  883. this.registerType('__torch__.torch.classes.xnnpack.LinearOpContext', class {
  884. __setstate__(state) {
  885. this.weight = state[0];
  886. this.bias = state[1];
  887. this.output_min = state[2];
  888. this.output_max = state[3];
  889. }
  890. });
  891. this.registerType('torch.ao.quantization.stubs.DeQuantStub', class {});
  892. this.registerType('torch.ao.quantization.stubs.QuantStub', class {});
  893. this.registerType('torch.autograd.variable.Variable', class {});
  894. this.registerType('torch.backends.cudnn.rnn.Unserializable', class {});
  895. this.registerType('torch.distributions.bernoulli.Bernoulli', class {});
  896. this.registerType('torch.distributions.constraints._LowerCholesky', class {});
  897. this.registerType('torch.distributions.constraints._Real', class {});
  898. this.registerType('torch.distributions.multivariate_normal.MultivariateNormal', class {});
  899. this.registerType('torch.distributions.normal.Normal', class {});
  900. this.registerType('torch.distributions.transforms.LowerCholeskyTransform', class {});
  901. this.registerType('torch.distributions.uniform.Uniform', class {});
  902. this.registerType('torch.nn.backends.thnn._get_thnn_function_backend', class {});
  903. this.registerType('torch.nn.intrinsic.modules.fused.ConvBnReLU2d', class {});
  904. this.registerType('torch.nn.intrinsic.modules.fused.ConvReLU2d', class {});
  905. this.registerType('torch.nn.intrinsic.modules.fused.BNReLU2d', class {});
  906. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU2d', class {});
  907. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvReLU2d', class {});
  908. this.registerType('torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', class {});
  909. this.registerType('torch.nn.intrinsic.quantized.modules.linear_relu.LinearReLU', class {});
  910. this.registerType('torch.nn.modules.activation.CELU', class {});
  911. this.registerType('torch.nn.modules.activation.ELU', class {});
  912. this.registerType('torch.nn.modules.activation.GELU', class {});
  913. this.registerType('torch.nn.modules.activation.GLU', class {});
  914. this.registerType('torch.nn.modules.activation.Hardtanh', class {});
  915. this.registerType('torch.nn.modules.activation.Hardswish', class {});
  916. this.registerType('torch.nn.modules.activation.Hardsigmoid', class {});
  917. this.registerType('torch.nn.modules.activation.LeakyReLU', class {});
  918. this.registerType('torch.nn.modules.activation.LogSigmoid', class {});
  919. this.registerType('torch.nn.modules.activation.LogSoftmax', class {});
  920. this.registerType('torch.nn.modules.activation.Mish', class {});
  921. this.registerType('torch.nn.modules.activation.MultiheadAttention', class {});
  922. this.registerType('torch.nn.modules.activation.ReLU', class {});
  923. this.registerType('torch.nn.modules.activation.ReLU6', class {});
  924. this.registerType('torch.nn.modules.activation.PReLU', class {});
  925. this.registerType('torch.nn.modules.activation.RReLU', class {});
  926. this.registerType('torch.nn.modules.activation.SELU', class {});
  927. this.registerType('torch.nn.modules.activation.Sigmoid', class {});
  928. this.registerType('torch.nn.modules.activation.SiLU', class {});
  929. this.registerType('torch.nn.modules.activation.Softmax', class {});
  930. this.registerType('torch.nn.modules.activation.Softmax2d', class {});
  931. this.registerType('torch.nn.modules.activation.Softplus', class {});
  932. this.registerType('torch.nn.modules.activation.Tanh', class {});
  933. this.registerType('torch.nn.modules.activation.Tanhshrink', class {});
  934. this.registerType('torch.nn.modules.activation.Threshold', class {});
  935. this.registerType('torch.nn.modules.batchnorm.BatchNorm1d', class {});
  936. this.registerType('torch.nn.modules.batchnorm.BatchNorm2d', class {});
  937. this.registerType('torch.nn.modules.batchnorm.BatchNorm3d', class {});
  938. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm1d', class {});
  939. this.registerType('torch.nn.modules.batchnorm.SyncBatchNorm', class {});
  940. this.registerType('torch.nn.modules.container.ModuleDict', class {});
  941. this.registerType('torch.nn.modules.container.ModuleList', class {});
  942. this.registerType('torch.nn.modules.container.ParameterDict', class {});
  943. this.registerType('torch.nn.modules.container.ParameterList', class {});
  944. this.registerType('torch.nn.modules.container.Sequential', class {});
  945. this.registerType('torch.nn.modules.conv.Conv1d', class {});
  946. this.registerType('torch.nn.modules.conv.Conv2d', class {});
  947. this.registerType('torch.nn.modules.conv.Conv3d', class {});
  948. this.registerType('torch.nn.modules.conv.ConvTranspose1d', class {});
  949. this.registerType('torch.nn.modules.conv.ConvTranspose2d', class {});
  950. this.registerType('torch.nn.modules.conv.ConvTranspose3d', class {});
  951. this.registerType('torch.nn.modules.distance.CosineSimilarity', class {});
  952. this.registerType('torch.nn.modules.dropout.AlphaDropout', class {});
  953. this.registerType('torch.nn.modules.dropout.Dropout', class {});
  954. this.registerType('torch.nn.modules.dropout.Dropout2d', class {});
  955. this.registerType('torch.nn.modules.dropout.Dropout3d', class {});
  956. this.registerType('torch.nn.modules.fold.Fold', class {});
  957. this.registerType('torch.nn.modules.fold.Unfold', class {});
  958. this.registerType('torch.nn.modules.flatten.Flatten', class {});
  959. this.registerType('torch.nn.modules.flatten.Unflatten', class {});
  960. this.registerType('torch.nn.modules.instancenorm.InstanceNorm1d', class {});
  961. this.registerType('torch.nn.modules.instancenorm.InstanceNorm2d', class {});
  962. this.registerType('torch.nn.modules.instancenorm.InstanceNorm3d', class {});
  963. this.registerType('torch.nn.modules.linear._LinearWithBias', class {});
  964. this.registerType('torch.nn.modules.linear.Bilinear', class {});
  965. this.registerType('torch.nn.modules.linear.Identity', class {});
  966. this.registerType('torch.nn.modules.linear.LazyLinear', class {});
  967. this.registerType('torch.nn.modules.linear.Linear', class {});
  968. this.registerType('torch.nn.modules.linear.NonDynamicallyQuantizableLinear', class {});
  969. this.registerType('torch.nn.modules.loss.BCELoss', class {});
  970. this.registerType('torch.nn.modules.loss.BCEWithLogitsLoss', class {});
  971. this.registerType('torch.nn.modules.loss.CrossEntropyLoss', class {});
  972. this.registerType('torch.nn.modules.loss.CTCLoss', class {});
  973. this.registerType('torch.nn.modules.loss.KLDivLoss', class {});
  974. this.registerType('torch.nn.modules.loss.L1Loss', class {});
  975. this.registerType('torch.nn.modules.loss.MarginRankingLoss', class {});
  976. this.registerType('torch.nn.modules.loss.MSELoss', class {});
  977. this.registerType('torch.nn.modules.loss.NLLLoss', class {});
  978. this.registerType('torch.nn.modules.loss.NLLLoss2d', class {});
  979. this.registerType('torch.nn.modules.loss.SmoothL1Loss', class {});
  980. this.registerType('torch.nn.modules.module._IncompatibleKeys', class {});
  981. this.registerType('torch.nn.modules.module.Module', class {});
  982. this.registerType('torch.nn.modules.module.PatchForward', class {});
  983. this.registerType('torch.nn.modules.normalization.CrossMapLRN2d', class {});
  984. this.registerType('torch.nn.modules.normalization.GroupNorm', class {});
  985. this.registerType('torch.nn.modules.normalization.LayerNorm', class {});
  986. this.registerType('torch.nn.modules.normalization.LocalResponseNorm', class {});
  987. this.registerType('torch.nn.modules.padding.ReflectionPad1d', class {});
  988. this.registerType('torch.nn.modules.padding.ReflectionPad2d', class {});
  989. this.registerType('torch.nn.modules.padding.ReplicationPad1d', class {});
  990. this.registerType('torch.nn.modules.padding.ReplicationPad2d', class {});
  991. this.registerType('torch.nn.modules.padding.ReplicationPad3d', class {});
  992. this.registerType('torch.nn.modules.padding.ZeroPad2d', class {});
  993. this.registerType('torch.nn.modules.padding.ConstantPad1d', class {});
  994. this.registerType('torch.nn.modules.padding.ConstantPad2d', class {});
  995. this.registerType('torch.nn.modules.padding.ConstantPad3d', class {});
  996. this.registerType('torch.nn.modules.pixelshuffle.PixelShuffle', class {});
  997. this.registerType('torch.nn.modules.pixelshuffle.PixelUnshuffle', class {});
  998. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool1d', class {});
  999. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool2d', class {});
  1000. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool3d', class {});
  1001. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool1d', class {});
  1002. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool2d', class {});
  1003. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool3d', class {});
  1004. this.registerType('torch.nn.modules.pooling.AvgPool1d', class {});
  1005. this.registerType('torch.nn.modules.pooling.AvgPool2d', class {});
  1006. this.registerType('torch.nn.modules.pooling.AvgPool3d', class {});
  1007. this.registerType('torch.nn.modules.pooling.FractionalMaxPool2d', class {});
  1008. this.registerType('torch.nn.modules.pooling.LPPool2d', class {});
  1009. this.registerType('torch.nn.modules.pooling.MaxPool1d', class {});
  1010. this.registerType('torch.nn.modules.pooling.MaxPool2d', class {});
  1011. this.registerType('torch.nn.modules.pooling.MaxPool3d', class {});
  1012. this.registerType('torch.nn.modules.pooling.MaxUnpool1d', class {});
  1013. this.registerType('torch.nn.modules.pooling.MaxUnpool2d', class {});
  1014. this.registerType('torch.nn.modules.pooling.MaxUnpool3d', class {});
  1015. this.registerType('torch.nn.modules.rnn.GRU', class {});
  1016. this.registerType('torch.nn.modules.rnn.GRUCell', class {});
  1017. this.registerType('torch.nn.modules.rnn.LSTM', class {});
  1018. this.registerType('torch.nn.modules.rnn.LSTMCell', class {});
  1019. this.registerType('torch.nn.modules.rnn.RNN', class {});
  1020. this.registerType('torch.nn.modules.sparse.Embedding', class {});
  1021. this.registerType('torch.nn.modules.sparse.EmbeddingBag', class {});
  1022. this.registerType('torch.nn.modules.transformer.Transformer', class {});
  1023. this.registerType('torch.nn.modules.transformer.TransformerDecoder', class {});
  1024. this.registerType('torch.nn.modules.transformer.TransformerDecoderLayer', class {});
  1025. this.registerType('torch.nn.modules.transformer.TransformerEncoder', class {});
  1026. this.registerType('torch.nn.modules.transformer.TransformerEncoderLayer', class {});
  1027. this.registerType('torch.nn.modules.upsampling.Upsample', class {});
  1028. this.registerType('torch.nn.modules.upsampling.UpsamplingBilinear2d', class {});
  1029. this.registerType('torch.nn.modules.upsampling.UpsamplingNearest2d', class {});
  1030. this.registerType('torch.nn.parallel.data_parallel.DataParallel', class {});
  1031. this.registerType('torch.nn.parallel.distributed._DDPUnevenInputsConfig', class {});
  1032. this.registerType('torch.nn.parallel.distributed.DistributedDataParallel', class {});
  1033. this.registerType('torch.nn.qat.modules.conv.Conv2d', class {});
  1034. this.registerType('torch.nn.qat.modules.linear.Linear', class {});
  1035. this.registerType('torch.nn.quantized.modules.activation.ReLU', class {});
  1036. this.registerType('torch.nn.quantized.modules.activation.LeakyReLU', class {});
  1037. this.registerType('torch.nn.quantized.dynamic.modules.linear.Linear', class {});
  1038. this.registerType('torch.nn.quantized.dynamic.modules.rnn.GRU', class {});
  1039. this.registerType('torch.nn.quantized.dynamic.modules.rnn.PackedParameter', class {});
  1040. this.registerType('torch.nn.quantized.modules.activation.ReLU6', class {});
  1041. this.registerType('torch.nn.quantized.modules.batchnorm.BatchNorm2d', class {});
  1042. this.registerType('torch.nn.quantized.modules.conv.Conv1d', class {});
  1043. this.registerType('torch.nn.quantized.modules.conv.Conv2d', class {});
  1044. this.registerType('torch.nn.quantized.modules.conv.ConvTranspose2d', class {});
  1045. this.registerType('torch.nn.quantized.modules.DeQuantize', class {});
  1046. this.registerType('torch.nn.quantized.modules.functional_modules.FloatFunctional', class {});
  1047. this.registerType('torch.nn.quantized.modules.functional_modules.QFunctional', class {});
  1048. this.registerType('torch.nn.quantized.modules.linear.Linear', class {});
  1049. this.registerType('torch.nn.quantized.modules.linear.LinearPackedParams', class {});
  1050. this.registerType('torch.nn.quantized.modules.normalization.InstanceNorm2d', class {});
  1051. this.registerType('torch.nn.quantized.modules.Quantize', class {});
  1052. this.registerType('torch.nn.utils.prune.L1Unstructured', class {});
  1053. this.registerType('torch.nn.utils.spectral_norm.SpectralNorm', class {});
  1054. this.registerType('torch.nn.utils.spectral_norm.SpectralNormStateDictHook', class {});
  1055. this.registerType('torch.nn.utils.spectral_norm.SpectralNormLoadStateDictPreHook', class {});
  1056. this.registerType('torch.nn.utils.weight_norm.WeightNorm', class {});
  1057. this.registerType('torch.optim.adam.Adam', class {});
  1058. this.registerType('torch.optim.adamw.AdamW', class {});
  1059. this.registerType('torch.optim.adagrad.Adagrad', class {});
  1060. this.registerType('torch.optim.adadelta.Adadelta', class {});
  1061. this.registerType('torch.optim.lr_scheduler.CosineAnnealingLR', class {});
  1062. this.registerType('torch.optim.lr_scheduler.CyclicLR', class {});
  1063. this.registerType('torch.optim.lr_scheduler.ExponentialLR', class {});
  1064. this.registerType('torch.optim.lr_scheduler.LambdaLR', class {});
  1065. this.registerType('torch.optim.lr_scheduler.MultiStepLR', class {});
  1066. this.registerType('torch.optim.lr_scheduler.OneCycleLR', class {});
  1067. this.registerType('torch.optim.lr_scheduler.ReduceLROnPlateau', class {});
  1068. this.registerType('torch.optim.lr_scheduler.StepLR', class {});
  1069. this.registerType('torch.optim.optimizer._RequiredParameter', class {});
  1070. this.registerType('torch.optim.rmsprop.RMSprop', class {});
  1071. this.registerType('torch.optim.sgd.SGD', class {});
  1072. this.registerType('torch.quantization.fake_quantize.FakeQuantize', class {});
  1073. this.registerType('torch.quantization.observer._PartialWrapper', class {});
  1074. this.registerType('torch.quantization.observer.MinMaxObserver', class {});
  1075. this.registerType('torch.quantization.observer.MovingAverageMinMaxObserver', class {});
  1076. this.registerType('torch.quantization.observer.MovingAveragePerChannelMinMaxObserver', class {});
  1077. this.registerType('torch.quantization.qconfig.QConfig', class {});
  1078. this.registerType('torch.quantization.stubs.DeQuantStub', class {});
  1079. this.registerType('torch.quantization.stubs.QuantStub', class {});
  1080. this.registerType('torch.utils.data.dataloader._MultiProcessingDataLoaderIter', class {});
  1081. this.registerType('torch.utils.data.dataloader.DataLoader', class {});
  1082. this.registerType('torch.utils.data.dataset.Subset', class {});
  1083. this.registerType('torch.utils.data.dataset.ConcatDataset', class {});
  1084. this.registerType('torch.utils.data.dataset.TensorDataset', class {});
  1085. this.registerType('torch.utils.data.sampler.BatchSampler', class {});
  1086. this.registerType('torch.utils.data.sampler.RandomSampler', class {});
  1087. this.registerType('torch.utils.data.sampler.SequentialSampler', class {});
  1088. this.registerType('torchvision.datasets.folder.ImageFolder', class {});
  1089. this.registerType('torchvision.datasets.mnist.MNIST', class {});
  1090. this.registerType('torchvision.datasets.vision.StandardTransform', class {});
  1091. this.registerType('torchvision.models.alexnet.AlexNet', class {});
  1092. this.registerType('torchvision.models.densenet.DenseNet', class {});
  1093. this.registerType('torchvision.models.densenet._DenseBlock', class {});
  1094. this.registerType('torchvision.models.densenet._DenseLayer', class {});
  1095. this.registerType('torchvision.models.densenet._Transition', class {});
  1096. this.registerType('torchvision.models.detection._utils.BalancedPositiveNegativeSampler', class {});
  1097. this.registerType('torchvision.models.detection._utils.BoxCoder', class {});
  1098. this.registerType('torchvision.models.detection._utils.Matcher', class {});
  1099. this.registerType('torchvision.models.detection._utils.SSDMatcher', class {});
  1100. this.registerType('torchvision.models.detection.anchor_utils.AnchorGenerator', class {});
  1101. this.registerType('torchvision.models.detection.anchor_utils.DefaultBoxGenerator', class {});
  1102. this.registerType('torchvision.models.detection.backbone_utils.BackboneWithFPN', class {});
  1103. this.registerType('torchvision.models.detection.faster_rcnn.FasterRCNN', class {});
  1104. this.registerType('torchvision.models.detection.faster_rcnn.FastRCNNPredictor', class {});
  1105. this.registerType('torchvision.models.detection.faster_rcnn.TwoMLPHead', class {});
  1106. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNN', class {});
  1107. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNHeads', class {});
  1108. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNPredictor', class {});
  1109. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNN', class {});
  1110. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNHeads', class {});
  1111. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNPredictor', class {});
  1112. this.registerType('torchvision.models.detection.retinanet.RetinaNetClassificationHead', class {});
  1113. this.registerType('torchvision.models.detection.retinanet.RetinaNetHead', class {});
  1114. this.registerType('torchvision.models.detection.retinanet.RetinaNetRegressionHead', class {});
  1115. this.registerType('torchvision.models.detection.roi_heads.RoIHeads', class {});
  1116. this.registerType('torchvision.models.detection.rpn.AnchorGenerator', class {});
  1117. this.registerType('torchvision.models.detection.rpn.RegionProposalNetwork', class {});
  1118. this.registerType('torchvision.models.detection.rpn.RPNHead', class {});
  1119. this.registerType('torchvision.models.detection.ssd.SSD', class {});
  1120. this.registerType('torchvision.models.detection.ssdlite.SSDLiteClassificationHead', class {});
  1121. this.registerType('torchvision.models.detection.ssdlite.SSDLiteFeatureExtractorMobileNet', class {});
  1122. this.registerType('torchvision.models.detection.ssdlite.SSDLiteHead', class {});
  1123. this.registerType('torchvision.models.detection.ssdlite.SSDLiteRegressionHead', class {}); this.registerType('torchvision.models.detection.transform.GeneralizedRCNNTransform', class {});
  1124. this.registerType('torchvision.models.googlenet.BasicConv2d', class {});
  1125. this.registerType('torchvision.models.googlenet.GoogLeNet', class {});
  1126. this.registerType('torchvision.models.googlenet.Inception', class {});
  1127. this.registerType('torchvision.models.googlenet.InceptionAux', class {});
  1128. this.registerType('torchvision.models.inception.BasicConv2d', class {});
  1129. this.registerType('torchvision.models.inception.Inception3', class {});
  1130. this.registerType('torchvision.models.inception.InceptionAux', class {});
  1131. this.registerType('torchvision.models.inception.InceptionA', class {});
  1132. this.registerType('torchvision.models.inception.InceptionB', class {});
  1133. this.registerType('torchvision.models.inception.InceptionC', class {});
  1134. this.registerType('torchvision.models.inception.InceptionD', class {});
  1135. this.registerType('torchvision.models.inception.InceptionE', class {});
  1136. this.registerType('torchvision.models.mnasnet._InvertedResidual', class {});
  1137. this.registerType('torchvision.models.mnasnet.MNASNet', class {});
  1138. this.registerType('torchvision.models.mobilenet.ConvBNReLU', class {});
  1139. this.registerType('torchvision.models.mobilenet.MobileNetV2', class {});
  1140. this.registerType('torchvision.models.mobilenet.InvertedResidual', class {});
  1141. this.registerType('torchvision.models.mobilenetv2.ConvBNActivation', class {});
  1142. this.registerType('torchvision.models.mobilenetv2.InvertedResidual', class {});
  1143. this.registerType('torchvision.models.mobilenetv2.MobileNetV2', class {});
  1144. this.registerType('torchvision.models.mobilenetv3.InvertedResidual', class {});
  1145. this.registerType('torchvision.models.mobilenetv3.MobileNetV3', class {});
  1146. this.registerType('torchvision.models.mobilenetv3.SqueezeExcitation', class {});
  1147. this.registerType('torchvision.models.resnet.Bottleneck', class {});
  1148. this.registerType('torchvision.models.resnet.BasicBlock', class {});
  1149. this.registerType('torchvision.models.quantization.mobilenet.QuantizableInvertedResidual', class {});
  1150. this.registerType('torchvision.models.quantization.mobilenet.QuantizableMobileNetV2', class {});
  1151. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableInvertedResidual', class {});
  1152. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableMobileNetV2', class {});
  1153. this.registerType('torchvision.models.quantization.resnet.QuantizableBasicBlock', class {});
  1154. this.registerType('torchvision.models.quantization.resnet.QuantizableBottleneck', class {});
  1155. this.registerType('torchvision.models.quantization.resnet.QuantizableResNet', class {});
  1156. this.registerType('torchvision.models.segmentation.deeplabv3.ASPP', class {});
  1157. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPConv', class {});
  1158. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPPooling', class {});
  1159. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabHead', class {});
  1160. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabV3', class {});
  1161. this.registerType('torchvision.models.segmentation.fcn.FCN', class {});
  1162. this.registerType('torchvision.models.segmentation.fcn.FCNHead', class {});
  1163. this.registerType('torchvision.models.shufflenetv2.ShuffleNetV2', class {});
  1164. this.registerType('torchvision.models.shufflenetv2.InvertedResidual', class {});
  1165. this.registerType('torchvision.models.squeezenet.Fire', class {});
  1166. this.registerType('torchvision.models.squeezenet.SqueezeNet', class {});
  1167. this.registerType('torchvision.models.resnet.ResNet', class {});
  1168. this.registerType('torchvision.models.vgg.VGG', class {});
  1169. this.registerType('torchvision.models.video.resnet.BasicBlock', class {});
  1170. this.registerType('torchvision.models.video.resnet.BasicStem', class {});
  1171. this.registerType('torchvision.models.video.resnet.Conv2Plus1D', class {});
  1172. this.registerType('torchvision.models.video.resnet.Conv3DNoTemporal', class {});
  1173. this.registerType('torchvision.models.video.resnet.Conv3DSimple', class {});
  1174. this.registerType('torchvision.models.video.resnet.R2Plus1dStem', class {});
  1175. this.registerType('torchvision.models.video.resnet.VideoResNet', class {});
  1176. this.registerType('torchvision.models._utils.IntermediateLayerGetter', class {});
  1177. this.registerType('torchvision.ops.deform_conv.DeformConv2d', class {});
  1178. this.registerType('torchvision.ops.feature_pyramid_network.FeaturePyramidNetwork', class {});
  1179. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelMaxPool', class {});
  1180. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelP6P7', class {});
  1181. this.registerType('torchvision.ops.misc.ConvNormActivation', class {});
  1182. this.registerType('torchvision.ops.misc.ConvTranspose2d', class {});
  1183. this.registerType('torchvision.ops.misc.FrozenBatchNorm2d', class {});
  1184. this.registerType('torchvision.ops.misc.SqueezeExcitation', class {});
  1185. this.registerType('torchvision.ops.poolers.LevelMapper', class {});
  1186. this.registerType('torchvision.ops.poolers.MultiScaleRoIAlign', class {});
  1187. this.registerType('torchvision.transforms.functional.InterpolationMode', class {});
  1188. this.registerType('torchvision.transforms.transforms.Compose', class {});
  1189. this.registerType('torchvision.transforms.transforms.CenterCrop', class {});
  1190. this.registerType('torchvision.transforms.transforms.Grayscale', class {});
  1191. this.registerType('torchvision.transforms.transforms.Normalize', class {});
  1192. this.registerType('torchvision.transforms.transforms.RandomAffine', class {});
  1193. this.registerType('torchvision.transforms.transforms.RandomCrop', class {});
  1194. this.registerType('torchvision.transforms.transforms.RandomHorizontalFlip', class {});
  1195. this.registerType('torchvision.transforms.transforms.Resize', class {});
  1196. this.registerType('torchvision.transforms.transforms.Scale', class {});
  1197. this.registerType('torchvision.transforms.transforms.ToPILImage', class {});
  1198. this.registerType('torchvision.transforms.transforms.ToTensor', class {});
  1199. this.registerFunction('annotate', function(type, value) {
  1200. if (type === self.context.scope.builtins.int) {
  1201. return Number.isInteger(value) ? value : NaN;
  1202. }
  1203. if (type === self.context.scope.builtins.float) {
  1204. return typeof value === 'number' ? value : NaN;
  1205. }
  1206. if (type === self.context.scope.builtins.number) {
  1207. if (pytorch.Utility.isTensor(value)) {
  1208. value.resize_([]);
  1209. }
  1210. }
  1211. return value;
  1212. });
  1213. this.registerFunction('bool', function(value) {
  1214. if (pytorch.Utility.isTensor(value)) {
  1215. return true;
  1216. }
  1217. throw new pytorch.Error("Unsupported bool expression '" + JSON.stringify(value) + "'.");
  1218. });
  1219. this.registerFunction('int', function(value) {
  1220. if (pytorch.Utility.isTensor(value)) {
  1221. const storage = value.storage();
  1222. if (storage && storage.dtype.__reduce__() === 'int64' && storage.data.length === 8) {
  1223. const buffer = storage.data;
  1224. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  1225. return view.getInt64(0, true);
  1226. }
  1227. }
  1228. if (Number.isInteger(value)) {
  1229. return value;
  1230. }
  1231. return NaN;
  1232. });
  1233. this.registerFunction('float', function(value) {
  1234. if (pytorch.Utility.isTensor(value)) {
  1235. const storage = value.storage();
  1236. if (storage && storage.dtype.__reduce__() === 'float32') {
  1237. if (storage.size() !== undefined && storage.data.length === 4) {
  1238. const buffer = storage.data;
  1239. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  1240. return view.getFloat32(0, true);
  1241. }
  1242. return NaN;
  1243. }
  1244. }
  1245. if (Number(value) === value) {
  1246. return value;
  1247. }
  1248. return NaN;
  1249. });
  1250. this.registerFunction('str', function(value) {
  1251. return JSON.stringify(value);
  1252. });
  1253. this.registerFunction('unchecked_cast', function(type, value) {
  1254. return value;
  1255. });
  1256. this.registerFunction('ops.prim.data', function(tensor) {
  1257. return tensor;
  1258. });
  1259. this.registerFunction('ops.prim.device', function(tensor) {
  1260. return tensor.device;
  1261. });
  1262. this.registerFunction('ops.prim.dtype', function(tensor) {
  1263. return tensor.dtype.scalar_type();
  1264. });
  1265. this.registerFunction('ops.prim.is_quantized', function(tensor) {
  1266. return tensor && tensor.__quantized__ === true;
  1267. });
  1268. this.registerFunction('ops.prim.unchecked_unwrap_optional', function(value) {
  1269. return value;
  1270. });
  1271. this.registerFunction('ops.prim.NumToTensor', function(value) {
  1272. const tensor = self.invoke('torch.Tensor', []);
  1273. tensor.value = value; // TODO
  1274. return tensor;
  1275. });
  1276. this.registerFunction('ops.prim.min', function(value) {
  1277. if (Array.isArray(value)) {
  1278. return Math.min.apply(null, value);
  1279. }
  1280. return Math.min.apply(null, arguments);
  1281. });
  1282. this.registerFunction('ops.prim.max', function(value) {
  1283. if (Array.isArray(value)) {
  1284. return Math.max.apply(null, value);
  1285. }
  1286. return Math.max.apply(null, arguments);
  1287. });
  1288. this.registerFunction('ops.prim.shape', function(tensor) {
  1289. return tensor && tensor.size ? tensor.size() : undefined;
  1290. });
  1291. this.registerFunction('ops.quantized.conv_prepack', function(weight, bias, stride, padding, dilation, groups) {
  1292. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  1293. params.weight = weight;
  1294. params.bias = bias;
  1295. params.stride = stride;
  1296. params.padding =padding;
  1297. params.dilation = dilation;
  1298. params.groups = groups;
  1299. return params;
  1300. });
  1301. this.registerFunction('ops.quantized.conv1d_prepack', function(weight, bias, stride, padding, dilation, groups) {
  1302. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  1303. params.weight = weight;
  1304. params.bias = bias;
  1305. params.stride = stride;
  1306. params.padding =padding;
  1307. params.dilation = dilation;
  1308. params.groups = groups;
  1309. return params;
  1310. });
  1311. this.registerFunction('ops.quantized.conv2d_prepack', function(weight, bias, stride, padding, dilation, groups) {
  1312. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  1313. params.weight = weight;
  1314. params.bias = bias;
  1315. params.stride = stride;
  1316. params.padding =padding;
  1317. params.dilation = dilation;
  1318. params.groups = groups;
  1319. return params;
  1320. });
  1321. this.registerFunction('ops.quantized.conv3d_prepack', function(weight, bias, stride, padding, dilation, groups) {
  1322. const params = self.invoke('__torch__.torch.classes.quantized.Conv3dPackedParamsBase', []);
  1323. params.weight = weight;
  1324. params.bias = bias;
  1325. params.stride = stride;
  1326. params.padding =padding;
  1327. params.dilation = dilation;
  1328. params.groups = groups;
  1329. return params;
  1330. });
  1331. this.registerFunction('ops.quantized.conv_transpose2d_prepack', function(weight, bias, stride, padding, output_padding, dilation, groups) {
  1332. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  1333. params.weight = weight;
  1334. params.bias = bias;
  1335. params.stride = stride;
  1336. params.padding =padding;
  1337. params.output_padding = output_padding;
  1338. params.dilation = dilation;
  1339. params.groups = groups;
  1340. return params;
  1341. });
  1342. this.registerFunction('ops.quantized.linear_prepack', function(weight, bias) {
  1343. const params = self.invoke('__torch__.torch.classes.quantized.LinearPackedParamsBase', []);
  1344. params.weight = weight;
  1345. params.bias = bias;
  1346. return params;
  1347. });
  1348. this.registerFunction('ops.prim.RaiseException', function(message) {
  1349. throw new pytorch.Error(message);
  1350. });
  1351. this.registerFunction('range', function(start, stop, step) {
  1352. if (stop === undefined && step === undefined) {
  1353. if (Number.isInteger(start)) {
  1354. return Array(start).keys();
  1355. }
  1356. if (isNaN(start)) {
  1357. return [];
  1358. }
  1359. }
  1360. throw new pytorch.Error('Unsupported function range(' + JSON.stringify(start) + ', ' + JSON.stringify(stop) + ', ' + JSON.stringify(step) + ')');
  1361. });
  1362. this.registerFunction('torch._utils._rebuild_tensor', function (storage, storage_offset, size, stride) {
  1363. const name = storage.__class__.__module__ + '.' + storage.__class__.__name__.replace('Storage', 'Tensor');
  1364. const tensor = self.invoke(name, []);
  1365. tensor.__setstate__([ storage, storage_offset, size, stride ]);
  1366. return tensor;
  1367. });
  1368. this.registerFunction('torch._utils._rebuild_tensor_v2', function (storage, storage_offset, size, stride, requires_grad, backward_hooks) {
  1369. const name = storage.__class__.__module__ + '.' + storage.__class__.__name__.replace('Storage', 'Tensor');
  1370. const tensor = self.invoke(name, []);
  1371. tensor.__setstate__([ storage, storage_offset, size, stride ]);
  1372. tensor.requires_grad = requires_grad;
  1373. tensor.backward_hooks = backward_hooks;
  1374. return tensor;
  1375. });
  1376. this.registerFunction('torch._utils._rebuild_parameter', function(data, requires_grad, backward_hooks) {
  1377. const obj = self.invoke('torch.nn.parameter.Parameter', [ data, requires_grad ]);
  1378. obj.backward_hooks = backward_hooks;
  1379. return obj;
  1380. });
  1381. this.registerFunction('torch._utils._rebuild_qtensor', function(storage, storage_offset, size, stride, quantizer_params, requires_grad, backward_hooks) {
  1382. const name = storage.__class__.__module__ + '.' + storage.__class__.__name__.replace('Storage', 'Tensor');
  1383. const tensor = self.invoke(name, []);
  1384. tensor.__setstate__([ storage, storage_offset, size, stride ]);
  1385. tensor.quantizer_params = quantizer_params;
  1386. tensor.requires_grad = requires_grad;
  1387. tensor.backward_hooks = backward_hooks;
  1388. return tensor;
  1389. });
  1390. this.registerFunction('torch._set_item', function(dict, key, value) {
  1391. dict[key] = value;
  1392. });
  1393. this.registerFunction('torch.__and__', function(left, right) {
  1394. return left && right;
  1395. });
  1396. this.registerFunction('torch.__contains__', function(dict, key) {
  1397. return dict[key] !== undefined;
  1398. });
  1399. this.registerFunction('torch.__derive_index', function(index, start, step) {
  1400. return start + index * step;
  1401. });
  1402. this.registerFunction('torch.__is__', function(left, right) {
  1403. if (left === null && right === null) {
  1404. return true;
  1405. }
  1406. if ((left !== null && right === null) || (left === null && right !== null)) {
  1407. return false;
  1408. }
  1409. throw new pytorch.Error("Unsupported 'torch.__is__' expression type.");
  1410. });
  1411. this.registerFunction('torch.__isnot__', function(left, right) {
  1412. if (left === null && right === null) {
  1413. return false;
  1414. }
  1415. if ((left !== null && right === null) || (left === null && right !== null)) {
  1416. return true;
  1417. }
  1418. throw new pytorch.Error("Unsupported 'torch.__isnot__' expression type.");
  1419. });
  1420. this.registerFunction('torch.__not__', function(value) {
  1421. if (typeof value === 'boolean') {
  1422. return !value;
  1423. }
  1424. throw new pytorch.Error("Unsupported 'torch.__not__' expression type.");
  1425. });
  1426. this.registerFunction('torch.__range_length', function(lo, hi, step) {
  1427. if (step === 0) {
  1428. throw new pytorch.Error('range() arg 3 must not be zero');
  1429. }
  1430. if (step > 0 && lo < hi) {
  1431. return 1 + (hi - 1 - lo) / step;
  1432. }
  1433. else if (step < 0 && lo > hi) {
  1434. return 1 + (lo - 1 - hi) / (0 - step);
  1435. }
  1436. return 0;
  1437. });
  1438. this.registerFunction('torch._unwrap_optional', function(value) {
  1439. return value; // TODO
  1440. });
  1441. this.registerFunction('torch.add', function(left, right) {
  1442. if (typeof left === 'number' && typeof right === 'number') {
  1443. return left * right;
  1444. }
  1445. if (Array.isArray(left) && Array.isArray(right)) {
  1446. return left.concat(right);
  1447. }
  1448. if (typeof left === 'string' && typeof right === 'string') {
  1449. return left + right;
  1450. }
  1451. throw new pytorch.Error('Unsupported torch.add expression type.');
  1452. });
  1453. this.registerFunction('torch.append', function(list, value) {
  1454. list.push(value);
  1455. return value;
  1456. });
  1457. this.registerFunction('torch.extend', function(list, value) {
  1458. list.push(...value);
  1459. });
  1460. this.registerFunction('torch.insert', function(list, index, value) {
  1461. list.splice(index, 0, value);
  1462. return value;
  1463. });
  1464. this.registerFunction('torch.clear', function(value) {
  1465. if (Object(value) === value) {
  1466. for (const key of Object.keys(value)) {
  1467. delete value[key];
  1468. }
  1469. }
  1470. });
  1471. this.registerFunction('torch.replace', function(value) {
  1472. return value;
  1473. });
  1474. this.registerFunction('torch.dict', function(args) {
  1475. const obj = {};
  1476. if (args) {
  1477. if (Array.isArray(args)) {
  1478. for (const pair of args) {
  1479. const key = pair[0];
  1480. const value = pair[1];
  1481. obj[key] = value;
  1482. }
  1483. }
  1484. else {
  1485. throw new pytorch.Error("'torch.dict' arguments not supported.");
  1486. }
  1487. }
  1488. return obj;
  1489. });
  1490. this.registerFunction('torch.dim', function(tensor) {
  1491. if (tensor && tensor.size) {
  1492. const size = tensor.size();
  1493. if (size) {
  1494. return size.length;
  1495. }
  1496. }
  1497. return undefined; // TODO
  1498. });
  1499. this.registerFunction('torch.numel', function(tensor) {
  1500. if (tensor && tensor.size) {
  1501. const size = tensor.size();
  1502. if (size) {
  1503. return size.reduce((a, b) => a * b, 1);
  1504. }
  1505. }
  1506. return NaN;
  1507. });
  1508. this.registerFunction('torch.eq', function(left, right) {
  1509. if (typeof left === 'string' && typeof right === 'string') {
  1510. return left === right;
  1511. }
  1512. if (typeof left === 'number' && typeof right === 'number') {
  1513. if (isNaN(left) && isNaN(right)) {
  1514. return true;
  1515. }
  1516. return left === right;
  1517. }
  1518. if (left === undefined || right === undefined) {
  1519. return true;
  1520. }
  1521. if (Array.isArray(left) && Array.isArray(right)) {
  1522. return left.length === right.length && left.every((item, index) => item === right[index]);
  1523. }
  1524. throw new pytorch.Error("Unsupported 'torch.eq' expression type.");
  1525. });
  1526. this.registerFunction('torch.floor', function(value) {
  1527. return Math.floor(value);
  1528. });
  1529. this.registerFunction('torch.ceil', function(value) {
  1530. return Math.ceil(value);
  1531. });
  1532. this.registerFunction('torch.floordiv', function(left, right) {
  1533. return Math.floor(left / right);
  1534. });
  1535. this.registerFunction('torch.format', function() {
  1536. const args = Array.from(arguments);
  1537. const list = args.shift().split(/({}D?)/);
  1538. return list.map((text) => {
  1539. if (text === '{}' || text === '{}D') {
  1540. const arg = args.shift();
  1541. return Array.isArray(arg) ? '[' + arg.map((item) => item.toString()).join(', ') + ']' : arg ? arg.toString() : '?';
  1542. }
  1543. return text;
  1544. }).join('');
  1545. });
  1546. this.registerFunction('torch.gt', function(left, right) {
  1547. if (typeof left === 'number' && typeof right === 'number') {
  1548. if (!isNaN(left) && !isNaN(right)) {
  1549. return left > right;
  1550. }
  1551. }
  1552. if (isNaN(left) && !isNaN(right)) {
  1553. return true;
  1554. }
  1555. throw new pytorch.Error("Unsupported 'torch.gt' expression type.");
  1556. });
  1557. this.registerFunction('torch.ge', function(left, right) {
  1558. if (typeof left === 'number' && typeof right === 'number') {
  1559. if (!isNaN(left) && !isNaN(right)) {
  1560. return left > right;
  1561. }
  1562. }
  1563. if (isNaN(left) && !isNaN(right)) {
  1564. return true;
  1565. }
  1566. throw new pytorch.Error("Unsupported 'torch.ge' expression type.");
  1567. });
  1568. this.registerFunction('torch.is_floating_point', function(tensor) {
  1569. const type = tensor.dtype.scalar_type();
  1570. return (type === 5 || type === 6 || type === 7);
  1571. });
  1572. this.registerFunction('torch.jit._pickle.build_boollist', function(data) {
  1573. return data;
  1574. });
  1575. this.registerFunction('torch.jit._pickle.build_doublelist', function(data) {
  1576. return data;
  1577. });
  1578. this.registerFunction('torch.jit._pickle.build_intlist', function(data) {
  1579. return data;
  1580. });
  1581. this.registerFunction('torch.jit._pickle.build_tensorlist', function(data) {
  1582. return data;
  1583. });
  1584. this.registerFunction('torch.jit._pickle.build_tensor_from_id', function(data) {
  1585. const constants = self.context.getx('CONSTANTS');
  1586. return constants['c' + data.toString()];
  1587. });
  1588. this.registerFunction('torch.jit._pickle.restore_type_tag', function(value /*, type_str */) {
  1589. return value;
  1590. });
  1591. this.registerFunction('torch.keys', function(dict) {
  1592. return Object.keys(dict);
  1593. });
  1594. this.registerFunction('torch.len', function(value) {
  1595. if (Array.isArray(value)) {
  1596. return value.length;
  1597. }
  1598. if (value && value.shape && value.__len__) {
  1599. return value.__len__();
  1600. }
  1601. return NaN;
  1602. });
  1603. this.registerFunction('torch.le', function(left, right) {
  1604. if (typeof left === 'number' && typeof right === 'number') {
  1605. if (isNaN(left) || isNaN(right)) {
  1606. return false;
  1607. }
  1608. return left <= right;
  1609. }
  1610. if (left === undefined || right === undefined) {
  1611. return true;
  1612. }
  1613. throw new pytorch.Error("Unsupported 'torch.le' expression type.");
  1614. });
  1615. this.registerFunction('torch.list', function(args) {
  1616. return args;
  1617. });
  1618. this.registerFunction('torch.list_with_default', function(size /*, defaults */) {
  1619. return size;
  1620. });
  1621. this.registerFunction('torch.lt', function(left, right) {
  1622. if (typeof left === 'number' && typeof right === 'number') {
  1623. return left < right;
  1624. }
  1625. throw new pytorch.Error("Unsupported 'torch.lt' expression type.");
  1626. });
  1627. this.registerFunction('torch.mul', function(left, right) {
  1628. if (typeof left === 'number' && typeof right === 'number') {
  1629. return left * right;
  1630. }
  1631. if (isNaN(left) || isNaN(right)) {
  1632. return NaN;
  1633. }
  1634. if (Array.isArray(left) && left.every((value) => typeof value === 'number') && typeof right === 'number') {
  1635. return left.map((value) => value * right);
  1636. }
  1637. throw new pytorch.Error("Unsupported 'torch.mul' expression type.");
  1638. });
  1639. this.registerFunction('torch.div', function(left, right) {
  1640. if (typeof left === 'number' && typeof right === 'number') {
  1641. return left / right;
  1642. }
  1643. if (isNaN(left) || isNaN(right)) {
  1644. return NaN;
  1645. }
  1646. throw new pytorch.Error("Unsupported 'torch.div' expression type.");
  1647. });
  1648. this.registerFunction('torch.remainder', function(left, right) {
  1649. if (typeof left === 'number' && typeof right === 'number') {
  1650. return left % right;
  1651. }
  1652. if (isNaN(left) || isNaN(right)) {
  1653. return NaN;
  1654. }
  1655. throw new pytorch.Error("Unsupported 'torch.remainder' expression type.");
  1656. });
  1657. this.registerFunction('torch.ne', function(left, right) {
  1658. if (typeof left === 'number' && typeof right === 'number') {
  1659. if (isNaN(left) || isNaN(right)) {
  1660. return false;
  1661. }
  1662. return left !== right;
  1663. }
  1664. if (Array.isArray(left) && Array.isArray(right) && left.length === right.length) {
  1665. return false;
  1666. }
  1667. if (typeof left === 'string' && typeof right === 'string') {
  1668. return left !== right;
  1669. }
  1670. if (left === undefined || right === undefined) {
  1671. return true;
  1672. }
  1673. throw new pytorch.Error("Unsupported 'torch.ne' expression type.");
  1674. });
  1675. this.registerFunction('torch.neg', function(value) {
  1676. if (typeof value === 'number') {
  1677. return -value;
  1678. }
  1679. throw new pytorch.Error("Unsupported 'torch.neg' expression type.");
  1680. });
  1681. this.registerFunction('torch.q_scale', function(/* tensor */) {
  1682. return -1; // TODO
  1683. });
  1684. this.registerFunction('torch.t', function(tensor) {
  1685. return tensor;
  1686. });
  1687. this.registerFunction('torch.size', function(tensor, dim) {
  1688. if (tensor && tensor.size) {
  1689. const size = tensor.size();
  1690. if (Array.isArray(size)) {
  1691. if (dim === undefined) {
  1692. return size;
  1693. }
  1694. if (Number.isInteger(dim)) {
  1695. if (dim >= 0 && dim < size.length) {
  1696. return size[dim];
  1697. }
  1698. if (dim < 0 && -dim < size.length) {
  1699. return size[size.length + dim];
  1700. }
  1701. }
  1702. throw new pytorch.Error('Dimension out of range (expected to be in range of ' + JSON.stringify(size) + ', but got ' + JSON.stringify(dim) + ').');
  1703. }
  1704. }
  1705. if (Number.isInteger(dim)) {
  1706. return NaN;
  1707. }
  1708. return [];
  1709. });
  1710. this.registerFunction('torch.slice', function(l, start, end, step) {
  1711. if (!Array.isArray(l)) {
  1712. throw new pytorch.Error('Slicing expected array');
  1713. }
  1714. step = step || 1;
  1715. if (step !== 1) {
  1716. throw new pytorch.Error('Slicing only supports step=1');
  1717. }
  1718. start = Math.max(0, start >= 0 ? start : l.length + start);
  1719. end = Math.min(l.length, end || Number.MAX_SAFE_INTEGER);
  1720. return l.slice(start, end);
  1721. });
  1722. this.registerFunction('torch.sub', function(left, right) {
  1723. if (typeof left === 'number' && typeof right === 'number') {
  1724. return left - right;
  1725. }
  1726. throw new pytorch.Error("Unsupported 'torch.sub' expression type.");
  1727. });
  1728. this.registerFunction('torch.values', function(dict) {
  1729. return Object.keys(dict).map((key) => dict[key]);
  1730. });
  1731. this.registerFunction('torch.warn', function() {
  1732. });
  1733. this.registerFunction('uninitialized', function(/* type */) {
  1734. return undefined;
  1735. });
  1736. this.registerType('torch.device', class {
  1737. constructor(type, index) {
  1738. this.type = type;
  1739. if (index) {
  1740. this.index = index;
  1741. }
  1742. }
  1743. });
  1744. this.registerType('torch.dtype', class {
  1745. constructor(type) {
  1746. this._type = type;
  1747. this._data = pytorch.Utility.getScalarType(type);
  1748. }
  1749. scalar_type() {
  1750. return this._type;
  1751. }
  1752. itemsize() {
  1753. return this._data.itemsize;
  1754. }
  1755. __reduce__() {
  1756. return this._data.name;
  1757. }
  1758. __str__() {
  1759. return 'torch.' + this._data.name;
  1760. }
  1761. });
  1762. this.registerType('torch.utils.hooks.RemovableHandle', class {
  1763. __setstate__(state) {
  1764. this.hooks_dict_ref = state[0] || new Map();
  1765. this.id = state[1];
  1766. }
  1767. });
  1768. this.registerType('torch.storage._StorageBase', class {
  1769. constructor(size, dtype) {
  1770. this._size = size;
  1771. this._dtype = dtype;
  1772. this._device = null;
  1773. }
  1774. get device() {
  1775. return null;
  1776. }
  1777. get dtype() {
  1778. return this._dtype;
  1779. }
  1780. get data() {
  1781. return this._cdata;
  1782. }
  1783. element_size() {
  1784. return this._dtype.element_size;
  1785. }
  1786. size() {
  1787. return this._size;
  1788. }
  1789. _set_cdata(data) {
  1790. const length = this.size() * this.dtype.itemsize();
  1791. if (length !== data.length) {
  1792. throw new pytorch.Error('Storage data size mismatch.');
  1793. }
  1794. this._cdata = data;
  1795. }
  1796. _set_from_file(unpickler) {
  1797. const size = unpickler.int64();
  1798. if (size !== this.size()) {
  1799. throw new pytorch.Error('Storage size mismatch.');
  1800. }
  1801. const itemsize = this.dtype.itemsize();
  1802. const data = unpickler.stream(itemsize * size);
  1803. this._set_cdata(data);
  1804. }
  1805. static _new_with_file(unpickler) {
  1806. const size = unpickler.int64();
  1807. const storage = new this(size);
  1808. const itemsize = storage.dtype.itemsize();
  1809. const data = unpickler.stream(itemsize * size);
  1810. storage._set_cdata(data);
  1811. return storage;
  1812. }
  1813. });
  1814. this.registerType('torch.BoolStorage', class extends torch.storage._StorageBase {
  1815. constructor(size) {
  1816. super(size, torch.bool);
  1817. }
  1818. });
  1819. this.registerType('torch.ByteStorage', class extends torch.storage._StorageBase {
  1820. constructor(size) {
  1821. super(size, torch.uint8);
  1822. }
  1823. });
  1824. this.registerType('torch.CharStorage', class extends torch.storage._StorageBase {
  1825. constructor(size) {
  1826. super(size, torch.int8);
  1827. }
  1828. });
  1829. this.registerType('torch.ShortStorage', class extends torch.storage._StorageBase {
  1830. constructor(size) {
  1831. super(size, torch.int16);
  1832. }
  1833. });
  1834. this.registerType('torch.IntStorage', class extends torch.storage._StorageBase {
  1835. constructor(size) {
  1836. super(size, torch.int32);
  1837. }
  1838. });
  1839. this.registerType('torch.LongStorage', class extends torch.storage._StorageBase {
  1840. constructor(size) {
  1841. super(size, torch.int64);
  1842. }
  1843. });
  1844. this.registerType('torch.HalfStorage', class extends torch.storage._StorageBase {
  1845. constructor(size) {
  1846. super(size, torch.float16);
  1847. }
  1848. });
  1849. this.registerType('torch.FloatStorage', class extends torch.storage._StorageBase {
  1850. constructor(size) {
  1851. super(size, torch.float32);
  1852. }
  1853. });
  1854. this.registerType('torch.DoubleStorage', class extends torch.storage._StorageBase {
  1855. constructor(size) {
  1856. super(size, torch.float64);
  1857. }
  1858. });
  1859. this.registerType('torch.QInt8Storage', class extends torch.storage._StorageBase {
  1860. constructor(size) {
  1861. super(size, torch.qint8);
  1862. }
  1863. });
  1864. this.registerType('torch.QUInt8Storage', class extends torch.storage._StorageBase {
  1865. constructor(size) {
  1866. super(size, torch.quint8);
  1867. }
  1868. });
  1869. this.registerType('torch.QInt32Storage', class extends torch.storage._StorageBase {
  1870. constructor(size) {
  1871. super(size, torch.qint32);
  1872. }
  1873. });
  1874. this.registerType('torch.BFloat16Storage', class extends torch.storage._StorageBase {
  1875. constructor(size) {
  1876. super(size, torch.bfloat16);
  1877. }
  1878. });
  1879. this.registerType('torch.Size', class extends Array {
  1880. constructor(size) {
  1881. super(size.length);
  1882. for (let i = 0; i < size.length; i++) {
  1883. this[i] = size[i];
  1884. }
  1885. }
  1886. __len__() {
  1887. return this.length;
  1888. }
  1889. });
  1890. this.registerType('torch.Tensor', class {
  1891. constructor() {
  1892. }
  1893. get device() {
  1894. return this.storage().device;
  1895. }
  1896. get dtype() {
  1897. return this.storage().dtype;
  1898. }
  1899. get shape() {
  1900. return this._shape;
  1901. }
  1902. size() {
  1903. return this._shape;
  1904. }
  1905. storage() {
  1906. if (!this._storage) {
  1907. const name = this.__class__.__name__ == 'Tensor' ? 'FloatStorage' : this.__storage__.__name__.replace('Tensor', 'Storage');
  1908. this._storage = self.invoke(this.__class__.__module__ + '.' + name, []);
  1909. }
  1910. return this._storage;
  1911. }
  1912. storage_offset() {
  1913. return this._storage_offset;
  1914. }
  1915. stride() {
  1916. return this._stride;
  1917. }
  1918. resize_(shape) {
  1919. this._shape = shape;
  1920. }
  1921. __len__() {
  1922. return this._shape[0];
  1923. }
  1924. __setstate__(state) {
  1925. this._storage = state[0];
  1926. this._storage_offset = state[1];
  1927. this._shape = state[2];
  1928. this._stride = state[3];
  1929. }
  1930. });
  1931. this.registerType('torch.nn.parameter.Parameter', class extends torch.Tensor {
  1932. constructor(data, requires_grad) {
  1933. super();
  1934. if (!data) {
  1935. data = self.invoke('torch.Tensor', [[]]);
  1936. }
  1937. this.data = data;
  1938. this.requires_grad = requires_grad !== undefined ? requires_grad : true;
  1939. }
  1940. __setstate__(state) {
  1941. switch (state.length) {
  1942. case 3:
  1943. this.data = null;
  1944. break;
  1945. case 4:
  1946. this.data = state[0];
  1947. break;
  1948. case 5:
  1949. this.data = state[0];
  1950. break;
  1951. default:
  1952. throw new pytorch.Error("Unsupported parameter state length '" + state.length + "'.");
  1953. }
  1954. }
  1955. });
  1956. this.registerType('torch.nn.parameter.UninitializedParameter', class extends torch.nn.parameter.Parameter {
  1957. constructor(requires_grad /*, device, dtype */) {
  1958. super(undefined, requires_grad);
  1959. }
  1960. });
  1961. this.registerType('torch.BoolTensor', class extends torch.Tensor {});
  1962. this.registerType('torch.ByteTensor', class extends torch.Tensor {});
  1963. this.registerType('torch.CharTensor', class extends torch.Tensor {});
  1964. this.registerType('torch.ShortTensor', class extends torch.Tensor {});
  1965. this.registerType('torch.IntTensor', class extends torch.Tensor {});
  1966. this.registerType('torch.LongTensor', class extends torch.Tensor {});
  1967. this.registerType('torch.HalfTensor', class extends torch.Tensor {});
  1968. this.registerType('torch.FloatTensor', class extends torch.Tensor {});
  1969. this.registerType('torch.DoubleTensor', class extends torch.Tensor {});
  1970. this.registerType('torch.QInt8Tensor', class extends torch.Tensor {});
  1971. this.registerType('torch.QUInt8Tensor', class extends torch.Tensor {});
  1972. this.registerType('torch.QInt32Tensor', class extends torch.Tensor {});
  1973. this.registerType('torch.BFloat16Tensor', class extends torch.Tensor {});
  1974. this.registerType('torch.cuda.FloatTensor', class extends torch.Tensor {});
  1975. this.registerType('torch.cuda.DoubleTensor', class extends torch.Tensor {});
  1976. torch.uint8 = new torch.dtype(pytorch.ScalarType.uint8);
  1977. torch.int8 = new torch.dtype(pytorch.ScalarType.int8);
  1978. torch.int16 = new torch.dtype(pytorch.ScalarType.int16);
  1979. torch.int32 = new torch.dtype(pytorch.ScalarType.int32);
  1980. torch.int64 = new torch.dtype(pytorch.ScalarType.int64);
  1981. torch.float16 = new torch.dtype(pytorch.ScalarType.float16);
  1982. torch.float32 = new torch.dtype(pytorch.ScalarType.float32);
  1983. torch.float64 = new torch.dtype(pytorch.ScalarType.float64);
  1984. torch.complex32 = new torch.dtype(pytorch.ScalarType.complex32);
  1985. torch.complex64 = new torch.dtype(pytorch.ScalarType.complex64);
  1986. torch.complex128 = new torch.dtype(pytorch.ScalarType.complex128);
  1987. torch.bool = new torch.dtype(pytorch.ScalarType.boolean);
  1988. torch.qint8 = new torch.dtype(pytorch.ScalarType.qint8);
  1989. torch.quint8 = new torch.dtype(pytorch.ScalarType.quint8);
  1990. torch.qint32 = new torch.dtype(pytorch.ScalarType.qint32);
  1991. torch.bfloat16 = new torch.dtype(pytorch.ScalarType.bfloat16);
  1992. }
  1993. debug(file) {
  1994. const buffer = this.source(file + '.debug_pkl');
  1995. if (buffer) {
  1996. return null;
  1997. // const unpickler = python.Unpickler.open(buffer);
  1998. // return unpickler.load((name, args) => this.invoke(name, args), null);
  1999. }
  2000. return null;
  2001. }
  2002. };
  2003. pytorch.Container = class {
  2004. static open(context) {
  2005. const zip = pytorch.Container.Zip.open(context.entries('zip'));
  2006. if (zip) {
  2007. return zip;
  2008. }
  2009. const pickle = pytorch.Container.Pickle.open(context.stream);
  2010. if (pickle) {
  2011. return pickle;
  2012. }
  2013. const tar = pytorch.Container.Tar.open(context.entries('tar'));
  2014. if (tar) {
  2015. return tar;
  2016. }
  2017. return null;
  2018. }
  2019. };
  2020. pytorch.Container.Tar = class {
  2021. static open(entries) {
  2022. if (entries.has('pickle')) {
  2023. return new pytorch.Container.Tar(entries);
  2024. }
  2025. return null;
  2026. }
  2027. constructor(entries) {
  2028. this._entries = entries;
  2029. }
  2030. set metadata(value) {
  2031. this._metadata = value;
  2032. }
  2033. set exception(value) {
  2034. this._exceptionCallack = value;
  2035. }
  2036. get format() {
  2037. return 'PyTorch v0.1.1';
  2038. }
  2039. get type() {
  2040. this._unpickle();
  2041. return this._type;
  2042. }
  2043. get data() {
  2044. this._unpickle();
  2045. return this._data;
  2046. }
  2047. get littleEndian() {
  2048. this._unpickle();
  2049. return this._littleEndian;
  2050. }
  2051. _unpickle() {
  2052. if (!this._entries) {
  2053. return;
  2054. }
  2055. this._type = '';
  2056. this._data = null;
  2057. this._littleEndian = true;
  2058. const execution = new pytorch.Execution(null, this._exceptionCallback);
  2059. const entries = {};
  2060. for (const entry of this._entries) {
  2061. const key = entry[0];
  2062. const value = entry[1];
  2063. entries[key] = value.peek();
  2064. }
  2065. this._exceptionCallback = null;
  2066. this._entries = null;
  2067. if (entries.sys_info) {
  2068. const unpickler = python.Unpickler.open(entries.sys_info);
  2069. const sys_info = unpickler.load((name, args) => execution.invoke(name, args));
  2070. if (sys_info.protocol_version != 1000) {
  2071. throw new pytorch.Error("Unsupported protocol version '" + sys_info.protocol_version + "'.");
  2072. }
  2073. if (sys_info.type_sizes &&
  2074. ((sys_info.type_sizes.int && sys_info.type_sizes.int != 4) ||
  2075. (sys_info.type_sizes.long && sys_info.type_sizes.long != 4) ||
  2076. (sys_info.type_sizes.short && sys_info.type_sizes.short != 2))) {
  2077. throw new pytorch.Error('Unsupported type sizes.');
  2078. }
  2079. this._littleEndian = sys_info.little_endian;
  2080. }
  2081. const deserialized_objects = {};
  2082. if (entries.storages) {
  2083. const unpickler = python.Unpickler.open(entries.storages);
  2084. const num_storages = unpickler.load((name, args) => execution.invoke(name, args));
  2085. for (let i = 0; i < num_storages; i++) {
  2086. const args = unpickler.load();
  2087. const key = args[0];
  2088. const storage_type = execution.type(args[2]);
  2089. const obj = storage_type._new_with_file(unpickler);
  2090. deserialized_objects[key] = obj;
  2091. }
  2092. /*
  2093. let storage_views = unpickler.load();
  2094. for target_cdata, root_cdata, offset, size in storage_views:
  2095. root = deserialized_objects[root_cdata]
  2096. deserialized_objects[target_cdata] = root[offset:offset + size]
  2097. */
  2098. }
  2099. if (entries.tensors) {
  2100. const unpickler = python.Unpickler.open(entries.tensors);
  2101. const num_tensors = unpickler.load((name, args) => execution.invoke(name, args));
  2102. for (let i = 0; i < num_tensors; i++) {
  2103. const args = unpickler.load();
  2104. const key = args[0];
  2105. const storage_id = args[1];
  2106. const storage = deserialized_objects[storage_id];
  2107. const ndim = unpickler.int32();
  2108. unpickler.read(4);
  2109. const shape = new Array(ndim);
  2110. for (let j = 0; j < ndim; j++) {
  2111. shape[j] = unpickler.int64();
  2112. }
  2113. const stride = new Array(ndim);
  2114. for (let j = 0; j < ndim; j++) {
  2115. stride[j] = unpickler.int64();
  2116. }
  2117. const storage_offset = unpickler.int64();
  2118. const tensor = execution.invoke('torch._utils._rebuild_tensor', [ storage, storage_offset, shape, stride ]);
  2119. deserialized_objects[key] = tensor;
  2120. }
  2121. }
  2122. if (entries.pickle) {
  2123. const unpickler = python.Unpickler.open(entries.pickle);
  2124. const persistent_load = (saved_id) => {
  2125. return deserialized_objects[saved_id];
  2126. };
  2127. const obj = unpickler.load((name, args) => execution.invoke(name, args), persistent_load);
  2128. const weights = pytorch.Utility.findWeights(obj);
  2129. if (weights) {
  2130. this._type = 'weights';
  2131. this._data = weights;
  2132. }
  2133. else {
  2134. throw new pytorch.Error('File does not contain root module or state dictionary.');
  2135. }
  2136. }
  2137. }
  2138. };
  2139. pytorch.Container.Pickle = class {
  2140. static open(stream) {
  2141. const signature = [ 0x80, undefined, 0x8a, 0x0a, 0x6c, 0xfc, 0x9c, 0x46, 0xf9, 0x20, 0x6a, 0xa8, 0x50, 0x19 ];
  2142. if (stream && signature.length <= stream.length && stream.peek(signature.length).every((value, index) => signature[index] === undefined || signature[index] === value)) {
  2143. return new pytorch.Container.Pickle(stream);
  2144. }
  2145. return null;
  2146. }
  2147. constructor(stream) {
  2148. this._stream = stream;
  2149. }
  2150. set metadata(value) {
  2151. this._metadata = value;
  2152. }
  2153. set exception(value) {
  2154. this._exceptionCallback = value;
  2155. }
  2156. get format() {
  2157. return 'PyTorch v0.1.10';
  2158. }
  2159. get type() {
  2160. this._unpickle();
  2161. return this._type;
  2162. }
  2163. get data() {
  2164. this._unpickle();
  2165. return this._data;
  2166. }
  2167. get littleEndian() {
  2168. this._unpickle();
  2169. return this._littleEndian;
  2170. }
  2171. _unpickle() {
  2172. if (!this._stream) {
  2173. return;
  2174. }
  2175. const execution = new pytorch.Execution(null, this._exceptionCallback);
  2176. const unpickler = python.Unpickler.open(this._stream.length < 0x7ffff000 ? this._stream.peek() : this._stream);
  2177. this._stream = null;
  2178. this._exceptionCallback = null;
  2179. unpickler.load(); // magic_number
  2180. const protocol_version = unpickler.load();
  2181. if (protocol_version != 1001) {
  2182. throw new pytorch.Error("Unsupported protocol version '" + protocol_version + "'.");
  2183. }
  2184. const sys_info = unpickler.load();
  2185. if (sys_info.protocol_version != 1001) {
  2186. throw new pytorch.Error("Unsupported protocol version '" + sys_info.protocol_version + "'.");
  2187. }
  2188. this._littleEndian = sys_info.little_endian;
  2189. const module_source_map = new Map();
  2190. const deserialized_objects = new Map();
  2191. const persistent_load = (saved_id) => {
  2192. const typename = saved_id.shift();
  2193. const data = saved_id;
  2194. switch (typename) {
  2195. case 'module': {
  2196. const module = data[0];
  2197. const source = data[2];
  2198. module_source_map.set(module, source);
  2199. return data[0];
  2200. }
  2201. case 'storage': {
  2202. const data_type = execution.type(data.shift());
  2203. const root_key = data.shift();
  2204. data.shift(); // location
  2205. const size = data.shift();
  2206. const view_metadata = data.shift();
  2207. if (!deserialized_objects.has(root_key)) {
  2208. const obj = new data_type(size);
  2209. deserialized_objects.set(root_key, obj);
  2210. }
  2211. if (view_metadata) {
  2212. const view_key = view_metadata.shift();
  2213. view_metadata.shift(); // view_offset
  2214. view_metadata.shift(); // view_size
  2215. if (!deserialized_objects.has(view_key)) {
  2216. const view = null; // storage.slice(view_offset, view_offset + view_size);
  2217. deserialized_objects.set(view_key, view);
  2218. }
  2219. return deserialized_objects.get(view_key);
  2220. }
  2221. return deserialized_objects.get(root_key);
  2222. }
  2223. default: {
  2224. throw new pytorch.Error("Unsupported persistent load type '" + typename + "'.");
  2225. }
  2226. }
  2227. };
  2228. const obj = unpickler.load((name, args) => execution.invoke(name, args), persistent_load);
  2229. if (!obj) {
  2230. throw new pytorch.Error('File format is not PyTorch.');
  2231. }
  2232. if (obj === 'None') {
  2233. throw new pytorch.Error("File contains 'None' root object.");
  2234. }
  2235. const deserialized_storage_keys = unpickler.load();
  2236. for (const deserialized_storage_key of deserialized_storage_keys) {
  2237. const storage = deserialized_objects.get(deserialized_storage_key);
  2238. storage._set_from_file(unpickler);
  2239. }
  2240. const root = pytorch.Utility.findModule(obj);
  2241. if (root) {
  2242. this._type = 'module';
  2243. this._data = root;
  2244. }
  2245. else {
  2246. const weights = pytorch.Utility.findWeights(obj);
  2247. if (weights) {
  2248. this._type = 'weights';
  2249. this._data = weights;
  2250. }
  2251. else {
  2252. throw new pytorch.Error('File does not contain root module or state dictionary.');
  2253. }
  2254. }
  2255. }
  2256. };
  2257. pytorch.Container.Zip = class {
  2258. static open(entries) {
  2259. const name = Array.from(entries.keys()).find((name) => name == 'model.json' || name == 'data.pkl' || name.endsWith('/model.json') || name.endsWith('/data.pkl'));
  2260. if (!name) {
  2261. return null;
  2262. }
  2263. let model = null;
  2264. if (name.endsWith('.json')) {
  2265. try {
  2266. const stream = entries.get(name);
  2267. const buffer = stream.peek();
  2268. const decoder = new TextDecoder('utf-8');
  2269. const content = decoder.decode(buffer);
  2270. model = JSON.parse(content);
  2271. if (!model.mainModule) {
  2272. return null;
  2273. }
  2274. }
  2275. catch (error) {
  2276. return null;
  2277. }
  2278. }
  2279. return new pytorch.Container.Zip(entries, name, model);
  2280. }
  2281. constructor(entries, name, model) {
  2282. this._entries = entries;
  2283. // https://github.com/pytorch/pytorch/blob/master/torch/csrc/jit/docs/serialization.md
  2284. this._model = model;
  2285. const lastIndex = name.lastIndexOf('/');
  2286. this._prefix = lastIndex === -1 ? '' : name.substring(0, lastIndex + 1);
  2287. }
  2288. set metadata(value) {
  2289. this._metadata = value;
  2290. }
  2291. set exception(value) {
  2292. this._exceptionCallback = value;
  2293. }
  2294. get format() {
  2295. if (this._format === undefined) {
  2296. if (this._entry('model.json')) {
  2297. this._format = this._entry('attributes.pkl') ? 'TorchScript v1.1' : 'TorchScript v1.0';
  2298. }
  2299. else if (this._entry('data.pkl')) {
  2300. // https://github.com/pytorch/pytorch/blob/master/caffe2/serialize/inline_container.h
  2301. // kProducedFileFormatVersion
  2302. const versions = new Map([
  2303. [ '1', 'v1.3' ],
  2304. [ '2', 'v1.5' ], // 7a2889b014ce36fcc333b2c6de6f29f976652f84 (#28122)
  2305. [ '3', 'v1.6' ], // 2ec6a30722b0ef85632a2f3e7ce6f80da403008a (#36085)
  2306. [ '4', 'v1.6' ], // 95489b590f00801bdee7f41783f30874883cf6bb (#38620)
  2307. [ '5', 'v1.7' ], // cb26661fe4faf26386703180a9045e6ac6d157df (#40364)
  2308. [ '6', 'v1.9' ], // 3ee7637ffa50df0d9b231c7b40778ac1c390bf4a (#59714)
  2309. [ '7', 'v1.10' ] // 880098a7e34a20628f960daa8eab0eb1ad566c39 (#63651)
  2310. ]);
  2311. const value = this.version;
  2312. if (!versions.has(value)) {
  2313. this._exceptionCallback(new pytorch.Error("Unsupported PyTorch Zip version '" + value + "'."));
  2314. }
  2315. const version = versions.get(value);
  2316. const constants = this._entry('constants.pkl');
  2317. this._format = (constants ? 'TorchScript' : 'PyTorch') + ' ' + (version || 'v-' + value.toString() );
  2318. }
  2319. }
  2320. return this._format;
  2321. }
  2322. get version() {
  2323. const stream = this._entry('version');
  2324. if (stream) {
  2325. const decoder = new TextDecoder('utf-8');
  2326. const buffer = stream.peek();
  2327. const value = decoder.decode(buffer);
  2328. return value.split('\n').shift();
  2329. }
  2330. return '';
  2331. }
  2332. get producer() {
  2333. return this.data ? this._producer : '';
  2334. }
  2335. get name() {
  2336. return this._name;
  2337. }
  2338. get littleEndian() {
  2339. return true;
  2340. }
  2341. get type() {
  2342. this._load();
  2343. return this._type;
  2344. }
  2345. get data() {
  2346. this._load();
  2347. return this._data;
  2348. }
  2349. get constants() {
  2350. if (this._constants === undefined) {
  2351. this._constants = [];
  2352. const stream = this._entry('constants.pkl');
  2353. if (stream) {
  2354. const buffer = stream.peek();
  2355. this._constants = this._unpickle(buffer, this._storage('constants'));
  2356. for (let i = 0; i < this._constants.length; i++) {
  2357. const constant = this._constants[i];
  2358. const variable = 'CONSTANTS.c' + i.toString();
  2359. if (pytorch.Utility.isTensor(constant)) {
  2360. constant.__variable__ = variable;
  2361. }
  2362. else if (constant && constant.__class__ && constant.__class__.__module__ && constant.__class__.__name__) {
  2363. const type = constant.__class__.__module__ + '.' + constant.__class__.__name__;
  2364. switch (type) {
  2365. case '__torch__.torch.classes.xnnpack.LinearOpContext':
  2366. case '__torch__.torch.classes.xnnpack.Conv2dOpContext':
  2367. case '__torch__.torch.classes.quantized.LinearPackedParamsBase':
  2368. case '__torch__.torch.classes.quantized.Conv2dPackedParamsBase':
  2369. if (pytorch.Utility.isTensor(constant.weight)) {
  2370. constant.weight.__variable__ = variable + '.weight';
  2371. }
  2372. if (pytorch.Utility.isTensor(constant.bias)) {
  2373. constant.bias.__variable__ = variable + '.bias';
  2374. }
  2375. break;
  2376. default:
  2377. throw new pytorch.Error("Unsupported constant context '" + type + "'.");
  2378. }
  2379. }
  2380. else {
  2381. throw new pytorch.Error('Unsupported constant.');
  2382. }
  2383. }
  2384. }
  2385. }
  2386. return this._constants;
  2387. }
  2388. get execution() {
  2389. if (this._execution === undefined) {
  2390. const sources = new Map();
  2391. for (const entry of this._entries) {
  2392. const name = entry[0];
  2393. if (name.startsWith(this._prefix + 'code')) {
  2394. const file = name.substring(this._prefix.length);
  2395. if (sources.has(file)) {
  2396. throw new pytorch.Error("Duplicate source file '" + file + "'.");
  2397. }
  2398. const stream = entry[1];
  2399. const buffer = stream.peek();
  2400. sources.set(file, buffer);
  2401. }
  2402. }
  2403. this._execution = new pytorch.Container.Zip.Execution(sources, this._exceptionCallback, this._metadata);
  2404. const constants = {};
  2405. for (let i = 0; i < this.constants.length; i++) {
  2406. constants['c' + i.toString()] = this.constants[i];
  2407. }
  2408. this._execution.context.set('CONSTANTS', constants);
  2409. }
  2410. return this._execution;
  2411. }
  2412. _entry(name) {
  2413. return this._entries.get(this._prefix + name);
  2414. }
  2415. _load() {
  2416. if (this._data === undefined) {
  2417. this._data = null;
  2418. const stream = this._entry('data.pkl');
  2419. if (stream) {
  2420. const buffer = stream.peek();
  2421. this._data = this._unpickle(buffer, this._storage('data'));
  2422. }
  2423. else if (this._model) {
  2424. this._producer = this._model.producerName + (this._model.producerVersion ? ' v' + this._model.producerVersion : '');
  2425. this._data = this._model.mainModule || {};
  2426. this._name = this._data.name || '';
  2427. if (this._data.torchscriptArena) {
  2428. this._torchscriptArena = this._data.torchscriptArena.key;
  2429. }
  2430. const queue = [ this._data ];
  2431. const entries = new Map();
  2432. for (const entry of this._entries) {
  2433. const name = entry[0];
  2434. const stream = entry[1];
  2435. const buffer = stream.peek();
  2436. entries.set(name, buffer);
  2437. }
  2438. const tensorTypeMap = new Map([
  2439. [ 'FLOAT', 'Float' ],
  2440. [ 'FLOAT16', 'Half' ],
  2441. [ 'DOUBLE', 'Double' ],
  2442. [ 'INT8', 'Char' ],
  2443. [ 'INT32', 'Int' ],
  2444. [ 'INT64', 'Long' ]
  2445. ]);
  2446. const constants = this._model.tensors || [];
  2447. this._constants = constants.map((constant) => {
  2448. const key = this._prefix + constant.data.key;
  2449. if (!tensorTypeMap.has(constant.dataType)) {
  2450. throw new pytorch.Error("Unsupported tensor data type '" + constant.dataType + "'.");
  2451. }
  2452. const type = tensorTypeMap.get(constant.dataType);
  2453. const shape = constant.dims ? constant.dims.map((dim) => parseInt(dim, 10)) : null;
  2454. const storage_type = this.execution.type('torch.' + type + 'Storage');
  2455. const size = (shape || []).reduce((a, b) => a * b, 1);
  2456. const offset = parseInt(constant.offset, 10) || 0;
  2457. const storage = new storage_type([ size ]);
  2458. const itemsize = storage.dtype.itemsize();
  2459. const buffer = entries.get(key);
  2460. const length = size * itemsize;
  2461. const data = buffer.slice(offset, offset + length);
  2462. storage._set_cdata(data);
  2463. const tensor = this.execution.invoke('torch._utils._rebuild_tensor', [ storage, 0, shape, 0 ]);
  2464. tensor.name = constant.data.key;
  2465. return tensor;
  2466. });
  2467. this._attributes = [];
  2468. const stream = this._entry('attributes.pkl');
  2469. if (stream) {
  2470. const buffer = stream.peek();
  2471. const unpickler = python.Unpickler.open(buffer);
  2472. this._attributes.push(...unpickler.load((name, args) => this.execution.invoke(name, args)));
  2473. }
  2474. while (queue.length > 0) {
  2475. const module = queue.shift();
  2476. if (!module.__class__) {
  2477. module.__class__ = {
  2478. __module__: 'torch.nn.modules.module',
  2479. __name__: 'Module'
  2480. };
  2481. }
  2482. if (module.name) {
  2483. module.__id__ = module.name;
  2484. }
  2485. if (module.submodules) {
  2486. for (const submodule of module.submodules) {
  2487. module[submodule.name] = submodule;
  2488. submodule.__parent__ = module;
  2489. queue.push(submodule);
  2490. }
  2491. delete module.submodules;
  2492. }
  2493. const attributes = [];
  2494. if (module.attributes) {
  2495. attributes.push(...module.attributes);
  2496. delete module.attributes;
  2497. }
  2498. const parameters = [];
  2499. if (module.parameters) {
  2500. parameters.push(...module.parameters);
  2501. delete module.parameters;
  2502. }
  2503. if (module.arguments) {
  2504. parameters.push(...module.arguments);
  2505. delete module.arguments;
  2506. }
  2507. for (const parameter of parameters) {
  2508. const tensor = this._constants[parameter.tensorId];
  2509. module[parameter.name] = tensor;
  2510. if (!parameter.__class__) {
  2511. parameter.__class__ = {
  2512. __module__: 'torch',
  2513. __name__: 'Tensor'
  2514. };
  2515. }
  2516. }
  2517. for (const attribute of attributes) {
  2518. module[attribute.name] = this._attributes[attribute.id];
  2519. }
  2520. }
  2521. delete this._model;
  2522. }
  2523. if (this.format.startsWith('TorchScript ') && (this._torchscriptArena || this._data.forward)) {
  2524. this._type = 'script';
  2525. return;
  2526. }
  2527. const root = pytorch.Utility.findModule(this._data);
  2528. if (root) {
  2529. this._type = 'module';
  2530. this._data = root;
  2531. }
  2532. else {
  2533. const weights = pytorch.Utility.findWeights(this._data);
  2534. if (weights) {
  2535. this._type = 'weights';
  2536. this._data = weights;
  2537. }
  2538. else {
  2539. throw new pytorch.Error('File does not contain root module or state dictionary.');
  2540. }
  2541. }
  2542. }
  2543. }
  2544. _unpickle(data, storage_map) {
  2545. const loaded_storages = new Map();
  2546. const persistent_load = (saved_id) => {
  2547. const typename = saved_id.shift();
  2548. if (typename !== 'storage') {
  2549. throw new pytorch.Error("Unsupported persistent load type '" + typename + "'.");
  2550. }
  2551. const name = saved_id.shift();
  2552. const data_type = this.execution.type(name);
  2553. const root_key = saved_id.shift();
  2554. /* const location = */ saved_id.shift();
  2555. const size = saved_id.shift();
  2556. if (!loaded_storages.has(root_key)) {
  2557. const storage = new data_type(size);
  2558. storage._set_cdata(storage_map.get(root_key));
  2559. loaded_storages.set(root_key, storage);
  2560. }
  2561. const storage = loaded_storages.get(root_key);
  2562. const view_metadata = saved_id.shift();
  2563. if (view_metadata) {
  2564. const view_key = view_metadata.shift();
  2565. view_metadata.shift(); // view_offset
  2566. view_metadata.shift(); // view_size
  2567. let view = null;
  2568. if (loaded_storages.has(view_key)) {
  2569. view = loaded_storages.get(root_key);
  2570. }
  2571. else {
  2572. view = null; // storage.slice(view_offset, view_offset + view_size);
  2573. loaded_storages.set(view_key, view);
  2574. }
  2575. return view;
  2576. }
  2577. return storage;
  2578. };
  2579. const unpickler = python.Unpickler.open(data);
  2580. return unpickler.load((name, args) => this.execution.invoke(name, args), persistent_load);
  2581. }
  2582. _storage(dirname) {
  2583. const map = new Map();
  2584. const prefix = this._prefix + dirname + '/';
  2585. for (const entry of this._entries) {
  2586. if (entry[0].startsWith(prefix)) {
  2587. const key = entry[0].substring(prefix.length);
  2588. const buffer = entry[1].peek();
  2589. map.set(key, buffer);
  2590. }
  2591. }
  2592. return map;
  2593. }
  2594. trace() {
  2595. this._inputs = [];
  2596. this._outputs = [];
  2597. this.execution.reset();
  2598. if (this._torchscriptArena) {
  2599. const program = this.execution.parse(this._torchscriptArena);
  2600. for (const statement of program.body) {
  2601. if (statement.type == 'def') {
  2602. const self = this;
  2603. const globals = this.execution.context;
  2604. const func = {
  2605. __class__: this.execution.context.scope.builtins.function,
  2606. __name__: statement.name,
  2607. __code__: statement,
  2608. __call__: function(args) {
  2609. return self.execution.apply(this.__code__, args, globals);
  2610. }
  2611. };
  2612. this.data[statement.name] = func;
  2613. }
  2614. }
  2615. }
  2616. if (this.data.forward) {
  2617. const args = [ this.data ]; // self
  2618. if (this.data.forward.__code__ && this.data.forward.__code__.parameters) {
  2619. for (const parameter of this.data.forward.__code__.parameters) {
  2620. const defaultValue = (type, name) => {
  2621. if (type.type === 'type' && type.name.type) {
  2622. switch (type.name.value) {
  2623. case 'Tensor': {
  2624. const tensor = this.execution.invoke('torch.Tensor', []);
  2625. tensor.__variable__ = name;
  2626. tensor.__origin__ = 'graph-input';
  2627. return tensor;
  2628. }
  2629. case 'Tuple':
  2630. return type.arguments.map((type, index) => defaultValue(type, name + '[' + index.toString() + ']'));
  2631. case 'List':
  2632. return type.arguments.map((type, index) => defaultValue(type, name + '[' + index.toString() + ']' ));
  2633. case 'Dict':
  2634. return {};
  2635. case 'int':
  2636. return 0;
  2637. case 'float':
  2638. return 0.0;
  2639. case 'bool':
  2640. return false;
  2641. case 'Optional':
  2642. return undefined;
  2643. default:
  2644. break;
  2645. }
  2646. }
  2647. throw new pytorch.Error("Unsupported function parameter type '" + JSON.stringify(type) + "'.");
  2648. };
  2649. if (parameter.name !== 'self') {
  2650. const type = parameter.parameterType;
  2651. const value = defaultValue(type, parameter.name);
  2652. if (pytorch.Utility.isTensor(value)) {
  2653. value.__variable__ = parameter.name;
  2654. value.__origin__ = 'graph-input';
  2655. this._inputs.push(parameter.name);
  2656. }
  2657. args.push(value);
  2658. }
  2659. }
  2660. }
  2661. const result = this.data.forward.__call__(args);
  2662. if (Array.isArray(result)) {
  2663. for (const output of result) {
  2664. if (pytorch.Utility.isTensor(output)) {
  2665. this._outputs.push(output.__variable__);
  2666. }
  2667. }
  2668. }
  2669. else if (pytorch.Utility.isTensor(result)) {
  2670. this._outputs.push(result.__variable__);
  2671. }
  2672. else if (Object(result) === result) {
  2673. for (const key of Object.keys(result)) {
  2674. const value = result[key];
  2675. if (Array.isArray(value)) {
  2676. for (const output of value) {
  2677. if (pytorch.Utility.isTensor(output)) {
  2678. this._outputs.push(output.__variable__);
  2679. }
  2680. }
  2681. }
  2682. else if (pytorch.Utility.isTensor(value)) {
  2683. this._outputs.push(value.__variable__);
  2684. }
  2685. }
  2686. }
  2687. this._nodes = this.execution.nodes;
  2688. return true;
  2689. }
  2690. throw new pytorch.Error("Module 'forward' not implemented.");
  2691. }
  2692. get inputs() {
  2693. return this._inputs;
  2694. }
  2695. get outputs() {
  2696. return this._outputs;
  2697. }
  2698. get nodes() {
  2699. return this._nodes;
  2700. }
  2701. };
  2702. pytorch.Container.Zip.Execution = class extends pytorch.Execution {
  2703. constructor(sources, exceptionCallback, metadata) {
  2704. super(sources, exceptionCallback);
  2705. this._metadata = metadata;
  2706. this.reset();
  2707. }
  2708. reset() {
  2709. this._nodes = [];
  2710. this._variableIndex = 0;
  2711. }
  2712. get nodes() {
  2713. return this._nodes;
  2714. }
  2715. call(target, name, args, context) {
  2716. let resolvedTarget = pytorch.Utility.target(target);
  2717. let outputTypes = null;
  2718. if (resolvedTarget && resolvedTarget + '.' + name === 'ops.prim.NumToTensor' &&
  2719. args.length === 1 && args[0].type === 'call' && args[0].target.member.type == 'id') {
  2720. const innerCall = args[0];
  2721. resolvedTarget = pytorch.Utility.target(innerCall.target.target);
  2722. name = innerCall.target.member.value;
  2723. args = innerCall.arguments;
  2724. outputTypes = [ 'int64' ];
  2725. }
  2726. if (resolvedTarget) {
  2727. const type = resolvedTarget + '.' + name;
  2728. // https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/native_functions.yaml
  2729. let schemas = this._metadata.type(type);
  2730. if (schemas) {
  2731. schemas = !Array.isArray(schemas) ? [ schemas ] : schemas;
  2732. const evalArgs = args.map((argument) => argument.type === '=' && argument.target && argument.target.type === 'id' ? this.expression(argument.expression, context) : this.expression(argument, context));
  2733. for (const schema of schemas) {
  2734. const copyArgs = Array.prototype.slice.call(args);
  2735. const copyEvalArgs = Array.prototype.slice.call(evalArgs);
  2736. const node = {
  2737. type: schema.name,
  2738. inputs: [],
  2739. attributes: [],
  2740. outputs: []
  2741. };
  2742. const referencedParameters = [];
  2743. let next = false;
  2744. const parameters = Array.prototype.slice.call(schema.inputs || []).concat(Array.prototype.slice.call(schema.attributes || []));
  2745. let op_context = null;
  2746. while (copyEvalArgs.length > 0 || (op_context && parameters.length > 0)) {
  2747. if (parameters.length <= 0) {
  2748. next = true;
  2749. break;
  2750. }
  2751. const arg = copyEvalArgs[0];
  2752. if (arg && arg.__class__ && arg.__class__.__module__ && arg.__class__.__name__) {
  2753. const type = arg.__class__.__module__ + '.' + arg.__class__.__name__;
  2754. switch (type) {
  2755. case '__torch__.torch.classes.quantized.Conv2dPackedParamsBase':
  2756. case '__torch__.torch.classes.quantized.Conv3dPackedParamsBase':
  2757. case '__torch__.torch.classes.quantized.LinearPackedParamsBase':
  2758. case '__torch__.torch.classes.xnnpack.Conv2dOpContext':
  2759. case '__torch__.torch.classes.xnnpack.LinearOpContext':
  2760. op_context = arg;
  2761. copyArgs.shift();
  2762. copyEvalArgs.shift();
  2763. continue;
  2764. default:
  2765. break;
  2766. }
  2767. }
  2768. if (op_context && parameters[0]) {
  2769. const parameter = parameters[0];
  2770. const name = parameter.name;
  2771. if (name in op_context && parameter.context) {
  2772. copyArgs.unshift({ type: null });
  2773. copyEvalArgs.unshift(op_context[name]);
  2774. }
  2775. }
  2776. if (copyArgs.every((arg) => arg.type === '=' && arg.target && arg.target.type === 'id') &&
  2777. parameters.every((parameter) => parameter.type !== 'Tensor' && parameter.type !== 'Tensor[]')) {
  2778. const map = new Map(parameters.map((parameter) => [ parameter.name, parameter ]));
  2779. while (copyArgs.length > 0) {
  2780. const argument = copyArgs.shift();
  2781. const value = copyEvalArgs.shift();
  2782. const parameter = map.get(argument.target.value);
  2783. if (!parameter) {
  2784. next = true;
  2785. break;
  2786. }
  2787. if (!pytorch.Utility.isType(value, parameter.type)) {
  2788. if (parameter.optional) {
  2789. continue;
  2790. }
  2791. next = true;
  2792. break;
  2793. }
  2794. node.attributes.push({ name: parameter.name, value: value });
  2795. }
  2796. continue;
  2797. }
  2798. if (next) {
  2799. break;
  2800. }
  2801. const parameter = parameters.shift();
  2802. const argument = copyEvalArgs[0];
  2803. if (parameter.type === 'Tensor' || (parameter.type === 'Scalar' && pytorch.Utility.isTensor(argument))) {
  2804. if (Array.isArray(argument) || (!pytorch.Utility.isTensor(argument) && argument !== null && argument !== undefined)) {
  2805. if (parameter.optional) {
  2806. if (argument === undefined) {
  2807. copyArgs.shift();
  2808. copyEvalArgs.shift();
  2809. }
  2810. continue;
  2811. }
  2812. next = true;
  2813. }
  2814. else {
  2815. copyArgs.shift();
  2816. copyEvalArgs.shift();
  2817. const item = (argument === null || argument === undefined) ? {} : argument;
  2818. item.__variable__ = item.__variable__ || this.variable();
  2819. const inputs = [];
  2820. inputs.push({ id: item.__variable__ });
  2821. referencedParameters.push(item);
  2822. node.inputs.push(inputs);
  2823. }
  2824. }
  2825. else if (parameter.type === 'Tensor[]') {
  2826. const argument = copyEvalArgs[0];
  2827. if (!Array.isArray(argument) || !argument.every((item) => pytorch.Utility.isTensor(item) || item === null)) {
  2828. if (parameter.optional) {
  2829. continue;
  2830. }
  2831. next = true;
  2832. }
  2833. else {
  2834. copyArgs.shift();
  2835. copyEvalArgs.shift();
  2836. const inputs = [];
  2837. for (let item of argument) {
  2838. if (item === null) {
  2839. item = {};
  2840. }
  2841. item.__variable__ = item.__variable__ || this.variable();
  2842. inputs.push({ id: item.__variable__ });
  2843. referencedParameters.push(item);
  2844. }
  2845. node.inputs.push(inputs);
  2846. }
  2847. }
  2848. else {
  2849. const arg = copyArgs[0];
  2850. if (!pytorch.Utility.isType(argument, parameter.type) && argument !== null) {
  2851. if (parameter.optional) {
  2852. continue;
  2853. }
  2854. next = true;
  2855. }
  2856. else if (arg.type !== '=') {
  2857. copyArgs.shift();
  2858. copyEvalArgs.shift();
  2859. node.attributes.push({ name: parameter.name, value: argument });
  2860. }
  2861. else {
  2862. throw new pytorch.Error('Expected named argument.');
  2863. }
  2864. }
  2865. if (next) {
  2866. break;
  2867. }
  2868. }
  2869. if (next) {
  2870. continue;
  2871. }
  2872. const result = [];
  2873. for (let i = 0; i < schema.outputs.length; i++) {
  2874. const parameter = schema.outputs[i];
  2875. switch (parameter.type) {
  2876. case 'Tensor': {
  2877. const parameter = this.invoke('torch.Tensor', []);
  2878. parameter.__origin__ = type;
  2879. if (i === 0) {
  2880. switch (type) {
  2881. case 'torch.conv1d':
  2882. case 'torch.embedding': {
  2883. parameter.resize_([ NaN, NaN, NaN ]);
  2884. break;
  2885. }
  2886. case 'torch.cat':
  2887. case 'torch.conv2d':
  2888. case 'torch.dropout':
  2889. case 'torch.flatten':
  2890. case 'torch.max_pool2d':
  2891. case 'torch.adaptive_avg_pool2d':
  2892. case 'torch.avg_pool2d':
  2893. case 'torch.quantize_per_tensor':
  2894. case 'torch.relu_':
  2895. case 'torch.hardtanh_':
  2896. case 'torch.upsample_bilinear2d':
  2897. case 'torch.unsqueeze':
  2898. case 'ops.prepacked.conv2d_clamp_run': {
  2899. parameter.resize_([ NaN, NaN, NaN, NaN ]);
  2900. break;
  2901. }
  2902. case 'torch.slice': {
  2903. const input = evalArgs[0];
  2904. if (pytorch.Utility.isTensor(input) && Array.isArray(input.size())) {
  2905. const size = input.size();
  2906. parameter.resize_(size);
  2907. }
  2908. break;
  2909. }
  2910. case 'torch.to': {
  2911. const input = evalArgs[0];
  2912. if (pytorch.Utility.isTensor(input) && Array.isArray(input.size())) {
  2913. const size = input.size();
  2914. parameter.resize_(size);
  2915. }
  2916. break;
  2917. }
  2918. case 'torch.conv3d': {
  2919. parameter.resize_([ NaN, NaN, NaN, NaN, NaN ]);
  2920. break;
  2921. }
  2922. case 'torch.mean':
  2923. case 'torch.mul':
  2924. case 'torch.div':
  2925. case 'torch.batch_norm':
  2926. case 'torch.gelu':
  2927. case 'torch.relu':
  2928. case 'torch.clamp_':
  2929. case 'torch.hardswish_': {
  2930. const input = evalArgs[0];
  2931. if (pytorch.Utility.isTensor(input) && Array.isArray(input.size())) {
  2932. parameter.resize_(input.size());
  2933. }
  2934. break;
  2935. }
  2936. case 'torch.add':
  2937. case 'torch.sub': {
  2938. const input = evalArgs[0];
  2939. if (pytorch.Utility.isTensor(input) && Array.isArray(input.size())) {
  2940. parameter.resize_(input.size());
  2941. }
  2942. else {
  2943. const other = evalArgs[1];
  2944. if (pytorch.Utility.isTensor(other) && Array.isArray(other.size())) {
  2945. parameter.resize_(other.size());
  2946. }
  2947. }
  2948. break;
  2949. }
  2950. case 'torch.select': {
  2951. const input = evalArgs[0];
  2952. if (pytorch.Utility.isTensor(input) && Array.isArray(input.size())) {
  2953. parameter.resize_(Array(input.size().length - 1).fill(NaN));
  2954. }
  2955. break;
  2956. }
  2957. case 'torch.layer_norm': {
  2958. const input = evalArgs[0];
  2959. const normalized_shape = evalArgs[1];
  2960. if (pytorch.Utility.isTensor(input) && Array.isArray(input.size())) {
  2961. const shape = input.size();
  2962. if (Array.isArray(normalized_shape) && normalized_shape.length === 1) {
  2963. shape[shape.length - 1] = normalized_shape[0];
  2964. }
  2965. parameter.resize_(shape);
  2966. }
  2967. break;
  2968. }
  2969. case 'torch.ones':
  2970. case 'torch.zeros':
  2971. case 'torch.zeros_like': {
  2972. parameter.resize_(evalArgs[0]);
  2973. break;
  2974. }
  2975. case 'torch.view':
  2976. case 'torch.reshape':
  2977. case 'torch.new_full': {
  2978. parameter.resize_(evalArgs[1]);
  2979. break;
  2980. }
  2981. case 'torch.transpose': {
  2982. const input = evalArgs[0];
  2983. let dim0 = evalArgs[1];
  2984. let dim1 = evalArgs[2];
  2985. if (pytorch.Utility.isTensor(input) && Array.isArray(input.size())) {
  2986. const size = input.size().slice();
  2987. dim0 = dim0 > 0 ? dim0 : size.length + dim0;
  2988. dim1 = dim1 > 0 ? dim1 : size.length + dim1;
  2989. const value = size[dim0];
  2990. size[dim0] = size[1];
  2991. size[dim1] = value;
  2992. parameter.resize_(size);
  2993. }
  2994. break;
  2995. }
  2996. case 'ops.quantized.cat':
  2997. case 'ops.quantized.cat_relu':
  2998. case 'ops.quantized.linear':
  2999. case 'ops.quantized.conv2d':
  3000. case 'ops.quantized.conv2d_relu':
  3001. case 'ops.quantized.add':
  3002. case 'ops.quantized.add_relu':
  3003. parameter.resize_([ NaN, NaN, NaN, NaN ]);
  3004. parameter.__quantized__ = true;
  3005. break;
  3006. case 'torch.contiguous':
  3007. parameter.__source__ = evalArgs[0];
  3008. break;
  3009. default:
  3010. break;
  3011. }
  3012. }
  3013. parameter.__variable__ = this.variable();
  3014. result.push(parameter);
  3015. node.outputs.push([ { id: parameter.__variable__ } ]);
  3016. break;
  3017. }
  3018. case 'Tensor[]': {
  3019. let count = 1;
  3020. switch (type) {
  3021. case 'torch.chunk':
  3022. count = node.attributes.filter((attribute) => attribute.name == 'chunks')[0].value;
  3023. break;
  3024. case 'torch.meshgrid':
  3025. count = node.inputs[0].length;
  3026. break;
  3027. case 'torch.unbind':
  3028. count = args[0].__tuple__ || count;
  3029. break;
  3030. case 'torch.broadcast_tensors':
  3031. case 'torch.split':
  3032. case 'torch.split_with_sizes':
  3033. if (context.target.length > 0) {
  3034. count = context.target[context.target.length - 1].length;
  3035. }
  3036. break;
  3037. default:
  3038. break;
  3039. }
  3040. const tensors = [];
  3041. const outputs = [];
  3042. for (let i = 0; i < count; i ++) {
  3043. const tensor = this.invoke('torch.Tensor', []);
  3044. tensor.__origin__ = type;
  3045. tensor.__variable__ = this.variable();
  3046. tensors.push(tensor);
  3047. outputs.push({ id: tensor.__variable__ });
  3048. }
  3049. result.push(tensors);
  3050. node.outputs.push(outputs);
  3051. break;
  3052. }
  3053. default: {
  3054. if (!outputTypes || schema.outputs.length !== 1 || schema.outputs[0].type !== outputTypes[0]) {
  3055. next = true;
  3056. break;
  3057. }
  3058. const tensor = this.invoke('torch.Tensor', []);
  3059. tensor.resize_([]);
  3060. tensor.__origin__ = type;
  3061. tensor.__variable__ = this.variable();
  3062. result.push(tensor);
  3063. node.outputs.push([ { id: tensor.__variable__ } ]);
  3064. break;
  3065. }
  3066. }
  3067. }
  3068. if (next) {
  3069. continue;
  3070. }
  3071. for (const parameter of referencedParameters) {
  3072. parameter.__count__ = (parameter.__count__ || 0) + 1;
  3073. }
  3074. this.push(node);
  3075. if (result.length > 1) {
  3076. return result;
  3077. }
  3078. return result[0];
  3079. }
  3080. }
  3081. }
  3082. return super.call(target, name, args, context);
  3083. }
  3084. block(statements, context) {
  3085. statements = Array.prototype.slice.call(statements);
  3086. while (statements.length > 0) {
  3087. if (statements.length > 1) {
  3088. const assign = statements[0];
  3089. const condition = statements[1];
  3090. // _x = torch.ne(torch.len(torch.size(input)), 5)
  3091. // if _x:
  3092. // ops.prim.RaiseException(...)
  3093. if (assign.type === '=' &&
  3094. condition.type === 'if' &&
  3095. pytorch.Utility.isEqual(assign.target, condition.condition) &&
  3096. pytorch.Utility.isCall(assign.expression, 'torch.ne', 2) &&
  3097. pytorch.Utility.isCall(assign.expression.arguments[0], 'torch.len', 1) &&
  3098. pytorch.Utility.isCall(assign.expression.arguments[0].arguments[0], 'torch.size', 1) &&
  3099. condition.then.statements.length == 1 &&
  3100. pytorch.Utility.isCall(condition.then.statements[0], 'ops.prim.RaiseException', 1)) {
  3101. const tensor = this.expression(assign.expression.arguments[0].arguments[0].arguments[0], context);
  3102. if (pytorch.Utility.isTensor(tensor) && tensor.size) {
  3103. const number = this.expression(assign.expression.arguments[1], context);
  3104. const size = tensor.size();
  3105. if (number >= 3 && number <= 5) {
  3106. if (!Array.isArray(size) || size.length !== number) {
  3107. tensor.resize_(Array(number).fill(NaN));
  3108. }
  3109. }
  3110. }
  3111. }
  3112. // _x = torch.ne(torch.dim(input), 5)
  3113. // if _x:
  3114. // ops.prim.RaiseException(...)
  3115. if (assign.type === '=' &&
  3116. condition.type === 'if' &&
  3117. pytorch.Utility.isEqual(assign.target, condition.condition) &&
  3118. pytorch.Utility.isCall(assign.expression, 'torch.ne', 2) &&
  3119. pytorch.Utility.isCall(assign.expression.arguments[0], 'torch.dim', 1) &&
  3120. condition.then.statements.length > 0 &&
  3121. pytorch.Utility.isCall(condition.then.statements[condition.then.statements.length - 1], 'ops.prim.RaiseException', 1)) {
  3122. const tensor = this.expression(assign.expression.arguments[0].arguments[0], context);
  3123. if (pytorch.Utility.isTensor(tensor)) {
  3124. const size = this.expression(assign.expression.arguments[1], context);
  3125. tensor.resize_(Array(size).fill(NaN));
  3126. }
  3127. }
  3128. // _0 = torch.eq(torch.len(torch.size(x)), 2)
  3129. // if _0:
  3130. // pass
  3131. // else:
  3132. // ops.prim.RaiseException("AssertionError: ")
  3133. if (assign.type === '=' &&
  3134. condition.type === 'if' &&
  3135. pytorch.Utility.isEqual(assign.target, condition.condition) &&
  3136. pytorch.Utility.isCall(assign.expression, 'torch.eq', 2) &&
  3137. pytorch.Utility.isCall(assign.expression.arguments[0], 'torch.len', 1) &&
  3138. pytorch.Utility.isCall(assign.expression.arguments[0].arguments[0], 'torch.size', 1) &&
  3139. condition.else.statements.length == 1 &&
  3140. pytorch.Utility.isCall(condition.else.statements[0], 'ops.prim.RaiseException', 1)) {
  3141. const tensor = this.expression(assign.expression.arguments[0].arguments[0].arguments[0], context);
  3142. if (pytorch.Utility.isTensor(tensor) && tensor.shape === undefined) {
  3143. const number = this.expression(assign.expression.arguments[1], context);
  3144. tensor.resize_(Array(number).fill(NaN));
  3145. }
  3146. }
  3147. // val = torch.slice(torch.size(img), -2)
  3148. // if torch.eq(torch.len(val), 2):
  3149. // pass
  3150. // else:
  3151. // ops.prim.RaiseException("AssertionError: ")
  3152. if (assign.type === '=' &&
  3153. condition.type === 'if' &&
  3154. pytorch.Utility.isCall(assign.expression, 'torch.slice', 2) &&
  3155. pytorch.Utility.isCall(assign.expression.arguments[0], 'torch.size', 1) &&
  3156. pytorch.Utility.isCall(condition.condition, 'torch.eq', 2) &&
  3157. pytorch.Utility.isCall(condition.condition.arguments[0], 'torch.len', 1) &&
  3158. pytorch.Utility.isEqual(condition.condition.arguments[0].arguments[0], assign.target) &&
  3159. condition.else.statements.length == 1 &&
  3160. pytorch.Utility.isCall(condition.else.statements[0], 'ops.prim.RaiseException', 1)) {
  3161. const tensor = this.expression(assign.expression.arguments[0].arguments[0], context);
  3162. if (pytorch.Utility.isTensor(tensor) && tensor.shape === undefined) {
  3163. const start = this.expression(assign.expression.arguments[1], context);
  3164. const value = this.expression(condition.condition.arguments[1], context);
  3165. if (Number.isInteger(start) && start < 0 && Number.isInteger(value) && value > 0) {
  3166. tensor.resize_(Array(value - start).fill(NaN));
  3167. }
  3168. }
  3169. }
  3170. }
  3171. if (statements.length > 1) {
  3172. // getattr_1 = torch.size(x)
  3173. // getitem = torch.slice(getattr_1, -2, 9223372036854775807, 1)
  3174. const size = statements[0];
  3175. const statement = statements[1];
  3176. if (size.type === '=' && statement.type === '=' &&
  3177. size.target.type === 'id' &&
  3178. pytorch.Utility.isCall(size.expression, 'torch.size', 1) &&
  3179. pytorch.Utility.isCall(statement.expression, 'torch.slice', 4) &&
  3180. statement.expression.arguments[0].type === 'id' && size.target.value === statement.expression.arguments[0].value) {
  3181. const tensor = this.expression(size.expression.arguments[0], context);
  3182. if (pytorch.Utility.isTensor(tensor) && tensor.__origin__ === 'graph-input' && tensor.shape === undefined) {
  3183. tensor.resize_([ 1, 3, 299, 299 ]);
  3184. }
  3185. }
  3186. }
  3187. if (statements.length > 1) {
  3188. // _0 = torch.split_with_sizes(...)
  3189. // a, a_1, a_2, = _0
  3190. const statement = statements[0];
  3191. const tuple = statements[1];
  3192. if (statement.type === '=' && statement.target.type === 'id' && statement.expression.type == 'call' &&
  3193. tuple.type === '=' && tuple.target.type === 'tuple' &&
  3194. tuple.target.value.every((item) => item.type === 'id') &&
  3195. tuple.expression.value === statement.target.value) {
  3196. const containsVariableReference = (queue, value) => {
  3197. while (queue.length > 0) {
  3198. const obj = queue.shift();
  3199. if (obj && obj.type === 'id' && obj.value === value) {
  3200. return true;
  3201. }
  3202. else if (Array.isArray(obj)) {
  3203. for (const item of obj) {
  3204. if (Array.isArray(item) || (Object(item) === item && item.type)) {
  3205. queue.push(item);
  3206. }
  3207. }
  3208. }
  3209. else if (Object(obj) === obj) {
  3210. for (const entry of Object.entries(obj)) {
  3211. const key = entry[0];
  3212. const value = entry[1];
  3213. if (key === 'location') {
  3214. continue;
  3215. }
  3216. if (Array.isArray(value)) {
  3217. for (const item of value) {
  3218. if (Array.isArray(item) || (Object(item) === item && item.type)) {
  3219. queue.push(item);
  3220. }
  3221. }
  3222. }
  3223. else if (Object(value) === value && value.type) {
  3224. queue.push(value);
  3225. }
  3226. }
  3227. }
  3228. }
  3229. return false;
  3230. };
  3231. if (!containsVariableReference(statements.slice(2, statements.length - 1), statement.target.value)) {
  3232. statements[0] = Object.assign({}, statement);
  3233. statements[0].target = tuple.target;
  3234. statements.splice(1, 1);
  3235. }
  3236. }
  3237. }
  3238. const statement = statements.shift();
  3239. // input_shape = torch.slice(torch.size(x), -2, 9223372036854775807, 1)
  3240. if (statement.type === '=' &&
  3241. pytorch.Utility.isCall(statement.expression, 'torch.slice', 4) &&
  3242. pytorch.Utility.isCall(statement.expression.arguments[0], 'torch.size', 1)) {
  3243. const tensor = this.expression(statement.expression.arguments[0].arguments[0], context);
  3244. if (pytorch.Utility.isTensor(tensor) && tensor.shape === undefined) {
  3245. tensor.resize_([ 1, 3, 299, 299 ]);
  3246. }
  3247. }
  3248. // torch.slice(ops.prim.shape(input), 0, 2, 1)
  3249. if (statement.type === '=' &&
  3250. pytorch.Utility.isCall(statement.expression, 'torch.slice', 4) &&
  3251. pytorch.Utility.isCall(statement.expression.arguments[0], 'ops.prim.shape', 1)) {
  3252. const tensor = this.expression(statement.expression.arguments[0].arguments[0], context);
  3253. if (pytorch.Utility.isTensor(tensor) && tensor.__origin__ === 'graph-input' && tensor.shape === undefined) {
  3254. tensor.resize_([ NaN, NaN, NaN, NaN ]);
  3255. }
  3256. }
  3257. // _3 = torch.le(xxxx, torch.dim(f0))
  3258. if (statement.type === '=' &&
  3259. pytorch.Utility.isCall(statement.expression, 'torch.le', 2) &&
  3260. pytorch.Utility.isCall(statement.expression.arguments[1], 'torch.dim', 1)) {
  3261. const tensor = this.expression(statement.expression.arguments[1].arguments[0], context);
  3262. if (pytorch.Utility.isTensor(tensor) && tensor.__origin__ === 'graph-input' && tensor.shape === undefined) {
  3263. tensor.resize_([ NaN, NaN, NaN, NaN ]);
  3264. }
  3265. }
  3266. // if torch.ne(torch.dim(image), 3):
  3267. // xxxx
  3268. // ops.prim.RaiseException(_7)
  3269. if (statement.type === 'if' &&
  3270. pytorch.Utility.isCall(statement.condition, 'torch.ne', 2) &&
  3271. pytorch.Utility.isCall(statement.condition.arguments[0], 'torch.dim', 1) &&
  3272. statement.then.statements.length > 0 &&
  3273. pytorch.Utility.isCall(statement.then.statements.slice(-1).pop(), 'ops.prim.RaiseException', 1)) {
  3274. const tensor = this.expression(statement.condition.arguments[0].arguments[0], context);
  3275. const size = this.expression(statement.condition.arguments[1], context);
  3276. if (pytorch.Utility.isTensor(tensor) && Number.isInteger(size) && size < 10) {
  3277. tensor.resize_(Array.isArray(tensor.shape) && tensor.shape.length > size ? tensor.shape.slice(-size) : Array(size).fill(NaN));
  3278. }
  3279. }
  3280. // if bool(...):
  3281. // ops.prim.RaiseException(torch.format(_1, dtype))
  3282. // else:
  3283. // pass
  3284. if (statement.type === 'if' &&
  3285. pytorch.Utility.isCall(statement.condition, 'bool', 1) &&
  3286. statement.then.statements.length > 0 &&
  3287. pytorch.Utility.isCall(statement.then.statements.slice(-1).pop(), 'ops.prim.RaiseException', 1)) {
  3288. statement.condition = { type: 'id', value: 'False' };
  3289. }
  3290. // dim = torch.sub(torch.dim(input), 2)
  3291. if (statement.type === '=' &&
  3292. statement.target.type === 'id' && statement.target.value === 'dim' &&
  3293. pytorch.Utility.isCall(statement.expression, 'torch.sub', 2) &&
  3294. pytorch.Utility.isCall(statement.expression.arguments[0], 'torch.dim', 1)) {
  3295. const tensor = this.expression(statement.expression.arguments[0].arguments[0], context);
  3296. if (pytorch.Utility.isTensor(tensor) && tensor.__origin__ === 'graph-input' && tensor.shape === undefined) {
  3297. tensor.resize_([ NaN, NaN, NaN, NaN ]);
  3298. }
  3299. }
  3300. // a, b = torch.unbind(size, 0)
  3301. if (statement.type === '=' &&
  3302. statement.target.type === 'tuple' &&
  3303. (pytorch.Utility.isCall(statement.expression, 'torch.unbind', 1) ||
  3304. pytorch.Utility.isCall(statement.expression, 'torch.unbind', 2))) {
  3305. statement.expression.arguments[0].__tuple__ = statement.target.value.length;
  3306. }
  3307. // x = torch.len(input)
  3308. if (statement.type === '=' &&
  3309. statement.target.type === 'id' &&
  3310. pytorch.Utility.isCall(statement.expression, 'torch.len', 1)) {
  3311. const tensor = this.expression(statement.expression.arguments[0], context);
  3312. if (pytorch.Utility.isTensor(tensor) && tensor.__origin__ === 'graph-input' && tensor.shape === undefined) {
  3313. tensor.resize_([ NaN, NaN, NaN, NaN ]);
  3314. }
  3315. }
  3316. if (statement.type === '=' &&
  3317. statement.expression.type === 'call' && statement.expression.arguments.length > 0 &&
  3318. pytorch.Utility.isCall(statement.expression.arguments[0], 'torch.size', 2)) {
  3319. const tensor = this.expression(statement.expression.arguments[0].arguments[0], context);
  3320. const dim = this.expression(statement.expression.arguments[0].arguments[1], context);
  3321. if (pytorch.Utility.isTensor(tensor) && Number.isInteger(dim)) {
  3322. if (tensor.shape === undefined) {
  3323. tensor.resize_(Array(dim + 1).fill(NaN));
  3324. }
  3325. else if (Array.isArray(tensor.shape) && tensor.shape.length <= dim) {
  3326. tensor.resize_(tensor.shape.concat(Array(dim + 1 - tensor.shape.length).fill(NaN)));
  3327. }
  3328. }
  3329. }
  3330. const value = this.statement(statement, context);
  3331. if (value !== undefined) {
  3332. return value;
  3333. }
  3334. }
  3335. return undefined;
  3336. }
  3337. push(node) {
  3338. this._nodes.push(node);
  3339. }
  3340. variable() {
  3341. this._variableIndex++;
  3342. return this._variableIndex.toString();
  3343. }
  3344. };
  3345. pytorch.ScalarType = {
  3346. uint8: 0,
  3347. int8: 1,
  3348. int16: 2,
  3349. int32: 3,
  3350. int64: 4,
  3351. float16: 5,
  3352. float32: 6,
  3353. float64: 7,
  3354. complex32: 8,
  3355. complex64: 9,
  3356. complex128: 10,
  3357. boolean: 11,
  3358. qint8: 12,
  3359. quint8: 13,
  3360. qint32: 14,
  3361. bfloat16: 15,
  3362. quint4x2: 16
  3363. };
  3364. pytorch.MemoryFormat = {
  3365. Contiguous: 0,
  3366. Preserve: 1,
  3367. ChannelsLast: 2,
  3368. ChannelsLast3d: 3
  3369. };
  3370. pytorch.Layout = {
  3371. Strided: 0,
  3372. Sparse: 1,
  3373. Mkldnn: 2
  3374. };
  3375. pytorch.Utility = class {
  3376. static getScalarType(scalarType) {
  3377. if (!pytorch.Utility._scalarTypes) {
  3378. pytorch.Utility._scalarTypes = [
  3379. { name: 'uint8', itemsize: 1 },
  3380. { name: 'int8', itemsize: 1 },
  3381. { name: 'int16', itemsize: 2 },
  3382. { name: 'int32', itemsize: 4 },
  3383. { name: 'int64', itemsize: 8 },
  3384. { name: 'float16', itemsize: 2 },
  3385. { name: 'float32', itemsize: 4 },
  3386. { name: 'float64', itemsize: 8 },
  3387. { name: 'complex32', itemsize: 4 },
  3388. { name: 'complex64', itemsize: 8 },
  3389. { name: 'complex128', itemsize: 16 },
  3390. { name: 'boolean', itemsize: 1 },
  3391. { name: 'qint8', itemsize: 1 },
  3392. { name: 'quint8', itemsize: 1 },
  3393. { name: 'qint32', itemsize: 4 },
  3394. { name: 'bfloat16', itemsize: 2 },
  3395. { name: 'quint4x2' }
  3396. ];
  3397. }
  3398. if (scalarType < pytorch.Utility._scalarTypes.length) {
  3399. return pytorch.Utility._scalarTypes[scalarType];
  3400. }
  3401. throw new pytorch.Error("Unsupported scalar type '" + scalarType + "'.");
  3402. }
  3403. static target(expression) {
  3404. if (expression.type == 'id') {
  3405. return expression.value;
  3406. }
  3407. if (expression.type == '.') {
  3408. return pytorch.Utility.target(expression.target) + '.' + pytorch.Utility.target(expression.member);
  3409. }
  3410. return null;
  3411. }
  3412. static isTensor(obj) {
  3413. const name = obj && obj.__class__ ? obj.__class__.__module__ : null;
  3414. switch (name) {
  3415. case 'torch':
  3416. case 'torch.cuda':
  3417. return obj.__class__.__name__.endsWith('Tensor');
  3418. case 'torch.nn.parameter':
  3419. return obj.__class__.__name__ === 'Parameter';
  3420. default:
  3421. return false;
  3422. }
  3423. }
  3424. static toTensor(obj) {
  3425. const name = obj && obj.__class__ ? obj.__class__.__module__ : null;
  3426. switch (name) {
  3427. case 'torch':
  3428. case 'torch.cuda':
  3429. return obj.__class__.__name__.endsWith('Tensor') ? obj : null;
  3430. case 'torch.nn.parameter':
  3431. return obj.__class__.__name__ === 'Parameter' ? obj.data : null;
  3432. default:
  3433. return null;
  3434. }
  3435. }
  3436. static createTensor(name, tensor, littleEndian) {
  3437. const storage = tensor.storage();
  3438. const size = tensor.size();
  3439. const type = new pytorch.TensorType(storage.dtype.__reduce__(), new pytorch.TensorShape(size));
  3440. return new pytorch.Tensor(name || '', type, storage.data, littleEndian);
  3441. }
  3442. static isType(obj, type) {
  3443. switch (type) {
  3444. case 'Tensor':
  3445. return !Array.isArray(obj) && (pytorch.Utility.isTensor(obj) || obj === null);
  3446. case 'Tensor[]':
  3447. return Array.isArray(obj) && obj.length > 0 && obj.every((tensor) => pytorch.Utility.isTensor(tensor) || tensor === null);
  3448. case 'Scalar':
  3449. return (obj !== null && obj !== Object(obj)) || (pytorch.Utility.isTensor(obj) && Array.isArray(obj.size()) && obj.size().length === 0);
  3450. case 'boolean':
  3451. return obj === true || obj === false;
  3452. case 'int64':
  3453. return Number.isInteger(obj) || obj instanceof base.Int64 || (typeof obj === 'number' && isNaN(obj));
  3454. case 'int64[]':
  3455. return Array.isArray(obj) && obj.every((item) => Number.isInteger(item) || (typeof item === 'number' && isNaN(item)) || item === undefined);
  3456. case 'int64[1]':
  3457. return pytorch.Utility.isType(obj, 'int64') || pytorch.Utility.isType(obj, 'int64[]');
  3458. case 'float32':
  3459. case 'float64':
  3460. return obj !== null && obj !== Object(obj);
  3461. case 'string[][]':
  3462. return Array.isArray(obj) && obj.every((item) => Array.isArray(item) && item.every((item) => typeof item === 'string'));
  3463. case 'Layout':
  3464. case 'ScalarType':
  3465. case 'MemoryFormat':
  3466. return Number.isInteger(obj) || obj === null;
  3467. case 'Device':
  3468. return obj === null || obj === Object(obj);
  3469. default:
  3470. return true;
  3471. }
  3472. }
  3473. static isCall(expression, name, size) {
  3474. if (expression.type === 'call' &&
  3475. expression.arguments.length === size &&
  3476. pytorch.Utility.target(expression.target) === name) {
  3477. return true;
  3478. }
  3479. return false;
  3480. }
  3481. static isEqual(a, b) {
  3482. return (a.type === 'id' && b.type === 'id' && a.value === b.value);
  3483. }
  3484. static findModule(root) {
  3485. if (root) {
  3486. const keys = [ '', 'model', 'net' ];
  3487. for (const key of keys) {
  3488. const obj = key === '' ? root : root[key];
  3489. if (obj && obj instanceof Map && obj.has('engine')) {
  3490. // https://github.com/NVIDIA-AI-IOT/torch2trt/blob/master/torch2trt/torch2trt.py
  3491. const signature = [ 0x70, 0x74, 0x72, 0x74 ]; // ptrt
  3492. const buffer = obj.get('engine');
  3493. if (buffer instanceof Uint8Array && buffer.length > signature.length && signature.every((value, index) => value === buffer[index])) {
  3494. throw new pytorch.Error('Invalid file content. File contains undocumented PyTorch TensorRT engine data.');
  3495. }
  3496. }
  3497. if (obj) {
  3498. if (obj._modules) {
  3499. return [ { name: '', obj: obj } ];
  3500. }
  3501. const objKeys = Object.keys(obj).filter((key) => obj[key] && obj[key]._modules);
  3502. if (objKeys.length > 1) {
  3503. return objKeys.map((key) => { return { name: key, obj: obj[key] }; });
  3504. }
  3505. }
  3506. }
  3507. }
  3508. return null;
  3509. }
  3510. static findWeights(root) {
  3511. if (!root) {
  3512. return null;
  3513. }
  3514. if (root instanceof Map) {
  3515. const obj = {};
  3516. for (const pair of root) {
  3517. const key = pair[0];
  3518. const value = pair[1];
  3519. obj[key] = value;
  3520. }
  3521. root = obj;
  3522. }
  3523. const keys = root && !Array.isArray(root) ? Object.keys(root) : [];
  3524. if (keys.length > 1) {
  3525. keys.splice(0, keys.length);
  3526. }
  3527. keys.push(...[
  3528. 'state_dict', 'state', 'model_state', 'model', 'model_state_dict', 'model_dict', 'net_dict', 'params', 'generator', 'module', 'weights',
  3529. 'discriminator', 'g_state', 'network', 'net', 'netG', 'net_states', 'state_dict_stylepredictor', 'state_dict_ghiasi', 'runner', ''
  3530. ]);
  3531. for (const key of keys) {
  3532. const obj = key === '' ? root : root[key];
  3533. let graphs = null;
  3534. graphs = graphs || pytorch.Utility._convertTensor(obj);
  3535. graphs = graphs || pytorch.Utility._convertObjectList(obj);
  3536. graphs = graphs || pytorch.Utility._convertStateDict(obj);
  3537. if (graphs) {
  3538. return graphs;
  3539. }
  3540. }
  3541. return null;
  3542. }
  3543. static _convertTensor(obj) {
  3544. if (obj && pytorch.Utility.isTensor(obj)) {
  3545. const layers = [];
  3546. const argument = { id: '', value: obj };
  3547. const parameter = { name: 'value', arguments: [ argument ] };
  3548. layers.push({ states: [ parameter ] });
  3549. return [ { layers: layers } ];
  3550. }
  3551. return null;
  3552. }
  3553. static _convertObjectList(obj) {
  3554. if (obj && Array.isArray(obj)) {
  3555. if (obj.every((item) => typeof item === 'number' || typeof item === 'string')) {
  3556. const layers = [];
  3557. const type = obj.__class__ ? obj.__class__.__module__ + '.' + obj.__class__.__name__ : '?';
  3558. const layer = { type: type, states: [], attributes: [] };
  3559. for (let i = 0; i < obj.length; i++) {
  3560. const key = i.toString();
  3561. const value = obj[i];
  3562. if (pytorch.Utility.isTensor(value)) {
  3563. layer.states.push({ name: key, arguments: [ { id: '', value: value } ] });
  3564. }
  3565. else {
  3566. layer.attributes.push({ name: key, value: value });
  3567. }
  3568. }
  3569. layers.push(layer);
  3570. return [ { layers: layers } ];
  3571. }
  3572. if (obj.every((item) => item && Object.values(item).filter((value) => pytorch.Utility.isTensor(value)).length > 0)) {
  3573. const layers = [];
  3574. for (const item of obj) {
  3575. const type = item.__class__ ? item.__class__.__module__ + '.' + item.__class__.__name__ : '?';
  3576. const layer = { type: type, states: [], attributes: [] };
  3577. if (item instanceof Map) {
  3578. return null;
  3579. }
  3580. for (const entry of Object.entries(item)) {
  3581. const key = entry[0];
  3582. const value = entry[1];
  3583. if (pytorch.Utility.isTensor(value)) {
  3584. layer.states.push({ name: key, arguments: [ { id: '', value: value } ] });
  3585. }
  3586. else {
  3587. layer.attributes.push({ name: key, value: value });
  3588. }
  3589. }
  3590. layers.push(layer);
  3591. }
  3592. return [ { layers: layers } ];
  3593. }
  3594. }
  3595. return null;
  3596. }
  3597. static _convertStateDict(obj) {
  3598. const clean = (obj) => {
  3599. if (obj && Array.isArray(obj)) {
  3600. return obj;
  3601. }
  3602. if (obj && obj instanceof Map) {
  3603. return obj;
  3604. }
  3605. if (obj && Object(obj) === obj) {
  3606. const target = {};
  3607. const map_count = Object.entries(obj).filter((entry) => entry[1] instanceof Map).length;
  3608. for (const entry of Object.entries(obj)) {
  3609. const key = entry[0];
  3610. const value = entry[1];
  3611. if (key.indexOf('optim') !== -1 || key.indexOf('opt') !== -1) {
  3612. if (value === null || (value.state && value.param_groups)) {
  3613. continue;
  3614. }
  3615. }
  3616. if (map_count > 2 && key.endsWith('_avg') && pytorch.Utility.isTensor(value)) {
  3617. continue;
  3618. }
  3619. if (typeof value === 'number' || typeof value === 'string' || typeof value === 'boolean') {
  3620. continue;
  3621. }
  3622. if (key === '__class__' && value.__module__ && value.__name__) {
  3623. continue;
  3624. }
  3625. if (Array.isArray(value) && (key.indexOf('loss') !== -1 || value.length === 0)) {
  3626. continue;
  3627. }
  3628. if (value && value.__class__ && value.__class__.__module__ === 'datetime' && value.__class__.__name__ === 'datetime') {
  3629. continue;
  3630. }
  3631. if ((key.startsWith('dico_') && Object(value) === value) ||
  3632. (key === 'args' && Object(value) === value) ||
  3633. (key.startsWith('params') && Object(value) === value && (value.id2lang || value.lang2id)) ||
  3634. (key.startsWith('spk_dict_') && Object(value) === value && Object.keys(value).length === 0)) {
  3635. continue;
  3636. }
  3637. target[key] = value;
  3638. }
  3639. return target;
  3640. }
  3641. return obj;
  3642. };
  3643. const validate = (map) => {
  3644. let tensor = false;
  3645. if (map && map instanceof Map) {
  3646. for (const pair of map) {
  3647. const key = pair[0];
  3648. const value = pair[1];
  3649. if (key.split('.').pop() === '_metadata') {
  3650. continue;
  3651. }
  3652. if (pytorch.Utility.isTensor(value)) {
  3653. tensor = true;
  3654. continue;
  3655. }
  3656. else if (value && Array.isArray(value) && value.every((item) => pytorch.Utility.isTensor(item))) {
  3657. tensor = true;
  3658. continue;
  3659. }
  3660. else if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
  3661. continue;
  3662. }
  3663. else if (value === null) {
  3664. continue;
  3665. }
  3666. return false;
  3667. }
  3668. }
  3669. return tensor;
  3670. };
  3671. const flatten = (obj) => {
  3672. if (!obj || Array.isArray(obj) || ArrayBuffer.isView(obj)) {
  3673. return null;
  3674. }
  3675. if (obj instanceof Map) {
  3676. if (validate(obj)) {
  3677. return obj;
  3678. }
  3679. return null;
  3680. }
  3681. if (Object(obj) !== obj) {
  3682. return null;
  3683. }
  3684. const map = new Map(Object.keys(obj).map((key) => [ key, obj[key] ]));
  3685. if (validate(map)) {
  3686. return map;
  3687. }
  3688. map.clear();
  3689. for (const key of Object.keys(obj)) {
  3690. const value = flatten(obj[key]);
  3691. if (value && value instanceof Map) {
  3692. for (const pair of value) {
  3693. map.set(key + '.' + pair[0], pair[1]);
  3694. }
  3695. continue;
  3696. }
  3697. return null;
  3698. }
  3699. return map;
  3700. };
  3701. if (!obj) {
  3702. return null;
  3703. }
  3704. obj = clean(obj);
  3705. const map = new Map();
  3706. if (Array.isArray(obj) && obj.every((item) => validate(item))) {
  3707. for (let i = 0; i < obj.length; i++) {
  3708. map.set(i.toString(), flatten(obj[i]));
  3709. }
  3710. }
  3711. else if (obj instanceof Map && validate(obj)) {
  3712. map.set('', flatten(obj));
  3713. }
  3714. else if (Object(obj) === obj && Object.entries(obj).every((entry) => validate(entry[1]))) {
  3715. for (const entry of Object.entries(obj)) {
  3716. map.set(entry[0], entry[1]);
  3717. }
  3718. }
  3719. else if (Object(obj) === obj && Object.entries(obj).every((entry) => pytorch.Utility.isTensor(entry[1]))) {
  3720. map.set('', new Map(Object.keys(obj).map((key) => [ key, obj[key] ])));
  3721. }
  3722. else {
  3723. const value = flatten(obj);
  3724. if (value) {
  3725. map.set('', value);
  3726. }
  3727. }
  3728. if (map.size > 0) {
  3729. const graphs = [];
  3730. for (const pair of map) {
  3731. const graph_key = pair[0];
  3732. const layer_map = pair[1];
  3733. const layers = new Map();
  3734. for (const item of layer_map) {
  3735. const key = item[0];
  3736. const value = item[1];
  3737. let layerName = '';
  3738. let parameter = '';
  3739. const separator = key.indexOf('.') === -1 && key.indexOf('|') !== -1 ? '|' : '.';
  3740. const keys = key.split(separator);
  3741. if (keys[keys.length - 1] === '_metadata') {
  3742. continue;
  3743. }
  3744. if (keys.length >= 2 && keys[keys.length - 2] === '_packed_params') {
  3745. parameter = keys.slice(-2).join(separator);
  3746. keys.pop();
  3747. keys.pop();
  3748. }
  3749. else {
  3750. parameter = keys.pop();
  3751. if (keys.length < 0) {
  3752. keys.push('');
  3753. }
  3754. }
  3755. layerName = keys.join(separator);
  3756. if (!layers.has(layerName)) {
  3757. layers.set(layerName, { name: layerName, states: [], attributes: [] });
  3758. }
  3759. const layer = layers.get(layerName);
  3760. if (pytorch.Utility.isTensor(value)) {
  3761. layer.states.push({ name: parameter, arguments: [ { id: key, value: value } ] });
  3762. if (layer.name == '' && layer.states.length > 12) {
  3763. return null;
  3764. }
  3765. }
  3766. else if (value && Array.isArray(value) && value.every((item) => pytorch.Utility.isTensor(item))) {
  3767. layer.states.push({ name: parameter, arguments: value.map((item) => { return { id: '', value: item }; }) });
  3768. }
  3769. else if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
  3770. layer.attributes.push({ name: parameter, value: value });
  3771. }
  3772. }
  3773. graphs.push({
  3774. name: graph_key,
  3775. layers: layers.values()
  3776. });
  3777. }
  3778. return graphs;
  3779. }
  3780. return null;
  3781. }
  3782. };
  3783. pytorch.nnapi = {};
  3784. pytorch.nnapi.SerializedModel = class {
  3785. constructor(serialized_model, buffers) {
  3786. const reader = new base.BinaryReader(serialized_model);
  3787. this.version = reader.int32();
  3788. if (this.version !== 1) {
  3789. throw new pytorch.Error('Invalid NNAPI serialized model version.');
  3790. }
  3791. const operands = new Array(reader.int32());
  3792. const values = new Array(reader.int32());
  3793. this.operations = new Array(reader.int32());
  3794. this.inputs = new Array(reader.int32());
  3795. this.outputs = new Array(reader.int32());
  3796. const data_types = new Map([
  3797. [ 0, 'float32' ],
  3798. [ 1, 'int32' ],
  3799. [ 2, 'uint32' ],
  3800. [ 3, 'float32[]' ],
  3801. [ 4, 'int32[]' ],
  3802. [ 5, 'quant8_asymm[]' ],
  3803. [ 6, 'boolean' ],
  3804. [ 7, 'quant16_symm[]' ],
  3805. [ 8, 'float16[]' ],
  3806. [ 9, 'boolean[]' ],
  3807. [ 10, 'float16' ],
  3808. [ 11, 'quant8_symm_per_channel[]' ],
  3809. [ 12, 'quant16_asymm[]' ],
  3810. [ 13, 'quant8_symm[]' ],
  3811. [ 14, 'quant8_asymm_signed[]' ],
  3812. [ 16, 'model' ]
  3813. ]);
  3814. for (let i = 0; i < operands.length; i++) {
  3815. const data_type = reader.int32();
  3816. operands[i] = {
  3817. index: i,
  3818. data_type: data_types.has(data_type) ? data_types.get(data_type) : data_type,
  3819. dimensions: new Array(reader.uint32()),
  3820. scale: reader.float32(),
  3821. zero_point: reader.int32()
  3822. };
  3823. }
  3824. for (let i = 0; i < values.length; i++) {
  3825. values[i] = {
  3826. index: reader.int32(),
  3827. source_type: reader.int32(),
  3828. source_length: reader.uint32()
  3829. };
  3830. }
  3831. for (let i = 0; i < this.operations.length; i++) {
  3832. this.operations[i] = {
  3833. index: reader.int32(),
  3834. location: i,
  3835. inputs: new Array(reader.uint32()),
  3836. outputs: new Array(reader.uint32())
  3837. };
  3838. }
  3839. for (const operand of operands) {
  3840. for (let i = 0; i< operand.dimensions.length; i++) {
  3841. operand.dimensions[i] = reader.uint32();
  3842. }
  3843. }
  3844. for (const value of values) {
  3845. const index = value.index;
  3846. const operand = operands[index];
  3847. switch (value.source_type) {
  3848. case 0: { // immediate
  3849. switch (operand.data_type) {
  3850. case 'boolean':
  3851. operand.value = reader.byte() ? true : false;
  3852. reader.skip(3);
  3853. break;
  3854. case 'int32':
  3855. operand.value = reader.int32();
  3856. break;
  3857. case 'float32':
  3858. operand.value = reader.float32();
  3859. break;
  3860. case 'int32[]':
  3861. operand.data = reader.read(value.source_length);
  3862. break;
  3863. case 'float32[]':
  3864. operand.data = reader.read(value.source_length);
  3865. break;
  3866. default:
  3867. throw new pytorch.Error("Unsupported NNAPI operand type '" + operand.data_type.toString() + "'.");
  3868. }
  3869. break;
  3870. }
  3871. case 2: { // numbered buffer
  3872. if (value.source_length !== 12) {
  3873. throw new pytorch.Error('Invalid NNAPI numbered buffer source length.');
  3874. }
  3875. const number = reader.uint32();
  3876. const offset = reader.uint32();
  3877. const operand_length = reader.uint32();
  3878. const buffer = buffers[number];
  3879. operand.data = buffer.slice(offset, operand_length);
  3880. break;
  3881. }
  3882. case 3: { // numbered memory
  3883. throw new pytorch.Error('NNAPI numbered memory buffer not implemented.');
  3884. }
  3885. default: {
  3886. throw new pytorch.Error('Unsupported NNAPI value source type.');
  3887. }
  3888. }
  3889. }
  3890. for (const operation of this.operations) {
  3891. for (let i = 0; i< operation.inputs.length; i++) {
  3892. const index = reader.uint32();
  3893. operation.inputs[i] = operands[index];
  3894. }
  3895. for (let i = 0; i< operation.outputs.length; i++) {
  3896. const index = reader.uint32();
  3897. operation.outputs[i] = operands[index];
  3898. }
  3899. }
  3900. for (let i = 0; i< this.inputs.length; i++) {
  3901. const index = reader.uint32();
  3902. this.inputs[i] = operands[index];
  3903. }
  3904. for (let i = 0; i< this.outputs.length; i++) {
  3905. const index = reader.uint32();
  3906. this.outputs[i] = operands[index];
  3907. }
  3908. if (reader.position !== reader.length) {
  3909. throw new pytorch.Error('Invalid NNAPI serialized model length.');
  3910. }
  3911. }
  3912. };
  3913. pytorch.nnapi.Metadata = class {
  3914. constructor() {
  3915. this._types = new Map();
  3916. // https://developer.android.com/ndk/reference/group/neural-networks
  3917. // https://github.com/pytorch/pytorch/commits/master/torch/backends/_nnapi/serializer.py
  3918. this.register( 0, 'ADD', '', [ 'A', 'B' ], [ [ 'activation', 'int32'] ], [ 'C' ]);
  3919. this.register( 1, 'AVERAGE_POOL_2D', 'Pool', [ 'input' ], [ [ 'padding_left', 'int32' ], [ 'padding_right', 'int32' ], [ 'padding_top', 'int32' ], [ 'padding_bottom', 'int32' ], [ 'stride_x', 'int32' ], [ 'stride_y', 'int32' ], [ 'filter_x', 'int32' ], [ 'filter_y', 'int32' ], [ 'activation', 'int32' ], [ 'nchw', 'boolean' ] ], [ 'output' ]);
  3920. this.register( 1, 'AVERAGE_POOL_2D', 'Pool', [ 'input' ], [ [ 'padding_scheme', 'int32' ], [ 'stride_x', 'int32' ], [ 'stride_y', 'int32' ], [ 'filter_x', 'int32' ], [ 'filter_y', 'int32' ], [ 'activation', 'int32' ], [ 'nchw', 'boolean' ] ], [ 'output' ]);
  3921. this.register( 2, 'CONCATENATION');
  3922. this.register( 3, 'CONV_2D', 'Layer', [ 'input', 'weights', 'bias' ], [ [ 'padding_left', 'int32' ], [ 'padding_right', 'int32' ], [ 'padding_top', 'int32' ], [ 'padding_bottom', 'int32' ], [ 'stride_x', 'int32' ], [ 'stride_y', 'int32' ], [ 'activation', 'int32' ], [ 'nchw', 'boolean' ], [ 'dilation_width', 'int32' ], [ 'dilation_height', 'int32' ] ], [ 'output' ]);
  3923. this.register( 3, 'CONV_2D', 'Layer', [ 'input', 'weights', 'bias' ], [ [ 'padding_scheme', 'int32' ], [ 'stride_x', 'int32' ], [ 'stride_y', 'int32' ], [ 'activation', 'int32' ], [ 'nchw', 'boolean' ], [ 'dilation_width', 'int32' ], [ 'dilation_height', 'int32' ] ], [ 'output' ]);
  3924. this.register( 4, 'DEPTHWISE_CONV_2D', 'Layer', [ 'input', 'weights', 'bias' ], [ [ 'padding_left', 'int32' ], [ 'padding_right', 'int32' ], [ 'padding_top', 'int32' ], [ 'padding_bottom', 'int32' ], [ 'stride_x', 'int32' ], [ 'stride_y', 'int32' ], [ 'activation', 'int32' ], [ 'nchw', 'boolean' ], [ 'dilation_width', 'int32' ], [ 'dilation_height', 'int32' ] ], [ 'output' ]);
  3925. this.register( 4, 'DEPTHWISE_CONV_2D', 'Layer', [ 'input', 'weights', 'bias' ], [ [ 'padding_scheme', 'int32' ], [ 'stride_x', 'int32' ], [ 'stride_y', 'int32' ], [ 'activation', 'int32' ], [ 'nchw', 'boolean' ], [ 'dilation_width', 'int32' ], [ 'dilation_height', 'int32' ] ], [ 'output' ]);
  3926. this.register( 5, 'DEPTH_TO_SPACE');
  3927. this.register( 6, 'DEQUANTIZE');
  3928. this.register( 7, 'EMBEDDING_LOOKUP');
  3929. this.register( 8, 'FLOOR');
  3930. this.register( 9, 'FULLY_CONNECTED', 'Layer', [ 'input', 'weights', 'bias' ], [ [ 'activation', 'int32' ] ], [ 'output' ]);
  3931. this.register(10, 'HASHTABLE_LOOKUP');
  3932. this.register(11, 'L2_NORMALIZATION');
  3933. this.register(12, 'L2_POOL_2D', 'Pool');
  3934. this.register(13, 'LOCAL_RESPONSE_NORMALIZATION');
  3935. this.register(14, 'LOGISTIC');
  3936. this.register(15, 'LSH_PROJECTION');
  3937. this.register(16, 'LSTM', 'Layer');
  3938. this.register(17, 'MAX_POOL_2D', 'Pool');
  3939. this.register(18, 'MUL');
  3940. this.register(19, 'RELU', 'Activation', [ 'input' ], [], [ 'output' ]);
  3941. this.register(20, 'RELU1', 'Activation');
  3942. this.register(21, 'RELU6', 'Activation');
  3943. this.register(22, 'RESHAPE', 'Shape', [ 'input', 'shape' ], [], [ 'output' ]);
  3944. this.register(23, 'RESIZE_BILINEAR');
  3945. this.register(24, 'RNN', 'Layer');
  3946. this.register(25, 'SOFTMAX', 'Activation');
  3947. this.register(26, 'SPACE_TO_DEPTH');
  3948. this.register(27, 'SVDF');
  3949. this.register(28, 'TANH');
  3950. this.register(29, 'BATCH_TO_SPACE_ND');
  3951. this.register(30, 'DIV');
  3952. this.register(31, 'MEAN');
  3953. this.register(32, 'PAD');
  3954. this.register(33, 'SPACE_TO_BATCH_ND');
  3955. this.register(34, 'SQUEEZE');
  3956. this.register(35, 'STRIDED_SLICE');
  3957. this.register(36, 'SUB');
  3958. this.register(37, 'TRANSPOSE');
  3959. this.register(38, 'ABS');
  3960. this.register(39, 'ARGMAX');
  3961. this.register(40, 'ARGMIN');
  3962. this.register(41, 'AXIS_ALIGNED_BBOX_TRANSFORM');
  3963. this.register(42, 'BIDIRECTIONAL_SEQUENCE_LSTM');
  3964. this.register(43, 'BIDIRECTIONAL_SEQUENCE_RNN');
  3965. this.register(44, 'BOX_WITH_NMS_LIMIT');
  3966. this.register(45, 'CAST');
  3967. this.register(46, 'CHANNEL_SHUFFLE');
  3968. this.register(47, 'DETECTION_POSTPROCESSING');
  3969. this.register(48, 'EQUAL');
  3970. this.register(49, 'EXP');
  3971. this.register(50, 'EXPAND_DIMS');
  3972. this.register(51, 'GATHER');
  3973. this.register(52, 'GENERATE_PROPOSALS');
  3974. this.register(53, 'GREATER');
  3975. this.register(54, 'GREATER_EQUAL');
  3976. this.register(55, 'GROUPED_CONV_2D');
  3977. this.register(56, 'HEATMAP_MAX_KEYPOINT');
  3978. this.register(57, 'INSTANCE_NORMALIZATION');
  3979. this.register(58, 'LESS');
  3980. this.register(59, 'LESS_EQUAL');
  3981. this.register(60, 'LOG');
  3982. this.register(61, 'LOGICAL_AND');
  3983. this.register(62, 'LOGICAL_NOT');
  3984. this.register(63, 'LOGICAL_OR');
  3985. this.register(64, 'LOG_SOFTMAX');
  3986. this.register(65, 'MAXIMUM');
  3987. this.register(66, 'MINIMUM');
  3988. this.register(67, 'NEG');
  3989. this.register(68, 'NOT_EQUAL');
  3990. this.register(69, 'PAD_V2');
  3991. this.register(70, 'POW');
  3992. this.register(71, 'PRELU');
  3993. this.register(72, 'QUANTIZE');
  3994. this.register(73, 'QUANTIZED_16BIT_LSTM');
  3995. this.register(74, 'RANDOM_MULTINOMIAL');
  3996. this.register(75, 'REDUCE_ALL');
  3997. this.register(76, 'REDUCE_ANY');
  3998. this.register(77, 'REDUCE_MAX');
  3999. this.register(78, 'REDUCE_MIN');
  4000. this.register(79, 'REDUCE_PROD');
  4001. this.register(80, 'REDUCE_SUM');
  4002. this.register(81, 'ROI_ALIGN');
  4003. this.register(82, 'ROI_POOLING');
  4004. this.register(83, 'RSQRT');
  4005. this.register(84, 'SELECT');
  4006. this.register(85, 'SIN');
  4007. this.register(86, 'SLICE');
  4008. this.register(87, 'SPLIT');
  4009. this.register(88, 'SQRT');
  4010. this.register(89, 'TILE');
  4011. this.register(90, 'TOPK_V2');
  4012. this.register(91, 'TRANSPOSE_CONV_2D', 'Layer');
  4013. this.register(92, 'UNIDIRECTIONAL_SEQUENCE_LSTM', 'Layer');
  4014. this.register(93, 'UNIDIRECTIONAL_SEQUENCE_RNN', 'Layer');
  4015. this.register(94, 'RESIZE_NEAREST_NEIGHBOR');
  4016. this.register(95, 'QUANTIZED_LSTM', 'Layer');
  4017. this.register(96, 'IF');
  4018. this.register(97, 'WHILE');
  4019. this.register(98, 'ELU', 'Activation');
  4020. this.register(99, 'HARD_SWISH', 'Activation');
  4021. this.register(100, 'FILL');
  4022. this.register(101, 'RANK');
  4023. }
  4024. register(index, name, category, inputs, attributes, outputs) {
  4025. inputs = inputs || [];
  4026. outputs = outputs || [];
  4027. attributes = attributes || [];
  4028. const type = {
  4029. name: name,
  4030. inputs: inputs.map((name) => { return { name: name, type: 'Tensor' }; }),
  4031. outputs: outputs.map((name) => { return { name: name, type: 'Tensor' }; }),
  4032. attributes: attributes.map((pair) => { return { name: pair[0], type: pair[1] }; })
  4033. };
  4034. if (category) {
  4035. type.category = category;
  4036. }
  4037. if (!this._types.has(index)) {
  4038. this._types.set(index, []);
  4039. }
  4040. this._types.get(index).push(type);
  4041. }
  4042. type(index, signature) {
  4043. if (!this._types.has(index)) {
  4044. this._types.set(index, { name: index.toString(), inputs: [], outputs: [], attributes: [] });
  4045. }
  4046. const types = this._types.get(index);
  4047. for (const type of types) {
  4048. const inputs = type.inputs.concat(type.attributes);
  4049. if (signature.length < inputs.length) {
  4050. let match = true;
  4051. for (let i = 0; i < inputs.length; i++) {
  4052. const input = inputs[i];
  4053. if (input.type === undefined || input.type === 'Tensor' || input.type === signature[i]) {
  4054. continue;
  4055. }
  4056. match = false;
  4057. }
  4058. if (match) {
  4059. return type;
  4060. }
  4061. }
  4062. }
  4063. return types[0];
  4064. }
  4065. };
  4066. pytorch.nnapi.Graph = class {
  4067. constructor(model) {
  4068. this._nodes = [];
  4069. this._inputs = [];
  4070. this._outputs = [];
  4071. const args = new Map();
  4072. const arg = (operand) => {
  4073. if (!args.has(operand.index)) {
  4074. const argument = new pytorch.nnapi.Argument(operand);
  4075. args.set(operand.index, argument);
  4076. }
  4077. return args.get(operand.index);
  4078. };
  4079. const metadata = new pytorch.nnapi.Metadata();
  4080. for (const operation of model.operations) {
  4081. const node = new pytorch.nnapi.Node(metadata, operation, arg);
  4082. this._nodes.push(node);
  4083. }
  4084. for (let i = 0; i < model.inputs.length; i++) {
  4085. const operand = model.inputs[i];
  4086. const argument = arg(operand);
  4087. const parameter = new pytorch.Parameter(i.toString(), true, [ argument ]);
  4088. this._inputs.push(parameter);
  4089. }
  4090. for (let i = 0; i < model.outputs.length; i++) {
  4091. const operand = model.outputs[i];
  4092. const argument = arg(operand);
  4093. const parameter = new pytorch.Parameter(i.toString(), true, [ argument ]);
  4094. this._outputs.push(parameter);
  4095. }
  4096. }
  4097. get name() {
  4098. return 'torch.classes._nnapi.Compilation';
  4099. }
  4100. get inputs() {
  4101. return this._inputs;
  4102. }
  4103. get outputs() {
  4104. return this._outputs;
  4105. }
  4106. get nodes() {
  4107. return this._nodes;
  4108. }
  4109. };
  4110. pytorch.nnapi.Argument = class {
  4111. constructor(operand) {
  4112. this._name = operand.index.toString();
  4113. const shape = new pytorch.TensorShape(operand.dimensions);
  4114. this._type = new pytorch.TensorType(operand.data_type.replace('[]', ''), shape);
  4115. this._initializer = operand.data ? new pytorch.Tensor(this._name, this._type, operand.data, true) : null;
  4116. this._scale = operand.scale;
  4117. this._zeroPoint = operand.zero_point;
  4118. }
  4119. get name() {
  4120. return this._name;
  4121. }
  4122. get type() {
  4123. return this._type;
  4124. }
  4125. get quantization() {
  4126. if (this._scale != 0 || this._zeroPoint != 0) {
  4127. return this._scale.toString() + ' * ' + (this._zeroPoint == 0 ? 'q' : ('(q - ' + this._zeroPoint.toString() + ')'));
  4128. }
  4129. return null;
  4130. }
  4131. get initializer() {
  4132. return this._initializer;
  4133. }
  4134. };
  4135. pytorch.nnapi.Node = class {
  4136. constructor(metadata, operation, arg) {
  4137. const signature = (operation.inputs || []).map((input) => input.data_type);
  4138. this._type = metadata.type(operation.index, signature);
  4139. this._inputs = [];
  4140. this._outputs = [];
  4141. this._attributes = [];
  4142. this._chain = [];
  4143. if (operation.location !== undefined) {
  4144. this._location = operation.location.toString();
  4145. }
  4146. const inputs = this._type.inputs.concat(this._type.attributes);
  4147. if (operation.inputs) {
  4148. for (let i = 0; i < operation.inputs.length; i++) {
  4149. const name = i < inputs.length ? inputs[i].name : i.toString();
  4150. const operand = operation.inputs[i];
  4151. if (operand.dimensions.length > 0) {
  4152. const argument = arg(operand);
  4153. const parameter = new pytorch.Parameter(name, true, [ argument ]);
  4154. this._inputs.push(parameter);
  4155. }
  4156. else if (name === 'activation') {
  4157. const activation = new Map([ [ 1, 19 ], [ 2, 20 ], [ 3, 21 ] ]).get(operand.value) || 0;
  4158. if (activation !== 0) {
  4159. this._chain.push(new pytorch.nnapi.Node(metadata, { index: activation }));
  4160. }
  4161. }
  4162. else {
  4163. const attribute = new pytorch.nnapi.Attribute(name, operand);
  4164. this._attributes.push(attribute);
  4165. }
  4166. }
  4167. }
  4168. if (operation.outputs) {
  4169. for (let i = 0; i < operation.outputs.length; i++) {
  4170. const name = i < inputs.length ? inputs[i].name : i.toString();
  4171. const operand = operation.outputs[i];
  4172. const argument = arg(operand);
  4173. const parameter = new pytorch.Parameter(name, true, [ argument ]);
  4174. this._outputs.push(parameter);
  4175. }
  4176. }
  4177. }
  4178. get type() {
  4179. return this._type;
  4180. }
  4181. get location() {
  4182. return this._location;
  4183. }
  4184. get inputs() {
  4185. return this._inputs;
  4186. }
  4187. get outputs() {
  4188. return this._outputs;
  4189. }
  4190. get attributes() {
  4191. return this._attributes;
  4192. }
  4193. get chain() {
  4194. return this._chain;
  4195. }
  4196. };
  4197. pytorch.nnapi.Attribute = class {
  4198. constructor(name, operand) {
  4199. this._name = name;
  4200. this._type = operand.data_type;
  4201. this._value = operand.value;
  4202. }
  4203. get type() {
  4204. return this._type;
  4205. }
  4206. get name() {
  4207. return this._name;
  4208. }
  4209. get value() {
  4210. return this._value;
  4211. }
  4212. get visible() {
  4213. return false;
  4214. }
  4215. };
  4216. pytorch.nnapi.Tensor = class {
  4217. constructor(type, data) {
  4218. this._type = type;
  4219. this._data = data;
  4220. }
  4221. get type() {
  4222. return this._type;
  4223. }
  4224. get state() {
  4225. return 'Not implemented.';
  4226. }
  4227. };
  4228. pytorch.Metadata = class {
  4229. static open(context) {
  4230. if (pytorch.Metadata._metadata) {
  4231. return Promise.resolve(pytorch.Metadata._metadata);
  4232. }
  4233. return context.request('pytorch-metadata.json', 'utf-8', null).then((data) => {
  4234. pytorch.Metadata._metadata = new pytorch.Metadata(data);
  4235. return pytorch.Metadata._metadata;
  4236. }).catch(() => {
  4237. pytorch.Metadata._metadata = new pytorch.Metadata(null);
  4238. return pytorch.Metadata._metadata;
  4239. });
  4240. }
  4241. constructor(data) {
  4242. this._types = new Map();
  4243. this._attributes = new Map();
  4244. if (data) {
  4245. const items = JSON.parse(data);
  4246. for (const item of items) {
  4247. this._types.set(item.name, item);
  4248. const index = item.name.indexOf(':');
  4249. if (index !== -1) {
  4250. const name = item.name.substring(0, index);
  4251. if (!this._types.has(name)) {
  4252. this._types.set(name, []);
  4253. }
  4254. this._types.get(name).push(item.name);
  4255. }
  4256. }
  4257. }
  4258. }
  4259. type(name) {
  4260. const schema = this._types.get(name);
  4261. if (schema) {
  4262. return Array.isArray(schema) ? schema.map((name) => this._types.get(name)) : schema;
  4263. }
  4264. return null;
  4265. }
  4266. attribute(type, name) {
  4267. const attributeName = type + ':' + name;
  4268. if (!this._attributes.has(attributeName)) {
  4269. this._attributes.set(attributeName, null);
  4270. const schema = this.type(type);
  4271. if (schema) {
  4272. if (schema.inputs) {
  4273. for (const input of schema.inputs) {
  4274. this._attributes.set(type + ':' + input.name, input);
  4275. }
  4276. }
  4277. if (schema.attributes) {
  4278. for (const attribute of schema.attributes) {
  4279. this._attributes.set(type + ':' + attribute.name, attribute);
  4280. }
  4281. }
  4282. }
  4283. }
  4284. return this._attributes.get(attributeName);
  4285. }
  4286. };
  4287. pytorch.Error = class extends Error {
  4288. constructor(message) {
  4289. super(message);
  4290. this.name = 'Error loading PyTorch model.';
  4291. }
  4292. };
  4293. if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  4294. module.exports.ModelFactory = pytorch.ModelFactory;
  4295. }