rknn.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. import * as base from './base.js';
  2. import * as flatbuffers from './flatbuffers.js';
  3. import * as json from './json.js';
  4. const rknn = {};
  5. const openvx = {};
  6. rknn.ModelFactory = class {
  7. async match(context) {
  8. const container = await rknn.Container.open(context);
  9. if (container) {
  10. return context.set('rknn', container);
  11. }
  12. return null;
  13. }
  14. async open(context) {
  15. rknn.schema = await context.require('./rknn-schema');
  16. rknn.schema = rknn.schema.rknn;
  17. const metadata = await context.metadata('rknn-metadata.json');
  18. const target = context.value;
  19. target.read();
  20. if (target.has('json')) {
  21. const buffer = target.get('json');
  22. const reader = json.TextReader.open(buffer);
  23. const model = reader.read();
  24. return new rknn.Model(metadata, 'json', model, target);
  25. }
  26. if (target.has('flatbuffers')) {
  27. const buffer = target.get('flatbuffers');
  28. const reader = flatbuffers.BinaryReader.open(buffer);
  29. const model = rknn.schema.Model.create(reader);
  30. return new rknn.Model(metadata, 'flatbuffers', model, null);
  31. }
  32. if (target.has('openvx')) {
  33. const buffer = target.get('openvx');
  34. const model = new openvx.Model(buffer);
  35. return new rknn.Model(metadata, 'openvx', model, null);
  36. }
  37. throw new rknn.Error("Unsupported RKNN format.");
  38. }
  39. };
  40. rknn.Model = class {
  41. constructor(metadata, type, model, container) {
  42. switch (type) {
  43. case 'json': {
  44. this.format = `RKNN v${model.version.split('-').shift()}`;
  45. this.name = model.name || '';
  46. this.producer = model.ori_network_platform || model.network_platform || '';
  47. this.runtime = model.target_platform ? model.target_platform.join(',') : '';
  48. this.modules = [new rknn.Graph(metadata, type, model.name || '', model, container)];
  49. break;
  50. }
  51. case 'flatbuffers': {
  52. const version = model.compiler.split('-').shift();
  53. this.format = `RKNN Lite${version ? ` v${version}` : ''}`;
  54. this.runtime = model.runtime;
  55. this.name = model.name || '';
  56. this.modules = model.graphs.map((graph) => new rknn.Graph(metadata, type, '', graph, null));
  57. this.source = model.source;
  58. break;
  59. }
  60. case 'openvx': {
  61. this.format = 'RKNN OpenVX';
  62. this.name = model.name || '';
  63. this.modules = [new rknn.Graph(metadata, type, '', model, container)];
  64. break;
  65. }
  66. default: {
  67. throw new rknn.Error(`Unsupported RKNN model type '${type}'.`);
  68. }
  69. }
  70. }
  71. };
  72. rknn.Graph = class {
  73. constructor(metadata, type, name, obj, container) {
  74. this.name = name;
  75. this.inputs = [];
  76. this.outputs = [];
  77. this.nodes = [];
  78. switch (type) {
  79. case 'json': {
  80. const dataType = (value) => {
  81. const type = value.vx_type.startsWith('VSI_NN_TYPE_') ? value.vx_type.split('_').pop().toLowerCase() : value.vx_type;
  82. switch (type) {
  83. case 'uint8':
  84. case 'int8':
  85. case 'int16':
  86. case 'int32':
  87. case 'int64':
  88. case 'float16':
  89. case 'float32':
  90. case 'float64':
  91. case 'vdata':
  92. return type;
  93. default:
  94. if (value.vx_type !== '') {
  95. throw new rknn.Error(`Invalid data type '${JSON.stringify(dataType)}'.`);
  96. }
  97. return '?';
  98. }
  99. };
  100. const model = obj;
  101. const values = new Map();
  102. for (const const_tensor of model.const_tensor) {
  103. const name = `const_tensor:${const_tensor.tensor_id}`;
  104. const shape = new rknn.TensorShape(const_tensor.size);
  105. if (const_tensor.data_type === 0) {
  106. const value = new rknn.Value(name, null, null);
  107. values.set(name, value);
  108. } else {
  109. const type = new rknn.TensorType(dataType(const_tensor.dtype), shape);
  110. const tensor = new rknn.Tensor(type, const_tensor.offset, undefined, null);
  111. const value = new rknn.Value(name, type, tensor);
  112. values.set(name, value);
  113. }
  114. }
  115. for (const virtual_tensor of model.virtual_tensor) {
  116. const name = `${virtual_tensor.node_id}:${virtual_tensor.output_port}`;
  117. const value = new rknn.Value(name, null, null);
  118. values.set(name, value);
  119. }
  120. for (const norm_tensor of model.norm_tensor) {
  121. const name = `norm_tensor:${norm_tensor.tensor_id}`;
  122. const shape = new rknn.TensorShape(norm_tensor.size);
  123. if (norm_tensor.dtype === 0) {
  124. const value = new rknn.Value(name, null, null);
  125. values.set(name, value);
  126. } else {
  127. const type = new rknn.TensorType(dataType(norm_tensor.dtype), shape);
  128. const value = new rknn.Value(name, type, null);
  129. values.set(name, value);
  130. }
  131. }
  132. const value = (name) => {
  133. if (!values.has(name)) {
  134. values.set(name, new rknn.Value(name, null, null));
  135. }
  136. return values.get(name);
  137. };
  138. for (const node of model.nodes) {
  139. node.input = [];
  140. node.output = [];
  141. }
  142. for (const connection of model.connection) {
  143. switch (connection.left) {
  144. case 'input':
  145. model.nodes[connection.node_id].input.push(connection);
  146. if (connection.right_node) {
  147. model.nodes[connection.right_node.node_id].output[connection.right_node.tensor_id] = connection;
  148. }
  149. break;
  150. case 'output':
  151. model.nodes[connection.node_id].output.push(connection);
  152. break;
  153. default:
  154. throw new rknn.Error(`Unsupported left connection '${connection.left}'.`);
  155. }
  156. }
  157. for (const graph of model.graph) {
  158. const key = `${graph.right}:${graph.right_tensor_id}`;
  159. const name = graph.left + (graph.left_tensor_id === 0 ? '' : graph.left_tensor_id.toString());
  160. const argument = new rknn.Argument(name, [value(key)]);
  161. switch (graph.left) {
  162. case 'input':
  163. this.inputs.push(argument);
  164. break;
  165. case 'output':
  166. this.outputs.push(argument);
  167. break;
  168. default:
  169. throw new rknn.Error(`Unsupported left graph connection '${graph.left}'.`);
  170. }
  171. }
  172. this.nodes = model.nodes.map((node) => new rknn.Node(metadata, type, node, value, container));
  173. break;
  174. }
  175. case 'flatbuffers': {
  176. const graph = obj;
  177. const dataTypes = ['?', 'float32', 'uint8', 'int8', 'uint16', 'int16', 'int32', 'int64', 'string', 'boolean', 'float16', 'float64', 'uint32', 'uint64', 'complex<float32>', 'complex<float64>', 'bfloat16'];
  178. const args = graph.tensors.map((tensor) => {
  179. const shape = new rknn.TensorShape(Array.from(tensor.shape));
  180. const dataType = tensor.data_type < dataTypes.length ? dataTypes[tensor.data_type] : '?';
  181. const type = new rknn.TensorType(dataType, shape);
  182. const initializer = tensor.kind !== 4 && tensor.kind !== 5 ? null : new rknn.Tensor(type, 0, tensor.size, null);
  183. return new rknn.Value(tensor.name, type, initializer);
  184. });
  185. const arg = (index) => {
  186. if (index >= args.length) {
  187. throw new rknn.Error(`Invalid tensor index '${index}'.`);
  188. }
  189. return args[index];
  190. };
  191. this.nodes = graph.nodes.map((node) => new rknn.Node(metadata, type, node, arg, container));
  192. break;
  193. }
  194. case 'openvx': {
  195. const model = obj;
  196. this.nodes = model.nodes.map((node) => new rknn.Node(metadata, type, node, null, container));
  197. break;
  198. }
  199. default: {
  200. throw new rknn.Error(`Unsupported RKNN graph type '${type}'.`);
  201. }
  202. }
  203. }
  204. };
  205. rknn.Argument = class {
  206. constructor(name, value) {
  207. this.name = name;
  208. this.value = value;
  209. }
  210. };
  211. rknn.Value = class {
  212. constructor(name, type = null, initializer = null) {
  213. if (typeof name !== 'string') {
  214. throw new rknn.Error(`Invalid value identifier '${JSON.stringify(name)}'.`);
  215. }
  216. this.name = name;
  217. this.type = type;
  218. this.initializer = initializer;
  219. }
  220. };
  221. rknn.Node = class {
  222. constructor(metadata, type, node, value, container) {
  223. this.inputs = [];
  224. this.outputs = [];
  225. this.attributes = [];
  226. switch (type) {
  227. case 'json': {
  228. this.name = node.name || '';
  229. if (node.op === 'VSI_NN_OP_NBG' && container && container.has('openvx')) {
  230. const buffer = container.get('openvx');
  231. const model = new openvx.Model(buffer);
  232. this.type = new rknn.Graph(metadata, 'openvx', 'NBG', model, null);
  233. } else if (node.op === 'RKNN_OP_NNBG' && container && container.has('flatbuffers')) {
  234. const buffer = container.get('flatbuffers');
  235. const reader = flatbuffers.BinaryReader.open(buffer);
  236. const model = rknn.schema.Model.create(reader);
  237. this.type = new rknn.Graph(metadata, 'flatbuffers', 'NNBG', model.graphs[0], null);
  238. } else {
  239. const type = metadata.type(node.op);
  240. this.type = type ? { ...type } : { name: node.op };
  241. for (const prefix of ['VSI_NN_OP_', 'RKNN_OP_']) {
  242. this.type.name = this.type.name.startsWith(prefix) ? this.type.name.substring(prefix.length) : this.type.name;
  243. }
  244. }
  245. node.input = node.input || [];
  246. for (let i = 0; i < node.input.length;) {
  247. const input = this.type && this.type.inputs && i < this.type.inputs.length ? this.type.inputs[i] : { name: i === 0 ? 'input' : i.toString() };
  248. const count = input.list ? node.input.length - i : 1;
  249. const list = node.input.slice(i, i + count).map((input) => {
  250. if (input.right_tensor) {
  251. return value(`${input.right_tensor.type}:${input.right_tensor.tensor_id}`);
  252. }
  253. if (input.right_node) {
  254. return value(`${input.right_node.node_id}:${input.right_node.tensor_id}`);
  255. }
  256. throw new rknn.Error('Invalid input argument.');
  257. });
  258. this.inputs.push(new rknn.Argument(input.name, list));
  259. i += count;
  260. }
  261. node.output = node.output || [];
  262. for (let i = 0; i < node.output.length;) {
  263. const output = this.type.outputs && i < this.type.outputs.length ? this.type.outputs[i] : { name: i === 0 ? 'output' : i.toString() };
  264. const count = output.list ? node.output.length - i : 1;
  265. const list = node.output.slice(i, i + count).map((output) => {
  266. if (output.right_tensor) {
  267. return value(`${output.right_tensor.type}:${output.right_tensor.tensor_id}`);
  268. }
  269. if (output.right_node) {
  270. return value(`${output.right_node.node_id}:${output.right_node.tensor_id}`);
  271. }
  272. throw new rknn.Error('Invalid output argument.');
  273. });
  274. this.outputs.push(new rknn.Argument(output.name, list));
  275. i += count;
  276. }
  277. if (node.nn) {
  278. for (const params of Object.values(node.nn)) {
  279. for (const [name, value] of Object.entries(params)) {
  280. const attribute = new rknn.Argument(name, value);
  281. this.attributes.push(attribute);
  282. }
  283. }
  284. }
  285. break;
  286. }
  287. case 'flatbuffers': {
  288. this.name = node.name;
  289. this.type = metadata.type(node.type);
  290. if (node.inputs.length > 0) {
  291. const inputs = this.type.inputs || (node.inputs.length === 1 ? [{ name: "input" }] : [{ name: "inputs", list: true }]);
  292. if (Array.isArray(inputs) && inputs.length > 0 && inputs[0].list === true) {
  293. this.inputs = [new rknn.Argument(inputs[0].name, Array.from(node.inputs).map((input) => value(input)))];
  294. } else {
  295. this.inputs = Array.from(node.inputs).map((input, index) => {
  296. return new rknn.Argument(index < inputs.length ? inputs[index].name : index.toString(), [value(input)]);
  297. });
  298. }
  299. }
  300. if (node.outputs.length > 0) {
  301. const outputs = this.type.outputs || (node.outputs.length === 1 ? [{ name: "output" }] : [{ name: "outputs", list: true }]);
  302. if (Array.isArray(outputs) && outputs.length > 0 && outputs[0].list === true) {
  303. const values = Array.from(node.outputs).map((output) => value(output));
  304. const argument = new rknn.Argument(outputs[0].name, values);
  305. this.outputs = [argument];
  306. } else {
  307. this.outputs = Array.from(node.outputs).map((output, index) => {
  308. return new rknn.Argument(index < outputs.length ? outputs[index].name : index.toString(), [value(output)]);
  309. });
  310. }
  311. }
  312. break;
  313. }
  314. case 'openvx': {
  315. this.name = '';
  316. this.type = metadata.type(node.type);
  317. break;
  318. }
  319. default: {
  320. throw new rknn.Error(`Unsupported RKNN node type '${type}'.`);
  321. }
  322. }
  323. }
  324. };
  325. rknn.Tensor = class {
  326. constructor(type, offset, size, weights) {
  327. this.type = type;
  328. this.values = null;
  329. let itemsize = 0;
  330. switch (this.type.dataType) {
  331. case 'uint8': itemsize = 1; break;
  332. case 'int8': itemsize = 1; break;
  333. case 'int16': itemsize = 2; break;
  334. case 'int32': itemsize = 4; break;
  335. case 'int64': itemsize = 8; break;
  336. case 'uint16': itemsize = 2; break;
  337. case 'uint32': itemsize = 4; break;
  338. case 'uint64': itemsize = 8; break;
  339. case 'float16': itemsize = 2; break;
  340. case 'bfloat16': itemsize = 2; break;
  341. case 'float32': itemsize = 4; break;
  342. case 'float64': itemsize = 8; break;
  343. case 'boolean': itemsize = 1; break;
  344. case 'vdata': itemsize = 1; break;
  345. case 'string': itemsize = 1; break;
  346. case '?': itemsize = 0; break;
  347. default: throw new rknn.Error(`Unsupported tensor data type '${this.type.dataType}'.`);
  348. }
  349. if (weights) {
  350. const shape = type.shape.dimensions;
  351. const count = shape.reduce((a, b) => a * b, 1);
  352. const length = itemsize * count;
  353. if (length > 0) {
  354. if (size !== undefined && size !== length) {
  355. throw new rknn.Error(`Tensor size mismatch for '${this.type.dataType}'. Expected '${length}' bytes but got '${size}' bytes.`);
  356. }
  357. this.values = weights.slice(offset, offset + length);
  358. }
  359. }
  360. }
  361. };
  362. rknn.TensorType = class {
  363. constructor(dataType, shape) {
  364. this.dataType = dataType;
  365. this.shape = shape;
  366. }
  367. toString() {
  368. return this.dataType + this.shape.toString();
  369. }
  370. };
  371. rknn.TensorShape = class {
  372. constructor(dimensions) {
  373. this.dimensions = dimensions;
  374. }
  375. toString() {
  376. if (!this.dimensions || this.dimensions.length === 0) {
  377. return '';
  378. }
  379. return `[${this.dimensions.join(',')}]`;
  380. }
  381. };
  382. rknn.Container = class extends Map {
  383. static async open(context) {
  384. const stream = context.stream;
  385. if (stream) {
  386. const signature = rknn.Container.signature(stream);
  387. switch (signature) {
  388. case 'rknn':
  389. case 'openvx':
  390. case 'flatbuffers':
  391. case 'cyptrknn':
  392. return new rknn.Container(stream, signature);
  393. default:
  394. break;
  395. }
  396. const obj = await context.peek('json');
  397. if (obj && obj.version && Array.isArray(obj.nodes) && obj.network_platform) {
  398. const entries = new Map();
  399. entries.set('json', stream);
  400. return new rknn.Container(null, null, entries);
  401. }
  402. }
  403. return null;
  404. }
  405. constructor(stream, signature, entries) {
  406. super(entries);
  407. this.stream = stream;
  408. this.signature = signature;
  409. }
  410. read() {
  411. const stream = this.stream;
  412. if (stream) {
  413. switch (this.signature) {
  414. case 'rknn': {
  415. const uint64 = () => {
  416. const buffer = stream.read(8);
  417. const reader = base.BinaryReader.open(buffer);
  418. return reader.uint64();
  419. };
  420. stream.skip(8);
  421. const version = uint64();
  422. if ((version >> 8n) !== 0n && (version >> 8n) !== 0x10n) {
  423. throw new rknn.Error(`Unsupported RKNN container version '${version}'.`);
  424. }
  425. const data_size = uint64().toNumber();
  426. if ((version & 0xffn) > 1n && data_size > 0) {
  427. stream.skip(40);
  428. }
  429. const signature = rknn.Container.signature(stream, data_size);
  430. const data = stream.read(data_size);
  431. const json_size = uint64().toNumber();
  432. const json = stream.read(json_size);
  433. this.set('json', json);
  434. if (signature) {
  435. this.set(signature, data);
  436. }
  437. break;
  438. }
  439. case 'openvx':
  440. case 'flatbuffers': {
  441. this.set(this.signature, stream.peek());
  442. break;
  443. }
  444. case 'cyptrknn': {
  445. throw new rknn.Error('Invalid file content. File contains undocumented encrypted RKNN data.');
  446. }
  447. default: {
  448. break;
  449. }
  450. }
  451. delete this.stream;
  452. }
  453. }
  454. static signature(stream, length) {
  455. length = length || stream.length;
  456. if (stream && (stream.position + 16) <= length) {
  457. const signature = [0x52, 0x4B, 0x4E, 0x4E]; // RKNN
  458. if (stream.peek(signature.length).every((value, index) => value === signature[index])) {
  459. return 'rknn';
  460. }
  461. }
  462. if (stream && (stream.position + 16) <= length) {
  463. const signature = [0x43, 0x59, 0x50, 0x54, 0x52, 0x4B, 0x4E, 0x4E]; // CYPTRKNN
  464. if (stream.peek(signature.length).every((value, index) => value === signature[index])) {
  465. return 'cyptrknn';
  466. }
  467. }
  468. if (stream && (stream.position + 8) <= length) {
  469. const signature = [0x52, 0x4B, 0x4E, 0x4E]; // RKNN
  470. if (stream.peek(8).subarray(4, 8).every((value, index) => value === signature[index])) {
  471. return 'flatbuffers';
  472. }
  473. }
  474. if (stream && (stream.position + 8) <= length) {
  475. const signature = [0x56, 0x50, 0x4D, 0x4E]; // VPMN
  476. if (stream.peek(signature.length).every((value, index) => value === signature[index])) {
  477. return 'openvx';
  478. }
  479. }
  480. return undefined;
  481. }
  482. };
  483. openvx.BufferReader = class {
  484. constructor(buffer) {
  485. this._reader = base.BinaryReader.open(buffer);
  486. }
  487. seek(position) {
  488. this._reader.seek(position);
  489. }
  490. skip(offset) {
  491. this._reader.skip(offset);
  492. }
  493. read(length) {
  494. return this._reader.read(length);
  495. }
  496. uint16() {
  497. return this._reader.uint16();
  498. }
  499. uint32() {
  500. return this._reader.uint32();
  501. }
  502. string(length) {
  503. const buffer = this.read(length);
  504. const index = buffer.indexOf(0);
  505. const data = index === -1 ? buffer : buffer.subarray(0, index);
  506. this._decoder = this._decoder || new TextDecoder('ascii');
  507. return this._decoder.decode(data);
  508. }
  509. };
  510. openvx.Model = class {
  511. constructor(buffer) {
  512. const reader = new openvx.BufferReader(buffer);
  513. reader.skip(4); // signature
  514. const major = reader.uint16();
  515. /* const minor = */ reader.uint16();
  516. reader.skip(4);
  517. this.name = reader.string(64);
  518. this.nodes = new Array(reader.uint32());
  519. if (major > 3) {
  520. reader.skip(296);
  521. } else if (major > 1) {
  522. reader.skip(288);
  523. } else {
  524. reader.skip(32);
  525. }
  526. /* const inputOffset = */ reader.uint32();
  527. /* const inputSize = */ reader.uint32();
  528. /* const outputOffset = */ reader.uint32();
  529. /* const outputSize = */ reader.uint32();
  530. const nodeOffset = reader.uint32();
  531. /* const nodeSize = */ reader.uint32();
  532. reader.seek(nodeOffset);
  533. for (let i = 0; i < this.nodes.length; i++) {
  534. const type = reader.string(64);
  535. const node = { type };
  536. node.index = reader.uint32();
  537. node.c = reader.uint32();
  538. if (major > 3) {
  539. node.d = reader.uint32();
  540. }
  541. this.nodes[i] = node;
  542. }
  543. }
  544. };
  545. rknn.Error = class extends Error {
  546. constructor(message) {
  547. super(message);
  548. this.name = 'Error loading RKNN model.';
  549. }
  550. };
  551. export const ModelFactory = rknn.ModelFactory;