rknn.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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._type = Object.assign({}, metadata.type(node.op) || { name: node.op });
  160. for (const prefix of [ 'VSI_NN_OP_', 'RKNN_OP_' ]) {
  161. this._type.name = this._type.name.startsWith(prefix) ? this._type.name.substring(prefix.length) : this._type.name;
  162. }
  163. this._inputs = [];
  164. this._outputs = [];
  165. this._attributes = [];
  166. node.input = node.input || [];
  167. for (let i = 0; i < node.input.length; ) {
  168. const input = this._type && this._type.inputs && i < this._type.inputs.length ? this._type.inputs[i] : { name: i === 0 ? 'input' : i.toString() };
  169. const count = input.list ? node.input.length - i : 1;
  170. const list = node.input.slice(i, i + count).map((input) => {
  171. if (input.right_tensor) {
  172. return arg(input.right_tensor.type + ':' + input.right_tensor.tensor_id.toString());
  173. }
  174. if (input.right_node) {
  175. return arg(input.right_node.node_id.toString() + ':' + input.right_node.tensor_id.toString());
  176. }
  177. throw new rknn.Error('Invalid input argument.');
  178. });
  179. this._inputs.push(new rknn.Parameter(input.name, list));
  180. i += count;
  181. }
  182. node.output = node.output || [];
  183. for (let i = 0; i < node.output.length; ) {
  184. const output = this._metadata && this._metadata.outputs && i < this._metadata.outputs.length ? this._metadata.outputs[i] : { name: i === 0 ? 'output' : i.toString() };
  185. const count = output.list ? node.output.length - i : 1;
  186. const list = node.output.slice(i, i + count).map((output) => {
  187. if (output.right_tensor) {
  188. return arg(output.right_tensor.type + ':' + output.right_tensor.tensor_id.toString());
  189. }
  190. if (output.right_node) {
  191. return arg(output.right_node.node_id.toString() + ':' + output.right_node.tensor_id.toString());
  192. }
  193. throw new rknn.Error('Invalid output argument.');
  194. });
  195. this._outputs.push(new rknn.Parameter(output.name, list));
  196. i += count;
  197. }
  198. if (node.nn) {
  199. const nn = node.nn;
  200. for (const key of Object.keys(nn)) {
  201. const params = nn[key];
  202. for (const name of Object.keys(params)) {
  203. const value = params[name];
  204. this._attributes.push(new rknn.Attribute(name, value));
  205. }
  206. }
  207. }
  208. }
  209. get name() {
  210. return this._name;
  211. }
  212. get type() {
  213. return this._type;
  214. }
  215. get inputs() {
  216. return this._inputs;
  217. }
  218. get outputs() {
  219. return this._outputs;
  220. }
  221. get attributes() {
  222. return this._attributes;
  223. }
  224. };
  225. rknn.Attribute = class {
  226. constructor(name, value) {
  227. this._name = name;
  228. this._value = value;
  229. }
  230. get name() {
  231. return this._name;
  232. }
  233. get value() {
  234. return this._value;
  235. }
  236. };
  237. rknn.Tensor = class {
  238. constructor(type, offset, weights) {
  239. this._type = type;
  240. let size = 0;
  241. switch (this._type.dataType) {
  242. case 'uint8': size = 1; break;
  243. case 'int8': size = 1; break;
  244. case 'int32': size = 4; break;
  245. case 'float16': size = 2; break;
  246. case 'float32': size = 4; break;
  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 'uint8':
  316. results.push(context.view.getUint8(context.index, true));
  317. context.index++;
  318. context.count++;
  319. break;
  320. case 'int8':
  321. results.push(context.view.getInt8(context.index, true));
  322. context.index += 1;
  323. context.count++;
  324. break;
  325. case 'int32':
  326. results.push(context.view.getInt32(context.index, true));
  327. context.index += 4;
  328. context.count++;
  329. break;
  330. }
  331. }
  332. }
  333. else {
  334. for (let j = 0; j < size; j++) {
  335. if (context.count > context.limit) {
  336. results.push('...');
  337. return results;
  338. }
  339. results.push(this._decode(context, dimension + 1));
  340. }
  341. }
  342. if (context.shape.length == 0) {
  343. return results[0];
  344. }
  345. return results;
  346. }
  347. };
  348. rknn.TensorType = class {
  349. constructor(dataType, shape) {
  350. const type = dataType.vx_type.startsWith('VSI_NN_TYPE_') ? dataType.vx_type.split('_').pop().toLowerCase() : dataType.vx_type;
  351. switch (type) {
  352. case 'uint8':
  353. case 'int8':
  354. case 'int16':
  355. case 'int32':
  356. case 'int64':
  357. case 'float16':
  358. case 'float32':
  359. this._dataType = type;
  360. break;
  361. default:
  362. throw new rknn.Error("Invalid data type '" + JSON.stringify(dataType) + "'.");
  363. }
  364. this._shape = shape;
  365. }
  366. get dataType() {
  367. return this._dataType;
  368. }
  369. get shape() {
  370. return this._shape;
  371. }
  372. toString() {
  373. return this.dataType + this._shape.toString();
  374. }
  375. };
  376. rknn.TensorShape = class {
  377. constructor(shape) {
  378. this._dimensions = shape;
  379. }
  380. get dimensions() {
  381. return this._dimensions;
  382. }
  383. toString() {
  384. if (!this._dimensions || this._dimensions.length == 0) {
  385. return '';
  386. }
  387. return '[' + this._dimensions.join(',') + ']';
  388. }
  389. };
  390. rknn.Container = class {
  391. static open(stream) {
  392. const signature = [ 0x52, 0x4B, 0x4E, 0x4E, 0x00, 0x00, 0x00, 0x00 ];
  393. if (signature.length <= stream.length && stream.peek(signature.length).every((value, index) => value === signature[index])) {
  394. return new rknn.Container(stream);
  395. }
  396. return null;
  397. }
  398. constructor(stream) {
  399. this._reader = new rknn.Container.StreamReader(stream);
  400. }
  401. get version() {
  402. this._read();
  403. return this._version;
  404. }
  405. get weights() {
  406. this._read();
  407. return this._weights;
  408. }
  409. get model() {
  410. this._read();
  411. return this._model;
  412. }
  413. _read() {
  414. if (this._reader) {
  415. this._reader.uint64();
  416. this._version = this._reader.uint64();
  417. this._weights = this._reader.read();
  418. const buffer = this._reader.read();
  419. const reader = json.TextReader.open(buffer);
  420. this._model = reader.read();
  421. delete this._reader;
  422. }
  423. }
  424. };
  425. rknn.Container.StreamReader = class {
  426. constructor(stream) {
  427. this._stream = stream;
  428. this._length = stream.length;
  429. this._position = 0;
  430. }
  431. skip(offset) {
  432. this._position += offset;
  433. if (this._position > this._length) {
  434. throw new rknn.Error('Expected ' + (this._position - this._length) + ' more bytes. The file might be corrupted. Unexpected end of file.');
  435. }
  436. }
  437. uint64() {
  438. this.skip(8);
  439. const buffer = this._stream.read(8);
  440. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  441. return view.getUint64(0, true).toNumber();
  442. }
  443. read() {
  444. const size = this.uint64();
  445. this.skip(size);
  446. return this._stream.read(size);
  447. }
  448. };
  449. rknn.Metadata = class {
  450. static open(context) {
  451. if (rknn.Metadata._metadata) {
  452. return Promise.resolve(rknn.Metadata._metadata);
  453. }
  454. return context.request('rknn-metadata.json', 'utf-8', null).then((data) => {
  455. rknn.Metadata._metadata = new rknn.Metadata(data);
  456. return rknn.Metadata._metadata;
  457. }).catch(() => {
  458. rknn.Metadata._metadata = new rknn.Metadata(null);
  459. return rknn.Metadata._metadata;
  460. });
  461. }
  462. constructor(data) {
  463. this._map = new Map();
  464. if (data) {
  465. const metadata = JSON.parse(data);
  466. this._map = new Map(metadata.map((item) => [ item.name, item ]));
  467. }
  468. }
  469. type(name) {
  470. return this._map.has(name) ? this._map.get(name) : null;
  471. }
  472. attribute(type, name) {
  473. const schema = this.type(type);
  474. if (schema) {
  475. let attributeMap = schema.attributeMap;
  476. if (!attributeMap) {
  477. attributeMap = {};
  478. if (schema.attributes) {
  479. for (const attribute of schema.attributes) {
  480. attributeMap[attribute.name] = attribute;
  481. }
  482. }
  483. schema.attributeMap = attributeMap;
  484. }
  485. const attributeSchema = attributeMap[name];
  486. if (attributeSchema) {
  487. return attributeSchema;
  488. }
  489. }
  490. return null;
  491. }
  492. };
  493. rknn.Error = class extends Error {
  494. constructor(message) {
  495. super(message);
  496. this.name = 'Error loading RKNN model.';
  497. }
  498. };
  499. if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  500. module.exports.ModelFactory = rknn.ModelFactory;
  501. }