rknn.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. var rknn = rknn || {};
  2. var json = json || require('./json');
  3. rknn.ModelFactory = class {
  4. match(context) {
  5. return rknn.Reader.open(context);
  6. }
  7. open(context, match) {
  8. return rknn.Metadata.open(context).then((metadata) => {
  9. const reader = match;
  10. return new rknn.Model(metadata, reader.model, reader.weights);
  11. });
  12. }
  13. };
  14. rknn.Model = class {
  15. constructor(metadata, model, weights) {
  16. this._version = model.version;
  17. this._producer = model.ori_network_platform || model.network_platform || '';
  18. this._runtime = model.target_platform ? model.target_platform.join(',') : '';
  19. this._graphs = [ new rknn.Graph(metadata, model, weights) ];
  20. }
  21. get format() {
  22. return 'RKNN v' + this._version;
  23. }
  24. get producer() {
  25. return this._producer;
  26. }
  27. get runtime() {
  28. return this._runtime;
  29. }
  30. get graphs() {
  31. return this._graphs;
  32. }
  33. };
  34. rknn.Graph = class {
  35. constructor(metadata, model, weights) {
  36. this._name = model.name || '';
  37. this._inputs = [];
  38. this._outputs = [];
  39. this._nodes = [];
  40. const args = new Map();
  41. for (const const_tensor of model.const_tensor) {
  42. const name = 'const_tensor:' + const_tensor.tensor_id.toString();
  43. const shape = new rknn.TensorShape(const_tensor.size);
  44. const type = new rknn.TensorType(const_tensor.dtype, shape);
  45. const tensor = new rknn.Tensor(type, const_tensor.offset, weights);
  46. const argument = new rknn.Argument(name, type, tensor);
  47. args.set(name, argument);
  48. }
  49. for (const virtual_tensor of model.virtual_tensor) {
  50. const name = virtual_tensor.node_id.toString() + ':' + virtual_tensor.output_port.toString();
  51. const argument = new rknn.Argument(name, null, null);
  52. args.set(name, argument);
  53. }
  54. for (const norm_tensor of model.norm_tensor) {
  55. const name = 'norm_tensor:' + norm_tensor.tensor_id.toString();
  56. const shape = new rknn.TensorShape(norm_tensor.size);
  57. const type = new rknn.TensorType(norm_tensor.dtype, shape);
  58. const argument = new rknn.Argument(name, type, null);
  59. args.set(name, argument);
  60. }
  61. const arg = (name) => {
  62. if (!args.has(name)) {
  63. const argument = new rknn.Argument(name, null, null);
  64. args.set(name, argument);
  65. }
  66. return args.get(name);
  67. };
  68. for (const node of model.nodes) {
  69. node.input = [];
  70. node.output = [];
  71. }
  72. for (const connection of model.connection) {
  73. switch (connection.left) {
  74. case 'input':
  75. model.nodes[connection.node_id].input.push(connection);
  76. if (connection.right_node) {
  77. model.nodes[connection.right_node.node_id].output[connection.right_node.tensor_id] = connection;
  78. }
  79. break;
  80. case 'output':
  81. model.nodes[connection.node_id].output.push(connection);
  82. break;
  83. default:
  84. throw new rknn.Error("Unsupported left connection '" + connection.left + "'.");
  85. }
  86. }
  87. for (const graph of model.graph) {
  88. const key = graph.right + ':' + graph.right_tensor_id.toString();
  89. const argument = arg(key);
  90. const name = graph.left + (graph.left_tensor_id === 0 ? '' : graph.left_tensor_id.toString());
  91. const parameter = new rknn.Parameter(name, [ argument ]);
  92. switch (graph.left) {
  93. case 'input':
  94. this._inputs.push(parameter);
  95. break;
  96. case 'output':
  97. this._outputs.push(parameter);
  98. break;
  99. default:
  100. throw new rknn.Error("Unsupported left graph connection '" + graph.left + "'.");
  101. }
  102. }
  103. this._nodes = model.nodes.map((node) => new rknn.Node(metadata, node, arg));
  104. }
  105. get name() {
  106. return this._name;
  107. }
  108. get inputs() {
  109. return this._inputs;
  110. }
  111. get outputs() {
  112. return this._outputs;
  113. }
  114. get nodes() {
  115. return this._nodes;
  116. }
  117. };
  118. rknn.Parameter = class {
  119. constructor(name, args) {
  120. this._name = name;
  121. this._arguments = args;
  122. }
  123. get name() {
  124. return this._name;
  125. }
  126. get visible() {
  127. return true;
  128. }
  129. get arguments() {
  130. return this._arguments;
  131. }
  132. };
  133. rknn.Argument = class {
  134. constructor(name, type, initializer) {
  135. if (typeof name !== 'string') {
  136. throw new rknn.Error("Invalid argument identifier '" + JSON.stringify(name) + "'.");
  137. }
  138. this._name = name;
  139. this._type = type || null;
  140. this._initializer = initializer || null;
  141. }
  142. get name() {
  143. return this._name;
  144. }
  145. get type() {
  146. return this._type;
  147. }
  148. get initializer() {
  149. return this._initializer;
  150. }
  151. };
  152. rknn.Node = class {
  153. constructor(metadata, node, arg) {
  154. this._name = node.name || '';
  155. this._type = Object.assign({}, metadata.type(node.op) || { name: node.op });
  156. for (const prefix of [ 'VSI_NN_OP_', 'RKNN_OP_' ]) {
  157. this._type.name = this._type.name.startsWith(prefix) ? this._type.name.substring(prefix.length) : this._type.name;
  158. }
  159. this._inputs = [];
  160. this._outputs = [];
  161. this._attributes = [];
  162. node.input = node.input || [];
  163. for (let i = 0; i < node.input.length; ) {
  164. const input = this._type && this._type.inputs && i < this._type.inputs.length ? this._type.inputs[i] : { name: i === 0 ? 'input' : i.toString() };
  165. const count = input.list ? node.input.length - i : 1;
  166. const list = node.input.slice(i, i + count).map((input) => {
  167. if (input.right_tensor) {
  168. return arg(input.right_tensor.type + ':' + input.right_tensor.tensor_id.toString());
  169. }
  170. if (input.right_node) {
  171. return arg(input.right_node.node_id.toString() + ':' + input.right_node.tensor_id.toString());
  172. }
  173. throw new rknn.Error('Invalid input argument.');
  174. });
  175. this._inputs.push(new rknn.Parameter(input.name, list));
  176. i += count;
  177. }
  178. node.output = node.output || [];
  179. for (let i = 0; i < node.output.length; ) {
  180. const output = this._metadata && this._metadata.outputs && i < this._metadata.outputs.length ? this._metadata.outputs[i] : { name: i === 0 ? 'output' : i.toString() };
  181. const count = output.list ? node.output.length - i : 1;
  182. const list = node.output.slice(i, i + count).map((output) => {
  183. if (output.right_tensor) {
  184. return arg(output.right_tensor.type + ':' + output.right_tensor.tensor_id.toString());
  185. }
  186. if (output.right_node) {
  187. return arg(output.right_node.node_id.toString() + ':' + output.right_node.tensor_id.toString());
  188. }
  189. throw new rknn.Error('Invalid output argument.');
  190. });
  191. this._outputs.push(new rknn.Parameter(output.name, list));
  192. i += count;
  193. }
  194. if (node.nn) {
  195. const nn = node.nn;
  196. for (const key of Object.keys(nn)) {
  197. const params = nn[key];
  198. for (const name of Object.keys(params)) {
  199. const value = params[name];
  200. this._attributes.push(new rknn.Attribute(name, value));
  201. }
  202. }
  203. }
  204. }
  205. get name() {
  206. return this._name;
  207. }
  208. get type() {
  209. return this._type;
  210. }
  211. get inputs() {
  212. return this._inputs;
  213. }
  214. get outputs() {
  215. return this._outputs;
  216. }
  217. get attributes() {
  218. return this._attributes;
  219. }
  220. };
  221. rknn.Attribute = class {
  222. constructor(name, value) {
  223. this._name = name;
  224. this._value = value;
  225. }
  226. get name() {
  227. return this._name;
  228. }
  229. get value() {
  230. return this._value;
  231. }
  232. };
  233. rknn.Tensor = class {
  234. constructor(type, offset, weights) {
  235. this._type = type;
  236. let size = 0;
  237. switch (this._type.dataType) {
  238. case 'uint8': size = 1; break;
  239. case 'int8': size = 1; break;
  240. case 'int16': size = 2; break;
  241. case 'int32': size = 4; break;
  242. case 'int64': size = 8; break;
  243. case 'float16': size = 2; break;
  244. case 'float32': size = 4; break;
  245. case 'float64': size = 8; break;
  246. default: throw new rknn.Error("Unsupported tensor data type '" + this._type.dataType + "'.");
  247. }
  248. const shape = type.shape.dimensions;
  249. size = size * shape.reduce((a, b) => a * b, 1);
  250. if (size > 0) {
  251. this._data = weights.slice(offset, offset + size);
  252. }
  253. }
  254. get type() {
  255. return this._type;
  256. }
  257. get state() {
  258. return this._context().state || null;
  259. }
  260. get value() {
  261. const context = this._context();
  262. if (context.state) {
  263. return null;
  264. }
  265. context.limit = Number.MAX_SAFE_INTEGER;
  266. return this._decode(context, 0);
  267. }
  268. toString() {
  269. const context = this._context();
  270. if (context.state) {
  271. return '';
  272. }
  273. context.limit = 10000;
  274. const value = this._decode(context, 0);
  275. return JSON.stringify(value, '', ' ');
  276. }
  277. _context() {
  278. const context = {};
  279. if (!this._type.dataType) {
  280. context.state = 'Tensor data type is not implemented.';
  281. return context;
  282. }
  283. if (!this._data) {
  284. context.state = 'Tensor data is empty.';
  285. return context;
  286. }
  287. context.index = 0;
  288. context.count = 0;
  289. context.shape = this._type.shape.dimensions;
  290. context.dataType = this._type.dataType;
  291. context.view = new DataView(this._data.buffer, this._data.byteOffset, this._data.byteLength);
  292. return context;
  293. }
  294. _decode(context, dimension) {
  295. const shape = context.shape.length !== 0 ? context.shape : [ 1 ];
  296. const results = [];
  297. const size = shape[dimension];
  298. if (dimension == shape.length - 1) {
  299. for (let i = 0; i < size; i++) {
  300. if (context.count > context.limit) {
  301. results.push('...');
  302. return results;
  303. }
  304. switch (context.dataType) {
  305. case 'float16':
  306. results.push(context.view.getFloat16(context.index, true));
  307. context.index += 2;
  308. context.count++;
  309. break;
  310. case 'float32':
  311. results.push(context.view.getFloat32(context.index, true));
  312. context.index += 4;
  313. context.count++;
  314. break;
  315. case 'float64':
  316. results.push(context.view.getFloat64(context.index, true));
  317. context.index += 8;
  318. context.count++;
  319. break;
  320. case 'uint8':
  321. results.push(context.view.getUint8(context.index, true));
  322. context.index++;
  323. context.count++;
  324. break;
  325. case 'int8':
  326. results.push(context.view.getInt8(context.index, true));
  327. context.index += 1;
  328. context.count++;
  329. break;
  330. case 'int16':
  331. results.push(context.view.getInt16(context.index, true));
  332. context.index += 2;
  333. context.count++;
  334. break;
  335. case 'int32':
  336. results.push(context.view.getInt32(context.index, true));
  337. context.index += 4;
  338. context.count++;
  339. break;
  340. case 'int64':
  341. results.push(context.view.getInt64(context.index, true));
  342. context.index += 8;
  343. context.count++;
  344. break;
  345. default:
  346. throw new rknn.Error("Unsupported tensor data type '" + context.dataType + "'.");
  347. }
  348. }
  349. }
  350. else {
  351. for (let j = 0; j < size; j++) {
  352. if (context.count > context.limit) {
  353. results.push('...');
  354. return results;
  355. }
  356. results.push(this._decode(context, dimension + 1));
  357. }
  358. }
  359. if (context.shape.length == 0) {
  360. return results[0];
  361. }
  362. return results;
  363. }
  364. };
  365. rknn.TensorType = class {
  366. constructor(dataType, shape) {
  367. const type = dataType.vx_type.startsWith('VSI_NN_TYPE_') ? dataType.vx_type.split('_').pop().toLowerCase() : dataType.vx_type;
  368. switch (type) {
  369. case 'uint8':
  370. case 'int8':
  371. case 'int16':
  372. case 'int32':
  373. case 'int64':
  374. case 'float16':
  375. case 'float32':
  376. case 'float64':
  377. case 'vdata':
  378. this._dataType = type;
  379. break;
  380. default:
  381. if (dataType.vx_type !== '') {
  382. throw new rknn.Error("Invalid data type '" + JSON.stringify(dataType) + "'.");
  383. }
  384. this._dataType = '?';
  385. break;
  386. }
  387. this._shape = shape;
  388. }
  389. get dataType() {
  390. return this._dataType;
  391. }
  392. get shape() {
  393. return this._shape;
  394. }
  395. toString() {
  396. return this.dataType + this._shape.toString();
  397. }
  398. };
  399. rknn.TensorShape = class {
  400. constructor(shape) {
  401. this._dimensions = shape;
  402. }
  403. get dimensions() {
  404. return this._dimensions;
  405. }
  406. toString() {
  407. if (!this._dimensions || this._dimensions.length == 0) {
  408. return '';
  409. }
  410. return '[' + this._dimensions.join(',') + ']';
  411. }
  412. };
  413. rknn.Reader = class {
  414. static open(context) {
  415. const stream = context.stream;
  416. if (stream.length >= 8) {
  417. const buffer = stream.read(8);
  418. const decoder = new TextDecoder();
  419. const signature = decoder.decode(buffer);
  420. if (signature === 'RKNN\0\0\0\0' || signature === 'CYPTRKNN') {
  421. return new rknn.Reader(stream, signature);
  422. }
  423. }
  424. return null;
  425. }
  426. constructor(stream, signature) {
  427. this._stream = stream;
  428. this._signature = signature;
  429. }
  430. get version() {
  431. this._decode();
  432. return this._version;
  433. }
  434. get weights() {
  435. this._decode();
  436. return this._weights;
  437. }
  438. get model() {
  439. this._decode();
  440. return this._model;
  441. }
  442. _decode() {
  443. if (this._stream) {
  444. if (this._signature === 'CYPTRKNN') {
  445. throw new rknn.Error('Invalid file content. File contains undocumented encrypted RKNN data.');
  446. }
  447. this._version = this._uint64();
  448. const weights_size = this._uint64();
  449. if (this._version > 1) {
  450. this._stream.read(40);
  451. }
  452. this._weights = this._stream.read(weights_size);
  453. const model_size = this._uint64();
  454. const model_buffer = this._stream.read(model_size);
  455. const reader = json.TextReader.open(model_buffer);
  456. this._model = reader.read();
  457. delete this._stream;
  458. }
  459. }
  460. _uint64() {
  461. const buffer = this._stream.read(8);
  462. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  463. return view.getUint64(0, true).toNumber();
  464. }
  465. _read() {
  466. const size = this._uint64();
  467. return this._stream.read(size);
  468. }
  469. };
  470. rknn.Metadata = class {
  471. static open(context) {
  472. if (rknn.Metadata._metadata) {
  473. return Promise.resolve(rknn.Metadata._metadata);
  474. }
  475. return context.request('rknn-metadata.json', 'utf-8', null).then((data) => {
  476. rknn.Metadata._metadata = new rknn.Metadata(data);
  477. return rknn.Metadata._metadata;
  478. }).catch(() => {
  479. rknn.Metadata._metadata = new rknn.Metadata(null);
  480. return rknn.Metadata._metadata;
  481. });
  482. }
  483. constructor(data) {
  484. this._types = new Map();
  485. this._attributes = new Map();
  486. if (data) {
  487. const items = JSON.parse(data);
  488. for (const item of items) {
  489. this._types.set(item.name, item);
  490. }
  491. }
  492. }
  493. type(name) {
  494. if (!this._types.has(name)) {
  495. this._types.set(name, { name: name });
  496. }
  497. return this._types.get(name);
  498. }
  499. attribute(type, name) {
  500. const key = type + ':' + name;
  501. if (!this._attributes.has(key)) {
  502. this._attributes.set(key, null);
  503. const metadata = this.type(type);
  504. if (metadata && Array.isArray(metadata.attributes)) {
  505. for (const attribute of metadata.attributes) {
  506. this._attributes.set(type + ':' + attribute.name, attribute);
  507. }
  508. }
  509. }
  510. return this._attributes.get(key);
  511. }
  512. };
  513. rknn.Error = class extends Error {
  514. constructor(message) {
  515. super(message);
  516. this.name = 'Error loading RKNN model.';
  517. }
  518. };
  519. if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  520. module.exports.ModelFactory = rknn.ModelFactory;
  521. }