dl4j.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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 = true) {
  135. this.name = name;
  136. this.value = value;
  137. this.visible = visible;
  138. }
  139. };
  140. dl4j.Value = class {
  141. constructor(name, type, initializer) {
  142. if (typeof name !== 'string') {
  143. throw new dl4j.Error(`Invalid value identifier '${JSON.stringify(name)}'.`);
  144. }
  145. this.name = name;
  146. this.type = initializer ? initializer.type : type;
  147. this.initializer = initializer;
  148. }
  149. };
  150. dl4j.Node = class {
  151. constructor(metadata, layer, inputs, dataType, variables, values) {
  152. this.name = layer.layerName || '';
  153. this.inputs = [];
  154. this.outputs = [];
  155. this.attributes = [];
  156. const type = layer.__type__;
  157. this.type = metadata.type(type) || { name: type };
  158. if (inputs && inputs.length > 0) {
  159. const argument = new dl4j.Argument(values.length < 2 ? 'input' : 'inputs', inputs.map((input) => values.map(input)));
  160. this.inputs.push(argument);
  161. }
  162. if (variables) {
  163. for (const variable of variables) {
  164. let tensor = null;
  165. switch (type) {
  166. case 'Convolution':
  167. switch (variable) {
  168. case 'W':
  169. tensor = new dl4j.Tensor(dataType, layer.kernelSize.concat([layer.nin, layer.nout]));
  170. break;
  171. case 'b':
  172. tensor = new dl4j.Tensor(dataType, [layer.nout]);
  173. break;
  174. default:
  175. throw new dl4j.Error(`Unsupported '${type}' variable '${variable}'.`);
  176. }
  177. break;
  178. case 'SeparableConvolution2D':
  179. switch (variable) {
  180. case 'W':
  181. tensor = new dl4j.Tensor(dataType, layer.kernelSize.concat([layer.nin, layer.nout]));
  182. break;
  183. case 'pW':
  184. tensor = new dl4j.Tensor(dataType, [layer.nout]);
  185. break;
  186. default:
  187. throw new dl4j.Error(`Unsupported '${type}' variable '${variable}'.`);
  188. }
  189. break;
  190. case 'Output':
  191. case 'Dense':
  192. switch (variable) {
  193. case 'W':
  194. tensor = new dl4j.Tensor(dataType, [layer.nout, layer.nin]);
  195. break;
  196. case 'b':
  197. tensor = new dl4j.Tensor(dataType, [layer.nout]);
  198. break;
  199. default:
  200. throw new dl4j.Error(`Unsupported '${this.type}' variable '${variable}'.`);
  201. }
  202. break;
  203. case 'BatchNormalization':
  204. tensor = new dl4j.Tensor(dataType, [layer.nin]);
  205. break;
  206. default:
  207. throw new dl4j.Error(`Unsupported '${type}' variable '${variable}'.`);
  208. }
  209. const argument = new dl4j.Argument(variable, [values.map('', null, tensor)]);
  210. this.inputs.push(argument);
  211. }
  212. }
  213. if (this.name) {
  214. const value = values.map(this.name);
  215. const argument = new dl4j.Argument('output', [value]);
  216. this.outputs.push(argument);
  217. }
  218. let attributes = layer;
  219. if (layer.activationFn) {
  220. const activation = dl4j.Node._object(layer.activationFn);
  221. if (activation.__type__ !== 'ActivationIdentity' && activation.__type__ !== 'Identity') {
  222. if (activation.__type__.startsWith('Activation')) {
  223. activation.__type__ = activation.__type__.substring('Activation'.length);
  224. }
  225. if (this.type === 'Activation') {
  226. this.type = activation.__type__;
  227. attributes = activation;
  228. } else {
  229. this.chain = this.chain || [];
  230. this.chain.push(new dl4j.Node(metadata, activation, [], null, null, values));
  231. }
  232. }
  233. }
  234. for (const [name, value] of Object.entries(attributes)) {
  235. switch (name) {
  236. case '__type__':
  237. case 'constraints':
  238. case 'layerName':
  239. case 'activationFn':
  240. case 'idropout':
  241. case 'hasBias':
  242. continue;
  243. default:
  244. break;
  245. }
  246. const definition = metadata.attribute(type, name);
  247. const visible = definition && definition.visible === false ? false : true;
  248. const attribute = new dl4j.Argument(name, value, visible);
  249. this.attributes.push(attribute);
  250. }
  251. if (layer.idropout) {
  252. const dropout = dl4j.Node._object(layer.idropout);
  253. if (dropout.p !== 1.0) {
  254. throw new dl4j.Error("Layer 'idropout' not implemented.");
  255. }
  256. }
  257. }
  258. static _object(value) {
  259. let result = {};
  260. if (value['@class']) {
  261. result = value;
  262. let type = value['@class'].split('.').pop();
  263. if (type.endsWith('Layer')) {
  264. type = type.substring(0, type.length - 5);
  265. }
  266. delete value['@class'];
  267. result.__type__ = type;
  268. } else {
  269. let [key] = Object.keys(value);
  270. result = value[key];
  271. if (key.length > 0) {
  272. key = key[0].toUpperCase() + key.substring(1);
  273. }
  274. result.__type__ = key;
  275. }
  276. return result;
  277. }
  278. };
  279. dl4j.Tensor = class {
  280. constructor(dataType, shape) {
  281. this.type = new dl4j.TensorType(dataType, new dl4j.TensorShape(shape));
  282. }
  283. };
  284. dl4j.TensorType = class {
  285. constructor(dataType, shape) {
  286. this.dataType = dataType;
  287. this.shape = shape;
  288. }
  289. toString() {
  290. return (this.dataType || '?') + this.shape.toString();
  291. }
  292. };
  293. dl4j.TensorShape = class {
  294. constructor(dimensions) {
  295. this.dimensions = dimensions;
  296. }
  297. toString() {
  298. if (this.dimensions) {
  299. if (this.dimensions.length === 0) {
  300. return '';
  301. }
  302. return `[${this.dimensions.map((dimension) => dimension.toString()).join(',')}]`;
  303. }
  304. return '';
  305. }
  306. };
  307. dl4j.NDArray = class {
  308. constructor(reader) {
  309. reader = new dl4j.BinaryReader(reader);
  310. const readHeader = (reader) => {
  311. const alloc = reader.string();
  312. let length = 0;
  313. switch (alloc) {
  314. case 'DIRECT':
  315. case 'HEAP':
  316. case 'JAVACPP':
  317. length = reader.int32();
  318. break;
  319. case 'LONG_SHAPE':
  320. case 'MIXED_DATA_TYPES':
  321. length = reader.int64().toNumber();
  322. break;
  323. default:
  324. throw new dl4j.Error(`Unsupported header alloc '${alloc}'.`);
  325. }
  326. const type = reader.string();
  327. return [alloc, length, type];
  328. };
  329. const headerShape = readHeader(reader);
  330. if (headerShape[2] !== 'INT') {
  331. throw new dl4j.Error(`Unsupported header shape type '${headerShape[2]}'.`);
  332. }
  333. const shapeInfo = new Array(headerShape[1]);
  334. for (let i = 0; i < shapeInfo.length; i++) {
  335. shapeInfo[i] = reader.int32();
  336. }
  337. const [rank] = shapeInfo;
  338. const shapeInfoLength = rank * 2 + 4;
  339. this.shape = shapeInfo.slice(1, 1 + rank);
  340. this.strides = shapeInfo.slice(1 + rank, 1 + (rank * 2));
  341. this.order = shapeInfo[shapeInfoLength - 1];
  342. const headerData = readHeader(reader);
  343. const dataTypes = new Map([
  344. ['INT', ['int32', 4]],
  345. ['FLOAT', ['float32', 4]],
  346. ['DOUBLE', ['float64', 8]]
  347. ]);
  348. if (!dataTypes.has(headerData[2])) {
  349. throw new dl4j.Error(`Unsupported header data type '${headerData[2]}'.`);
  350. }
  351. const [dataType, itemSize] = dataTypes.get(headerData[2]);
  352. this.dataType = dataType;
  353. const size = headerData[1] * itemSize;
  354. if ((reader.position + size) <= reader.length) {
  355. this.data = reader.read(size);
  356. }
  357. }
  358. };
  359. dl4j.BinaryReader = class {
  360. constructor(reader) {
  361. this._reader = reader;
  362. }
  363. get length() {
  364. return this._reader.length;
  365. }
  366. get position() {
  367. return this._reader.position;
  368. }
  369. read(length) {
  370. return this._reader.read(length);
  371. }
  372. int32() {
  373. return this._reader.int32();
  374. }
  375. int64() {
  376. return this._reader.int64();
  377. }
  378. uint16() {
  379. return this._reader.uint16();
  380. }
  381. string() {
  382. const size = this.uint16();
  383. const buffer = this.read(size);
  384. this._decoder = this._decoder || new TextDecoder('ascii');
  385. return this._decoder.decode(buffer);
  386. }
  387. };
  388. dl4j.Error = class extends Error {
  389. constructor(message) {
  390. super(message);
  391. this.name = 'Error loading Deeplearning4j model.';
  392. }
  393. };
  394. export const ModelFactory = dl4j.ModelFactory;