dnn.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. /* jshint esversion: 6 */
  2. // Experimental
  3. var dnn = dnn || {};
  4. dnn.ModelFactory = class {
  5. match(context) {
  6. const extension = context.identifier.split('.').pop().toLowerCase();
  7. if (extension == 'dnn') {
  8. const tags = context.tags('pb');
  9. if (tags.get(4) == 0 && tags.get(10) == 2) {
  10. return true;
  11. }
  12. }
  13. return false;
  14. }
  15. open(context, host) {
  16. return host.require('./dnn-proto').then(() => {
  17. let model = null;
  18. const identifier = context.identifier;
  19. try {
  20. dnn.proto = protobuf.get('dnn').dnn;
  21. const reader = protobuf.Reader.create(context.buffer);
  22. model = dnn.proto.Model.decode(reader);
  23. }
  24. catch (error) {
  25. throw new dnn.Error("File format is not dnn.Graph (" + error.message + ") in '" + identifier + "'.");
  26. }
  27. return dnn.Metadata.open(host).then((metadata) => {
  28. try {
  29. return new dnn.Model(metadata, model);
  30. }
  31. catch (error) {
  32. host.exception(error, false);
  33. const message = error && error.message ? error.message : error.toString();
  34. throw new dnn.Error(message.replace(/\.$/, '') + " in '" + identifier + "'.");
  35. }
  36. });
  37. });
  38. }
  39. };
  40. dnn.Model = class {
  41. constructor(metadata, model) {
  42. this._name = model.name || '';
  43. this._format = 'SnapML' + (model.version ? ' v' + model.version.toString() : '');
  44. this._graphs = [ new dnn.Graph(metadata, model) ];
  45. }
  46. get format() {
  47. return this._format;
  48. }
  49. get name() {
  50. return this._name;
  51. }
  52. get graphs() {
  53. return this._graphs;
  54. }
  55. };
  56. dnn.Graph = class {
  57. constructor(metadata, model) {
  58. this._inputs = [];
  59. this._outputs = [];
  60. this._nodes = [];
  61. const scope = {};
  62. let index = 0;
  63. for (const node of model.node) {
  64. node.input = node.input.map((input) => scope[input] ? scope[input] : input);
  65. node.output = node.output.map((output) => {
  66. scope[output] = scope[output] ? output + '\n' + index.toString() : output; // custom argument id
  67. return scope[output];
  68. });
  69. index++;
  70. }
  71. const args = new Map();
  72. const arg = (name, type) => {
  73. if (!args.has(name)) {
  74. args.set(name, new dnn.Argument(name, type));
  75. }
  76. return args.get(name);
  77. };
  78. for (const input of model.input) {
  79. const shape = input.shape;
  80. const type = new dnn.TensorType('float32', new dnn.TensorShape([ shape.dim0, shape.dim1, shape.dim2, shape.dim3 ]));
  81. this._inputs.push(new dnn.Parameter(input.name, [ arg(input.name, type) ]));
  82. }
  83. for (const output of model.output) {
  84. const shape = output.shape;
  85. const type = new dnn.TensorType('float32', new dnn.TensorShape([ shape.dim0, shape.dim1, shape.dim2, shape.dim3 ]));
  86. this._outputs.push(new dnn.Parameter(output.name, [ arg(output.name, type) ]));
  87. }
  88. if (this._inputs.length === 0 && model.input_name && model.input_shape && model.input_shape.length === model.input_name.length * 4) {
  89. for (let i = 0; i < model.input_name.length; i++) {
  90. const name = model.input_name[i];
  91. const shape = model.input_shape.slice(i * 4, (i * 4 + 4));
  92. const type = new dnn.TensorType('float32', new dnn.TensorShape([ shape[1], shape[3], shape[2], shape[0] ]));
  93. this._inputs.push(new dnn.Parameter(name, [ arg(name, type) ]));
  94. }
  95. }
  96. if (this._inputs.length === 0 && model.input_shape && model.input_shape.length === 4 &&
  97. model.node.length > 0 && model.node[0].input.length > 0) {
  98. const name = model.node[0].input[0];
  99. const shape = model.input_shape;
  100. const type = new dnn.TensorType('float32', new dnn.TensorShape([ shape[1], shape[3], shape[2], shape[0] ]));
  101. this._inputs.push(new dnn.Parameter(name, [ arg(name, type) ]));
  102. }
  103. for (const node of model.node) {
  104. this._nodes.push(new dnn.Node(metadata, node, arg));
  105. }
  106. }
  107. get inputs() {
  108. return this._inputs;
  109. }
  110. get outputs() {
  111. return this._outputs;
  112. }
  113. get nodes() {
  114. return this._nodes;
  115. }
  116. };
  117. dnn.Parameter = class {
  118. constructor(name, args) {
  119. this._name = name;
  120. this._arguments = args;
  121. }
  122. get name() {
  123. return this._name;
  124. }
  125. get visible() {
  126. return true;
  127. }
  128. get arguments() {
  129. return this._arguments;
  130. }
  131. };
  132. dnn.Argument = class {
  133. constructor(name, type, initializer, quantization) {
  134. if (typeof name !== 'string') {
  135. throw new dnn.Error("Invalid argument identifier '" + JSON.stringify(name) + "'.");
  136. }
  137. this._name = name;
  138. this._type = type || null;
  139. this._initializer = initializer || null;
  140. this._quantization = quantization || null;
  141. }
  142. get name() {
  143. return this._name;
  144. }
  145. get type() {
  146. return this._type;
  147. }
  148. get quantization() {
  149. if (this._quantization) {
  150. return this._quantization.map((value, index) => index.toString() + ' = ' + value.toString()).join('; ');
  151. }
  152. return null;
  153. }
  154. get initializer() {
  155. return this._initializer;
  156. }
  157. };
  158. dnn.Node = class {
  159. constructor(metadata, node, arg) {
  160. const layer = node.layer;
  161. this._name = layer.name;
  162. this._type = layer.type;
  163. this._metadata = metadata.type(this._type);
  164. this._attributes = [];
  165. this._inputs = [];
  166. this._outputs = [];
  167. const inputs = node.input.map((input) => { return arg(input); });
  168. for (const weight of layer.weight) {
  169. let quantization = null;
  170. if (layer.is_quantized && weight === layer.weight[0] && layer.quantization && layer.quantization.data) {
  171. const data = layer.quantization.data;
  172. quantization = new Array(data.length >> 2);
  173. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  174. for (let i = 0; i < quantization.length; i++) {
  175. quantization[i] = view.getFloat32(i << 2, true);
  176. }
  177. }
  178. const initializer = new dnn.Tensor(weight, quantization);
  179. inputs.push(new dnn.Argument('', initializer.type, initializer, quantization));
  180. }
  181. const outputs = node.output.map((output) => { return arg(output); });
  182. const schema = this._metadata;
  183. if (inputs && inputs.length > 0) {
  184. let inputIndex = 0;
  185. if (schema && schema.inputs) {
  186. for (const inputSchema of schema.inputs) {
  187. if (inputIndex < inputs.length || inputSchema.option != 'optional') {
  188. const inputCount = (inputSchema.option == 'variadic') ? (node.input.length - inputIndex) : 1;
  189. const inputArguments = inputs.slice(inputIndex, inputIndex + inputCount);
  190. this._inputs.push(new dnn.Parameter(inputSchema.name, inputArguments));
  191. inputIndex += inputCount;
  192. }
  193. }
  194. }
  195. this._inputs.push(...inputs.slice(inputIndex).map((input, index) => {
  196. const inputName = ((inputIndex + index) == 0) ? 'input' : (inputIndex + index).toString();
  197. return new dnn.Parameter(inputName, [ input ]);
  198. }));
  199. }
  200. if (outputs.length > 0) {
  201. this._outputs = outputs.map((output, index) => {
  202. const inputName = (index == 0) ? 'output' : index.toString();
  203. return new dnn.Parameter(inputName, [ output ]);
  204. });
  205. }
  206. for (const key of Object.keys(layer)) {
  207. switch (key) {
  208. case 'name':
  209. case 'type':
  210. case 'weight':
  211. case 'is_quantized':
  212. case 'quantization':
  213. break;
  214. default:
  215. this._attributes.push(new dnn.Attribute(metadata.attribute(this._type, key), key, layer[key]));
  216. break;
  217. }
  218. }
  219. }
  220. get name() {
  221. return this._name;
  222. }
  223. get type() {
  224. return this._type;
  225. }
  226. get metadata() {
  227. return this._metadata;
  228. }
  229. get inputs() {
  230. return this._inputs;
  231. }
  232. get outputs() {
  233. return this._outputs;
  234. }
  235. get attributes() {
  236. return this._attributes;
  237. }
  238. };
  239. dnn.Attribute = class {
  240. constructor(metadata, name, value) {
  241. this._name = name;
  242. this._value = value;
  243. }
  244. get name() {
  245. return this._name;
  246. }
  247. get value() {
  248. return this._value;
  249. }
  250. };
  251. dnn.Tensor = class {
  252. constructor(weight, quantization) {
  253. const shape = new dnn.TensorShape([ weight.dim0, weight.dim1, weight.dim2, weight.dim3 ]);
  254. this._data = quantization ? weight.quantized_data : weight.data;
  255. const size = shape.dimensions.reduce((a, b) => a * b, 1);
  256. const itemSize = Math.floor(this._data.length / size);
  257. const remainder = this._data.length - (itemSize * size);
  258. if (remainder < 0 || remainder > itemSize) {
  259. throw new dnn.Error('Invalid tensor data size.');
  260. }
  261. switch (itemSize) {
  262. case 1:
  263. this._type = new dnn.TensorType('int8', shape);
  264. break;
  265. case 2:
  266. this._type = new dnn.TensorType('float16', shape);
  267. break;
  268. case 4:
  269. this._type = new dnn.TensorType('float16', shape);
  270. break;
  271. default:
  272. this._type = new dnn.TensorType('?', shape);
  273. break;
  274. }
  275. }
  276. get kind() {
  277. return 'Weight';
  278. }
  279. get type() {
  280. return this._type;
  281. }
  282. get state() {
  283. return this._context().state;
  284. }
  285. get value() {
  286. const context = this._context();
  287. if (context.state) {
  288. return null;
  289. }
  290. context.limit = Number.MAX_SAFE_INTEGER;
  291. return this._decode(context, 0);
  292. }
  293. toString() {
  294. const context = this._context();
  295. if (context.state) {
  296. return '';
  297. }
  298. context.limit = 10000;
  299. const value = this._decode(context, 0);
  300. return JSON.stringify(value, null, 4);
  301. }
  302. _context() {
  303. const context = {};
  304. context.state = null;
  305. context.index = 0;
  306. context.count = 0;
  307. if (this._data == null) {
  308. context.state = 'Tensor data is empty.';
  309. return context;
  310. }
  311. switch (this._type.dataType) {
  312. case 'int8':
  313. case 'float16':
  314. case 'float32':
  315. break;
  316. default:
  317. context.state = "Tensor data type '" + this._type.dataType + "' is not supported.";
  318. return context;
  319. }
  320. context.dataType = this._type.dataType;
  321. context.shape = this._type.shape.dimensions;
  322. context.data = new DataView(this._data.buffer, this._data.byteOffset, this._data.byteLength);
  323. return context;
  324. }
  325. _decode(context, dimension) {
  326. const shape = (context.shape.length == 0) ? [ 1 ] : context.shape;
  327. const size = shape[dimension];
  328. const results = [];
  329. if (dimension == shape.length - 1) {
  330. for (let i = 0; i < size; i++) {
  331. if (context.count > context.limit) {
  332. results.push('...');
  333. return results;
  334. }
  335. switch (context.dataType) {
  336. case 'int8':
  337. results.push(context.data.getInt8(context.index));
  338. context.index++;
  339. context.count++;
  340. break;
  341. case 'float16':
  342. results.push(context.data.getFloat16(context.index, true));
  343. context.index += 2;
  344. context.count++;
  345. break;
  346. case 'float32':
  347. results.push(context.data.getFloat32(context.index, true));
  348. context.index += 4;
  349. context.count++;
  350. break;
  351. default:
  352. break;
  353. }
  354. }
  355. }
  356. else {
  357. for (let j = 0; j < size; j++) {
  358. if (context.count > context.limit) {
  359. results.push('...');
  360. return results;
  361. }
  362. results.push(this._decode(context, dimension + 1));
  363. }
  364. }
  365. if (context.shape.length == 0) {
  366. return results[0];
  367. }
  368. return results;
  369. }
  370. };
  371. dnn.TensorType = class {
  372. constructor(dataType, shape) {
  373. this._dataType = dataType;
  374. this._shape = shape;
  375. }
  376. get dataType() {
  377. return this._dataType;
  378. }
  379. get shape() {
  380. return this._shape;
  381. }
  382. toString() {
  383. return this.dataType + this._shape.toString();
  384. }
  385. };
  386. dnn.TensorShape = class {
  387. constructor(shape) {
  388. this._dimensions = shape;
  389. }
  390. get dimensions() {
  391. return this._dimensions;
  392. }
  393. toString() {
  394. if (!this._dimensions || this._dimensions.length == 0) {
  395. return '';
  396. }
  397. return '[' + this._dimensions.join(',') + ']';
  398. }
  399. };
  400. dnn.Metadata = class {
  401. static open(host) {
  402. if (dnn.Metadata._metadata) {
  403. return Promise.resolve(dnn.Metadata._metadata);
  404. }
  405. return host.request(null, 'dnn-metadata.json', 'utf-8').then((data) => {
  406. dnn.Metadata._metadata = new dnn.Metadata(data);
  407. return dnn.Metadata._metadata;
  408. }).catch(() => {
  409. dnn.Metadata._metadata = new dnn.Metadata(null);
  410. return dnn.Metadata._metadata;
  411. });
  412. }
  413. constructor(data) {
  414. this._map = new Map();
  415. this._attributeCache = new Map();
  416. if (data) {
  417. const items = JSON.parse(data);
  418. if (items) {
  419. for (const item of items) {
  420. if (item.name && item.schema) {
  421. item.schema.name = item.name;
  422. this._map.set(item.name, item.schema);
  423. }
  424. }
  425. }
  426. }
  427. }
  428. type(name) {
  429. return this._map.get(name);
  430. }
  431. attribute(type, name) {
  432. const key = type + ':' + name;
  433. if (!this._attributeCache.has(key)) {
  434. const schema = this.type(type);
  435. if (schema && schema.attributes && schema.attributes.length > 0) {
  436. for (const attribute of schema.attributes) {
  437. this._attributeCache.set(type + ':' + attribute.name, attribute);
  438. }
  439. }
  440. if (!this._attributeCache.has(key)) {
  441. this._attributeCache.set(key, null);
  442. }
  443. }
  444. return this._attributeCache.get(key);
  445. }
  446. };
  447. dnn.Error = class extends Error {
  448. constructor(message) {
  449. super(message);
  450. this.name = 'Error loading SnapML model.';
  451. }
  452. };
  453. if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  454. module.exports.ModelFactory = dnn.ModelFactory;
  455. }