cntk.js 46 KB

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