keras.js 51 KB

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