cntk.js 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135
  1. const cntk = {};
  2. cntk.ModelFactory = class {
  3. async match(context) {
  4. const stream = context.stream;
  5. // CNTK v1
  6. const signature = [0x42, 0x00, 0x43, 0x00, 0x4e, 0x00, 0x00, 0x00];
  7. if (stream && signature.length <= stream.length && stream.peek(signature.length).every((value, index) => value === signature[index])) {
  8. return context.set('cntk.v1');
  9. }
  10. // CNTK v2
  11. const tags = await context.tags('pb');
  12. if (tags.get(1) === 0 && tags.get(2) === 2) {
  13. return context.set('cntk.v2');
  14. }
  15. return null;
  16. }
  17. async open(context) {
  18. const metadata = await context.metadata('cntk-metadata.json');
  19. switch (context.type) {
  20. case 'cntk.v1': {
  21. let obj = null;
  22. try {
  23. const reader = await context.read('binary');
  24. obj = new cntk.ComputationNetwork(reader);
  25. } catch (error) {
  26. const message = error && error.message ? error.message : error.toString();
  27. throw new cntk.Error(`File format is not CNTK v1 (${message.replace(/\.$/, '')}).`);
  28. }
  29. return new cntk.Model(metadata, 1, obj);
  30. }
  31. case 'cntk.v2': {
  32. cntk.proto = await context.require('./cntk-proto');
  33. cntk.proto = cntk.proto.CNTK.proto;
  34. cntk.proto.PoolingType = { 0: 'Max', 1: 'Average' };
  35. let obj = null;
  36. try {
  37. const reader = await context.read('protobuf.binary');
  38. const dictionary = cntk.proto.Dictionary.decode(reader);
  39. obj = cntk.ModelFactory._convertDictionary(dictionary);
  40. } catch (error) {
  41. const message = error && error.message ? error.message : error.toString();
  42. throw new cntk.Error(`File format is not cntk.Dictionary (${message.replace(/\.$/, '')}).`);
  43. }
  44. return new cntk.Model(metadata, 2, obj);
  45. }
  46. default: {
  47. throw new cntk.Error(`Unsupported CNTK format '${context.type}'.`);
  48. }
  49. }
  50. }
  51. static _convertDictionary(dictionary) {
  52. const target = {};
  53. for (const key of Object.keys(dictionary.data).filter((key) => key !== 'version')) {
  54. target[key] = cntk.ModelFactory._convertDictionaryValue(dictionary.data[key]);
  55. }
  56. return target;
  57. }
  58. static _convertDictionaryValue(dictionaryValue) {
  59. switch (dictionaryValue.value_type) {
  60. case cntk.proto.DictionaryValue.Type.Bool:
  61. return dictionaryValue.bool_value;
  62. case cntk.proto.DictionaryValue.Type.Int:
  63. return dictionaryValue.int_value;
  64. case cntk.proto.DictionaryValue.Type.SizeT:
  65. return dictionaryValue.size_t_value;
  66. case cntk.proto.DictionaryValue.Type.Float:
  67. return dictionaryValue.float_value;
  68. case cntk.proto.DictionaryValue.Type.Double:
  69. return dictionaryValue.double_value;
  70. case cntk.proto.DictionaryValue.Type.String:
  71. return dictionaryValue.string_value;
  72. case cntk.proto.DictionaryValue.Type.Vector:
  73. return cntk.ModelFactory._convertVectorValue(dictionaryValue.vector_value);
  74. case cntk.proto.DictionaryValue.Type.NDShape:
  75. return dictionaryValue.nd_shape_value;
  76. case cntk.proto.DictionaryValue.Type.Axis:
  77. return dictionaryValue.axis_value;
  78. case cntk.proto.DictionaryValue.Type.Dictionary:
  79. return cntk.ModelFactory._convertDictionary(dictionaryValue.dictionary_value);
  80. case cntk.proto.DictionaryValue.Type.NDArrayView:
  81. return dictionaryValue.nd_array_view_value;
  82. default:
  83. throw new cntk.Error(`Unsupported dictionary value type '${dictionaryValue.value_type}'.`);
  84. }
  85. }
  86. static _convertVectorValue(vectorValue) {
  87. return vectorValue.value.map((item) => {
  88. return cntk.ModelFactory._convertDictionaryValue(item);
  89. });
  90. }
  91. };
  92. cntk.Model = class {
  93. constructor(metadata, version, obj) {
  94. switch (version) {
  95. case 1:
  96. this.format = `CNTK v1${obj.version ? (`.${obj.version}`) : ''}`;
  97. break;
  98. case 2:
  99. this.format = 'CNTK v2';
  100. break;
  101. default:
  102. throw new cntk.Error(`Unsupported CNTK version '${version}'.`);
  103. }
  104. this.modules = [new cntk.Graph(metadata, version, obj)];
  105. }
  106. };
  107. cntk.Graph = class {
  108. constructor(metadata, version, obj) {
  109. metadata = new cntk.GraphMetadata(metadata);
  110. this.inputs = [];
  111. this.outputs = [];
  112. this.nodes = [];
  113. const values = new Map();
  114. values.map = (name, version, obj) => {
  115. if (obj && values.has(name)) {
  116. throw new cntk.Error(`Duplicate value '${name}'.`);
  117. }
  118. if (!values.has(name)) {
  119. switch (version) {
  120. case 1:
  121. values.set(name, new cntk.Value(version, obj ? obj : { name }));
  122. break;
  123. case 2:
  124. values.set(name, new cntk.Value(version, obj ? obj : { uid: name }));
  125. break;
  126. default:
  127. throw new cntk.Error(`Unsupported CNTK version '${version}'.`);
  128. }
  129. }
  130. return values.get(name);
  131. };
  132. switch (version) {
  133. case 1: {
  134. for (const name of Object.keys(obj.nodes)) {
  135. const node = obj.nodes[name];
  136. switch (node.__type__) {
  137. case 'InputValue': {
  138. const argument = new cntk.Argument(node.name, [values.map(node.name, version, node)]);
  139. this.inputs.push(argument);
  140. break;
  141. }
  142. case 'LearnableParameter': {
  143. values.map(node.name, version, node);
  144. break;
  145. }
  146. default:
  147. break;
  148. }
  149. }
  150. for (const name of Object.keys(obj.nodes)) {
  151. const node = obj.nodes[name];
  152. if (node.__type__ !== 'InputValue' && node.__type__ !== 'LearnableParameter') {
  153. this.nodes.push(new cntk.Node(metadata, version, node, values));
  154. }
  155. }
  156. if (obj.output) {
  157. for (const output of obj.output) {
  158. const argument = new cntk.Argument(output, [values.map(output, version)]);
  159. this.outputs.push(argument);
  160. }
  161. }
  162. break;
  163. }
  164. case 2: {
  165. const map = new Map(obj.primitive_functions.map((node) => [node.uid, node]));
  166. for (const input of obj.inputs) {
  167. const value = values.map(input.uid, version, input);
  168. // VariableKind { 0: 'input', 1: 'output', 2: 'parameter', 3: 'constant', 4: 'placeholder' }
  169. if (input.kind === 0n) {
  170. const inputName = input.name || input.uid;
  171. this.inputs.push(new cntk.Argument(inputName, [value]));
  172. }
  173. }
  174. for (const block of obj.primitive_functions) {
  175. if (block.op === 57n && block.block_function_composite) {
  176. const list = [block.block_function_composite.root];
  177. const output = map.get(block.block_function_composite.root);
  178. const keys = block.block_function_composite_arguments_map_keys;
  179. const args = block.block_function_composite_arguments_map_values;
  180. block.inputs = args;
  181. if (!Array.isArray(keys) || !Array.isArray(args) || keys.length !== args.length) {
  182. throw new cntk.Error('Invalid block function composite arguments.');
  183. }
  184. const inputs = keys.map((key) => new cntk.Argument(key, [values.map(key, version)]));
  185. const outputs = [new cntk.Argument('output', [values.map(`${output.uid}_Output_0`, version)])];
  186. const nodes = [];
  187. while (list.length > 0) {
  188. const name = list.shift();
  189. if (map.has(name)) {
  190. const node = map.get(name);
  191. nodes.push(new cntk.Node(metadata, version, node, values));
  192. map.delete(name);
  193. for (let i = 0; i < node.inputs.length; i++) {
  194. const parts = node.inputs[i].split('_');
  195. if (parts.length >= 3) {
  196. parts.pop();
  197. if (parts.pop() === 'Output') {
  198. list.push(parts.join('_'));
  199. }
  200. }
  201. }
  202. }
  203. }
  204. const func = new cntk.Function(block.block_function_op_name, nodes, inputs, outputs);
  205. metadata.add(block.uid, func);
  206. }
  207. }
  208. for (const node of map.values()) {
  209. this.nodes.push(new cntk.Node(metadata, version, node, values));
  210. }
  211. break;
  212. }
  213. default: {
  214. throw new cntk.Error(`Unsupported graph version '${version}'.`);
  215. }
  216. }
  217. }
  218. };
  219. cntk.Argument = class {
  220. constructor(name, value, type = null, visible = true) {
  221. this.name = name;
  222. this.value = value;
  223. this.type = type;
  224. this.visible = visible;
  225. }
  226. };
  227. cntk.Value = class {
  228. constructor(version, obj) {
  229. switch (version) {
  230. case 1:
  231. switch (obj.__type__) {
  232. case 'InputValue':
  233. this.name = obj.name;
  234. this.type = new cntk.TensorType(version, obj.precision, obj.sampleLayout);
  235. this.initializer = null;
  236. break;
  237. case 'LearnableParameter':
  238. this.name = obj.name;
  239. this.initializer = new cntk.Tensor(version, obj);
  240. this.type = this.initializer.type;
  241. break;
  242. default:
  243. this.name = obj.name;
  244. this.type = null;
  245. this.initializer = null;
  246. break;
  247. }
  248. break;
  249. case 2:
  250. if (obj.value) {
  251. this.name = obj.name || obj.uid;
  252. this.initializer = new cntk.Tensor(version, obj);
  253. this.type = this.initializer.type;
  254. } else {
  255. this.name = obj.uid;
  256. if (obj.data_type && obj.shape) {
  257. this.type = new cntk.TensorType(version, obj.data_type, obj.shape);
  258. }
  259. this.initializer = null;
  260. }
  261. break;
  262. default:
  263. throw new cntk.Error(`Unsupported CNTK version '${version}'.`);
  264. }
  265. }
  266. };
  267. cntk.Node = class {
  268. constructor(metadata, version, obj, values) {
  269. this.attributes = [];
  270. this.inputs = [];
  271. this.outputs = [];
  272. let inputs = [];
  273. let outputs = [];
  274. const attributes = [];
  275. switch (version) {
  276. case 1: {
  277. const type = obj.__type__;
  278. this.type = { name: type, ...metadata.type(type) };
  279. delete this.type.identifier;
  280. this.name = obj.name;
  281. for (const [name, value] of Object.entries(obj)) {
  282. if (name !== '__type__' && name !== 'name' && name !== 'inputs' && name !== 'precision') {
  283. const schema = metadata.attribute(type, name);
  284. attributes.push([schema, name, value]);
  285. }
  286. }
  287. inputs = obj.inputs.map((input) => values.map(input, version));
  288. outputs = [values.map(this.name, version)];
  289. break;
  290. }
  291. case 2: {
  292. this.name = obj.name || obj.uid || null;
  293. const output = obj.uid;
  294. if (obj.op === 57n) {
  295. this.type = { name: obj.uid, ...metadata.type(obj.uid) };
  296. delete this.type.identifier;
  297. } else if (Object.prototype.hasOwnProperty.call(obj, 'op')) {
  298. // cntk/Source/CNTKv2LibraryDll/API/Internals/PrimitiveOpType.h
  299. const op = obj.op.toNumber();
  300. this.type = { ...metadata.type(op) };
  301. delete this.type.identifier;
  302. } else {
  303. const type = obj.type;
  304. this.type = { name: type, ...metadata.type(type) };
  305. delete this.type.identifier;
  306. if (obj.user_defined_state) {
  307. for (const [name, value] of Object.entries(obj.user_defined_state)) {
  308. const schema = metadata.attribute(type, name);
  309. attributes.push([schema, name, value]);
  310. }
  311. }
  312. }
  313. if (obj.attributes) {
  314. for (const [name, value] of Object.entries(obj.attributes)) {
  315. const schema = metadata.attribute(this.type, name);
  316. attributes.push([schema, name, value]);
  317. }
  318. }
  319. inputs = obj.inputs.map((input) => values.map(input, version));
  320. outputs.push(values.map(`${output}_Output_0`, version));
  321. break;
  322. }
  323. default: {
  324. throw new cntk.Error(`Unsupported CNTK version '${version}'.`);
  325. }
  326. }
  327. let inputIndex = 0;
  328. if (this.type && this.type.inputs) {
  329. for (const schema of this.type.inputs) {
  330. if (inputIndex < inputs.length || schema.option !== 'optional') {
  331. const count = schema.type === 'Tensor[]' ? (inputs.length - inputIndex) : 1;
  332. const values = [];
  333. for (const value of inputs.slice(inputIndex, inputIndex + count)) {
  334. if (value.name !== '' || schema.option !== 'optional') {
  335. values.push(value);
  336. }
  337. }
  338. const argument = new cntk.Argument(schema.name, values);
  339. this.inputs.push(argument);
  340. inputIndex += count;
  341. }
  342. }
  343. }
  344. this.inputs.push(...inputs.slice(inputIndex).map((argument, index) => {
  345. return new cntk.Argument((inputIndex + index).toString(), [argument]);
  346. }));
  347. let outputIndex = 0;
  348. if (this.type && this.type.outputs) {
  349. for (const schema of this.type.outputs) {
  350. if (outputIndex < outputs.length || !schema.optional) {
  351. const count = schema.type === 'Tensor[]' ? (outputs.length - outputIndex) : 1;
  352. const values = outputs.slice(outputIndex, outputIndex + count);
  353. const argument = new cntk.Argument(schema.name, values);
  354. this.outputs.push(argument);
  355. outputIndex += count;
  356. }
  357. }
  358. }
  359. this.outputs.push(...outputs.slice(outputIndex).map((argument) => {
  360. return new cntk.Argument(outputIndex.toString(), [argument]);
  361. }));
  362. this.attributes = attributes.map(([metadata, name, value]) => {
  363. let type = null;
  364. let visible = true;
  365. if (value && value.__type__ === 'shape') {
  366. value = new cntk.TensorShape(1, value);
  367. type = 'shape';
  368. }
  369. if (cntk.proto && value instanceof cntk.proto.NDShape) {
  370. value = new cntk.TensorShape(2, value);
  371. type = 'shape';
  372. }
  373. if (cntk.proto && value instanceof cntk.proto.Axis) {
  374. const axis = { __type__: 'Axis' };
  375. for (const key of Object.keys(value).filter((key) => key !== 'name')) {
  376. axis[key] = value[key];
  377. }
  378. value = axis;
  379. }
  380. if (metadata) {
  381. if (metadata.type) {
  382. type = metadata.type;
  383. const table = cntk[type] || cntk.proto[type];
  384. if (table && table[value]) {
  385. value = table[value];
  386. }
  387. }
  388. if (metadata.visible === false) {
  389. visible = false;
  390. } else if (metadata.default !== undefined) {
  391. let defaultValue = metadata.default;
  392. if (typeof value === 'function') {
  393. value = value();
  394. }
  395. if (type === 'shape') {
  396. value = value.dimensions;
  397. }
  398. if (value === defaultValue) {
  399. visible = false;
  400. } else if (Array.isArray(value) && Array.isArray(defaultValue)) {
  401. defaultValue = defaultValue.slice(0, defaultValue.length);
  402. if (defaultValue.length > 1 && defaultValue[defaultValue.length - 1] === null) {
  403. defaultValue.pop();
  404. while (defaultValue.length < value.length) {
  405. defaultValue.push(defaultValue[defaultValue.length - 1]);
  406. }
  407. }
  408. if (value.every((item, index) => item === defaultValue[index])) {
  409. visible = false;
  410. }
  411. }
  412. }
  413. }
  414. return new cntk.Argument(name, value, type, visible);
  415. });
  416. }
  417. };
  418. cntk.Tensor = class {
  419. constructor(version, tensor) {
  420. this.encoding = '|';
  421. this.values = null;
  422. switch (version) {
  423. case 1: {
  424. if (tensor.__type__ === 'LearnableParameter') {
  425. this.name = tensor.name || null;
  426. this.type = new cntk.TensorType(version, tensor.precision, tensor.sampleLayout);
  427. }
  428. break;
  429. }
  430. case 2: {
  431. this.name = tensor.name || tensor.uid || null;
  432. this.type = new cntk.TensorType(version, tensor.data_type, tensor.shape);
  433. const value = tensor.value;
  434. if (this.type.dataType === 'float32' && value && value.float_values && value.float_values.value && value.float_values.value.length > 0) {
  435. this.values = value.float_values.value;
  436. }
  437. break;
  438. }
  439. default:
  440. throw new cntk.Error(`Unsupported CNTK version '${version}'.`);
  441. }
  442. }
  443. };
  444. cntk.TensorType = class {
  445. constructor(version, dataType, shape) {
  446. this.dataType = '?';
  447. switch (version) {
  448. case 1:
  449. switch (dataType) {
  450. case 'float': this.dataType = 'float32'; break;
  451. case 'double': this.dataType = 'float64'; break;
  452. case 'half': this.dataType = 'float16'; break;
  453. case '': this.dataType = 'float32'; break;
  454. default: throw new cntk.Error(`Unsupported tensor data type '${dataType}'.`);
  455. }
  456. this.shape = new cntk.TensorShape(version, shape);
  457. break;
  458. case 2:
  459. switch (dataType) {
  460. case 1n: this.dataType = 'float32'; break;
  461. default: throw new cntk.Error(`Unsupported tensor data type '${dataType}'.`);
  462. }
  463. this.shape = new cntk.TensorShape(version, shape);
  464. break;
  465. default:
  466. throw new cntk.Error(`Unsupported CNTK version '${version}'.`);
  467. }
  468. }
  469. toString() {
  470. return this.dataType + this.shape.toString();
  471. }
  472. };
  473. cntk.TensorShape = class {
  474. constructor(version, shape) {
  475. switch (version) {
  476. case 1:
  477. this.dimensions = shape.dims;
  478. break;
  479. case 2:
  480. this.dimensions = shape.shape_dim.map((dimension) => dimension.toNumber());
  481. break;
  482. default:
  483. throw new cntk.Error(`Unsupported CNTK version '${version}'.`);
  484. }
  485. }
  486. toString() {
  487. return (this.dimensions && this.dimensions.length) ? (`[${this.dimensions.join(',')}]`) : '';
  488. }
  489. };
  490. cntk.Function = class {
  491. constructor(name, nodes, inputs, outputs) {
  492. this.type = 'function';
  493. this.name = name;
  494. this.inputs = inputs;
  495. this.outputs = outputs;
  496. this.nodes = nodes;
  497. switch (this.name) {
  498. case 'PReLU':
  499. case 'Softmax':
  500. this.category = 'Activation';
  501. break;
  502. case 'Dropout':
  503. this.category = 'Dropout';
  504. break;
  505. case 'Convolution':
  506. case 'ConvolutionTranspose':
  507. case 'Dense':
  508. case 'linear':
  509. case 'LSTM':
  510. this.category = 'Layer';
  511. break;
  512. case 'BatchNormalization':
  513. case 'lrn':
  514. this.category = 'Normalization';
  515. break;
  516. case 'AveragePooling':
  517. case 'MaxPooling':
  518. this.category = 'Pool';
  519. break;
  520. default:
  521. this.category = null;
  522. break;
  523. }
  524. }
  525. };
  526. cntk.GraphMetadata = class {
  527. constructor(metadata) {
  528. this._metadata = metadata;
  529. this._functions = new Map();
  530. this._attributes = new Map();
  531. }
  532. add(name, func) {
  533. if (this._functions.has(name)) {
  534. throw new cntk.Error(`Duplicate function identifier '${func.name}'.`);
  535. }
  536. this._functions.set(name, func);
  537. }
  538. name(code) {
  539. // cntk/Source/CNTKv2LibraryDll/API/Internals/PrimitiveOpType.h
  540. return this._metadata.name(code);
  541. }
  542. type(name) {
  543. if (this._functions.has(name)) {
  544. return this._functions.get(name);
  545. }
  546. return this._metadata.type(name);
  547. }
  548. attribute(type, name) {
  549. const key = `${type}:${name}`;
  550. if (!this._attributes.has(key)) {
  551. const metadata = this.type(type);
  552. if (metadata && metadata.attributes && metadata.attributes.length > 0) {
  553. for (const attribute of metadata.attributes) {
  554. this._attributes.set(`${type}:${attribute.name}`, attribute);
  555. }
  556. }
  557. if (!this._attributes.has(key)) {
  558. this._attributes.set(key, null);
  559. }
  560. }
  561. return this._attributes.get(key);
  562. }
  563. };
  564. cntk.ComputationNetwork = class {
  565. constructor(reader) {
  566. reader = new cntk.BinaryReader(reader);
  567. const shape = (dims) => {
  568. return { __type__: 'shape', dims };
  569. };
  570. reader.assert('BCN');
  571. reader.assert('BVersion');
  572. this.version = reader.uint64().toNumber();
  573. reader.assert('EVersion');
  574. const numNodes = reader.uint64().toNumber();
  575. reader.assert('BNodeList');
  576. const op = {};
  577. op.Minus = function() {};
  578. op.Plus = function() {};
  579. op.GreaterEqual = function() {};
  580. op.Equal = function() {};
  581. op.NotEqual = function() {};
  582. op.GreaterEqual = function() {};
  583. op.Exp = function() {};
  584. op.Log = function() {};
  585. op.Reciprocal = function() {};
  586. op.ElementTimes = function() {};
  587. op.ClassificationError = function() {};
  588. op.RectifiedLinear = function() {};
  589. op.InputValue = function(reader, version) {
  590. this.rows = reader.uint64().toNumber();
  591. this.cols = reader.uint64().toNumber();
  592. this.sampleLayout = reader.shape(true);
  593. this.dynamicAxisNodeName = '';
  594. if (version >= 8) {
  595. const nrAxes = reader.uint32();
  596. if (nrAxes === 1) {
  597. this.dynamicAxisNodeName = reader.string();
  598. }
  599. }
  600. this.learningRateMultiplier = 0;
  601. if (version >= 10) {
  602. this.learningRateMultiplier = reader.float32();
  603. }
  604. };
  605. op.LearnableParameter = function(reader, version) {
  606. if (version >= 3) {
  607. this.learningRateMultiplier = reader.float32();
  608. this.sampleLayout = reader.shape(false);
  609. } else {
  610. throw new cntk.Error('LeanableParameter reader implemented.');
  611. }
  612. this.value = reader.matrix();
  613. };
  614. op.CrossEntropyWithSoftmax = function(reader) {
  615. this.evalMode = reader.uint32();
  616. if (this.evalMode > 2) {
  617. this.evalMode = 0;
  618. reader.skip(-4);
  619. }
  620. };
  621. op.Times = function(reader, version) {
  622. this.outputRank = (version >= 3) ? reader.uint64().toNumber() : 1;
  623. this.inferInputRankToMap = (version >= 12) ? reader.int32() : -1;
  624. };
  625. op.Dropout = function(reader, version) {
  626. if (version >= 16) {
  627. this.rngSeed = (version === 16) ? reader.uint32() : reader.uint64().toNumber();
  628. this.rngOffset = reader.uint64().toNumber();
  629. }
  630. };
  631. op.ConvolutionBase = function(reader, version) {
  632. if (version >= 5) {
  633. this.kernelShape = reader.shape(false);
  634. this.mapCount = reader.shape(false);
  635. this.strides = reader.shape(false);
  636. this.sharing = reader.booleans();
  637. this.autoPadding = reader.booleans();
  638. this.lowerPad = reader.shape(false);
  639. this.upperPad = reader.shape(false);
  640. this.poolKind = reader.int32();
  641. this.imageLayoutKind = reader.int32();
  642. this.maxTempMemSizeInSamples = reader.uint64().toNumber();
  643. }
  644. if (version >= 9) {
  645. this.transpose = reader.boolean();
  646. }
  647. if (version >= 20) {
  648. this.outputShape = reader.shape(false);
  649. }
  650. if (version >= 21) {
  651. this.ceilOutDim = reader.boolean();
  652. }
  653. if (version >= 23) {
  654. this.includePad = reader.boolean();
  655. }
  656. };
  657. op.Convolution = function(reader, version) {
  658. op.ConvolutionBase.apply(this, [reader, version]);
  659. if (version < 5) {
  660. this.kernelShape = shape([reader.uint64().toNumber(), reader.uint64().toNumber(), 1]);
  661. this.strides = shape([reader.uint64().toNumber(), reader.uint64().toNumber(), 1]);
  662. this.mapCount = shape([reader.uint32()]);
  663. this.imageLayoutKind = reader.int32();
  664. this.autoPadding = [reader.boolean()];
  665. this.maxTempMemSizeInSamples = reader.uint64().toNumber();
  666. this.poolKind = 'None';
  667. this.convolution2D = true;
  668. this.sharing = [true];
  669. this.lowerPad = shape([0]);
  670. this.upperPad = shape([0]);
  671. } else {
  672. this.convolution2D = reader.boolean();
  673. if (version >= 18) {
  674. this.dilation = reader.shape();
  675. } else {
  676. this.dilation = shape([1]);
  677. }
  678. }
  679. };
  680. op.Pooling = function(reader, version) {
  681. op.ConvolutionBase.apply(this, [reader, version]);
  682. };
  683. op.PoolingBase = function(reader) {
  684. this.imageLayoutKind = reader.int32();
  685. this.windowWidth = reader.uint32();
  686. this.windowHeight = reader.uint64().toNumber();
  687. this.horizontalSubsample = reader.uint64().toNumber();
  688. this.verticalSubsample = reader.uint64().toNumber();
  689. };
  690. op.MaxPooling = function(reader, version) {
  691. op.PoolingBase.apply(this, [reader, version]);
  692. };
  693. op.ROIPooling = function(reader, version) {
  694. this.roiOutputShape = reader.shape(false);
  695. this.poolKind = (version < 26) ? 'Max' : reader.int32();
  696. this.spatialScale = (version < 26) ? 0.0625 : reader.float64();
  697. };
  698. op.Reshape = function(reader) {
  699. this.beginDimParameter = reader.uint32();
  700. this.endDimParameter = reader.uint32();
  701. this.replacementSampleLayout = reader.shape(false);
  702. };
  703. op.ReduceElements = function(reader, version) {
  704. let num_axes = 1;
  705. if (version >= 27) {
  706. num_axes = reader.uint32();
  707. }
  708. this.axes = [];
  709. for (let i = 0; i < num_axes; i++) {
  710. this.axes.push(reader.uint32());
  711. }
  712. this.operation = reader.string();
  713. if (version >= 24) {
  714. this.keepDimensions = reader.boolean();
  715. }
  716. };
  717. op.BatchNormalization = function(reader, version) {
  718. let mbCount = 0;
  719. if (version >= 6) {
  720. this.spatial = reader.boolean();
  721. this.normalizationTimeConstant = reader.float64();
  722. this.blendTimeConstant = reader.float64();
  723. this.imageLayoutKind = reader.int32();
  724. if (version >= 13) {
  725. if (version === 19) {
  726. this.runCountUntied = reader.boolean() ? 0 : 'SIZE_MAX';
  727. } else {
  728. this.runCountUntied = reader.uint64().toNumber();
  729. }
  730. } else {
  731. mbCount = reader.uint64().toNumber();
  732. }
  733. this.epsilon = reader.float64();
  734. this.useCntkEngine = reader.boolean();
  735. } else {
  736. const verWritten = reader.int32();
  737. const verReadable = reader.int32();
  738. if (verReadable > verWritten || verWritten < 0x00010001 || verReadable > 0x00010004) {
  739. throw new cntk.Error('BatchNormalization version not supported.');
  740. }
  741. this.eval = reader.boolean();
  742. this.spatial = reader.boolean();
  743. if (verWritten >= 0x00010004) {
  744. this.normalizationTimeConstant = reader.float64();
  745. } else {
  746. reader.float64(); // expAvgFactor
  747. }
  748. if (verWritten >= 0x00010002) {
  749. this.imageLayoutKind = reader.int32();
  750. mbCount = reader.uint64().toNumber();
  751. }
  752. if (verWritten >= 0x00010003) {
  753. this.epsilon = reader.float64();
  754. this.useCntkEngine = reader.boolean();
  755. }
  756. }
  757. if (version < 13) {
  758. this.runCountUntied = 16 * mbCount;
  759. this.convertRunningVariancePending = true;
  760. }
  761. };
  762. op.Tanh = function() {};
  763. op.Sigmoid = function() {};
  764. op.Logistic = function() {};
  765. op.SquareError = function() {};
  766. op.ErrorPrediction = function() {};
  767. op.RowStack = function(reader, version) {
  768. this.spliceDim = (version >= 3) ? reader.int32() : 1;
  769. };
  770. op.Slice = function(reader, version) {
  771. let num = 1;
  772. if (version >= 22) {
  773. num = reader.int32();
  774. }
  775. this.index = [];
  776. this.axis = [];
  777. this.strideMultiplier = [];
  778. for (let i = 0; i < num; i++) {
  779. this.index.push([[reader.uint64().toNumber(), reader.uint64().toNumber()]]);
  780. if (version >= 3) {
  781. this.axis.push(reader.int32());
  782. }
  783. if (version >= 27) {
  784. this.strideMultiplier.push(reader.int32());
  785. }
  786. }
  787. };
  788. op.PastValue = function(reader, version) {
  789. this.timeStep = reader.int32();
  790. if (version > 3) {
  791. this.sampleLayout = reader.shape(false);
  792. } else {
  793. const rows = reader.uint64().toNumber();
  794. reader.uint64();
  795. this.sampleLayout = shape([rows], true);
  796. }
  797. if (version >= 2) {
  798. this.initialStateValue = reader.int32();
  799. }
  800. };
  801. op.FutureValue = function(reader, version) {
  802. this.timeStep = reader.int32();
  803. if (version > 3) {
  804. this.sampleLayout = reader.shape(false);
  805. } else {
  806. const rows = reader.uint64().toNumber();
  807. reader.uint64();
  808. this.sampleLayout = shape([rows], true);
  809. }
  810. if (version >= 2) {
  811. this.initialStateValue = reader.int32();
  812. }
  813. };
  814. op.TransposeDimensions = function(reader, version) {
  815. if (version >= 3) {
  816. this.axis1 = reader.int32();
  817. this.axis2 = reader.int32();
  818. if (version >= 25 && this.axis1 === 0 && this.axis2 === 0) {
  819. const size = reader.uint64().toNumber();
  820. this.perm = [];
  821. for (let i = 0; i < size; i++) {
  822. this.perm.push(reader.uint64().toNumber());
  823. }
  824. }
  825. } else {
  826. this.axis1 = 1;
  827. this.axis2 = 2;
  828. }
  829. };
  830. op.AveragePooling = function(reader, version) {
  831. op.PoolingBase.apply(this, [reader, version]);
  832. };
  833. op.InvStdDev = function(reader) {
  834. this.hasComputed = reader.boolean();
  835. this.value = reader.matrix();
  836. };
  837. op.Mean = function(reader) {
  838. this.hasComputed = reader.boolean();
  839. this.value = reader.matrix();
  840. };
  841. op.PerDimMeanVarNormalization = function() {};
  842. op.Softmax = function() {};
  843. op.DynamicAxis = function() {};
  844. const nodes = [];
  845. this.nodes = {};
  846. for (let i = 0; i < numNodes; i++) {
  847. const precision = this.version >= 7 ? reader.string() : '';
  848. if (precision !== 'float' && precision !== 'double' && precision !== 'half' && precision !== '') {
  849. throw new cntk.Error(`Invalid precision format '${precision}'.`);
  850. }
  851. const obj = { __type__: reader.string() };
  852. obj.name = reader.string();
  853. obj.precision = precision;
  854. const constructor = op[obj.__type__];
  855. if (!constructor) {
  856. throw new cntk.Error(`Unsupported node type '${obj.__type__}'.`);
  857. }
  858. constructor.apply(obj, [reader, this.version]);
  859. nodes.push(obj);
  860. this.nodes[obj.name] = obj;
  861. }
  862. reader.assert('ENodeList');
  863. reader.assert('BRelation');
  864. for (let j = 0; j < numNodes; j++) {
  865. const nodeName = reader.string();
  866. const node = this.nodes[nodeName];
  867. const numChildren = reader.uint64().toNumber();
  868. const children = [];
  869. for (let k = 0; k < numChildren; k++) {
  870. children.push(reader.string());
  871. }
  872. if (this.version < 19 && node.__type__ === 'BatchNormalization') {
  873. const runSampleCount = {
  874. __type__: 'LearnableParameter',
  875. name: `${nodeName}.run_sample_count`,
  876. precision: node.precision,
  877. sampleLayout: shape([1]),
  878. learningRateMultiplier: 0
  879. };
  880. nodes.push(runSampleCount);
  881. this.nodes[runSampleCount.name] = runSampleCount;
  882. children.push(runSampleCount.name);
  883. }
  884. if (node.__type__ === 'Convolution' && children.length > 1) {
  885. children.splice(0, 0, children.pop());
  886. }
  887. node.inputs = children;
  888. }
  889. reader.assert('ERelation');
  890. reader.assert('BRootNodes');
  891. if (reader.match('BFeatureNodes')) {
  892. this.feature = reader.strings();
  893. reader.assert('EFeatureNodes');
  894. }
  895. if (reader.match('BLabelNodes')) {
  896. this.label = reader.strings();
  897. reader.assert('ELabelNodes');
  898. }
  899. if (reader.match('BCriterionNodes')) {
  900. this.criterion = reader.strings();
  901. reader.assert('ECriterionNodes');
  902. }
  903. if (this.criterion.length === 0) {
  904. if (reader.match('BCriteriaNodes')) {
  905. this.criterion = reader.strings();
  906. reader.assert('ECriteriaNodes');
  907. }
  908. }
  909. if (reader.match('BNodesReqMultiSeqHandling')) {
  910. reader.strings();
  911. reader.assert('ENodesReqMultiSeqHandling');
  912. }
  913. if (reader.match('BEvalNodes')) {
  914. this.eval = reader.strings();
  915. reader.assert('EEvalNodes');
  916. }
  917. if (reader.match('BOutputNodes')) {
  918. this.output = reader.strings();
  919. reader.assert('EOutputNodes');
  920. }
  921. if (reader.match('BPairNodes')) {
  922. this.pair = reader.strings();
  923. reader.assert('EPairNodes');
  924. }
  925. reader.assert('ERootNodes');
  926. reader.assert('ECN');
  927. }
  928. };
  929. cntk.BinaryReader = class {
  930. constructor(reader) {
  931. this._reader = reader;
  932. }
  933. get position() {
  934. return this._reader.position;
  935. }
  936. seek(offset) {
  937. this._reader.seek(offset);
  938. }
  939. skip(offset) {
  940. this._reader.skip(offset);
  941. }
  942. read(length) {
  943. return this._reader.read(length);
  944. }
  945. boolean() {
  946. return this._reader.boolean();
  947. }
  948. byte() {
  949. return this._reader.byte();
  950. }
  951. int32() {
  952. return this._reader.int32();
  953. }
  954. uint16() {
  955. return this._reader.uint16();
  956. }
  957. uint32() {
  958. return this._reader.uint32();
  959. }
  960. uint64() {
  961. return this._reader.uint64();
  962. }
  963. float32() {
  964. return this._reader.float32();
  965. }
  966. float64() {
  967. return this._reader.float64();
  968. }
  969. match(text) {
  970. const position = this.position;
  971. for (let i = 0; i < text.length; i++) {
  972. if (this.uint16() !== text.charCodeAt(i)) {
  973. this.seek(position);
  974. return false;
  975. }
  976. }
  977. if (this.uint16() !== 0) {
  978. this.seek(position);
  979. return false;
  980. }
  981. return true;
  982. }
  983. assert(text) {
  984. if (!this.match(text)) {
  985. throw new cntk.Error(`Invalid '${text}' signature.`);
  986. }
  987. }
  988. string() {
  989. const content = [];
  990. let c = this.uint16();
  991. while (c !== 0) {
  992. content.push(String.fromCharCode(c));
  993. c = this.uint16();
  994. }
  995. return content.join('');
  996. }
  997. strings() {
  998. const size = this.uint64().toNumber();
  999. const array = new Array(size);
  1000. for (let i = 0; i < size; i++) {
  1001. array[i] = this.string();
  1002. }
  1003. return array;
  1004. }
  1005. booleans() {
  1006. const size = this.uint64().toNumber();
  1007. const array = new Array(size);
  1008. for (let i = 0; i < size; i++) {
  1009. array[i] = this.boolean();
  1010. }
  1011. return array;
  1012. }
  1013. matrix() {
  1014. const type = this.byte();
  1015. switch (type) {
  1016. case 100: {
  1017. // dense
  1018. this.assert('BMAT');
  1019. const elsize = this.uint64().toNumber();
  1020. const value = {};
  1021. value.name = this.string();
  1022. value.format = this.uint32();
  1023. value.rows = this.uint64().toNumber();
  1024. value.columns = this.uint64().toNumber();
  1025. this.read(elsize * value.rows * value.columns);
  1026. this.assert('EMAT');
  1027. return value;
  1028. }
  1029. case 115: // sparse
  1030. throw new cntk.Error('Matrix sparse type not implemented.');
  1031. default:
  1032. throw new cntk.Error(`Matrix type '${type}' not implemented.`);
  1033. }
  1034. }
  1035. shape(acceptLegacyFormat) {
  1036. const dims = [];
  1037. const rank = this.uint32();
  1038. let dim0 = 0;
  1039. if (rank > 0) {
  1040. dim0 = this.uint32();
  1041. }
  1042. if (!acceptLegacyFormat || dim0 !== 0) {
  1043. if (rank > 0) {
  1044. dims.push(dim0);
  1045. }
  1046. for (let i = 1; i < rank; i++) {
  1047. dims.push(this.uint32());
  1048. }
  1049. } else {
  1050. const dim = this.uint32();
  1051. dims.push(this.uint32());
  1052. dims.push(rank);
  1053. dims.push(dim);
  1054. }
  1055. return { __type__: 'shape', dims };
  1056. }
  1057. };
  1058. cntk.ImageLayoutKind = {
  1059. 0: 'CHW',
  1060. 1: 'HWC'
  1061. };
  1062. cntk.PoolKind = {
  1063. 0: 'None',
  1064. 1: 'Max',
  1065. 2: 'Average'
  1066. };
  1067. cntk.Error = class extends Error {
  1068. constructor(message) {
  1069. super(message);
  1070. this.name = 'Error loading CNTK model.';
  1071. }
  1072. };
  1073. export const ModelFactory = cntk.ModelFactory;