onnx.js 88 KB

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