pytorch.js 153 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674
  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 = container.graphs.map((graph) => new pytorch.Graph(metadata, graph, container));
  33. }
  34. get format() {
  35. return this._format;
  36. }
  37. get graphs() {
  38. return this._graphs;
  39. }
  40. };
  41. pytorch.Graph = class {
  42. constructor(metadata, graph, container) {
  43. this._nodes = [];
  44. this._inputs = [];
  45. this._outputs = [];
  46. this._groups = true;
  47. this._littleEndian = container.littleEndian;
  48. this._name = graph.name || '';
  49. const type = graph.type;
  50. switch (type) {
  51. case 'script': {
  52. const traced = graph.trace();
  53. const initializers = new Map();
  54. if (graph.constants) {
  55. for (const constant of graph.constants) {
  56. if (pytorch.Utility.isTensor(constant)) {
  57. constant.initializer = pytorch.Utility.createTensor(constant.__variable__, constant, this._littleEndian);
  58. initializers.set(constant.__variable__, constant);
  59. }
  60. else if (constant && constant.__class__ && constant.__class__.__module__ && constant.__class__.__name__) {
  61. const type = constant.__class__.__module__ + '.' + constant.__class__.__name__;
  62. switch (type) {
  63. case '__torch__.torch.classes.xnnpack.LinearOpContext':
  64. case '__torch__.torch.classes.xnnpack.Conv2dOpContext':
  65. case '__torch__.torch.classes.quantized.LinearPackedParamsBase':
  66. case '__torch__.torch.classes.quantized.Conv2dPackedParamsBase':
  67. for (const key of Object.keys(constant)) {
  68. const value = constant[key];
  69. if (pytorch.Utility.isTensor(value)) {
  70. value.initializer = pytorch.Utility.createTensor(value.__variable__, value, this._littleEndian);
  71. initializers.set(value.__variable__, value);
  72. }
  73. }
  74. break;
  75. default:
  76. throw new pytorch.Error("Unsupported constant context '" + type + "'.");
  77. }
  78. }
  79. else {
  80. throw new pytorch.Error('Unsupported constant.');
  81. }
  82. }
  83. }
  84. if (graph.data) {
  85. const queue = [ graph.data ];
  86. while (queue.length > 0) {
  87. const module = queue.shift();
  88. if (module.__class__ && module.__class__.__module__ === '__torch__.torch.classes._nnapi' && module.__class__.__name__ === 'Compilation') {
  89. continue;
  90. }
  91. for (const key of Object.keys(module)) {
  92. if (key !== '__module__' && key !== '__name__' && key !== '__class__' && key !== '__parent__') {
  93. const obj = module[key];
  94. if (!Array.isArray(obj) && obj === Object(obj)) {
  95. if (pytorch.Utility.isTensor(obj)) {
  96. const parameter = obj;
  97. parameter.__parent__ = module;
  98. if (!parameter.initializer && parameter.storage()) {
  99. parameter.initializer = pytorch.Utility.createTensor(parameter.name, parameter, this._littleEndian);
  100. }
  101. if (parameter.__variable__ && parameter.__count__ === 1) {
  102. initializers.set(parameter.__variable__, parameter);
  103. }
  104. }
  105. else if (obj && obj.__class__) {
  106. obj.__parent__ = module;
  107. if (!obj.__id__) {
  108. obj.__id__ = key;
  109. }
  110. queue.push(obj);
  111. }
  112. }
  113. }
  114. }
  115. }
  116. }
  117. if (traced) {
  118. if (graph.inputs) {
  119. for (const input of graph.inputs) {
  120. this._inputs.push(new pytorch.Parameter(input, true, [
  121. new pytorch.Argument(input, null, null)
  122. ]));
  123. }
  124. }
  125. if (graph.outputs) {
  126. for (const output of graph.outputs) {
  127. this._outputs.push(new pytorch.Parameter(output, true, [
  128. new pytorch.Argument(output, null, null)
  129. ]));
  130. }
  131. }
  132. if (graph.nodes) {
  133. for (const node of graph.nodes) {
  134. const item = {
  135. type: node.type,
  136. node: node
  137. };
  138. this._nodes.push(new pytorch.Node(metadata, '', item, initializers));
  139. }
  140. }
  141. }
  142. if (graph) {
  143. this._loadScriptModule(metadata, container, graph.data, initializers);
  144. }
  145. break;
  146. }
  147. case 'module': {
  148. this._type = (graph.data.__module__ && graph.data.__name__) ? (graph.data.__module__ + '.' + graph.data.__name__) : '';
  149. this._loadModule(metadata, graph.data, [], []);
  150. break;
  151. }
  152. case 'weights': {
  153. for (const state_group of graph.data) {
  154. const attributes = state_group.attributes || [];
  155. const inputs = state_group.states.map((parameter) => {
  156. return new pytorch.Parameter(parameter.name, true,
  157. parameter.arguments.map((state) => {
  158. const tensor = pytorch.Utility.createTensor(state.id, pytorch.Utility.toTensor(state.value), this._littleEndian);
  159. return new pytorch.Argument(state.id, null, tensor);
  160. }));
  161. });
  162. const obj = {
  163. name: state_group.name,
  164. type: state_group.type || 'torch.nn.Module',
  165. attributes: attributes,
  166. inputs: inputs,
  167. outputs: []
  168. };
  169. this._nodes.push(new pytorch.Node(metadata, '', obj, null));
  170. }
  171. break;
  172. }
  173. default: {
  174. throw new pytorch.Error("Unsupported container type '" + type + "'.");
  175. }
  176. }
  177. }
  178. _loadModule(metadata, current, groups, inputs) {
  179. if (current.__class__ && current.__class__.__module__ !== 'torch.nn.modules.container' && (!current._modules || current._modules.size == 0)) {
  180. this._createNode(metadata, groups, '', current, inputs, false);
  181. return [];
  182. }
  183. if (!current._modules) {
  184. throw new pytorch.Error('Module does not contain modules.');
  185. }
  186. const sequential = current.__class__ && current.__class__.__module__ === 'torch.nn.modules.container' && current.__class__.__name__ === 'Sequential';
  187. for (const pair of current._modules) {
  188. const key = pair[0];
  189. const value = pair[1];
  190. if (value) {
  191. const type = value.__class__.__module__ + '.' + value.__class__.__name__;
  192. switch (type) {
  193. case 'torch.nn.modules.container.Sequential':
  194. groups.push(key);
  195. inputs = this._loadModule(metadata, value, groups, sequential ? inputs : []);
  196. groups.pop(key);
  197. break;
  198. default: {
  199. inputs = this._createNode(metadata, groups, key, value, sequential ? inputs : [], sequential);
  200. break;
  201. }
  202. }
  203. }
  204. }
  205. return inputs;
  206. }
  207. _createNode(metadata, groups, key, obj, args, output) {
  208. const type = obj.__class__.__module__ + '.' + obj.__class__.__name__;
  209. const schema = metadata.type(type);
  210. let inputSchema = [ { name: 'input'} ];
  211. if (schema && schema.inputs && schema.inputs.length > 0) {
  212. inputSchema = schema.inputs.slice();
  213. }
  214. const inputName = inputSchema.shift().name;
  215. const inputs = [];
  216. if (args.length > 0) {
  217. inputs.push(new pytorch.Parameter(inputName, true, args.map((argument) => {
  218. return new pytorch.Argument(argument, null, null);
  219. })));
  220. }
  221. const parameters = obj._parameters || obj._buffers || [];
  222. for (const parameter of parameters) {
  223. const key = parameter[0];
  224. const value = pytorch.Utility.toTensor(parameter[1]);
  225. let visible = true;
  226. let inputName = '';
  227. if (inputSchema.length > 0) {
  228. const input = inputSchema.shift();
  229. inputName = input.name;
  230. visible = input.visible === false ? false : true;
  231. }
  232. if (value) {
  233. const initializer = pytorch.Utility.createTensor('', value, this._littleEndian);
  234. inputs.push(new pytorch.Parameter(inputName || key, visible, [ new pytorch.Argument('', null, initializer) ]));
  235. }
  236. }
  237. const group = groups.join('/');
  238. const name = group ? (group + '/' + key) : key;
  239. const outputs = output ? [ new pytorch.Parameter('output', true, [ new pytorch.Argument(name, null, null) ]) ] : [];
  240. const attributes = [];
  241. for (const name of Object.keys(obj)) {
  242. if (name.startsWith('_')) {
  243. continue;
  244. }
  245. attributes.push({ name: name, value: obj[name] });
  246. }
  247. const item = {
  248. name: name,
  249. type: type,
  250. attributes: attributes,
  251. children: obj._modules && obj._modules.size > 0 ? true : false,
  252. inputs: inputs,
  253. outputs: outputs
  254. };
  255. const node = new pytorch.Node(metadata, group, item, {});
  256. this._nodes.push(node);
  257. return [ node.name ];
  258. }
  259. _loadScriptModule(metadata, container, module, initializers) {
  260. if (module) {
  261. if (pytorch.Graph._getParameters(module).length > 0 && !module.__hide__) {
  262. const item = { module: module };
  263. this._nodes.push(new pytorch.Node(metadata, '', item, initializers));
  264. }
  265. const submodules = pytorch.Graph._getSubmodules(module);
  266. for (const submodule of submodules) {
  267. this._loadScriptModule(metadata, container, submodule, initializers);
  268. }
  269. }
  270. }
  271. static _getParameters(module) {
  272. const parameters = [];
  273. if (module && module.__class__.__module__ && module.__class__.__name__) {
  274. for (const key of Object.keys(module)) {
  275. if (pytorch.Utility.isTensor(module[key])) {
  276. const parameter = module[key];
  277. parameter.__id__ = key;
  278. parameters.push(parameter);
  279. }
  280. }
  281. }
  282. return parameters;
  283. }
  284. static _getSubmodules(module) {
  285. const submodules = [];
  286. if (module && module.__class__ && module.__class__.__module__ && module.__class__.__name__) {
  287. for (const key of Object.keys(module)) {
  288. if (!key.startsWith('__')) {
  289. const value = module[key];
  290. if (value && value.__class__ && value.__module__ && value.__name__ && !pytorch.Utility.isTensor(value)) {
  291. submodules.push(value);
  292. }
  293. }
  294. }
  295. }
  296. return submodules;
  297. }
  298. get type() {
  299. return this._type;
  300. }
  301. get name() {
  302. return this._name;
  303. }
  304. get groups() {
  305. return this._groups;
  306. }
  307. get inputs() {
  308. return this._inputs;
  309. }
  310. get outputs() {
  311. return this._outputs;
  312. }
  313. get nodes() {
  314. return this._nodes;
  315. }
  316. };
  317. pytorch.Parameter = class {
  318. constructor(name, visible, args) {
  319. this._name = name;
  320. this._visible = visible;
  321. this._arguments = args;
  322. }
  323. get name() {
  324. return this._name;
  325. }
  326. get visible() {
  327. return this._visible;
  328. }
  329. get arguments() {
  330. return this._arguments;
  331. }
  332. };
  333. pytorch.Argument = class {
  334. constructor(name, type, initializer) {
  335. if (typeof name !== 'string') {
  336. throw new pytorch.Error("Invalid argument identifier '" + JSON.stringify(name) + "'.");
  337. }
  338. this._name = name;
  339. this._type = type;
  340. this._initializer = initializer;
  341. }
  342. get name() {
  343. return this._name;
  344. }
  345. get type() {
  346. if (this._initializer) {
  347. return this._initializer.type;
  348. }
  349. return this._type;
  350. }
  351. get initializer() {
  352. return this._initializer;
  353. }
  354. };
  355. pytorch.Node = class {
  356. constructor(metadata, group, item, initializers) {
  357. this._group = group || '';
  358. this._name = item.name || '';
  359. const type = (metadata, name) => {
  360. if (name instanceof pytorch.nnapi.Graph) {
  361. this._type = name;
  362. return;
  363. }
  364. this._type = Object.assign({}, metadata.type(name) || { name: name });
  365. const identifier = this._type.name;
  366. this._type.identifier = identifier;
  367. const index = identifier.indexOf(':');
  368. this._type.name = index === -1 ? identifier : identifier.substring(0, index);
  369. };
  370. if (!item.module && !item.node) {
  371. type(metadata, item.type);
  372. this._nodes = item.children;
  373. this._inputs = item.inputs;
  374. this._outputs = item.outputs;
  375. this._attributes = item.attributes.map((attribute) => {
  376. const schema = metadata.attribute(this._type.identifier, attribute.name);
  377. return new pytorch.Attribute(schema, attribute.name, attribute.value);
  378. });
  379. }
  380. else {
  381. this._attributes = [];
  382. this._inputs = [];
  383. this._outputs = [];
  384. let module = item.module;
  385. if (module) {
  386. this._type = { name: 'torch.nn.modules.module.Module' };
  387. for (const parameter of pytorch.Graph._getParameters(module)) {
  388. this._inputs.push(new pytorch.Parameter(parameter.__id__, true, [
  389. new pytorch.Argument('', null, parameter.initializer || null)
  390. ]));
  391. if (parameter.__variable__) {
  392. this._outputs.push(new pytorch.Parameter(parameter.__id__, true, [
  393. new pytorch.Argument(parameter.__variable__, null, null)
  394. ]));
  395. }
  396. }
  397. }
  398. if (item.node) {
  399. type(metadata, item.type);
  400. module = null;
  401. let match = true;
  402. let count = 0;
  403. for (const input of item.node.inputs) {
  404. for (const argument of input) {
  405. const parameter = initializers.get(argument.id);
  406. if (parameter) {
  407. if (parameter.__parent__ && (module == null || module == parameter.__parent__)) {
  408. module = parameter.__parent__;
  409. count++;
  410. }
  411. else if (parameter.__variable__.startsWith('CONSTANTS.c')) {
  412. argument.initializer = parameter.initializer;
  413. count++;
  414. }
  415. else {
  416. match = false;
  417. break;
  418. }
  419. }
  420. }
  421. if (!match) {
  422. break;
  423. }
  424. }
  425. if (module) {
  426. const params = pytorch.Graph._getParameters(module).filter((p) => p.__id__ !== 'num_batches_tracked');
  427. if (params.length == count && match) {
  428. module.__hide__ = true;
  429. for (const input of item.node.inputs) {
  430. for (const argument of input) {
  431. const parameter = initializers.get(argument.id);
  432. if (parameter && parameter.initializer) {
  433. argument.initializer = parameter.initializer;
  434. }
  435. }
  436. }
  437. }
  438. else {
  439. module = null;
  440. }
  441. }
  442. for (let inputIndex = 0; inputIndex < item.node.inputs.length; inputIndex++) {
  443. let inputName = inputIndex.toString();
  444. if (this._type && this._type.inputs && this._type.inputs.length > inputIndex) {
  445. inputName = this._type.inputs[inputIndex].name;
  446. }
  447. this._inputs.push(new pytorch.Parameter(inputName, true,
  448. item.node.inputs[inputIndex].map((input) => new pytorch.Argument(input.id, null, input.initializer || null))
  449. ));
  450. }
  451. for (let outputIndex = 0; outputIndex < item.node.outputs.length; outputIndex++) {
  452. let outputName = outputIndex.toString();
  453. if (this._type && this._type.outputs && this._type.outputs.length > outputIndex) {
  454. outputName = this._type.outputs[outputIndex].name;
  455. }
  456. this._outputs.push(new pytorch.Parameter(outputName, true,
  457. item.node.outputs[outputIndex].map((output) => new pytorch.Argument(output.id, null, null))
  458. ));
  459. }
  460. for (const attribute of item.node.attributes) {
  461. const name = attribute.name;
  462. const value = attribute.value;
  463. const schema = metadata.attribute(this._type.identifier, name);
  464. this._attributes.push(new pytorch.Attribute(schema, name, value));
  465. }
  466. }
  467. if (module) {
  468. if (module.__id__) {
  469. let current = module;
  470. this._name = current.__id__;
  471. while (current.__parent__ != null) {
  472. current = current.__parent__;
  473. if (!current.__parent__ && !current.__id__) {
  474. break;
  475. }
  476. this._name = [ current.__id__, this._name ].join('.');
  477. }
  478. }
  479. }
  480. }
  481. }
  482. get name() {
  483. return this._name;
  484. }
  485. get group() {
  486. return this._group;
  487. }
  488. get type() {
  489. return this._type;
  490. }
  491. get attributes() {
  492. return this._attributes;
  493. }
  494. get inputs() {
  495. return this._inputs;
  496. }
  497. get outputs() {
  498. return this._outputs;
  499. }
  500. get nodes() {
  501. return this._nodes;
  502. }
  503. };
  504. pytorch.Attribute = class {
  505. constructor(metadata, name, value) {
  506. this._name = name;
  507. this._value = value;
  508. if (this._name === 'training') {
  509. this._visible = false;
  510. this._type = 'boolean';
  511. }
  512. else if (metadata) {
  513. if (metadata.type) {
  514. this._type = metadata.type;
  515. }
  516. if (metadata.visible === false) {
  517. this._visible = false;
  518. }
  519. else if (metadata.default !== undefined) {
  520. if (Array.isArray(value)) {
  521. if (Array.isArray(metadata.default)) {
  522. this._visible = value.length !== metadata.default || !this.value.every((item, index) => item == metadata.default[index]);
  523. }
  524. else {
  525. this._visible = !this.value.every((item) => item == metadata.default);
  526. }
  527. }
  528. else {
  529. this._visible = this.value !== metadata.default;
  530. }
  531. }
  532. }
  533. if (Array.isArray(value) && value.length > 0 && value.every((obj) => obj && obj.__class__ && obj.__class__.__module__ && obj.__class__.__module__.startsWith('torch.nn'))) {
  534. this._value = '?';
  535. }
  536. }
  537. get type() {
  538. return this._type;
  539. }
  540. get name() {
  541. return this._name;
  542. }
  543. get value() {
  544. return this._value;
  545. }
  546. get visible() {
  547. return this._visible == false ? false : true;
  548. }
  549. };
  550. pytorch.Tensor = class {
  551. constructor(name, type, data, littleEndian) {
  552. this._name = name || '';
  553. this._type = type;
  554. this._data = data;
  555. this._littleEndian = littleEndian;
  556. }
  557. get kind() {
  558. return 'Tensor';
  559. }
  560. get name() {
  561. return this._name;
  562. }
  563. get type() {
  564. return this._type;
  565. }
  566. get state() {
  567. return this._context().state;
  568. }
  569. get value() {
  570. const context = this._context();
  571. if (context.state) {
  572. return null;
  573. }
  574. context.limit = Number.MAX_SAFE_INTEGER;
  575. return this._decode(context, 0);
  576. }
  577. toString() {
  578. const context = this._context();
  579. if (context.state) {
  580. return '';
  581. }
  582. context.limit = 10000;
  583. const value = this._decode(context, 0);
  584. return pytorch.Tensor._stringify(value, '', ' ');
  585. }
  586. _context() {
  587. const context = {};
  588. context.state = null;
  589. context.index = 0;
  590. context.count = 0;
  591. if (!this._type.dataType) {
  592. context.state = 'Tensor has no data type.';
  593. return context;
  594. }
  595. switch (this._type.dataType) {
  596. case 'boolean':
  597. case 'uint8':
  598. case 'qint8':
  599. case 'int8':
  600. case 'int16':
  601. case 'int32':
  602. case 'int64':
  603. case 'float16':
  604. case 'float32':
  605. case 'float64':
  606. case 'bfloat16':
  607. case 'complex64':
  608. case 'complex128':
  609. break;
  610. default:
  611. context.state = "Tensor data type '" + this._type.dataType + "' is not implemented.";
  612. return context;
  613. }
  614. if (!this._type.shape) {
  615. context.state = 'Tensor has no dimensions.';
  616. return context;
  617. }
  618. if (!this._data) {
  619. context.state = 'Tensor data is empty.';
  620. return context;
  621. }
  622. try {
  623. context.data = this._data instanceof Uint8Array ? this._data : this._data.peek();
  624. }
  625. catch (err) {
  626. context.state = err.message;
  627. return context;
  628. }
  629. context.dataType = this._type.dataType;
  630. context.dimensions = this._type.shape.dimensions;
  631. context.view = new DataView(context.data.buffer, context.data.byteOffset, context.data.byteLength);
  632. return context;
  633. }
  634. _decode(context, dimension) {
  635. const results = [];
  636. const dimensions = (context.dimensions.length == 0) ? [ 1 ] : context.dimensions;
  637. const size = dimensions[dimension];
  638. if (dimension == dimensions.length - 1) {
  639. for (let i = 0; i < size; i++) {
  640. if (context.count > context.limit) {
  641. results.push('...');
  642. return results;
  643. }
  644. switch (context.dataType) {
  645. case 'boolean':
  646. results.push(context.view.getUint8(context.index) === 0 ? false : true);
  647. context.index++;
  648. context.count++;
  649. break;
  650. case 'uint8':
  651. results.push(context.view.getUint8(context.index));
  652. context.index++;
  653. context.count++;
  654. break;
  655. case 'qint8':
  656. case 'int8':
  657. results.push(context.view.getInt8(context.index));
  658. context.index++;
  659. context.count++;
  660. break;
  661. case 'int16':
  662. results.push(context.view.getInt16(context.index, this._littleEndian));
  663. context.index += 2;
  664. context.count++;
  665. break;
  666. case 'int32':
  667. results.push(context.view.getInt32(context.index, this._littleEndian));
  668. context.index += 4;
  669. context.count++;
  670. break;
  671. case 'int64':
  672. results.push(context.view.getInt64(context.index, this._littleEndian));
  673. context.index += 8;
  674. context.count++;
  675. break;
  676. case 'float16':
  677. results.push(context.view.getFloat16(context.index, this._littleEndian));
  678. context.index += 2;
  679. context.count++;
  680. break;
  681. case 'float32':
  682. results.push(context.view.getFloat32(context.index, this._littleEndian));
  683. context.index += 4;
  684. context.count++;
  685. break;
  686. case 'float64':
  687. results.push(context.view.getFloat64(context.index, this._littleEndian));
  688. context.index += 8;
  689. context.count++;
  690. break;
  691. case 'bfloat16':
  692. results.push(context.view.getBfloat16(context.index, this._littleEndian));
  693. context.index += 2;
  694. context.count++;
  695. break;
  696. case 'complex64':
  697. results.push(context.view.getComplex64(i << 3, this._littleEndian));
  698. context.index += 8;
  699. context.count++;
  700. break;
  701. case 'complex128':
  702. results.push(context.view.getComplex128(i << 4, this._littleEndian));
  703. context.index += 16;
  704. context.count++;
  705. break;
  706. default:
  707. throw new pytorch.Error("Unsupported tensor data type '" + context.dataType + "'.");
  708. }
  709. }
  710. }
  711. else {
  712. for (let j = 0; j < size; j++) {
  713. if (context.count > context.limit) {
  714. results.push('...');
  715. return results;
  716. }
  717. results.push(this._decode(context, dimension + 1));
  718. }
  719. }
  720. if (context.dimensions.length == 0) {
  721. return results[0];
  722. }
  723. return results;
  724. }
  725. static _stringify(value, indentation, indent) {
  726. if (Array.isArray(value)) {
  727. const result = [];
  728. result.push(indentation + '[');
  729. const items = value.map((item) => pytorch.Tensor._stringify(item, indentation + indent, indent));
  730. if (items.length > 0) {
  731. result.push(items.join(',\n'));
  732. }
  733. result.push(indentation + ']');
  734. return result.join('\n');
  735. }
  736. switch (typeof value) {
  737. case 'boolean':
  738. return indentation + value.toString();
  739. case 'string':
  740. return indentation + value;
  741. case 'number':
  742. if (value == Infinity) {
  743. return indentation + 'Infinity';
  744. }
  745. if (value == -Infinity) {
  746. return indentation + '-Infinity';
  747. }
  748. if (isNaN(value)) {
  749. return indentation + 'NaN';
  750. }
  751. return indentation + value.toString();
  752. default:
  753. if (value && value.toString) {
  754. return indentation + value.toString();
  755. }
  756. return indentation + '(undefined)';
  757. }
  758. }
  759. };
  760. pytorch.TensorType = class {
  761. constructor(dataType, shape) {
  762. this._dataType = dataType;
  763. this._shape = shape;
  764. }
  765. get dataType() {
  766. return this._dataType;
  767. }
  768. get shape() {
  769. return this._shape;
  770. }
  771. toString() {
  772. return this._dataType + this._shape.toString();
  773. }
  774. };
  775. pytorch.TensorShape = class {
  776. constructor(dimensions) {
  777. this._dimensions = dimensions || [];
  778. }
  779. get dimensions() {
  780. return this._dimensions;
  781. }
  782. toString() {
  783. if (this._dimensions && this._dimensions.length > 0) {
  784. return '[' + this._dimensions.map((dimension) => dimension.toString()).join(',') + ']';
  785. }
  786. return '';
  787. }
  788. };
  789. pytorch.Execution = class extends python.Execution {
  790. constructor(sources, exceptionCallback) {
  791. super(sources, exceptionCallback);
  792. const self = this;
  793. this.registerType('__torch__.torch.classes._nnapi.Compilation', class {
  794. constructor() {
  795. this.__hide__ = true;
  796. }
  797. __init__() {
  798. }
  799. init(serialized_model_tensor, parameter_buffers) {
  800. this.serialized_model_tensor = serialized_model_tensor;
  801. this.parameter_buffers = parameter_buffers;
  802. const buffers = parameter_buffers.map((buffer) => buffer.__source__.storage().data);
  803. const serialized_model = serialized_model_tensor.storage().data;
  804. this.serialized_model = new pytorch.nnapi.SerializedModel(serialized_model, buffers);
  805. }
  806. run(inputs, outputs) {
  807. this.serialized_model_tensor.__variable__ = this.serialized_model_tensor.__variable__ || self.variable();
  808. this.serialized_model_tensor.__count__ = (this.serialized_model_tensor.__count__ || 0) + 1;
  809. self.push({
  810. type: new pytorch.nnapi.Graph(this.serialized_model),
  811. attributes: [],
  812. inputs: [
  813. inputs.map((input) => { return { id: input.__variable__ }; }),
  814. // [ { id: this.serialized_model_tensor.__variable__ } ] //,
  815. // this.parameter_buffers.map((buffer) => { return { id: buffer.__variable__ }; })
  816. ],
  817. outputs: [
  818. outputs.map((output) => { return { id: output.__variable__ }; })
  819. ],
  820. });
  821. }
  822. });
  823. this.registerType('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', class {
  824. __setstate__(state) {
  825. const pack_version = state[0];
  826. if (pack_version !== '2') {
  827. throw new pytorch.Error("Unsupported pack version '" + pack_version.toString() + "'.");
  828. }
  829. const tensors = state[1];
  830. const opt_tensors = state[2];
  831. const packed_config = pytorch.Utility.createTensor('', tensors[0], true).value;
  832. this.weight = tensors[1];
  833. this.bias = opt_tensors[0];
  834. this.stride = [ packed_config[1], packed_config[2] ];
  835. this.padding = [ packed_config[3], packed_config[4] ];
  836. this.dilation = [ packed_config[5], packed_config[6] ];
  837. this.output_padding = [ packed_config[7], packed_config[8] ];
  838. this.groups = packed_config[9];
  839. }
  840. });
  841. this.registerType('__torch__.torch.classes.quantized.Conv3dPackedParamsBase', class {
  842. __setstate__(state) {
  843. const pack_version = state[0];
  844. if (pack_version !== '2') {
  845. throw new pytorch.Error("Unsupported pack version '" + pack_version.toString() + "'.");
  846. }
  847. const tensors = state[1];
  848. const opt_tensors = state[2];
  849. const packed_config = pytorch.Utility.createTensor('', tensors[0], true).value;
  850. this.weight = tensors[1];
  851. this.bias = opt_tensors[0];
  852. this.stride = [ packed_config[1], packed_config[2] ];
  853. this.padding = [ packed_config[3], packed_config[4] ];
  854. this.dilation = [ packed_config[5], packed_config[6] ];
  855. this.output_padding = [ packed_config[7], packed_config[8] ];
  856. this.groups = packed_config[9];
  857. }
  858. });
  859. this.registerType('__torch__.torch.classes.quantized.LinearPackedParamsBase', class {
  860. __setstate__(state) {
  861. this.weight = state[0];
  862. this.bias = state[1];
  863. }
  864. });
  865. this.registerType('__torch__.torch.classes.xnnpack.Conv2dOpContext', class {
  866. __setstate__(state) {
  867. this.weight = state[0];
  868. this.bias = state[1];
  869. this.stride = state[2];
  870. this.padding = state[3];
  871. this.dilation = state[4];
  872. this.groups = state[5];
  873. this.output_min = state[6];
  874. this.output_max = state[7];
  875. }
  876. });
  877. this.registerType('__torch__.torch.classes.xnnpack.LinearOpContext', class {
  878. __setstate__(state) {
  879. this.weight = state[0];
  880. this.bias = state[1];
  881. this.output_min = state[2];
  882. this.output_max = state[3];
  883. }
  884. });
  885. }
  886. debug(file) {
  887. const buffer = this.source(file + '.debug_pkl');
  888. if (buffer) {
  889. return null;
  890. // const unpickler = python.Unpickler.open(buffer, this);
  891. // return unpickler.load();
  892. }
  893. return null;
  894. }
  895. };
  896. pytorch.Container = class {
  897. static open(context) {
  898. const zip = pytorch.Container.Zip.open(context.entries('zip'));
  899. if (zip) {
  900. return zip;
  901. }
  902. const pickle = pytorch.Container.Pickle.open(context.stream);
  903. if (pickle) {
  904. return pickle;
  905. }
  906. const tar = pytorch.Container.Tar.open(context.entries('tar'));
  907. if (tar) {
  908. return tar;
  909. }
  910. return null;
  911. }
  912. };
  913. pytorch.Container.Tar = class {
  914. static open(entries) {
  915. if (entries.has('pickle')) {
  916. return new pytorch.Container.Tar(entries);
  917. }
  918. return null;
  919. }
  920. constructor(entries) {
  921. this._entries = entries;
  922. this._graphs = [ this ];
  923. }
  924. set metadata(value) {
  925. this._metadata = value;
  926. }
  927. set exception(value) {
  928. this._exceptionCallack = value;
  929. }
  930. get format() {
  931. return 'PyTorch v0.1.1';
  932. }
  933. get graphs() {
  934. this._unpickle();
  935. return this._graphs;
  936. }
  937. get littleEndian() {
  938. this._unpickle();
  939. return this._littleEndian;
  940. }
  941. _unpickle() {
  942. if (!this._entries) {
  943. return;
  944. }
  945. this._type = '';
  946. this._data = null;
  947. this._littleEndian = true;
  948. const execution = new pytorch.Execution(null, this._exceptionCallback);
  949. const entries = {};
  950. for (const entry of this._entries) {
  951. const key = entry[0];
  952. const value = entry[1];
  953. entries[key] = value.peek();
  954. }
  955. this._exceptionCallback = null;
  956. this._entries = null;
  957. if (entries.sys_info) {
  958. const unpickler = python.Unpickler.open(entries.sys_info, execution);
  959. const sys_info = unpickler.load();
  960. if (sys_info.protocol_version != 1000) {
  961. throw new pytorch.Error("Unsupported protocol version '" + sys_info.protocol_version + "'.");
  962. }
  963. if (sys_info.type_sizes &&
  964. ((sys_info.type_sizes.int && sys_info.type_sizes.int != 4) ||
  965. (sys_info.type_sizes.long && sys_info.type_sizes.long != 4) ||
  966. (sys_info.type_sizes.short && sys_info.type_sizes.short != 2))) {
  967. throw new pytorch.Error('Unsupported type sizes.');
  968. }
  969. this._littleEndian = sys_info.little_endian;
  970. }
  971. const deserialized_objects = {};
  972. if (entries.storages) {
  973. const data = entries.storages;
  974. const unpickler = python.Unpickler.open(data, execution);
  975. const num_storages = unpickler.load();
  976. for (let i = 0; i < num_storages; i++) {
  977. const args = unpickler.load();
  978. const key = args[0];
  979. const storage_type = args[2];
  980. const obj = storage_type._new_with_file(unpickler);
  981. deserialized_objects[key] = obj;
  982. }
  983. /*
  984. let storage_views = unpickler.load();
  985. for target_cdata, root_cdata, offset, size in storage_views:
  986. root = deserialized_objects[root_cdata]
  987. deserialized_objects[target_cdata] = root[offset:offset + size]
  988. */
  989. }
  990. if (entries.tensors) {
  991. const data = entries.tensors;
  992. const unpickler = python.Unpickler.open(data, execution);
  993. const num_tensors = unpickler.load();
  994. for (let i = 0; i < num_tensors; i++) {
  995. const args = unpickler.load();
  996. const key = args[0];
  997. const storage_id = args[1];
  998. const storage = deserialized_objects[storage_id];
  999. const int32 = (unpickler) => {
  1000. const buffer = unpickler.read(4);
  1001. const reader = new base.BinaryReader(buffer);
  1002. return reader.int32();
  1003. };
  1004. const int64 = (unpickler) => {
  1005. const buffer = unpickler.read(8);
  1006. const reader = new base.BinaryReader(buffer);
  1007. return reader.int64();
  1008. };
  1009. const ndim = int32(unpickler);
  1010. unpickler.read(4);
  1011. const shape = new Array(ndim);
  1012. for (let j = 0; j < ndim; j++) {
  1013. shape[j] = int64(unpickler);
  1014. }
  1015. const stride = new Array(ndim);
  1016. for (let j = 0; j < ndim; j++) {
  1017. stride[j] = int64(unpickler);
  1018. }
  1019. const storage_offset = int64(unpickler);
  1020. const tensor = execution.invoke('torch._utils._rebuild_tensor', [ storage, storage_offset, shape, stride ]);
  1021. deserialized_objects[key] = tensor;
  1022. }
  1023. }
  1024. if (entries.pickle) {
  1025. const unpickler = python.Unpickler.open(entries.pickle, execution);
  1026. unpickler.persistent_load = (saved_id) => deserialized_objects[saved_id];
  1027. const obj = unpickler.load();
  1028. const weights = pytorch.Utility.findWeights(obj);
  1029. if (weights) {
  1030. this._graphs = weights;
  1031. for (const graph of this._graphs) {
  1032. graph.type = 'weights';
  1033. }
  1034. }
  1035. else {
  1036. throw new pytorch.Error('File does not contain root module or state dictionary.');
  1037. }
  1038. }
  1039. }
  1040. };
  1041. pytorch.Container.Pickle = class {
  1042. static open(stream) {
  1043. const signature = [ 0x80, undefined, 0x8a, 0x0a, 0x6c, 0xfc, 0x9c, 0x46, 0xf9, 0x20, 0x6a, 0xa8, 0x50, 0x19 ];
  1044. if (stream && signature.length <= stream.length && stream.peek(signature.length).every((value, index) => signature[index] === undefined || signature[index] === value)) {
  1045. return new pytorch.Container.Pickle(stream);
  1046. }
  1047. return null;
  1048. }
  1049. constructor(stream) {
  1050. this._stream = stream;
  1051. this._graphs = [ this ];
  1052. }
  1053. set metadata(value) {
  1054. this._metadata = value;
  1055. }
  1056. set exception(value) {
  1057. this._exceptionCallback = value;
  1058. }
  1059. get format() {
  1060. return 'PyTorch v0.1.10';
  1061. }
  1062. get graphs() {
  1063. this._unpickle();
  1064. return this._graphs;
  1065. }
  1066. get littleEndian() {
  1067. this._unpickle();
  1068. return this._littleEndian;
  1069. }
  1070. _unpickle() {
  1071. if (!this._stream) {
  1072. return;
  1073. }
  1074. const data = this._stream.length < 0x7ffff000 ? this._stream.peek() : this._stream;
  1075. const execution = new pytorch.Execution(null, this._exceptionCallback);
  1076. const unpickler = python.Unpickler.open(data, execution);
  1077. this._stream = null;
  1078. this._exceptionCallback = null;
  1079. unpickler.load(); // magic_number
  1080. const protocol_version = unpickler.load();
  1081. if (protocol_version != 1001) {
  1082. throw new pytorch.Error("Unsupported protocol version '" + protocol_version + "'.");
  1083. }
  1084. const sys_info = unpickler.load();
  1085. if (sys_info.protocol_version != 1001) {
  1086. throw new pytorch.Error("Unsupported protocol version '" + sys_info.protocol_version + "'.");
  1087. }
  1088. this._littleEndian = sys_info.little_endian;
  1089. const module_source_map = new Map();
  1090. const deserialized_objects = new Map();
  1091. unpickler.persistent_load = (saved_id) => {
  1092. const typename = saved_id.shift();
  1093. const data = saved_id;
  1094. switch (typename) {
  1095. case 'module': {
  1096. const module = data[0];
  1097. const source = data[2];
  1098. module_source_map.set(module, source);
  1099. return data[0];
  1100. }
  1101. case 'storage': {
  1102. const storage_type = data.shift();
  1103. const root_key = data.shift();
  1104. data.shift(); // location
  1105. const size = data.shift();
  1106. const view_metadata = data.shift();
  1107. if (!deserialized_objects.has(root_key)) {
  1108. const obj = new storage_type(size);
  1109. deserialized_objects.set(root_key, obj);
  1110. }
  1111. if (view_metadata) {
  1112. const view_key = view_metadata.shift();
  1113. view_metadata.shift(); // view_offset
  1114. view_metadata.shift(); // view_size
  1115. if (!deserialized_objects.has(view_key)) {
  1116. const view = null; // storage.slice(view_offset, view_offset + view_size);
  1117. deserialized_objects.set(view_key, view);
  1118. }
  1119. return deserialized_objects.get(view_key);
  1120. }
  1121. return deserialized_objects.get(root_key);
  1122. }
  1123. default: {
  1124. throw new pytorch.Error("Unsupported persistent load type '" + typename + "'.");
  1125. }
  1126. }
  1127. };
  1128. const obj = unpickler.load();
  1129. if (!obj) {
  1130. throw new pytorch.Error('File format is not PyTorch.');
  1131. }
  1132. if (obj === 'None') {
  1133. throw new pytorch.Error("File contains 'None' root object.");
  1134. }
  1135. const deserialized_storage_keys = unpickler.load();
  1136. for (const deserialized_storage_key of deserialized_storage_keys) {
  1137. const storage = deserialized_objects.get(deserialized_storage_key);
  1138. storage._set_from_file(unpickler);
  1139. }
  1140. this._graphs = pytorch.Utility.find(obj);
  1141. }
  1142. };
  1143. pytorch.Container.Zip = class {
  1144. static open(entries) {
  1145. if (entries.size > 0) {
  1146. let prefix = [];
  1147. const paths = Array.from(entries.keys()).map((path) => path.split('/').reverse());
  1148. for (;;) {
  1149. const set = new Set(paths.map((path) => path.length > 0 ? path.pop() : null));
  1150. if (set.size !== 1 || set.keys().next().value === null) {
  1151. break;
  1152. }
  1153. prefix.push(set.keys().next().value);
  1154. }
  1155. prefix = prefix.join('/');
  1156. prefix = prefix.length > 0 ? prefix + '/' : prefix;
  1157. entries = new Map(Array.from(entries).map((entry) => [ entry[0].substring(prefix.length), entry[1] ]));
  1158. if (entries.has('model.json')) {
  1159. try {
  1160. const stream = entries.get('model.json');
  1161. const buffer = stream.peek();
  1162. const decoder = new TextDecoder('utf-8');
  1163. const content = decoder.decode(buffer);
  1164. const model = JSON.parse(content);
  1165. if (model.mainModule) {
  1166. return new pytorch.Container.Zip.Json(entries, model);
  1167. }
  1168. }
  1169. catch (error) {
  1170. // continue regardless of error
  1171. }
  1172. }
  1173. if (entries.has('data.pkl')) {
  1174. return new pytorch.Container.Zip.Pickle(entries);
  1175. }
  1176. if (Array.from(entries.keys()).find((name) => name.startsWith('.data/'))) {
  1177. return new pytorch.Container.Zip.Package(entries);
  1178. }
  1179. }
  1180. return null;
  1181. }
  1182. constructor(entries) {
  1183. // https://github.com/pytorch/pytorch/blob/master/torch/csrc/jit/docs/serialization.md
  1184. this._entries = entries;
  1185. this._producer = '';
  1186. }
  1187. set metadata(value) {
  1188. this._metadata = value;
  1189. }
  1190. set exception(value) {
  1191. this._exceptionCallback = value;
  1192. }
  1193. get producer() {
  1194. return this._producer;
  1195. }
  1196. get littleEndian() {
  1197. return true;
  1198. }
  1199. version(name) {
  1200. const stream = this._entries.get(name);
  1201. if (stream) {
  1202. const decoder = new TextDecoder('utf-8');
  1203. const buffer = stream.peek();
  1204. const text = decoder.decode(buffer);
  1205. const value = text.split('\n').shift();
  1206. // https://github.com/pytorch/pytorch/blob/master/caffe2/serialize/inline_container.h
  1207. // kProducedFileFormatVersion
  1208. const versions = new Map([
  1209. [ '1', 'v1.3' ],
  1210. [ '2', 'v1.5' ], // 7a2889b014ce36fcc333b2c6de6f29f976652f84 (#28122)
  1211. [ '3', 'v1.6' ], // 2ec6a30722b0ef85632a2f3e7ce6f80da403008a (#36085)
  1212. [ '4', 'v1.6' ], // 95489b590f00801bdee7f41783f30874883cf6bb (#38620)
  1213. [ '5', 'v1.7' ], // cb26661fe4faf26386703180a9045e6ac6d157df (#40364)
  1214. [ '6', 'v1.9' ], // 3ee7637ffa50df0d9b231c7b40778ac1c390bf4a (#59714)
  1215. [ '7', 'v1.10' ], // 880098a7e34a20628f960daa8eab0eb1ad566c39 (#63651)
  1216. [ '8', 'v1.11' ], // b28e696516a7f0c7a6ead6da967590ce6c1d6698 (#71486)
  1217. [ '9', 'v1.11' ], // 8757e21c6a4fc00e83539aa7f9c28eb11eff53c1 (#72051)
  1218. [ '10', 'v1.12' ] // 4f8b986e28736b59bc46cd0873a0f36fdaa6f5b8 (#61439)
  1219. ]);
  1220. if (!versions.has(value)) {
  1221. this._exceptionCallback(new pytorch.Error("Unsupported PyTorch Zip version '" + value + "'."));
  1222. }
  1223. return versions.get(value) || 'v-' + value.toString();
  1224. }
  1225. return '';
  1226. }
  1227. };
  1228. pytorch.Container.Zip.Script = class {
  1229. constructor(entries, execution, location, name) {
  1230. this._entries = entries;
  1231. this._execution = execution;
  1232. this._location = location || {};
  1233. this._name = name || '';
  1234. }
  1235. get name() {
  1236. return this._name;
  1237. }
  1238. get type() {
  1239. return 'script';
  1240. }
  1241. trace() {
  1242. this._inputs = [];
  1243. this._outputs = [];
  1244. this.execution.reset();
  1245. if (this.data.forward) {
  1246. const args = [ this.data ]; // self
  1247. if (this.data.forward.__code__ && this.data.forward.__code__.parameters) {
  1248. for (const parameter of this.data.forward.__code__.parameters) {
  1249. const defaultValue = (type, name) => {
  1250. if (type.type === 'type' && type.name.type) {
  1251. switch (type.name.value) {
  1252. case 'Tensor': {
  1253. const tensor = this.execution.invoke('torch.Tensor', []);
  1254. tensor.__variable__ = name;
  1255. tensor.__origin__ = 'graph-input';
  1256. return tensor;
  1257. }
  1258. case 'Tuple': {
  1259. return type.arguments.map((type, index) => defaultValue(type, name + '[' + index.toString() + ']'));
  1260. }
  1261. case 'List': {
  1262. return type.arguments.map((type, index) => defaultValue(type, name + '[' + index.toString() + ']' ));
  1263. }
  1264. case 'Dict': {
  1265. if (type.arguments[1].name.value === 'Tensor') {
  1266. const Dict = class extends Map {
  1267. get(key) {
  1268. if (!super.has(key)) {
  1269. super.set(key, defaultValue(type.arguments[1], name + ':' + key));
  1270. }
  1271. return super.get(key);
  1272. }
  1273. };
  1274. return new Dict();
  1275. }
  1276. return new Map();
  1277. }
  1278. case 'int': {
  1279. return 0;
  1280. }
  1281. case 'float': {
  1282. return 0.0;
  1283. }
  1284. case 'bool': {
  1285. return false;
  1286. }
  1287. case 'Optional': {
  1288. return undefined;
  1289. }
  1290. case 'str':
  1291. return '';
  1292. default: {
  1293. break;
  1294. }
  1295. }
  1296. }
  1297. throw new pytorch.Error("Unsupported function parameter type '" + JSON.stringify(type) + "'.");
  1298. };
  1299. if (parameter.name !== 'self') {
  1300. const type = parameter.parameterType;
  1301. const value = defaultValue(type, parameter.name);
  1302. if (pytorch.Utility.isTensor(value)) {
  1303. value.__variable__ = parameter.name;
  1304. value.__origin__ = 'graph-input';
  1305. this._inputs.push(parameter.name);
  1306. }
  1307. args.push(value);
  1308. }
  1309. }
  1310. }
  1311. const result = this.data.forward.__call__(args);
  1312. if (Array.isArray(result)) {
  1313. for (const output of result) {
  1314. if (pytorch.Utility.isTensor(output)) {
  1315. this._outputs.push(output.__variable__);
  1316. }
  1317. }
  1318. }
  1319. else if (pytorch.Utility.isTensor(result)) {
  1320. this._outputs.push(result.__variable__);
  1321. }
  1322. else if (Object(result) === result) {
  1323. for (const key of Object.keys(result)) {
  1324. const value = result[key];
  1325. if (Array.isArray(value)) {
  1326. for (const output of value) {
  1327. if (pytorch.Utility.isTensor(output)) {
  1328. this._outputs.push(output.__variable__);
  1329. }
  1330. }
  1331. }
  1332. else if (pytorch.Utility.isTensor(value)) {
  1333. this._outputs.push(value.__variable__);
  1334. }
  1335. }
  1336. }
  1337. this._nodes = this.execution.nodes;
  1338. return true;
  1339. }
  1340. throw new pytorch.Error("Module 'forward' not implemented.");
  1341. }
  1342. get execution() {
  1343. const directory = this._location.code || 'code/';
  1344. const sources = new Map();
  1345. for (const entry of this._entries) {
  1346. const name = entry[0];
  1347. if (name.startsWith(directory) && name.endsWith('.py')) {
  1348. const file = name.substring(directory.length);
  1349. if (sources.has(file)) {
  1350. throw new pytorch.Error("Duplicate source file '" + file + "'.");
  1351. }
  1352. const stream = entry[1];
  1353. const buffer = stream.peek();
  1354. this._execution.add(file, buffer);
  1355. sources.set(file, buffer);
  1356. }
  1357. }
  1358. const torch = this._execution.import('torch');
  1359. this._execution.builtins.torch = torch;
  1360. this._execution.builtins.Tensor = torch.Tensor;
  1361. this._execution.builtins.ops = torch.ops;
  1362. this._execution.builtins.inf = torch.inf;
  1363. const constants = {};
  1364. for (let i = 0; i < this.constants.length; i++) {
  1365. constants['c' + i.toString()] = this.constants[i];
  1366. }
  1367. this._execution.builtins.CONSTANTS = constants;
  1368. return this._execution;
  1369. }
  1370. _unpickle(data, storage_map) {
  1371. const loaded_storages = new Map();
  1372. const execution = this.execution;
  1373. const unpickler = python.Unpickler.open(data, execution);
  1374. unpickler.persistent_load = (saved_id) => {
  1375. const typename = saved_id.shift();
  1376. switch (typename) {
  1377. case 'storage': {
  1378. const storage_type = saved_id.shift();
  1379. const root_key = saved_id.shift();
  1380. /* const location = */ saved_id.shift();
  1381. const size = saved_id.shift();
  1382. if (!loaded_storages.has(root_key)) {
  1383. const storage = new storage_type(size);
  1384. storage._set_cdata(storage_map.get(root_key));
  1385. loaded_storages.set(root_key, storage);
  1386. }
  1387. const storage = loaded_storages.get(root_key);
  1388. const view_metadata = saved_id.shift();
  1389. if (view_metadata) {
  1390. const view_key = view_metadata.shift();
  1391. view_metadata.shift(); // view_offset
  1392. view_metadata.shift(); // view_size
  1393. let view = null;
  1394. if (loaded_storages.has(view_key)) {
  1395. view = loaded_storages.get(root_key);
  1396. }
  1397. else {
  1398. view = null; // storage.slice(view_offset, view_offset + view_size);
  1399. loaded_storages.set(view_key, view);
  1400. }
  1401. return view;
  1402. }
  1403. return storage;
  1404. }
  1405. default: {
  1406. throw new pytorch.Error("Unsupported persistent load type '" + typename + "'.");
  1407. }
  1408. }
  1409. };
  1410. return unpickler.load();
  1411. }
  1412. get constants() {
  1413. if (this._constants === undefined) {
  1414. this._constants = [];
  1415. const stream = this._entries.get('constants.pkl');
  1416. if (stream) {
  1417. const buffer = stream.peek();
  1418. this._constants = this._unpickle(buffer, this._storage('constants/'));
  1419. for (let i = 0; i < this._constants.length; i++) {
  1420. const constant = this._constants[i];
  1421. const variable = 'CONSTANTS.c' + i.toString();
  1422. if (pytorch.Utility.isTensor(constant)) {
  1423. constant.__variable__ = variable;
  1424. }
  1425. else if (constant && constant.__class__ && constant.__class__.__module__ && constant.__class__.__name__) {
  1426. const type = constant.__class__.__module__ + '.' + constant.__class__.__name__;
  1427. switch (type) {
  1428. case '__torch__.torch.classes.xnnpack.LinearOpContext':
  1429. case '__torch__.torch.classes.xnnpack.Conv2dOpContext':
  1430. case '__torch__.torch.classes.quantized.LinearPackedParamsBase':
  1431. case '__torch__.torch.classes.quantized.Conv2dPackedParamsBase':
  1432. if (pytorch.Utility.isTensor(constant.weight)) {
  1433. constant.weight.__variable__ = variable + '.weight';
  1434. }
  1435. if (pytorch.Utility.isTensor(constant.bias)) {
  1436. constant.bias.__variable__ = variable + '.bias';
  1437. }
  1438. break;
  1439. default:
  1440. throw new pytorch.Error("Unsupported constant context '" + type + "'.");
  1441. }
  1442. }
  1443. else {
  1444. throw new pytorch.Error('Unsupported constant.');
  1445. }
  1446. }
  1447. }
  1448. }
  1449. return this._constants;
  1450. }
  1451. _storage(dirname) {
  1452. const map = new Map();
  1453. const prefix = dirname;
  1454. for (const entry of this._entries) {
  1455. if (entry[0].startsWith(prefix)) {
  1456. const key = entry[0].substring(prefix.length);
  1457. const buffer = entry[1].peek();
  1458. map.set(key, buffer);
  1459. }
  1460. }
  1461. return map;
  1462. }
  1463. get inputs() {
  1464. return this._inputs;
  1465. }
  1466. get outputs() {
  1467. return this._outputs;
  1468. }
  1469. get nodes() {
  1470. return this._nodes;
  1471. }
  1472. };
  1473. pytorch.Container.Zip.Json = class extends pytorch.Container.Zip {
  1474. constructor(entries, model) {
  1475. super(entries);
  1476. this._producer = model && model.producerName ? model.producerName + (model.producerVersion ? ' v' + model.producerVersion : '') : '';
  1477. this._model = model;
  1478. }
  1479. get format() {
  1480. return this._entries.get('attributes.pkl') ? 'TorchScript v1.1' : 'TorchScript v1.0';
  1481. }
  1482. get graphs() {
  1483. if (!this._graphs) {
  1484. const execution = new pytorch.Container.Zip.Execution(null, this._exceptionCallback, this._metadata);
  1485. const graph = new pytorch.Container.Zip.Json.Script(this._entries, execution, this._model);
  1486. this._graphs = graph.data.forward ? [ graph ] : pytorch.Utility.find(graph.data);
  1487. }
  1488. return this._graphs;
  1489. }
  1490. };
  1491. pytorch.Container.Zip.Json.Script = class extends pytorch.Container.Zip.Script {
  1492. constructor(entries, execution, model) {
  1493. super(entries);
  1494. this._execution = execution;
  1495. this._model = model;
  1496. this._name = model.mainModule.name || '';
  1497. }
  1498. get name() {
  1499. return this._name;
  1500. }
  1501. get data() {
  1502. if (!this._data) {
  1503. this._data = this._model.mainModule || {};
  1504. const queue = [ this._data ];
  1505. const entries = new Map();
  1506. for (const entry of this._entries) {
  1507. const name = entry[0];
  1508. const stream = entry[1];
  1509. const buffer = stream.peek();
  1510. entries.set(name, buffer);
  1511. }
  1512. const tensorTypeMap = new Map([
  1513. [ 'FLOAT', 'Float' ],
  1514. [ 'FLOAT16', 'Half' ],
  1515. [ 'DOUBLE', 'Double' ],
  1516. [ 'INT8', 'Char' ],
  1517. [ 'INT32', 'Int' ],
  1518. [ 'INT64', 'Long' ]
  1519. ]);
  1520. const constants = this._model.tensors || [];
  1521. this._constants = constants.map((constant) => {
  1522. const key = constant.data.key;
  1523. if (!tensorTypeMap.has(constant.dataType)) {
  1524. throw new pytorch.Error("Unsupported tensor data type '" + constant.dataType + "'.");
  1525. }
  1526. const type = tensorTypeMap.get(constant.dataType);
  1527. const shape = constant.dims ? constant.dims.map((dim) => parseInt(dim, 10)) : null;
  1528. const storage_type = this.execution.resolve('torch.' + type + 'Storage');
  1529. const size = (shape || []).reduce((a, b) => a * b, 1);
  1530. const offset = parseInt(constant.offset, 10) || 0;
  1531. const storage = new storage_type([ size ]);
  1532. const itemsize = storage.dtype.itemsize();
  1533. const buffer = entries.get(key);
  1534. const length = size * itemsize;
  1535. const data = buffer.slice(offset, offset + length);
  1536. storage._set_cdata(data);
  1537. const tensor = this.execution.invoke('torch._utils._rebuild_tensor', [ storage, 0, shape, 0 ]);
  1538. tensor.name = constant.data.key;
  1539. return tensor;
  1540. });
  1541. this._attributes = [];
  1542. const stream = this._entries.get('attributes.pkl');
  1543. if (stream) {
  1544. const buffer = stream.peek();
  1545. const unpickler = python.Unpickler.open(buffer, this.execution);
  1546. this._attributes.push(...unpickler.load());
  1547. }
  1548. while (queue.length > 0) {
  1549. const module = queue.shift();
  1550. if (!module.__class__) {
  1551. module.__class__ = {
  1552. __module__: 'torch.nn.modules.module',
  1553. __name__: 'Module'
  1554. };
  1555. }
  1556. if (module.name) {
  1557. module.__id__ = module.name;
  1558. }
  1559. if (module.submodules) {
  1560. for (const submodule of module.submodules) {
  1561. module[submodule.name] = submodule;
  1562. submodule.__parent__ = module;
  1563. queue.push(submodule);
  1564. }
  1565. delete module.submodules;
  1566. }
  1567. const attributes = [];
  1568. if (module.attributes) {
  1569. attributes.push(...module.attributes);
  1570. delete module.attributes;
  1571. }
  1572. const parameters = [];
  1573. if (module.parameters) {
  1574. parameters.push(...module.parameters);
  1575. delete module.parameters;
  1576. }
  1577. if (module.arguments) {
  1578. parameters.push(...module.arguments);
  1579. delete module.arguments;
  1580. }
  1581. for (const parameter of parameters) {
  1582. const tensor = this._constants[parameter.tensorId];
  1583. module[parameter.name] = tensor;
  1584. if (!parameter.__class__) {
  1585. parameter.__class__ = {
  1586. __module__: 'torch',
  1587. __name__: 'Tensor'
  1588. };
  1589. }
  1590. }
  1591. for (const attribute of attributes) {
  1592. module[attribute.name] = this._attributes[attribute.id];
  1593. }
  1594. }
  1595. const code = this._data.torchscriptArena;
  1596. if (code && code.key && code.key.startsWith('code/')) {
  1597. const file = code.key.substring('code/'.length);
  1598. const name = file.replace(/\.py$/, '').split('/').join('.');
  1599. const module = this.execution.import(name);
  1600. if (module.forward.__class__ === this.execution.builtins.function) {
  1601. this._data.forward = module.forward;
  1602. }
  1603. }
  1604. delete this._model;
  1605. }
  1606. return this._data;
  1607. }
  1608. };
  1609. pytorch.Container.Zip.Pickle = class extends pytorch.Container.Zip {
  1610. constructor(entries) {
  1611. super(entries);
  1612. }
  1613. get format() {
  1614. const version = this.version('version') || this.version('.data/version');
  1615. return (this._entries.get('constants.pkl') ? 'TorchScript' : 'PyTorch') + (version ? ' ' + version : '');
  1616. }
  1617. get graphs() {
  1618. if (!this._graphs) {
  1619. const execution = new pytorch.Container.Zip.Execution(null, this._exceptionCallback, this._metadata);
  1620. const graph = new pytorch.Container.Zip.Pickle.Script(this._entries, execution);
  1621. if (graph.data && graph.data.forward) {
  1622. this._graphs = [ graph ];
  1623. }
  1624. else if (graph.data && graph.data.__class__ && graph.data.__class__.__module__ == 'fastai.learner' && graph.data.__class__.__name__ == 'Learner') {
  1625. this._graphs = pytorch.Utility.find(graph.data.model);
  1626. }
  1627. else {
  1628. this._graphs = pytorch.Utility.find(graph.data);
  1629. }
  1630. }
  1631. return this._graphs;
  1632. }
  1633. };
  1634. pytorch.Container.Zip.Pickle.Script = class extends pytorch.Container.Zip.Script {
  1635. constructor(entries, execution, location, name) {
  1636. super(entries, execution, location, name);
  1637. }
  1638. get data() {
  1639. if (!this._data) {
  1640. const stream = this._entries.get(this._location.model || 'data.pkl');
  1641. const buffer = stream.peek();
  1642. this._data = this._unpickle(buffer, this._storage(this._location.data || 'data/'));
  1643. }
  1644. return this._data;
  1645. }
  1646. };
  1647. pytorch.Container.Zip.Package = class extends pytorch.Container.Zip {
  1648. constructor(entries) {
  1649. super(entries);
  1650. }
  1651. get format() {
  1652. const version = this.version('.data/version');
  1653. return 'PyTorch Package' + (version ? ' ' + version : '');
  1654. }
  1655. get graphs() {
  1656. if (!this._graphs) {
  1657. this._graphs = [];
  1658. const entries = Array.from(this._entries).filter((entry) => !entry[0].startsWith('.data/') && !entry[0].endsWith('py'));
  1659. if (entries.length > 0) {
  1660. const execution = new pytorch.Container.Zip.Execution(null, this._exceptionCallback, this._metadata);
  1661. const torch_jit_script = execution.register('torch.jit._script');
  1662. execution.registerType('torch.package.PackageImporter', class {
  1663. constructor(entries) {
  1664. this._entries = entries;
  1665. }
  1666. load_pickle(name) {
  1667. const stream = this._entries.get(name);
  1668. const loaded_reduces = new Map();
  1669. const loaded_storages = new Map();
  1670. const unpickler = python.Unpickler.open(stream, execution);
  1671. unpickler.persistent_load = (saved_id) => {
  1672. const typename = saved_id.shift();
  1673. switch (typename) {
  1674. case 'storage': {
  1675. const storage_type = saved_id[0];
  1676. const key = saved_id[1];
  1677. /* const location = saved_id[2]; */
  1678. const size = saved_id[3];
  1679. if (!loaded_storages.has(key)) {
  1680. const storage = new storage_type(size);
  1681. const stream = this._entries.get('.data/' + key + '.storage');
  1682. const buffer = stream.peek();
  1683. storage._set_cdata(buffer);
  1684. loaded_storages.set(key, storage);
  1685. }
  1686. return loaded_storages.get(key);
  1687. }
  1688. case 'reduce_package': {
  1689. if (saved_id.left === 2) {
  1690. const func = saved_id[0];
  1691. const args = saved_id[1];
  1692. return execution.invoke(func, args);
  1693. }
  1694. const reduce_id = saved_id[0];
  1695. const func = saved_id[1];
  1696. const args = saved_id[2];
  1697. if (!loaded_reduces.has(reduce_id)) {
  1698. const value = execution.invoke(func, [ this ].concat(args));
  1699. loaded_reduces.set(reduce_id, value);
  1700. }
  1701. return loaded_reduces.get(reduce_id);
  1702. }
  1703. default: {
  1704. throw new pytorch.Error("Unknown package typename '" + typename + "'.");
  1705. }
  1706. }
  1707. };
  1708. return unpickler.load();
  1709. }
  1710. });
  1711. execution.registerFunction('torch.jit._script.unpackage_script_module', function(importer, script_module_id) {
  1712. return execution.invoke('torch.jit._script.RecursiveScriptModule', [ script_module_id ]);
  1713. });
  1714. execution.registerType('torch.jit._script.ScriptModule', class {});
  1715. execution.registerType('torch.jit._script.RecursiveScriptModule', class extends torch_jit_script.ScriptModule {
  1716. constructor(script_module_id) {
  1717. super();
  1718. this.script_module_id = script_module_id;
  1719. }
  1720. });
  1721. for (const entry of this._entries) {
  1722. if (!entry[0].startsWith('.data/') && entry[0].endsWith('.py')) {
  1723. const name = entry[0];
  1724. const stream = entry[1];
  1725. const buffer = stream.peek();
  1726. execution.add(name, buffer);
  1727. }
  1728. }
  1729. const importer = execution.invoke('torch.package.PackageImporter', [ new Map(this._entries) ]);
  1730. for (const entry of entries) {
  1731. const name = entry[0];
  1732. const root = importer.load_pickle(name);
  1733. this._graphs.push({
  1734. name: name,
  1735. type: 'module',
  1736. data: root
  1737. });
  1738. }
  1739. }
  1740. }
  1741. return this._graphs;
  1742. }
  1743. };
  1744. pytorch.Container.Zip.Execution = class extends pytorch.Execution {
  1745. constructor(sources, exceptionCallback, metadata) {
  1746. super(sources, exceptionCallback);
  1747. this._metadata = metadata;
  1748. this.reset();
  1749. }
  1750. reset() {
  1751. this._nodes = [];
  1752. this._variableIndex = 0;
  1753. }
  1754. get nodes() {
  1755. return this._nodes;
  1756. }
  1757. target(expression, context) {
  1758. if (expression.type === 'id') {
  1759. switch (expression.value) {
  1760. case 'torch':
  1761. case 'ops':
  1762. case 'CONSTANTS':
  1763. case 'uninitialized':
  1764. return this.builtins[expression.value];
  1765. default:
  1766. break;
  1767. }
  1768. }
  1769. let current = expression;
  1770. let path = [];
  1771. for (;;) {
  1772. if (current.type === '.' && current.member && current.member.type === 'id') {
  1773. path.push(current.member.value);
  1774. current = current.target;
  1775. }
  1776. else if (current.type === 'id' && current.value !== 'self' && current.value !== 'CONSTANTS') {
  1777. path.push(current.value);
  1778. break;
  1779. }
  1780. else {
  1781. path = null;
  1782. break;
  1783. }
  1784. }
  1785. if (path) {
  1786. let target = null;
  1787. for (let i = path.length - 1; i >= 0; i--) {
  1788. target = target ? target[path[i]] : context.get(path[i]);
  1789. if (!target) {
  1790. break;
  1791. }
  1792. }
  1793. if (!target) {
  1794. path.reverse();
  1795. const name = path.join('.');
  1796. const file = path.join('/') + '.py';
  1797. if (this.source(file)) {
  1798. return this.import(name);
  1799. }
  1800. return this.resolve(name);
  1801. }
  1802. }
  1803. return super.target(expression, context);
  1804. }
  1805. call(target, name, args, context) {
  1806. let resolvedTarget = pytorch.Utility.target(target);
  1807. let outputTypes = null;
  1808. if (resolvedTarget && resolvedTarget + '.' + name === 'ops.prim.NumToTensor' &&
  1809. args.length === 1 && args[0].type === 'call' && args[0].target.member.type == 'id') {
  1810. const innerCall = args[0];
  1811. resolvedTarget = pytorch.Utility.target(innerCall.target.target);
  1812. name = innerCall.target.member.value;
  1813. args = innerCall.arguments;
  1814. outputTypes = [ 'int64' ];
  1815. }
  1816. if (resolvedTarget && name !== null) {
  1817. const type = resolvedTarget + '.' + name;
  1818. // https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/native_functions.yaml
  1819. let schemas = this._metadata.type(type);
  1820. if (schemas) {
  1821. schemas = !Array.isArray(schemas) ? [ schemas ] : schemas;
  1822. const evalArgs = args.map((argument) => argument.type === '=' && argument.target && argument.target.type === 'id' ? this.expression(argument.expression, context) : this.expression(argument, context));
  1823. for (const schema of schemas) {
  1824. const copyArgs = Array.prototype.slice.call(args);
  1825. const copyEvalArgs = Array.prototype.slice.call(evalArgs);
  1826. const node = {
  1827. type: schema.name,
  1828. inputs: [],
  1829. attributes: [],
  1830. outputs: []
  1831. };
  1832. const referencedParameters = [];
  1833. let next = false;
  1834. const parameters = Array.prototype.slice.call(schema.inputs || []).concat(Array.prototype.slice.call(schema.attributes || []));
  1835. let op_context = null;
  1836. while (copyEvalArgs.length > 0 || (op_context && parameters.length > 0)) {
  1837. if (parameters.length <= 0) {
  1838. next = true;
  1839. break;
  1840. }
  1841. const arg = copyEvalArgs[0];
  1842. if (arg && arg.__class__ && arg.__class__.__module__ && arg.__class__.__name__) {
  1843. const type = arg.__class__.__module__ + '.' + arg.__class__.__name__;
  1844. switch (type) {
  1845. case '__torch__.torch.classes.quantized.Conv2dPackedParamsBase':
  1846. case '__torch__.torch.classes.quantized.Conv3dPackedParamsBase':
  1847. case '__torch__.torch.classes.quantized.LinearPackedParamsBase':
  1848. case '__torch__.torch.classes.xnnpack.Conv2dOpContext':
  1849. case '__torch__.torch.classes.xnnpack.LinearOpContext':
  1850. op_context = arg;
  1851. copyArgs.shift();
  1852. copyEvalArgs.shift();
  1853. continue;
  1854. default:
  1855. break;
  1856. }
  1857. }
  1858. if (op_context && parameters[0]) {
  1859. const parameter = parameters[0];
  1860. const name = parameter.name;
  1861. if (name in op_context && parameter.context) {
  1862. copyArgs.unshift({ type: null });
  1863. copyEvalArgs.unshift(op_context[name]);
  1864. }
  1865. }
  1866. if (copyArgs.every((arg) => arg.type === '=' && arg.target && arg.target.type === 'id') &&
  1867. parameters.every((parameter) => parameter.type !== 'Tensor' && parameter.type !== 'Tensor[]')) {
  1868. const map = new Map(parameters.map((parameter) => [ parameter.name, parameter ]));
  1869. while (copyArgs.length > 0) {
  1870. const argument = copyArgs.shift();
  1871. const value = copyEvalArgs.shift();
  1872. const parameter = map.get(argument.target.value);
  1873. if (!parameter) {
  1874. next = true;
  1875. break;
  1876. }
  1877. if (!pytorch.Utility.isType(value, parameter.type)) {
  1878. if (parameter.optional) {
  1879. continue;
  1880. }
  1881. next = true;
  1882. break;
  1883. }
  1884. node.attributes.push({ name: parameter.name, value: value });
  1885. }
  1886. continue;
  1887. }
  1888. if (next) {
  1889. break;
  1890. }
  1891. const parameter = parameters.shift();
  1892. const argument = copyEvalArgs[0];
  1893. if (parameter.type === 'Tensor' || (parameter.type === 'Scalar' && pytorch.Utility.isTensor(argument))) {
  1894. if (Array.isArray(argument) || (!pytorch.Utility.isTensor(argument) && argument !== null && argument !== undefined)) {
  1895. if (parameter.optional) {
  1896. if (argument === undefined) {
  1897. copyArgs.shift();
  1898. copyEvalArgs.shift();
  1899. }
  1900. continue;
  1901. }
  1902. next = true;
  1903. }
  1904. else {
  1905. copyArgs.shift();
  1906. copyEvalArgs.shift();
  1907. const item = (argument === null || argument === undefined) ? {} : argument;
  1908. item.__variable__ = item.__variable__ || this.variable();
  1909. const inputs = [];
  1910. inputs.push({ id: item.__variable__ });
  1911. referencedParameters.push(item);
  1912. node.inputs.push(inputs);
  1913. }
  1914. }
  1915. else if (parameter.type === 'Tensor[]') {
  1916. const argument = copyEvalArgs[0];
  1917. if (!Array.isArray(argument) || !argument.every((item) => pytorch.Utility.isTensor(item) || item === null)) {
  1918. if (parameter.optional) {
  1919. continue;
  1920. }
  1921. next = true;
  1922. }
  1923. else {
  1924. copyArgs.shift();
  1925. copyEvalArgs.shift();
  1926. const inputs = [];
  1927. for (let item of argument) {
  1928. if (item === null) {
  1929. item = {};
  1930. }
  1931. item.__variable__ = item.__variable__ || this.variable();
  1932. inputs.push({ id: item.__variable__ });
  1933. referencedParameters.push(item);
  1934. }
  1935. node.inputs.push(inputs);
  1936. }
  1937. }
  1938. else {
  1939. const arg = copyArgs[0];
  1940. if (!pytorch.Utility.isType(argument, parameter.type) && argument !== null) {
  1941. if (parameter.optional) {
  1942. continue;
  1943. }
  1944. next = true;
  1945. }
  1946. else if (arg.type !== '=') {
  1947. copyArgs.shift();
  1948. copyEvalArgs.shift();
  1949. node.attributes.push({ name: parameter.name, value: argument });
  1950. }
  1951. else {
  1952. throw new pytorch.Error('Expected named argument.');
  1953. }
  1954. }
  1955. if (next) {
  1956. break;
  1957. }
  1958. }
  1959. if (next) {
  1960. continue;
  1961. }
  1962. const result = [];
  1963. for (let i = 0; i < schema.outputs.length; i++) {
  1964. const parameter = schema.outputs[i];
  1965. switch (parameter.type) {
  1966. case 'Tensor': {
  1967. const parameter = this.invoke('torch.Tensor', []);
  1968. parameter.__origin__ = type;
  1969. if (i === 0) {
  1970. switch (type) {
  1971. case 'torch.conv1d':
  1972. case 'torch.embedding': {
  1973. parameter.resize_([ NaN, NaN, NaN ]);
  1974. break;
  1975. }
  1976. case 'torch.cat':
  1977. case 'torch.conv2d':
  1978. case 'torch.dropout':
  1979. case 'torch.flatten':
  1980. case 'torch.max_pool2d':
  1981. case 'torch.adaptive_avg_pool2d':
  1982. case 'torch.avg_pool2d':
  1983. case 'torch.quantize_per_tensor':
  1984. case 'torch.relu_':
  1985. case 'torch.hardtanh_':
  1986. case 'torch.upsample_bilinear2d':
  1987. case 'ops.prepacked.conv2d_clamp_run': {
  1988. parameter.resize_([ NaN, NaN, NaN, NaN ]);
  1989. break;
  1990. }
  1991. case 'torch.slice': {
  1992. const input = evalArgs[0];
  1993. if (pytorch.Utility.isTensor(input) && Array.isArray(input.size())) {
  1994. const size = input.size();
  1995. parameter.resize_(size);
  1996. }
  1997. break;
  1998. }
  1999. case 'torch.to': {
  2000. const input = evalArgs[0];
  2001. if (pytorch.Utility.isTensor(input) && Array.isArray(input.size())) {
  2002. const size = input.size();
  2003. parameter.resize_(size);
  2004. }
  2005. break;
  2006. }
  2007. case 'torch.conv3d': {
  2008. parameter.resize_([ NaN, NaN, NaN, NaN, NaN ]);
  2009. break;
  2010. }
  2011. case 'torch.detach':
  2012. case 'torch.mean':
  2013. case 'torch.mul':
  2014. case 'torch.div':
  2015. case 'torch.batch_norm':
  2016. case 'torch.gelu':
  2017. case 'torch.relu':
  2018. case 'torch.clamp_':
  2019. case 'torch.hardswish_': {
  2020. const input = evalArgs[0];
  2021. if (pytorch.Utility.isTensor(input) && Array.isArray(input.size())) {
  2022. parameter.resize_(input.size());
  2023. }
  2024. break;
  2025. }
  2026. case 'torch.add':
  2027. case 'torch.sub': {
  2028. const input = evalArgs[0];
  2029. if (pytorch.Utility.isTensor(input) && Array.isArray(input.size())) {
  2030. parameter.resize_(input.size());
  2031. }
  2032. else {
  2033. const other = evalArgs[1];
  2034. if (pytorch.Utility.isTensor(other) && Array.isArray(other.size())) {
  2035. parameter.resize_(other.size());
  2036. }
  2037. }
  2038. break;
  2039. }
  2040. case 'torch.select': {
  2041. const input = evalArgs[0];
  2042. if (pytorch.Utility.isTensor(input) && Array.isArray(input.size())) {
  2043. parameter.resize_(Array(input.size().length - 1).fill(NaN));
  2044. }
  2045. break;
  2046. }
  2047. case 'torch.layer_norm': {
  2048. const input = evalArgs[0];
  2049. const normalized_shape = evalArgs[1];
  2050. if (pytorch.Utility.isTensor(input) && Array.isArray(input.size())) {
  2051. const shape = input.size();
  2052. if (Array.isArray(normalized_shape) && normalized_shape.length === 1) {
  2053. shape[shape.length - 1] = normalized_shape[0];
  2054. }
  2055. parameter.resize_(shape);
  2056. }
  2057. break;
  2058. }
  2059. case 'torch.empty':
  2060. case 'torch.ones':
  2061. case 'torch.zeros':
  2062. case 'torch.zeros_like': {
  2063. parameter.resize_(evalArgs[0]);
  2064. break;
  2065. }
  2066. case 'torch.view':
  2067. case 'torch.reshape':
  2068. case 'torch.new_full': {
  2069. parameter.resize_(evalArgs[1]);
  2070. break;
  2071. }
  2072. case 'torch.squeeze': {
  2073. const input = evalArgs[0];
  2074. const size = input.size();
  2075. if (Array.isArray(size)) {
  2076. switch (evalArgs.length) {
  2077. case 1: {
  2078. parameter.resize_(size.filter((value) => value !== 1));
  2079. break;
  2080. }
  2081. case 2: {
  2082. const dim = evalArgs[1];
  2083. parameter.resize_(size.filter((value, index) => (value !== 1 && !isNaN(value)) || index !== dim));
  2084. break;
  2085. }
  2086. default: {
  2087. break;
  2088. }
  2089. }
  2090. }
  2091. break;
  2092. }
  2093. case 'torch.unsqueeze': {
  2094. const input = evalArgs[0];
  2095. const size = input.size();
  2096. const dim = evalArgs[1];
  2097. if (Array.isArray(size) && dim !== undefined) {
  2098. const shape = size.slice();
  2099. shape.splice(dim, 0, 1);
  2100. parameter.resize_(shape);
  2101. }
  2102. else {
  2103. parameter.resize_([ NaN, NaN, NaN, NaN ]);
  2104. }
  2105. break;
  2106. }
  2107. case 'torch.transpose': {
  2108. const input = evalArgs[0];
  2109. let dim0 = evalArgs[1];
  2110. let dim1 = evalArgs[2];
  2111. if (pytorch.Utility.isTensor(input) && Array.isArray(input.size())) {
  2112. const size = input.size().slice();
  2113. dim0 = dim0 >= 0 ? dim0 : size.length + dim0;
  2114. dim1 = dim1 >= 0 ? dim1 : size.length + dim1;
  2115. const value = size[dim0];
  2116. size[dim0] = size[1];
  2117. size[dim1] = value;
  2118. parameter.resize_(size);
  2119. }
  2120. break;
  2121. }
  2122. case 'ops.quantized.cat':
  2123. case 'ops.quantized.cat_relu':
  2124. case 'ops.quantized.linear':
  2125. case 'ops.quantized.conv2d':
  2126. case 'ops.quantized.conv2d_relu':
  2127. case 'ops.quantized.add':
  2128. case 'ops.quantized.add_relu':
  2129. parameter.resize_([ NaN, NaN, NaN, NaN ]);
  2130. parameter.__quantized__ = true;
  2131. break;
  2132. case 'torch.contiguous':
  2133. parameter.__source__ = evalArgs[0];
  2134. break;
  2135. default:
  2136. break;
  2137. }
  2138. }
  2139. parameter.__variable__ = this.variable();
  2140. result.push(parameter);
  2141. node.outputs.push([ { id: parameter.__variable__ } ]);
  2142. break;
  2143. }
  2144. case 'Tensor[]': {
  2145. let count = 1;
  2146. switch (type) {
  2147. case 'torch.chunk':
  2148. count = node.attributes.filter((attribute) => attribute.name == 'chunks')[0].value;
  2149. break;
  2150. case 'torch.meshgrid':
  2151. count = node.inputs[0].length;
  2152. break;
  2153. case 'torch.unbind':
  2154. count = args[0].__tuple__ || count;
  2155. break;
  2156. case 'torch.broadcast_tensors':
  2157. case 'torch.split':
  2158. case 'torch.split_with_sizes':
  2159. if (context.target.length > 0) {
  2160. count = context.target[context.target.length - 1].length;
  2161. }
  2162. break;
  2163. default:
  2164. break;
  2165. }
  2166. const tensors = [];
  2167. const outputs = [];
  2168. for (let i = 0; i < count; i ++) {
  2169. const tensor = this.invoke('torch.Tensor', []);
  2170. tensor.__origin__ = type;
  2171. tensor.__variable__ = this.variable();
  2172. tensors.push(tensor);
  2173. outputs.push({ id: tensor.__variable__ });
  2174. }
  2175. result.push(tensors);
  2176. node.outputs.push(outputs);
  2177. break;
  2178. }
  2179. default: {
  2180. if (!outputTypes || schema.outputs.length !== 1 || schema.outputs[0].type !== outputTypes[0]) {
  2181. next = true;
  2182. break;
  2183. }
  2184. const tensor = this.invoke('torch.Tensor', []);
  2185. tensor.resize_([]);
  2186. tensor.__origin__ = type;
  2187. tensor.__variable__ = this.variable();
  2188. result.push(tensor);
  2189. node.outputs.push([ { id: tensor.__variable__ } ]);
  2190. break;
  2191. }
  2192. }
  2193. }
  2194. if (next) {
  2195. continue;
  2196. }
  2197. for (const parameter of referencedParameters) {
  2198. parameter.__count__ = (parameter.__count__ || 0) + 1;
  2199. }
  2200. this.push(node);
  2201. if (result.length > 1) {
  2202. return result;
  2203. }
  2204. return result[0];
  2205. }
  2206. }
  2207. }
  2208. return super.call(target, name, args, context);
  2209. }
  2210. block(statements, context) {
  2211. statements = Array.prototype.slice.call(statements);
  2212. while (statements.length > 0) {
  2213. if (statements.length > 1) {
  2214. const assign = statements[0];
  2215. const condition = statements[1];
  2216. // _x = torch.ne(torch.len(torch.size(input)), 5)
  2217. // if _x:
  2218. // ops.prim.RaiseException(...)
  2219. if (assign.type === '=' &&
  2220. condition.type === 'if' &&
  2221. pytorch.Utility.isEqual(assign.target, condition.condition) &&
  2222. pytorch.Utility.isCall(assign.expression, 'torch.ne', 2) &&
  2223. pytorch.Utility.isCall(assign.expression.arguments[0], 'torch.len', 1) &&
  2224. pytorch.Utility.isCall(assign.expression.arguments[0].arguments[0], 'torch.size', 1) &&
  2225. condition.then.statements.length == 1 &&
  2226. pytorch.Utility.isCall(condition.then.statements[0], 'ops.prim.RaiseException', 1)) {
  2227. const tensor = this.expression(assign.expression.arguments[0].arguments[0].arguments[0], context);
  2228. if (pytorch.Utility.isTensor(tensor) && tensor.size) {
  2229. const number = this.expression(assign.expression.arguments[1], context);
  2230. const size = tensor.size();
  2231. if (number >= 3 && number <= 5) {
  2232. if (!Array.isArray(size) || size.length !== number) {
  2233. tensor.resize_(Array(number).fill(NaN));
  2234. }
  2235. }
  2236. }
  2237. }
  2238. // _x = torch.ne(torch.dim(input), 5)
  2239. // if _x:
  2240. // ops.prim.RaiseException(...)
  2241. if (assign.type === '=' &&
  2242. condition.type === 'if' &&
  2243. pytorch.Utility.isEqual(assign.target, condition.condition) &&
  2244. pytorch.Utility.isCall(assign.expression, 'torch.ne', 2) &&
  2245. pytorch.Utility.isCall(assign.expression.arguments[0], 'torch.dim', 1) &&
  2246. condition.then.statements.length > 0 &&
  2247. pytorch.Utility.isCall(condition.then.statements[condition.then.statements.length - 1], 'ops.prim.RaiseException', 1)) {
  2248. const tensor = this.expression(assign.expression.arguments[0].arguments[0], context);
  2249. if (pytorch.Utility.isTensor(tensor)) {
  2250. const size = this.expression(assign.expression.arguments[1], context);
  2251. tensor.resize_(Array(size).fill(NaN));
  2252. }
  2253. }
  2254. // _0 = torch.eq(torch.len(torch.size(x)), 2)
  2255. // if _0:
  2256. // pass
  2257. // else:
  2258. // ops.prim.RaiseException("AssertionError: ")
  2259. if (assign.type === '=' &&
  2260. condition.type === 'if' &&
  2261. pytorch.Utility.isEqual(assign.target, condition.condition) &&
  2262. pytorch.Utility.isCall(assign.expression, 'torch.eq', 2) &&
  2263. pytorch.Utility.isCall(assign.expression.arguments[0], 'torch.len', 1) &&
  2264. pytorch.Utility.isCall(assign.expression.arguments[0].arguments[0], 'torch.size', 1) &&
  2265. condition.else.statements.length == 1 &&
  2266. pytorch.Utility.isCall(condition.else.statements[0], 'ops.prim.RaiseException', 1)) {
  2267. const tensor = this.expression(assign.expression.arguments[0].arguments[0].arguments[0], context);
  2268. if (pytorch.Utility.isTensor(tensor) && tensor.shape === undefined) {
  2269. const number = this.expression(assign.expression.arguments[1], context);
  2270. tensor.resize_(Array(number).fill(NaN));
  2271. }
  2272. }
  2273. // val = torch.slice(torch.size(img), -2)
  2274. // if torch.eq(torch.len(val), 2):
  2275. // pass
  2276. // else:
  2277. // ops.prim.RaiseException("AssertionError: ")
  2278. if (assign.type === '=' &&
  2279. condition.type === 'if' &&
  2280. pytorch.Utility.isCall(assign.expression, 'torch.slice', 2) &&
  2281. pytorch.Utility.isCall(assign.expression.arguments[0], 'torch.size', 1) &&
  2282. pytorch.Utility.isCall(condition.condition, 'torch.eq', 2) &&
  2283. pytorch.Utility.isCall(condition.condition.arguments[0], 'torch.len', 1) &&
  2284. pytorch.Utility.isEqual(condition.condition.arguments[0].arguments[0], assign.target) &&
  2285. condition.else.statements.length == 1 &&
  2286. pytorch.Utility.isCall(condition.else.statements[0], 'ops.prim.RaiseException', 1)) {
  2287. const tensor = this.expression(assign.expression.arguments[0].arguments[0], context);
  2288. if (pytorch.Utility.isTensor(tensor) && tensor.shape === undefined) {
  2289. const start = this.expression(assign.expression.arguments[1], context);
  2290. const value = this.expression(condition.condition.arguments[1], context);
  2291. if (Number.isInteger(start) && start < 0 && Number.isInteger(value) && value > 0) {
  2292. tensor.resize_(Array(value - start).fill(NaN));
  2293. }
  2294. }
  2295. }
  2296. }
  2297. if (statements.length > 1) {
  2298. // getattr_1 = torch.size(x)
  2299. // getitem = torch.slice(getattr_1, -2, 9223372036854775807, 1)
  2300. const size = statements[0];
  2301. const statement = statements[1];
  2302. if (size.type === '=' && statement.type === '=' &&
  2303. size.target.type === 'id' &&
  2304. pytorch.Utility.isCall(size.expression, 'torch.size', 1) &&
  2305. pytorch.Utility.isCall(statement.expression, 'torch.slice', 4) &&
  2306. statement.expression.arguments[0].type === 'id' && size.target.value === statement.expression.arguments[0].value) {
  2307. const tensor = this.expression(size.expression.arguments[0], context);
  2308. if (pytorch.Utility.isTensor(tensor) && tensor.__origin__ === 'graph-input' && tensor.shape === undefined) {
  2309. tensor.resize_([ 1, 3, 299, 299 ]);
  2310. }
  2311. }
  2312. }
  2313. if (statements.length > 1) {
  2314. // _0 = torch.split_with_sizes(...)
  2315. // a, a_1, a_2, = _0
  2316. const statement = statements[0];
  2317. const tuple = statements[1];
  2318. if (statement.type === '=' && statement.target.type === 'id' && statement.expression.type == 'call' &&
  2319. tuple.type === '=' && tuple.target.type === 'tuple' &&
  2320. tuple.target.value.every((item) => item.type === 'id') &&
  2321. tuple.expression.value === statement.target.value) {
  2322. const containsVariableReference = (queue, value) => {
  2323. while (queue.length > 0) {
  2324. const obj = queue.shift();
  2325. if (obj && obj.type === 'id' && obj.value === value) {
  2326. return true;
  2327. }
  2328. else if (Array.isArray(obj)) {
  2329. for (const item of obj) {
  2330. if (Array.isArray(item) || (Object(item) === item && item.type)) {
  2331. queue.push(item);
  2332. }
  2333. }
  2334. }
  2335. else if (Object(obj) === obj) {
  2336. for (const entry of Object.entries(obj)) {
  2337. const key = entry[0];
  2338. const value = entry[1];
  2339. if (key === 'location') {
  2340. continue;
  2341. }
  2342. if (Array.isArray(value)) {
  2343. for (const item of value) {
  2344. if (Array.isArray(item) || (Object(item) === item && item.type)) {
  2345. queue.push(item);
  2346. }
  2347. }
  2348. }
  2349. else if (Object(value) === value && value.type) {
  2350. queue.push(value);
  2351. }
  2352. }
  2353. }
  2354. }
  2355. return false;
  2356. };
  2357. if (!containsVariableReference(statements.slice(2, statements.length - 1), statement.target.value)) {
  2358. statements[0] = Object.assign({}, statement);
  2359. statements[0].target = tuple.target;
  2360. statements.splice(1, 1);
  2361. }
  2362. }
  2363. }
  2364. const statement = statements.shift();
  2365. // input_shape = torch.slice(torch.size(x), -2, 9223372036854775807, 1)
  2366. if (statement.type === '=' &&
  2367. pytorch.Utility.isCall(statement.expression, 'torch.slice', 4) &&
  2368. pytorch.Utility.isCall(statement.expression.arguments[0], 'torch.size', 1)) {
  2369. const tensor = this.expression(statement.expression.arguments[0].arguments[0], context);
  2370. if (pytorch.Utility.isTensor(tensor) && tensor.shape === undefined) {
  2371. tensor.resize_([ 1, 3, 299, 299 ]);
  2372. }
  2373. }
  2374. // torch.slice(ops.prim.shape(input), 0, 2, 1)
  2375. if (statement.type === '=' &&
  2376. pytorch.Utility.isCall(statement.expression, 'torch.slice', 4) &&
  2377. pytorch.Utility.isCall(statement.expression.arguments[0], 'ops.prim.shape', 1)) {
  2378. const tensor = this.expression(statement.expression.arguments[0].arguments[0], context);
  2379. if (pytorch.Utility.isTensor(tensor) && tensor.__origin__ === 'graph-input' && tensor.shape === undefined) {
  2380. tensor.resize_([ NaN, NaN, NaN, NaN ]);
  2381. }
  2382. }
  2383. // _3 = torch.le(xxxx, torch.dim(f0))
  2384. if (statement.type === '=' &&
  2385. pytorch.Utility.isCall(statement.expression, 'torch.le', 2) &&
  2386. pytorch.Utility.isCall(statement.expression.arguments[1], 'torch.dim', 1)) {
  2387. const tensor = this.expression(statement.expression.arguments[1].arguments[0], context);
  2388. if (pytorch.Utility.isTensor(tensor) && tensor.__origin__ === 'graph-input' && tensor.shape === undefined) {
  2389. tensor.resize_([ NaN, NaN, NaN, NaN ]);
  2390. }
  2391. }
  2392. // if torch.ne(torch.dim(image), 3):
  2393. // xxxx
  2394. // ops.prim.RaiseException(_7)
  2395. if (statement.type === 'if' &&
  2396. pytorch.Utility.isCall(statement.condition, 'torch.ne', 2) &&
  2397. pytorch.Utility.isCall(statement.condition.arguments[0], 'torch.dim', 1) &&
  2398. statement.then.statements.length > 0 &&
  2399. pytorch.Utility.isCall(statement.then.statements.slice(-1).pop(), 'ops.prim.RaiseException', 1)) {
  2400. const tensor = this.expression(statement.condition.arguments[0].arguments[0], context);
  2401. const size = this.expression(statement.condition.arguments[1], context);
  2402. if (pytorch.Utility.isTensor(tensor) && Number.isInteger(size) && size < 10) {
  2403. tensor.resize_(Array.isArray(tensor.shape) && tensor.shape.length > size ? tensor.shape.slice(-size) : Array(size).fill(NaN));
  2404. }
  2405. }
  2406. // if bool(...):
  2407. // ops.prim.RaiseException(torch.format(_1, dtype))
  2408. // else:
  2409. // pass
  2410. if (statement.type === 'if' &&
  2411. pytorch.Utility.isCall(statement.condition, 'bool', 1) &&
  2412. statement.then.statements.length > 0 &&
  2413. pytorch.Utility.isCall(statement.then.statements.slice(-1).pop(), 'ops.prim.RaiseException', 1)) {
  2414. statement.condition = { type: 'id', value: 'False' };
  2415. }
  2416. // dim = torch.sub(torch.dim(input), 2)
  2417. if (statement.type === '=' &&
  2418. statement.target.type === 'id' && statement.target.value === 'dim' &&
  2419. pytorch.Utility.isCall(statement.expression, 'torch.sub', 2) &&
  2420. pytorch.Utility.isCall(statement.expression.arguments[0], 'torch.dim', 1)) {
  2421. const tensor = this.expression(statement.expression.arguments[0].arguments[0], context);
  2422. if (pytorch.Utility.isTensor(tensor) && tensor.__origin__ === 'graph-input' && tensor.shape === undefined) {
  2423. tensor.resize_([ NaN, NaN, NaN, NaN ]);
  2424. }
  2425. }
  2426. // a, b = torch.unbind(size, 0)
  2427. if (statement.type === '=' &&
  2428. statement.target.type === 'tuple' &&
  2429. (pytorch.Utility.isCall(statement.expression, 'torch.unbind', 1) ||
  2430. pytorch.Utility.isCall(statement.expression, 'torch.unbind', 2))) {
  2431. statement.expression.arguments[0].__tuple__ = statement.target.value.length;
  2432. }
  2433. // a, b, c = torch.size(input)
  2434. if (statement.type === '=' &&
  2435. statement.target.type === 'tuple' &&
  2436. pytorch.Utility.isCall(statement.expression, 'torch.size', 1)) {
  2437. const tensor = this.expression(statement.expression.arguments[0], context);
  2438. if (pytorch.Utility.isTensor(tensor) && tensor.__origin__ === 'graph-input' && tensor.shape === undefined) {
  2439. const dim = statement.target.value.length;
  2440. tensor.resize_(Array(dim).fill(NaN));
  2441. }
  2442. }
  2443. // x = torch.len(input)
  2444. if (statement.type === '=' &&
  2445. statement.target.type === 'id' &&
  2446. pytorch.Utility.isCall(statement.expression, 'torch.len', 1)) {
  2447. const tensor = this.expression(statement.expression.arguments[0], context);
  2448. if (pytorch.Utility.isTensor(tensor) && tensor.__origin__ === 'graph-input' && tensor.shape === undefined) {
  2449. tensor.resize_([ NaN, NaN, NaN, NaN ]);
  2450. }
  2451. }
  2452. if (statement.type === '=' &&
  2453. statement.expression.type === 'call' && statement.expression.arguments.length > 0 &&
  2454. pytorch.Utility.isCall(statement.expression.arguments[0], 'torch.size', 2)) {
  2455. const tensor = this.expression(statement.expression.arguments[0].arguments[0], context);
  2456. const dim = this.expression(statement.expression.arguments[0].arguments[1], context);
  2457. if (pytorch.Utility.isTensor(tensor) && Number.isInteger(dim)) {
  2458. if (tensor.shape === undefined) {
  2459. tensor.resize_(Array(dim + 1).fill(NaN));
  2460. }
  2461. else if (Array.isArray(tensor.shape) && tensor.shape.length <= dim) {
  2462. tensor.resize_(tensor.shape.concat(Array(dim + 1 - tensor.shape.length).fill(NaN)));
  2463. }
  2464. }
  2465. }
  2466. if (statement.type === '=' && statement.target.type === 'tuple' &&
  2467. statement.expression.type === 'call' && statement.expression.arguments.length > 0 &&
  2468. pytorch.Utility.isCall(statement.expression, 'torch.size', 1)) {
  2469. const tensor = this.expression(statement.expression.arguments[0], context);
  2470. if (pytorch.Utility.isTensor(tensor) && tensor.__origin__ === 'graph-input') {
  2471. if (tensor.shape === undefined) {
  2472. tensor.resize_(Array(statement.target.value.length).fill(NaN));
  2473. }
  2474. }
  2475. }
  2476. const value = this.statement(statement, context);
  2477. if (value !== undefined) {
  2478. return value;
  2479. }
  2480. }
  2481. return undefined;
  2482. }
  2483. push(node) {
  2484. this._nodes.push(node);
  2485. }
  2486. variable() {
  2487. this._variableIndex++;
  2488. return this._variableIndex.toString();
  2489. }
  2490. };
  2491. pytorch.MemoryFormat = {
  2492. Contiguous: 0,
  2493. Preserve: 1,
  2494. ChannelsLast: 2,
  2495. ChannelsLast3d: 3
  2496. };
  2497. pytorch.Layout = {
  2498. Strided: 0,
  2499. Sparse: 1,
  2500. Mkldnn: 2
  2501. };
  2502. pytorch.Utility = class {
  2503. static getScalarType(scalarType) {
  2504. if (!pytorch.Utility._scalarTypes) {
  2505. pytorch.Utility._scalarTypes = [
  2506. ];
  2507. }
  2508. if (scalarType < pytorch.Utility._scalarTypes.length) {
  2509. return pytorch.Utility._scalarTypes[scalarType];
  2510. }
  2511. throw new pytorch.Error("Unsupported scalar type '" + scalarType + "'.");
  2512. }
  2513. static target(expression) {
  2514. if (expression.type == 'id') {
  2515. return expression.value;
  2516. }
  2517. if (expression.type == '.') {
  2518. return pytorch.Utility.target(expression.target) + '.' + pytorch.Utility.target(expression.member);
  2519. }
  2520. return null;
  2521. }
  2522. static isTensor(obj) {
  2523. const name = obj && obj.__class__ ? obj.__class__.__module__ : null;
  2524. switch (name) {
  2525. case 'torch':
  2526. case 'torch.cuda':
  2527. return obj.__class__.__name__.endsWith('Tensor');
  2528. case 'torch.nn.parameter':
  2529. return obj.__class__.__name__ === 'Parameter';
  2530. default:
  2531. return false;
  2532. }
  2533. }
  2534. static toTensor(obj) {
  2535. const name = obj && obj.__class__ ? obj.__class__.__module__ : null;
  2536. switch (name) {
  2537. case 'torch':
  2538. case 'torch.cuda':
  2539. return obj.__class__.__name__.endsWith('Tensor') ? obj : null;
  2540. case 'torch.nn.parameter':
  2541. return obj.__class__.__name__ === 'Parameter' ? obj.data : null;
  2542. default:
  2543. return null;
  2544. }
  2545. }
  2546. static createTensor(name, tensor, littleEndian) {
  2547. const storage = tensor.storage();
  2548. const size = tensor.size();
  2549. const type = new pytorch.TensorType(storage.dtype.__reduce__(), new pytorch.TensorShape(size));
  2550. return new pytorch.Tensor(name || '', type, storage.data, littleEndian);
  2551. }
  2552. static isType(obj, type) {
  2553. switch (type) {
  2554. case 'Tensor':
  2555. return !Array.isArray(obj) && (pytorch.Utility.isTensor(obj) || obj === null);
  2556. case 'Tensor[]':
  2557. return Array.isArray(obj) && obj.length > 0 && obj.every((tensor) => pytorch.Utility.isTensor(tensor) || tensor === null);
  2558. case 'Scalar':
  2559. return (obj !== null && obj !== Object(obj)) || (pytorch.Utility.isTensor(obj) && Array.isArray(obj.size()) && obj.size().length === 0);
  2560. case 'boolean':
  2561. return obj === true || obj === false;
  2562. case 'int64':
  2563. return Number.isInteger(obj) || obj instanceof base.Int64 || (typeof obj === 'number' && isNaN(obj));
  2564. case 'int64[]':
  2565. return Array.isArray(obj) && obj.every((item) => Number.isInteger(item) || (typeof item === 'number' && isNaN(item)) || item === undefined);
  2566. case 'int64[1]':
  2567. return pytorch.Utility.isType(obj, 'int64') || pytorch.Utility.isType(obj, 'int64[]');
  2568. case 'float32':
  2569. case 'float64':
  2570. return obj !== null && obj !== Object(obj);
  2571. case 'string[][]':
  2572. return Array.isArray(obj) && obj.every((item) => Array.isArray(item) && item.every((item) => typeof item === 'string'));
  2573. case 'Layout':
  2574. case 'ScalarType':
  2575. case 'MemoryFormat':
  2576. return Number.isInteger(obj) || obj === null;
  2577. case 'Device':
  2578. return obj === null || obj === Object(obj);
  2579. default:
  2580. return true;
  2581. }
  2582. }
  2583. static isCall(expression, name, size) {
  2584. if (expression.type === 'call' &&
  2585. expression.arguments.length === size &&
  2586. pytorch.Utility.target(expression.target) === name) {
  2587. return true;
  2588. }
  2589. return false;
  2590. }
  2591. static isEqual(a, b) {
  2592. return (a.type === 'id' && b.type === 'id' && a.value === b.value);
  2593. }
  2594. static find(data) {
  2595. const root = pytorch.Utility.findModule(data);
  2596. if (root) {
  2597. for (const graph of root) {
  2598. graph.type = 'module';
  2599. }
  2600. return root;
  2601. }
  2602. const weights = pytorch.Utility.findWeights(data);
  2603. if (weights) {
  2604. for (const graph of weights) {
  2605. graph.type = 'weights';
  2606. }
  2607. return weights;
  2608. }
  2609. throw new pytorch.Error('File does not contain root module or state dictionary.');
  2610. }
  2611. static findModule(root) {
  2612. if (root) {
  2613. const keys = [ '', 'model', 'net' ];
  2614. for (const key of keys) {
  2615. const obj = key === '' ? root : root[key];
  2616. if (obj && obj instanceof Map && obj.has('engine')) {
  2617. // https://github.com/NVIDIA-AI-IOT/torch2trt/blob/master/torch2trt/torch2trt.py
  2618. const data = obj.get('engine');
  2619. const signature = [ 0x70, 0x74, 0x72, 0x74 ]; // ptrt
  2620. if (data instanceof Uint8Array && data.length > signature.length && signature.every((value, index) => value === data[index])) {
  2621. const buffer = data.slice(0, 24);
  2622. const content = Array.from(buffer).map((c) => (c < 16 ? '0' : '') + c.toString(16)).join('');
  2623. throw new pytorch.Error("Invalid file content. File contains undocumented PyTorch TensorRT engine data (" + content.substring(8) + ").");
  2624. }
  2625. }
  2626. if (obj) {
  2627. if (obj._modules) {
  2628. return [ { name: '', data: obj } ];
  2629. }
  2630. const objKeys = Object.keys(obj).filter((key) => obj[key] && obj[key]._modules);
  2631. if (objKeys.length > 1) {
  2632. return objKeys.map((key) => { return { name: key, data: obj[key] }; });
  2633. }
  2634. }
  2635. }
  2636. }
  2637. return null;
  2638. }
  2639. static findWeights(root) {
  2640. if (!root) {
  2641. return null;
  2642. }
  2643. if (root instanceof Map) {
  2644. const obj = {};
  2645. for (const pair of root) {
  2646. const key = pair[0];
  2647. const value = pair[1];
  2648. obj[key] = value;
  2649. }
  2650. root = obj;
  2651. }
  2652. const keys = root && !Array.isArray(root) ? Object.keys(root) : [];
  2653. if (keys.length > 1) {
  2654. keys.splice(0, keys.length);
  2655. }
  2656. keys.push(...[
  2657. 'state_dict', 'state', 'model_state', 'model', 'model_state_dict', 'model_dict', 'net_dict', 'params', 'generator', 'module', 'weights',
  2658. 'discriminator', 'g_state', 'network', 'net', 'netG', 'net_states', 'state_dict_stylepredictor', 'state_dict_ghiasi', 'runner', ''
  2659. ]);
  2660. for (const key of keys) {
  2661. const obj = key === '' ? root : root[key];
  2662. let graphs = null;
  2663. graphs = graphs || pytorch.Utility._convertTensor(obj);
  2664. graphs = graphs || pytorch.Utility._convertObjectList(obj);
  2665. graphs = graphs || pytorch.Utility._convertStateDict(obj);
  2666. if (graphs) {
  2667. return graphs;
  2668. }
  2669. }
  2670. return null;
  2671. }
  2672. static _convertTensor(obj) {
  2673. if (obj && pytorch.Utility.isTensor(obj)) {
  2674. const layers = [];
  2675. const argument = { id: '', value: obj };
  2676. const parameter = { name: 'value', arguments: [ argument ] };
  2677. layers.push({ states: [ parameter ] });
  2678. return [ { data: layers } ];
  2679. }
  2680. return null;
  2681. }
  2682. static _convertObjectList(obj) {
  2683. if (obj && Array.isArray(obj)) {
  2684. if (obj.every((item) => typeof item === 'number' || typeof item === 'string')) {
  2685. const layers = [];
  2686. const type = obj.__class__ ? obj.__class__.__module__ + '.' + obj.__class__.__name__ : '?';
  2687. const layer = { type: type, states: [], attributes: [] };
  2688. for (let i = 0; i < obj.length; i++) {
  2689. const key = i.toString();
  2690. const value = obj[i];
  2691. if (pytorch.Utility.isTensor(value)) {
  2692. layer.states.push({ name: key, arguments: [ { id: '', value: value } ] });
  2693. }
  2694. else {
  2695. layer.attributes.push({ name: key, value: value });
  2696. }
  2697. }
  2698. layers.push(layer);
  2699. return [ { data: layers } ];
  2700. }
  2701. if (obj.every((item) => item && Object.values(item).filter((value) => pytorch.Utility.isTensor(value)).length > 0)) {
  2702. const layers = [];
  2703. for (const item of obj) {
  2704. const type = item.__class__ ? item.__class__.__module__ + '.' + item.__class__.__name__ : '?';
  2705. const layer = { type: type, states: [], attributes: [] };
  2706. if (item instanceof Map) {
  2707. return null;
  2708. }
  2709. for (const entry of Object.entries(item)) {
  2710. const key = entry[0];
  2711. const value = entry[1];
  2712. if (pytorch.Utility.isTensor(value)) {
  2713. layer.states.push({ name: key, arguments: [ { id: '', value: value } ] });
  2714. }
  2715. else {
  2716. layer.attributes.push({ name: key, value: value });
  2717. }
  2718. }
  2719. layers.push(layer);
  2720. }
  2721. return [ { data: layers } ];
  2722. }
  2723. }
  2724. return null;
  2725. }
  2726. static _convertStateDict(obj) {
  2727. const clean = (obj) => {
  2728. if (obj && Array.isArray(obj)) {
  2729. return obj;
  2730. }
  2731. if (obj && obj instanceof Map) {
  2732. return obj;
  2733. }
  2734. if (obj && Object(obj) === obj) {
  2735. const target = {};
  2736. const map_count = Object.entries(obj).filter((entry) => entry[1] instanceof Map).length;
  2737. for (const entry of Object.entries(obj)) {
  2738. const key = entry[0];
  2739. const value = entry[1];
  2740. if (key.indexOf('optim') !== -1 || key.indexOf('opt') !== -1) {
  2741. if (value === null || (value.state && value.param_groups)) {
  2742. continue;
  2743. }
  2744. }
  2745. if (map_count > 2 && key.endsWith('_avg') && pytorch.Utility.isTensor(value)) {
  2746. continue;
  2747. }
  2748. if (typeof value === 'number' || typeof value === 'string' || typeof value === 'boolean') {
  2749. continue;
  2750. }
  2751. if (key === '__class__' && value.__module__ && value.__name__) {
  2752. continue;
  2753. }
  2754. if (Array.isArray(value) && (key.indexOf('loss') !== -1 || value.length === 0)) {
  2755. continue;
  2756. }
  2757. if (value && value.__class__ && value.__class__.__module__ === 'datetime' && value.__class__.__name__ === 'datetime') {
  2758. continue;
  2759. }
  2760. if ((key.startsWith('dico_') && Object(value) === value) ||
  2761. (key === 'args' && Object(value) === value) ||
  2762. (key.startsWith('params') && Object(value) === value && (value.id2lang || value.lang2id)) ||
  2763. (key.startsWith('spk_dict_') && Object(value) === value && Object.keys(value).length === 0)) {
  2764. continue;
  2765. }
  2766. target[key] = value;
  2767. }
  2768. return target;
  2769. }
  2770. return obj;
  2771. };
  2772. const validate = (map) => {
  2773. let tensor = false;
  2774. if (map && map instanceof Map) {
  2775. for (const pair of map) {
  2776. const key = pair[0];
  2777. const value = pair[1];
  2778. const separator = key.indexOf('.') === -1 && key.indexOf('|') !== -1 ? '|' : '.';
  2779. const keys = key.split(separator);
  2780. if (keys[keys.length - 1] === '_metadata') {
  2781. continue;
  2782. }
  2783. else if (keys.length >= 2 && keys[keys.length - 2] === '_packed_params') {
  2784. continue;
  2785. }
  2786. else if (pytorch.Utility.isTensor(value)) {
  2787. tensor = true;
  2788. continue;
  2789. }
  2790. else if (value && Array.isArray(value) && value.every((item) => pytorch.Utility.isTensor(item))) {
  2791. tensor = true;
  2792. continue;
  2793. }
  2794. else if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
  2795. continue;
  2796. }
  2797. else if (value === null) {
  2798. continue;
  2799. }
  2800. return false;
  2801. }
  2802. }
  2803. return tensor;
  2804. };
  2805. const flatten = (obj) => {
  2806. if (!obj || Array.isArray(obj) || ArrayBuffer.isView(obj)) {
  2807. return null;
  2808. }
  2809. if (obj instanceof Map) {
  2810. if (validate(obj)) {
  2811. return obj;
  2812. }
  2813. return null;
  2814. }
  2815. if (Object(obj) !== obj) {
  2816. return null;
  2817. }
  2818. const map = new Map(Object.keys(obj).map((key) => [ key, obj[key] ]));
  2819. if (validate(map)) {
  2820. return map;
  2821. }
  2822. map.clear();
  2823. for (const key of Object.keys(obj)) {
  2824. const value = flatten(obj[key]);
  2825. if (value && value instanceof Map) {
  2826. for (const pair of value) {
  2827. map.set(key + '.' + pair[0], pair[1]);
  2828. }
  2829. continue;
  2830. }
  2831. return null;
  2832. }
  2833. return map;
  2834. };
  2835. if (!obj) {
  2836. return null;
  2837. }
  2838. obj = clean(obj);
  2839. const map = new Map();
  2840. if (Array.isArray(obj) && obj.every((item) => validate(item))) {
  2841. for (let i = 0; i < obj.length; i++) {
  2842. map.set(i.toString(), flatten(obj[i]));
  2843. }
  2844. }
  2845. else if (obj instanceof Map && validate(obj)) {
  2846. map.set('', flatten(obj));
  2847. }
  2848. else if (Object(obj) === obj && Object.entries(obj).every((entry) => validate(entry[1]))) {
  2849. for (const entry of Object.entries(obj)) {
  2850. map.set(entry[0], entry[1]);
  2851. }
  2852. }
  2853. else if (Object(obj) === obj && Object.entries(obj).every((entry) => pytorch.Utility.isTensor(entry[1]))) {
  2854. map.set('', new Map(Object.keys(obj).map((key) => [ key, obj[key] ])));
  2855. }
  2856. else {
  2857. const value = flatten(obj);
  2858. if (value) {
  2859. map.set('', value);
  2860. }
  2861. }
  2862. if (map.size > 0) {
  2863. const graphs = [];
  2864. for (const entry of map) {
  2865. const graph_key = entry[0];
  2866. const layer_map = entry[1];
  2867. const layers = new Map();
  2868. for (const item of layer_map) {
  2869. const key = item[0];
  2870. const value = item[1];
  2871. let layerName = '';
  2872. let parameter = '';
  2873. const separator = key.indexOf('.') === -1 && key.indexOf('|') !== -1 ? '|' : '.';
  2874. const keys = key.split(separator);
  2875. if (keys[keys.length - 1] === '_metadata') {
  2876. continue;
  2877. }
  2878. if (keys.length >= 2 && keys[keys.length - 2] === '_packed_params') {
  2879. parameter = keys.slice(-2).join(separator);
  2880. keys.pop();
  2881. keys.pop();
  2882. }
  2883. else {
  2884. parameter = keys.pop();
  2885. if (keys.length < 0) {
  2886. keys.push('');
  2887. }
  2888. }
  2889. layerName = keys.join(separator);
  2890. if (!layers.has(layerName)) {
  2891. layers.set(layerName, { name: layerName, states: [], attributes: [] });
  2892. }
  2893. const layer = layers.get(layerName);
  2894. if (pytorch.Utility.isTensor(value)) {
  2895. layer.states.push({ name: parameter, arguments: [ { id: key, value: value } ] });
  2896. if (layer.name == '' && layer.states.length > 12) {
  2897. return null;
  2898. }
  2899. }
  2900. else if (value && Array.isArray(value) && value.every((item) => pytorch.Utility.isTensor(item))) {
  2901. layer.states.push({ name: parameter, arguments: value.map((item) => { return { id: '', value: item }; }) });
  2902. }
  2903. else if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
  2904. layer.attributes.push({ name: parameter, value: value });
  2905. }
  2906. }
  2907. graphs.push({
  2908. name: graph_key,
  2909. data: layers.values()
  2910. });
  2911. }
  2912. return graphs;
  2913. }
  2914. return null;
  2915. }
  2916. };
  2917. pytorch.nnapi = {};
  2918. pytorch.nnapi.SerializedModel = class {
  2919. constructor(serialized_model, buffers) {
  2920. const reader = new base.BinaryReader(serialized_model);
  2921. this.version = reader.int32();
  2922. if (this.version !== 1) {
  2923. throw new pytorch.Error('Invalid NNAPI serialized model version.');
  2924. }
  2925. const operands = new Array(reader.int32());
  2926. const values = new Array(reader.int32());
  2927. this.operations = new Array(reader.int32());
  2928. this.inputs = new Array(reader.int32());
  2929. this.outputs = new Array(reader.int32());
  2930. const data_types = new Map([
  2931. [ 0, 'float32' ],
  2932. [ 1, 'int32' ],
  2933. [ 2, 'uint32' ],
  2934. [ 3, 'float32[]' ],
  2935. [ 4, 'int32[]' ],
  2936. [ 5, 'quant8_asymm[]' ],
  2937. [ 6, 'boolean' ],
  2938. [ 7, 'quant16_symm[]' ],
  2939. [ 8, 'float16[]' ],
  2940. [ 9, 'boolean[]' ],
  2941. [ 10, 'float16' ],
  2942. [ 11, 'quant8_symm_per_channel[]' ],
  2943. [ 12, 'quant16_asymm[]' ],
  2944. [ 13, 'quant8_symm[]' ],
  2945. [ 14, 'quant8_asymm_signed[]' ],
  2946. [ 16, 'model' ]
  2947. ]);
  2948. for (let i = 0; i < operands.length; i++) {
  2949. const data_type = reader.int32();
  2950. operands[i] = {
  2951. index: i,
  2952. data_type: data_types.has(data_type) ? data_types.get(data_type) : data_type,
  2953. dimensions: new Array(reader.uint32()),
  2954. scale: reader.float32(),
  2955. zero_point: reader.int32()
  2956. };
  2957. }
  2958. for (let i = 0; i < values.length; i++) {
  2959. values[i] = {
  2960. index: reader.int32(),
  2961. source_type: reader.int32(),
  2962. source_length: reader.uint32()
  2963. };
  2964. }
  2965. for (let i = 0; i < this.operations.length; i++) {
  2966. this.operations[i] = {
  2967. index: reader.int32(),
  2968. location: i,
  2969. inputs: new Array(reader.uint32()),
  2970. outputs: new Array(reader.uint32())
  2971. };
  2972. }
  2973. for (const operand of operands) {
  2974. for (let i = 0; i< operand.dimensions.length; i++) {
  2975. operand.dimensions[i] = reader.uint32();
  2976. }
  2977. }
  2978. for (const value of values) {
  2979. const index = value.index;
  2980. const operand = operands[index];
  2981. switch (value.source_type) {
  2982. case 0: { // immediate
  2983. switch (operand.data_type) {
  2984. case 'boolean':
  2985. operand.value = reader.byte() ? true : false;
  2986. reader.skip(3);
  2987. break;
  2988. case 'int32':
  2989. operand.value = reader.int32();
  2990. break;
  2991. case 'float32':
  2992. operand.value = reader.float32();
  2993. break;
  2994. case 'int32[]':
  2995. operand.data = reader.read(value.source_length);
  2996. break;
  2997. case 'float32[]':
  2998. operand.data = reader.read(value.source_length);
  2999. break;
  3000. default:
  3001. throw new pytorch.Error("Unsupported NNAPI operand type '" + operand.data_type.toString() + "'.");
  3002. }
  3003. break;
  3004. }
  3005. case 2: { // numbered buffer
  3006. if (value.source_length !== 12) {
  3007. throw new pytorch.Error('Invalid NNAPI numbered buffer source length.');
  3008. }
  3009. const number = reader.uint32();
  3010. const offset = reader.uint32();
  3011. const operand_length = reader.uint32();
  3012. const buffer = buffers[number];
  3013. operand.data = buffer.slice(offset, operand_length);
  3014. break;
  3015. }
  3016. case 3: { // numbered memory
  3017. throw new pytorch.Error('NNAPI numbered memory buffer not implemented.');
  3018. }
  3019. default: {
  3020. throw new pytorch.Error('Unsupported NNAPI value source type.');
  3021. }
  3022. }
  3023. }
  3024. for (const operation of this.operations) {
  3025. for (let i = 0; i< operation.inputs.length; i++) {
  3026. const index = reader.uint32();
  3027. operation.inputs[i] = operands[index];
  3028. }
  3029. for (let i = 0; i< operation.outputs.length; i++) {
  3030. const index = reader.uint32();
  3031. operation.outputs[i] = operands[index];
  3032. }
  3033. }
  3034. for (let i = 0; i< this.inputs.length; i++) {
  3035. const index = reader.uint32();
  3036. this.inputs[i] = operands[index];
  3037. }
  3038. for (let i = 0; i< this.outputs.length; i++) {
  3039. const index = reader.uint32();
  3040. this.outputs[i] = operands[index];
  3041. }
  3042. if (reader.position !== reader.length) {
  3043. throw new pytorch.Error('Invalid NNAPI serialized model length.');
  3044. }
  3045. }
  3046. };
  3047. pytorch.nnapi.Metadata = class {
  3048. constructor() {
  3049. this._types = new Map();
  3050. // https://developer.android.com/ndk/reference/group/neural-networks
  3051. // https://github.com/pytorch/pytorch/commits/master/torch/backends/_nnapi/serializer.py
  3052. this.register( 0, 'ADD', '', [ 'A', 'B' ], [ [ 'activation', 'int32'] ], [ 'C' ]);
  3053. 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' ]);
  3054. 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' ]);
  3055. this.register( 2, 'CONCATENATION');
  3056. 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' ]);
  3057. 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' ]);
  3058. 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' ]);
  3059. 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' ]);
  3060. this.register( 5, 'DEPTH_TO_SPACE');
  3061. this.register( 6, 'DEQUANTIZE');
  3062. this.register( 7, 'EMBEDDING_LOOKUP');
  3063. this.register( 8, 'FLOOR');
  3064. this.register( 9, 'FULLY_CONNECTED', 'Layer', [ 'input', 'weights', 'bias' ], [ [ 'activation', 'int32' ] ], [ 'output' ]);
  3065. this.register(10, 'HASHTABLE_LOOKUP');
  3066. this.register(11, 'L2_NORMALIZATION');
  3067. this.register(12, 'L2_POOL_2D', 'Pool');
  3068. this.register(13, 'LOCAL_RESPONSE_NORMALIZATION');
  3069. this.register(14, 'LOGISTIC');
  3070. this.register(15, 'LSH_PROJECTION');
  3071. this.register(16, 'LSTM', 'Layer');
  3072. this.register(17, 'MAX_POOL_2D', 'Pool');
  3073. this.register(18, 'MUL');
  3074. this.register(19, 'RELU', 'Activation', [ 'input' ], [], [ 'output' ]);
  3075. this.register(20, 'RELU1', 'Activation');
  3076. this.register(21, 'RELU6', 'Activation');
  3077. this.register(22, 'RESHAPE', 'Shape', [ 'input', 'shape' ], [], [ 'output' ]);
  3078. this.register(23, 'RESIZE_BILINEAR');
  3079. this.register(24, 'RNN', 'Layer');
  3080. this.register(25, 'SOFTMAX', 'Activation');
  3081. this.register(26, 'SPACE_TO_DEPTH');
  3082. this.register(27, 'SVDF');
  3083. this.register(28, 'TANH');
  3084. this.register(29, 'BATCH_TO_SPACE_ND');
  3085. this.register(30, 'DIV');
  3086. this.register(31, 'MEAN');
  3087. this.register(32, 'PAD');
  3088. this.register(33, 'SPACE_TO_BATCH_ND');
  3089. this.register(34, 'SQUEEZE');
  3090. this.register(35, 'STRIDED_SLICE');
  3091. this.register(36, 'SUB');
  3092. this.register(37, 'TRANSPOSE');
  3093. this.register(38, 'ABS');
  3094. this.register(39, 'ARGMAX');
  3095. this.register(40, 'ARGMIN');
  3096. this.register(41, 'AXIS_ALIGNED_BBOX_TRANSFORM');
  3097. this.register(42, 'BIDIRECTIONAL_SEQUENCE_LSTM');
  3098. this.register(43, 'BIDIRECTIONAL_SEQUENCE_RNN');
  3099. this.register(44, 'BOX_WITH_NMS_LIMIT');
  3100. this.register(45, 'CAST');
  3101. this.register(46, 'CHANNEL_SHUFFLE');
  3102. this.register(47, 'DETECTION_POSTPROCESSING');
  3103. this.register(48, 'EQUAL');
  3104. this.register(49, 'EXP');
  3105. this.register(50, 'EXPAND_DIMS');
  3106. this.register(51, 'GATHER');
  3107. this.register(52, 'GENERATE_PROPOSALS');
  3108. this.register(53, 'GREATER');
  3109. this.register(54, 'GREATER_EQUAL');
  3110. this.register(55, 'GROUPED_CONV_2D');
  3111. this.register(56, 'HEATMAP_MAX_KEYPOINT');
  3112. this.register(57, 'INSTANCE_NORMALIZATION');
  3113. this.register(58, 'LESS');
  3114. this.register(59, 'LESS_EQUAL');
  3115. this.register(60, 'LOG');
  3116. this.register(61, 'LOGICAL_AND');
  3117. this.register(62, 'LOGICAL_NOT');
  3118. this.register(63, 'LOGICAL_OR');
  3119. this.register(64, 'LOG_SOFTMAX');
  3120. this.register(65, 'MAXIMUM');
  3121. this.register(66, 'MINIMUM');
  3122. this.register(67, 'NEG');
  3123. this.register(68, 'NOT_EQUAL');
  3124. this.register(69, 'PAD_V2');
  3125. this.register(70, 'POW');
  3126. this.register(71, 'PRELU');
  3127. this.register(72, 'QUANTIZE');
  3128. this.register(73, 'QUANTIZED_16BIT_LSTM');
  3129. this.register(74, 'RANDOM_MULTINOMIAL');
  3130. this.register(75, 'REDUCE_ALL');
  3131. this.register(76, 'REDUCE_ANY');
  3132. this.register(77, 'REDUCE_MAX');
  3133. this.register(78, 'REDUCE_MIN');
  3134. this.register(79, 'REDUCE_PROD');
  3135. this.register(80, 'REDUCE_SUM');
  3136. this.register(81, 'ROI_ALIGN');
  3137. this.register(82, 'ROI_POOLING');
  3138. this.register(83, 'RSQRT');
  3139. this.register(84, 'SELECT');
  3140. this.register(85, 'SIN');
  3141. this.register(86, 'SLICE');
  3142. this.register(87, 'SPLIT');
  3143. this.register(88, 'SQRT');
  3144. this.register(89, 'TILE');
  3145. this.register(90, 'TOPK_V2');
  3146. this.register(91, 'TRANSPOSE_CONV_2D', 'Layer');
  3147. this.register(92, 'UNIDIRECTIONAL_SEQUENCE_LSTM', 'Layer');
  3148. this.register(93, 'UNIDIRECTIONAL_SEQUENCE_RNN', 'Layer');
  3149. this.register(94, 'RESIZE_NEAREST_NEIGHBOR');
  3150. this.register(95, 'QUANTIZED_LSTM', 'Layer');
  3151. this.register(96, 'IF');
  3152. this.register(97, 'WHILE');
  3153. this.register(98, 'ELU', 'Activation');
  3154. this.register(99, 'HARD_SWISH', 'Activation');
  3155. this.register(100, 'FILL');
  3156. this.register(101, 'RANK');
  3157. }
  3158. register(index, name, category, inputs, attributes, outputs) {
  3159. inputs = inputs || [];
  3160. outputs = outputs || [];
  3161. attributes = attributes || [];
  3162. const type = {
  3163. name: name,
  3164. inputs: inputs.map((name) => { return { name: name, type: 'Tensor' }; }),
  3165. outputs: outputs.map((name) => { return { name: name, type: 'Tensor' }; }),
  3166. attributes: attributes.map((pair) => { return { name: pair[0], type: pair[1] }; })
  3167. };
  3168. if (category) {
  3169. type.category = category;
  3170. }
  3171. if (!this._types.has(index)) {
  3172. this._types.set(index, []);
  3173. }
  3174. this._types.get(index).push(type);
  3175. }
  3176. type(index, signature) {
  3177. if (!this._types.has(index)) {
  3178. this._types.set(index, { name: index.toString(), inputs: [], outputs: [], attributes: [] });
  3179. }
  3180. const types = this._types.get(index);
  3181. for (const type of types) {
  3182. const inputs = type.inputs.concat(type.attributes);
  3183. if (signature.length < inputs.length) {
  3184. let match = true;
  3185. for (let i = 0; i < inputs.length; i++) {
  3186. const input = inputs[i];
  3187. if (input.type === undefined || input.type === 'Tensor' || input.type === signature[i]) {
  3188. continue;
  3189. }
  3190. match = false;
  3191. }
  3192. if (match) {
  3193. return type;
  3194. }
  3195. }
  3196. }
  3197. return types[0];
  3198. }
  3199. };
  3200. pytorch.nnapi.Graph = class {
  3201. constructor(model) {
  3202. this._nodes = [];
  3203. this._inputs = [];
  3204. this._outputs = [];
  3205. const args = new Map();
  3206. const arg = (operand) => {
  3207. if (!args.has(operand.index)) {
  3208. const argument = new pytorch.nnapi.Argument(operand);
  3209. args.set(operand.index, argument);
  3210. }
  3211. return args.get(operand.index);
  3212. };
  3213. const metadata = new pytorch.nnapi.Metadata();
  3214. for (const operation of model.operations) {
  3215. const node = new pytorch.nnapi.Node(metadata, operation, arg);
  3216. this._nodes.push(node);
  3217. }
  3218. for (let i = 0; i < model.inputs.length; i++) {
  3219. const operand = model.inputs[i];
  3220. const argument = arg(operand);
  3221. const parameter = new pytorch.Parameter(i.toString(), true, [ argument ]);
  3222. this._inputs.push(parameter);
  3223. }
  3224. for (let i = 0; i < model.outputs.length; i++) {
  3225. const operand = model.outputs[i];
  3226. const argument = arg(operand);
  3227. const parameter = new pytorch.Parameter(i.toString(), true, [ argument ]);
  3228. this._outputs.push(parameter);
  3229. }
  3230. }
  3231. get name() {
  3232. return 'torch.classes._nnapi.Compilation';
  3233. }
  3234. get inputs() {
  3235. return this._inputs;
  3236. }
  3237. get outputs() {
  3238. return this._outputs;
  3239. }
  3240. get nodes() {
  3241. return this._nodes;
  3242. }
  3243. };
  3244. pytorch.nnapi.Argument = class {
  3245. constructor(operand) {
  3246. this._name = operand.index.toString();
  3247. const shape = new pytorch.TensorShape(operand.dimensions);
  3248. this._type = new pytorch.TensorType(operand.data_type.replace('[]', ''), shape);
  3249. this._initializer = operand.data ? new pytorch.Tensor(this._name, this._type, operand.data, true) : null;
  3250. this._scale = operand.scale;
  3251. this._zeroPoint = operand.zero_point;
  3252. }
  3253. get name() {
  3254. return this._name;
  3255. }
  3256. get type() {
  3257. return this._type;
  3258. }
  3259. get quantization() {
  3260. if (this._scale != 0 || this._zeroPoint != 0) {
  3261. return this._scale.toString() + ' * ' + (this._zeroPoint == 0 ? 'q' : ('(q - ' + this._zeroPoint.toString() + ')'));
  3262. }
  3263. return null;
  3264. }
  3265. get initializer() {
  3266. return this._initializer;
  3267. }
  3268. };
  3269. pytorch.nnapi.Node = class {
  3270. constructor(metadata, operation, arg) {
  3271. const signature = (operation.inputs || []).map((input) => input.data_type);
  3272. this._type = metadata.type(operation.index, signature);
  3273. this._inputs = [];
  3274. this._outputs = [];
  3275. this._attributes = [];
  3276. this._chain = [];
  3277. if (operation.location !== undefined) {
  3278. this._location = operation.location.toString();
  3279. }
  3280. const inputs = this._type.inputs.concat(this._type.attributes);
  3281. if (operation.inputs) {
  3282. for (let i = 0; i < operation.inputs.length; i++) {
  3283. const name = i < inputs.length ? inputs[i].name : i.toString();
  3284. const operand = operation.inputs[i];
  3285. if (operand.dimensions.length > 0) {
  3286. const argument = arg(operand);
  3287. const parameter = new pytorch.Parameter(name, true, [ argument ]);
  3288. this._inputs.push(parameter);
  3289. }
  3290. else if (name === 'activation') {
  3291. const activation = new Map([ [ 1, 19 ], [ 2, 20 ], [ 3, 21 ] ]).get(operand.value) || 0;
  3292. if (activation !== 0) {
  3293. this._chain.push(new pytorch.nnapi.Node(metadata, { index: activation }));
  3294. }
  3295. }
  3296. else {
  3297. const attribute = new pytorch.nnapi.Attribute(name, operand);
  3298. this._attributes.push(attribute);
  3299. }
  3300. }
  3301. }
  3302. if (operation.outputs) {
  3303. for (let i = 0; i < operation.outputs.length; i++) {
  3304. const name = i < inputs.length ? inputs[i].name : i.toString();
  3305. const operand = operation.outputs[i];
  3306. const argument = arg(operand);
  3307. const parameter = new pytorch.Parameter(name, true, [ argument ]);
  3308. this._outputs.push(parameter);
  3309. }
  3310. }
  3311. }
  3312. get type() {
  3313. return this._type;
  3314. }
  3315. get location() {
  3316. return this._location;
  3317. }
  3318. get inputs() {
  3319. return this._inputs;
  3320. }
  3321. get outputs() {
  3322. return this._outputs;
  3323. }
  3324. get attributes() {
  3325. return this._attributes;
  3326. }
  3327. get chain() {
  3328. return this._chain;
  3329. }
  3330. };
  3331. pytorch.nnapi.Attribute = class {
  3332. constructor(name, operand) {
  3333. this._name = name;
  3334. this._type = operand.data_type;
  3335. this._value = operand.value;
  3336. }
  3337. get type() {
  3338. return this._type;
  3339. }
  3340. get name() {
  3341. return this._name;
  3342. }
  3343. get value() {
  3344. return this._value;
  3345. }
  3346. get visible() {
  3347. return false;
  3348. }
  3349. };
  3350. pytorch.nnapi.Tensor = class {
  3351. constructor(type, data) {
  3352. this._type = type;
  3353. this._data = data;
  3354. }
  3355. get type() {
  3356. return this._type;
  3357. }
  3358. get state() {
  3359. return 'Not implemented.';
  3360. }
  3361. };
  3362. pytorch.Metadata = class {
  3363. static open(context) {
  3364. if (pytorch.Metadata._metadata) {
  3365. return Promise.resolve(pytorch.Metadata._metadata);
  3366. }
  3367. return context.request('pytorch-metadata.json', 'utf-8', null).then((data) => {
  3368. pytorch.Metadata._metadata = new pytorch.Metadata(data);
  3369. return pytorch.Metadata._metadata;
  3370. }).catch(() => {
  3371. pytorch.Metadata._metadata = new pytorch.Metadata(null);
  3372. return pytorch.Metadata._metadata;
  3373. });
  3374. }
  3375. constructor(data) {
  3376. this._types = new Map();
  3377. this._attributes = new Map();
  3378. if (data) {
  3379. const items = JSON.parse(data);
  3380. for (const item of items) {
  3381. this._types.set(item.name, item);
  3382. const index = item.name.indexOf(':');
  3383. if (index !== -1) {
  3384. const name = item.name.substring(0, index);
  3385. if (!this._types.has(name)) {
  3386. this._types.set(name, []);
  3387. }
  3388. this._types.get(name).push(item.name);
  3389. }
  3390. }
  3391. }
  3392. }
  3393. type(name) {
  3394. const schema = this._types.get(name);
  3395. if (schema) {
  3396. return Array.isArray(schema) ? schema.map((name) => this._types.get(name)) : schema;
  3397. }
  3398. return null;
  3399. }
  3400. attribute(type, name) {
  3401. const attributeName = type + ':' + name;
  3402. if (!this._attributes.has(attributeName)) {
  3403. this._attributes.set(attributeName, null);
  3404. const schema = this.type(type);
  3405. if (schema) {
  3406. if (schema.inputs) {
  3407. for (const input of schema.inputs) {
  3408. this._attributes.set(type + ':' + input.name, input);
  3409. }
  3410. }
  3411. if (schema.attributes) {
  3412. for (const attribute of schema.attributes) {
  3413. this._attributes.set(type + ':' + attribute.name, attribute);
  3414. }
  3415. }
  3416. }
  3417. }
  3418. return this._attributes.get(attributeName);
  3419. }
  3420. };
  3421. pytorch.Error = class extends Error {
  3422. constructor(message) {
  3423. super(message);
  3424. this.name = 'Error loading PyTorch model.';
  3425. }
  3426. };
  3427. if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  3428. module.exports.ModelFactory = pytorch.ModelFactory;
  3429. }