keras.js 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  1. /* jshint esversion: 6 */
  2. var keras = keras || {};
  3. var json = json || require('./json');
  4. keras.ModelFactory = class {
  5. match(context) {
  6. return this._format(context).length > 0;
  7. }
  8. open(context) {
  9. const openModel = (format, producer, backend, config, weights) => {
  10. return keras.Metadata.open(context).then((metadata) => {
  11. return new keras.Model(metadata, format, producer, backend, config, weights);
  12. });
  13. };
  14. const openShards = (manifests, shards) => {
  15. const weights = new keras.Weights();
  16. const dtype_size_map = new Map([ [ 'float16', 2 ], [ 'float32', 4 ], [ 'float64', 8 ], [ 'int8', 1 ], [ 'int16', 2 ], [ 'int32', 4 ], [ 'int64', 8 ], [ 'uint8', 1 ], [ 'uint16', 2 ], [ 'uint32', 4 ], [ 'uint64', 8 ] ]);
  17. for (const manifest of manifests) {
  18. let buffer = null;
  19. if (Array.isArray(manifest.paths) && manifest.paths.length > 0 && manifest.paths.every((path) => shards.has(path))) {
  20. const list = manifest.paths.map((path) => shards.get(path));
  21. const size = list.reduce((a, b) => a + b.length, 0);
  22. buffer = new Uint8Array(size);
  23. let offset = 0;
  24. for (const item of list) {
  25. buffer.set(item, offset);
  26. offset += item.length;
  27. }
  28. }
  29. let offset = 0;
  30. for (const weight of manifest.weights) {
  31. const dtype = weight.quantization && weight.quantization.dtype ? weight.quantization.dtype : weight.dtype;
  32. if (!dtype_size_map.has(dtype)) {
  33. throw new keras.Error("Unknown weight data type size '" + dtype + "'.");
  34. }
  35. const itemsize = dtype_size_map.get(dtype);
  36. const size = weight.shape.reduce((a, b) => a * b, 1);
  37. const length = itemsize * size;
  38. const data = buffer ? buffer.slice(offset, offset + length) : null;
  39. weights.add(weight.identifier, new keras.Tensor(weight.name, weight.shape, dtype, weight.quantization, true, data));
  40. offset += length;
  41. }
  42. }
  43. return Promise.resolve(weights);
  44. };
  45. const openManifests = (manifests) => {
  46. const shards = new Map();
  47. for (const manifest of manifests) {
  48. for (const path of manifest.paths) {
  49. if (!shards.has(path)) {
  50. shards.set(path, context.request(path, null));
  51. }
  52. }
  53. }
  54. const promises = shards.values();
  55. return Promise.all(promises).then((streams) => {
  56. for (const key of shards.keys()) {
  57. shards.set(key, streams.shift().peek());
  58. }
  59. return openShards(manifests, shards);
  60. }).catch(() => {
  61. shards.clear();
  62. return openShards(manifests, shards);
  63. });
  64. };
  65. const stream = context.stream;
  66. switch (this._format(context)) {
  67. case 'keras.h5': {
  68. return context.require('./hdf5').then((hdf5) => {
  69. const weights = new keras.Weights();
  70. const file = hdf5.File.open(stream);
  71. const rootGroup = file.rootGroup;
  72. const read_model_config = (group) => {
  73. if (group.attributes.has('model_config')) {
  74. const buffer = rootGroup.attributes.get('model_config');
  75. const reader = json.TextReader.open(buffer);
  76. return reader.read();
  77. }
  78. return null;
  79. };
  80. const load_attributes_from_hdf5_group = (group, name) => {
  81. if (group.attributes.has(name)) {
  82. return group.attributes.get(name);
  83. }
  84. if (group.attributes.has(name + '0')) {
  85. let index = 0;
  86. let value = [];
  87. while (group.attributes.has(name + index.toString())) {
  88. const chunk = group.attributes.get(name + index.toString());
  89. value = value.concat(chunk);
  90. index++;
  91. }
  92. return value;
  93. }
  94. return null;
  95. };
  96. const model_config = read_model_config(rootGroup);
  97. if (model_config) {
  98. const backend = rootGroup.attributes.get('backend') || '';
  99. const version = rootGroup.attributes.get('keras_version') || '';
  100. const format = 'Keras' + (version ? ' v' + version : '');
  101. const model_weights_group = rootGroup.group('model_weights');
  102. if (model_weights_group) {
  103. const layer_names = load_attributes_from_hdf5_group(model_weights_group, 'layer_names');
  104. for (const layer_name of layer_names) {
  105. const layer_weights = model_weights_group.group(layer_name);
  106. if (layer_weights) {
  107. const weight_names = load_attributes_from_hdf5_group(layer_weights, 'weight_names');
  108. if (Array.isArray(weight_names) && weight_names.length > 0) {
  109. for (const weight_name of weight_names) {
  110. const weight = layer_weights.group(weight_name);
  111. if (weight && weight.value) {
  112. const variable = weight.value;
  113. const tensor = new keras.Tensor(weight_name, variable.shape, variable.type, null, variable.littleEndian, variable.data);
  114. weights.add(layer_name, tensor);
  115. }
  116. }
  117. }
  118. }
  119. }
  120. }
  121. if (!model_config) {
  122. throw new keras.Error("'model_config' is not present.");
  123. }
  124. if (!model_config.class_name) {
  125. throw new keras.Error("'class_name' is not present.");
  126. }
  127. return openModel(format, '', backend, model_config, weights);
  128. }
  129. const layer_names = load_attributes_from_hdf5_group(rootGroup, 'layer_names');
  130. if (layer_names && Array.isArray(layer_names)) {
  131. const version = rootGroup.attributes.get('keras_version') || '';
  132. const format = 'Keras Weights' + (version ? ' v' + version : '');
  133. const backend = rootGroup.attributes.get('backend') || '';
  134. for (const layer_name of layer_names) {
  135. const layer_weights = rootGroup.group(layer_name);
  136. if (layer_weights) {
  137. const weight_names = load_attributes_from_hdf5_group(layer_weights, 'weight_names');
  138. if (Array.isArray(weight_names) && weight_names.length > 0) {
  139. for (const weight_name of weight_names) {
  140. const weight = layer_weights.group(weight_name);
  141. if (weight && weight.value) {
  142. const variable = weight.value;
  143. const components = weight_name.split('/');
  144. components.pop();
  145. const name = (components.length == 0 || components[0] !== layer_name) ? [ layer_name ].concat(components).join('/') : components.join('/');
  146. const tensor = new keras.Tensor(weight_name, variable.shape, variable.type, null, variable.littleEndian, variable.data);
  147. weights.add(name, tensor);
  148. }
  149. }
  150. }
  151. }
  152. }
  153. return openModel(format, '', backend, null, weights);
  154. }
  155. else {
  156. const rootKeys = new Set(rootGroup.attributes.keys());
  157. rootKeys.delete('nb_layers');
  158. if (rootKeys.size > 0 || rootGroup.value !== null) {
  159. throw new keras.Error('File format is not HDF5 Weights');
  160. }
  161. let format = 'HDF5 Weights';
  162. let weightsGroup = rootGroup;
  163. if (rootGroup.attributes.size === 0 && rootGroup.value === null && rootGroup.groups.size == 1) {
  164. const group = rootGroup.groups.values().next().value;
  165. if (group.attributes.size === 0 && group.value === null) {
  166. weightsGroup = group;
  167. }
  168. }
  169. const tensorKeys = new Set([ 'name', 'shape', 'quantization' ]);
  170. const groups = Array.from(weightsGroup.groups.values());
  171. if (groups.every((group) => group.attributes.size === 0 && group.groups.length == 0 && group.value !== null)) {
  172. for (const group of groups) {
  173. const variable = group.value;
  174. const tensor = new keras.Tensor(group.name, variable.shape, variable.type, null, variable.littleEndian, variable.type === 'string' ? variable.value : variable.data);
  175. weights.add('', tensor);
  176. }
  177. return openModel(format, '', '', null, weights);
  178. }
  179. if (groups.every((group) => group.value === null && Array.from(group.attributes.keys()).filter((key) => !tensorKeys.has(key)).length === 0 && Array.from(group.groups.values()).every((variable) => Object.keys(variable.attributes).length === 0 && variable.value !== null))) {
  180. for (const group of groups) {
  181. const moduleName = group.attributes.has('name') ? group.attributes.get('name') : group.name;
  182. for (const variableGroup of group.groups.values()) {
  183. if (variableGroup.attributes.size !== 0 || variableGroup.groups.size !== 0) {
  184. throw new keras.Error('Variable format is not HDF5 Weights');
  185. }
  186. const variable = variableGroup.value;
  187. if (!variable) {
  188. throw new keras.Error('Variable value is not HDF5 Weights');
  189. }
  190. const name = moduleName ? [ moduleName, variableGroup.name ].join('/') : moduleName.name;
  191. const tensor = new keras.Tensor(name, variable.shape, variable.type, null, variable.littleEndian, variable.type === 'string' ? variable.value : variable.data);
  192. weights.add(moduleName, tensor);
  193. }
  194. }
  195. return openModel(format, '', '', null, weights);
  196. }
  197. const walk = function(group) {
  198. if (group.attributes.size === 0 && group.value === null && group.groups.size > 0) {
  199. for (const subGroup of group.groups.values()) {
  200. walk(subGroup);
  201. }
  202. return;
  203. }
  204. const subKeys = new Set([ 'index', 'need_grad' ]);
  205. const attribtues = Array.from(group.attributes.keys());
  206. const match = attribtues.filter((key) => !subKeys.has(key)).length === 0;
  207. if (match && attribtues.length !== 0) {
  208. format = 'nnabla HDF5 Weights';
  209. }
  210. if (match && group.value !== null && group.groups.size === 0) {
  211. const variable = group.value;
  212. const variableName = group.path;
  213. let moduleName = variableName;
  214. const parts = variableName.split('/');
  215. if (parts.length > 1) {
  216. parts.pop();
  217. moduleName = parts.join('/');
  218. }
  219. const tensor = new keras.Tensor(variableName, variable.shape, variable.type, null, variable.littleEndian, variable.type === 'string' ? variable.value : variable.data);
  220. weights.add(moduleName, tensor);
  221. return;
  222. }
  223. throw new keras.Error('Module group format is not HDF5 Weights');
  224. };
  225. walk(weightsGroup);
  226. return openModel(format, '', '', null, weights);
  227. }
  228. });
  229. }
  230. case 'keras.json': {
  231. const obj = context.open('json');
  232. const format = 'Keras' + (obj.keras_version ? ' v' + obj.keras_version : '');
  233. const backend = obj.backend || '';
  234. const config = obj.model_config ? obj.model_config : obj;
  235. const weights = new keras.Weights();
  236. return openModel(format, '', backend, config, weights);
  237. }
  238. case 'keras.json.tfjs': {
  239. const obj = context.open('json');
  240. const modelTopology = obj.modelTopology;
  241. const backend = modelTopology.backend || '';
  242. const format = 'TensorFlow.js ' + (obj.format ? obj.format : 'Keras' + (modelTopology.keras_version ? (' v' + modelTopology.keras_version) : ''));
  243. const producer = obj.convertedBy || obj.generatedBy || '';
  244. const manifests = obj.weightsManifest;
  245. for (const manifest of manifests) {
  246. for (const weight of manifest.weights) {
  247. weight.identifier = '';
  248. }
  249. }
  250. const model_config = modelTopology.model_config ? modelTopology.model_config : modelTopology;
  251. return openManifests(manifests).then((weights) => {
  252. return openModel(format, producer, backend, model_config, weights);
  253. });
  254. }
  255. case 'keras.json.tfjs.weights': {
  256. const obj = context.open('json');
  257. const manifests = [];
  258. const format = 'TensorFlow.js Weights';
  259. manifests.push(...obj);
  260. for (const manifest of manifests) {
  261. for (const weight of manifest.weights) {
  262. const parts = weight.name.split('/');
  263. parts.pop();
  264. weight.identifier = parts.join('/');
  265. }
  266. }
  267. return openManifests(manifests).then((weights) => {
  268. return openModel(format, '', '', null, weights);
  269. });
  270. }
  271. default: {
  272. throw new keras.Error("Unsupported Keras format '" + this._format(context) + "'.");
  273. }
  274. }
  275. }
  276. _format(context) {
  277. const stream = context.stream;
  278. const signature = [ 0x89, 0x48, 0x44, 0x46, 0x0D, 0x0A, 0x1A, 0x0A ];
  279. if (stream.length > signature.length && stream.peek(signature.length).every((value, index) => value === signature[index])) {
  280. return 'keras.h5';
  281. }
  282. const obj = context.open('json');
  283. if (obj) {
  284. if (obj.mxnet_version) {
  285. return '';
  286. }
  287. if (obj.nodes && obj.arg_nodes && obj.heads) {
  288. return '';
  289. }
  290. if (obj.modelTopology) {
  291. if (obj.format === 'layers-model' || obj.modelTopology.class_name || obj.modelTopology.model_config) {
  292. return 'keras.json.tfjs';
  293. }
  294. }
  295. if (obj.model_config || (obj.class_name && obj.config)) {
  296. return 'keras.json';
  297. }
  298. if (Array.isArray(obj) && obj.every((item) => item.weights && item.paths)) {
  299. return 'keras.json.tfjs.weights';
  300. }
  301. }
  302. return '';
  303. }
  304. };
  305. keras.Model = class {
  306. constructor(metadata, format, producer, backend, config, weights) {
  307. this._format = format;
  308. this._backend = backend;
  309. this._producer = producer;
  310. this._graphs = [ new keras.Graph(new keras.GraphMetadata(metadata), config, weights) ];
  311. }
  312. get name() {
  313. return null;
  314. }
  315. get description() {
  316. return null;
  317. }
  318. get format() {
  319. return this._format;
  320. }
  321. get producer() {
  322. return this._producer;
  323. }
  324. get runtime() {
  325. return this._backend;
  326. }
  327. get graphs() {
  328. return this._graphs;
  329. }
  330. };
  331. keras.Graph = class {
  332. constructor(metadata, config, weights) {
  333. this._metadata = metadata;
  334. this._inputs = [];
  335. this._outputs = [];
  336. this._nodes = [];
  337. this._groups = false;
  338. if (config) {
  339. this._name = config.name || (config.config && config.config.name ? config.config.name : '');
  340. switch (config.class_name) {
  341. case 'AllCNN':
  342. case 'Sequential':
  343. this._loadSequential(config.config, weights, '', null, null);
  344. break;
  345. case 'Functional':
  346. case 'Model':
  347. this._loadModel(config.config, weights, '', null, null);
  348. break;
  349. default:
  350. throw new keras.Error('\'' + config.class_name + '\' is not supported.');
  351. }
  352. }
  353. else if (weights) {
  354. for (const layer of weights.keys()) {
  355. if (weights.get('', layer).length <= 6) {
  356. const node = new keras.Node(metadata, 'Weights', { name: layer }, [], [], '', weights);
  357. this._nodes.push(node);
  358. }
  359. }
  360. }
  361. }
  362. get name() {
  363. return this._name;
  364. }
  365. get groups() {
  366. return this._groups ? true : false;
  367. }
  368. get inputs() {
  369. return this._inputs;
  370. }
  371. get outputs() {
  372. return this._outputs;
  373. }
  374. get nodes() {
  375. return this._nodes;
  376. }
  377. _loadModel(config, weights, group, inputs, outputs) {
  378. if (group) {
  379. this._groups = true;
  380. }
  381. const nodeMap = new Map();
  382. if (config.layers) {
  383. for (const layer of config.layers) {
  384. layer._inputs = [];
  385. layer._outputs = [];
  386. if (layer.name) {
  387. if (!nodeMap.has(layer.name)) {
  388. nodeMap.set(layer.name, layer);
  389. }
  390. }
  391. }
  392. for (const layer of config.layers) {
  393. if (layer.inbound_nodes) {
  394. for (let inbound_node of layer.inbound_nodes) {
  395. const is_connection = (item) => {
  396. return Array.isArray(item) && (item.length === 3 || item.length === 4) && typeof item[0] === 'string';
  397. };
  398. // wrap
  399. if (is_connection(inbound_node)) {
  400. inbound_node = [ inbound_node ];
  401. }
  402. // unwrap
  403. if (Array.isArray(inbound_node) && inbound_node.every((array) => Array.isArray(array) && array.every((item) => is_connection(item)))) {
  404. inbound_node = inbound_node.flat();
  405. }
  406. for (const inbound_connection of inbound_node) {
  407. let inputName = inbound_connection[0];
  408. const inputNode = nodeMap.get(inputName);
  409. if (inputNode) {
  410. const inputIndex = inbound_connection[2];
  411. if (inputIndex != 0) {
  412. inputName += ':' + inputIndex.toString();
  413. }
  414. while (inputIndex >= inputNode._outputs.length) {
  415. inputNode._outputs.push('');
  416. }
  417. inputNode._outputs[inputIndex] = inputName;
  418. }
  419. layer._inputs.push(inputName);
  420. }
  421. }
  422. }
  423. }
  424. }
  425. const input_layers = config.input_layers;
  426. if (input_layers) {
  427. for (let i = 0; i < input_layers.length; i++) {
  428. const input_layer = input_layers[i];
  429. const name = input_layer[0];
  430. let type = null;
  431. const node = nodeMap.get(name);
  432. if (node && node.class_name == 'InputLayer') {
  433. type = this._getInputType(node);
  434. nodeMap.delete(name);
  435. }
  436. if (inputs && i < inputs.length) {
  437. if (config.layers) {
  438. for (const layer of config.layers) {
  439. if (layer._inputs) {
  440. layer._inputs = layer._inputs.map((input) => {
  441. return input === name ? inputs[i] : input;
  442. });
  443. }
  444. }
  445. }
  446. }
  447. else {
  448. this._inputs.push(new keras.Parameter(name, true, [ new keras.Argument(name, type, null) ]));
  449. }
  450. }
  451. }
  452. const inputMap = new Map();
  453. const output_layers = config.output_layers;
  454. if (output_layers) {
  455. for (let j = 0; j < output_layers.length; j++) {
  456. const output_layer = output_layers[j];
  457. let outputName = output_layer[0];
  458. const outputNode = nodeMap.get(outputName);
  459. let addGraphOutput = true;
  460. if (outputs && j < outputs.length) {
  461. inputMap.set(outputName, outputs[j]);
  462. outputName = outputs[j];
  463. addGraphOutput = false;
  464. }
  465. if (outputNode) {
  466. const outputIndex = output_layer[2];
  467. if (outputIndex != 0) {
  468. outputName += ':' + outputIndex.toString();
  469. }
  470. while (outputIndex >= outputNode._outputs.length) {
  471. outputNode._outputs.push('');
  472. }
  473. outputNode._outputs[outputIndex] = outputName;
  474. }
  475. if (addGraphOutput) {
  476. this._outputs.push(new keras.Parameter(outputName, true, [ new keras.Argument(outputName, null, null) ]));
  477. }
  478. }
  479. }
  480. if (config.layers) {
  481. for (const layer of config.layers) {
  482. if (nodeMap.has(layer.name)) {
  483. this._loadNode(layer, layer._inputs, layer._outputs, weights, group, inputMap);
  484. }
  485. }
  486. }
  487. }
  488. _loadSequential(config, weights, group, inputs, outputs) {
  489. if (group) {
  490. this._groups = true;
  491. }
  492. const inputName = 'input';
  493. let inputType = null;
  494. let argument = inputName;
  495. let index = 0;
  496. const layers = config.layers ? config.layers : config;
  497. for (const layer of layers) {
  498. let name = index.toString();
  499. let nodeInputs = [ argument ];
  500. if (index == 0) {
  501. if (inputs && inputs.length > 0) {
  502. nodeInputs = [ inputs[0] ];
  503. }
  504. else {
  505. inputType = this._getInputType(layer);
  506. }
  507. }
  508. index++;
  509. if (layer.config && layer.config.name) {
  510. name = layer.config.name;
  511. }
  512. argument = name;
  513. let nodeOutputs = [ argument ];
  514. if (index == layers.length) {
  515. if (outputs && outputs.length > 0) {
  516. nodeOutputs = [ outputs[0] ];
  517. argument = null;
  518. }
  519. }
  520. this._loadNode(layer, nodeInputs, nodeOutputs, weights, group);
  521. }
  522. if (!inputs) {
  523. this._inputs.push(new keras.Parameter(inputName, true, [ new keras.Argument(inputName, inputType, null) ]));
  524. }
  525. if (argument) {
  526. this._outputs.push(new keras.Parameter(argument, true, [ new keras.Argument(argument, null, null) ]));
  527. }
  528. }
  529. _loadNode(layer, inputs, outputs, weights, group, inputMap) {
  530. const class_name = layer.class_name;
  531. switch (class_name) {
  532. case 'Sequential': {
  533. const name = layer.name || (layer.config ? layer.config.name : '');
  534. this._loadSequential(layer.config, weights, (group ? group + '/' : '') + name, inputs, outputs);
  535. break;
  536. }
  537. case 'Functional':
  538. case 'Model': {
  539. const name = layer.name || (layer.config ? layer.config.name : '');
  540. this._loadModel(layer.config, weights, (group ? group + '/' : '') + name, inputs, outputs);
  541. break;
  542. }
  543. default: {
  544. inputs = inputs.map((input) => inputMap && inputMap.has(input) ? inputMap.get(input) : input);
  545. const node = new keras.Node(this._metadata, class_name, layer.config, inputs, outputs, group, weights);
  546. this._nodes.push(node);
  547. break;
  548. }
  549. }
  550. }
  551. _getInputType(layer) {
  552. if (layer && layer.config) {
  553. let dataType = '?';
  554. let shape = [];
  555. const config = layer.config;
  556. if (config.dtype) {
  557. dataType = config.dtype;
  558. delete config.dtype;
  559. }
  560. if (config.batch_input_shape) {
  561. shape = config.batch_input_shape.map(s => s == null ? '?' : s);
  562. delete config.batch_input_shape;
  563. }
  564. return new keras.TensorType(dataType, new keras.TensorShape(shape));
  565. }
  566. return null;
  567. }
  568. };
  569. keras.Parameter = class {
  570. constructor(name, visible, args) {
  571. this._name = name;
  572. this._visible = visible;
  573. this._arguments = args;
  574. }
  575. get name() {
  576. return this._name;
  577. }
  578. get visible() {
  579. return this._visible;
  580. }
  581. get arguments() {
  582. return this._arguments;
  583. }
  584. };
  585. keras.Argument = class {
  586. constructor(name, type, initializer) {
  587. if (typeof name !== 'string') {
  588. throw new keras.Error("Invalid argument identifier '" + JSON.stringify(name) + "'.");
  589. }
  590. this._name= name;
  591. this._type = type || null;
  592. this._initializer = initializer || null;
  593. }
  594. get name() {
  595. return this._name;
  596. }
  597. get type() {
  598. if (this._initializer) {
  599. return this._initializer.type;
  600. }
  601. return this._type;
  602. }
  603. get quantization() {
  604. if (this._initializer) {
  605. return this._initializer.quantization;
  606. }
  607. return null;
  608. }
  609. get initializer() {
  610. return this._initializer;
  611. }
  612. };
  613. keras.Node = class {
  614. constructor(metadata, type, config, inputs, outputs, group, weights) {
  615. this._group = group || '';
  616. const name = config && config.name ? config.name : '';
  617. this._name = (this._group ? this._group + '/' : '') + name;
  618. this._inputs = [];
  619. this._outputs = [];
  620. this._attributes = [];
  621. this._chain = [];
  622. let names = [ name ];
  623. if ((type == 'Bidirectional' || type == 'TimeDistributed') && (config && config.layer)) {
  624. const inner = config.layer;
  625. delete config.layer;
  626. this._inner = new keras.Node(metadata, inner.class_name, inner.config, [], [], null, null);
  627. if (type == 'Bidirectional' && inner.config.name) {
  628. names = [ name + '/forward_' + inner.config.name, name + '/backward_' + inner.config.name ];
  629. if (!group) {
  630. group = name;
  631. }
  632. }
  633. }
  634. const initializers = {};
  635. if (weights) {
  636. for (const name of names) {
  637. for (const initializer of weights.get(group, name)) {
  638. inputs.push(initializer.name);
  639. initializers[initializer.name] = initializer;
  640. }
  641. }
  642. }
  643. if (config) {
  644. for (const name of Object.keys(config)) {
  645. const value = config[name];
  646. if (name === 'activation' && value !== 'linear') {
  647. if (typeof value === 'string') {
  648. const set = new Map([ [ 'elu', 'ELU' ], [ 'exponential', 'Exponential' ], [ 'hard_sigmoid', 'HardSigmoid' ], [ 'linear', 'Linear' ], [ 'relu', 'ReLU' ], [ 'selu', 'SELU' ], [ 'softmax', 'Softmax'], [ 'sigmoid', 'Sigmoid' ], [ 'softplus', 'Softplus' ], [ 'softsign', 'Softsign' ], [ 'tanh', 'TanH' ] ]);
  649. const type = set.has(value) ? set.get(value) : value;
  650. this.chain.push(new keras.Node(metadata, type, {}, [], [], null, null));
  651. }
  652. else if (value && typeof value.class_name === 'string' && value.config) {
  653. const type = value.class_name;
  654. if (!metadata.type(type)) {
  655. metadata.add(type, { category: 'Activation' });
  656. }
  657. this.chain.push(new keras.Node(metadata, type, value.config, [], [], null, null));
  658. }
  659. }
  660. if (name !== 'name' && value !== null) {
  661. const attribute = new keras.Attribute(metadata.attribute(type, name), name, value);
  662. this._attributes.push(attribute);
  663. }
  664. }
  665. }
  666. this._type = metadata.type(type) || { name: type };
  667. const innerType = this.inner ? this.inner.type : null;
  668. const innerSchema = innerType ? metadata.type(innerType) : null;
  669. let inputIndex = 0;
  670. while (inputs.length > 0) {
  671. let list = false;
  672. let inputName = null;
  673. let visible = true;
  674. if (!innerSchema || inputIndex == 0) {
  675. if (this._type && this._type.inputs && inputIndex < this._type.inputs.length) {
  676. const input = this._type.inputs[inputIndex];
  677. inputName = input.name;
  678. if (type === 'BatchNormalization' && inputName === 'gamma' && config.scale === false) {
  679. inputIndex++;
  680. continue;
  681. }
  682. visible = input.visible == false ? false : true;
  683. if (this._type.inputs[inputIndex].list) {
  684. list = true;
  685. }
  686. }
  687. }
  688. else {
  689. switch (type) {
  690. case 'Bidirectional': {
  691. let innerIndex = inputIndex;
  692. if (innerSchema && innerSchema.inputs) {
  693. if (innerIndex < innerSchema.inputs.length) {
  694. inputName = 'forward_' + innerSchema.inputs[innerIndex].name;
  695. }
  696. else {
  697. innerIndex = innerIndex - innerSchema.inputs.length + 1;
  698. if (innerIndex < innerSchema.inputs.length) {
  699. inputName = 'backward_' + innerSchema.inputs[innerIndex].name;
  700. }
  701. }
  702. }
  703. visible = false;
  704. break;
  705. }
  706. case 'TimeDistributed':
  707. if (innerSchema && innerSchema.inputs && inputIndex < innerSchema.inputs.length) {
  708. inputName = innerSchema.inputs[inputIndex].name;
  709. }
  710. break;
  711. }
  712. }
  713. const input = !list ? [ inputs.shift() ] : inputs.splice(0, inputs.length);
  714. const inputArguments = input.map((id) => {
  715. if (typeof id === 'string') {
  716. return new keras.Argument(id, null, initializers[id]);
  717. }
  718. if (Array.isArray(id) && id.every((item) => Array.isArray(item) && item.length === 4 && item[0] === '_CONSTANT_VALUE' && item[1] === -1)) {
  719. return new keras.Argument('', null, new keras.Tensor());
  720. }
  721. throw new keras.Error("Invalid argument '" + JSON.stringify(id) + "'.");
  722. });
  723. if (!inputName && inputArguments.length == 1 && inputArguments[0].initializer && inputArguments[0].initializer.name) {
  724. if (names.length === 1 && names[0] === '') {
  725. inputName = inputArguments[0].initializer.name;
  726. }
  727. else {
  728. const parts = inputArguments[0].initializer.name.split('/').pop().split(':').shift().split('_');
  729. const inputName1 = parts.pop();
  730. const inputName2 = parts.length > 0 ? [ parts.pop(), inputName1 ].join('_') : '';
  731. const inputNames = new Set([ 'recurrent_kernel', 'running_mean', 'running_std', 'moving_mean', 'moving_variance', 'depthwise_filter', 'pointwise_filter' ]);
  732. inputName = inputNames.has(inputName2) ? inputName2 : inputName1;
  733. }
  734. }
  735. this._inputs.push(new keras.Parameter(inputName || inputIndex.toString(), visible, inputArguments));
  736. inputIndex++;
  737. }
  738. this._outputs = outputs.map((output, outputIndex) => {
  739. const outputName =
  740. (this._type && this._type.outputs && outputIndex < this._type.outputs.length && this._type.outputs[outputIndex] && this._type.outputs[outputIndex].name) ?
  741. this._type.outputs[outputIndex].name :
  742. outputIndex.toString();
  743. return new keras.Parameter(outputName, true, [ new keras.Argument(output, null, null) ]);
  744. });
  745. if (typeof this.type.name !== 'string' || !this.type.name.split) { // #416
  746. throw new keras.Error("Unknown node type '" + JSON.stringify(this.type.name) + "'.");
  747. }
  748. }
  749. get type() {
  750. return this._type;
  751. }
  752. get name() {
  753. return this._name;
  754. }
  755. get group() {
  756. return this._group;
  757. }
  758. get inputs() {
  759. return this._inputs;
  760. }
  761. get outputs() {
  762. return this._outputs;
  763. }
  764. get attributes() {
  765. return this._attributes;
  766. }
  767. get chain() {
  768. return this._chain;
  769. }
  770. get inner() {
  771. return this._inner;
  772. }
  773. };
  774. keras.Attribute = class {
  775. constructor(metadata, name, value) {
  776. this._name = name;
  777. this._value = value;
  778. if (typeof value == 'object' && value.class_name && value.config) {
  779. this._value = keras.Attribute._convert(value);
  780. }
  781. switch (name) {
  782. case 'trainable':
  783. this._type = 'boolean';
  784. this._visible = false;
  785. break;
  786. case 'dtype':
  787. this._visible = false;
  788. break;
  789. default: {
  790. if (metadata) {
  791. if (metadata.type) {
  792. this._type = metadata.type;
  793. }
  794. if (Object.prototype.hasOwnProperty.call(metadata, 'visible')) {
  795. this._visible = metadata.visible;
  796. }
  797. else if (Object.prototype.hasOwnProperty.call(metadata, 'default')) {
  798. if (keras.Attribute._isEquivalent(metadata.default, value)) {
  799. this._visible = false;
  800. }
  801. }
  802. }
  803. break;
  804. }
  805. }
  806. }
  807. get name() {
  808. return this._name;
  809. }
  810. get type() {
  811. return this._type;
  812. }
  813. get value() {
  814. return this._value;
  815. }
  816. get visible() {
  817. return this._visible == false ? false : true;
  818. }
  819. static _convert(value) {
  820. if (Array.isArray(value) || value !== Object(value)) {
  821. return value;
  822. }
  823. const obj = {};
  824. if (value.class_name) {
  825. obj.__type__ = value.class_name;
  826. }
  827. for (const key of Object.keys(value.config)) {
  828. obj[key] = keras.Attribute._convert(value.config[key]);
  829. }
  830. return obj;
  831. }
  832. static _isEquivalent(a, b) {
  833. if (a === b) {
  834. return a !== 0 || 1 / a === 1 / b;
  835. }
  836. if (a == null || b == null) {
  837. return false;
  838. }
  839. if (a !== a) {
  840. return b !== b;
  841. }
  842. const type = typeof a;
  843. if (type !== 'function' && type !== 'object' && typeof b != 'object') {
  844. return false;
  845. }
  846. const className = toString.call(a);
  847. if (className !== toString.call(b)) {
  848. return false;
  849. }
  850. switch (className) {
  851. case '[object RegExp]':
  852. case '[object String]':
  853. return '' + a === '' + b;
  854. case '[object Number]':
  855. if (+a !== +a) {
  856. return +b !== +b;
  857. }
  858. return +a === 0 ? 1 / +a === 1 / b : +a === +b;
  859. case '[object Date]':
  860. case '[object Boolean]':
  861. return +a === +b;
  862. case '[object Array]': {
  863. let length = a.length;
  864. if (length !== b.length) {
  865. return false;
  866. }
  867. while (length--) {
  868. if (!keras.Attribute._isEquivalent(a[length], b[length])) {
  869. return false;
  870. }
  871. }
  872. return true;
  873. }
  874. }
  875. const keys = Object.keys(a);
  876. let size = keys.length;
  877. if (Object.keys(b).length != size) {
  878. return false;
  879. }
  880. while (size--) {
  881. const key = keys[size];
  882. if (!(Object.prototype.hasOwnProperty.call(b, key) && keras.Attribute._isEquivalent(a[key], b[key]))) {
  883. return false;
  884. }
  885. }
  886. return true;
  887. }
  888. };
  889. keras.Tensor = class {
  890. constructor(name, shape, type, quantization, littleEndian, data) {
  891. this._name = name;
  892. this._type = new keras.TensorType(type, new keras.TensorShape(shape));
  893. this._quantization = quantization;
  894. this._littleEndian = littleEndian;
  895. this._data = data;
  896. }
  897. get kind() {
  898. return 'Weights';
  899. }
  900. get name() {
  901. return this._name;
  902. }
  903. get type() {
  904. return this._type;
  905. }
  906. get quantization() {
  907. if (this._quantization && (this._quantization.scale !== 0 || this._quantization.min !== 0)) {
  908. const scale = this._quantization.scale || 0;
  909. const min = this._quantization.min || 0;
  910. return scale.toString() + ' * ' + (min == 0 ? 'q' : ('(q - ' + min.toString() + ')'));
  911. }
  912. return null;
  913. }
  914. get state() {
  915. return this._context().state;
  916. }
  917. get value() {
  918. const context = this._context();
  919. if (context.state) {
  920. return null;
  921. }
  922. context.limit = Number.MAX_SAFE_INTEGER;
  923. return this._decode(context, 0);
  924. }
  925. toString() {
  926. const context = this._context();
  927. if (context.state) {
  928. return '';
  929. }
  930. context.limit = 10000;
  931. const value = this._decode(context, 0);
  932. return keras.Tensor._stringify(value, '', ' ');
  933. }
  934. _context() {
  935. const context = {};
  936. context.index = 0;
  937. context.count = 0;
  938. context.state = null;
  939. if (!this._data) {
  940. context.state = 'Tensor data is empty.';
  941. return context;
  942. }
  943. switch (this._type.dataType) {
  944. case 'boolean':
  945. case 'float16':
  946. case 'float32':
  947. case 'float64':
  948. case 'uint8':
  949. case 'int32':
  950. case 'int64':
  951. context.dataType = this._type.dataType;
  952. context.data = new DataView(this._data.buffer, this._data.byteOffset, this._data.byteLength);
  953. context.littleEndian = this._littleEndian;
  954. break;
  955. case 'string':
  956. context.dataType = this._type.dataType;
  957. context.data = this._data;
  958. break;
  959. default:
  960. context.state = 'Tensor data type is not supported.';
  961. break;
  962. }
  963. context.shape = this._type.shape.dimensions;
  964. return context;
  965. }
  966. _decode(context, dimension) {
  967. const shape = context.shape.length !== 0 ? context.shape : [ 1 ];
  968. const results = [];
  969. const size = shape[dimension];
  970. const littleEndian = context.littleEndian;
  971. if (dimension == shape.length - 1) {
  972. for (let i = 0; i < size; i++) {
  973. if (context.count > context.limit) {
  974. results.push(null);
  975. return results;
  976. }
  977. switch (context.dataType) {
  978. case 'float16':
  979. results.push(context.data.getFloat16(context.index, littleEndian));
  980. context.index += 2;
  981. break;
  982. case 'float32':
  983. results.push(context.data.getFloat32(context.index, littleEndian));
  984. context.index += 4;
  985. break;
  986. case 'float64':
  987. results.push(context.data.getFloat64(context.index, littleEndian));
  988. context.index += 8;
  989. break;
  990. case 'boolean':
  991. results.push(context.data.getInt8(context.index) !== 0);
  992. context.index += 1;
  993. break;
  994. case 'uint8':
  995. results.push(context.data.getUint8(context.index));
  996. context.index += 1;
  997. break;
  998. case 'int32':
  999. results.push(context.data.getInt32(context.index, littleEndian));
  1000. context.index += 4;
  1001. break;
  1002. case 'int64':
  1003. results.push(context.data.getInt64(context.index, littleEndian));
  1004. context.index += 8;
  1005. break;
  1006. case 'string':
  1007. results.push(context.data[context.index]);
  1008. context.index++;
  1009. break;
  1010. }
  1011. context.count++;
  1012. }
  1013. }
  1014. else {
  1015. for (let j = 0; j < size; j++) {
  1016. if (context.count > context.limit) {
  1017. results.push(null);
  1018. return results;
  1019. }
  1020. results.push(this._decode(context, dimension + 1));
  1021. }
  1022. }
  1023. if (context.shape.length == 0) {
  1024. return results[0];
  1025. }
  1026. return results;
  1027. }
  1028. static _stringify(value, indentation, indent) {
  1029. if (Array.isArray(value)) {
  1030. const result = [];
  1031. result.push(indentation + '[');
  1032. const items = value.map((item) => keras.Tensor._stringify(item, indentation + indent, indent));
  1033. if (items.length > 0) {
  1034. result.push(items.join(',\n'));
  1035. }
  1036. result.push(indentation + ']');
  1037. return result.join('\n');
  1038. }
  1039. if (value === null) {
  1040. return indentation + '...';
  1041. }
  1042. if (typeof value == 'string') {
  1043. return indentation + '"' + value + '"';
  1044. }
  1045. if (value == Infinity) {
  1046. return indentation + 'Infinity';
  1047. }
  1048. if (value == -Infinity) {
  1049. return indentation + '-Infinity';
  1050. }
  1051. if (isNaN(value)) {
  1052. return indentation + 'NaN';
  1053. }
  1054. return indentation + value.toString();
  1055. }
  1056. };
  1057. keras.TensorType = class {
  1058. constructor(dataType, shape) {
  1059. this._dataType = dataType;
  1060. this._shape = shape;
  1061. }
  1062. get dataType() {
  1063. return this._dataType;
  1064. }
  1065. get shape() {
  1066. return this._shape;
  1067. }
  1068. toString() {
  1069. return this._dataType + this._shape.toString();
  1070. }
  1071. };
  1072. keras.TensorShape = class {
  1073. constructor(dimensions) {
  1074. this._dimensions = dimensions;
  1075. }
  1076. get dimensions() {
  1077. return this._dimensions;
  1078. }
  1079. toString() {
  1080. return this._dimensions ? ('[' + this._dimensions.map((dimension) => dimension.toString()).join(',') + ']') : '';
  1081. }
  1082. };
  1083. keras.GraphMetadata = class {
  1084. constructor(metadata) {
  1085. this._metadata = metadata;
  1086. this._map = new Map();
  1087. }
  1088. type(name) {
  1089. if (this._map.has(name)) {
  1090. return this._map.get(name);
  1091. }
  1092. return this._metadata.type(name);
  1093. }
  1094. attribute(type, name) {
  1095. return this._metadata.attribute(type, name);
  1096. }
  1097. add(type, metadata) {
  1098. this._map.set(type, metadata);
  1099. }
  1100. };
  1101. keras.Metadata = class {
  1102. static open(context) {
  1103. if (keras.Metadata._metadata) {
  1104. return Promise.resolve(keras.Metadata._metadata);
  1105. }
  1106. return context.request('keras-metadata.json', 'utf-8', null).then((data) => {
  1107. keras.Metadata._metadata = new keras.Metadata(data);
  1108. return keras.Metadata._metadata;
  1109. }).catch(() => {
  1110. keras.Metadata._metadata = new keras.Metadata(null);
  1111. return keras.Metadata._metadatas;
  1112. });
  1113. }
  1114. constructor(data) {
  1115. this._map = new Map();
  1116. this._attributeCache = new Map();
  1117. if (data) {
  1118. const metadata = JSON.parse(data);
  1119. this._map = new Map(metadata.map((item) => [ item.name, item ]));
  1120. }
  1121. }
  1122. type(name) {
  1123. return this._map.get(name);
  1124. }
  1125. attribute(type, name) {
  1126. const key = type + ':' + name;
  1127. if (!this._attributeCache.has(key)) {
  1128. const schema = this.type(type);
  1129. if (schema && schema.attributes && schema.attributes.length > 0) {
  1130. for (const attribute of schema.attributes) {
  1131. this._attributeCache.set(type + ':' + attribute.name, attribute);
  1132. }
  1133. }
  1134. if (!this._attributeCache.has(key)) {
  1135. this._attributeCache.set(key, null);
  1136. }
  1137. }
  1138. return this._attributeCache.get(key);
  1139. }
  1140. };
  1141. keras.Weights = class {
  1142. constructor() {
  1143. this._map = new Map();
  1144. }
  1145. add(layer_name, tensor) {
  1146. if (!this._map.has(layer_name)) {
  1147. this._map.set(layer_name, []);
  1148. }
  1149. this._map.get(layer_name).push(tensor);
  1150. }
  1151. get(group, name) {
  1152. if (group) {
  1153. const list = this._map.get(group.split('/').shift());
  1154. if (list) {
  1155. const match1 = list.filter((tensor) => tensor.name.startsWith(name + '/'));
  1156. if (match1.length > 0) {
  1157. return match1;
  1158. }
  1159. const match2 = list.filter((tensor) => tensor.name.startsWith(group + '/' + name + '/'));
  1160. if (match2.length > 0) {
  1161. return match2;
  1162. }
  1163. }
  1164. }
  1165. else {
  1166. const match1 = this._map.get(name);
  1167. if (match1 && match1.length > 0) {
  1168. return match1;
  1169. }
  1170. const match2 = this._map.get('');
  1171. if (match2 && match2.length > 0) {
  1172. const match3 = match2.filter((tensor) => tensor.name.startsWith((group ? group + '/' : '') + name + '/'));
  1173. if (match3.length > 0) {
  1174. return match3;
  1175. }
  1176. }
  1177. }
  1178. return [];
  1179. }
  1180. keys() {
  1181. return this._map.keys();
  1182. }
  1183. };
  1184. keras.Error = class extends Error {
  1185. constructor(message) {
  1186. super(message);
  1187. this.name = 'Error loading Keras model.';
  1188. }
  1189. };
  1190. if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  1191. module.exports.ModelFactory = keras.ModelFactory;
  1192. }