rknn.js 17 KB

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