dl4j.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. // Experimental
  2. const dl4j = {};
  3. dl4j.ModelFactory = class {
  4. async match(context) {
  5. const identifier = context.identifier;
  6. if (identifier === 'configuration.json') {
  7. const obj = await context.peek('json');
  8. if (obj && (obj.confs || obj.vertices)) {
  9. return context.set('dl4j.configuration', obj);
  10. }
  11. } else if (identifier === 'coefficients.bin') {
  12. const signature = [0x00, 0x07, 0x4A, 0x41, 0x56, 0x41, 0x43, 0x50, 0x50]; // JAVACPP
  13. const stream = context.stream;
  14. if (signature.length <= stream.length && stream.peek(signature.length).every((value, index) => value === signature[index])) {
  15. return context.set('dl4j.coefficients');
  16. }
  17. }
  18. return null;
  19. }
  20. filter(context, match) {
  21. return context.type !== 'dl4j.configuration' || (match.type !== 'dl4j.coefficients' && match.type !== 'openvino.bin');
  22. }
  23. async open(context) {
  24. const metadata = await context.metadata('dl4j-metadata.json');
  25. switch (context.type) {
  26. case 'dl4j.configuration': {
  27. const obj = context.value;
  28. try {
  29. const content = await context.fetch('coefficients.bin');
  30. const reader = await content.read('binary.big-endian');
  31. return new dl4j.Model(metadata, obj, reader);
  32. } catch {
  33. return new dl4j.Model(metadata, obj, null);
  34. }
  35. }
  36. case 'dl4j.coefficients': {
  37. const content = await context.fetch('configuration.json');
  38. const obj = await content.read('json');
  39. const reader = await context.read('binary.big-endian');
  40. return new dl4j.Model(metadata, obj, reader);
  41. }
  42. default: {
  43. throw new dl4j.Error(`Unsupported Deeplearning4j format '${context.type}'.`);
  44. }
  45. }
  46. }
  47. };
  48. dl4j.Model = class {
  49. constructor(metadata, configuration, coefficients) {
  50. this.format = 'Deeplearning4j';
  51. this.modules = [new dl4j.Graph(metadata, configuration, coefficients)];
  52. }
  53. };
  54. dl4j.Graph = class {
  55. constructor(metadata, configuration, coefficients) {
  56. this.inputs = [];
  57. this.outputs = [];
  58. this.nodes = [];
  59. coefficients = coefficients ? new dl4j.NDArray(coefficients) : null;
  60. const dataType = coefficients ? coefficients.dataType : '?';
  61. const values = new Map();
  62. values.map = (name, type, tensor) => {
  63. if (name.length === 0 && tensor) {
  64. return new dl4j.Value(name, type || null, tensor);
  65. }
  66. if (!values.has(name)) {
  67. values.set(name, new dl4j.Value(name, type || null, tensor || null));
  68. } else if (type || tensor) {
  69. throw new dl4j.Error(`Duplicate value '${name}'.`);
  70. }
  71. return values.get(name);
  72. };
  73. if (configuration.networkInputs) {
  74. for (const input of configuration.networkInputs) {
  75. const value = values.map(input);
  76. const argument = new dl4j.Argument(input, [value]);
  77. this.inputs.push(argument);
  78. }
  79. }
  80. if (configuration.networkOutputs) {
  81. for (const output of configuration.networkOutputs) {
  82. const value = values.map(output);
  83. const argument = new dl4j.Argument(output, [value]);
  84. this.outputs.push(argument);
  85. }
  86. }
  87. let inputs = null;
  88. // Computation Graph
  89. if (configuration.vertices) {
  90. for (const [name,obj] of Object.entries(configuration.vertices)) {
  91. const vertex = dl4j.Node._object(obj);
  92. inputs = configuration.vertexInputs[name];
  93. let variables = [];
  94. let layer = null;
  95. switch (vertex.__type__) {
  96. case 'LayerVertex':
  97. layer = dl4j.Node._object(vertex.layerConf.layer);
  98. variables = vertex.layerConf.variables;
  99. break;
  100. case 'MergeVertex':
  101. layer = { __type__: 'Merge', layerName: name };
  102. break;
  103. case 'ElementWiseVertex':
  104. layer = { __type__: 'ElementWise', layerName: name, op: vertex.op };
  105. break;
  106. case 'PreprocessorVertex':
  107. layer = { __type__: 'Preprocessor', layerName: name };
  108. break;
  109. default:
  110. throw new dl4j.Error(`Unsupported vertex class '${vertex['@class']}'.`);
  111. }
  112. const node = new dl4j.Node(metadata, layer, inputs, dataType, variables, values);
  113. this.nodes.push(node);
  114. }
  115. }
  116. // Multi Layer Network
  117. if (configuration.confs) {
  118. inputs = ['input'];
  119. this.inputs.push(new dl4j.Argument('input', [values.map('input')]));
  120. for (const conf of configuration.confs) {
  121. const layer = dl4j.Node._object(conf.layer);
  122. const node = new dl4j.Node(metadata, layer, inputs, dataType, conf.variables, values);
  123. this.nodes.push(node);
  124. inputs = [layer.layerName];
  125. }
  126. if (inputs && inputs.length > 0) {
  127. const argument = new dl4j.Argument('output', [values.map(inputs[0])]);
  128. this.outputs.push(argument);
  129. }
  130. }
  131. }
  132. };
  133. dl4j.Argument = class {
  134. constructor(name, value, visible) {
  135. this.name = name;
  136. this.value = value;
  137. if (visible === false) {
  138. this.visible = false;
  139. }
  140. }
  141. };
  142. dl4j.Value = class {
  143. constructor(name, type, initializer) {
  144. if (typeof name !== 'string') {
  145. throw new dl4j.Error(`Invalid value identifier '${JSON.stringify(name)}'.`);
  146. }
  147. this.name = name;
  148. this.type = initializer ? initializer.type : type;
  149. this.initializer = initializer;
  150. }
  151. };
  152. dl4j.Node = class {
  153. constructor(metadata, layer, inputs, dataType, variables, values) {
  154. this.name = layer.layerName || '';
  155. this.inputs = [];
  156. this.outputs = [];
  157. this.attributes = [];
  158. const type = layer.__type__;
  159. this.type = metadata.type(type) || { name: type };
  160. if (inputs && inputs.length > 0) {
  161. const argument = new dl4j.Argument(values.length < 2 ? 'input' : 'inputs', inputs.map((input) => values.map(input)));
  162. this.inputs.push(argument);
  163. }
  164. if (variables) {
  165. for (const variable of variables) {
  166. let tensor = null;
  167. switch (type) {
  168. case 'Convolution':
  169. switch (variable) {
  170. case 'W':
  171. tensor = new dl4j.Tensor(dataType, layer.kernelSize.concat([layer.nin, layer.nout]));
  172. break;
  173. case 'b':
  174. tensor = new dl4j.Tensor(dataType, [layer.nout]);
  175. break;
  176. default:
  177. throw new dl4j.Error(`Unsupported '${type}' variable '${variable}'.`);
  178. }
  179. break;
  180. case 'SeparableConvolution2D':
  181. switch (variable) {
  182. case 'W':
  183. tensor = new dl4j.Tensor(dataType, layer.kernelSize.concat([layer.nin, layer.nout]));
  184. break;
  185. case 'pW':
  186. tensor = new dl4j.Tensor(dataType, [layer.nout]);
  187. break;
  188. default:
  189. throw new dl4j.Error(`Unsupported '${type}' variable '${variable}'.`);
  190. }
  191. break;
  192. case 'Output':
  193. case 'Dense':
  194. switch (variable) {
  195. case 'W':
  196. tensor = new dl4j.Tensor(dataType, [layer.nout, layer.nin]);
  197. break;
  198. case 'b':
  199. tensor = new dl4j.Tensor(dataType, [layer.nout]);
  200. break;
  201. default:
  202. throw new dl4j.Error(`Unsupported '${this.type}' variable '${variable}'.`);
  203. }
  204. break;
  205. case 'BatchNormalization':
  206. tensor = new dl4j.Tensor(dataType, [layer.nin]);
  207. break;
  208. default:
  209. throw new dl4j.Error(`Unsupported '${type}' variable '${variable}'.`);
  210. }
  211. const argument = new dl4j.Argument(variable, [values.map('', null, tensor)]);
  212. this.inputs.push(argument);
  213. }
  214. }
  215. if (this.name) {
  216. const value = values.map(this.name);
  217. const argument = new dl4j.Argument('output', [value]);
  218. this.outputs.push(argument);
  219. }
  220. let attributes = layer;
  221. if (layer.activationFn) {
  222. const activation = dl4j.Node._object(layer.activationFn);
  223. if (activation.__type__ !== 'ActivationIdentity' && activation.__type__ !== 'Identity') {
  224. if (activation.__type__.startsWith('Activation')) {
  225. activation.__type__ = activation.__type__.substring('Activation'.length);
  226. }
  227. if (this.type === 'Activation') {
  228. this.type = activation.__type__;
  229. attributes = activation;
  230. } else {
  231. this.chain = this.chain || [];
  232. this.chain.push(new dl4j.Node(metadata, activation, [], null, null, values));
  233. }
  234. }
  235. }
  236. for (const [name, value] of Object.entries(attributes)) {
  237. switch (name) {
  238. case '__type__':
  239. case 'constraints':
  240. case 'layerName':
  241. case 'activationFn':
  242. case 'idropout':
  243. case 'hasBias':
  244. continue;
  245. default:
  246. break;
  247. }
  248. const definition = metadata.attribute(type, name);
  249. const visible = definition && definition.visible === false ? false : true;
  250. const attribute = new dl4j.Argument(name, value, visible);
  251. this.attributes.push(attribute);
  252. }
  253. if (layer.idropout) {
  254. const dropout = dl4j.Node._object(layer.idropout);
  255. if (dropout.p !== 1.0) {
  256. throw new dl4j.Error("Layer 'idropout' not implemented.");
  257. }
  258. }
  259. }
  260. static _object(value) {
  261. let result = {};
  262. if (value['@class']) {
  263. result = value;
  264. let type = value['@class'].split('.').pop();
  265. if (type.endsWith('Layer')) {
  266. type = type.substring(0, type.length - 5);
  267. }
  268. delete value['@class'];
  269. result.__type__ = type;
  270. } else {
  271. let [key] = Object.keys(value);
  272. result = value[key];
  273. if (key.length > 0) {
  274. key = key[0].toUpperCase() + key.substring(1);
  275. }
  276. result.__type__ = key;
  277. }
  278. return result;
  279. }
  280. };
  281. dl4j.Tensor = class {
  282. constructor(dataType, shape) {
  283. this.type = new dl4j.TensorType(dataType, new dl4j.TensorShape(shape));
  284. }
  285. };
  286. dl4j.TensorType = class {
  287. constructor(dataType, shape) {
  288. this.dataType = dataType;
  289. this.shape = shape;
  290. }
  291. toString() {
  292. return (this.dataType || '?') + this.shape.toString();
  293. }
  294. };
  295. dl4j.TensorShape = class {
  296. constructor(dimensions) {
  297. this.dimensions = dimensions;
  298. }
  299. toString() {
  300. if (this.dimensions) {
  301. if (this.dimensions.length === 0) {
  302. return '';
  303. }
  304. return `[${this.dimensions.map((dimension) => dimension.toString()).join(',')}]`;
  305. }
  306. return '';
  307. }
  308. };
  309. dl4j.NDArray = class {
  310. constructor(reader) {
  311. reader = new dl4j.BinaryReader(reader);
  312. const readHeader = (reader) => {
  313. const alloc = reader.string();
  314. let length = 0;
  315. switch (alloc) {
  316. case 'DIRECT':
  317. case 'HEAP':
  318. case 'JAVACPP':
  319. length = reader.int32();
  320. break;
  321. case 'LONG_SHAPE':
  322. case 'MIXED_DATA_TYPES':
  323. length = reader.int64().toNumber();
  324. break;
  325. default:
  326. throw new dl4j.Error(`Unsupported header alloc '${alloc}'.`);
  327. }
  328. const type = reader.string();
  329. return [alloc, length, type];
  330. };
  331. const headerShape = readHeader(reader);
  332. if (headerShape[2] !== 'INT') {
  333. throw new dl4j.Error(`Unsupported header shape type '${headerShape[2]}'.`);
  334. }
  335. const shapeInfo = new Array(headerShape[1]);
  336. for (let i = 0; i < shapeInfo.length; i++) {
  337. shapeInfo[i] = reader.int32();
  338. }
  339. const [rank] = shapeInfo;
  340. const shapeInfoLength = rank * 2 + 4;
  341. this.shape = shapeInfo.slice(1, 1 + rank);
  342. this.strides = shapeInfo.slice(1 + rank, 1 + (rank * 2));
  343. this.order = shapeInfo[shapeInfoLength - 1];
  344. const headerData = readHeader(reader);
  345. const dataTypes = new Map([
  346. ['INT', ['int32', 4]],
  347. ['FLOAT', ['float32', 4]],
  348. ['DOUBLE', ['float64', 8]]
  349. ]);
  350. if (!dataTypes.has(headerData[2])) {
  351. throw new dl4j.Error(`Unsupported header data type '${headerShape[2]}'.`);
  352. }
  353. const [dataType, itemSize] = dataTypes.get(headerData[2]);
  354. this.dataType = dataType;
  355. const size = headerData[1] * itemSize;
  356. if ((reader.position + size) <= reader.length) {
  357. this.data = reader.read(size);
  358. }
  359. }
  360. };
  361. dl4j.BinaryReader = class {
  362. constructor(reader) {
  363. this._reader = reader;
  364. }
  365. get length() {
  366. return this._reader.length;
  367. }
  368. get position() {
  369. return this._reader.position;
  370. }
  371. read(length) {
  372. return this._reader.read(length);
  373. }
  374. int32() {
  375. return this._reader.int32();
  376. }
  377. int64() {
  378. return this._reader.int64();
  379. }
  380. uint16() {
  381. return this._reader.uint16();
  382. }
  383. string() {
  384. const size = this.uint16();
  385. const buffer = this.read(size);
  386. this._decoder = this._decoder || new TextDecoder('ascii');
  387. return this._decoder.decode(buffer);
  388. }
  389. };
  390. dl4j.Error = class extends Error {
  391. constructor(message) {
  392. super(message);
  393. this.name = 'Error loading Deeplearning4j model.';
  394. }
  395. };
  396. export const ModelFactory = dl4j.ModelFactory;