dnn.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. // Experimental
  2. var dnn = dnn || {};
  3. dnn.ModelFactory = class {
  4. match(context) {
  5. const tags = context.tags('pb');
  6. if (tags.get(4) == 0 && tags.get(10) == 2) {
  7. return 'dnn';
  8. }
  9. return undefined;
  10. }
  11. open(context) {
  12. return context.require('./dnn-proto').then(() => {
  13. let model = null;
  14. try {
  15. dnn.proto = protobuf.get('dnn').dnn;
  16. const stream = context.stream;
  17. const reader = protobuf.BinaryReader.open(stream);
  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 context.metadata('dnn-metadata.json').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. const type = layer.type;
  153. this._type = metadata.type(type) || { name: type };
  154. this._attributes = [];
  155. this._inputs = [];
  156. this._outputs = [];
  157. const inputs = node.input.map((input) => 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) => arg(output));
  172. if (inputs && inputs.length > 0) {
  173. let inputIndex = 0;
  174. if (this._type && this._type.inputs) {
  175. for (const inputSchema of this._type.inputs) {
  176. if (inputIndex < inputs.length || inputSchema.option != 'optional') {
  177. const inputCount = (inputSchema.option == 'variadic') ? (node.input.length - inputIndex) : 1;
  178. const inputArguments = inputs.slice(inputIndex, inputIndex + inputCount);
  179. this._inputs.push(new dnn.Parameter(inputSchema.name, inputArguments));
  180. inputIndex += inputCount;
  181. }
  182. }
  183. }
  184. this._inputs.push(...inputs.slice(inputIndex).map((input, index) => {
  185. const inputName = ((inputIndex + index) == 0) ? 'input' : (inputIndex + index).toString();
  186. return new dnn.Parameter(inputName, [ input ]);
  187. }));
  188. }
  189. if (outputs.length > 0) {
  190. this._outputs = outputs.map((output, index) => {
  191. const inputName = (index == 0) ? 'output' : index.toString();
  192. return new dnn.Parameter(inputName, [ output ]);
  193. });
  194. }
  195. for (const key of Object.keys(layer)) {
  196. switch (key) {
  197. case 'name':
  198. case 'type':
  199. case 'weight':
  200. case 'is_quantized':
  201. case 'quantization':
  202. break;
  203. default:
  204. this._attributes.push(new dnn.Attribute(metadata.attribute(type, key), key, layer[key]));
  205. break;
  206. }
  207. }
  208. }
  209. get name() {
  210. return this._name;
  211. }
  212. get type() {
  213. return this._type;
  214. }
  215. get inputs() {
  216. return this._inputs;
  217. }
  218. get outputs() {
  219. return this._outputs;
  220. }
  221. get attributes() {
  222. return this._attributes;
  223. }
  224. };
  225. dnn.Attribute = class {
  226. constructor(metadata, name, value) {
  227. this._name = name;
  228. this._value = value;
  229. }
  230. get name() {
  231. return this._name;
  232. }
  233. get value() {
  234. return this._value;
  235. }
  236. };
  237. dnn.Tensor = class {
  238. constructor(weight, quantization) {
  239. const shape = new dnn.TensorShape([ weight.dim0, weight.dim1, weight.dim2, weight.dim3 ]);
  240. this._data = quantization ? weight.quantized_data : weight.data;
  241. const size = shape.dimensions.reduce((a, b) => a * b, 1);
  242. const itemSize = Math.floor(this._data.length / size);
  243. const remainder = this._data.length - (itemSize * size);
  244. if (remainder < 0 || remainder > itemSize) {
  245. throw new dnn.Error('Invalid tensor data size.');
  246. }
  247. switch (itemSize) {
  248. case 1:
  249. this._type = new dnn.TensorType('int8', shape);
  250. break;
  251. case 2:
  252. this._type = new dnn.TensorType('float16', shape);
  253. break;
  254. case 4:
  255. this._type = new dnn.TensorType('float16', shape);
  256. break;
  257. default:
  258. this._type = new dnn.TensorType('?', shape);
  259. break;
  260. }
  261. }
  262. get kind() {
  263. return 'Weight';
  264. }
  265. get type() {
  266. return this._type;
  267. }
  268. get state() {
  269. return this._context().state;
  270. }
  271. get value() {
  272. const context = this._context();
  273. if (context.state) {
  274. return null;
  275. }
  276. context.limit = Number.MAX_SAFE_INTEGER;
  277. return this._decode(context, 0);
  278. }
  279. toString() {
  280. const context = this._context();
  281. if (context.state) {
  282. return '';
  283. }
  284. context.limit = 10000;
  285. const value = this._decode(context, 0);
  286. return JSON.stringify(value, null, 4);
  287. }
  288. _context() {
  289. const context = {};
  290. context.state = null;
  291. context.index = 0;
  292. context.count = 0;
  293. if (this._data == null) {
  294. context.state = 'Tensor data is empty.';
  295. return context;
  296. }
  297. switch (this._type.dataType) {
  298. case 'int8':
  299. case 'float16':
  300. case 'float32':
  301. break;
  302. default:
  303. context.state = "Tensor data type '" + this._type.dataType + "' is not supported.";
  304. return context;
  305. }
  306. context.dataType = this._type.dataType;
  307. context.shape = this._type.shape.dimensions;
  308. context.data = new DataView(this._data.buffer, this._data.byteOffset, this._data.byteLength);
  309. return context;
  310. }
  311. _decode(context, dimension) {
  312. const shape = (context.shape.length == 0) ? [ 1 ] : context.shape;
  313. const size = shape[dimension];
  314. const results = [];
  315. if (dimension == shape.length - 1) {
  316. for (let i = 0; i < size; i++) {
  317. if (context.count > context.limit) {
  318. results.push('...');
  319. return results;
  320. }
  321. switch (context.dataType) {
  322. case 'int8':
  323. results.push(context.data.getInt8(context.index));
  324. context.index++;
  325. context.count++;
  326. break;
  327. case 'float16':
  328. results.push(context.data.getFloat16(context.index, true));
  329. context.index += 2;
  330. context.count++;
  331. break;
  332. case 'float32':
  333. results.push(context.data.getFloat32(context.index, true));
  334. context.index += 4;
  335. context.count++;
  336. break;
  337. default:
  338. break;
  339. }
  340. }
  341. }
  342. else {
  343. for (let j = 0; j < size; j++) {
  344. if (context.count > context.limit) {
  345. results.push('...');
  346. return results;
  347. }
  348. results.push(this._decode(context, dimension + 1));
  349. }
  350. }
  351. if (context.shape.length == 0) {
  352. return results[0];
  353. }
  354. return results;
  355. }
  356. };
  357. dnn.TensorType = class {
  358. constructor(dataType, shape) {
  359. this._dataType = dataType;
  360. this._shape = shape;
  361. }
  362. get dataType() {
  363. return this._dataType;
  364. }
  365. get shape() {
  366. return this._shape;
  367. }
  368. toString() {
  369. return this.dataType + this._shape.toString();
  370. }
  371. };
  372. dnn.TensorShape = class {
  373. constructor(shape) {
  374. this._dimensions = shape;
  375. }
  376. get dimensions() {
  377. return this._dimensions;
  378. }
  379. toString() {
  380. if (!this._dimensions || this._dimensions.length == 0) {
  381. return '';
  382. }
  383. return '[' + this._dimensions.join(',') + ']';
  384. }
  385. };
  386. dnn.Error = class extends Error {
  387. constructor(message) {
  388. super(message);
  389. this.name = 'Error loading SnapML model.';
  390. }
  391. };
  392. if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  393. module.exports.ModelFactory = dnn.ModelFactory;
  394. }