mxnet.js 44 KB

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