rknn.js 17 KB

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