onnx.js 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644
  1. /* jshint esversion: 6 */
  2. var onnx = onnx || {};
  3. var protobuf = protobuf || require('./protobuf');
  4. var flatbuffers = flatbuffers || require('./flatbuffers');
  5. onnx.ModelFactory = class {
  6. match(context) {
  7. return this._format(context).length > 0;
  8. }
  9. open(context) {
  10. const open = (model, format) => {
  11. return onnx.Metadata.open(context).then((metadata) => {
  12. return new onnx.Model(metadata, model, format);
  13. });
  14. };
  15. switch (this._format(context)) {
  16. case 'onnx.pbtxt.ModelProto':
  17. return context.require('./onnx-proto').then(() => {
  18. try {
  19. onnx.proto = protobuf.get('onnx').onnx;
  20. const stream = context.stream;
  21. const reader = protobuf.TextReader.open(stream);
  22. const model = onnx.proto.ModelProto.decodeText(reader);
  23. const format = 'ONNX' + (model.ir_version ? ' v' + model.ir_version.toString() : '');
  24. return open(model, format);
  25. }
  26. catch (error) {
  27. const message = error && error.message ? error.message : error.toString();
  28. throw new onnx.Error('File text format is not onnx.ModelProto (' + message.replace(/\.$/, '') + ').');
  29. }
  30. });
  31. case 'onnx.pb.TensorProto':
  32. return context.require('./onnx-proto').then(() => {
  33. // TensorProto
  34. // input_0.pb, output_0.pb
  35. try {
  36. onnx.proto = protobuf.get('onnx').onnx;
  37. const stream = context.stream;
  38. const reader = protobuf.BinaryReader.open(stream);
  39. const tensor = onnx.proto.TensorProto.decode(reader);
  40. tensor.name = tensor.name || context.identifier;
  41. const model = new onnx.proto.ModelProto();
  42. model.graph = new onnx.proto.GraphProto();
  43. model.graph.initializer = [ tensor ];
  44. model.graph.value_info = [ new onnx.proto.ValueInfoProto() ];
  45. model.graph.value_info[0].name = tensor.name;
  46. model.graph.node = [ new onnx.proto.NodeProto() ];
  47. model.graph.node[0].op_type = 'Constant';
  48. model.graph.node[0].attribute = [ new onnx.proto.AttributeProto() ];
  49. model.graph.node[0].attribute[0].name = 'value';
  50. model.graph.node[0].attribute[0].t = tensor;
  51. const format = 'ONNX Tensor';
  52. return open(model, format);
  53. }
  54. catch (error) {
  55. const message = error && error.message ? error.message : error.toString();
  56. throw new onnx.Error('File format is not onnx.TensorProto (' + message.replace(/\.$/, '') + ').');
  57. }
  58. });
  59. case 'onnx.pb.GraphProto':
  60. return context.require('./onnx-proto').then(() => {
  61. // GraphProto
  62. try {
  63. onnx.proto = protobuf.get('onnx').onnx;
  64. const stream = context.stream;
  65. const reader = protobuf.BinaryReader.open(stream);
  66. const model = new onnx.proto.ModelProto();
  67. model.graph = onnx.proto.GraphProto.decode(reader);
  68. const format = 'ONNX';
  69. return open(model, format);
  70. }
  71. catch (error) {
  72. const message = error && error.message ? error.message : error.toString();
  73. throw new onnx.Error('File format is not onnx.GraphProto (' + message.replace(/\.$/, '') + ').');
  74. }
  75. });
  76. case 'onnx.pb.ModelProto':
  77. return context.require('./onnx-proto').then(() => {
  78. // ModelProto
  79. try {
  80. onnx.proto = protobuf.get('onnx').onnx;
  81. const stream = context.stream;
  82. const reader = protobuf.BinaryReader.open(stream);
  83. const model = onnx.proto.ModelProto.decode(reader);
  84. const format = 'ONNX' + (model.ir_version ? ' v' + model.ir_version.toString() : '');
  85. return open(model, format);
  86. }
  87. catch (error) {
  88. const message = error && error.message ? error.message : error.toString();
  89. throw new onnx.Error('File format is not onnx.ModelProto (' + message.replace(/\.$/, '') + ').');
  90. }
  91. });
  92. case 'onnx.flatbuffers': {
  93. return context.require('./ort-schema').then((/* schema */) => {
  94. try {
  95. onnx.schema = flatbuffers.get('ort').onnxruntime.experimental.fbs;
  96. const stream = context.stream;
  97. const reader = flatbuffers.BinaryReader.open(stream);
  98. const session = onnx.schema.InferenceSession.create(reader);
  99. const model = session.model;
  100. const graph = model.graph;
  101. graph.node = graph.nodes;
  102. graph.doc_string = model.graph_doc_string;
  103. graph.value_info = graph.node_args;
  104. graph.input = graph.inputs.map((input) => {
  105. return { name: input };
  106. });
  107. graph.output = graph.outputs.map((output) => {
  108. return { name: output };
  109. });
  110. graph.initializer = graph.initializers.map((tensor) => {
  111. tensor.data_location = onnx.DataLocation.DEFAULT;
  112. return tensor;
  113. });
  114. graph.sparse_initializer = graph.sparse_initializers.map((tensor) => {
  115. tensor.values.data_location = onnx.DataLocation.DEFAULT;
  116. tensor.indices.data_location = onnx.DataLocation.DEFAULT;
  117. return tensor;
  118. });
  119. delete graph.nodes;
  120. delete graph.node_args;
  121. delete graph.inputs;
  122. delete graph.outputs;
  123. delete graph.initializers;
  124. delete graph.sparse_initializers;
  125. delete model.graph_doc_string;
  126. for (const node of graph.node) {
  127. node.input = node.inputs;
  128. node.output = node.outputs;
  129. node.attribute = node.attributes;
  130. delete node.inputs;
  131. delete node.outputs;
  132. delete node.attributes;
  133. }
  134. const format = 'ONNX Runtime' + (model.ir_version ? ' v' + model.ir_version.toString() : '');
  135. return open(model, format);
  136. }
  137. catch (error) {
  138. const message = error && error.message ? error.message : error.toString();
  139. throw new onnx.Error('File format is not ort.Model (' + message.replace(/\.$/, '') + ').');
  140. }
  141. });
  142. }
  143. default: {
  144. throw new onnx.Error("Unknown ONNX format '" + this._format(context) + "'.");
  145. }
  146. }
  147. }
  148. _format(context) {
  149. const identifier = context.identifier;
  150. const extension = identifier.split('.').pop().toLowerCase();
  151. if (identifier.endsWith('saved_model.pb') || identifier.endsWith('predict_net.pb') || identifier.endsWith('init_net.pb')) {
  152. return '';
  153. }
  154. if (identifier.endsWith('predict_net.pbtxt') || identifier.endsWith('predict_net.prototxt') ||
  155. identifier.endsWith('init_net.pbtxt') || identifier.endsWith('init_net.prototxt')) {
  156. return '';
  157. }
  158. let tags = context.tags('pb');
  159. if (tags.size > 0) {
  160. if (tags.size === 1 && tags.get(1) === 2) {
  161. const tags = context.tags('pb+');
  162. const match = (tags, schema) => {
  163. for (const pair of schema) {
  164. const key = pair[0];
  165. const inner = pair[1];
  166. if (!tags.has(key)) {
  167. continue;
  168. }
  169. else if (inner === false) {
  170. return false;
  171. }
  172. if (Array.isArray(inner)) {
  173. const value = tags.get(key);
  174. if (!(value instanceof Map) || !match(value, inner)) {
  175. return false;
  176. }
  177. }
  178. else if (inner !== tags.get(key)) {
  179. return false;
  180. }
  181. }
  182. return true;
  183. };
  184. // mediapipe.BoxDetectorIndex
  185. if (match(tags, [[1,[[1,[[1,[[1,5],[2,5],[3,5],[4,5],[6,0],[7,5],[8,5],[10,5],[11,0],[12,0]]],[2,5],[3,[]]]],[2,false],[3,false],[4,false],[5,false]]],[2,false],[3,false]] )) {
  186. return '';
  187. }
  188. // third_party.tensorflow.python.keras.protobuf.SavedMetadata
  189. if (match(tags, [[1,[[1,[[1,0],[2,0]]],[2,0],[3,2],[4,2],[5,2]]]])) {
  190. return '';
  191. }
  192. }
  193. if (Array.from(tags.keys()).every((tag) => tag <= 100) &&
  194. Array.from(tags.values()).every((type) => type < 5)) {
  195. // TensorProto
  196. if (tags.get(1) === 0 && tags.get(2) === 0 && tags.get(9) === 2) {
  197. const schema = [[1,0],[2,0],[4,2],[5,2],[7,2],[8,2],[9,2]];
  198. if (schema.every((pair) => !tags.has(pair[0]) || tags.get(pair[0]) === pair[1])) {
  199. return 'onnx.pb.TensorProto';
  200. }
  201. }
  202. // GraphProto
  203. if (tags.get(1) === 2) {
  204. const schema = [[1,2],[2,2],[3,2],[4,2],[5,2],[6,0],[7,0],[8,2],[9,2],[10,2],[11,2],[12,2],[13,2],[14,2]];
  205. if (schema.every((pair) => !tags.has(pair[0]) || tags.get(pair[0]) === pair[1])) {
  206. const decode = (buffer, value) => {
  207. const reader = protobuf.BinaryReader.open(buffer);
  208. const length = reader.length;
  209. while (reader.position < length) {
  210. const tag = reader.uint32();
  211. const number = tag >>> 3;
  212. const type = tag & 7;
  213. if (value === number) {
  214. return type === 2 ? reader.bytes() : null;
  215. }
  216. else {
  217. reader.skipType(type);
  218. }
  219. }
  220. return null;
  221. };
  222. const stream = context.stream;
  223. const buffer = stream.peek();
  224. const nodeBuffer = decode(buffer, 1);
  225. if (nodeBuffer) {
  226. const nameBuffer = decode(nodeBuffer, 4);
  227. if (nameBuffer && nameBuffer.every((c) => c > 0x20 && c < 0x7f)) {
  228. return 'onnx.pb.GraphProto';
  229. }
  230. }
  231. }
  232. }
  233. // ModelProto
  234. if (tags.get(7) === 2) {
  235. const schema = [[1,0],[2,2],[3,2],[4,2][5,0],[6,2],[7,2],[8,2],[14,2],[20,2]];
  236. if (schema.every((pair) => !tags.has(pair[0]) || tags.get(pair[0]) === pair[1])) {
  237. return 'onnx.pb.ModelProto';
  238. }
  239. }
  240. }
  241. }
  242. const stream = context.stream;
  243. if (stream.length > 5) {
  244. const buffer = stream.peek(Math.min(stream.length, 32));
  245. if (buffer[0] === 0x08 && buffer[1] < 0x0A && buffer[2] === 0x12) {
  246. const producers = [
  247. 'backend-test', 'BrainwaveCompiler',
  248. 'CNTK',
  249. 'keras2onnx', 'Kneron', 'kneron_formatter', 'kneron_kl530_test_case',
  250. 'darknet to ONNX example',
  251. 'htshinichi',
  252. 'MATLAB Deep Learning Toolbox Converter for ONNX Model Format', 'ML.NET', 'MVTec Software',
  253. 'onnx-caffe2', 'onnx-example', 'onnx.quantize', 'onnx.utils.extract_model', 'OnnxMLTools', 'onnx_test', 'onnxruntime-tools', 'onnxruntime.transformers',
  254. 'PaddlePaddle', 'pytorch',
  255. 'skl2onnx',
  256. 'Tencent YouTu', 'tf2onnx', 'tflite2onnx',
  257. 'WinMLTools'
  258. ];
  259. if (producers.some((producer) => Array.from(producer).every((ch, index) => index + 4 < buffer.length && ch.charCodeAt(0) === buffer[index + 4]))) {
  260. return 'onnx.pb.ModelProto';
  261. }
  262. }
  263. }
  264. tags = context.tags('pbtxt');
  265. if (tags.has('ir_version')) {
  266. return 'onnx.pbtxt.ModelProto';
  267. }
  268. if (tags.has('graph') && extension !== 'model') {
  269. return 'onnx.pbtxt.ModelProto';
  270. }
  271. if (context.tags('flatbuffers').get('file_identifier') === 'ORTM') {
  272. return 'onnx.flatbuffers';
  273. }
  274. return '';
  275. }
  276. };
  277. onnx.Model = class {
  278. constructor(metadata, model, format) {
  279. this._graphs = [];
  280. this._format = format;
  281. this._producerName = model.producer_name;
  282. this._producerVersion = model.producer_version;
  283. this._domain = model.domain;
  284. this._modelVersion = model.model_version;
  285. this._description = model.doc_string;
  286. this._metadata = [];
  287. this._imports = null;
  288. const imports = new Map();
  289. if (model.opset_import && model.opset_import.length > 0) {
  290. for (const opset_import of model.opset_import) {
  291. const domain = opset_import.domain || 'ai.onnx';
  292. const version = opset_import.version ? opset_import.version.toNumber() : 0;
  293. if (!imports.has(domain) || imports.get(domain) > version) {
  294. imports.set(domain, version);
  295. }
  296. }
  297. this._imports = Array.from(imports).map((pair) => pair[0] + ' v' + pair[1].toString());
  298. }
  299. if (imports.size == 0) {
  300. imports.set('ai.onnx', 1);
  301. imports.set('ai.onnx.ml', 1);
  302. }
  303. let imageFormat = '';
  304. if (model.metadata_props) {
  305. const imageMetadata = {};
  306. for (const metadata_prop of model.metadata_props) {
  307. switch (metadata_prop.key) {
  308. case 'author':
  309. this._author = metadata_prop.value;
  310. break;
  311. case 'company':
  312. this._company = metadata_prop.value;
  313. break;
  314. case 'converted_from':
  315. this._converted_from = metadata_prop.value;
  316. break;
  317. case 'license':
  318. this._license = metadata_prop.value;
  319. break;
  320. case 'license_url':
  321. this._licenseUrl = metadata_prop.value;
  322. break;
  323. case 'Image.BitmapPixelFormat':
  324. case 'Image.ColorSpaceGamma':
  325. case 'Image.NominalPixelRange':
  326. imageMetadata[metadata_prop.key] = metadata_prop.value;
  327. break;
  328. default:
  329. this._metadata.push({ name: metadata_prop.key, value: metadata_prop.value});
  330. break;
  331. }
  332. }
  333. imageFormat = [ imageMetadata['Image.BitmapPixelFormat'], imageMetadata['Image.ColorSpaceGamma'], imageMetadata['Image.NominalPixelRange'] ].filter((item) => item);
  334. }
  335. this._graphs = [];
  336. if (model && model.graph) {
  337. let key = 1000;
  338. const context = {};
  339. context.metadata = new onnx.GraphMetadata(metadata, imports);
  340. context.imageFormat = imageFormat;
  341. for (const func of model.functions || []) {
  342. context.metadata.add(new onnx.Function(context, func));
  343. }
  344. context.graphs = new Map();
  345. context.graph = function(graph) {
  346. graph.key = graph.key || (key++).toString();
  347. if (!this.graphs.has(graph.key)) {
  348. this.graphs.set(graph.key, new onnx.Graph(this, graph));
  349. }
  350. return this.graphs.get(graph.key);
  351. };
  352. const graphs = [ model.graph ];
  353. while (graphs.length > 0) {
  354. const graph = graphs.shift();
  355. this._graphs.push(context.graph(graph));
  356. for (const node of graph.node || []) {
  357. for (const attribute of node.attribute || []) {
  358. if (attribute.g) {
  359. graphs.push(attribute.g);
  360. }
  361. else if (attribute.graphs && attribute.graphs.length > 0) {
  362. graphs.push(...attribute.graphs);
  363. }
  364. }
  365. }
  366. }
  367. }
  368. }
  369. get format() {
  370. return this._format;
  371. }
  372. get imports() {
  373. return this._imports;
  374. }
  375. get producer() {
  376. const producer = [];
  377. if (this._producerName) {
  378. producer.push(this._producerName);
  379. }
  380. if (this._producerVersion && this._producerVersion.length > 0) {
  381. producer.push(this._producerVersion);
  382. }
  383. if (producer.length > 0) {
  384. return producer.join(' ');
  385. }
  386. return null;
  387. }
  388. get domain() {
  389. return this._domain || null;
  390. }
  391. get description() {
  392. return this._description || null;
  393. }
  394. get author() {
  395. return this._author || null;
  396. }
  397. get company() {
  398. return this._company || null;
  399. }
  400. get source() {
  401. return this._converted_from || null;
  402. }
  403. get license() {
  404. const license = [];
  405. if (this._license && this._license.length > 0) {
  406. license.push(this._license);
  407. }
  408. if (this._licenseUrl && this._licenseUrl.length > 0) {
  409. license.push('<a href=\'' + this._licenseUrl + '\'>' + this._licenseUrl + '</a>');
  410. }
  411. if (license.length > 0) {
  412. return license;
  413. }
  414. return null;
  415. }
  416. get metadata() {
  417. return this._metadata;
  418. }
  419. get graphs() {
  420. return this._graphs;
  421. }
  422. };
  423. onnx.Graph = class {
  424. constructor(context, graph) {
  425. this._node = '';
  426. this._description = '';
  427. this._nodes = [];
  428. this._inputs = [];
  429. this._outputs = [];
  430. this._name = graph.name || null;
  431. this._description = graph.doc_string || '';
  432. const tensors = onnx.Utility.createTensors(graph.node);
  433. for (const initializer of graph.initializer) {
  434. const tensor = tensors.map(initializer.name);
  435. tensor.initializer = new onnx.Tensor(initializer, 'Initializer');
  436. }
  437. for (const sparse_initializer of graph.sparse_initializer) {
  438. const tensor = tensors.map(sparse_initializer.values.name);
  439. tensor.initializer = new onnx.Tensor(sparse_initializer, 'Sparse Initializer');
  440. }
  441. for (const tensor_annotation of graph.quantization_annotation || []) {
  442. const tensor = tensors.map(tensor_annotation.tensor_name);
  443. const annotation = {};
  444. for (const pair of tensor_annotation.quant_parameter_tensor_names) {
  445. annotation[pair.key] = pair.value;
  446. }
  447. tensor.annotation = annotation;
  448. }
  449. for (const valueInfo of graph.value_info) {
  450. const tensor = tensors.map(valueInfo.name);
  451. tensor.type = onnx.Utility.formatType(valueInfo.type, context.imageFormat);
  452. tensor.description = valueInfo.doc_string;
  453. }
  454. graph.input = graph.input.map((valueInfo) => {
  455. const tensor = tensors.map(valueInfo.name);
  456. tensor.type = onnx.Utility.formatType(valueInfo.type, context.imageFormat);
  457. tensor.description = valueInfo.doc_string;
  458. return tensor;
  459. });
  460. graph.output = graph.output.map((valueInfo) => {
  461. const tensor = tensors.map(valueInfo.name);
  462. tensor.type = onnx.Utility.formatType(valueInfo.type, context.imageFormat);
  463. tensor.description = valueInfo.doc_string;
  464. return tensor;
  465. });
  466. new onnx.Inference(graph.node, graph.output);
  467. const args = new Map();
  468. args.map = function(name) {
  469. if (!this.has(name)) {
  470. const tensor = tensors.map(name);
  471. const type = tensor.initializer ? tensor.initializer.type : tensor.type || null;
  472. this.set(name, new onnx.Argument(name, type, tensor.initializer, tensor.annotation, tensor.description));
  473. }
  474. return this.get(name);
  475. };
  476. this._nodes = onnx.Utility.createNodes(context, graph.node, graph.input, graph.output, tensors, args);
  477. for (const input of graph.input) {
  478. const argument = args.map(input.name);
  479. if (!argument.initializer) {
  480. this._inputs.push(new onnx.Parameter(input.name, [ argument ]));
  481. }
  482. }
  483. for (const output of graph.output) {
  484. const argument = args.map(output.name);
  485. if (!argument.initializer) {
  486. this._outputs.push(new onnx.Parameter(output.name, [ argument ]));
  487. }
  488. }
  489. }
  490. get name() {
  491. return this._name;
  492. }
  493. get description() {
  494. return this._description;
  495. }
  496. get groups() {
  497. return false;
  498. }
  499. get inputs() {
  500. return this._inputs;
  501. }
  502. get outputs() {
  503. return this._outputs;
  504. }
  505. get nodes() {
  506. return this._nodes;
  507. }
  508. toString() {
  509. return 'graph(' + this.name + ')';
  510. }
  511. };
  512. onnx.Parameter = class {
  513. constructor(name, args) {
  514. this._name = name;
  515. this._arguments = args;
  516. }
  517. get name() {
  518. return this._name;
  519. }
  520. get visible() {
  521. return true;
  522. }
  523. get arguments() {
  524. return this._arguments;
  525. }
  526. };
  527. onnx.Argument = class {
  528. constructor(name, type, initializer, annotation, description) {
  529. if (typeof name !== 'string') {
  530. throw new onnx.Error("Invalid argument identifier '" + JSON.stringify(name) + "'.");
  531. }
  532. this._name = name;
  533. this._type = type || null;
  534. this._initializer = initializer || null;
  535. this._annotation = annotation;
  536. this._description = description || '';
  537. }
  538. get name() {
  539. return this._name;
  540. }
  541. get type() {
  542. return this._type;
  543. }
  544. get description() {
  545. return this._description;
  546. }
  547. get quantization() {
  548. if (this._annotation) {
  549. return Object.keys(this._annotation).map((key) => key + ': ' + this._annotation[key]).join(', ');
  550. }
  551. return null;
  552. }
  553. get initializer() {
  554. return this._initializer;
  555. }
  556. };
  557. onnx.Node = class {
  558. constructor(context, op_type, domain, name, description, attributes, inputs, outputs) {
  559. this._type = context.metadata.type(op_type, domain) || { name: op_type, module: domain };
  560. if (this.type.module !== domain && !(this._type instanceof onnx.Function)) {
  561. this._type = Object.assign({}, this.type);
  562. this._type.name = op_type;
  563. this._type.module = domain;
  564. }
  565. this._name = name || '';
  566. this._description = description || '';
  567. this._inputs = inputs;
  568. this._outputs = outputs;
  569. this._attributes = (attributes || []).map((attribute) => new onnx.Attribute(context, op_type, domain, attribute));
  570. }
  571. get type() {
  572. return this._type;
  573. }
  574. get name() {
  575. return this._name;
  576. }
  577. get description() {
  578. return this._description;
  579. }
  580. get group() {
  581. return null;
  582. }
  583. get attributes() {
  584. return this._attributes;
  585. }
  586. get inputs() {
  587. return this._inputs;
  588. }
  589. get outputs() {
  590. return this._outputs;
  591. }
  592. };
  593. onnx.Attribute = class {
  594. constructor(context, op_type, domain, attribute) {
  595. this._name = attribute.name;
  596. this._description = attribute.doc_string || '';
  597. this._type = null;
  598. this._value = null;
  599. switch (attribute.type) {
  600. case onnx.AttributeType.FLOAT:
  601. this._value = attribute.f;
  602. this._type = 'float32';
  603. break;
  604. case onnx.AttributeType.INT:
  605. this._value = attribute.i;
  606. this._type = 'int64';
  607. break;
  608. case onnx.AttributeType.STRING:
  609. switch (op_type) {
  610. case 'Int8GivenTensorFill':
  611. this._value = Array.from(attribute.s);
  612. break;
  613. default:
  614. this._value = onnx.Utility.decodeText(attribute.s);
  615. break;
  616. }
  617. this._type = 'string';
  618. break;
  619. case onnx.AttributeType.TENSOR:
  620. this._value = new onnx.Tensor(attribute.t);
  621. this._type = 'tensor';
  622. break;
  623. case onnx.AttributeType.GRAPH:
  624. this._value = context.graph(attribute.g);
  625. this._type = 'graph';
  626. break;
  627. case onnx.AttributeType.FLOATS:
  628. this._value = attribute.floats;
  629. this._type = 'float32[]';
  630. break;
  631. case onnx.AttributeType.INTS:
  632. this._value = attribute.ints;
  633. this._type = 'int64[]';
  634. break;
  635. case onnx.AttributeType.STRINGS:
  636. this._value = attribute.strings.map((s) => onnx.Utility.decodeText(s));
  637. this._type = 'string[]';
  638. break;
  639. case onnx.AttributeType.TENSORS:
  640. this._value = attribute.tensors.map((tensor) => new onnx.Tensor(tensor));
  641. this._type = 'tensor[]';
  642. break;
  643. case onnx.AttributeType.GRAPHS:
  644. this._value = attribute.graphs.map((graph) => context.graph(graph));
  645. this._type = 'graph[]';
  646. break;
  647. case onnx.AttributeType.SPARSE_TENSOR:
  648. this._value = new onnx.Tensor(attribute.sparse_tensor);
  649. this._type = 'tensor';
  650. break;
  651. case onnx.AttributeType.SPARSE_TENSORS:
  652. this._value = attribute.sparse_tensors.map((tensor) => new onnx.Tensor(tensor));
  653. this._type = 'tensor[]';
  654. break;
  655. case onnx.AttributeType.TYPE_PROTO:
  656. this._value = onnx.Utility.formatType(attribute.tp, context.imageFormat);
  657. this._type = 'type';
  658. break;
  659. case onnx.AttributeType.TYPE_PROTOS:
  660. this._value = attribute.type_protos.map((type) => onnx.Utility.formatType(type, context.imageFormat));
  661. this._type = 'type[]';
  662. break;
  663. default:
  664. throw new onnx.Error("Unknown attribute type '" + attribute.type + "'.");
  665. }
  666. const metadata = context.metadata.attribute(op_type, domain, attribute.name);
  667. if (metadata && Object.prototype.hasOwnProperty.call(metadata, 'default') && this._value == metadata.default) {
  668. this._visible = false;
  669. }
  670. }
  671. get name() {
  672. return this._name;
  673. }
  674. get type() {
  675. return this._type;
  676. }
  677. get value() {
  678. return this._value;
  679. }
  680. get description() {
  681. return this._description;
  682. }
  683. get visible() {
  684. return this._visible == false ? false : true;
  685. }
  686. };
  687. onnx.Tensor = class {
  688. constructor(tensor, kind) {
  689. this._kind = kind || null;
  690. const data = (tensor) => {
  691. let data = undefined;
  692. if (tensor.data_location === onnx.DataLocation.DEFAULT) {
  693. switch (tensor.data_type) {
  694. case onnx.DataType.FLOAT16:
  695. if (tensor.int32_data && tensor.int32_data.length > 0) {
  696. const buffer = new Uint8Array(tensor.int32_data.length << 1);
  697. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  698. const array = tensor.int32_data;
  699. for (let i = 0; i < array.length; i++) {
  700. view.setUint16(i << 1, array[i], true);
  701. }
  702. data = {
  703. type: tensor.data_type,
  704. buffer: buffer
  705. };
  706. }
  707. break;
  708. case onnx.DataType.FLOAT:
  709. data = new Float32Array(tensor.float_data);
  710. break;
  711. case onnx.DataType.DOUBLE:
  712. data = new Float64Array(tensor.double_data);
  713. break;
  714. case onnx.DataType.BOOL:
  715. data = new Array(tensor.int32_data.size);
  716. for (let i = 0; i < data.length; i++) {
  717. data[i] = data[i] === 0 ? false : true;
  718. }
  719. break;
  720. case onnx.DataType.INT8:
  721. data = new Int8Array(tensor.int32_data);
  722. break;
  723. case onnx.DataType.UINT8:
  724. data = new Uint8Array(tensor.int32_data);
  725. break;
  726. case onnx.DataType.INT16:
  727. data = new Int32Array(tensor.int32_data);
  728. break;
  729. case onnx.DataType.UINT16:
  730. data = new Int32Array(tensor.int32_data);
  731. break;
  732. case onnx.DataType.INT32:
  733. data = new Int32Array(tensor.int32_data);
  734. break;
  735. case onnx.DataType.UINT32:
  736. case onnx.DataType.UINT64:
  737. data = tensor.uint64_data;
  738. break;
  739. case onnx.DataType.INT64:
  740. data = tensor.int64_data;
  741. break;
  742. }
  743. if (data && (Array.isArray(data) || ArrayBuffer.isView(data)) && data.length === 0) {
  744. data = undefined;
  745. }
  746. if (!data && tensor.raw_data && tensor.raw_data.length > 0) {
  747. data = {
  748. type: tensor.data_type,
  749. buffer: tensor.raw_data
  750. };
  751. }
  752. }
  753. return data;
  754. };
  755. const location = (tensor) => {
  756. return onnx.Utility.formatLocation(tensor.data_location);
  757. };
  758. if ((onnx.proto && tensor instanceof onnx.proto.SparseTensorProto) ||
  759. (onnx.schema && tensor instanceof onnx.schema.SparseTensor)) {
  760. this._name = tensor.values.name || '';
  761. this._type = new onnx.TensorType(tensor.values.data_type, new onnx.TensorShape(tensor.dims.map((dim) => dim)), null);
  762. this._location = Array.from(new Set([ location(tensor.values), location(tensor.indices) ])).join(':');
  763. this._values = data(tensor.values);
  764. this._indices = data(tensor.indices);
  765. }
  766. else {
  767. this._name = tensor.name || '';
  768. this._type = new onnx.TensorType(tensor.data_type, new onnx.TensorShape(tensor.dims.map((dim) => dim)), null);
  769. this._location = location(tensor);
  770. this._values = data(tensor);
  771. }
  772. }
  773. get name() {
  774. return this._name;
  775. }
  776. get kind() {
  777. return this._kind;
  778. }
  779. get type() {
  780. return this._type;
  781. }
  782. get state() {
  783. return this._context().state || null;
  784. }
  785. get value() {
  786. const context = this._context();
  787. if (context.state) {
  788. return null;
  789. }
  790. context.limit = Number.MAX_SAFE_INTEGER;
  791. return this._decode(context, 0);
  792. }
  793. toString() {
  794. const context = this._context();
  795. if (context.state) {
  796. return '';
  797. }
  798. context.limit = 10000;
  799. const value = this._decode(context, 0);
  800. return onnx.Tensor._stringify(value, '', ' ');
  801. }
  802. _context() {
  803. const context = {};
  804. context.state = null;
  805. if (this._sparse) {
  806. context.state = 'Sparse data not implemented.';
  807. return context;
  808. }
  809. if (this._location !== 'default') {
  810. context.state = "Data '" + this._location + "' location not implemented.";
  811. return context;
  812. }
  813. const decode = (data) => {
  814. if (!data || Array.isArray(data) || ArrayBuffer.isView(data)) {
  815. return data;
  816. }
  817. const buffer = data.buffer;
  818. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  819. const type = data.type;
  820. data = undefined;
  821. switch (type) {
  822. case onnx.DataType.BOOL:
  823. data = new Array(buffer.length);
  824. for (let i = 0; i < buffer.length; i++) {
  825. data[i] = view.getUint8(i) === 0 ? false : true;
  826. }
  827. break;
  828. case onnx.DataType.FLOAT16:
  829. data = new Float32Array(buffer.length >> 1);
  830. for (let i = 0; i < data.length; i++) {
  831. data[i] = view.getFloat16(i << 1, true);
  832. }
  833. break;
  834. case onnx.DataType.FLOAT:
  835. data = new Float32Array(buffer.length >> 2);
  836. for (let i = 0; i < data.length; i++) {
  837. data[i] = view.getFloat32(i << 2, true);
  838. }
  839. break;
  840. case onnx.DataType.DOUBLE:
  841. data = new Float64Array(buffer.length >> 3);
  842. for (let i = 0; i < data.length; i++) {
  843. data[i] = view.getFloat64(i << 3, true);
  844. }
  845. break;
  846. case onnx.DataType.INT8:
  847. data = new Int8Array(buffer.length);
  848. for (let i = 0; i < data.length; i++) {
  849. data[i] = view.getInt8(i, true);
  850. }
  851. break;
  852. case onnx.DataType.UINT8:
  853. data = new Uint8Array(buffer.length);
  854. for (let i = 0; i < data.length; i++) {
  855. data[i] = view.getUint8(i, true);
  856. }
  857. break;
  858. case onnx.DataType.INT16:
  859. data = new Int16Array(buffer.length >> 1);
  860. for (let i = 0; i < data.length; i++) {
  861. data[i] = view.getInt16(i << 1, true);
  862. }
  863. break;
  864. case onnx.DataType.UINT16:
  865. data = new Uint16Array(buffer.length >> 1);
  866. for (let i = 0; i < data.length; i++) {
  867. data[i] = view.getUint16(i << 1, true);
  868. }
  869. break;
  870. case onnx.DataType.INT32:
  871. data = new Int32Array(buffer.length >> 2);
  872. for (let i = 0; i < data.length; i++) {
  873. data[i] = view.getInt32(i << 2, true);
  874. }
  875. break;
  876. case onnx.DataType.UINT32:
  877. data = new Uint32Array(buffer.length >> 2);
  878. for (let i = 0; i < data.length; i++) {
  879. data[i] = view.getUint32(i << 2, true);
  880. }
  881. break;
  882. case onnx.DataType.INT64:
  883. data = new Array(buffer.length >> 3);
  884. for (let i = 0; i < data.length; i++) {
  885. data[i] = view.getInt64(i << 3, true);
  886. }
  887. break;
  888. case onnx.DataType.UINT64:
  889. data = new Array(buffer.length >> 3);
  890. for (let i = 0; i < data.length; i++) {
  891. data[i] = view.getUint64(i << 3, true);
  892. }
  893. break;
  894. }
  895. return data;
  896. };
  897. this._values = decode(this._values);
  898. if (!this._values) {
  899. context.state = 'Tensor data is empty.';
  900. return context;
  901. }
  902. this._indices = decode(this._indices);
  903. context.values = this._values;
  904. context.indices = this._indices;
  905. context.index = 0;
  906. context.dataType = this.type.dataType;
  907. context.shape = this.type.shape.dimensions;
  908. context.data = function() {
  909. if (!this._data) {
  910. if (this.indices && this.values && this.indices.length === this.values.length) {
  911. const size = context.shape.reduce((a, b) => a * b, 1);
  912. const indices = this.indices;
  913. const values = this.values;
  914. const array = new values.constructor(size);
  915. switch (this.dataType) {
  916. case 'boolean':
  917. array.fill(false);
  918. break;
  919. case 'int64':
  920. case 'uint64':
  921. break;
  922. }
  923. if (indices.length > 0) {
  924. if (Object.prototype.hasOwnProperty.call(indices[0], 'low')) {
  925. for (let i = 0; i < indices.length; i++) {
  926. const index = indices[i];
  927. array[index.high === 0 ? index.low : index.toNumber()] = values[i];
  928. }
  929. }
  930. else {
  931. for (let i = 0; i < indices.length; i++) {
  932. array[indices[i]] = values[i];
  933. }
  934. }
  935. }
  936. this._data = array;
  937. }
  938. else {
  939. this._data = this.values;
  940. }
  941. }
  942. return this._data;
  943. };
  944. return context;
  945. }
  946. _decode(context, dimension) {
  947. const shape = context.shape.length !== 0 ? context.shape : [ 1 ];
  948. const results = [];
  949. const size = shape[dimension];
  950. const data = context.data();
  951. if (dimension == shape.length - 1) {
  952. for (let i = 0; i < size; i++) {
  953. if (context.index > context.limit) {
  954. results.push('...');
  955. return results;
  956. }
  957. results.push(data[context.index++]);
  958. }
  959. }
  960. else {
  961. for (let j = 0; j < size; j++) {
  962. if (context.index > context.limit) {
  963. results.push('...');
  964. return results;
  965. }
  966. results.push(this._decode(context, dimension + 1));
  967. }
  968. }
  969. if (context.shape.length == 0) {
  970. return results[0];
  971. }
  972. return results;
  973. }
  974. static _stringify(value, indentation, indent) {
  975. if (Array.isArray(value)) {
  976. const result = [];
  977. result.push(indentation + '[');
  978. const items = value.map((item) => onnx.Tensor._stringify(item, indentation + indent, indent));
  979. if (items.length > 0) {
  980. result.push(items.join(',\n'));
  981. }
  982. result.push(indentation + ']');
  983. return result.join('\n');
  984. }
  985. if (typeof value == 'string') {
  986. return indentation + value;
  987. }
  988. if (value == Infinity) {
  989. return indentation + 'Infinity';
  990. }
  991. if (value == -Infinity) {
  992. return indentation + '-Infinity';
  993. }
  994. if (isNaN(value)) {
  995. return indentation + 'NaN';
  996. }
  997. return indentation + value.toString();
  998. }
  999. };
  1000. onnx.TensorType = class {
  1001. constructor(dataType, shape, denotation) {
  1002. this._dataType = onnx.Utility.formatElementType(dataType);
  1003. this._shape = shape;
  1004. this._denotation = denotation || null;
  1005. }
  1006. get dataType() {
  1007. return this._dataType;
  1008. }
  1009. get shape() {
  1010. return this._shape;
  1011. }
  1012. get denotation() {
  1013. return this._denotation;
  1014. }
  1015. toString() {
  1016. return this.dataType + this._shape.toString();
  1017. }
  1018. };
  1019. onnx.TensorShape = class {
  1020. constructor(dimensions) {
  1021. this._dimensions = dimensions;
  1022. }
  1023. get dimensions() {
  1024. return this._dimensions;
  1025. }
  1026. toString() {
  1027. if (!this._dimensions || this._dimensions.length == 0) {
  1028. return '';
  1029. }
  1030. return '[' + this._dimensions.join(',') + ']';
  1031. }
  1032. };
  1033. onnx.SequenceType = class {
  1034. constructor(elementType, denotation) {
  1035. this._elementType = elementType;
  1036. this._denotation = denotation;
  1037. }
  1038. get elementType() {
  1039. return this._elementType;
  1040. }
  1041. get dennotation() {
  1042. return this._dennotation;
  1043. }
  1044. toString() {
  1045. return 'sequence<' + this._elementType.toString() + '>';
  1046. }
  1047. };
  1048. onnx.MapType = class {
  1049. constructor(keyType, valueType, denotation) {
  1050. this._keyType = onnx.Utility.formatElementType(keyType);
  1051. this._valueType = valueType;
  1052. this._denotation = denotation;
  1053. }
  1054. get keyType() {
  1055. return this._keyType;
  1056. }
  1057. get valueType() {
  1058. return this._valueType;
  1059. }
  1060. get denotation() {
  1061. return this._denotation;
  1062. }
  1063. toString() {
  1064. return 'map<' + this._keyType + ',' + this._valueType.toString() + '>';
  1065. }
  1066. };
  1067. onnx.OpaqueType = class {
  1068. constructor(domain, name) {
  1069. this._domain = domain;
  1070. this._name = name;
  1071. }
  1072. toString() {
  1073. const name = (this._domain ? (this._domain + '.') : '') + this._name;
  1074. return 'opaque<' + name + '>';
  1075. }
  1076. };
  1077. onnx.Function = class {
  1078. constructor(context, func) {
  1079. this._name = func.name;
  1080. this._domain = func.domain;
  1081. this._description = func.doc_string;
  1082. this._inputs = [];
  1083. this._outputs = [];
  1084. this._attributes = func.attribute.map((attribtue) => { return { name: attribtue }; });
  1085. const tensors = onnx.Utility.createTensors(func.node);
  1086. func.input = func.input.map((input) => tensors.map(input));
  1087. func.output = func.output.map((output) => tensors.map(output));
  1088. const args = new Map();
  1089. args.map = function(name) {
  1090. if (!this.has(name)) {
  1091. const tensor = tensors.map(name);
  1092. const type = tensor.initializer ? tensor.initializer.type : tensor.type || null;
  1093. this.set(name, new onnx.Argument(name, type, tensor.initializer, tensor.annotation, tensor.description));
  1094. }
  1095. return this.get(name);
  1096. };
  1097. this._nodes = onnx.Utility.createNodes(context, func.node, func.input, func.output, tensors, args);
  1098. for (const input of func.input) {
  1099. const argument = args.map(input.name);
  1100. if (!argument.initializer) {
  1101. this._inputs.push(new onnx.Parameter(input.name, [ argument ]));
  1102. }
  1103. }
  1104. for (const output of func.output) {
  1105. const argument = args.map(output.name);
  1106. if (!argument.initializer) {
  1107. this._outputs.push(new onnx.Parameter(output.name, [ argument ]));
  1108. }
  1109. }
  1110. }
  1111. get type() {
  1112. return 'function';
  1113. }
  1114. get name() {
  1115. return this._name;
  1116. }
  1117. get module() {
  1118. return this._domain;
  1119. }
  1120. get description() {
  1121. return this._description;
  1122. }
  1123. get inputs() {
  1124. return this._inputs;
  1125. }
  1126. get outputs() {
  1127. return this._outputs;
  1128. }
  1129. get attributes() {
  1130. return this._attributes;
  1131. }
  1132. get nodes() {
  1133. return this._nodes;
  1134. }
  1135. };
  1136. onnx.GraphMetadata = class {
  1137. constructor(metadata, imports) {
  1138. this._metadata = metadata;
  1139. this._imports = imports;
  1140. this._cache = new Map();
  1141. this._attributeCache = new Map();
  1142. this._functions = new Map();
  1143. }
  1144. add(func) {
  1145. if (!this._functions.has(func.module)) {
  1146. this._functions.set(func.module, new Map());
  1147. }
  1148. const map = this._functions.get(func.module);
  1149. if (map.has(func.name)) {
  1150. throw new onnx.Error("Duplicate function identifier '" + func.module + '.' + func.name + "'.");
  1151. }
  1152. map.set(func.name, func);
  1153. }
  1154. type(name, domain) {
  1155. domain = domain || 'ai.onnx';
  1156. const key = domain + ':' + name;
  1157. if (!this._cache.has(key)) {
  1158. let value = this._metadata.type(name, domain, this._imports);
  1159. if (!value) {
  1160. if (this._functions.has(domain)) {
  1161. const map = this._functions.get(domain);
  1162. if (map.has(name)) {
  1163. value = map.get(name);
  1164. }
  1165. }
  1166. }
  1167. this._cache.set(key, value);
  1168. }
  1169. return this._cache.get(key);
  1170. }
  1171. attribute(type, domain, name) {
  1172. const key = domain + ':' + type + ':' + name;
  1173. if (!this._attributeCache.has(key)) {
  1174. const schema = this.type(type, domain);
  1175. if (schema && schema.attributes && schema.attributes.length > 0) {
  1176. for (const attribute of schema.attributes) {
  1177. this._attributeCache.set(type + ':' + attribute.name, attribute);
  1178. }
  1179. }
  1180. if (!this._attributeCache.has(key)) {
  1181. this._attributeCache.set(key, null);
  1182. }
  1183. }
  1184. return this._attributeCache.get(key);
  1185. }
  1186. };
  1187. onnx.Metadata = class {
  1188. static open(context) {
  1189. if (onnx.Metadata._metadata) {
  1190. return Promise.resolve(onnx.Metadata._metadata);
  1191. }
  1192. return context.request('onnx-metadata.json', 'utf-8', null).then((data) => {
  1193. onnx.Metadata._metadata = new onnx.Metadata(data);
  1194. return onnx.Metadata._metadata;
  1195. }).catch(() => {
  1196. onnx.Metadata._metadata = new onnx.Metadata(null);
  1197. return onnx.Metadata._metadata;
  1198. });
  1199. }
  1200. constructor(data) {
  1201. this._map = new Map();
  1202. if (data) {
  1203. const metadata = JSON.parse(data);
  1204. for (const item of metadata) {
  1205. if (!this._map.has(item.module)) {
  1206. this._map.set(item.module, new Map());
  1207. }
  1208. const map = this._map.get(item.module);
  1209. if (!map.has(item.name)) {
  1210. map.set(item.name, []);
  1211. }
  1212. map.get(item.name).push(item);
  1213. }
  1214. }
  1215. }
  1216. type(name, domain, imports) {
  1217. domain = domain || 'ai.onnx';
  1218. let current = null;
  1219. if (this._map.has(domain)) {
  1220. const map = this._map.get(domain);
  1221. if (map.has(name)) {
  1222. for (const metadata of map.get(name)) {
  1223. const matchVersion = current ? current.version : -1;
  1224. const importVersion = imports.get(metadata.module) || 0;
  1225. if (importVersion >= metadata.version && matchVersion < metadata.version) {
  1226. current = metadata;
  1227. }
  1228. }
  1229. }
  1230. }
  1231. return current;
  1232. }
  1233. };
  1234. onnx.Inference = class {
  1235. constructor(nodes, outputs) {
  1236. this._outputs = new Map();
  1237. for (const node of nodes) {
  1238. for (const output of node.output) {
  1239. this._outputs.set(output.name, node);
  1240. }
  1241. }
  1242. for (const output of outputs) {
  1243. this._infer(output.name);
  1244. }
  1245. }
  1246. _infer(output) {
  1247. if (this._outputs.has(output)) {
  1248. let hasInputShapes = true;
  1249. const node = this._outputs.get(output);
  1250. for (const input of node.input) {
  1251. if (!input.type) {
  1252. this._infer(input);
  1253. if (!input.type) {
  1254. hasInputShapes = false;
  1255. break;
  1256. }
  1257. }
  1258. }
  1259. if (hasInputShapes) {
  1260. // continue
  1261. }
  1262. }
  1263. }
  1264. };
  1265. onnx.DataLocation = {
  1266. DEFAULT: 0,
  1267. EXTERNAL: 1
  1268. };
  1269. onnx.DataType = {
  1270. UNDEFINED: 0,
  1271. FLOAT: 1,
  1272. UINT8: 2,
  1273. INT8: 3,
  1274. UINT16: 4,
  1275. INT16: 5,
  1276. INT32: 6,
  1277. INT64: 7,
  1278. STRING: 8,
  1279. BOOL: 9,
  1280. FLOAT16: 10,
  1281. DOUBLE: 11,
  1282. UINT32: 12,
  1283. UINT64: 13,
  1284. COMPLEX64: 14,
  1285. COMPLEX128: 15,
  1286. BFLOAT16: 16
  1287. };
  1288. onnx.AttributeType = {
  1289. UNDEFINED: 0,
  1290. FLOAT: 1,
  1291. INT: 2,
  1292. STRING: 3,
  1293. TENSOR: 4,
  1294. GRAPH: 5,
  1295. FLOATS: 6,
  1296. INTS: 7,
  1297. STRINGS: 8,
  1298. TENSORS: 9,
  1299. GRAPHS: 10,
  1300. SPARSE_TENSOR: 11,
  1301. SPARSE_TENSORS: 12,
  1302. TYPE_PROTO: 13,
  1303. TYPE_PROTOS: 14
  1304. };
  1305. onnx.Utility = class {
  1306. static decodeText(value) {
  1307. if (typeof value === 'string') {
  1308. return value;
  1309. }
  1310. onnx.Utility._utf8Decoder = onnx.Utility._utf8Decoder || new TextDecoder('utf-8');
  1311. return onnx.Utility._utf8Decoder.decode(value);
  1312. }
  1313. static formatElementType(elementType) {
  1314. if (!onnx.Utility._elementTypeMap) {
  1315. const map = {};
  1316. map[onnx.DataType.UNDEFINED] = 'UNDEFINED';
  1317. map[onnx.DataType.FLOAT] = 'float32';
  1318. map[onnx.DataType.UINT8] = 'uint8';
  1319. map[onnx.DataType.INT8] = 'int8';
  1320. map[onnx.DataType.UINT16] = 'uint16';
  1321. map[onnx.DataType.INT16] = 'int16';
  1322. map[onnx.DataType.INT32] = 'int32';
  1323. map[onnx.DataType.INT64] = 'int64';
  1324. map[onnx.DataType.STRING] = 'string';
  1325. map[onnx.DataType.BOOL] = 'boolean';
  1326. map[onnx.DataType.FLOAT16] = 'float16';
  1327. map[onnx.DataType.DOUBLE] = 'float64';
  1328. map[onnx.DataType.UINT32] = 'uint32';
  1329. map[onnx.DataType.UINT64] = 'uint64';
  1330. map[onnx.DataType.COMPLEX64] = 'complex64';
  1331. map[onnx.DataType.COMPLEX128] = 'complex128';
  1332. map[onnx.DataType.BFLOAT16] = 'bfloat16';
  1333. onnx.Utility._elementTypeMap = map;
  1334. }
  1335. const name = onnx.Utility._elementTypeMap[elementType];
  1336. if (name) {
  1337. return name;
  1338. }
  1339. return onnx.Utility._elementTypeMap[onnx.DataType.UNDEFINED];
  1340. }
  1341. static formatType(type, imageFormat) {
  1342. if (!type) {
  1343. return null;
  1344. }
  1345. let denotation = '';
  1346. switch (type.denotation) {
  1347. case 'TENSOR':
  1348. denotation = 'Tensor';
  1349. break;
  1350. case 'IMAGE':
  1351. denotation = 'Image' + (imageFormat ? '(' + imageFormat.join(',') + ')' : '');
  1352. break;
  1353. case 'AUDIO':
  1354. denotation = 'Audio';
  1355. break;
  1356. case 'TEXT':
  1357. denotation = 'Text';
  1358. break;
  1359. }
  1360. switch (type.value) {
  1361. case 'tensor_type': {
  1362. {
  1363. const tensor_type = type.tensor_type;
  1364. let shape = [];
  1365. if (tensor_type.shape && tensor_type.shape.dim) {
  1366. shape = tensor_type.shape.dim.map((dim) => dim.dim_param ? dim.dim_param : dim.dim_value);
  1367. }
  1368. return new onnx.TensorType(tensor_type.elem_type, new onnx.TensorShape(shape), denotation);
  1369. }
  1370. }
  1371. case 'sparse_tensor_type': {
  1372. const tensor_type = type.sparse_tensor_type;
  1373. let shape = [];
  1374. if (tensor_type.shape && tensor_type.shape.dim) {
  1375. shape = tensor_type.shape.dim.map((dim) => dim.dim_param ? dim.dim_param : dim.dim_value);
  1376. }
  1377. return new onnx.TensorType(tensor_type.elem_type, new onnx.TensorShape(shape), denotation);
  1378. }
  1379. case 'map_type': {
  1380. return new onnx.MapType(type.map_type.key_type, onnx.Utility.formatType(type.map_type.value_type, imageFormat), denotation);
  1381. }
  1382. case 'sequence_type': {
  1383. return new onnx.SequenceType(onnx.Utility.formatType(type.sequence_type.elem_type, imageFormat), denotation);
  1384. }
  1385. case 'opaque_type': {
  1386. return new onnx.OpaqueType(type.opaque_type.domain, type.opaque_type.name);
  1387. }
  1388. }
  1389. return null;
  1390. }
  1391. static formatLocation(location) {
  1392. if (!onnx.Utility._dataLocations) {
  1393. onnx.Utility._dataLocations = new Map(Object.keys(onnx.DataLocation).map((key) => [ onnx.DataLocation[key], key.toLowerCase() ]));
  1394. }
  1395. return onnx.Utility._dataLocations.get(location);
  1396. }
  1397. static attributeType(attribute) {
  1398. if (attribute.type) {
  1399. return attribute.type;
  1400. }
  1401. if (attribute.ints && attribute.ints.length > 0) {
  1402. return onnx.AttributeType.INTS;
  1403. }
  1404. else if (attribute.floats && attribute.floats.length > 0) {
  1405. return onnx.AttributeType.FLOATS;
  1406. }
  1407. else if (attribute.strings && attribute.strings.length > 0) {
  1408. return onnx.AttributeType.STRINGS;
  1409. }
  1410. else if (attribute.graphs && attribute.graphs.length > 0) {
  1411. return onnx.AttributeType.GRAPHS;
  1412. }
  1413. else if (attribute.s && attribute.s.length > 0) {
  1414. return onnx.AttributeType.STRING;
  1415. }
  1416. else if (Object.prototype.hasOwnProperty.call(attribute, 'f')) {
  1417. return onnx.AttributeType.FLOAT;
  1418. }
  1419. else if (Object.prototype.hasOwnProperty.call(attribute, 'i')) {
  1420. return onnx.AttributeType.INT;
  1421. }
  1422. else if (Object.prototype.hasOwnProperty.call(attribute, 't')) {
  1423. return onnx.AttributeType.TENSOR;
  1424. }
  1425. else if (Object.prototype.hasOwnProperty.call(attribute, 'g')) {
  1426. return onnx.AttributeType.GRAPH;
  1427. }
  1428. else if (Object.prototype.hasOwnProperty.call(attribute, 'sparse_tensor')) {
  1429. return onnx.AttributeType.SPARSE_TENSOR;
  1430. }
  1431. return onnx.AttributeType.UNDEFINED;
  1432. }
  1433. static createTensors(nodes) {
  1434. const tensors = new Map();
  1435. tensors.map = function(name) {
  1436. if (!this.has(name)) {
  1437. this.set(name, { name: name });
  1438. }
  1439. return this.get(name);
  1440. };
  1441. for (const node of nodes) {
  1442. node.input = node.input.map((name) => tensors.map(name));
  1443. node.output = node.output.map((name) => tensors.map(name));
  1444. node.param = {};
  1445. for (const attribute of node.attribute) {
  1446. attribute.type = onnx.Utility.attributeType(attribute);
  1447. }
  1448. }
  1449. return tensors;
  1450. }
  1451. static createNodes(context, nodes, inputs, outputs, tensors, args) {
  1452. const inputMap = new Map();
  1453. const outputMap = new Map();
  1454. for (const node of nodes) {
  1455. node.input.every((input) => inputMap.set(input.name, (inputMap.get(input) || 0) + 1));
  1456. node.output.every((output) => outputMap.set(output.name, (outputMap.get(output) || 0) + 1));
  1457. }
  1458. inputs.every((input) => inputMap.delete(input.name));
  1459. outputs.every((output) => outputMap.delete(output.name));
  1460. nodes = nodes.filter((node) => {
  1461. const constant = node &&
  1462. node.op_type === 'Constant' &&
  1463. node.attribute.length === 1 && node.attribute[0] &&
  1464. node.input.length === 0 &&
  1465. node.output.length === 1 && node.output[0] && inputMap.get(node.output[0].name) === 1 && outputMap.get(node.output[0].name) === 1;
  1466. const attribute = constant ? node.attribute[0] : null;
  1467. if (attribute && attribute.name === 'value' && attribute.type === onnx.AttributeType.TENSOR && attribute.t) {
  1468. const tensor = tensors.map(node.output[0].name);
  1469. tensor.initializer = new onnx.Tensor(attribute.t, 'Constant');
  1470. return false;
  1471. }
  1472. else if (attribute && attribute.name === 'sparse_value' && attribute.type === onnx.AttributeType.SPARSE_TENSOR && attribute.sparse_tensor) {
  1473. const tensor = tensors.map(node.output[0].name);
  1474. tensor.initializer = new onnx.Tensor(attribute.sparse_tensor, 'Sparse Constant');
  1475. return false;
  1476. }
  1477. return true;
  1478. });
  1479. return nodes.map((node) => {
  1480. const schema = context.metadata.type(node.op_type, node.domain);
  1481. const inputs = [];
  1482. node.input = node.input || [];
  1483. for (let i = 0; i < node.input.length; ) {
  1484. const input = schema && schema.inputs && i < schema.inputs.length ? schema.inputs[i] : { name: i.toString() };
  1485. const count = input.list ? node.input.length - i : 1;
  1486. const list = node.input.slice(i, i + count).map((input) => args.map(input.name));
  1487. inputs.push(new onnx.Parameter(input.name, list));
  1488. i += count;
  1489. }
  1490. const outputs = [];
  1491. node.output = node.output || [];
  1492. for (let i = 0; i < node.output.length; ) {
  1493. const output = schema && schema.outputs && i < schema.outputs.length ? schema.outputs[i] : { name: i.toString() };
  1494. const count = output.list ? node.output.length - i : 1;
  1495. const list = node.output.slice(i, i + count).map((output) => args.map(output.name));
  1496. outputs.push(new onnx.Parameter(output.name, list));
  1497. i += count;
  1498. }
  1499. return new onnx.Node(context, node.op_type, node.domain, node.name, node.doc_string, node.attribute, inputs, outputs);
  1500. });
  1501. }
  1502. };
  1503. onnx.Error = class extends Error {
  1504. constructor(message) {
  1505. super(message);
  1506. this.name = 'Error loading ONNX model.';
  1507. }
  1508. };
  1509. if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  1510. module.exports.ModelFactory = onnx.ModelFactory;
  1511. }