onnx.js 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358
  1. var onnx = onnx || {};
  2. var protobuf = protobuf || require('./protobuf');
  3. var flatbuffers = flatbuffers || require('./flatbuffers');
  4. var text = text || require('./text');
  5. onnx.ModelFactory = class {
  6. match(context) {
  7. const identifier = context.identifier;
  8. const extension = identifier.split('.').pop().toLowerCase();
  9. if (identifier.endsWith('saved_model.pb') || identifier.endsWith('predict_net.pb') || identifier.endsWith('init_net.pb')) {
  10. return undefined;
  11. }
  12. if (identifier.endsWith('predict_net.pbtxt') || identifier.endsWith('predict_net.prototxt') ||
  13. identifier.endsWith('init_net.pbtxt') || identifier.endsWith('init_net.prototxt')) {
  14. return undefined;
  15. }
  16. let tags = context.tags('pb');
  17. if (tags.size > 0) {
  18. if (tags.size === 1 && tags.get(1) === 2) {
  19. const tags = context.tags('pb+');
  20. const match = (tags, schema) => {
  21. for (const pair of schema) {
  22. const key = pair[0];
  23. const inner = pair[1];
  24. const value = tags[key];
  25. if (value === undefined) {
  26. continue;
  27. }
  28. if (inner === false) {
  29. return false;
  30. }
  31. if (Array.isArray(inner)) {
  32. if (typeof value !== 'object' || !match(value, inner)) {
  33. return false;
  34. }
  35. }
  36. else if (inner !== value) {
  37. if (inner === 2 && !Array.isArray(value) && Object(value) === (value) && Object.keys(value).length === 0) {
  38. return true;
  39. }
  40. return false;
  41. }
  42. }
  43. return true;
  44. };
  45. // mediapipe.BoxDetectorIndex
  46. 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]] )) {
  47. return undefined;
  48. }
  49. // third_party.tensorflow.python.keras.protobuf.SavedMetadata
  50. if (match(tags, [[1,[[1,[[1,0],[2,0]]],[2,0],[3,2],[4,2],[5,2]]]])) {
  51. return undefined;
  52. }
  53. }
  54. if (Array.from(tags.keys()).every((tag) => tag <= 100) &&
  55. Array.from(tags.values()).every((type) => type < 5)) {
  56. // TensorProto
  57. if (tags.get(1) === 0 && tags.get(2) === 0) {
  58. const schema = [[1,0],[2,0],[4,2],[5,2],[7,2],[8,2],[9,2]];
  59. if (schema.every((pair) => !tags.has(pair[0]) || tags.get(pair[0]) === pair[1])) {
  60. return 'onnx.pb.TensorProto';
  61. }
  62. }
  63. // GraphProto
  64. if (tags.get(1) === 2) {
  65. 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]];
  66. if (schema.every((pair) => !tags.has(pair[0]) || tags.get(pair[0]) === pair[1])) {
  67. const decode = (buffer, value) => {
  68. const reader = protobuf.BinaryReader.open(buffer);
  69. const length = reader.length;
  70. while (reader.position < length) {
  71. const tag = reader.uint32();
  72. const number = tag >>> 3;
  73. const type = tag & 7;
  74. if (value === number) {
  75. return type === 2 ? reader.bytes() : null;
  76. }
  77. else {
  78. reader.skipType(type);
  79. }
  80. }
  81. return null;
  82. };
  83. const stream = context.stream;
  84. const buffer = stream.peek();
  85. const nodeBuffer = decode(buffer, 1);
  86. if (nodeBuffer) {
  87. const nameBuffer = decode(nodeBuffer, 4);
  88. if (nameBuffer && nameBuffer.every((c) => c > 0x20 && c < 0x7f)) {
  89. return 'onnx.pb.GraphProto';
  90. }
  91. }
  92. }
  93. }
  94. // ModelProto
  95. if (tags.get(7) === 2) {
  96. const schema = [[1,0],[2,2],[3,2],[4,2][5,0],[6,2],[7,2],[8,2],[14,2],[20,2]];
  97. if (schema.every((pair) => !tags.has(pair[0]) || tags.get(pair[0]) === pair[1])) {
  98. return 'onnx.pb.ModelProto';
  99. }
  100. }
  101. }
  102. }
  103. const stream = context.stream;
  104. if (stream.length > 5) {
  105. const buffer = stream.peek(Math.min(stream.length, 32));
  106. if (buffer[0] === 0x08 && buffer[1] < 0x0A && buffer[2] === 0x12) {
  107. const producers = [
  108. 'backend-test', 'BrainwaveCompiler',
  109. 'CNTK',
  110. 'keras2onnx', 'Kneron', 'kneron_formatter', 'kneron_kl530_test_case',
  111. 'darknet to ONNX example',
  112. 'htshinichi',
  113. 'MATLAB Deep Learning Toolbox Converter for ONNX Model Format', 'ML.NET', 'MVTec Software',
  114. 'onnx-caffe2', 'onnx-example', 'onnx.quantize', 'onnx.utils.extract_model', 'OnnxMLTools', 'onnx_test', 'onnxruntime-tools', 'onnxruntime.transformers',
  115. 'PaddlePaddle', 'pytorch',
  116. 'sclblonnx', 'skl2onnx',
  117. 'Tencent YouTu', 'tf2onnx', 'tflite2onnx',
  118. 'WinMLTools'
  119. ];
  120. if (producers.some((producer) => Array.from(producer).every((ch, index) => index + 4 < buffer.length && ch.charCodeAt(0) === buffer[index + 4]))) {
  121. return 'onnx.pb.ModelProto';
  122. }
  123. }
  124. }
  125. tags = context.tags('pbtxt');
  126. if (tags.has('ir_version')) {
  127. return 'onnx.pbtxt.ModelProto';
  128. }
  129. if (tags.has('graph') && extension !== 'model') {
  130. return 'onnx.pbtxt.ModelProto';
  131. }
  132. if (context.tags('flatbuffers').get('file_identifier') === 'ORTM') {
  133. return 'onnx.flatbuffers';
  134. }
  135. if (onnx.TextReader.open(stream)) {
  136. return 'onnx.text';
  137. }
  138. return undefined;
  139. }
  140. open(context, match) {
  141. const open = (model, format) => {
  142. return onnx.Metadata.open(context).then((metadata) => {
  143. return new onnx.Model(metadata, model, format);
  144. });
  145. };
  146. switch (match) {
  147. case 'onnx.pbtxt.ModelProto':
  148. return context.require('./onnx-proto').then(() => {
  149. try {
  150. onnx.proto = protobuf.get('onnx').onnx;
  151. const stream = context.stream;
  152. const reader = protobuf.TextReader.open(stream);
  153. const model = onnx.proto.ModelProto.decodeText(reader);
  154. const format = 'ONNX' + (model.ir_version ? ' v' + model.ir_version.toString() : '');
  155. return open(model, format);
  156. }
  157. catch (error) {
  158. const message = error && error.message ? error.message : error.toString();
  159. throw new onnx.Error('File text format is not onnx.ModelProto (' + message.replace(/\.$/, '') + ').');
  160. }
  161. });
  162. case 'onnx.pb.TensorProto':
  163. return context.require('./onnx-proto').then(() => {
  164. // TensorProto
  165. // input_0.pb, output_0.pb
  166. try {
  167. onnx.proto = protobuf.get('onnx').onnx;
  168. const stream = context.stream;
  169. const reader = protobuf.BinaryReader.open(stream);
  170. const tensor = onnx.proto.TensorProto.decode(reader);
  171. tensor.name = tensor.name || context.identifier;
  172. const model = new onnx.proto.ModelProto();
  173. model.graph = new onnx.proto.GraphProto();
  174. model.graph.initializer = [ tensor ];
  175. model.graph.value_info = [ new onnx.proto.ValueInfoProto() ];
  176. model.graph.value_info[0].name = tensor.name;
  177. model.graph.node = [ new onnx.proto.NodeProto() ];
  178. model.graph.node[0].op_type = 'Constant';
  179. model.graph.node[0].attribute = [ new onnx.proto.AttributeProto() ];
  180. model.graph.node[0].attribute[0].name = 'value';
  181. model.graph.node[0].attribute[0].type = onnx.AttributeType.TENSOR;
  182. model.graph.node[0].attribute[0].t = tensor;
  183. const format = 'ONNX Tensor';
  184. return open(model, format);
  185. }
  186. catch (error) {
  187. const message = error && error.message ? error.message : error.toString();
  188. throw new onnx.Error('File format is not onnx.TensorProto (' + message.replace(/\.$/, '') + ').');
  189. }
  190. });
  191. case 'onnx.pb.GraphProto':
  192. return context.require('./onnx-proto').then(() => {
  193. // GraphProto
  194. try {
  195. onnx.proto = protobuf.get('onnx').onnx;
  196. const stream = context.stream;
  197. const reader = protobuf.BinaryReader.open(stream);
  198. const model = new onnx.proto.ModelProto();
  199. model.graph = onnx.proto.GraphProto.decode(reader);
  200. const format = 'ONNX';
  201. return open(model, format);
  202. }
  203. catch (error) {
  204. const message = error && error.message ? error.message : error.toString();
  205. throw new onnx.Error('File format is not onnx.GraphProto (' + message.replace(/\.$/, '') + ').');
  206. }
  207. });
  208. case 'onnx.pb.ModelProto':
  209. return context.require('./onnx-proto').then(() => {
  210. // ModelProto
  211. try {
  212. onnx.proto = protobuf.get('onnx').onnx;
  213. const stream = context.stream;
  214. const reader = protobuf.BinaryReader.open(stream);
  215. const model = onnx.proto.ModelProto.decode(reader);
  216. const format = 'ONNX' + (model.ir_version ? ' v' + model.ir_version.toString() : '');
  217. return open(model, format);
  218. }
  219. catch (error) {
  220. const message = error && error.message ? error.message : error.toString();
  221. throw new onnx.Error('File format is not onnx.ModelProto (' + message.replace(/\.$/, '') + ').');
  222. }
  223. });
  224. case 'onnx.flatbuffers': {
  225. return context.require('./onnx-schema').then((/* schema */) => {
  226. try {
  227. onnx.schema = flatbuffers.get('ort').onnxruntime.fbs;
  228. const stream = context.stream;
  229. const reader = flatbuffers.BinaryReader.open(stream);
  230. const session = onnx.schema.InferenceSession.create(reader);
  231. const model = session.model;
  232. const graph = model.graph;
  233. graph.node = graph.nodes;
  234. graph.doc_string = model.graph_doc_string;
  235. graph.value_info = graph.node_args;
  236. graph.input = graph.inputs.map((input) => {
  237. return { name: input };
  238. });
  239. graph.output = graph.outputs.map((output) => {
  240. return { name: output };
  241. });
  242. graph.initializer = graph.initializers.map((tensor) => {
  243. tensor.data_location = onnx.DataLocation.DEFAULT;
  244. return tensor;
  245. });
  246. graph.sparse_initializer = graph.sparse_initializers.map((tensor) => {
  247. tensor.values.data_location = onnx.DataLocation.DEFAULT;
  248. tensor.indices.data_location = onnx.DataLocation.DEFAULT;
  249. return tensor;
  250. });
  251. delete graph.nodes;
  252. delete graph.node_args;
  253. delete graph.inputs;
  254. delete graph.outputs;
  255. delete graph.initializers;
  256. delete graph.sparse_initializers;
  257. delete model.graph_doc_string;
  258. for (const node of graph.node) {
  259. node.input = node.inputs;
  260. node.output = node.outputs;
  261. node.attribute = node.attributes;
  262. delete node.inputs;
  263. delete node.outputs;
  264. delete node.attributes;
  265. }
  266. const format = 'ONNX Runtime' + (model.ir_version ? ' v' + model.ir_version.toString() : '');
  267. return open(model, format);
  268. }
  269. catch (error) {
  270. const message = error && error.message ? error.message : error.toString();
  271. throw new onnx.Error('File format is not ort.Model (' + message.replace(/\.$/, '') + ').');
  272. }
  273. });
  274. }
  275. case 'onnx.text': {
  276. return context.require('./onnx-proto').then(() => {
  277. try {
  278. onnx.proto = protobuf.get('onnx').onnx;
  279. const stream = context.stream;
  280. const reader = onnx.TextReader.open(stream);
  281. const model = reader.read();
  282. const format = 'ONNX Text' + (model.ir_version ? ' v' + model.ir_version.toString() : '');
  283. return open(model, format);
  284. }
  285. catch (error) {
  286. const message = error && error.message ? error.message : error.toString();
  287. throw new onnx.Error('File format is not onnx.ModelProto (' + message.replace(/\.$/, '') + ').');
  288. }
  289. });
  290. }
  291. default: {
  292. throw new onnx.Error("Unknown ONNX format '" + match + "'.");
  293. }
  294. }
  295. }
  296. };
  297. onnx.Model = class {
  298. constructor(metadata, model, format) {
  299. this._graphs = [];
  300. this._format = format;
  301. this._producer = model.producer_name && model.producer_name.length > 0 ? model.producer_name + (model.producer_version && model.producer_version.length > 0 ? ' ' + model.producer_version : '') : null;
  302. this._domain = model.domain;
  303. this._modelVersion = model.model_version;
  304. this._description = model.doc_string;
  305. this._metadata = [];
  306. this._imports = null;
  307. const imports = new Map();
  308. if (model.opset_import && model.opset_import.length > 0) {
  309. for (const opset_import of model.opset_import) {
  310. const domain = opset_import.domain || 'ai.onnx';
  311. const version = opset_import.version ? typeof opset_import.version === 'number' ? opset_import.version: opset_import.version.toNumber() : 0;
  312. if (!imports.has(domain) || imports.get(domain) > version) {
  313. imports.set(domain, version);
  314. }
  315. }
  316. this._imports = Array.from(imports).map((pair) => pair[0] + ' v' + pair[1].toString());
  317. }
  318. if (imports.size == 0) {
  319. imports.set('ai.onnx', 1);
  320. imports.set('ai.onnx.ml', 1);
  321. }
  322. let imageFormat = '';
  323. if (model.metadata_props) {
  324. const imageMetadata = {};
  325. for (const metadata_prop of model.metadata_props) {
  326. switch (metadata_prop.key) {
  327. case 'author':
  328. this._author = metadata_prop.value;
  329. break;
  330. case 'company':
  331. this._company = metadata_prop.value;
  332. break;
  333. case 'converted_from':
  334. this._converted_from = metadata_prop.value;
  335. break;
  336. case 'license':
  337. this._license = metadata_prop.value;
  338. break;
  339. case 'license_url':
  340. this._licenseUrl = metadata_prop.value;
  341. break;
  342. case 'Image.BitmapPixelFormat':
  343. case 'Image.ColorSpaceGamma':
  344. case 'Image.NominalPixelRange':
  345. imageMetadata[metadata_prop.key] = metadata_prop.value;
  346. break;
  347. default:
  348. this._metadata.push({ name: metadata_prop.key, value: metadata_prop.value});
  349. break;
  350. }
  351. }
  352. imageFormat = [ imageMetadata['Image.BitmapPixelFormat'], imageMetadata['Image.ColorSpaceGamma'], imageMetadata['Image.NominalPixelRange'] ].filter((item) => item);
  353. }
  354. this._graphs = [];
  355. if (model && model.graph) {
  356. const graphMetadata = new onnx.GraphMetadata(metadata, imports);
  357. const context = new onnx.ModelContext(graphMetadata, imageFormat);
  358. for (const func of model.functions || []) {
  359. context.metadata.add(new onnx.Function(context, func));
  360. }
  361. const graphs = [ model.graph ];
  362. while (graphs.length > 0) {
  363. const graph = graphs.shift();
  364. this._graphs.push(context.graph(graph));
  365. for (const node of graph.node || []) {
  366. for (const attribute of node.attribute || []) {
  367. if (attribute.g) {
  368. graphs.push(attribute.g);
  369. }
  370. else if (attribute.graphs && attribute.graphs.length > 0) {
  371. graphs.push(...attribute.graphs);
  372. }
  373. }
  374. }
  375. }
  376. }
  377. }
  378. get format() {
  379. return this._format;
  380. }
  381. get imports() {
  382. return this._imports;
  383. }
  384. get producer() {
  385. return this._producer;
  386. }
  387. get domain() {
  388. return this._domain || null;
  389. }
  390. get description() {
  391. return this._description || null;
  392. }
  393. get author() {
  394. return this._author || null;
  395. }
  396. get company() {
  397. return this._company || null;
  398. }
  399. get source() {
  400. return this._converted_from || null;
  401. }
  402. get license() {
  403. const license = [];
  404. if (this._license && this._license.length > 0) {
  405. license.push(this._license);
  406. }
  407. if (this._licenseUrl && this._licenseUrl.length > 0) {
  408. license.push('<a href=\'' + this._licenseUrl + '\'>' + this._licenseUrl + '</a>');
  409. }
  410. if (license.length > 0) {
  411. return license;
  412. }
  413. return null;
  414. }
  415. get metadata() {
  416. return this._metadata;
  417. }
  418. get graphs() {
  419. return this._graphs;
  420. }
  421. };
  422. onnx.Graph = class {
  423. constructor(context, graph) {
  424. this._node = '';
  425. this._description = '';
  426. this._nodes = [];
  427. this._inputs = [];
  428. this._outputs = [];
  429. this._name = graph.name || null;
  430. this._description = graph.doc_string || '';
  431. context = new onnx.GraphContext(context, graph.node);
  432. for (const initializer of graph.initializer) {
  433. const tensor = context.tensor(initializer.name);
  434. tensor.initializer = new onnx.Tensor(context, initializer, 'Initializer');
  435. }
  436. for (const sparse_initializer of graph.sparse_initializer) {
  437. const tensor = context.tensor(sparse_initializer.values.name);
  438. tensor.initializer = new onnx.Tensor(context, sparse_initializer, 'Sparse Initializer');
  439. }
  440. for (const tensor_annotation of graph.quantization_annotation || []) {
  441. const tensor = context.tensor(tensor_annotation.tensor_name);
  442. const annotation = {};
  443. for (const pair of tensor_annotation.quant_parameter_tensor_names) {
  444. annotation[pair.key] = pair.value;
  445. }
  446. tensor.annotation = annotation;
  447. }
  448. for (const valueInfo of graph.value_info) {
  449. const tensor = context.tensor(valueInfo.name);
  450. tensor.type = context.createType(valueInfo.type);
  451. tensor.description = valueInfo.doc_string;
  452. }
  453. graph.input = graph.input.map((valueInfo) => {
  454. const tensor = context.tensor(valueInfo.name);
  455. tensor.type = context.createType(valueInfo.type);
  456. tensor.description = valueInfo.doc_string;
  457. return tensor;
  458. });
  459. graph.output = graph.output.map((valueInfo) => {
  460. const tensor = context.tensor(valueInfo.name);
  461. tensor.type = context.createType(valueInfo.type);
  462. tensor.description = valueInfo.doc_string;
  463. return tensor;
  464. });
  465. new onnx.Inference(graph.node, graph.output);
  466. context.push(graph.node, graph.input, graph.output);
  467. this._nodes = context.pop();
  468. for (const input of graph.input) {
  469. const argument = context.argument(input.name);
  470. if (!argument.initializer) {
  471. this._inputs.push(new onnx.Parameter(input.name, [ argument ]));
  472. }
  473. }
  474. for (const output of graph.output) {
  475. const argument = context.argument(output.name);
  476. if (!argument.initializer) {
  477. this._outputs.push(new onnx.Parameter(output.name, [ argument ]));
  478. }
  479. }
  480. }
  481. get name() {
  482. return this._name;
  483. }
  484. get description() {
  485. return this._description;
  486. }
  487. get inputs() {
  488. return this._inputs;
  489. }
  490. get outputs() {
  491. return this._outputs;
  492. }
  493. get nodes() {
  494. return this._nodes;
  495. }
  496. toString() {
  497. return 'graph(' + this.name + ')';
  498. }
  499. };
  500. onnx.Parameter = class {
  501. constructor(name, args) {
  502. this._name = name;
  503. this._arguments = args;
  504. }
  505. get name() {
  506. return this._name;
  507. }
  508. get visible() {
  509. return true;
  510. }
  511. get arguments() {
  512. return this._arguments;
  513. }
  514. };
  515. onnx.Argument = class {
  516. constructor(name, type, initializer, annotation, description) {
  517. if (typeof name !== 'string') {
  518. throw new onnx.Error("Invalid argument identifier '" + JSON.stringify(name) + "'.");
  519. }
  520. this._name = name;
  521. this._type = type || null;
  522. this._initializer = initializer || null;
  523. this._annotation = annotation;
  524. this._description = description || '';
  525. }
  526. get name() {
  527. return this._name;
  528. }
  529. get type() {
  530. return this._type;
  531. }
  532. get description() {
  533. return this._description;
  534. }
  535. get quantization() {
  536. if (this._annotation) {
  537. return Object.keys(this._annotation).map((key) => key + ': ' + this._annotation[key]).join(', ');
  538. }
  539. return null;
  540. }
  541. get initializer() {
  542. return this._initializer;
  543. }
  544. };
  545. onnx.Node = class {
  546. constructor(context, op_type, domain, name, description, attributes, inputs, outputs) {
  547. this._type = context.metadata.type(op_type, domain) || { name: op_type, module: domain };
  548. if (this.type.module !== domain && !(this._type instanceof onnx.Function)) {
  549. this._type = Object.assign({}, this.type);
  550. this._type.name = op_type;
  551. this._type.module = domain;
  552. }
  553. this._name = name || '';
  554. this._description = description || '';
  555. this._inputs = inputs;
  556. this._outputs = outputs;
  557. this._attributes = (attributes || []).map((attribute) => new onnx.Attribute(context, op_type, domain, attribute));
  558. }
  559. get type() {
  560. return this._type;
  561. }
  562. get name() {
  563. return this._name;
  564. }
  565. get description() {
  566. return this._description;
  567. }
  568. get attributes() {
  569. return this._attributes;
  570. }
  571. get inputs() {
  572. return this._inputs;
  573. }
  574. get outputs() {
  575. return this._outputs;
  576. }
  577. };
  578. onnx.Attribute = class {
  579. constructor(context, op_type, domain, attribute) {
  580. this._name = attribute.name;
  581. this._description = attribute.doc_string || '';
  582. this._type = null;
  583. this._value = null;
  584. switch (attribute.type) {
  585. case onnx.AttributeType.FLOAT:
  586. this._value = attribute.f;
  587. this._type = 'float32';
  588. break;
  589. case onnx.AttributeType.INT:
  590. this._value = attribute.i;
  591. this._type = 'int64';
  592. break;
  593. case onnx.AttributeType.STRING:
  594. switch (op_type) {
  595. case 'Int8GivenTensorFill':
  596. this._value = Array.from(attribute.s);
  597. break;
  598. default:
  599. this._value = context.decodeText(attribute.s);
  600. break;
  601. }
  602. this._type = 'string';
  603. break;
  604. case onnx.AttributeType.TENSOR:
  605. this._value = new onnx.Tensor(context, attribute.t);
  606. this._type = 'tensor';
  607. break;
  608. case onnx.AttributeType.GRAPH:
  609. this._value = context.graph(attribute.g);
  610. this._type = 'graph';
  611. break;
  612. case onnx.AttributeType.FLOATS:
  613. this._value = ArrayBuffer.isView(attribute.floats) ? Array.from(attribute.floats) : attribute.floats;
  614. this._type = 'float32[]';
  615. break;
  616. case onnx.AttributeType.INTS:
  617. this._value = ArrayBuffer.isView(attribute.ints) ? Array.from(attribute.ints) : attribute.ints;
  618. this._type = 'int64[]';
  619. break;
  620. case onnx.AttributeType.STRINGS:
  621. this._value = attribute.strings.map((s) => context.decodeText(s));
  622. this._type = 'string[]';
  623. break;
  624. case onnx.AttributeType.TENSORS:
  625. this._value = attribute.tensors.map((tensor) => new onnx.Tensor(context, tensor));
  626. this._type = 'tensor[]';
  627. break;
  628. case onnx.AttributeType.GRAPHS:
  629. this._value = attribute.graphs.map((graph) => context.graph(graph));
  630. this._type = 'graph[]';
  631. break;
  632. case onnx.AttributeType.SPARSE_TENSOR:
  633. this._value = new onnx.Tensor(context, attribute.sparse_tensor);
  634. this._type = 'tensor';
  635. break;
  636. case onnx.AttributeType.SPARSE_TENSORS:
  637. this._value = attribute.sparse_tensors.map((tensor) => new onnx.Tensor(context, tensor));
  638. this._type = 'tensor[]';
  639. break;
  640. case onnx.AttributeType.TYPE_PROTO:
  641. this._value = context.createType(attribute.tp);
  642. this._type = 'type';
  643. break;
  644. case onnx.AttributeType.TYPE_PROTOS:
  645. this._value = attribute.type_protos.map((type) => context.createType(type));
  646. this._type = 'type[]';
  647. break;
  648. default:
  649. throw new onnx.Error("Unknown attribute type '" + attribute.type + "'.");
  650. }
  651. const metadata = context.metadata.attribute(op_type, domain, attribute.name);
  652. if (metadata) {
  653. if (Object.prototype.hasOwnProperty.call(metadata, 'default') && this._value == metadata.default) {
  654. this._visible = false;
  655. }
  656. if (metadata.type === 'DataType') {
  657. this._type = metadata.type;
  658. const value = this._value ? parseInt(this._value.toString(), 10) : this._value;
  659. this._value = Number.isInteger(value) ? context.createDataType(value) : value;
  660. }
  661. }
  662. }
  663. get name() {
  664. return this._name;
  665. }
  666. get type() {
  667. return this._type;
  668. }
  669. get value() {
  670. return this._value;
  671. }
  672. get description() {
  673. return this._description;
  674. }
  675. get visible() {
  676. return this._visible == false ? false : true;
  677. }
  678. };
  679. onnx.Group = class {
  680. constructor(name, groups) {
  681. this._type = { name: 'Scope' };
  682. this._name = name;
  683. this._nodes = [];
  684. for (const entry of groups) {
  685. const key = entry[0];
  686. if (key === '') {
  687. for (const node of entry[1]) {
  688. this._nodes.push(node);
  689. }
  690. }
  691. else {
  692. this._nodes.push(new onnx.Group(name === '' ? key : name + '/' + key, entry[1]));
  693. }
  694. }
  695. const set = new Set();
  696. const inputs = new Array();
  697. const outputs = new Array();
  698. for (const node of this._nodes) {
  699. if (node instanceof onnx.Group) {
  700. node.freeze();
  701. }
  702. for (const parameter of node.outputs) {
  703. for (const argument of parameter.arguments) {
  704. if (!argument.initializer) {
  705. outputs.push(argument);
  706. set.add(argument.name);
  707. }
  708. }
  709. }
  710. }
  711. for (const node of this._nodes) {
  712. for (const parameter of node.inputs) {
  713. for (const argument of parameter.arguments) {
  714. if (!set.has(argument.name) && !argument.initializer) {
  715. inputs.push(argument);
  716. }
  717. }
  718. }
  719. }
  720. this._inputs = [ new onnx.Parameter('inputs', inputs) ];
  721. this._outputs = [ new onnx.Parameter('outputs', outputs) ];
  722. this._attributes = [];
  723. }
  724. get name() {
  725. return this._name;
  726. }
  727. get type() {
  728. return this._type;
  729. }
  730. get inputs() {
  731. return this._inputs;
  732. }
  733. get outputs() {
  734. return this._outputs;
  735. }
  736. get attributes() {
  737. return this._attributes;
  738. }
  739. get nodes() {
  740. return this._nodes;
  741. }
  742. };
  743. onnx.Tensor = class {
  744. constructor(context, tensor, kind) {
  745. this._kind = kind || null;
  746. const data = (tensor) => {
  747. let data = undefined;
  748. if (tensor.data_location === onnx.DataLocation.DEFAULT) {
  749. switch (tensor.data_type) {
  750. case onnx.DataType.FLOAT16:
  751. if (tensor.int32_data && tensor.int32_data.length > 0) {
  752. const buffer = new Uint8Array(tensor.int32_data.length << 1);
  753. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  754. const array = tensor.int32_data;
  755. for (let i = 0; i < array.length; i++) {
  756. view.setUint16(i << 1, array[i], true);
  757. }
  758. data = {
  759. type: tensor.data_type,
  760. buffer: buffer
  761. };
  762. }
  763. break;
  764. case onnx.DataType.FLOAT:
  765. data = new Float32Array(tensor.float_data);
  766. break;
  767. case onnx.DataType.DOUBLE:
  768. data = new Float64Array(tensor.double_data);
  769. break;
  770. case onnx.DataType.BOOL:
  771. if (tensor.int32_data && tensor.int32_data.length > 0) {
  772. const array = tensor.int32_data;
  773. data = new Array(array.length);
  774. for (let i = 0; i < data.length; i++) {
  775. data[i] = array[i] === 0 ? false : true;
  776. }
  777. }
  778. break;
  779. case onnx.DataType.INT8:
  780. data = new Int8Array(tensor.int32_data);
  781. break;
  782. case onnx.DataType.UINT8:
  783. data = new Uint8Array(tensor.int32_data);
  784. break;
  785. case onnx.DataType.INT16:
  786. data = new Int32Array(tensor.int32_data);
  787. break;
  788. case onnx.DataType.UINT16:
  789. data = new Int32Array(tensor.int32_data);
  790. break;
  791. case onnx.DataType.INT32:
  792. data = new Int32Array(tensor.int32_data);
  793. break;
  794. case onnx.DataType.UINT32:
  795. case onnx.DataType.UINT64:
  796. data = tensor.uint64_data;
  797. break;
  798. case onnx.DataType.INT64:
  799. data = tensor.int64_data;
  800. break;
  801. }
  802. if (data && (Array.isArray(data) || ArrayBuffer.isView(data)) && data.length === 0) {
  803. data = undefined;
  804. }
  805. if (!data && tensor.raw_data && tensor.raw_data.length > 0) {
  806. data = {
  807. type: tensor.data_type,
  808. buffer: tensor.raw_data
  809. };
  810. }
  811. }
  812. return data;
  813. };
  814. if ((onnx.proto && tensor instanceof onnx.proto.SparseTensorProto) ||
  815. (onnx.schema && tensor instanceof onnx.schema.SparseTensor)) {
  816. this._name = tensor.values.name || '';
  817. this._type = context.createTensorType(tensor.values.data_type, tensor.dims.map((dim) => dim), null);
  818. this._location = Array.from(new Set([ context.createLocation(tensor.values.data_location), context.createLocation(tensor.indices.data_location) ])).join(':');
  819. this._values = data(tensor.values);
  820. this._indices = data(tensor.indices);
  821. }
  822. else {
  823. this._name = tensor.name || '';
  824. this._type = context.createTensorType(tensor.data_type, tensor.dims.map((dim) => dim), null);
  825. this._location = context.createLocation(tensor.data_location);
  826. this._values = data(tensor);
  827. }
  828. }
  829. get name() {
  830. return this._name;
  831. }
  832. get kind() {
  833. return this._kind;
  834. }
  835. get type() {
  836. return this._type;
  837. }
  838. get state() {
  839. return this._context().state || null;
  840. }
  841. get value() {
  842. const context = this._context();
  843. if (context.state) {
  844. return null;
  845. }
  846. context.limit = Number.MAX_SAFE_INTEGER;
  847. return this._decode(context, 0);
  848. }
  849. toString() {
  850. const context = this._context();
  851. if (context.state) {
  852. return '';
  853. }
  854. context.limit = 10000;
  855. const value = this._decode(context, 0);
  856. return onnx.Tensor._stringify(value, '', ' ');
  857. }
  858. _context() {
  859. const context = {};
  860. context.state = null;
  861. if (this._sparse) {
  862. context.state = 'Sparse data not implemented.';
  863. return context;
  864. }
  865. if (this._location !== 'default') {
  866. context.state = "Data '" + this._location + "' location not implemented.";
  867. return context;
  868. }
  869. const decode = (data) => {
  870. if (!data || Array.isArray(data) || ArrayBuffer.isView(data)) {
  871. return data;
  872. }
  873. const buffer = data.buffer;
  874. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  875. const type = data.type;
  876. data = undefined;
  877. switch (type) {
  878. case onnx.DataType.BOOL:
  879. data = new Array(buffer.length);
  880. for (let i = 0; i < buffer.length; i++) {
  881. data[i] = view.getUint8(i) === 0 ? false : true;
  882. }
  883. break;
  884. case onnx.DataType.FLOAT16:
  885. data = new Float32Array(buffer.length >> 1);
  886. for (let i = 0; i < data.length; i++) {
  887. data[i] = view.getFloat16(i << 1, true);
  888. }
  889. break;
  890. case onnx.DataType.FLOAT:
  891. data = new Float32Array(buffer.length >> 2);
  892. for (let i = 0; i < data.length; i++) {
  893. data[i] = view.getFloat32(i << 2, true);
  894. }
  895. break;
  896. case onnx.DataType.DOUBLE:
  897. data = new Float64Array(buffer.length >> 3);
  898. for (let i = 0; i < data.length; i++) {
  899. data[i] = view.getFloat64(i << 3, true);
  900. }
  901. break;
  902. case onnx.DataType.INT8:
  903. data = new Int8Array(buffer.length);
  904. for (let i = 0; i < data.length; i++) {
  905. data[i] = view.getInt8(i, true);
  906. }
  907. break;
  908. case onnx.DataType.UINT8:
  909. data = new Uint8Array(buffer.length);
  910. for (let i = 0; i < data.length; i++) {
  911. data[i] = view.getUint8(i, true);
  912. }
  913. break;
  914. case onnx.DataType.INT16:
  915. data = new Int16Array(buffer.length >> 1);
  916. for (let i = 0; i < data.length; i++) {
  917. data[i] = view.getInt16(i << 1, true);
  918. }
  919. break;
  920. case onnx.DataType.UINT16:
  921. data = new Uint16Array(buffer.length >> 1);
  922. for (let i = 0; i < data.length; i++) {
  923. data[i] = view.getUint16(i << 1, true);
  924. }
  925. break;
  926. case onnx.DataType.INT32:
  927. data = new Int32Array(buffer.length >> 2);
  928. for (let i = 0; i < data.length; i++) {
  929. data[i] = view.getInt32(i << 2, true);
  930. }
  931. break;
  932. case onnx.DataType.UINT32:
  933. data = new Uint32Array(buffer.length >> 2);
  934. for (let i = 0; i < data.length; i++) {
  935. data[i] = view.getUint32(i << 2, true);
  936. }
  937. break;
  938. case onnx.DataType.INT64:
  939. data = new Array(buffer.length >> 3);
  940. for (let i = 0; i < data.length; i++) {
  941. data[i] = view.getInt64(i << 3, true);
  942. }
  943. break;
  944. case onnx.DataType.UINT64:
  945. data = new Array(buffer.length >> 3);
  946. for (let i = 0; i < data.length; i++) {
  947. data[i] = view.getUint64(i << 3, true);
  948. }
  949. break;
  950. }
  951. return data;
  952. };
  953. this._values = decode(this._values);
  954. if (!this._values) {
  955. context.state = 'Tensor data is empty.';
  956. return context;
  957. }
  958. this._indices = decode(this._indices);
  959. context.values = this._values;
  960. context.indices = this._indices;
  961. context.index = 0;
  962. context.dataType = this.type.dataType;
  963. context.shape = this.type.shape.dimensions;
  964. context.data = function() {
  965. if (!this._data) {
  966. if (this.indices && this.values && this.indices.length === this.values.length) {
  967. const size = context.shape.reduce((a, b) => a * b, 1);
  968. const indices = this.indices;
  969. const values = this.values;
  970. const array = new values.constructor(size);
  971. switch (this.dataType) {
  972. case 'boolean':
  973. array.fill(false);
  974. break;
  975. case 'int64':
  976. case 'uint64':
  977. break;
  978. }
  979. if (indices.length > 0) {
  980. if (Object.prototype.hasOwnProperty.call(indices[0], 'low')) {
  981. for (let i = 0; i < indices.length; i++) {
  982. const index = indices[i];
  983. array[index.high === 0 ? index.low : index.toNumber()] = values[i];
  984. }
  985. }
  986. else {
  987. for (let i = 0; i < indices.length; i++) {
  988. array[indices[i]] = values[i];
  989. }
  990. }
  991. }
  992. this._data = array;
  993. }
  994. else {
  995. this._data = this.values;
  996. }
  997. }
  998. return this._data;
  999. };
  1000. return context;
  1001. }
  1002. _decode(context, dimension) {
  1003. const shape = context.shape.length !== 0 ? context.shape : [ 1 ];
  1004. const results = [];
  1005. const size = shape[dimension];
  1006. const data = context.data();
  1007. if (dimension == shape.length - 1) {
  1008. for (let i = 0; i < size; i++) {
  1009. if (context.index > context.limit) {
  1010. results.push('...');
  1011. return results;
  1012. }
  1013. results.push(data[context.index++]);
  1014. }
  1015. }
  1016. else {
  1017. for (let j = 0; j < size; j++) {
  1018. if (context.index > context.limit) {
  1019. results.push('...');
  1020. return results;
  1021. }
  1022. results.push(this._decode(context, dimension + 1));
  1023. }
  1024. }
  1025. if (context.shape.length == 0) {
  1026. return results[0];
  1027. }
  1028. return results;
  1029. }
  1030. static _stringify(value, indentation, indent) {
  1031. if (Array.isArray(value)) {
  1032. const result = [];
  1033. result.push(indentation + '[');
  1034. const items = value.map((item) => onnx.Tensor._stringify(item, indentation + indent, indent));
  1035. if (items.length > 0) {
  1036. result.push(items.join(',\n'));
  1037. }
  1038. result.push(indentation + ']');
  1039. return result.join('\n');
  1040. }
  1041. if (typeof value == 'string') {
  1042. return indentation + value;
  1043. }
  1044. if (value == Infinity) {
  1045. return indentation + 'Infinity';
  1046. }
  1047. if (value == -Infinity) {
  1048. return indentation + '-Infinity';
  1049. }
  1050. if (isNaN(value)) {
  1051. return indentation + 'NaN';
  1052. }
  1053. return indentation + value.toString();
  1054. }
  1055. };
  1056. onnx.TensorType = class {
  1057. constructor(dataType, shape, denotation) {
  1058. this._dataType = dataType;
  1059. this._shape = shape;
  1060. this._denotation = denotation || null;
  1061. }
  1062. get dataType() {
  1063. return this._dataType;
  1064. }
  1065. get shape() {
  1066. return this._shape;
  1067. }
  1068. get denotation() {
  1069. return this._denotation;
  1070. }
  1071. toString() {
  1072. return this.dataType + this._shape.toString();
  1073. }
  1074. };
  1075. onnx.TensorShape = class {
  1076. constructor(dimensions) {
  1077. this._dimensions = dimensions;
  1078. }
  1079. get dimensions() {
  1080. return this._dimensions;
  1081. }
  1082. toString() {
  1083. if (!this._dimensions || this._dimensions.length == 0) {
  1084. return '';
  1085. }
  1086. return '[' + this._dimensions.map((dim) => dim ? dim.toString() : '?').join(',') + ']';
  1087. }
  1088. };
  1089. onnx.SequenceType = class {
  1090. constructor(elementType, denotation) {
  1091. this._elementType = elementType;
  1092. this._denotation = denotation;
  1093. }
  1094. get elementType() {
  1095. return this._elementType;
  1096. }
  1097. get dennotation() {
  1098. return this._dennotation;
  1099. }
  1100. toString() {
  1101. return 'sequence<' + this._elementType.toString() + '>';
  1102. }
  1103. };
  1104. onnx.MapType = class {
  1105. constructor(keyType, valueType, denotation) {
  1106. this._keyType = keyType;
  1107. this._valueType = valueType;
  1108. this._denotation = denotation;
  1109. }
  1110. get keyType() {
  1111. return this._keyType;
  1112. }
  1113. get valueType() {
  1114. return this._valueType;
  1115. }
  1116. get denotation() {
  1117. return this._denotation;
  1118. }
  1119. toString() {
  1120. return 'map<' + this._keyType + ',' + this._valueType.toString() + '>';
  1121. }
  1122. };
  1123. onnx.OpaqueType = class {
  1124. constructor(domain, name) {
  1125. this._domain = domain;
  1126. this._name = name;
  1127. }
  1128. toString() {
  1129. const name = (this._domain ? (this._domain + '.') : '') + this._name;
  1130. return 'opaque<' + name + '>';
  1131. }
  1132. };
  1133. onnx.Function = class {
  1134. constructor(context, func) {
  1135. this._name = func.name;
  1136. this._domain = func.domain;
  1137. this._description = func.doc_string;
  1138. this._inputs = [];
  1139. this._outputs = [];
  1140. this._attributes = func.attribute.map((attribtue) => { return { name: attribtue }; });
  1141. context = new onnx.GraphContext(context, func.node);
  1142. func.input = func.input.map((input) => context.tensor(input));
  1143. func.output = func.output.map((output) => context.tensor(output));
  1144. context.push(func.node, func.input, func.output);
  1145. this._nodes = context.pop();
  1146. for (const input of func.input) {
  1147. const argument = context.argument(input.name);
  1148. if (!argument.initializer) {
  1149. this._inputs.push(new onnx.Parameter(input.name, [ argument ]));
  1150. }
  1151. }
  1152. for (const output of func.output) {
  1153. const argument = context.argument(output.name);
  1154. if (!argument.initializer) {
  1155. this._outputs.push(new onnx.Parameter(output.name, [ argument ]));
  1156. }
  1157. }
  1158. }
  1159. get type() {
  1160. return 'function';
  1161. }
  1162. get name() {
  1163. return this._name;
  1164. }
  1165. get module() {
  1166. return this._domain;
  1167. }
  1168. get description() {
  1169. return this._description;
  1170. }
  1171. get inputs() {
  1172. return this._inputs;
  1173. }
  1174. get outputs() {
  1175. return this._outputs;
  1176. }
  1177. get attributes() {
  1178. return this._attributes;
  1179. }
  1180. get nodes() {
  1181. return this._nodes;
  1182. }
  1183. };
  1184. onnx.GraphMetadata = class {
  1185. constructor(metadata, imports) {
  1186. this._metadata = metadata;
  1187. this._imports = imports;
  1188. this._cache = new Map();
  1189. this._attributes = new Map();
  1190. this._functions = new Map();
  1191. }
  1192. add(func) {
  1193. if (!this._functions.has(func.module)) {
  1194. this._functions.set(func.module, new Map());
  1195. }
  1196. const map = this._functions.get(func.module);
  1197. if (map.has(func.name)) {
  1198. throw new onnx.Error("Duplicate function identifier '" + func.module + '.' + func.name + "'.");
  1199. }
  1200. map.set(func.name, func);
  1201. }
  1202. type(name, domain) {
  1203. domain = domain || 'ai.onnx';
  1204. const key = domain + ':' + name;
  1205. if (!this._cache.has(key)) {
  1206. let value = this._metadata.type(name, domain, this._imports);
  1207. if (!value) {
  1208. if (this._functions.has(domain)) {
  1209. const map = this._functions.get(domain);
  1210. if (map.has(name)) {
  1211. value = map.get(name);
  1212. }
  1213. }
  1214. }
  1215. this._cache.set(key, value);
  1216. }
  1217. return this._cache.get(key);
  1218. }
  1219. attribute(type, domain, name) {
  1220. const key = domain + ':' + type + ':' + name;
  1221. if (!this._attributes.has(key)) {
  1222. const schema = this.type(type, domain);
  1223. if (schema && schema.attributes && schema.attributes.length > 0) {
  1224. for (const attribute of schema.attributes) {
  1225. this._attributes.set(key, attribute);
  1226. }
  1227. }
  1228. if (!this._attributes.has(key)) {
  1229. this._attributes.set(key, null);
  1230. }
  1231. }
  1232. return this._attributes.get(key);
  1233. }
  1234. };
  1235. onnx.Metadata = class {
  1236. static open(context) {
  1237. if (onnx.Metadata._metadata) {
  1238. return Promise.resolve(onnx.Metadata._metadata);
  1239. }
  1240. return context.request('onnx-metadata.json', 'utf-8', null).then((data) => {
  1241. onnx.Metadata._metadata = new onnx.Metadata(data);
  1242. return onnx.Metadata._metadata;
  1243. }).catch(() => {
  1244. onnx.Metadata._metadata = new onnx.Metadata(null);
  1245. return onnx.Metadata._metadata;
  1246. });
  1247. }
  1248. constructor(data) {
  1249. this._map = new Map();
  1250. if (data) {
  1251. const metadata = JSON.parse(data);
  1252. for (const item of metadata) {
  1253. if (!this._map.has(item.module)) {
  1254. this._map.set(item.module, new Map());
  1255. }
  1256. const map = this._map.get(item.module);
  1257. if (!map.has(item.name)) {
  1258. map.set(item.name, []);
  1259. }
  1260. map.get(item.name).push(item);
  1261. }
  1262. }
  1263. }
  1264. type(name, domain, imports) {
  1265. domain = domain || 'ai.onnx';
  1266. let current = null;
  1267. if (this._map.has(domain)) {
  1268. const map = this._map.get(domain);
  1269. if (map.has(name)) {
  1270. for (const metadata of map.get(name)) {
  1271. const matchVersion = current ? current.version : -1;
  1272. const importVersion = imports.get(metadata.module) || 0;
  1273. if (importVersion >= metadata.version && matchVersion < metadata.version) {
  1274. current = metadata;
  1275. }
  1276. }
  1277. }
  1278. }
  1279. return current;
  1280. }
  1281. };
  1282. onnx.Inference = class {
  1283. constructor(nodes, outputs) {
  1284. this._outputs = new Map();
  1285. for (const node of nodes) {
  1286. for (const output of node.output) {
  1287. this._outputs.set(output.name, node);
  1288. }
  1289. }
  1290. for (const output of outputs) {
  1291. this._infer(output.name);
  1292. }
  1293. }
  1294. _infer(output) {
  1295. if (this._outputs.has(output)) {
  1296. let hasInputShapes = true;
  1297. const node = this._outputs.get(output);
  1298. for (const input of node.input) {
  1299. if (!input.type) {
  1300. this._infer(input);
  1301. if (!input.type) {
  1302. hasInputShapes = false;
  1303. break;
  1304. }
  1305. }
  1306. }
  1307. if (hasInputShapes) {
  1308. // continue
  1309. }
  1310. }
  1311. }
  1312. };
  1313. onnx.DataLocation = {
  1314. DEFAULT: 0,
  1315. EXTERNAL: 1
  1316. };
  1317. onnx.DataType = {
  1318. UNDEFINED: 0,
  1319. FLOAT: 1,
  1320. UINT8: 2,
  1321. INT8: 3,
  1322. UINT16: 4,
  1323. INT16: 5,
  1324. INT32: 6,
  1325. INT64: 7,
  1326. STRING: 8,
  1327. BOOL: 9,
  1328. FLOAT16: 10,
  1329. DOUBLE: 11,
  1330. UINT32: 12,
  1331. UINT64: 13,
  1332. COMPLEX64: 14,
  1333. COMPLEX128: 15,
  1334. BFLOAT16: 16
  1335. };
  1336. onnx.AttributeType = {
  1337. UNDEFINED: 0,
  1338. FLOAT: 1,
  1339. INT: 2,
  1340. STRING: 3,
  1341. TENSOR: 4,
  1342. GRAPH: 5,
  1343. FLOATS: 6,
  1344. INTS: 7,
  1345. STRINGS: 8,
  1346. TENSORS: 9,
  1347. GRAPHS: 10,
  1348. SPARSE_TENSOR: 11,
  1349. SPARSE_TENSORS: 12,
  1350. TYPE_PROTO: 13,
  1351. TYPE_PROTOS: 14
  1352. };
  1353. onnx.ModelContext = class {
  1354. constructor(metadata, imageFormat) {
  1355. this._metadata = metadata;
  1356. this._imageFormat = imageFormat;
  1357. this._graphs = new Map();
  1358. }
  1359. get metadata() {
  1360. return this._metadata;
  1361. }
  1362. get imageFormat() {
  1363. return this._imageFormat;
  1364. }
  1365. graph(value) {
  1366. if (!this._graphs.has(value)) {
  1367. this._graphs.set(value, new onnx.Graph(this, value));
  1368. }
  1369. return this._graphs.get(value);
  1370. }
  1371. };
  1372. onnx.GraphContext = class {
  1373. constructor(context, nodes) {
  1374. this._context = context;
  1375. this._decoder = new TextDecoder('utf-8');
  1376. this._dataTypes = new Map(Object.entries(onnx.DataType).map((entry) => [ entry[1], entry[0].toLowerCase() ]));
  1377. this._dataTypes.set(onnx.DataType.UNDEFINED, 'UNDEFINED');
  1378. this._dataTypes.set(onnx.DataType.BOOL, 'boolean');
  1379. this._dataTypes.set(onnx.DataType.FLOAT, 'float32');
  1380. this._dataTypes.set(onnx.DataType.DOUBLE, 'float64');
  1381. this._tensors = new Map();
  1382. this._arguments = new Map();
  1383. this._groups = new Map();
  1384. this._nodes = [];
  1385. for (const node of nodes) {
  1386. node.input = node.input.map((name) => this.tensor(name));
  1387. node.output = node.output.map((name) => this.tensor(name));
  1388. node.param = {};
  1389. for (const attribute of node.attribute) {
  1390. if (attribute.type) {
  1391. continue;
  1392. }
  1393. if (attribute.ints && attribute.ints.length > 0) {
  1394. attribute.type = onnx.AttributeType.INTS;
  1395. }
  1396. else if (attribute.floats && attribute.floats.length > 0) {
  1397. attribute.type = onnx.AttributeType.FLOATS;
  1398. }
  1399. else if (attribute.strings && attribute.strings.length > 0) {
  1400. attribute.type = onnx.AttributeType.STRINGS;
  1401. }
  1402. else if (attribute.graphs && attribute.graphs.length > 0) {
  1403. attribute.type = onnx.AttributeType.GRAPHS;
  1404. }
  1405. else if (attribute.s && attribute.s.length > 0) {
  1406. attribute.type = onnx.AttributeType.STRING;
  1407. }
  1408. else if (Object.prototype.hasOwnProperty.call(attribute, 'f')) {
  1409. attribute.type = onnx.AttributeType.FLOAT;
  1410. }
  1411. else if (Object.prototype.hasOwnProperty.call(attribute, 'i')) {
  1412. attribute.type = onnx.AttributeType.INT;
  1413. }
  1414. else if (Object.prototype.hasOwnProperty.call(attribute, 't')) {
  1415. attribute.type = onnx.AttributeType.TENSOR;
  1416. }
  1417. else if (Object.prototype.hasOwnProperty.call(attribute, 'g')) {
  1418. attribute.type = onnx.AttributeType.GRAPH;
  1419. }
  1420. else if (Object.prototype.hasOwnProperty.call(attribute, 'sparse_tensor')) {
  1421. attribute.type =onnx.AttributeType.SPARSE_TENSOR;
  1422. }
  1423. else {
  1424. attribute.type = onnx.AttributeType.UNDEFINED;
  1425. }
  1426. }
  1427. }
  1428. }
  1429. get metadata() {
  1430. return this._context.metadata;
  1431. }
  1432. graph(name) {
  1433. return this._context.graph(name);
  1434. }
  1435. tensor(name) {
  1436. if (!this._tensors.has(name)) {
  1437. this._tensors.set(name, { name: name });
  1438. }
  1439. return this._tensors.get(name);
  1440. }
  1441. group(name) {
  1442. if (!this._groups.has(name)) {
  1443. const path = name.split('/');
  1444. if (path.length > 1) {
  1445. path.pop();
  1446. return this.group(path.join('/'));
  1447. }
  1448. this._groups.set(name, new Map([ [ '', [] ]]));
  1449. }
  1450. return this._groups.get(name);
  1451. }
  1452. argument(name) {
  1453. if (!this._arguments.has(name)) {
  1454. const tensor = this.tensor(name);
  1455. const type = tensor.initializer ? tensor.initializer.type : tensor.type || null;
  1456. this._arguments.set(name, new onnx.Argument(name, type, tensor.initializer, tensor.annotation, tensor.description));
  1457. }
  1458. return this._arguments.get(name);
  1459. }
  1460. createType(type) {
  1461. if (!type) {
  1462. return null;
  1463. }
  1464. let denotation = '';
  1465. switch (type.denotation) {
  1466. case 'TENSOR':
  1467. denotation = 'Tensor';
  1468. break;
  1469. case 'IMAGE':
  1470. denotation = 'Image' + (this._context.imageFormat ? '(' + this._context.imageFormat.join(',') + ')' : '');
  1471. break;
  1472. case 'AUDIO':
  1473. denotation = 'Audio';
  1474. break;
  1475. case 'TEXT':
  1476. denotation = 'Text';
  1477. break;
  1478. }
  1479. switch (type.value) {
  1480. case 'tensor_type': {
  1481. const tensor_type = type.tensor_type;
  1482. let shape = [];
  1483. if (tensor_type.shape && tensor_type.shape.dim) {
  1484. shape = tensor_type.shape.dim.map((dim) => dim.dim_param ? dim.dim_param : dim.dim_value ? dim.dim_value : null);
  1485. }
  1486. return this.createTensorType(tensor_type.elem_type, shape, denotation);
  1487. }
  1488. case 'sparse_tensor_type': {
  1489. const tensor_type = type.sparse_tensor_type;
  1490. let shape = [];
  1491. if (tensor_type.shape && tensor_type.shape.dim) {
  1492. shape = tensor_type.shape.dim.map((dim) => dim.dim_param ? dim.dim_param : dim.dim_value);
  1493. }
  1494. return this.createTensorType(tensor_type.elem_type, shape, denotation);
  1495. }
  1496. case 'map_type': {
  1497. return this.createMapType(type.map_type.key_type, this.createType(type.map_type.value_type), denotation);
  1498. }
  1499. case 'sequence_type': {
  1500. return new onnx.SequenceType(this.createType(type.sequence_type.elem_type), denotation);
  1501. }
  1502. case 'opaque_type': {
  1503. return new onnx.OpaqueType(type.opaque_type.domain, type.opaque_type.name);
  1504. }
  1505. }
  1506. return null;
  1507. }
  1508. createTensorType(dataType, shape, denotation) {
  1509. dataType = this.createDataType(dataType);
  1510. return new onnx.TensorType(dataType, new onnx.TensorShape(shape), denotation);
  1511. }
  1512. createMapType(keyType, valueType, denotation) {
  1513. keyType = this.createDataType(keyType);
  1514. return new onnx.MapType(keyType, valueType, denotation);
  1515. }
  1516. createDataType(value) {
  1517. return this._dataTypes.has(value) ? this._dataTypes.get(value) : this._dataTypes.get(onnx.DataType.UNDEFINED);
  1518. }
  1519. createLocation(value) {
  1520. switch (value) {
  1521. case onnx.DataLocation.DEFAULT: return 'default';
  1522. case onnx.DataLocation.EXTERNAL: return 'external';
  1523. }
  1524. return 'UNDEFINED';
  1525. }
  1526. decodeText(value) {
  1527. if (typeof value === 'string') {
  1528. return value;
  1529. }
  1530. return this._decoder.decode(value);
  1531. }
  1532. push(nodes, inputs, outputs) {
  1533. const inputMap = new Map();
  1534. const outputMap = new Map();
  1535. for (const node of nodes) {
  1536. node.input.every((input) => inputMap.set(input.name, (inputMap.get(input) || 0) + 1));
  1537. node.output.every((output) => outputMap.set(output.name, (outputMap.get(output) || 0) + 1));
  1538. }
  1539. inputs.every((input) => inputMap.delete(input.name));
  1540. outputs.every((output) => outputMap.delete(output.name));
  1541. nodes = nodes.filter((node) => {
  1542. const constant = node &&
  1543. node.op_type === 'Constant' &&
  1544. node.attribute.length === 1 && node.attribute[0] &&
  1545. node.input.length === 0 &&
  1546. node.output.length === 1 && node.output[0] && inputMap.get(node.output[0].name) === 1 && outputMap.get(node.output[0].name) === 1;
  1547. const attribute = constant ? node.attribute[0] : null;
  1548. if (attribute && attribute.name === 'value' && attribute.type === onnx.AttributeType.TENSOR && attribute.t) {
  1549. const tensor = this.tensor(node.output[0].name);
  1550. tensor.initializer = new onnx.Tensor(this, attribute.t, 'Constant');
  1551. return false;
  1552. }
  1553. else if (attribute && attribute.name === 'sparse_value' && attribute.type === onnx.AttributeType.SPARSE_TENSOR && attribute.sparse_tensor) {
  1554. const tensor = this.tensor(node.output[0].name);
  1555. tensor.initializer = new onnx.Tensor(this, attribute.sparse_tensor, 'Sparse Constant');
  1556. return false;
  1557. }
  1558. return true;
  1559. });
  1560. for (let node of nodes) {
  1561. const schema = this._context.metadata.type(node.op_type, node.domain);
  1562. const inputs = [];
  1563. node.input = node.input || [];
  1564. for (let i = 0; i < node.input.length; ) {
  1565. const input = schema && schema.inputs && i < schema.inputs.length ? schema.inputs[i] : { name: i.toString() };
  1566. const count = input.list ? node.input.length - i : 1;
  1567. const list = node.input.slice(i, i + count).map((input) => this.argument(input.name));
  1568. inputs.push(new onnx.Parameter(input.name, list));
  1569. i += count;
  1570. }
  1571. const outputs = [];
  1572. node.output = node.output || [];
  1573. for (let i = 0; i < node.output.length; ) {
  1574. const output = schema && schema.outputs && i < schema.outputs.length ? schema.outputs[i] : { name: i.toString() };
  1575. const count = output.list ? node.output.length - i : 1;
  1576. const list = node.output.slice(i, i + count).map((output) => this.argument(output.name));
  1577. outputs.push(new onnx.Parameter(output.name, list));
  1578. i += count;
  1579. }
  1580. node = new onnx.Node(this, node.op_type, node.domain, node.name, node.doc_string, node.attribute, inputs, outputs);
  1581. this._nodes.push(node);
  1582. // const path = (node.name || '').split('/');
  1583. // path.pop();
  1584. // this.group(path.join('/')).get('').push(node);
  1585. }
  1586. }
  1587. pop() {
  1588. /*
  1589. const nodes = [];
  1590. for (const entry of this._groups) {
  1591. if (entry[0] === '') {
  1592. for (const node of entry[1].get('')) {
  1593. nodes.push(node);
  1594. }
  1595. continue;
  1596. }
  1597. nodes.push(new onnx.Group(entry[0], entry[1]));
  1598. }
  1599. return nodes;
  1600. */
  1601. return this._nodes;
  1602. }
  1603. };
  1604. onnx.TextReader = class {
  1605. static open(data) {
  1606. try {
  1607. const reader = text.Reader.open(data);
  1608. const lines = [];
  1609. for (let i = 0; i < 32; i++) {
  1610. const line = reader.read();
  1611. if (line === undefined) {
  1612. break;
  1613. }
  1614. lines.push(line);
  1615. }
  1616. const content = lines.join('\n');
  1617. if (/^\s*<\s*ir_version\s*:/m.exec(content) ||
  1618. /^\s*[a-zA-Z][a-zA-Z0-9]*\s*\(.*\)\s=>\s\(/m.exec(content)) {
  1619. return new onnx.TextReader(data);
  1620. }
  1621. }
  1622. catch (err) {
  1623. // continue regardless of error
  1624. }
  1625. return null;
  1626. }
  1627. constructor(data) {
  1628. this._data = data;
  1629. this._dataTypes = new Map([
  1630. [ 'float', 1 ], [ 'uint8', 2 ], [ 'int8', 3 ], [ 'uint16', 4 ],
  1631. [ 'int16', 5 ], [ 'int32', 6 ], [ 'int64', 7 ], [ 'string', 8 ],
  1632. [ 'bool', 9 ], [ 'float16', 10 ], [ 'double', 11 ], [ 'uint32', 12 ],
  1633. [ 'uint64', 13 ], [ 'complex64', 14 ], [ 'complex128', 15 ], [ 'bfloat16', 16 ]
  1634. ]);
  1635. this._attributeTypes = new Map([
  1636. [ 'float', 1 ], [ 'int', 2 ], [ 'string', 3 ],
  1637. [ 'tensor', 4 ], [ 'graph', 5 ], [ 'sparse_tensor', 11 ], [ 'type_proto', 13 ],
  1638. [ 'floats', 6 ], [ 'ints', 7 ], [ 'strings', 8 ],
  1639. [ 'tensors', 9 ], [ 'graphs', 10 ], [ 'sparse_tensors', 12 ], [ 'type_protos', 14 ]
  1640. ]);
  1641. }
  1642. read() {
  1643. const decoder = text.Decoder.open(this._data);
  1644. this._decoder = decoder;
  1645. this._position = 0;
  1646. this._char = decoder.decode();
  1647. return this._model();
  1648. }
  1649. _seek(position) {
  1650. this._decoder.position = position;
  1651. this._char = '';
  1652. this._next();
  1653. }
  1654. _model() {
  1655. this._whitespace();
  1656. const model = new onnx.proto.ModelProto();
  1657. if (this._match('<')) {
  1658. do {
  1659. const keyword = this._identifier();
  1660. this._expect(':');
  1661. switch (keyword) {
  1662. case 'ir_version':
  1663. case 'model_version':
  1664. model[keyword] = this._int64();
  1665. break;
  1666. case 'opset_import':
  1667. model[keyword] = this._operatorSetId();
  1668. break;
  1669. case 'producer_name':
  1670. case 'producer_version':
  1671. case 'domain':
  1672. case 'doc_string':
  1673. model[keyword] = this._string();
  1674. break;
  1675. case 'metadata_props':
  1676. this._expect('[');
  1677. if (!this._match(']')) {
  1678. do {
  1679. const entry = new onnx.proto.StringStringEntryProto();
  1680. entry.key = this._string();
  1681. this._expect(':');
  1682. entry.value = this._string();
  1683. model.metadata_props.push(entry);
  1684. } while (this._match(','));
  1685. this._expect(']');
  1686. }
  1687. break;
  1688. default:
  1689. this._throw("Unknown keyword '" + keyword + "'.");
  1690. break;
  1691. }
  1692. } while (this._match(','));
  1693. this._expect('>');
  1694. }
  1695. model.graph = this._graph();
  1696. this._whitespace();
  1697. while (this._char !== undefined) {
  1698. const func = this._function();
  1699. if (func) {
  1700. model.functions.push(func);
  1701. }
  1702. this._whitespace();
  1703. }
  1704. return model;
  1705. }
  1706. _graph() {
  1707. const graph = new onnx.proto.GraphProto();
  1708. graph.name = this._identifier();
  1709. if (this._match('(')) {
  1710. if (!this._match(')')) {
  1711. do {
  1712. const valueInfo = this._valueInfo();
  1713. if (this._match('=')) {
  1714. this._throw('Initializer not implemented.');
  1715. }
  1716. graph.input.push(valueInfo);
  1717. }
  1718. while (this._match(','));
  1719. this._expect(')');
  1720. }
  1721. }
  1722. this._expect('=>');
  1723. graph.output = this._valueInfoList();
  1724. if (this._match('<')) {
  1725. if (!this._match('>')) {
  1726. do {
  1727. const valueInfo = this._valueInfo();
  1728. if (this._match('=')) {
  1729. this._throw('Initializer not implemented.');
  1730. }
  1731. else {
  1732. graph.value_info.push(valueInfo);
  1733. }
  1734. }
  1735. while (this._match(','));
  1736. this._expect('>');
  1737. }
  1738. }
  1739. graph.node = this._nodeList();
  1740. return graph;
  1741. }
  1742. _nodeList() {
  1743. const list = [];
  1744. this._expect('{');
  1745. while (!this._match('}')) {
  1746. list.push(this._node());
  1747. }
  1748. return list;
  1749. }
  1750. _node() {
  1751. const node = new onnx.proto.NodeProto();
  1752. node.output = this._identifierList();
  1753. this._expect('=');
  1754. let identifier = this._identifier();
  1755. let domain = '';
  1756. while (this._match('.')) {
  1757. if (domain) {
  1758. domain += '.';
  1759. }
  1760. domain += identifier;
  1761. identifier = this._identifier();
  1762. }
  1763. node.domain = domain;
  1764. node.op_type = identifier;
  1765. node.attribute = this._attributeList();
  1766. this._expect('(');
  1767. node.input = this._identifierList();
  1768. this._expect(')');
  1769. if (!node.attribute || node.attribute.length === 0) {
  1770. node.attribute = this._attributeList();
  1771. }
  1772. return node;
  1773. }
  1774. _attributeList() {
  1775. const list = [];
  1776. if (this._match('<')) {
  1777. do {
  1778. list.push(this._attribute());
  1779. }
  1780. while (this._match(','));
  1781. this._expect('>');
  1782. }
  1783. return list;
  1784. }
  1785. _attribute() {
  1786. const attribute = new onnx.proto.AttributeProto();
  1787. attribute.name = this._identifier();
  1788. if (this._match(':')) {
  1789. const type = this._identifier();
  1790. if (!this._attributeTypes.has(type)) {
  1791. this._throw("Unexpected attribute type '" + type + "'.");
  1792. }
  1793. attribute.type = this._attributeTypes.get(type);
  1794. }
  1795. this._expect('=');
  1796. if (this._match('[')) {
  1797. const list = [];
  1798. do {
  1799. list.push(this._literal());
  1800. }
  1801. while (this._match(','));
  1802. this._expect(']');
  1803. if (list.every((value) => typeof value === 'string')) {
  1804. attribute.type = onnx.AttributeType.STRINGS;
  1805. attribute.strings = list;
  1806. }
  1807. else if (list.every((value) => typeof value === 'number' && Number.isInteger(value))) {
  1808. attribute.type = onnx.AttributeType.INTS;
  1809. attribute.ints = list;
  1810. }
  1811. else if (list.every((value) => typeof value === 'number')) {
  1812. attribute.type = onnx.AttributeType.FLOATS;
  1813. attribute.floats = list;
  1814. }
  1815. else {
  1816. this._throw("Unexpected value '" + JSON.stringify(list) + "'.");
  1817. }
  1818. }
  1819. else {
  1820. if ((this._char >= 'a' && this._char <= 'z') || (this._char >= 'A' && this._char <= 'Z') || this._char === '_') {
  1821. const identifier = this._identifier();
  1822. if (this._dataTypes.has(identifier)) {
  1823. attribute.type = onnx.AttributeType.TENSOR;
  1824. attribute.t = this._tensor(identifier);
  1825. }
  1826. else {
  1827. attribute.type = onnx.AttributeType.GRAPH;
  1828. attribute.g = this._graph();
  1829. }
  1830. }
  1831. else if (this._match('@')) {
  1832. attribute.ref_attr_name = this._identifier();
  1833. }
  1834. else {
  1835. const value = this._literal();
  1836. switch (typeof value) {
  1837. case 'number':
  1838. if (Number.isInteger(value)) {
  1839. attribute.type = onnx.AttributeType.INT;
  1840. attribute.i = value;
  1841. }
  1842. else {
  1843. attribute.type = onnx.AttributeType.FLOAT;
  1844. attribute.f = value;
  1845. }
  1846. break;
  1847. case 'string':
  1848. attribute.type = onnx.AttributeType.STRING;
  1849. attribute.s = value;
  1850. break;
  1851. default: {
  1852. this._throw("Unexpected value '" + JSON.stringify(value) + "'.");
  1853. }
  1854. }
  1855. }
  1856. }
  1857. return attribute;
  1858. }
  1859. _valueInfoList() {
  1860. const list = [];
  1861. this._expect('(');
  1862. if (!this._match(')')) {
  1863. do {
  1864. list.push(this._valueInfo());
  1865. } while (this._match(','));
  1866. this._expect(')');
  1867. }
  1868. return list;
  1869. }
  1870. _valueInfo() {
  1871. const valueInfo = new onnx.proto.ValueInfoProto();
  1872. let identifier = this._identifier();
  1873. if (this._dataTypes.has(identifier)) {
  1874. valueInfo.type = this._type(this._dataTypes.get(identifier));
  1875. identifier = this._identifier();
  1876. }
  1877. valueInfo.name = identifier;
  1878. return valueInfo;
  1879. }
  1880. _type(elem_type) {
  1881. const type = new onnx.proto.TypeProto();
  1882. type.tensor_type = new onnx.proto.TypeProto.Tensor();
  1883. type.tensor_type.elem_type = elem_type;
  1884. if (this._match('[')) {
  1885. if (!this._match(']')) {
  1886. type.tensor_type.shape = this._shape();
  1887. this._expect(']');
  1888. }
  1889. }
  1890. else {
  1891. type.tensor_type.shape = new onnx.proto.TensorShapeProto();
  1892. }
  1893. return type;
  1894. }
  1895. _shape() {
  1896. const shape = new onnx.proto.TensorShapeProto();
  1897. do {
  1898. const dimension = new onnx.proto.TensorShapeProto.Dimension();
  1899. if (!this._match('?')) {
  1900. const identifier = this._identifier(true);
  1901. if (identifier) {
  1902. dimension.dim_param = identifier;
  1903. }
  1904. else {
  1905. dimension.dim_value = this._int64();
  1906. }
  1907. }
  1908. shape.dim.push(dimension);
  1909. }
  1910. while (this._match(','));
  1911. return shape;
  1912. }
  1913. _tensor(elem_type) {
  1914. const tensor = new onnx.proto.TensorProto();
  1915. if (!this._dataTypes.has(elem_type)) {
  1916. this._throw("Unexpected type '" + elem_type + "'.");
  1917. }
  1918. const type = this._type(this._dataTypes.get(elem_type));
  1919. if (!type.tensor_type.elem_type) {
  1920. this._throw('Expected tensor data type.');
  1921. }
  1922. if (!type.tensor_type.shape || !type.tensor_type.shape.dim) {
  1923. this._throw('Expected tensor shape.');
  1924. }
  1925. tensor.data_type = type.tensor_type.elem_type;
  1926. tensor.dims = type.tensor_type.shape.dim.map((dim) => dim.dim_value);
  1927. this._expect('{');
  1928. if (!this._match('}')) {
  1929. do {
  1930. this._next();
  1931. } while (!this._match('}'));
  1932. }
  1933. return tensor;
  1934. }
  1935. _function() {
  1936. const func = new onnx.proto.FunctionProto();
  1937. if (this._match('<')) {
  1938. do {
  1939. const keyword = this._identifier();
  1940. this._expect(':');
  1941. switch (keyword) {
  1942. case 'opset_import':
  1943. func[keyword] = this._operatorSetId();
  1944. break;
  1945. case 'domain':
  1946. case 'doc_string':
  1947. func[keyword] = this._string();
  1948. break;
  1949. default:
  1950. this._throw("Unknown keyword '" + keyword + "'.");
  1951. break;
  1952. }
  1953. }
  1954. while (this._match(','));
  1955. this._expect('>');
  1956. }
  1957. func.name = this._identifier();
  1958. if (this._match('<')) {
  1959. func.attribute = this._identifierList();
  1960. this._expect('>');
  1961. }
  1962. if (this._match('(')) {
  1963. func.input = this._identifierList();
  1964. this._expect(')');
  1965. }
  1966. this._expect('=>');
  1967. if (this._match('(')) {
  1968. func.output = this._identifierList();
  1969. this._expect(')');
  1970. }
  1971. func.node = this._nodeList();
  1972. return func;
  1973. }
  1974. _identifierList() {
  1975. const list = [];
  1976. const identifier = this._identifier(true);
  1977. if (identifier) {
  1978. list.push(identifier);
  1979. while (this._match(',')) {
  1980. list.push(this._identifier());
  1981. }
  1982. }
  1983. return list;
  1984. }
  1985. _identifier(optional) {
  1986. this._whitespace();
  1987. const value = [];
  1988. if ((this._char >= 'a' && this._char <= 'z') || (this._char >= 'A' && this._char <= 'Z')) {
  1989. value.push(this._char);
  1990. this._next();
  1991. while ((this._char >= 'a' && this._char <= 'z') || (this._char >= 'A' && this._char <= 'Z') || (this._char >= '0' && this._char <= '9') || this._char === '_') {
  1992. value.push(this._char);
  1993. this._next();
  1994. }
  1995. }
  1996. if (optional !== true && value.length == 0) {
  1997. this._throw('Identifier expected.');
  1998. }
  1999. return value.join('');
  2000. }
  2001. _literal() {
  2002. this._whitespace();
  2003. let decimal_point = false;
  2004. if (this._char === '"') {
  2005. const value = [];
  2006. this._next();
  2007. while (this._char !== undefined && this._char !== '"') {
  2008. value.push(this._char);
  2009. this._next();
  2010. }
  2011. if (this._char !== undefined) {
  2012. this._next();
  2013. }
  2014. return value.join('');
  2015. }
  2016. else if ((this._char >= '0' && this._char <= '9') || this._char === '-') {
  2017. const value = [ this._char ];
  2018. this._next();
  2019. while ((this._char >= '0' && this._char <= '9') || this._char === '.') {
  2020. if (this._char === '.') {
  2021. if (decimal_point) {
  2022. this._throw();
  2023. }
  2024. decimal_point = true;
  2025. }
  2026. value.push(this._char);
  2027. this._next();
  2028. }
  2029. if (value.length === 0) {
  2030. this._throw('Value expected.');
  2031. }
  2032. if (this._char === 'e' || this._char === 'E') {
  2033. decimal_point = true;
  2034. value.push(this._char);
  2035. this._next();
  2036. if (this._char === '+' || this._char === '-') {
  2037. value.push(this._char);
  2038. this._next();
  2039. }
  2040. while ((this._char >= '0' && this._char <= '9')) {
  2041. value.push(this._char);
  2042. this._next();
  2043. }
  2044. }
  2045. return decimal_point ? Number.parseFloat(value.join('')) : Number.parseInt(value.join(''), 10);
  2046. }
  2047. return undefined;
  2048. }
  2049. _int64() {
  2050. const value = this._literal();
  2051. if (!Number.isInteger(value)) {
  2052. this._throw('Integer value expected.');
  2053. }
  2054. return value;
  2055. }
  2056. _string() {
  2057. const value = this._literal();
  2058. if (typeof value !== 'string') {
  2059. this._throw('String value expected.');
  2060. }
  2061. return value;
  2062. }
  2063. _operatorSetId() {
  2064. const list = [];
  2065. this._expect('[');
  2066. if (!this._match(']')) {
  2067. do {
  2068. const value = new onnx.proto.OperatorSetIdProto();
  2069. value.domain = this._string();
  2070. this._expect(':');
  2071. value.version = this._int64();
  2072. list.push(value);
  2073. }
  2074. while (this._match(','));
  2075. this._expect(']');
  2076. }
  2077. return list;
  2078. }
  2079. _match(value) {
  2080. this._whitespace();
  2081. if (this._char !== value[0]) {
  2082. return false;
  2083. }
  2084. if (value.length === 1) {
  2085. this._next();
  2086. return true;
  2087. }
  2088. const position = this._position;
  2089. for (let i = 0; i < value.length; i++) {
  2090. if (this._char !== value[i]) {
  2091. this._seek(position);
  2092. return false;
  2093. }
  2094. this._next();
  2095. }
  2096. return true;
  2097. }
  2098. _expect(value) {
  2099. if (!this._match(value)) {
  2100. this._unexpected();
  2101. }
  2102. return true;
  2103. }
  2104. _whitespace() {
  2105. for (;;) {
  2106. while (this._char === ' ' || this._char === '\n' || this._char === '\r' || this._char === '\t') {
  2107. this._next();
  2108. }
  2109. if (this._char === undefined || this._char !== '#') {
  2110. break;
  2111. }
  2112. while (this._char !== undefined && this._char !== '\n') {
  2113. this._next();
  2114. }
  2115. }
  2116. }
  2117. _next() {
  2118. if (this._char === undefined) {
  2119. this._unexpected();
  2120. }
  2121. this._position = this._decoder.position;
  2122. this._char = this._decoder.decode();
  2123. }
  2124. _unexpected() {
  2125. let c = this._char;
  2126. if (c === undefined) {
  2127. throw new onnx.Error('Unexpected end of input.');
  2128. }
  2129. else if (c === '"') {
  2130. c = 'string';
  2131. }
  2132. else if ((c >= '0' && c <= '9') || c === '-') {
  2133. c = 'number';
  2134. }
  2135. else {
  2136. if (c < ' ' || c > '\x7F') {
  2137. const name = Object.keys(this._escape).filter((key) => this._escape[key] === c);
  2138. c = (name.length === 1) ? '\\' + name : '\\u' + ('000' + c.charCodeAt(0).toString(16)).slice(-4);
  2139. }
  2140. c = "token '" + c + "'";
  2141. }
  2142. this._throw('Unexpected ' + c);
  2143. }
  2144. _throw(message) {
  2145. throw new onnx.Error(message.replace(/\.$/, '') + this._location());
  2146. }
  2147. _location() {
  2148. let line = 1;
  2149. let column = 1;
  2150. this._decoder.position = 0;
  2151. let c;
  2152. do {
  2153. if (this._decoder.position === this._position) {
  2154. return ' at ' + line.toString() + ':' + column.toString() + '.';
  2155. }
  2156. c = this._decoder.decode();
  2157. if (c === '\n') {
  2158. line++;
  2159. column = 1;
  2160. }
  2161. else {
  2162. column++;
  2163. }
  2164. }
  2165. while (c !== undefined);
  2166. return ' at ' + line.toString() + ':' + column.toString() + '.';
  2167. }
  2168. };
  2169. onnx.Error = class extends Error {
  2170. constructor(message) {
  2171. super(message);
  2172. this.name = 'Error loading ONNX model.';
  2173. }
  2174. };
  2175. if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  2176. module.exports.ModelFactory = onnx.ModelFactory;
  2177. }