acuity.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  1. const acuity = {};
  2. acuity.ModelFactory = class {
  3. async match(context) {
  4. const obj = await context.peek('json');
  5. if (obj && obj.MetaData && obj.Layers && Object.keys(obj).length < 256) {
  6. return context.set('acuity', obj);
  7. }
  8. return null;
  9. }
  10. async open(context) {
  11. const metadata = await context.metadata('acuity-metadata.json');
  12. return new acuity.Model(metadata, context.value);
  13. }
  14. };
  15. acuity.Model = class {
  16. constructor(metadata, model, data, quantization) {
  17. this.name = model.MetaData.Name;
  18. this.format = `Acuity v${model.MetaData.AcuityVersion}`;
  19. this.runtime = model.MetaData.Platform;
  20. this.modules = [new acuity.Graph(metadata, model, data, quantization)];
  21. }
  22. };
  23. acuity.Graph = class {
  24. constructor(metadata, model) {
  25. this.nodes = [];
  26. this.inputs = [];
  27. this.outputs = [];
  28. this.metrics = [];
  29. const values = new Map();
  30. const value = (name) => {
  31. if (!values.has(name)) {
  32. values.set(name, { name, shape: null });
  33. }
  34. return values.get(name);
  35. };
  36. let totalFlops = 0;
  37. for (const [name, layer] of Object.entries(model.Layers)) {
  38. layer.inputs = layer.inputs.map((input) => {
  39. return value(input);
  40. });
  41. layer.outputs = layer.outputs.map((port) => {
  42. const output = value(`@${name}:${port}`);
  43. let shape = null;
  44. if (layer.op.toLowerCase() === 'input' ||
  45. layer.op.toLowerCase() === 'variable') {
  46. if (Object.prototype.hasOwnProperty.call(layer.parameters, 'shape') && layer.parameters.shape.length > 0) {
  47. shape = layer.parameters.shape;
  48. } else if (Object.prototype.hasOwnProperty.call(layer.parameters, 'size') && Object.prototype.hasOwnProperty.call(layer.parameters, 'channels')) {
  49. const sizes = layer.parameters.size.split(' ');
  50. shape = [0, parseInt(sizes[0], 10), parseInt(sizes[1], 10), layer.parameters.channels];
  51. } else if (Object.prototype.hasOwnProperty.call(layer.parameters, 'is_scalar')) {
  52. shape = [1];
  53. }
  54. if (shape && shape.length === 4 && shape[0] === 0) {
  55. shape[0] = 1;
  56. }
  57. }
  58. output.shape = shape;
  59. return output;
  60. });
  61. // Add other layer types (e.g., pooling, batch norm, etc.) as needed.
  62. if (layer.type === 'Conv2D') {
  63. const { kernelShape, inputShape, outputShape } = layer;
  64. const [kH, kW] = kernelShape;
  65. const [inC] = inputShape;
  66. const [outC, oH, oW] = outputShape;
  67. totalFlops += kH * kW * inC * oH * oW * outC;
  68. } else if (layer.type === 'Dense') {
  69. const { inputSize, outputSize } = layer;
  70. totalFlops += inputSize * outputSize;
  71. }
  72. }
  73. this.metrics.push(new acuity.Argument('flops', totalFlops));
  74. acuity.Inference.infer(model.Layers);
  75. for (const [name, obj] of values) {
  76. const type = new acuity.TensorType(null, new acuity.TensorShape(obj.shape));
  77. const value = new acuity.Value(name, type, null, null);
  78. values.set(name, value);
  79. }
  80. for (const [name, layer] of Object.entries(model.Layers)) {
  81. switch (layer.op.toLowerCase()) {
  82. case 'input': {
  83. const value = values.get(layer.outputs[0].name);
  84. const argument = new acuity.Argument(name, [value]);
  85. this.inputs.push(argument);
  86. break;
  87. }
  88. case 'output': {
  89. const value = values.get(layer.inputs[0].name);
  90. const argument = new acuity.Argument(name, [value]);
  91. this.outputs.push(argument);
  92. break;
  93. }
  94. default: {
  95. const node = new acuity.Node(metadata, name, layer, values);
  96. this.nodes.push(node);
  97. break;
  98. }
  99. }
  100. }
  101. }
  102. };
  103. acuity.Node = class {
  104. constructor(metadata, name, layer, values) {
  105. const op = layer.op;
  106. this.name = name;
  107. this.type = metadata.type(op) || { name: op };
  108. this.inputs = [];
  109. this.outputs = [];
  110. this.attributes = [];
  111. if (this.type) {
  112. if (layer.parameters) {
  113. for (const [name, value] of Object.entries(layer.parameters)) {
  114. const meta = metadata.attribute(op, name);
  115. const type = meta && meta.type ? meta.type : null;
  116. const visible = meta && meta.default !== undefined && meta.default === value ? false : true;
  117. const attribute = new acuity.Argument(name, value, type, visible);
  118. this.attributes.push(attribute);
  119. }
  120. }
  121. }
  122. for (let i = 0; i < layer.inputs.length; i++) {
  123. const input = layer.inputs[i];
  124. const value = values.get(input.name);
  125. const name = this.type && this.type.inputs && i < this.type.inputs.length ? this.type.inputs[i].name : `input${i}`;
  126. const argument = new acuity.Argument(name, [value]);
  127. this.inputs.push(argument);
  128. }
  129. if (this.type && this.type.constants) {
  130. for (const constant of this.type.constants) {
  131. // const name = "@" + this.name + ":" + constant.name;
  132. const type = new acuity.TensorType(null, new acuity.TensorShape(null));
  133. const value = new acuity.Value('', type, null, new acuity.Tensor(type));
  134. const argument = new acuity.Argument(constant.name, [value]);
  135. this.inputs.push(argument);
  136. }
  137. }
  138. for (let i = 0; i < layer.outputs.length; i++) {
  139. const output = layer.outputs[i];
  140. const value = values.get(output.name);
  141. const name = this.type && this.type.outputs && i < this.type.outputs.length ? this.type.outputs[i].name : `output${i}`;
  142. const argument = new acuity.Argument(name, [value]);
  143. this.outputs.push(argument);
  144. }
  145. }
  146. };
  147. acuity.Argument = class {
  148. constructor(name, value, type = null, visible = true) {
  149. this.name = name;
  150. this.value = value;
  151. this.type = type;
  152. this.visible = visible;
  153. }
  154. };
  155. acuity.Value = class {
  156. constructor(name, type = null, quantization = null, initializer = null) {
  157. if (typeof name !== 'string') {
  158. throw new acuity.Error(`Invalid value identifier '${JSON.stringify(name)}'.`);
  159. }
  160. this.name = name;
  161. this.type = type;
  162. this.quantization = quantization;
  163. this.initializer = initializer;
  164. }
  165. };
  166. acuity.TensorType = class {
  167. constructor(dataType, shape) {
  168. this.dataType = dataType || '?';
  169. this.shape = shape;
  170. }
  171. toString() {
  172. return (this.dataType || '?') + this.shape.toString();
  173. }
  174. };
  175. acuity.TensorShape = class {
  176. constructor(dimensions) {
  177. this.dimensions = Array.isArray(dimensions) && dimensions.length === 1 && dimensions[0] === 0 ? [] : dimensions;
  178. }
  179. toString() {
  180. if (!Array.isArray(this.dimensions) || this.dimensions.length === 0 || (this.dimensions.length === 1 && this.dimensions[0] === 0)) {
  181. return '';
  182. }
  183. return `[${this.dimensions.map((dimension) => dimension ? dimension.toString() : '?').join(',')}]`;
  184. }
  185. };
  186. acuity.Tensor = class {
  187. constructor(type) {
  188. this.type = type;
  189. this.Category = 'Constant';
  190. }
  191. };
  192. acuity.Inference = class {
  193. static infer(layers) {
  194. const outputs = new Map();
  195. const outputLayers = [];
  196. for (const [, layer] of Object.entries(layers)) {
  197. if (layer.op.toLowerCase() === 'output') {
  198. outputLayers.push(layer);
  199. }
  200. for (const output of layer.outputs) {
  201. outputs.set(output.name, layer);
  202. }
  203. }
  204. const broadcasts = new Set([
  205. 'add', 'equal', 'fllor_mod', 'floor_div', 'greater', 'greater_equal', 'less', 'less_equal',
  206. 'logical_and', 'logical_or', 'minimum', 'multiply', 'not_equal', 'pow', 'real_div',
  207. 'squared_difference', 'subtract', 'divide', 'addn', 'Divide', 'bitwise_and', 'bitwise_or',
  208. 'bitwise_xor', 'average', 'logical_not', 'logical_xor'
  209. ]);
  210. const passthroughs = new Set([
  211. 'LocalResponseNormalization', 'a_times_b_plus_c', 'abs', 'batchnorm_single', 'batchnormalize',
  212. 'cast', 'cast', 'clipbyvalue', 'dequantize', 'dtype_converter', 'elu', 'exp', 'floor',
  213. 'groupnormalize', 'hard_sigmoid', 'hard_swish', 'instancenormalize', 'l2normalize', 'l2normalizescale',
  214. 'layernormalize', 'leakyrelu', 'log', 'log_softmax', 'mish', 'neg', 'norm_with_channel_mean',
  215. 'norm_with_min_max', 'norm_with_scale', 'pow', 'prelu', 'quantize', 'relu', 'relu_keras',
  216. 'relun', 'reverse', 'round', 'rsqrt', 'sigmoid', 'sin', 'softmax', 'softrelu', 'sqrt', 'square', 'tanh',
  217. 'swish', 'gelu', 'dropout', 'eltwise', 'cos', 'l1_layernormalize', 'inverse_sigmoid', 'selu', 'mod',
  218. 'mish', 'minimum_with_clip', 'celu', 'cumsum', 'dft', 'dropout2', 'erf', 'noop', 'squashing', 'tan', 'ceil',
  219. 'atan', 'atan2', 'atanh', 'alpha_dropout', 'acosh', 'rmsnormalize', 'sign'
  220. ]);
  221. const reduces = new Set([
  222. 'reduceany', 'reducemax', 'reducemean', 'reducemin', 'reduceprod', 'reducesum'
  223. ]);
  224. const poolings = new Set([
  225. 'pooling', 'l2pooling'
  226. ]);
  227. const operators = new Map();
  228. operators.set('broadcast', ([a, b]) => {
  229. const longer = a.length >= b.length ? a.slice() : b.slice();
  230. const shorter = a.length < b.length ? a.slice() : b.slice();
  231. const remain = longer.length - shorter.length;
  232. for (let i = 0; i < remain; i++) {
  233. shorter.splice(0, 0, 1);
  234. }
  235. for (let i = 0; i < longer.length; i++) {
  236. longer[i] = longer[i] > shorter[i] ? longer[i] : shorter[i];
  237. }
  238. return [longer];
  239. });
  240. operators.set('concat', (inputs, params) => {
  241. const outputShape = inputs[0].slice();
  242. outputShape[params.dim] = 0;
  243. for (const shape of inputs) {
  244. outputShape[params.dim] += shape[params.dim];
  245. }
  246. return [outputShape];
  247. });
  248. operators.set('conv1d', (inputs, params) => {
  249. if (params.padding === 'VALID') {
  250. const out_h = ~~((inputs[0][1] + params.stride - params.ksize) / params.stride);
  251. return [[inputs[0][0], out_h, params.weights]];
  252. } else if (params.padding === 'SAME') {
  253. const out_h = ~~((inputs[0][1] + params.stride - 1) / params.stride);
  254. return [[inputs[0][0], out_h, params.weights]];
  255. }
  256. return null;
  257. });
  258. operators.set('convolution', (inputs, params) => {
  259. if (params.padding === 'VALID') {
  260. const out_h = Math.floor((inputs[0][1] + params.stride_h + 2 * params.pad_h - params.ksize_h) / params.stride_h);
  261. const out_w = Math.floor((inputs[0][2] + params.stride_w + 2 * params.pad_w - params.ksize_w) / params.stride_w);
  262. return [[inputs[0][0], out_h, out_w, params.weights]];
  263. } else if (params.padding === 'SAME') {
  264. const out_h = Math.floor((inputs[0][1] + params.stride_h - 1) / params.stride_h);
  265. const out_w = Math.floor((inputs[0][2] + params.stride_w - 1) / params.stride_w);
  266. return [[inputs[0][0], out_h, out_w, params.weights]];
  267. }
  268. return null;
  269. });
  270. operators.set('depthwise_conv1d', (inputs, params) => {
  271. if (params.padding === 'VALID') {
  272. const out_h = ~~((inputs[0][1] + params.stride + params.pad[0] + params.pad[1] - params.ksize) / params.stride);
  273. return [[inputs[0][0], out_h, inputs[0][2] * params.multiplier]];
  274. } else if (params.padding === 'SAME') {
  275. const out_h = ~~((inputs[0][1] + params.stride - 1) / params.stride);
  276. return [[inputs[0][0], out_h, inputs[0][2] * params.multiplier]];
  277. }
  278. return null;
  279. });
  280. operators.set('depthwise_convolution', (inputs, params) => {
  281. if (params.padding === 'VALID') {
  282. const out_h = ~~((inputs[0][1] + params.stride_h + params.pad[0] + params.pad[1] - params.ksize_h) / params.stride_h);
  283. const out_w = ~~((inputs[0][2] + params.stride_w + params.pad[2] + params.pad[3] - params.ksize_w) / params.stride_w);
  284. return [[inputs[0][0], out_h, out_w, inputs[0][3] * params.multiplier]];
  285. } else if (params.padding === 'SAME') {
  286. const out_h = ~~((inputs[0][1] + params.stride_h - 1) / params.stride_h);
  287. const out_w = ~~((inputs[0][2] + params.stride_w - 1) / params.stride_w);
  288. return [[inputs[0][0], out_h, out_w, inputs[0][3] * params.multiplier]];
  289. }
  290. return null;
  291. });
  292. operators.set('deconvolution', (inputs, params) => {
  293. return [params.output_shape.map((item, index) => item === 0 ? inputs[0][index] : item)];
  294. });
  295. operators.set('deconvolution1d', (inputs, params) => {
  296. return [params.output_shape.map((item, index) => item === 0 ? inputs[0][index] : item)];
  297. });
  298. operators.set('fullconnect', (inputs, params) => {
  299. return [inputs[0].slice(0, params.axis).concat([params.weights])];
  300. });
  301. operators.set('gather', (inputs, params) => {
  302. const prefix = inputs[1].slice();
  303. const suffix = inputs[0].slice(params.axis + 1);
  304. return [prefix.concat(suffix)];
  305. });
  306. operators.set('lstm', (inputs, params) => {
  307. const [input] = inputs;
  308. const [a, b] = input;
  309. let batch = a;
  310. const output = params.num_proj === null ? params.weights : params.num_proj;
  311. if (params.time_major) {
  312. batch = b;
  313. }
  314. const newShape = params.return_sequences ? [a, b, output] : [batch, output];
  315. return [newShape, [batch, output], [batch, params.weights]];
  316. });
  317. operators.set('matmul', ([a, b], params) => {
  318. let newShape = a.slice(0, -2);
  319. if (params.transpose_a) {
  320. newShape = newShape.concat(a.slice(-1));
  321. } else {
  322. newShape = newShape.concat(a.slice(-2, -1));
  323. }
  324. if (params.transpose_b) {
  325. newShape = newShape.concat(b.slice(-2, -1));
  326. } else {
  327. newShape = newShape.concat(b.slice(-1));
  328. }
  329. return [newShape];
  330. });
  331. operators.set('pad', (inputs, params) => {
  332. return [inputs[0].map((item, index) => item + params.padding_value[index][0] + params.padding_value[index][1])];
  333. });
  334. operators.set('permute', (inputs, params) => {
  335. return [inputs[0].map((item, index) => inputs[0][params.perm[index]])];
  336. });
  337. operators.set('pooling', (inputs, params) => {
  338. if (params.padding === 'VALID') {
  339. const out_h = ~~((inputs[0][1] + params.stride_h - params.ksize_h) / params.stride_h);
  340. const out_w = ~~((inputs[0][2] + params.stride_w - params.ksize_w) / params.stride_w);
  341. return [[inputs[0][0], out_h, out_w, inputs[0][3]]];
  342. } else if (params.padding === 'SAME') {
  343. const out_h = ~~((inputs[0][1] + params.stride_h - 1) / params.stride_h);
  344. const out_w = ~~((inputs[0][2] + params.stride_w - 1) / params.stride_w);
  345. return [[inputs[0][0], out_h, out_w, inputs[0][3]]];
  346. }
  347. return null;
  348. });
  349. operators.set('reduce', (inputs, params) => {
  350. const newShape = inputs[0].slice();
  351. const axis_list = params.axis_list.map((item) => {
  352. return item < 0 ? newShape.length + item : item;
  353. });
  354. axis_list.sort((a, b) => {
  355. return b - a;
  356. });
  357. axis_list.forEach((i) => {
  358. newShape[i] = 1;
  359. });
  360. if (!params.keep_dims) {
  361. axis_list.forEach((i) => {
  362. newShape.splice(i, 1);
  363. });
  364. if (!newShape.length) {
  365. newShape.splice(0, 0, 0);
  366. }
  367. }
  368. return [newShape];
  369. });
  370. operators.set('repeat', (inputs, params) => {
  371. const newShape = inputs[0].slice();
  372. newShape[params.axis] = params.maxlen;
  373. return [newShape];
  374. });
  375. operators.set('reshape', (inputs, params) => {
  376. const negativeIndexs = [];
  377. let shape = params.shape;
  378. if (typeof params.shape === 'string') {
  379. shape = params.shape.split(/\s+/).map((item) => {
  380. return parseInt(item, 10);
  381. });
  382. }
  383. const newShape = shape.map((item, index) => {
  384. if (item === 0) {
  385. return inputs[0][index];
  386. }
  387. if (item === -1) {
  388. negativeIndexs.push(index);
  389. return 1;
  390. }
  391. return item;
  392. });
  393. if (negativeIndexs.length > 0) {
  394. newShape[negativeIndexs[0]] = inputs[0].reduce((a, c) => a * c) / newShape.reduce((a, c) => a * c);
  395. }
  396. return [newShape];
  397. });
  398. operators.set('sequence_mask', (inputs, params) => {
  399. return [inputs[0].slice().concat([params.maxlen])];
  400. });
  401. operators.set('slice', (inputs, params) => {
  402. return [params.size.map((item, index) => item === -1 ? inputs[0][index] : item)];
  403. });
  404. operators.set('squeeze', (inputs, params) => {
  405. const newShape = inputs[0].slice();
  406. const axis_list = [...new Set(params.axis_list)].sort((a, b) => b - a);
  407. for (const item of axis_list) {
  408. newShape.splice(item, 1);
  409. }
  410. return [newShape];
  411. });
  412. operators.set('space2depth', (inputs, params) => {
  413. const h = inputs[0][1] / params.block_size[0];
  414. const w = inputs[0][2] / params.block_size[1];
  415. const c = inputs[0][3] * params.block_size[1] * params.block_size[1];
  416. return [[inputs[0][0], h, w, c]];
  417. });
  418. operators.set('depth2space', (inputs, params) => {
  419. const h = inputs[0][1] * params.block_size;
  420. const w = inputs[0][2] * params.block_size;
  421. const c = inputs[0][3] / (params.block_size * params.block_size);
  422. return [[inputs[0][0], h, w, c]];
  423. });
  424. operators.set('upsampling', (inputs, params) => {
  425. const h = inputs[0][1] * params.factor;
  426. const w = inputs[0][2] * params.factor;
  427. return [[inputs[0][0], h, w, inputs[0][3]]];
  428. });
  429. operators.set('crop_image', (inputs, params) => {
  430. return [[inputs[0][0], params.crop_size[0], params.crop_size[1], inputs[0][3]]];
  431. });
  432. operators.set('split', (inputs, params) => {
  433. const sizes = [];
  434. const slices = params.slices.slice();
  435. slices.splice(0, 0, 0);
  436. slices.push(inputs[0][params.dim]);
  437. slices.reduce((a, b) => {
  438. sizes.push(b - a);
  439. return b;
  440. });
  441. return sizes.map((item) => {
  442. const shape = inputs[0].slice();
  443. shape[params.dim] = item;
  444. return shape;
  445. });
  446. });
  447. operators.set('stack', (inputs, params) => {
  448. const newShape = inputs[0].slice();
  449. if (newShape.length === 1 && newShape[0] === 0) {
  450. newShape[0] = 1;
  451. } else {
  452. newShape.splice(params.axis, 0, inputs.length);
  453. }
  454. return [newShape];
  455. });
  456. operators.set('stridedslice', (inputs, params) => {
  457. const input_shape = inputs[0].slice();
  458. const begin = params.slice_begin.slice();
  459. const end = params.slice_end.slice();
  460. if (params.slice_begin_mask > 0) {
  461. for (let i = 0; i < begin.length; i++) {
  462. if ((params.slice_begin_mask >>> i) & 0x1) {
  463. begin[i] = -1;
  464. }
  465. }
  466. }
  467. if (params.slice_end_mask > 0) {
  468. for (let i = 0; i < end.length; i++) {
  469. if ((params.slice_end_mask >>> i) & 0x1) {
  470. end[i] = -1;
  471. }
  472. }
  473. }
  474. for (let i = 0; i < begin.length; i++) {
  475. if (begin[i] === -1) {
  476. begin[i] = 0;
  477. }
  478. }
  479. if (inputs[0].length === end.length) {
  480. for (let i = 0; i < end.length; i++) {
  481. if (end[i] === -1 || end[i] > input_shape[i]) {
  482. end[i] = input_shape[i];
  483. }
  484. }
  485. } else if (inputs[0].length < end.length) {
  486. if (params.slice_new_axis_mask) {
  487. const len = (params.slice_new_axis_mask >>> 0).toString(2).length;
  488. for (let i = 0; i < len; i++) {
  489. if ((params.slice_new_axis_mask >>> i) & 0x1) {
  490. input_shape.splice(i, 0, 1);
  491. }
  492. }
  493. for (let i = 0; i < end.length; i++) {
  494. if (end[i] === -1) {
  495. end[i] = input_shape[i];
  496. }
  497. }
  498. }
  499. }
  500. let newShape = [];
  501. for (let i = 0; i < begin.length; i++) {
  502. newShape = newShape.concat([(end[i] - begin[i]) / params.slice_strides[i]]);
  503. }
  504. if (params.slice_shrink_axis_mask) {
  505. const len = (params.slice_shrink_axis_mask >>> 0).toString(2).length;
  506. for (let i = 0; i < len; i++) {
  507. if ((params.slice_shrink_axis_mask >>> i) & 0x1) {
  508. newShape.splice(i, 1);
  509. }
  510. }
  511. }
  512. if (params.slice_new_axis_mask) {
  513. const len = (params.slice_new_axis_mask >>> 0).toString(2).length;
  514. for (let i = 0; i < len; i++) {
  515. if ((params.slice_new_axis_mask >>> i) & 0x1) {
  516. if (inputs[0].length === begin.length) {
  517. newShape.splice(i, 0, 1);
  518. } else if (inputs[0].length < begin.length) {
  519. newShape[i] = 1;
  520. }
  521. }
  522. }
  523. }
  524. return [newShape];
  525. });
  526. operators.set('image_resize', (inputs, params) => {
  527. const newShape = inputs[0].slice();
  528. /* eslint-disable prefer-destructuring */
  529. newShape[1] = params.new_size[0];
  530. newShape[2] = params.new_size[1];
  531. /* eslint-enable prefer-destructuring */
  532. return [newShape];
  533. });
  534. operators.set('argmax', (inputs, params) => {
  535. const newShape = inputs[0].slice();
  536. if (params.keepdims) {
  537. newShape[params.axis] = 1;
  538. } else {
  539. newShape.splice(params.axis, 1);
  540. if (!newShape.length) {
  541. newShape.splice(0, 0, 0);
  542. }
  543. }
  544. return [newShape];
  545. });
  546. operators.set('argmin', operators.get('argmax'));
  547. /* eslint-disable no-unused-vars */
  548. operators.set('shapelayer', (inputs, params) => {
  549. return [[inputs[0].length]];
  550. });
  551. operators.set('capsule_norm', (inputs, params) => {
  552. return [[inputs[0][0], inputs[0][inputs[0].length - 1]]];
  553. });
  554. operators.set('size', (inputs, params) => {
  555. return [[1]];
  556. });
  557. /* eslint-enable no-unused-vars */
  558. operators.set('einsum', ((operators, inputs, params) => {
  559. const identifyOperation = (inputs, equation) => {
  560. const identifyFuncs = new Map();
  561. identifyFuncs.set('matmul', (inputs, equation) => {
  562. if (inputs.length !== 2) {
  563. return { found: false };
  564. }
  565. const parts = equation.replace(/\s+/g, '').split(/,|->/);
  566. if (parts.length !== 3) {
  567. return { found: false };
  568. }
  569. const [first, second, output] = parts.map((p) => p.split(''));
  570. if (!(first.length === output.length || second.length === output.length)) {
  571. return { found: false };
  572. }
  573. let a = first.slice(-2);
  574. const b = second.slice(-2);
  575. const c = output.slice(-2);
  576. let transpose_a = false;
  577. let transpose_b = false;
  578. if (a[0] === c[0]) {
  579. transpose_a = false;
  580. } else if (a[1] === c[0]) {
  581. transpose_a = true;
  582. a = [].concat(a.reverse());
  583. } else {
  584. return { found: false };
  585. }
  586. if (a[1] === b[0]) {
  587. transpose_b = false;
  588. } else if (a[1] === b[1]) {
  589. transpose_b = true;
  590. } else {
  591. return { found: false };
  592. }
  593. return { found: true, op: 'matmul', params: { transpose_a, transpose_b } };
  594. });
  595. /* eslint-disable no-unused-vars */
  596. for (const [name, func] of identifyFuncs.entries()) {
  597. const result = func(inputs, equation);
  598. if (result.found) {
  599. return result;
  600. }
  601. }
  602. /* eslint-enable no-unused-vars */
  603. return { found: false };
  604. };
  605. const result = identifyOperation(inputs, params.equation);
  606. if (result.found) {
  607. if (operators.has(result.op)) {
  608. return operators.get(result.op)(inputs, result.params);
  609. }
  610. }
  611. return [];
  612. }).bind(undefined, operators));
  613. const infer = (output) => {
  614. if (outputs.has(output.name)) {
  615. let ready = true;
  616. const layer = outputs.get(output.name);
  617. for (const input of layer.inputs) {
  618. if (input.shape === null) {
  619. infer(input);
  620. if (input.shape === null) {
  621. ready = false;
  622. break;
  623. }
  624. }
  625. }
  626. if (ready) {
  627. let callback = null;
  628. if (operators.has(layer.op)) {
  629. callback = operators.get(layer.op);
  630. } else if (passthroughs.has(layer.op)) {
  631. callback = (inputs) => [inputs[0].slice()];
  632. } else if (broadcasts.has(layer.op)) {
  633. callback = operators.get('broadcast');
  634. } else if (reduces.has(layer.op)) {
  635. callback = operators.get('reduce');
  636. } else if (poolings.has(layer.op)) {
  637. callback = operators.get('pooling');
  638. }
  639. if (!callback) {
  640. callback = () => [];
  641. }
  642. const parameters = layer.parameters;
  643. const inputs = layer.inputs.map((input) => input.shape);
  644. const outputs = callback(inputs, parameters);
  645. for (let i = 0; i < outputs.length; i++) {
  646. if (i < layer.outputs.length) {
  647. layer.outputs[i].shape = outputs[i];
  648. }
  649. }
  650. }
  651. }
  652. };
  653. for (const layer of outputLayers) {
  654. for (const output of layer.outputs) {
  655. infer(output);
  656. }
  657. }
  658. }
  659. };
  660. acuity.Error = class extends Error {
  661. constructor(message) {
  662. super(message);
  663. this.name = 'Error loading Acuity model.';
  664. }
  665. };
  666. export const ModelFactory = acuity.ModelFactory;