cntk.js 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129
  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. const 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. const repeat = defaultValue.length > 1 && defaultValue[defaultValue.length - 1] === null;
  402. if (value.every((item, index) => item === (repeat && index >= defaultValue.length - 1 ? defaultValue[defaultValue.length - 2] : defaultValue[index]))) {
  403. visible = false;
  404. }
  405. }
  406. }
  407. }
  408. return new cntk.Argument(name, value, type, visible);
  409. });
  410. }
  411. };
  412. cntk.Tensor = class {
  413. constructor(version, tensor) {
  414. this.encoding = '|';
  415. this.values = null;
  416. switch (version) {
  417. case 1: {
  418. if (tensor.__type__ === 'LearnableParameter') {
  419. this.name = tensor.name || null;
  420. this.type = new cntk.TensorType(version, tensor.precision, tensor.sampleLayout);
  421. }
  422. break;
  423. }
  424. case 2: {
  425. this.name = tensor.name || tensor.uid || null;
  426. this.type = new cntk.TensorType(version, tensor.data_type, tensor.shape);
  427. const value = tensor.value;
  428. if (this.type.dataType === 'float32' && value && value.float_values && value.float_values.value && value.float_values.value.length > 0) {
  429. this.values = value.float_values.value;
  430. }
  431. break;
  432. }
  433. default:
  434. throw new cntk.Error(`Unsupported CNTK version '${version}'.`);
  435. }
  436. }
  437. };
  438. cntk.TensorType = class {
  439. constructor(version, dataType, shape) {
  440. this.dataType = '?';
  441. switch (version) {
  442. case 1:
  443. switch (dataType) {
  444. case 'float': this.dataType = 'float32'; break;
  445. case 'double': this.dataType = 'float64'; break;
  446. case 'half': this.dataType = 'float16'; break;
  447. case '': this.dataType = 'float32'; break;
  448. default: throw new cntk.Error(`Unsupported tensor data type '${dataType}'.`);
  449. }
  450. this.shape = new cntk.TensorShape(version, shape);
  451. break;
  452. case 2:
  453. switch (dataType) {
  454. case 1n: this.dataType = 'float32'; break;
  455. default: throw new cntk.Error(`Unsupported tensor data type '${dataType}'.`);
  456. }
  457. this.shape = new cntk.TensorShape(version, shape);
  458. break;
  459. default:
  460. throw new cntk.Error(`Unsupported CNTK version '${version}'.`);
  461. }
  462. }
  463. toString() {
  464. return this.dataType + this.shape.toString();
  465. }
  466. };
  467. cntk.TensorShape = class {
  468. constructor(version, shape) {
  469. switch (version) {
  470. case 1:
  471. this.dimensions = shape.dims;
  472. break;
  473. case 2:
  474. this.dimensions = shape.shape_dim.map((dimension) => dimension.toNumber());
  475. break;
  476. default:
  477. throw new cntk.Error(`Unsupported CNTK version '${version}'.`);
  478. }
  479. }
  480. toString() {
  481. return (this.dimensions && this.dimensions.length) ? (`[${this.dimensions.join(',')}]`) : '';
  482. }
  483. };
  484. cntk.Function = class {
  485. constructor(name, nodes, inputs, outputs) {
  486. this.type = 'function';
  487. this.name = name;
  488. this.inputs = inputs;
  489. this.outputs = outputs;
  490. this.nodes = nodes;
  491. switch (this.name) {
  492. case 'PReLU':
  493. case 'Softmax':
  494. this.category = 'Activation';
  495. break;
  496. case 'Dropout':
  497. this.category = 'Dropout';
  498. break;
  499. case 'Convolution':
  500. case 'ConvolutionTranspose':
  501. case 'Dense':
  502. case 'linear':
  503. case 'LSTM':
  504. this.category = 'Layer';
  505. break;
  506. case 'BatchNormalization':
  507. case 'lrn':
  508. this.category = 'Normalization';
  509. break;
  510. case 'AveragePooling':
  511. case 'MaxPooling':
  512. this.category = 'Pool';
  513. break;
  514. default:
  515. this.category = null;
  516. break;
  517. }
  518. }
  519. };
  520. cntk.GraphMetadata = class {
  521. constructor(metadata) {
  522. this._metadata = metadata;
  523. this._functions = new Map();
  524. this._attributes = new Map();
  525. }
  526. add(name, func) {
  527. if (this._functions.has(name)) {
  528. throw new cntk.Error(`Duplicate function identifier '${func.name}'.`);
  529. }
  530. this._functions.set(name, func);
  531. }
  532. name(code) {
  533. // cntk/Source/CNTKv2LibraryDll/API/Internals/PrimitiveOpType.h
  534. return this._metadata.name(code);
  535. }
  536. type(name) {
  537. if (this._functions.has(name)) {
  538. return this._functions.get(name);
  539. }
  540. return this._metadata.type(name);
  541. }
  542. attribute(type, name) {
  543. const key = `${type}:${name}`;
  544. if (!this._attributes.has(key)) {
  545. const metadata = this.type(type);
  546. if (metadata && metadata.attributes && metadata.attributes.length > 0) {
  547. for (const attribute of metadata.attributes) {
  548. this._attributes.set(`${type}:${attribute.name}`, attribute);
  549. }
  550. }
  551. if (!this._attributes.has(key)) {
  552. this._attributes.set(key, null);
  553. }
  554. }
  555. return this._attributes.get(key);
  556. }
  557. };
  558. cntk.ComputationNetwork = class {
  559. constructor(reader) {
  560. reader = new cntk.BinaryReader(reader);
  561. const shape = (dims) => {
  562. return { __type__: 'shape', dims };
  563. };
  564. reader.assert('BCN');
  565. reader.assert('BVersion');
  566. this.version = reader.uint64().toNumber();
  567. reader.assert('EVersion');
  568. const numNodes = reader.uint64().toNumber();
  569. reader.assert('BNodeList');
  570. const op = {};
  571. op.Minus = function() {};
  572. op.Plus = function() {};
  573. op.GreaterEqual = function() {};
  574. op.Equal = function() {};
  575. op.NotEqual = function() {};
  576. op.GreaterEqual = function() {};
  577. op.Exp = function() {};
  578. op.Log = function() {};
  579. op.Reciprocal = function() {};
  580. op.ElementTimes = function() {};
  581. op.ClassificationError = function() {};
  582. op.RectifiedLinear = function() {};
  583. op.InputValue = function(reader, version) {
  584. this.rows = reader.uint64().toNumber();
  585. this.cols = reader.uint64().toNumber();
  586. this.sampleLayout = reader.shape(true);
  587. this.dynamicAxisNodeName = '';
  588. if (version >= 8) {
  589. const nrAxes = reader.uint32();
  590. if (nrAxes === 1) {
  591. this.dynamicAxisNodeName = reader.string();
  592. }
  593. }
  594. this.learningRateMultiplier = 0;
  595. if (version >= 10) {
  596. this.learningRateMultiplier = reader.float32();
  597. }
  598. };
  599. op.LearnableParameter = function(reader, version) {
  600. if (version >= 3) {
  601. this.learningRateMultiplier = reader.float32();
  602. this.sampleLayout = reader.shape(false);
  603. } else {
  604. throw new cntk.Error('LeanableParameter reader implemented.');
  605. }
  606. this.value = reader.matrix();
  607. };
  608. op.CrossEntropyWithSoftmax = function(reader) {
  609. this.evalMode = reader.uint32();
  610. if (this.evalMode > 2) {
  611. this.evalMode = 0;
  612. reader.skip(-4);
  613. }
  614. };
  615. op.Times = function(reader, version) {
  616. this.outputRank = (version >= 3) ? reader.uint64().toNumber() : 1;
  617. this.inferInputRankToMap = (version >= 12) ? reader.int32() : -1;
  618. };
  619. op.Dropout = function(reader, version) {
  620. if (version >= 16) {
  621. this.rngSeed = (version === 16) ? reader.uint32() : reader.uint64().toNumber();
  622. this.rngOffset = reader.uint64().toNumber();
  623. }
  624. };
  625. op.ConvolutionBase = function(reader, version) {
  626. if (version >= 5) {
  627. this.kernelShape = reader.shape(false);
  628. this.mapCount = reader.shape(false);
  629. this.strides = reader.shape(false);
  630. this.sharing = reader.booleans();
  631. this.autoPadding = reader.booleans();
  632. this.lowerPad = reader.shape(false);
  633. this.upperPad = reader.shape(false);
  634. this.poolKind = reader.int32();
  635. this.imageLayoutKind = reader.int32();
  636. this.maxTempMemSizeInSamples = reader.uint64().toNumber();
  637. }
  638. if (version >= 9) {
  639. this.transpose = reader.boolean();
  640. }
  641. if (version >= 20) {
  642. this.outputShape = reader.shape(false);
  643. }
  644. if (version >= 21) {
  645. this.ceilOutDim = reader.boolean();
  646. }
  647. if (version >= 23) {
  648. this.includePad = reader.boolean();
  649. }
  650. };
  651. op.Convolution = function(reader, version) {
  652. op.ConvolutionBase.apply(this, [reader, version]);
  653. if (version < 5) {
  654. this.kernelShape = shape([reader.uint64().toNumber(), reader.uint64().toNumber(), 1]);
  655. this.strides = shape([reader.uint64().toNumber(), reader.uint64().toNumber(), 1]);
  656. this.mapCount = shape([reader.uint32()]);
  657. this.imageLayoutKind = reader.int32();
  658. this.autoPadding = [reader.boolean()];
  659. this.maxTempMemSizeInSamples = reader.uint64().toNumber();
  660. this.poolKind = 'None';
  661. this.convolution2D = true;
  662. this.sharing = [true];
  663. this.lowerPad = shape([0]);
  664. this.upperPad = shape([0]);
  665. } else {
  666. this.convolution2D = reader.boolean();
  667. if (version >= 18) {
  668. this.dilation = reader.shape();
  669. } else {
  670. this.dilation = shape([1]);
  671. }
  672. }
  673. };
  674. op.Pooling = function(reader, version) {
  675. op.ConvolutionBase.apply(this, [reader, version]);
  676. };
  677. op.PoolingBase = function(reader) {
  678. this.imageLayoutKind = reader.int32();
  679. this.windowWidth = reader.uint32();
  680. this.windowHeight = reader.uint64().toNumber();
  681. this.horizontalSubsample = reader.uint64().toNumber();
  682. this.verticalSubsample = reader.uint64().toNumber();
  683. };
  684. op.MaxPooling = function(reader, version) {
  685. op.PoolingBase.apply(this, [reader, version]);
  686. };
  687. op.ROIPooling = function(reader, version) {
  688. this.roiOutputShape = reader.shape(false);
  689. this.poolKind = (version < 26) ? 'Max' : reader.int32();
  690. this.spatialScale = (version < 26) ? 0.0625 : reader.float64();
  691. };
  692. op.Reshape = function(reader) {
  693. this.beginDimParameter = reader.uint32();
  694. this.endDimParameter = reader.uint32();
  695. this.replacementSampleLayout = reader.shape(false);
  696. };
  697. op.ReduceElements = function(reader, version) {
  698. let num_axes = 1;
  699. if (version >= 27) {
  700. num_axes = reader.uint32();
  701. }
  702. this.axes = [];
  703. for (let i = 0; i < num_axes; i++) {
  704. this.axes.push(reader.uint32());
  705. }
  706. this.operation = reader.string();
  707. if (version >= 24) {
  708. this.keepDimensions = reader.boolean();
  709. }
  710. };
  711. op.BatchNormalization = function(reader, version) {
  712. let mbCount = 0;
  713. if (version >= 6) {
  714. this.spatial = reader.boolean();
  715. this.normalizationTimeConstant = reader.float64();
  716. this.blendTimeConstant = reader.float64();
  717. this.imageLayoutKind = reader.int32();
  718. if (version >= 13) {
  719. if (version === 19) {
  720. this.runCountUntied = reader.boolean() ? 0 : 'SIZE_MAX';
  721. } else {
  722. this.runCountUntied = reader.uint64().toNumber();
  723. }
  724. } else {
  725. mbCount = reader.uint64().toNumber();
  726. }
  727. this.epsilon = reader.float64();
  728. this.useCntkEngine = reader.boolean();
  729. } else {
  730. const verWritten = reader.int32();
  731. const verReadable = reader.int32();
  732. if (verReadable > verWritten || verWritten < 0x00010001 || verReadable > 0x00010004) {
  733. throw new cntk.Error('BatchNormalization version not supported.');
  734. }
  735. this.eval = reader.boolean();
  736. this.spatial = reader.boolean();
  737. if (verWritten >= 0x00010004) {
  738. this.normalizationTimeConstant = reader.float64();
  739. } else {
  740. reader.float64(); // expAvgFactor
  741. }
  742. if (verWritten >= 0x00010002) {
  743. this.imageLayoutKind = reader.int32();
  744. mbCount = reader.uint64().toNumber();
  745. }
  746. if (verWritten >= 0x00010003) {
  747. this.epsilon = reader.float64();
  748. this.useCntkEngine = reader.boolean();
  749. }
  750. }
  751. if (version < 13) {
  752. this.runCountUntied = 16 * mbCount;
  753. this.convertRunningVariancePending = true;
  754. }
  755. };
  756. op.Tanh = function() {};
  757. op.Sigmoid = function() {};
  758. op.Logistic = function() {};
  759. op.SquareError = function() {};
  760. op.ErrorPrediction = function() {};
  761. op.RowStack = function(reader, version) {
  762. this.spliceDim = (version >= 3) ? reader.int32() : 1;
  763. };
  764. op.Slice = function(reader, version) {
  765. let num = 1;
  766. if (version >= 22) {
  767. num = reader.int32();
  768. }
  769. this.index = [];
  770. this.axis = [];
  771. this.strideMultiplier = [];
  772. for (let i = 0; i < num; i++) {
  773. this.index.push([[reader.uint64().toNumber(), reader.uint64().toNumber()]]);
  774. if (version >= 3) {
  775. this.axis.push(reader.int32());
  776. }
  777. if (version >= 27) {
  778. this.strideMultiplier.push(reader.int32());
  779. }
  780. }
  781. };
  782. op.PastValue = function(reader, version) {
  783. this.timeStep = reader.int32();
  784. if (version > 3) {
  785. this.sampleLayout = reader.shape(false);
  786. } else {
  787. const rows = reader.uint64().toNumber();
  788. reader.uint64();
  789. this.sampleLayout = shape([rows], true);
  790. }
  791. if (version >= 2) {
  792. this.initialStateValue = reader.int32();
  793. }
  794. };
  795. op.FutureValue = function(reader, version) {
  796. this.timeStep = reader.int32();
  797. if (version > 3) {
  798. this.sampleLayout = reader.shape(false);
  799. } else {
  800. const rows = reader.uint64().toNumber();
  801. reader.uint64();
  802. this.sampleLayout = shape([rows], true);
  803. }
  804. if (version >= 2) {
  805. this.initialStateValue = reader.int32();
  806. }
  807. };
  808. op.TransposeDimensions = function(reader, version) {
  809. if (version >= 3) {
  810. this.axis1 = reader.int32();
  811. this.axis2 = reader.int32();
  812. if (version >= 25 && this.axis1 === 0 && this.axis2 === 0) {
  813. const size = reader.uint64().toNumber();
  814. this.perm = [];
  815. for (let i = 0; i < size; i++) {
  816. this.perm.push(reader.uint64().toNumber());
  817. }
  818. }
  819. } else {
  820. this.axis1 = 1;
  821. this.axis2 = 2;
  822. }
  823. };
  824. op.AveragePooling = function(reader, version) {
  825. op.PoolingBase.apply(this, [reader, version]);
  826. };
  827. op.InvStdDev = function(reader) {
  828. this.hasComputed = reader.boolean();
  829. this.value = reader.matrix();
  830. };
  831. op.Mean = function(reader) {
  832. this.hasComputed = reader.boolean();
  833. this.value = reader.matrix();
  834. };
  835. op.PerDimMeanVarNormalization = function() {};
  836. op.Softmax = function() {};
  837. op.DynamicAxis = function() {};
  838. const nodes = [];
  839. this.nodes = {};
  840. for (let i = 0; i < numNodes; i++) {
  841. const precision = this.version >= 7 ? reader.string() : '';
  842. if (precision !== 'float' && precision !== 'double' && precision !== 'half' && precision !== '') {
  843. throw new cntk.Error(`Invalid precision format '${precision}'.`);
  844. }
  845. const obj = { __type__: reader.string() };
  846. obj.name = reader.string();
  847. obj.precision = precision;
  848. const constructor = op[obj.__type__];
  849. if (!constructor) {
  850. throw new cntk.Error(`Unsupported node type '${obj.__type__}'.`);
  851. }
  852. constructor.apply(obj, [reader, this.version]);
  853. nodes.push(obj);
  854. this.nodes[obj.name] = obj;
  855. }
  856. reader.assert('ENodeList');
  857. reader.assert('BRelation');
  858. for (let j = 0; j < numNodes; j++) {
  859. const nodeName = reader.string();
  860. const node = this.nodes[nodeName];
  861. const numChildren = reader.uint64().toNumber();
  862. const children = [];
  863. for (let k = 0; k < numChildren; k++) {
  864. children.push(reader.string());
  865. }
  866. if (this.version < 19 && node.__type__ === 'BatchNormalization') {
  867. const runSampleCount = {
  868. __type__: 'LearnableParameter',
  869. name: `${nodeName}.run_sample_count`,
  870. precision: node.precision,
  871. sampleLayout: shape([1]),
  872. learningRateMultiplier: 0
  873. };
  874. nodes.push(runSampleCount);
  875. this.nodes[runSampleCount.name] = runSampleCount;
  876. children.push(runSampleCount.name);
  877. }
  878. if (node.__type__ === 'Convolution' && children.length > 1) {
  879. children.splice(0, 0, children.pop());
  880. }
  881. node.inputs = children;
  882. }
  883. reader.assert('ERelation');
  884. reader.assert('BRootNodes');
  885. if (reader.match('BFeatureNodes')) {
  886. this.feature = reader.strings();
  887. reader.assert('EFeatureNodes');
  888. }
  889. if (reader.match('BLabelNodes')) {
  890. this.label = reader.strings();
  891. reader.assert('ELabelNodes');
  892. }
  893. if (reader.match('BCriterionNodes')) {
  894. this.criterion = reader.strings();
  895. reader.assert('ECriterionNodes');
  896. }
  897. if (this.criterion.length === 0) {
  898. if (reader.match('BCriteriaNodes')) {
  899. this.criterion = reader.strings();
  900. reader.assert('ECriteriaNodes');
  901. }
  902. }
  903. if (reader.match('BNodesReqMultiSeqHandling')) {
  904. reader.strings();
  905. reader.assert('ENodesReqMultiSeqHandling');
  906. }
  907. if (reader.match('BEvalNodes')) {
  908. this.eval = reader.strings();
  909. reader.assert('EEvalNodes');
  910. }
  911. if (reader.match('BOutputNodes')) {
  912. this.output = reader.strings();
  913. reader.assert('EOutputNodes');
  914. }
  915. if (reader.match('BPairNodes')) {
  916. this.pair = reader.strings();
  917. reader.assert('EPairNodes');
  918. }
  919. reader.assert('ERootNodes');
  920. reader.assert('ECN');
  921. }
  922. };
  923. cntk.BinaryReader = class {
  924. constructor(reader) {
  925. this._reader = reader;
  926. }
  927. get position() {
  928. return this._reader.position;
  929. }
  930. seek(offset) {
  931. this._reader.seek(offset);
  932. }
  933. skip(offset) {
  934. this._reader.skip(offset);
  935. }
  936. read(length) {
  937. return this._reader.read(length);
  938. }
  939. boolean() {
  940. return this._reader.boolean();
  941. }
  942. byte() {
  943. return this._reader.byte();
  944. }
  945. int32() {
  946. return this._reader.int32();
  947. }
  948. uint16() {
  949. return this._reader.uint16();
  950. }
  951. uint32() {
  952. return this._reader.uint32();
  953. }
  954. uint64() {
  955. return this._reader.uint64();
  956. }
  957. float32() {
  958. return this._reader.float32();
  959. }
  960. float64() {
  961. return this._reader.float64();
  962. }
  963. match(text) {
  964. const position = this.position;
  965. for (let i = 0; i < text.length; i++) {
  966. if (this.uint16() !== text.charCodeAt(i)) {
  967. this.seek(position);
  968. return false;
  969. }
  970. }
  971. if (this.uint16() !== 0) {
  972. this.seek(position);
  973. return false;
  974. }
  975. return true;
  976. }
  977. assert(text) {
  978. if (!this.match(text)) {
  979. throw new cntk.Error(`Invalid '${text}' signature.`);
  980. }
  981. }
  982. string() {
  983. const content = [];
  984. let c = this.uint16();
  985. while (c !== 0) {
  986. content.push(String.fromCharCode(c));
  987. c = this.uint16();
  988. }
  989. return content.join('');
  990. }
  991. strings() {
  992. const size = this.uint64().toNumber();
  993. const array = new Array(size);
  994. for (let i = 0; i < size; i++) {
  995. array[i] = this.string();
  996. }
  997. return array;
  998. }
  999. booleans() {
  1000. const size = this.uint64().toNumber();
  1001. const array = new Array(size);
  1002. for (let i = 0; i < size; i++) {
  1003. array[i] = this.boolean();
  1004. }
  1005. return array;
  1006. }
  1007. matrix() {
  1008. const type = this.byte();
  1009. switch (type) {
  1010. case 100: {
  1011. // dense
  1012. this.assert('BMAT');
  1013. const elsize = this.uint64().toNumber();
  1014. const value = {};
  1015. value.name = this.string();
  1016. value.format = this.uint32();
  1017. value.rows = this.uint64().toNumber();
  1018. value.columns = this.uint64().toNumber();
  1019. this.read(elsize * value.rows * value.columns);
  1020. this.assert('EMAT');
  1021. return value;
  1022. }
  1023. case 115: // sparse
  1024. throw new cntk.Error('Matrix sparse type not implemented.');
  1025. default:
  1026. throw new cntk.Error(`Matrix type '${type}' not implemented.`);
  1027. }
  1028. }
  1029. shape(acceptLegacyFormat) {
  1030. const dims = [];
  1031. const rank = this.uint32();
  1032. let dim0 = 0;
  1033. if (rank > 0) {
  1034. dim0 = this.uint32();
  1035. }
  1036. if (!acceptLegacyFormat || dim0 !== 0) {
  1037. if (rank > 0) {
  1038. dims.push(dim0);
  1039. }
  1040. for (let i = 1; i < rank; i++) {
  1041. dims.push(this.uint32());
  1042. }
  1043. } else {
  1044. const dim = this.uint32();
  1045. dims.push(this.uint32());
  1046. dims.push(rank);
  1047. dims.push(dim);
  1048. }
  1049. return { __type__: 'shape', dims };
  1050. }
  1051. };
  1052. cntk.ImageLayoutKind = {
  1053. 0: 'CHW',
  1054. 1: 'HWC'
  1055. };
  1056. cntk.PoolKind = {
  1057. 0: 'None',
  1058. 1: 'Max',
  1059. 2: 'Average'
  1060. };
  1061. cntk.Error = class extends Error {
  1062. constructor(message) {
  1063. super(message);
  1064. this.name = 'Error loading CNTK model.';
  1065. }
  1066. };
  1067. export const ModelFactory = cntk.ModelFactory;