mxnet.js 46 KB

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