tvm.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. const tvm = {};
  2. tvm.ModelFactory = class {
  3. async match(context) {
  4. const identifier = context.identifier;
  5. const extension = identifier.lastIndexOf('.') > 0 ? identifier.split('.').pop().toLowerCase() : '';
  6. if (extension === 'json') {
  7. const obj = await context.peek('json');
  8. if (obj && Array.isArray(obj.nodes) && Array.isArray(obj.arg_nodes) && Array.isArray(obj.heads) &&
  9. obj.nodes.every((node) => node && (node.op === 'null' || node.op === 'tvm_op'))) {
  10. return context.set('tvm.json', obj);
  11. }
  12. }
  13. const stream = context.stream;
  14. const signature = [0xB7, 0x9C, 0x04, 0x05, 0x4F, 0x8D, 0xE5, 0xF7];
  15. if (stream && signature.length <= stream.length && stream.peek(signature.length).every((value, index) => value === signature[index])) {
  16. return context.set('tvm.params');
  17. }
  18. return null;
  19. }
  20. filter(context, match) {
  21. return context.type !== 'tvm.json' || match.type !== 'tvm.params';
  22. }
  23. async open(context) {
  24. const metadata = await context.metadata('tvm-metadata.json');
  25. let obj = null;
  26. let params = null;
  27. switch (context.type) {
  28. case 'tvm.json': {
  29. obj = context.value;
  30. const identifier = context.identifier.replace(/\.json$/, '.params');
  31. try {
  32. const content = await context.fetch(identifier);
  33. const reader = await content.read('binary');
  34. params = tvm.NDArray.loadParams(reader);
  35. } catch {
  36. // continue regardless of error
  37. }
  38. break;
  39. }
  40. case 'tvm.params': {
  41. const identifier = context.identifier.replace(/\.params$/, '.json');
  42. try {
  43. const content = await context.fetch(identifier);
  44. obj = await content.read('json');
  45. } catch {
  46. // continue regardless of error
  47. }
  48. const reader = await context.read('binary');
  49. params = tvm.NDArray.loadParams(reader);
  50. break;
  51. }
  52. default:
  53. throw new tvm.Error(`Unsupported TVN format '${context.type}'.`);
  54. }
  55. return new tvm.Model(metadata, obj, params);
  56. }
  57. };
  58. tvm.Model = class {
  59. constructor(metadata, obj, params) {
  60. this.format = 'TVM';
  61. this.modules = [new tvm.Graph(metadata, obj, params)];
  62. }
  63. };
  64. tvm.Graph = class {
  65. constructor(metadata, obj, params) {
  66. this.nodes = [];
  67. this.inputs = [];
  68. this.outputs = [];
  69. const tensors = new Map();
  70. if (params) {
  71. for (const [name, value] of params) {
  72. const shape = new tvm.TensorShape(value.shape);
  73. const type = new tvm.TensorType(value.dtype, shape);
  74. const tensor = new tvm.Tensor(name, type, value.data);
  75. tensors.set(name, tensor);
  76. }
  77. }
  78. const values = new Map();
  79. values.map = (name, type, tensor) => {
  80. if (!values.has(name)) {
  81. values.set(name, new tvm.Value(name, type || null, tensor || null));
  82. } else if (type || (tensor && tensor !== values.get(name).initializer)) {
  83. throw new tvm.Error(`Duplicate value '${name}'.`);
  84. }
  85. return values.get(name);
  86. };
  87. const updateOutput = (nodes, input) => {
  88. const [nodeIndex, outputIndex] = input;
  89. const node = nodes[nodeIndex];
  90. if (node) {
  91. while (outputIndex >= node.outputs.length) {
  92. node.outputs.push([nodeIndex, node.outputs.length]);
  93. }
  94. }
  95. return [nodeIndex, outputIndex];
  96. };
  97. if (obj) {
  98. const nodes = obj.nodes;
  99. const inputs = {};
  100. const outputs = {};
  101. for (const node of nodes) {
  102. node.outputs = [];
  103. }
  104. for (const node of nodes) {
  105. node.inputs = node.inputs || [];
  106. node.inputs = node.inputs.map((input) => updateOutput(nodes, input));
  107. }
  108. const arg_nodes = new Map(obj.arg_nodes.map((index) => [index, index < nodes.length ? nodes[index] : null]));
  109. for (let i = 0; i < obj.heads.length; i++) {
  110. const head = obj.heads[i];
  111. const identifier = updateOutput(nodes, head);
  112. const name = `output${(i === 0) ? '' : (i + 1)}`;
  113. const signature = outputs[name];
  114. const type = signature && signature.data_shape ? new tvm.TensorType(-1, new tvm.TensorShape(signature.data_shape)) : null;
  115. const value = values.map(`[${identifier.join(',')}]`, type);
  116. const argument = new tvm.Argument(name, [value]);
  117. this.outputs.push(argument);
  118. }
  119. const filtered = nodes.filter((node, index) => !arg_nodes.has(index));
  120. const initializers = new Map();
  121. for (const node of filtered) {
  122. for (const input of node.inputs) {
  123. const identifier = `[${input.join(',')}]`;
  124. if (!initializers.has(identifier)) {
  125. const [index] = input;
  126. const arg_node = arg_nodes.get(index);
  127. if (arg_node && arg_node.name && (!arg_node.inputs || arg_node.inputs.length === 0) && (arg_node.outputs && arg_node.outputs.length === 1)) {
  128. if (tensors.has(arg_node.name)) {
  129. initializers.set(identifier, tensors.get(arg_node.name));
  130. arg_nodes.delete(index);
  131. }
  132. }
  133. }
  134. }
  135. if (node.params) {
  136. for (const param of node.params) {
  137. values.map(param.id, null, tensors.get(param.id));
  138. }
  139. }
  140. }
  141. for (const [, arg_node] of arg_nodes) {
  142. if (arg_node && (!arg_node.inputs || arg_node.inputs.length === 0) && (arg_node.outputs && arg_node.outputs.length === 1)) {
  143. const identifier = `[${arg_node.outputs[0].join(',')}]`;
  144. const name = arg_node.name;
  145. const signature = inputs[name];
  146. const type = signature && signature.data_shape ? new tvm.TensorType(-1, new tvm.TensorShape(signature.data_shape)) : null;
  147. const value = values.map(identifier, type, tensors.get(identifier));
  148. const argument = new tvm.Argument(name, [value]);
  149. this.inputs.push(argument);
  150. }
  151. }
  152. for (const node of filtered) {
  153. this.nodes.push(new tvm.Node(metadata, node, initializers, values));
  154. }
  155. } else if (params) {
  156. const blocks = new Map();
  157. const separator = Array.from(params.keys()).every((key) => key.indexOf('_') !== -1) ? '_' : '';
  158. for (const [key] of params) {
  159. const parts = separator ? key.split(separator) : [key];
  160. let argumentName = parts.pop();
  161. if (key.endsWith('moving_mean') || key.endsWith('moving_var')) {
  162. argumentName = [parts.pop(), argumentName].join(separator);
  163. }
  164. const nodeName = parts.join(separator);
  165. if (!blocks.has(nodeName)) {
  166. blocks.set(nodeName, { name: nodeName, op: 'Weights', params: [] });
  167. }
  168. blocks.get(nodeName).params.push({ name: argumentName, id: key });
  169. values.map(key, null, tensors.get(key));
  170. }
  171. for (const block of blocks.values()) {
  172. const node = new tvm.Node(metadata, block, new Map(), values);
  173. this.nodes.push(node);
  174. }
  175. }
  176. }
  177. };
  178. tvm.Argument = class {
  179. constructor(name, value, type = null, visible = true) {
  180. this.name = name;
  181. this.value = value;
  182. this.type = type;
  183. this.visible = visible;
  184. }
  185. };
  186. tvm.Value = class {
  187. constructor(name, type, initializer = null) {
  188. if (typeof name !== 'string') {
  189. throw new tvm.Error(`Invalid value identifier '${JSON.stringify(name)}'.`);
  190. }
  191. this.name = !name && initializer && initializer.name ? initializer.name : name;
  192. this.type = !type && initializer && initializer.type ? initializer.type : type;
  193. this.initializer = initializer;
  194. }
  195. };
  196. tvm.Node = class {
  197. constructor(metadata, node, initializers, values) {
  198. this.type = { name: node.op };
  199. this.name = node.name;
  200. this.attributes = Object.entries(node.attrs || {}).map(([name, value]) => new tvm.Argument(name, value));
  201. this.inputs = (node.inputs || []).map((input, index) => {
  202. const name = index.toString();
  203. const identifier = `[${input.join(',')}]`;
  204. const value = values.map(identifier, null, initializers.get(identifier));
  205. return new tvm.Argument(name, [value]);
  206. });
  207. this.outputs = (node.outputs || []).map((output, index) => {
  208. const name = index.toString();
  209. const value = values.map(`[${output.join(',')}]`);
  210. return new tvm.Argument(name, [value]);
  211. });
  212. for (const param of node.params || []) {
  213. const value = values.map(param.id);
  214. const argument = new tvm.Argument(param.name, [value]);
  215. this.inputs.push(argument);
  216. }
  217. }
  218. };
  219. tvm.Tensor = class {
  220. constructor(name, type, data) {
  221. this.name = name;
  222. this.type = type;
  223. this.values = data;
  224. this.encoding = '<';
  225. }
  226. };
  227. tvm.TensorType = class {
  228. constructor(dtype, shape) {
  229. let type = '';
  230. switch (dtype.code) { // TVMArgTypeCode
  231. case 0: type = 'int'; break;
  232. case 1: type = 'uint'; break;
  233. case 2: type = 'float'; break;
  234. default: throw new tvm.Error(`Unsupported data type code '${dtype.code}'.`);
  235. }
  236. if (dtype.lanes !== 1) {
  237. throw new tvm.Error(`Unsupported data type lanes '${dtype.lanes}'.`);
  238. }
  239. this.dataType = `${type}${dtype.bits}`;
  240. this.shape = shape;
  241. }
  242. toString() {
  243. return this.dataType + this.shape.toString();
  244. }
  245. };
  246. tvm.TensorShape = class {
  247. constructor(dimensions) {
  248. this.dimensions = Array.isArray(dimensions) ? dimensions.map((dim) => typeof dim === 'bigint' ? dim.toNumber() : dim) : dimensions;
  249. }
  250. toString() {
  251. if (this.dimensions) {
  252. if (this.dimensions.length === 0) {
  253. return '';
  254. }
  255. return `[${this.dimensions.map((dimension) => dimension.toString()).join(',')}]`;
  256. }
  257. return '';
  258. }
  259. };
  260. tvm.NDArray = class {
  261. static loadParams(reader) {
  262. // https://github.com/apache/tvm/blob/main/src/runtime/file_utils.cc
  263. reader = new tvm.BinaryReader(reader);
  264. const header = reader.read(8);
  265. const signature = [0xB7, 0x9C, 0x04, 0x05, 0x4F, 0x8D, 0xE5, 0xF7];
  266. if (!header.every((value, index) => value === signature[index])) {
  267. throw new tvm.Error('Invalid signature.');
  268. }
  269. reader.skip(8); // reserved
  270. const names = reader.strings();
  271. const values = new Array(reader.uint64().toNumber());
  272. if (names.length !== values.length) {
  273. throw new tvm.Error('Invalid parameters.');
  274. }
  275. const params = new Map();
  276. for (let i = 0; i < values.length; i++) {
  277. const value = new tvm.NDArray(reader);
  278. params.set(names[i], value);
  279. }
  280. return params;
  281. }
  282. constructor(reader) {
  283. // https://github.com/apache/tvm/blob/main/include/tvm/runtime/ndarray.h
  284. const header = reader.read(8);
  285. const signature = [0x3F, 0xA1, 0xB4, 0x96, 0xF0, 0x40, 0x5E, 0xDD];
  286. if (!header.every((value, index) => value === signature[index])) {
  287. throw new tvm.Error('Invalid signature.');
  288. }
  289. reader.skip(8); // reserved
  290. this.device = {
  291. deviceType: reader.uint32(),
  292. deviceId: reader.uint32()
  293. };
  294. this.shape = new Array(reader.uint32());
  295. this.dtype = {
  296. code: reader.uint8(),
  297. bits: reader.uint8(),
  298. lanes: reader.uint16(),
  299. };
  300. for (let i = 0; i < this.shape.length; i++) {
  301. this.shape[i] = reader.uint64();
  302. }
  303. const size = reader.uint64().toNumber();
  304. this.data = reader.read(size);
  305. }
  306. };
  307. tvm.BinaryReader = class {
  308. constructor(reader) {
  309. this._reader = reader;
  310. }
  311. skip(offset) {
  312. this._reader.skip(offset);
  313. }
  314. read(length) {
  315. return this._reader.read(length);
  316. }
  317. uint8() {
  318. return this._reader.byte();
  319. }
  320. uint16() {
  321. return this._reader.uint16();
  322. }
  323. uint32() {
  324. return this._reader.uint32();
  325. }
  326. uint64() {
  327. return this._reader.uint64();
  328. }
  329. string() {
  330. const length = this.uint64().toNumber();
  331. const buffer = this._reader.read(length);
  332. return String.fromCharCode.apply(null, new Uint8Array(buffer));
  333. }
  334. strings() {
  335. const list = new Array(this.uint64().toNumber());
  336. for (let i = 0; i < list.length; i++) {
  337. list[i] = this.string();
  338. }
  339. return list;
  340. }
  341. };
  342. tvm.Error = class extends Error {
  343. constructor(message) {
  344. super(message);
  345. this.name = 'Error loading TVM model.';
  346. }
  347. };
  348. export const ModelFactory = tvm.ModelFactory;