circle.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. import * as flatbuffers from '../source/flatbuffers.js';
  2. import * as flexbuffers from '../source/flexbuffers.js';
  3. import * as zip from '../source/zip.js';
  4. const circle = {};
  5. circle.ModelFactory = class {
  6. match(context) {
  7. const tags = context.tags('flatbuffers');
  8. if (tags.get('file_identifier') === 'CIR0') {
  9. return 'circle.flatbuffers';
  10. }
  11. const obj = context.peek('json');
  12. if (obj && obj.subgraphs && obj.operator_codes) {
  13. return 'circle.flatbuffers.json';
  14. }
  15. return undefined;
  16. }
  17. async open(context, target) {
  18. await context.require('./circle-schema');
  19. circle.schema = flatbuffers.get('circle').circle;
  20. let model = null;
  21. const attachments = new Map();
  22. switch (target) {
  23. case 'circle.flatbuffers.json': {
  24. try {
  25. const obj = context.peek('json');
  26. const reader = new flatbuffers.TextReader(obj);
  27. model = circle.schema.Model.createText(reader);
  28. } catch (error) {
  29. const message = error && error.message ? error.message : error.toString();
  30. throw new circle.Error('File text format is not circle.Model (' + message.replace(/\.$/, '') + ').');
  31. }
  32. break;
  33. }
  34. case 'circle.flatbuffers': {
  35. const stream = context.stream;
  36. try {
  37. const reader = flatbuffers.BinaryReader.open(stream);
  38. model = circle.schema.Model.create(reader);
  39. } catch (error) {
  40. const message = error && error.message ? error.message : error.toString();
  41. throw new circle.Error('File format is not circle.Model (' + message.replace(/\.$/, '') + ').');
  42. }
  43. try {
  44. const archive = zip.Archive.open(stream);
  45. if (archive) {
  46. for (const [name, value] of archive.entries) {
  47. attachments.set(name, value);
  48. }
  49. }
  50. } catch (error) {
  51. // continue regardless of error
  52. }
  53. break;
  54. }
  55. default: {
  56. throw new circle.Error("Unsupported Circle format '" + target + "'.");
  57. }
  58. }
  59. const metadata = await context.metadata('circle-metadata.json');
  60. return new circle.Model(metadata, model);
  61. }
  62. };
  63. circle.Model = class {
  64. constructor(metadata, model) {
  65. this._graphs = [];
  66. this._format = 'Circle';
  67. this._format = this._format + ' v' + model.version.toString();
  68. this._description = model.description || '';
  69. this._metadata = new Map();
  70. const builtinOperators = new Map();
  71. const upperCase = new Set([ '2D', 'LSH', 'SVDF', 'RNN', 'L2', 'LSTM' ]);
  72. for (const key of Object.keys(circle.schema.BuiltinOperator)) {
  73. const value = key === 'BATCH_MATMUL' ? 'BATCH_MAT_MUL' : key;
  74. const name = value.split('_').map((s) => (s.length < 1 || upperCase.has(s)) ? s : s[0] + s.substring(1).toLowerCase()).join('');
  75. const index = circle.schema.BuiltinOperator[key];
  76. builtinOperators.set(index, name);
  77. }
  78. const operators = model.operator_codes.map((operator) => {
  79. const code = operator.builtin_code || 0;
  80. const version = operator.version;
  81. const custom = code === circle.schema.BuiltinOperator.CUSTOM;
  82. const name = custom ? operator.custom_code ? operator.custom_code : 'Custom' : builtinOperators.has(code) ? builtinOperators.get(code) : code.toString();
  83. return custom ? { name: name, version: version, custom: true } : { name: name, version: version };
  84. });
  85. let modelMetadata = null;
  86. for (const metadata of model.metadata) {
  87. const buffer = model.buffers[metadata.buffer];
  88. if (buffer) {
  89. switch (metadata.name) {
  90. case 'min_runtime_version': {
  91. const data = buffer.data || new Uint8Array(0);
  92. this._runtime = new TextDecoder().decode(data);
  93. break;
  94. }
  95. case 'TFLITE_METADATA': {
  96. const data = buffer.data || new Uint8Array(0);
  97. const reader = flatbuffers.BinaryReader.open(data);
  98. if (circle.schema.ModelMetadata.identifier(reader)) {
  99. modelMetadata = circle.schema.ModelMetadata.create(reader);
  100. if (modelMetadata.name) {
  101. this._name = modelMetadata.name;
  102. }
  103. if (modelMetadata.version) {
  104. this._version = modelMetadata.version;
  105. }
  106. if (modelMetadata.description) {
  107. this._description = this._description ? [ this._description, modelMetadata.description].join(' ') : modelMetadata.description;
  108. }
  109. if (modelMetadata.author) {
  110. this._metadata.set('author', modelMetadata.author);
  111. }
  112. if (modelMetadata.license) {
  113. this._metadata.set('license', modelMetadata.license);
  114. }
  115. }
  116. break;
  117. }
  118. default: {
  119. break;
  120. }
  121. }
  122. }
  123. }
  124. const subgraphs = model.subgraphs;
  125. const subgraphsMetadata = modelMetadata ? modelMetadata.subgraph_metadata : null;
  126. for (let i = 0; i < subgraphs.length; i++) {
  127. const subgraph = subgraphs[i];
  128. const name = subgraphs.length > 1 ? i.toString() : '';
  129. const subgraphMetadata = subgraphsMetadata && i < subgraphsMetadata.length ? subgraphsMetadata[i] : null;
  130. this._graphs.push(new circle.Graph(metadata, subgraph, subgraphMetadata, name, operators, model));
  131. }
  132. }
  133. get format() {
  134. return this._format;
  135. }
  136. get runtime() {
  137. return this._runtime;
  138. }
  139. get name() {
  140. return this._name;
  141. }
  142. get version() {
  143. return this._version;
  144. }
  145. get description() {
  146. return this._description;
  147. }
  148. get metadata() {
  149. return this._metadata;
  150. }
  151. get graphs() {
  152. return this._graphs;
  153. }
  154. };
  155. circle.Graph = class {
  156. constructor(metadata, subgraph, subgraphMetadata, name, operators, model) {
  157. this._nodes = [];
  158. this._inputs = [];
  159. this._outputs = [];
  160. this._name = subgraph.name || name;
  161. const tensors = new Map();
  162. const args = (index) => {
  163. if (index === -1) {
  164. return null;
  165. }
  166. if (!tensors.has(index)) {
  167. if (index < subgraph.tensors.length) {
  168. const tensor = subgraph.tensors[index];
  169. const buffer = model.buffers[tensor.buffer];
  170. const is_variable = tensor.is_variable;
  171. const data = buffer ? buffer.data : null;
  172. const initializer = (data && data.length > 0) || is_variable ? new circle.Tensor(index, tensor, buffer, is_variable) : null;
  173. tensors.set(index, new circle.Value(index, tensor, initializer));
  174. } else {
  175. tensors.set(index, new circle.Value(index, { name: '' }, null));
  176. }
  177. }
  178. return tensors.get(index);
  179. };
  180. for (let i = 0; i < subgraph.operators.length; i++) {
  181. const node = subgraph.operators[i];
  182. const index = node.opcode_index;
  183. const operator = index < operators.length ? operators[index] : { name: '(' + index.toString() + ')' };
  184. this._nodes.push(new circle.Node(metadata, node, operator, i.toString(), args));
  185. }
  186. const applyTensorMetadata = (argument, tensorMetadata) => {
  187. if (tensorMetadata) {
  188. const description = tensorMetadata.description;
  189. if (description) {
  190. argument.description = description;
  191. }
  192. const content = tensorMetadata.content;
  193. if (argument.type && content) {
  194. let denotation = null;
  195. const contentProperties = content.content_properties;
  196. if (contentProperties instanceof circle.schema.FeatureProperties) {
  197. denotation = 'Feature';
  198. } else if (contentProperties instanceof circle.schema.ImageProperties) {
  199. denotation = 'Image';
  200. switch (contentProperties.color_space) {
  201. case 0: denotation += '(Unknown)'; break;
  202. case 1: denotation += '(RGB)'; break;
  203. case 2: denotation += '(Grayscale)'; break;
  204. default: throw circle.Error("Unsupported image color space '" + contentProperties.color_space + "'.");
  205. }
  206. } else if (contentProperties instanceof circle.schema.BoundingBoxProperties) {
  207. denotation = 'BoundingBox';
  208. } else if (contentProperties instanceof circle.schema.AudioProperties) {
  209. denotation = 'Audio(' + contentProperties.sample_rate.toString() + ',' + contentProperties.channels.toString() + ')';
  210. }
  211. if (denotation) {
  212. argument.type.denotation = denotation;
  213. }
  214. }
  215. }
  216. };
  217. const inputs = subgraph.inputs;
  218. for (let i = 0; i < inputs.length; i++) {
  219. const input = inputs[i];
  220. const value = args(input);
  221. if (subgraphMetadata && i < subgraphMetadata.input_tensor_metadata.length) {
  222. applyTensorMetadata(value, subgraphMetadata.input_tensor_metadata[i]);
  223. }
  224. this._inputs.push(new circle.Argument(value ? value.name : '?', true, value ? [ value ] : []));
  225. }
  226. const outputs = subgraph.outputs;
  227. for (let i = 0; i < outputs.length; i++) {
  228. const output = outputs[i];
  229. const value = args(output);
  230. if (subgraphMetadata && i < subgraphMetadata.output_tensor_metadata.length) {
  231. applyTensorMetadata(value, subgraphMetadata.output_tensor_metadata[i]);
  232. }
  233. this._outputs.push(new circle.Argument(value ? value.name : '?', true, value ? [ value ] : []));
  234. }
  235. }
  236. get name() {
  237. return this._name;
  238. }
  239. get inputs() {
  240. return this._inputs;
  241. }
  242. get outputs() {
  243. return this._outputs;
  244. }
  245. get nodes() {
  246. return this._nodes;
  247. }
  248. };
  249. circle.Node = class {
  250. constructor(metadata, node, type, location, args) {
  251. this._location = location;
  252. this._type = type.custom ? { name: type.name, category: 'custom' } : metadata.type(type.name);
  253. this._inputs = [];
  254. this._outputs = [];
  255. this._attributes = [];
  256. if (node) {
  257. let inputs = [];
  258. let outputs = [];
  259. inputs = Array.from(node.inputs || new Int32Array(0));
  260. outputs = Array.from(node.outputs || new Int32Array(0));
  261. let inputIndex = 0;
  262. while (inputIndex < inputs.length) {
  263. let count = 1;
  264. let inputName = null;
  265. let inputVisible = true;
  266. const inputArguments = [];
  267. if (this._type && this._type.inputs && inputIndex < this._type.inputs.length) {
  268. const input = this._type.inputs[inputIndex];
  269. inputName = input.name;
  270. if (input.option == 'variadic') {
  271. count = inputs.length - inputIndex;
  272. }
  273. if (input && input.visible === false) {
  274. inputVisible = false;
  275. }
  276. }
  277. const inputArray = inputs.slice(inputIndex, inputIndex + count);
  278. for (const index of inputArray) {
  279. const value = args(index);
  280. if (value) {
  281. inputArguments.push(value);
  282. }
  283. }
  284. inputIndex += count;
  285. inputName = inputName ? inputName : inputIndex.toString();
  286. this._inputs.push(new circle.Argument(inputName, inputVisible, inputArguments));
  287. }
  288. for (let k = 0; k < outputs.length; k++) {
  289. const index = outputs[k];
  290. const outputArguments = [];
  291. const value = args(index);
  292. if (value) {
  293. outputArguments.push(value);
  294. }
  295. let outputName = k.toString();
  296. if (this._type && this._type.outputs && k < this._type.outputs.length) {
  297. const output = this._type.outputs[k];
  298. if (output && output.name) {
  299. outputName = output.name;
  300. }
  301. }
  302. this._outputs.push(new circle.Argument(outputName, true, outputArguments));
  303. }
  304. if (type.custom && node.custom_options.length > 0) {
  305. let decoded = false;
  306. if (node.custom_options_format === circle.schema.CustomOptionsFormat.FLEXBUFFERS) {
  307. try {
  308. const reader = flexbuffers.BinaryReader.open(node.custom_options);
  309. if (reader) {
  310. const custom_options = reader.read();
  311. if (Array.isArray(custom_options)) {
  312. const attribute = new circle.Attribute(null, 'custom_options', custom_options);
  313. this._attributes.push(attribute);
  314. decoded = true;
  315. } else if (custom_options) {
  316. for (const [key, value] of Object.entries(custom_options)) {
  317. const schema = metadata.attribute(type.name, key);
  318. const attribute = new circle.Attribute(schema, key, value);
  319. this._attributes.push(attribute);
  320. }
  321. decoded = true;
  322. }
  323. }
  324. } catch (err) {
  325. // continue regardless of error
  326. }
  327. }
  328. if (!decoded) {
  329. const schema = metadata.attribute(type.name, 'custom');
  330. this._attributes.push(new circle.Attribute(schema, 'custom', Array.from(node.custom_options)));
  331. }
  332. }
  333. const options = node.builtin_options;
  334. if (options) {
  335. for (const [name, value] of Object.entries(options)) {
  336. if (name === 'fused_activation_function' && value !== 0) {
  337. const activationFunctionMap = { 1: 'Relu', 2: 'ReluN1To1', 3: 'Relu6', 4: 'Tanh', 5: 'SignBit' };
  338. if (!activationFunctionMap[value]) {
  339. throw new circle.Error("Unsupported activation funtion index '" + JSON.stringify(value) + "'.");
  340. }
  341. const type = activationFunctionMap[value];
  342. this._chain = [ new circle.Node(metadata, null, { name: type }, null, []) ];
  343. }
  344. const schema = metadata.attribute(type.name, name);
  345. this._attributes.push(new circle.Attribute(schema, name, value));
  346. }
  347. }
  348. }
  349. }
  350. get type() {
  351. return this._type;
  352. }
  353. get name() {
  354. return '';
  355. }
  356. get location() {
  357. return this._location;
  358. }
  359. get inputs() {
  360. return this._inputs;
  361. }
  362. get outputs() {
  363. return this._outputs;
  364. }
  365. get chain() {
  366. return this._chain;
  367. }
  368. get attributes() {
  369. return this._attributes;
  370. }
  371. };
  372. circle.Attribute = class {
  373. constructor(metadata, name, value) {
  374. this._name = name;
  375. this._value = ArrayBuffer.isView(value) ? Array.from(value) : value;
  376. this._type = metadata && metadata.type ? metadata.type : null;
  377. if (this._name === 'fused_activation_function') {
  378. this._visible = false;
  379. }
  380. if (this._type) {
  381. this._value = circle.Utility.enum(this._type, this._value);
  382. }
  383. if (metadata) {
  384. if (metadata.visible === false) {
  385. this._visible = false;
  386. } else if (metadata.default !== undefined) {
  387. value = this._value;
  388. if (typeof value === 'function') {
  389. value = value();
  390. }
  391. if (value === metadata.default) {
  392. this._visible = false;
  393. }
  394. }
  395. }
  396. }
  397. get name() {
  398. return this._name;
  399. }
  400. get type() {
  401. return this._type;
  402. }
  403. get value() {
  404. return this._value;
  405. }
  406. get visible() {
  407. return this._visible == false ? false : true;
  408. }
  409. };
  410. circle.Argument = class {
  411. constructor(name, visible, value) {
  412. this._name = name;
  413. this._visible = visible;
  414. this._value = value;
  415. }
  416. get name() {
  417. return this._name;
  418. }
  419. get visible() {
  420. return this._visible;
  421. }
  422. get value() {
  423. return this._value;
  424. }
  425. };
  426. circle.Value = class {
  427. constructor(index, tensor, initializer) {
  428. const name = tensor.name || '';
  429. this._name = name + '\n' + index.toString();
  430. this._location = index.toString();
  431. this._type = tensor.type !== undefined && tensor.shape !== undefined ? new circle.TensorType(tensor) : null;
  432. this._initializer = initializer;
  433. const quantization = tensor.quantization;
  434. if (quantization) {
  435. const length = Math.max(quantization.scale.length, quantization.zero_point.length, quantization.min.length, quantization.max.length);
  436. const list = [];
  437. for (let i = 0; i < length; i++) {
  438. let value = 'q';
  439. const scale = i < quantization.scale.length ? quantization.scale[i] : 0;
  440. const zeroPoint = (i < quantization.zero_point.length ? quantization.zero_point[i] : 0).toString();
  441. if (scale !== 0 || zeroPoint !== '0') {
  442. value = scale.toString() + ' * ' + (zeroPoint === '0' ? 'q' : ('(q' + (!zeroPoint.startsWith('-') ? ' - ' + zeroPoint : ' + ' + zeroPoint.substring(1)) + ')'));
  443. }
  444. if (i < quantization.min.length) {
  445. value = quantization.min[i].toString() + ' \u2264 ' + value;
  446. }
  447. if (i < quantization.max.length) {
  448. value = value + ' \u2264 ' + quantization.max[i].toString();
  449. }
  450. list.push(value);
  451. }
  452. if (list.length > 0 && !list.every((value) => value === 'q')) {
  453. this._quantization = list;
  454. }
  455. }
  456. }
  457. get name() {
  458. return this._name;
  459. }
  460. get location() {
  461. return this._location;
  462. }
  463. get type() {
  464. return this._type;
  465. }
  466. get quantization() {
  467. return this._quantization;
  468. }
  469. set description(value) {
  470. this._description = value;
  471. }
  472. get description() {
  473. return this._description;
  474. }
  475. get initializer() {
  476. return this._initializer;
  477. }
  478. };
  479. circle.Tensor = class {
  480. constructor(index, tensor, buffer, is_variable) {
  481. this._location = index.toString();
  482. this._type = new circle.TensorType(tensor);
  483. this._is_variable = is_variable;
  484. this._name = tensor.name;
  485. this._data = buffer.data.slice(0);
  486. }
  487. get category() {
  488. return this._is_variable ? 'Variable' : '';
  489. }
  490. get name() {
  491. return this._name;
  492. }
  493. get location() {
  494. return this._location;
  495. }
  496. get type() {
  497. return this._type;
  498. }
  499. get encoding() {
  500. switch (this._type.dataType) {
  501. case 'string': return '|';
  502. default: return '<';
  503. }
  504. }
  505. get values() {
  506. switch (this._type.dataType) {
  507. case 'string': {
  508. let offset = 0;
  509. const data = new DataView(this._data.buffer, this._data.byteOffset, this._data.byteLength);
  510. const count = data.getInt32(0, true);
  511. offset += 4;
  512. const offsetTable = [];
  513. for (let j = 0; j < count; j++) {
  514. offsetTable.push(data.getInt32(offset, true));
  515. offset += 4;
  516. }
  517. offsetTable.push(this._data.length);
  518. const stringTable = [];
  519. const utf8Decoder = new TextDecoder('utf-8');
  520. for (let k = 0; k < count; k++) {
  521. const textArray = this._data.subarray(offsetTable[k], offsetTable[k + 1]);
  522. stringTable.push(utf8Decoder.decode(textArray));
  523. }
  524. return stringTable;
  525. }
  526. default: return this._data;
  527. }
  528. }
  529. };
  530. circle.TensorType = class {
  531. constructor(tensor) {
  532. this._dataType = circle.Utility.dataType(tensor.type);
  533. this._shape = new circle.TensorShape(Array.from(tensor.shape || []));
  534. }
  535. get dataType() {
  536. return this._dataType;
  537. }
  538. get shape() {
  539. return this._shape;
  540. }
  541. set denotation(value) {
  542. this._denotation = value;
  543. }
  544. get denotation() {
  545. return this._denotation;
  546. }
  547. toString() {
  548. return this.dataType + this._shape.toString();
  549. }
  550. };
  551. circle.TensorShape = class {
  552. constructor(dimensions) {
  553. this._dimensions = dimensions;
  554. }
  555. get dimensions() {
  556. return this._dimensions;
  557. }
  558. toString() {
  559. if (!this._dimensions || this._dimensions.length == 0) {
  560. return '';
  561. }
  562. return '[' + this._dimensions.map((dimension) => dimension.toString()).join(',') + ']';
  563. }
  564. };
  565. circle.Utility = class {
  566. static dataType(type) {
  567. if (!circle.Utility._tensorTypeMap) {
  568. circle.Utility._tensorTypeMap = new Map(Object.entries(circle.schema.TensorType).map(([key, value]) => [ value, key.toLowerCase() ]));
  569. circle.Utility._tensorTypeMap.set(6, 'boolean');
  570. }
  571. return circle.Utility._tensorTypeMap.has(type) ? circle.Utility._tensorTypeMap.get(type) : '?';
  572. }
  573. static enum(name, value) {
  574. const type = name && circle.schema ? circle.schema[name] : undefined;
  575. if (type) {
  576. circle.Utility._enums = circle.Utility._enums || new Map();
  577. if (!circle.Utility._enums.has(name)) {
  578. const entries = new Map(Object.entries(type).map(([key, value]) => [ value, key ]));
  579. circle.Utility._enums.set(name, entries);
  580. }
  581. const map = circle.Utility._enums.get(name);
  582. if (map.has(value)) {
  583. return map.get(value);
  584. }
  585. }
  586. return value;
  587. }
  588. };
  589. circle.Error = class extends Error {
  590. constructor(message) {
  591. super(message);
  592. this.name = 'Error loading Circle model.';
  593. }
  594. };
  595. export const ModelFactory = circle.ModelFactory;