mxnet.js 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330
  1. /* jshint esversion: 6 */
  2. /* eslint "indent": [ "error", 4, { "SwitchCase": 1 } ] */
  3. var mxnet = mxnet || {};
  4. var long = long || { Long: require('long') };
  5. var zip = zip || require('./zip');
  6. var ndarray = ndarray || {};
  7. mxnet.ModelFactory = class {
  8. match(context) {
  9. const identifier = context.identifier;
  10. const extension = identifier.split('.').pop().toLowerCase();
  11. if (extension == 'model' || extension == 'mar') {
  12. if (context.entries('zip').length > 0) {
  13. return true;
  14. }
  15. }
  16. else if (extension == 'json') {
  17. const json = context.text;
  18. if (json.indexOf('"nodes":', 0) != -1) {
  19. try {
  20. const symbol = JSON.parse(json);
  21. if (symbol && symbol.nodes && symbol.arg_nodes && symbol.heads) {
  22. return true;
  23. }
  24. }
  25. catch (err) {
  26. // continue regardless of error
  27. }
  28. }
  29. }
  30. else if (extension == 'params') {
  31. const buffer = context.buffer;
  32. const signature = [ 0x12, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ];
  33. if (buffer && buffer.length > signature.length && signature.every((v, i) => v == buffer[i])) {
  34. return true;
  35. }
  36. }
  37. return false;
  38. }
  39. open(context, host) {
  40. const identifier = context.identifier;
  41. const extension = context.identifier.split('.').pop().toLowerCase();
  42. let symbol = null;
  43. let params = null;
  44. let format = null;
  45. let basename = null;
  46. switch (extension) {
  47. case 'json':
  48. try {
  49. symbol = JSON.parse(context.text);
  50. if (symbol && symbol.nodes && symbol.nodes.some((node) => node && node.op == 'tvm_op')) {
  51. format = 'TVM';
  52. }
  53. basename = mxnet.ModelFactory._basename(identifier, 'json', 'symbol');
  54. if (basename) {
  55. return context.request(basename + '-0000.params', null).then((params) => {
  56. return this._openModel(identifier, format, null, symbol, null, params, host);
  57. }).catch(() => {
  58. return this._openModel(identifier, format, null, symbol, null, params, host);
  59. });
  60. }
  61. return this._openModel(identifier, format, null, symbol, null, null, host);
  62. }
  63. catch (error) {
  64. host.exception(error, false);
  65. throw new mxnet.Error(error.message), null;
  66. }
  67. case 'params':
  68. params = context.buffer;
  69. basename = mxnet.ModelFactory._basename(context.identifier, 'params');
  70. if (basename) {
  71. return context.request(basename + '-symbol.json', 'utf-8').then((text) => {
  72. symbol = JSON.parse(text);
  73. if (symbol && symbol.nodes && symbol.nodes.some((node) => node && node.op == 'tvm_op')) {
  74. format = 'TVM';
  75. }
  76. return this._openModel(identifier, format, null, symbol, null, params, host);
  77. }).catch(() => {
  78. return this._openModel(identifier, format, null, null, null, params, host);
  79. });
  80. }
  81. else {
  82. return this._openModel(identifier, format, null, null, null, params, host);
  83. }
  84. case 'mar':
  85. case 'model': {
  86. let entries = new Map();
  87. try {
  88. for (const entry of context.entries('zip')) {
  89. entries.set(entry.name, entry);
  90. }
  91. }
  92. catch (err) {
  93. throw new mxnet.Error('Failed to decompress ZIP archive. ' + err.message);
  94. }
  95. let manifestEntry = entries.get(entries.has('MANIFEST.json') ? 'MANIFEST.json' : 'MAR-INF/MANIFEST.json');
  96. let rootFolder = '';
  97. if (!manifestEntry) {
  98. const folders = Array.from(entries.keys()).filter((name) => name.endsWith('/')).filter((name) => entries.get(name + 'MANIFEST.json'));
  99. if (folders.length != 1) {
  100. throw new mxnet.Error("Manifest not found in '" + context.identifier + "'.");
  101. }
  102. rootFolder = folders[0];
  103. manifestEntry = entries.get(rootFolder + 'MANIFEST.json');
  104. }
  105. const decoder = new TextDecoder('utf-8');
  106. let manifest = null;
  107. try {
  108. manifest = JSON.parse(decoder.decode(manifestEntry.data));
  109. }
  110. catch (err) {
  111. throw new mxnet.Error('Failed to read manifest. ' + err.message);
  112. }
  113. let modelFormat = null;
  114. let symbolEntry = null;
  115. let signatureEntry = null;
  116. let paramsEntry = null;
  117. if (manifest.Model) {
  118. modelFormat = manifest.Model['Model-Format'];
  119. if (modelFormat && modelFormat != 'MXNet-Symbolic') {
  120. throw new mxnet.Error('Model format \'' + modelFormat + '\' not supported.');
  121. }
  122. format = 'MXNet Model Server';
  123. if (manifest['Model-Archive-Version']) {
  124. format += ' v' + manifest['Model-Archive-Version'].toString();
  125. }
  126. if (!manifest.Model.Symbol) {
  127. throw new mxnet.Error('Manifest does not contain symbol entry.');
  128. }
  129. symbolEntry = entries.get(rootFolder + manifest.Model.Symbol);
  130. if (manifest.Model.Signature) {
  131. signatureEntry = entries.get(rootFolder + manifest.Model.Signature);
  132. }
  133. if (manifest.Model.Parameters) {
  134. paramsEntry = entries.get(rootFolder + manifest.Model.Parameters);
  135. }
  136. }
  137. else if (manifest.model) {
  138. format = 'MXNet Model Archive';
  139. if (manifest.specificationVersion) {
  140. format += ' v' + manifest.specificationVersion.toString();
  141. }
  142. if (manifest.model.modelName) {
  143. symbolEntry = entries.get(rootFolder + manifest.model.modelName + '-symbol.json');
  144. let key = null;
  145. for (key of Array.from(entries.keys())) {
  146. key = key.substring(rootFolder.length);
  147. if (key.endsWith('.params') && key.startsWith(manifest.model.modelName)) {
  148. paramsEntry = entries.get(key);
  149. break;
  150. }
  151. }
  152. if (!symbolEntry && !paramsEntry) {
  153. for (key of Object.keys(entries)) {
  154. key = key.substring(rootFolder.length);
  155. if (key.endsWith('.params')) {
  156. paramsEntry = entries.get(key);
  157. break;
  158. }
  159. }
  160. }
  161. }
  162. }
  163. else {
  164. throw new mxnet.Error('Manifest does not contain model.');
  165. }
  166. if (!symbolEntry && !paramsEntry) {
  167. throw new mxnet.Error("Model does not contain symbol entry.");
  168. }
  169. try {
  170. if (symbolEntry) {
  171. symbol = JSON.parse(decoder.decode(symbolEntry.data));
  172. }
  173. }
  174. catch (err) {
  175. throw new mxnet.Error('Failed to load symbol entry.' + err.message);
  176. }
  177. if (paramsEntry) {
  178. params = paramsEntry.data;
  179. }
  180. let signature = null;
  181. try {
  182. if (signatureEntry) {
  183. signature = JSON.parse(decoder.decode(signatureEntry.data));
  184. }
  185. }
  186. catch (err) {
  187. // continue regardless of error
  188. }
  189. try {
  190. return this._openModel(identifier, format, manifest, symbol, signature, params, host);
  191. }
  192. catch (error) {
  193. let message = error && error.message ? error.message : error.toString();
  194. message = message.endsWith('.') ? message.substring(0, message.length - 1) : message;
  195. throw new mxnet.Error(message + " in '" + identifier + "'.");
  196. }
  197. }
  198. default:
  199. throw new mxnet.Error('Unsupported file extension.');
  200. }
  201. }
  202. _openModel(identifier, format, manifest, symbol, signature, params, host) {
  203. return mxnet.Metadata.open(host).then((metadata) => {
  204. let parameters = new Map();
  205. if (params) {
  206. try {
  207. const stream = new ndarray.Stream(params);
  208. for (const key of Object.keys(stream.arrays)) {
  209. const name = (key.startsWith('arg:') || key.startsWith('aux:')) ? key.substring(4) : key;
  210. parameters.set(name, stream.arrays[key]);
  211. }
  212. }
  213. catch (error) {
  214. // continue regardless of error
  215. }
  216. }
  217. try {
  218. return new mxnet.Model(metadata, format, manifest, symbol, signature, parameters);
  219. }
  220. catch (error) {
  221. host.exception(error, false);
  222. let message = error && error.message ? error.message : error.toString();
  223. message = message.endsWith('.') ? message.substring(0, message.length - 1) : message;
  224. throw new mxnet.Error(message + " in '" + identifier + "'.");
  225. }
  226. });
  227. }
  228. static _basename(identifier, extension, suffix) {
  229. let dots = identifier.split('.');
  230. if (dots.length >= 2 && dots.pop().toLowerCase() === extension) {
  231. let dashes = dots.join('.').split('-');
  232. if (dashes.length >= 2) {
  233. let token = dashes.pop();
  234. if (suffix) {
  235. if (token != suffix) {
  236. return null;
  237. }
  238. }
  239. else {
  240. for (let i = 0; i < token.length; i++) {
  241. const c = token.charAt(i);
  242. if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) {
  243. continue;
  244. }
  245. return null;
  246. }
  247. }
  248. return dashes.join('-');
  249. }
  250. }
  251. return null;
  252. }
  253. };
  254. mxnet.Model = class {
  255. constructor(metadata, format, manifest, symbol, signature, params) {
  256. if (!symbol && !params) {
  257. throw new mxnet.Error('JSON symbol data not available.');
  258. }
  259. if (symbol) {
  260. if (!Object.prototype.hasOwnProperty.call(symbol, 'nodes')) {
  261. throw new mxnet.Error('JSON file does not contain an MXNet \'nodes\' property.');
  262. }
  263. if (!Object.prototype.hasOwnProperty.call(symbol, 'arg_nodes')) {
  264. throw new mxnet.Error('JSON file does not contain an MXNet \'arg_nodes\' property.');
  265. }
  266. if (!Object.prototype.hasOwnProperty.call(symbol, 'heads')) {
  267. throw new mxnet.Error('JSON file does not contain an MXNet \'heads\' property.');
  268. }
  269. }
  270. if (manifest) {
  271. if (manifest.Model && manifest.Model['Model-Name']) {
  272. this._name = manifest.Model['Model-Name'];
  273. }
  274. if (manifest.Model && manifest.Model.Description && this._name != manifest.Model.Description) {
  275. this._description = manifest.Model.Description;
  276. }
  277. if (manifest.Engine && manifest.Engine.MXNet) {
  278. const engineVersion = mxnet.Model._convert_version(manifest.Engine.MXNet);
  279. this._runtime = 'MXNet v' + (engineVersion ? engineVersion : manifest.Engine.MXNet.toString());
  280. }
  281. if (manifest.License) {
  282. this._license = manifest.License;
  283. }
  284. if (manifest.model && manifest.model.modelName) {
  285. this._name = manifest.model.modelName;
  286. }
  287. if (manifest.model && manifest.model.modelVersion) {
  288. this._version = manifest.model.modelVersion;
  289. }
  290. if (manifest.model && manifest.model.modelName && this._name != manifest.model.description) {
  291. this._description = manifest.model.description;
  292. }
  293. if (manifest.runtime) {
  294. this._runtime = manifest.runtime;
  295. }
  296. if (manifest.engine && manifest.engine.engineName) {
  297. let engine = manifest.engine.engineName;
  298. if (manifest.engine.engineVersion) {
  299. engine = engine + ' ' + manifest.engine.engineVersion;
  300. }
  301. this._runtime = this._runtime ? (this._runtime + ' (' + engine + ')') : engine;
  302. }
  303. if (manifest.publisher && manifest.publisher.author) {
  304. this._author = manifest.publisher.author;
  305. if (manifest.publisher.email) {
  306. this._author = this._author + ' <' + manifest.publisher.email + '>';
  307. }
  308. }
  309. if (manifest.license) {
  310. this._license = manifest.license;
  311. }
  312. }
  313. this._format = format;
  314. if (!this._format && symbol && symbol.attrs && symbol.attrs.mxnet_version) {
  315. const version = mxnet.Model._convert_version(symbol.attrs.mxnet_version);
  316. if (version) {
  317. this._format = 'MXNet v' + version;
  318. }
  319. }
  320. if (!this._format) {
  321. this._format = 'MXNet';
  322. }
  323. this._graphs = [];
  324. this._graphs.push(new mxnet.Graph(metadata, manifest, symbol, signature, params));
  325. }
  326. get format() {
  327. return this._format;
  328. }
  329. get name() {
  330. return this._name;
  331. }
  332. get version() {
  333. return this._version;
  334. }
  335. get description() {
  336. return this._description;
  337. }
  338. get author() {
  339. return this._author;
  340. }
  341. get license() {
  342. return this._license;
  343. }
  344. get runtime() {
  345. return this._runtime;
  346. }
  347. get graphs() {
  348. return this._graphs;
  349. }
  350. static _convert_version(value) {
  351. if (Array.isArray(value)) {
  352. if (value.length == 2 && value[0] == 'int') {
  353. const major = Math.floor(value[1] / 10000) % 100;
  354. const minor = Math.floor(value[1] / 100) % 100;
  355. const patch = Math.floor(value[1]) % 100;
  356. return [ major.toString(), minor.toString(), patch.toString() ].join('.');
  357. }
  358. }
  359. return null;
  360. }
  361. };
  362. mxnet.Graph = class {
  363. constructor(metadata, manifest, symbol, signature, params) {
  364. this._metadata = metadata;
  365. this._nodes = [];
  366. this._inputs = [];
  367. this._outputs = [];
  368. let tensors = new Map();
  369. if (params) {
  370. for (const pair of params) {
  371. const key = pair[0];
  372. const value = pair[1];
  373. tensors.set(key, new mxnet.Tensor('Initializer', key, new mxnet.TensorType(value.dataType, new mxnet.TensorShape(value.shape.dimensions)), value.data));
  374. }
  375. }
  376. if (symbol) {
  377. const nodes = symbol.nodes;
  378. for (const node of nodes) {
  379. if (node.op && node.op != 'null') {
  380. let operator = node.op;
  381. const attrs = node.attrs || node.attr || node.param;
  382. if (operator == 'tvm_op' && attrs && attrs.func_name) {
  383. operator = attrs.func_name;
  384. }
  385. }
  386. }
  387. let inputs = {};
  388. if (signature && signature.inputs) {
  389. for (const input of signature.inputs) {
  390. inputs[input.data_name] = input;
  391. }
  392. }
  393. let outputs = {};
  394. if (signature && signature.outputs) {
  395. for (const output of signature.outputs) {
  396. outputs[output.data_name] = output;
  397. }
  398. }
  399. for (const node of nodes) {
  400. node.outputs = [];
  401. }
  402. for (const node of nodes) {
  403. node.inputs = node.inputs.map((input) => {
  404. return mxnet.Graph._updateOutput(nodes, input);
  405. });
  406. }
  407. let outputCountMap = {};
  408. for (const node of nodes) {
  409. for (const output of node.outputs) {
  410. outputCountMap[output] = (outputCountMap[output] || 0) + 1;
  411. }
  412. }
  413. let argumentMap = {};
  414. for (const index of symbol.arg_nodes) {
  415. argumentMap[index] = (index < nodes.length) ? nodes[index] : null;
  416. }
  417. for (let i = 0; i < symbol.heads.length; i++) {
  418. const head = symbol.heads[i];
  419. const outputId = mxnet.Graph._updateOutput(nodes, head);
  420. const outputName = nodes[outputId[0]] ? nodes[outputId[0]].name : ('output' + ((i == 0) ? '' : (i + 1).toString()));
  421. let outputType = null;
  422. const outputSignature = outputs[outputName];
  423. if (outputSignature && outputSignature.data_shape) {
  424. outputType = new mxnet.TensorType(-1, new mxnet.TensorShape(outputSignature.data_shape));
  425. }
  426. this._outputs.push(new mxnet.Parameter(outputName, [ new mxnet.Argument('[' + outputId.join(',') + ']', outputType, null) ]));
  427. }
  428. let initializerMap = {};
  429. for (const node of nodes.filter((node, index) => !argumentMap[index])) {
  430. this._nodes.push(new mxnet.Node(this._metadata, node, argumentMap, initializerMap, tensors));
  431. }
  432. for (const argumentKey of Object.keys(argumentMap)) {
  433. let argument = argumentMap[argumentKey];
  434. if (argument && (!argument.inputs || argument.inputs.length == 0) && (argument.outputs && argument.outputs.length == 1)) {
  435. const inputId = argument.outputs[0];
  436. const inputName = argument.name;
  437. let inputType = null;
  438. const inputSignature = inputs[inputName];
  439. if (inputSignature && inputSignature.data_shape) {
  440. inputType = new mxnet.TensorType(-1, new mxnet.TensorShape(inputSignature.data_shape));
  441. }
  442. this._inputs.push(new mxnet.Parameter(inputName, [ new mxnet.Argument('[' + inputId.join(',') + ']', inputType) ]));
  443. }
  444. }
  445. }
  446. else if (params) {
  447. let block = null;
  448. let blocks = [];
  449. let separator = Object.keys(params).every((k) => k.indexOf('_') != -1) ? '_' : '';
  450. if (separator.length == 0) {
  451. separator = Object.keys(params).every((k) => k.indexOf('.') != -1) ? '.' : '';
  452. }
  453. if (separator.length > 0) {
  454. let blockMap = {};
  455. for (const id of Object.keys(params)) {
  456. let parts = id.split(separator);
  457. let argumentName = parts.pop();
  458. if (id.endsWith('moving_mean') || id.endsWith('moving_var')) {
  459. argumentName = [ parts.pop(), argumentName ].join(separator);
  460. }
  461. const nodeName = parts.join(separator);
  462. block = blockMap[nodeName];
  463. if (!block) {
  464. block = { name: nodeName, op: 'Weights', params: [] };
  465. blockMap[nodeName] = block;
  466. blocks.push(block)
  467. }
  468. blockMap[nodeName].params.push({ name: argumentName, id: id });
  469. }
  470. }
  471. else {
  472. throw new mxnet.Error("Unsupported key format in params.");
  473. }
  474. for (block of blocks) {
  475. this._nodes.push(new mxnet.Node(metadata, block, {}, {}, params))
  476. }
  477. }
  478. }
  479. get name() {
  480. return '';
  481. }
  482. get inputs() {
  483. return this._inputs;
  484. }
  485. get outputs() {
  486. return this._outputs;
  487. }
  488. get nodes() {
  489. return this._nodes;
  490. }
  491. static _updateOutput(nodes, input) {
  492. const nodeIndex = input[0];
  493. const node = nodes[nodeIndex];
  494. const outputIndex = input[1];
  495. if (node) {
  496. while (outputIndex >= node.outputs.length) {
  497. node.outputs.push([ nodeIndex, node.outputs.length ]);
  498. }
  499. }
  500. return [ nodeIndex, outputIndex ];
  501. }
  502. };
  503. mxnet.Parameter = class {
  504. constructor(name, args) {
  505. this._name = name;
  506. this._arguments = args;
  507. }
  508. get name() {
  509. return this._name;
  510. }
  511. get visible() {
  512. return true;
  513. }
  514. get arguments() {
  515. return this._arguments;
  516. }
  517. };
  518. mxnet.Argument = class {
  519. constructor(id, type, initializer) {
  520. this._id = id;
  521. this._type = type || null;
  522. this._initializer = initializer || null;
  523. }
  524. get id() {
  525. if (this._initializer) {
  526. return this._initializer.name;
  527. }
  528. return this._id;
  529. }
  530. get type() {
  531. if (this._initializer) {
  532. return this._initializer.type;
  533. }
  534. return this._type;
  535. }
  536. get initializer() {
  537. return this._initializer;
  538. }
  539. };
  540. mxnet.Node = class {
  541. constructor(metadata, node, argumentMap, initializerMap, tensors) {
  542. this._metadata = metadata;
  543. this._operator = node.op;
  544. this._name = node.name;
  545. this._attributes = [];
  546. this._inputs = [];
  547. this._outputs = [];
  548. const attrs = node.attrs || node.attr || node.param;
  549. if (attrs) {
  550. if (this._operator == 'tvm_op' && attrs.func_name) {
  551. this._operator = attrs.func_name;
  552. }
  553. for (const attributeName of Object.keys(attrs)) {
  554. if (this._operator != 'tvm_op' && attributeName != 'func_name') {
  555. this._attributes.push(new mxnet.Attribute(this._metadata, this.operator, attributeName, attrs[attributeName]));
  556. }
  557. }
  558. }
  559. let initializer = null;
  560. const schema = metadata.type(this.operator);
  561. if (node.inputs) {
  562. let inputs = node.inputs;
  563. if (this._operator == 'RNN') {
  564. inputs = inputs.map((input) => {
  565. const argumentNodeIndex = input[0];
  566. const argument = argumentMap[argumentNodeIndex];
  567. if (argument && argument.op == 'null' && argument.name &&
  568. argument.name.endsWith('_parameters') && argument.attr && argument.attr.__init__) {
  569. this._attributes.push(new mxnet.Attribute(this._metadata, this.operator, argument.name, argument.attr.__init__));
  570. delete argumentMap[argumentNodeIndex];
  571. return null;
  572. }
  573. return input;
  574. });
  575. inputs = inputs.filter((item) => item != null);
  576. }
  577. let initializers = {};
  578. for (const input of inputs) {
  579. const id = '[' + input.join(',') + ']';
  580. initializer = initializerMap[id];
  581. if (!initializer) {
  582. const argumentNodeIndex = input[0];
  583. const argument = argumentMap[argumentNodeIndex];
  584. if (argument && argument.name &&
  585. (!argument.inputs || argument.inputs.length == 0) &&
  586. (argument.outputs && argument.outputs.length == 1)) {
  587. initializer = tensors.get(argument.name) || null;
  588. if (initializer) {
  589. delete argumentMap[argumentNodeIndex];
  590. }
  591. else {
  592. let prefix = this._name;
  593. if (prefix.endsWith('_fwd')) {
  594. prefix = prefix.slice(0, -3);
  595. }
  596. if (argument.name && (argument.name.startsWith(prefix + '_') || argument.name.startsWith(prefix + '.'))) {
  597. let dataType = -1;
  598. let shape = [];
  599. if (argument.attrs && argument.attrs.__dtype__ && argument.attrs.__shape__) {
  600. try {
  601. dataType = parseInt(argument.attrs.__dtype__);
  602. shape = JSON.parse('[' + argument.attrs.__shape__.replace('(', '').replace(')', '').split(' ').join('').split(',').map((dimension => dimension || '"?"' )).join(',') + ']');
  603. }
  604. catch (err) {
  605. // continue regardless of error
  606. }
  607. }
  608. let argumentType = null;
  609. if (dataType !== -1 || shape.length > 0) {
  610. argumentType = new mxnet.TensorType(dataType, new mxnet.TensorShape(shape));
  611. }
  612. else {
  613. argumentType = new mxnet.TensorType(-1, new mxnet.TensorShape(null));
  614. }
  615. initializer = new mxnet.Tensor('Initializer', argument.name, argumentType, null);
  616. delete argumentMap[argumentNodeIndex];
  617. }
  618. }
  619. }
  620. }
  621. if (initializer) {
  622. initializers[id] = initializer;
  623. initializerMap[id] = initializer;
  624. }
  625. }
  626. let inputIndex = 0;
  627. if (schema && schema.inputs) {
  628. for (const inputDef of schema.inputs) {
  629. if (inputIndex < inputs.length || inputDef.option != 'optional') {
  630. let inputCount = (inputDef.option == 'variadic') ? (inputs.length - inputIndex) : 1;
  631. let inputArguments = [];
  632. for (const input of inputs.slice(inputIndex, inputIndex + inputCount)) {
  633. const inputId = '[' + input.join(',') + ']';
  634. if (inputId != '' || inputDef.option != 'optional') {
  635. inputArguments.push(new mxnet.Argument(inputId, inputDef.type, initializers[inputId]));
  636. }
  637. }
  638. this._inputs.push(new mxnet.Parameter(inputDef.name, inputArguments));
  639. inputIndex += inputCount;
  640. }
  641. }
  642. }
  643. if (inputIndex < inputs.length) {
  644. this._inputs = this._inputs.concat(inputs.slice(inputIndex).map((input, index) => {
  645. const inputId = '[' + input.join(',') + ']';
  646. return new mxnet.Parameter((inputIndex + index).toString(), [
  647. new mxnet.Argument(inputId, null, initializers[inputId])
  648. ]);
  649. }));
  650. }
  651. }
  652. if (node.outputs) {
  653. const outputs = node.outputs;
  654. let outputIndex = 0;
  655. if (schema && schema.outputs) {
  656. for (const outputDef of schema.outputs) {
  657. if (outputIndex < outputs.length || outputDef.option != 'optional') {
  658. let outputArguments = [];
  659. const outputCount = (outputDef.option == 'variadic') ? (outputs.length - outputIndex) : 1;
  660. for (const output of outputs.slice(outputIndex, outputIndex + outputCount)) {
  661. outputArguments.push(new mxnet.Argument('[' + output.join(',') + ']', null, null));
  662. }
  663. this._outputs.push(new mxnet.Parameter(outputDef.name, outputArguments));
  664. outputIndex += outputCount;
  665. }
  666. }
  667. }
  668. if (outputIndex < outputs.length) {
  669. this._outputs = this._outputs.concat(outputs.slice(outputIndex).map((output, index) => {
  670. return new mxnet.Parameter((outputIndex + index).toString(), [
  671. new mxnet.Argument('[' + output.join(',') + ']', null, null)
  672. ]);
  673. }));
  674. }
  675. }
  676. if (node.params) {
  677. for (const param of node.params) {
  678. this._inputs.push(new mxnet.Parameter(param.name, [
  679. new mxnet.Argument(param.id, null, tensors.get(param.id) || null)
  680. ]));
  681. }
  682. }
  683. }
  684. get operator() {
  685. return this._operator;
  686. }
  687. get metadata() {
  688. return this._metadata.type(this._operator);
  689. }
  690. get name() {
  691. return this._name;
  692. }
  693. get inputs() {
  694. return this._inputs;
  695. }
  696. get outputs() {
  697. return this._outputs;
  698. }
  699. get attributes() {
  700. return this._attributes;
  701. }
  702. };
  703. mxnet.Attribute = class {
  704. constructor(metadata, operator, name, value) {
  705. this._name = name;
  706. this._value = value;
  707. let number;
  708. const schema = metadata.attribute(operator, name);
  709. if (schema && schema.type) {
  710. switch (schema.type) {
  711. case 'boolean':
  712. switch (value) {
  713. case 'True':
  714. this._value = true;
  715. break;
  716. case 'False':
  717. this._value = false;
  718. break;
  719. }
  720. break;
  721. case 'int32':
  722. number = Number.parseInt(this._value, 10);
  723. this._value = Number.isNaN(this._value - number) ? value : number;
  724. break;
  725. case 'float32':
  726. case 'float64':
  727. number = Number.parseFloat(this._value);
  728. this._value = Number.isNaN(this._value - number) ? value : number;
  729. break;
  730. case 'int32[]':
  731. if (this._value.length > 2 && this._value.startsWith('(') && this._value.endsWith(')')) {
  732. let array = [];
  733. let items = this._value.substring(1, this._value.length - 1).split(',')
  734. .map((item) => item.trim())
  735. .map((item) => item.endsWith('L') ? item.substring(0, item.length - 1) : item);
  736. for (const item of items) {
  737. number = Number.parseInt(item, 10);
  738. if (Number.isNaN(item - number)) {
  739. array = null;
  740. }
  741. else if (array != null) {
  742. array.push(number);
  743. }
  744. }
  745. if (array != null) {
  746. this._value = array;
  747. }
  748. }
  749. break;
  750. }
  751. }
  752. if (schema) {
  753. if (Object.prototype.hasOwnProperty.call(schema, 'visible') && !schema.visible) {
  754. this._visible = false;
  755. }
  756. else if (Object.prototype.hasOwnProperty.call(schema, 'default')) {
  757. let defaultValue = schema.default;
  758. if (this._value == defaultValue) {
  759. this._visible = false;
  760. }
  761. else if (Array.isArray(this._value) && Array.isArray(defaultValue)) {
  762. defaultValue = defaultValue.slice(0, defaultValue.length);
  763. if (defaultValue.length > 1 && defaultValue[defaultValue.length - 1] == null) {
  764. defaultValue.pop();
  765. while (defaultValue.length < this._value.length) {
  766. defaultValue.push(defaultValue[defaultValue.length - 1]);
  767. }
  768. }
  769. if (this._value.every((item, index) => { return item == defaultValue[index]; })) {
  770. this._visible = false;
  771. }
  772. }
  773. }
  774. }
  775. }
  776. get name() {
  777. return this._name;
  778. }
  779. get type() {
  780. return this._type;
  781. }
  782. get value() {
  783. return this._value;
  784. }
  785. get visible() {
  786. return this._visible == false ? false : true;
  787. }
  788. };
  789. mxnet.Tensor = class {
  790. constructor(kind, name, type, data) {
  791. this._kind = kind;
  792. this._name = name;
  793. this._type = type;
  794. this._data = data;
  795. }
  796. get kind() {
  797. return 'Initializer';
  798. }
  799. get name() {
  800. return this._name;
  801. }
  802. get type() {
  803. return this._type;
  804. }
  805. get state() {
  806. return this._context().state;
  807. }
  808. get value() {
  809. let context = this._context();
  810. if (context.state) {
  811. return null;
  812. }
  813. context.limit = Number.MAX_SAFE_INTEGER;
  814. return this._decode(context, 0);
  815. }
  816. toString() {
  817. let context = this._context();
  818. if (context.state) {
  819. return '';
  820. }
  821. context.limit = 10000;
  822. const value = this._decode(context, 0);
  823. return JSON.stringify(value, null, 4);
  824. }
  825. _context() {
  826. let context = {};
  827. context.state = null;
  828. context.index = 0;
  829. context.count = 0;
  830. if (!this._data) {
  831. context.state = 'Tensor data is empty.';
  832. return context;
  833. }
  834. if (!this._type && this._type.dataType === '?') {
  835. context.state = 'Tensor has no data type.';
  836. return context;
  837. }
  838. if (this._type.shape.length < 1) {
  839. context.state = 'Tensor has unknown shape.';
  840. return context;
  841. }
  842. context.dataType = this._type.dataType;
  843. context.dimensions = this._type.shape.dimensions;
  844. context.data = new DataView(this._data.buffer, this._data.byteOffset, this._data.byteLength);
  845. return context;
  846. }
  847. _decode(context, dimension) {
  848. let results = [];
  849. const size = context.dimensions[dimension];
  850. if (dimension == context.dimensions.length - 1) {
  851. for (let i = 0; i < size; i++) {
  852. if (context.count > context.limit) {
  853. results.push('...');
  854. return results;
  855. }
  856. switch (context.dataType) {
  857. case 'float32':
  858. results.push(context.data.getFloat32(context.index, true));
  859. context.index += 4;
  860. context.count++;
  861. break;
  862. case 'float64':
  863. results.push(context.data.getFloat64(context.index, true));
  864. context.index += 8;
  865. context.count++;
  866. break;
  867. case 'float16':
  868. results.push(mxnet.Tensor._decodeNumberFromFloat16(context.data.getUint16(context.index, true)));
  869. context.index += 2;
  870. context.count++;
  871. break;
  872. case 'uint8':
  873. results.push(context.data.getUint8(context.index, true));
  874. context.index += 1;
  875. context.count++;
  876. break;
  877. case 'int32':
  878. results.push(context.data.getInt32(context.index, true));
  879. context.index += 4;
  880. context.count++;
  881. break;
  882. case 'int8':
  883. results.push(context.data.getInt8(context.index, true));
  884. context.index += 1;
  885. context.count++;
  886. break;
  887. case 'int64':
  888. results.push(new long.Long(context.data.getUint32(context.index, true), context.data.getUint32(context.index + 4, true), false));
  889. context.index += 8;
  890. context.count++;
  891. break;
  892. }
  893. }
  894. }
  895. else {
  896. for (let j = 0; j < size; j++) {
  897. if (context.count > context.limit) {
  898. results.push('...');
  899. return results;
  900. }
  901. results.push(this._decode(context, dimension + 1));
  902. }
  903. }
  904. return results;
  905. }
  906. static _decodeNumberFromFloat16(value) {
  907. const s = (value & 0x8000) >> 15;
  908. const e = (value & 0x7C00) >> 10;
  909. const f = value & 0x03FF;
  910. if(e == 0) {
  911. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  912. }
  913. else if (e == 0x1F) {
  914. return f ? NaN : ((s ? -1 : 1) * Infinity);
  915. }
  916. return (s ? -1 : 1) * Math.pow(2, e-15) * (1 + (f / Math.pow(2, 10)));
  917. }
  918. };
  919. mxnet.TensorType = class {
  920. constructor(dataType, shape) {
  921. switch (dataType) {
  922. case 0: this._dataType = 'float32'; break;
  923. case 1: this._dataType = 'float64'; break;
  924. case 2: this._dataType = 'float16'; break;
  925. case 3: this._dataType = 'uint8'; break;
  926. case 4: this._dataType = 'int32'; break;
  927. case 5: this._dataType = 'int8'; break;
  928. case 6: this._dataType = 'int64'; break;
  929. case -1: this._dataType = '?'; break;
  930. default: throw new mxnet.Error("Unknown type '" + dataType + "'.");
  931. }
  932. this._shape = shape;
  933. }
  934. get dataType() {
  935. return this._dataType;
  936. }
  937. get shape() {
  938. return this._shape;
  939. }
  940. toString() {
  941. return this._dataType + this._shape.toString();
  942. }
  943. };
  944. mxnet.TensorShape = class {
  945. constructor(dimensions) {
  946. this._dimensions = dimensions;
  947. }
  948. get dimensions() {
  949. return this._dimensions;
  950. }
  951. toString() {
  952. if (this._dimensions) {
  953. if (this._dimensions.length == 0) {
  954. return '';
  955. }
  956. return '[' + this._dimensions.map((dimension) => dimension.toString()).join(',') + ']';
  957. }
  958. return '';
  959. }
  960. };
  961. mxnet.Metadata = class {
  962. static open(host) {
  963. if (mxnet.Metadata._metadata) {
  964. return Promise.resolve(mxnet.Metadata._metadata);
  965. }
  966. return host.request(null, 'mxnet-metadata.json', 'utf-8').then((data) => {
  967. mxnet.Metadata._metadata = new mxnet.Metadata(data);
  968. return mxnet.Metadata._metadata;
  969. }).catch(() => {
  970. mxnet.Metadata._metadata = new mxnet.Metadata(null);
  971. return mxnet.Metadata._metadata;
  972. });
  973. }
  974. constructor(data) {
  975. this._map = {};
  976. this._attributeCache = {};
  977. if (data) {
  978. const items = JSON.parse(data);
  979. if (items) {
  980. for (const item of items) {
  981. if (item.name && item.schema) {
  982. item.schema.name = item.name;
  983. this._map[item.name] = item.schema;
  984. }
  985. }
  986. }
  987. }
  988. }
  989. type(operator) {
  990. return this._map[operator] || null;
  991. }
  992. attribute(operator, name) {
  993. let map = this._attributeCache[operator];
  994. if (!map) {
  995. map = {};
  996. const schema = this.type(operator);
  997. if (schema && schema.attributes) {
  998. for (const attribute of schema.attributes) {
  999. map[attribute.name] = attribute;
  1000. }
  1001. }
  1002. this._attributeCache[operator] = map;
  1003. }
  1004. return map[name] || null;
  1005. }
  1006. };
  1007. mxnet.Error = class extends Error {
  1008. constructor(message) {
  1009. super(message);
  1010. this.name = 'Error loading MXNet model.';
  1011. }
  1012. };
  1013. ndarray.Stream = class {
  1014. constructor(buffer) {
  1015. this._arrays = {};
  1016. const reader = new ndarray.Reader(buffer);
  1017. if (!reader.checkSignature([ 0x12, 1, 0, 0, 0, 0, 0, 0 ])) {
  1018. throw new ndarray.Error('Invalid signature.');
  1019. }
  1020. if (!reader.checkSignature([ 0, 0, 0, 0, 0, 0, 0, 0 ])) {
  1021. throw new ndarray.Error('Invalid reserved block.');
  1022. }
  1023. let data = [];
  1024. for (let dataSize = reader.uint64(); dataSize > 0; dataSize--) {
  1025. data.push(new ndarray.Array(reader));
  1026. }
  1027. const decoder = new TextDecoder('ascii');
  1028. let names = [];
  1029. for (let namesSize = reader.uint64(); namesSize > 0; namesSize--) {
  1030. const name = decoder.decode(reader.read(reader.uint64()));
  1031. names.push(name);
  1032. }
  1033. if (names.length != data.length) {
  1034. throw new ndarray.Error('Label count mismatch.');
  1035. }
  1036. for (let i = 0; i < names.length; i++) {
  1037. this._arrays[names[i]] = data[i];
  1038. }
  1039. }
  1040. get arrays() {
  1041. return this._arrays;
  1042. }
  1043. };
  1044. ndarray.Array = class {
  1045. constructor(reader) {
  1046. ndarray.Array._dataTypeSizeTable = [ 4, 8, 2, 1, 4, 1, 8 ];
  1047. if (reader.checkSignature([ 0xc9, 0xfa, 0x93, 0xF9 ])) {
  1048. this._loadV2(reader);
  1049. }
  1050. else if (reader.checkSignature([ 0xc8, 0xfa, 0x93, 0xF9 ])) {
  1051. this._loadV1(reader);
  1052. }
  1053. else {
  1054. this._loadV0(reader);
  1055. }
  1056. }
  1057. _loadV2(reader) {
  1058. const stype = reader.uint32();
  1059. let num_aux_data = 0;
  1060. switch (stype) {
  1061. case 0: num_aux_data = 0; break; // kDefaultStorage
  1062. case 1: num_aux_data = 1; break; // kRowSparseStorage
  1063. case 2: num_aux_data = 2; break; // kCSRStorage
  1064. }
  1065. this.sshape = null;
  1066. if (num_aux_data > 0) {
  1067. this.sshape = new ndarray.Shape(reader, true);
  1068. }
  1069. this._shape = new ndarray.Shape(reader, true);
  1070. if (this._shape.dimensions.length == 0) {
  1071. return;
  1072. }
  1073. this._context = new ndarray.Context(reader);
  1074. this._dataType = reader.uint32();
  1075. if (num_aux_data > 0) {
  1076. throw new ndarray.Error('Not implemented.');
  1077. }
  1078. const dataTypeSize = (this._dataType < ndarray.Array._dataTypeSizeTable.length) ? ndarray.Array._dataTypeSizeTable[this._dataType] : 0;
  1079. const size = dataTypeSize * this._shape.size();
  1080. this._data = reader.read(size);
  1081. }
  1082. _loadV1(reader) {
  1083. this._shape = new ndarray.Shape(reader, true);
  1084. if (this._shape.dimensions.length == 0) {
  1085. return;
  1086. }
  1087. this._context = new ndarray.Context(reader);
  1088. this._dataType = reader.uint32();
  1089. const dataTypeSize = (this._dataType < ndarray.Array._dataTypeSizeTable.length) ? ndarray.Array._dataTypeSizeTable[this._dataType] : 0;
  1090. const size = dataTypeSize * this._shape.size();
  1091. this._data = reader.read(size);
  1092. }
  1093. _loadV0(reader) {
  1094. this._shape = new ndarray.Shape(reader, false);
  1095. this._context = new ndarray.Context(reader);
  1096. this._dataType = reader.uint32();
  1097. const dataTypeSize = (this._dataType < ndarray.Array._dataTypeSizeTable.length) ? ndarray.Array._dataTypeSizeTable[this._dataType] : 0;
  1098. const size = dataTypeSize * this._shape.size();
  1099. this._data = reader.read(size);
  1100. }
  1101. get dataType() {
  1102. return this._dataType;
  1103. }
  1104. get shape() {
  1105. return this._shape;
  1106. }
  1107. get data() {
  1108. return this._data;
  1109. }
  1110. };
  1111. ndarray.Shape = class {
  1112. constructor(reader, uint64) {
  1113. const ndim = reader.uint32();
  1114. this._dimensions = [];
  1115. for (let i = 0; i < ndim; i++) {
  1116. this._dimensions.push(uint64 ? reader.uint64() : reader.uint32());
  1117. }
  1118. }
  1119. get dimensions() {
  1120. return this._dimensions;
  1121. }
  1122. size() {
  1123. let result = 1;
  1124. for (const dimension of this._dimensions) {
  1125. result *= dimension;
  1126. }
  1127. return result;
  1128. }
  1129. };
  1130. ndarray.Context = class {
  1131. constructor(reader) {
  1132. this._deviceType = reader.uint32();
  1133. this._deviceId = reader.uint32();
  1134. }
  1135. };
  1136. ndarray.Reader = class {
  1137. constructor(buffer) {
  1138. this._buffer = buffer;
  1139. this._position = 0;
  1140. this._end = buffer.length;
  1141. }
  1142. checkSignature(signature) {
  1143. if (this._position + signature.length <= this._end) {
  1144. for (let i = 0; i < signature.length; i++) {
  1145. if (this._buffer[this._position + i] != signature[i]) {
  1146. return false;
  1147. }
  1148. }
  1149. }
  1150. this._position += signature.length;
  1151. return true;
  1152. }
  1153. read(size) {
  1154. if (this._position + size > this._end) {
  1155. throw new ndarray.Error('Data not available.');
  1156. }
  1157. const data = this._buffer.subarray(this._position, this._position + size);
  1158. this._position += size;
  1159. return data;
  1160. }
  1161. uint16() {
  1162. if (this._position + 2 > this._end) {
  1163. throw new ndarray.Error('Data not available.');
  1164. }
  1165. const value = this._buffer[this._position] | (this._buffer[this._position + 1] << 8);
  1166. this._position += 2;
  1167. return value;
  1168. }
  1169. uint32() {
  1170. return this.uint16() | (this.uint16() << 16);
  1171. }
  1172. uint64() {
  1173. const value = this.uint32();
  1174. if (this.uint32() != 0) {
  1175. throw new ndarray.Error('Large int64 value.');
  1176. }
  1177. return value;
  1178. }
  1179. };
  1180. ndarray.Error = class extends Error {
  1181. constructor(message) {
  1182. super(message);
  1183. this.name = 'NDArray Error';
  1184. }
  1185. };
  1186. if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  1187. module.exports.ModelFactory = mxnet.ModelFactory;
  1188. }