tflite.js 23 KB

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