dnn.js 15 KB

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