cntk.js 46 KB

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