onnx.js 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607
  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.UNDEFINED:
  580. break;
  581. case onnx.AttributeType.FLOAT:
  582. this._value = attribute.f;
  583. this._type = 'float32';
  584. break;
  585. case onnx.AttributeType.INT:
  586. this._value = attribute.i;
  587. this._type = 'int64';
  588. break;
  589. case onnx.AttributeType.STRING:
  590. switch (op_type) {
  591. case 'Int8GivenTensorFill':
  592. this._value = Array.from(attribute.s);
  593. break;
  594. default:
  595. this._value = context.decodeText(attribute.s);
  596. break;
  597. }
  598. this._type = 'string';
  599. break;
  600. case onnx.AttributeType.TENSOR:
  601. this._value = new onnx.Tensor(context, attribute.t);
  602. this._type = 'tensor';
  603. break;
  604. case onnx.AttributeType.GRAPH:
  605. this._value = context.graph(attribute.g);
  606. this._type = 'graph';
  607. break;
  608. case onnx.AttributeType.FLOATS:
  609. this._value = ArrayBuffer.isView(attribute.floats) ? Array.from(attribute.floats) : attribute.floats;
  610. this._type = 'float32[]';
  611. break;
  612. case onnx.AttributeType.INTS:
  613. this._value = ArrayBuffer.isView(attribute.ints) ? Array.from(attribute.ints) : attribute.ints;
  614. this._type = 'int64[]';
  615. break;
  616. case onnx.AttributeType.STRINGS:
  617. this._value = attribute.strings.map((s) => context.decodeText(s));
  618. this._type = 'string[]';
  619. break;
  620. case onnx.AttributeType.TENSORS:
  621. this._value = attribute.tensors.map((tensor) => new onnx.Tensor(context, tensor));
  622. this._type = 'tensor[]';
  623. break;
  624. case onnx.AttributeType.GRAPHS:
  625. this._value = attribute.graphs.map((graph) => context.graph(graph));
  626. this._type = 'graph[]';
  627. break;
  628. case onnx.AttributeType.SPARSE_TENSOR:
  629. this._value = new onnx.Tensor(context, attribute.sparse_tensor);
  630. this._type = 'tensor';
  631. break;
  632. case onnx.AttributeType.SPARSE_TENSORS:
  633. this._value = attribute.sparse_tensors.map((tensor) => new onnx.Tensor(context, tensor));
  634. this._type = 'tensor[]';
  635. break;
  636. case onnx.AttributeType.TYPE_PROTO:
  637. this._value = context.createType(attribute.tp);
  638. this._type = 'type';
  639. break;
  640. case onnx.AttributeType.TYPE_PROTOS:
  641. this._value = attribute.type_protos.map((type) => context.createType(type));
  642. this._type = 'type[]';
  643. break;
  644. default:
  645. throw new onnx.Error("Unsupported attribute type '" + attribute.type + "'.");
  646. }
  647. const metadata = context.metadata.attribute(op_type, domain, attribute.name);
  648. if (metadata) {
  649. if (Object.prototype.hasOwnProperty.call(metadata, 'default') && this._value == metadata.default) {
  650. this._visible = false;
  651. }
  652. if (metadata.type === 'DataType') {
  653. this._type = metadata.type;
  654. const value = this._value ? parseInt(this._value.toString(), 10) : this._value;
  655. this._value = Number.isInteger(value) ? context.createDataType(value) : value;
  656. }
  657. }
  658. }
  659. get name() {
  660. return this._name;
  661. }
  662. get type() {
  663. return this._type;
  664. }
  665. get value() {
  666. return this._value;
  667. }
  668. get description() {
  669. return this._description;
  670. }
  671. get visible() {
  672. return this._visible == false ? false : true;
  673. }
  674. };
  675. onnx.Group = class {
  676. constructor(name, groups) {
  677. this._type = { name: 'Scope' };
  678. this._name = name;
  679. this._nodes = [];
  680. for (const entry of groups) {
  681. const key = entry[0];
  682. if (key === '') {
  683. for (const node of entry[1]) {
  684. this._nodes.push(node);
  685. }
  686. }
  687. else {
  688. this._nodes.push(new onnx.Group(name === '' ? key : name + '/' + key, entry[1]));
  689. }
  690. }
  691. const set = new Set();
  692. const inputs = new Array();
  693. const outputs = new Array();
  694. for (const node of this._nodes) {
  695. if (node instanceof onnx.Group) {
  696. node.freeze();
  697. }
  698. for (const parameter of node.outputs) {
  699. for (const argument of parameter.arguments) {
  700. if (!argument.initializer) {
  701. outputs.push(argument);
  702. set.add(argument.name);
  703. }
  704. }
  705. }
  706. }
  707. for (const node of this._nodes) {
  708. for (const parameter of node.inputs) {
  709. for (const argument of parameter.arguments) {
  710. if (!set.has(argument.name) && !argument.initializer) {
  711. inputs.push(argument);
  712. }
  713. }
  714. }
  715. }
  716. this._inputs = [ new onnx.Parameter('inputs', inputs) ];
  717. this._outputs = [ new onnx.Parameter('outputs', outputs) ];
  718. this._attributes = [];
  719. }
  720. get name() {
  721. return this._name;
  722. }
  723. get type() {
  724. return this._type;
  725. }
  726. get inputs() {
  727. return this._inputs;
  728. }
  729. get outputs() {
  730. return this._outputs;
  731. }
  732. get attributes() {
  733. return this._attributes;
  734. }
  735. get nodes() {
  736. return this._nodes;
  737. }
  738. };
  739. onnx.Tensor = class {
  740. constructor(context, tensor, kind) {
  741. this._kind = kind || null;
  742. const data = (tensor) => {
  743. let data = undefined;
  744. if (tensor.data_location === onnx.DataLocation.DEFAULT) {
  745. switch (tensor.data_type) {
  746. case onnx.DataType.FLOAT16:
  747. if (tensor.int32_data && tensor.int32_data.length > 0) {
  748. const buffer = new Uint8Array(tensor.int32_data.length << 1);
  749. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  750. const array = tensor.int32_data;
  751. for (let i = 0; i < array.length; i++) {
  752. view.setUint16(i << 1, array[i], true);
  753. }
  754. data = {
  755. type: tensor.data_type,
  756. buffer: buffer
  757. };
  758. }
  759. break;
  760. case onnx.DataType.FLOAT:
  761. data = new Float32Array(tensor.float_data);
  762. break;
  763. case onnx.DataType.DOUBLE:
  764. data = new Float64Array(tensor.double_data);
  765. break;
  766. case onnx.DataType.BOOL:
  767. if (tensor.int32_data && tensor.int32_data.length > 0) {
  768. const array = tensor.int32_data;
  769. data = new Array(array.length);
  770. for (let i = 0; i < data.length; i++) {
  771. data[i] = array[i] === 0 ? false : true;
  772. }
  773. }
  774. break;
  775. case onnx.DataType.INT8:
  776. data = new Int8Array(tensor.int32_data);
  777. break;
  778. case onnx.DataType.UINT8:
  779. data = new Uint8Array(tensor.int32_data);
  780. break;
  781. case onnx.DataType.INT16:
  782. data = new Int32Array(tensor.int32_data);
  783. break;
  784. case onnx.DataType.UINT16:
  785. data = new Int32Array(tensor.int32_data);
  786. break;
  787. case onnx.DataType.INT32:
  788. data = new Int32Array(tensor.int32_data);
  789. break;
  790. case onnx.DataType.UINT32:
  791. case onnx.DataType.UINT64:
  792. data = tensor.uint64_data;
  793. break;
  794. case onnx.DataType.INT64:
  795. data = tensor.int64_data;
  796. break;
  797. case onnx.DataType.STRING:
  798. data = tensor.string_data;
  799. break;
  800. case onnx.DataType.BFLOAT16:
  801. case onnx.DataType.COMPLEX64:
  802. case onnx.DataType.COMPLEX128:
  803. break;
  804. default:
  805. throw new onnx.Error("Unsupported tensor data type '" + tensor.data_type + "'.");
  806. }
  807. if (data && (Array.isArray(data) || ArrayBuffer.isView(data)) && data.length === 0) {
  808. data = undefined;
  809. }
  810. if (!data && tensor.raw_data && tensor.raw_data.length > 0) {
  811. data = {
  812. type: tensor.data_type,
  813. buffer: tensor.raw_data
  814. };
  815. }
  816. }
  817. return data;
  818. };
  819. if ((onnx.proto && tensor instanceof onnx.proto.SparseTensorProto) ||
  820. (onnx.schema && tensor instanceof onnx.schema.SparseTensor)) {
  821. this._name = tensor.values.name || '';
  822. this._type = context.createTensorType(tensor.values.data_type, tensor.dims.map((dim) => dim), null);
  823. this._location = Array.from(new Set([ context.createLocation(tensor.values.data_location), context.createLocation(tensor.indices.data_location) ])).join(':');
  824. this._values = data(tensor.values);
  825. this._indices = data(tensor.indices);
  826. }
  827. else {
  828. this._name = tensor.name || '';
  829. this._type = context.createTensorType(tensor.data_type, tensor.dims.map((dim) => dim), null);
  830. this._location = context.createLocation(tensor.data_location);
  831. this._values = data(tensor);
  832. }
  833. }
  834. get name() {
  835. return this._name;
  836. }
  837. get kind() {
  838. return this._kind;
  839. }
  840. get type() {
  841. return this._type;
  842. }
  843. get state() {
  844. return this._context().state || null;
  845. }
  846. get value() {
  847. const context = this._context();
  848. if (context.state) {
  849. return null;
  850. }
  851. context.limit = Number.MAX_SAFE_INTEGER;
  852. return this._decode(context, 0);
  853. }
  854. toString() {
  855. const context = this._context();
  856. if (context.state) {
  857. return '';
  858. }
  859. context.limit = 10000;
  860. const value = this._decode(context, 0);
  861. return onnx.Tensor._stringify(value, '', ' ');
  862. }
  863. _context() {
  864. const context = {};
  865. context.state = null;
  866. if (this._sparse) {
  867. context.state = 'Sparse data not implemented.';
  868. return context;
  869. }
  870. if (this._location !== 'default') {
  871. context.state = "Data '" + this._location + "' location not implemented.";
  872. return context;
  873. }
  874. const decode = (data) => {
  875. if (!data || Array.isArray(data) || ArrayBuffer.isView(data)) {
  876. return data;
  877. }
  878. const buffer = data.buffer;
  879. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  880. const type = data.type;
  881. data = undefined;
  882. switch (type) {
  883. case onnx.DataType.BOOL:
  884. data = new Array(buffer.length);
  885. for (let i = 0; i < buffer.length; i++) {
  886. data[i] = view.getUint8(i) === 0 ? false : true;
  887. }
  888. break;
  889. case onnx.DataType.FLOAT16:
  890. data = new Float32Array(buffer.length >> 1);
  891. for (let i = 0; i < data.length; i++) {
  892. data[i] = view.getFloat16(i << 1, true);
  893. }
  894. break;
  895. case onnx.DataType.FLOAT:
  896. data = new Float32Array(buffer.length >> 2);
  897. for (let i = 0; i < data.length; i++) {
  898. data[i] = view.getFloat32(i << 2, true);
  899. }
  900. break;
  901. case onnx.DataType.DOUBLE:
  902. data = new Float64Array(buffer.length >> 3);
  903. for (let i = 0; i < data.length; i++) {
  904. data[i] = view.getFloat64(i << 3, true);
  905. }
  906. break;
  907. case onnx.DataType.INT8:
  908. data = new Int8Array(buffer.length);
  909. for (let i = 0; i < data.length; i++) {
  910. data[i] = view.getInt8(i, true);
  911. }
  912. break;
  913. case onnx.DataType.UINT8:
  914. data = new Uint8Array(buffer.length);
  915. for (let i = 0; i < data.length; i++) {
  916. data[i] = view.getUint8(i, true);
  917. }
  918. break;
  919. case onnx.DataType.INT16:
  920. data = new Int16Array(buffer.length >> 1);
  921. for (let i = 0; i < data.length; i++) {
  922. data[i] = view.getInt16(i << 1, true);
  923. }
  924. break;
  925. case onnx.DataType.UINT16:
  926. data = new Uint16Array(buffer.length >> 1);
  927. for (let i = 0; i < data.length; i++) {
  928. data[i] = view.getUint16(i << 1, true);
  929. }
  930. break;
  931. case onnx.DataType.INT32:
  932. data = new Int32Array(buffer.length >> 2);
  933. for (let i = 0; i < data.length; i++) {
  934. data[i] = view.getInt32(i << 2, true);
  935. }
  936. break;
  937. case onnx.DataType.UINT32:
  938. data = new Uint32Array(buffer.length >> 2);
  939. for (let i = 0; i < data.length; i++) {
  940. data[i] = view.getUint32(i << 2, true);
  941. }
  942. break;
  943. case onnx.DataType.INT64:
  944. data = new Array(buffer.length >> 3);
  945. for (let i = 0; i < data.length; i++) {
  946. data[i] = view.getInt64(i << 3, true);
  947. }
  948. break;
  949. case onnx.DataType.UINT64:
  950. data = new Array(buffer.length >> 3);
  951. for (let i = 0; i < data.length; i++) {
  952. data[i] = view.getUint64(i << 3, true);
  953. }
  954. break;
  955. case onnx.DataType.BFLOAT16:
  956. data = new Array(buffer.length >> 1);
  957. for (let i = 0; i < data.length; i++) {
  958. data[i] = view.getBfloat16(i << 1, true);
  959. }
  960. break;
  961. case onnx.DataType.COMPLEX64:
  962. data = new Array(buffer.length >> 3);
  963. for (let i = 0; i < data.length; i++) {
  964. data[i] = view.getComplex64(i << 3, true);
  965. }
  966. break;
  967. case onnx.DataType.COMPLEX128:
  968. data = new Array(buffer.length >> 4);
  969. for (let i = 0; i < data.length; i++) {
  970. data[i] = view.getComplex64(i << 4, true);
  971. }
  972. break;
  973. default:
  974. throw new onnx.Error("Unsupported tensor data type '" + type + "'.");
  975. }
  976. return data;
  977. };
  978. this._values = decode(this._values);
  979. if (!this._values) {
  980. context.state = 'Tensor data is empty.';
  981. return context;
  982. }
  983. this._indices = decode(this._indices);
  984. context.values = this._values;
  985. context.indices = this._indices;
  986. context.index = 0;
  987. context.dataType = this.type.dataType;
  988. context.shape = this.type.shape.dimensions;
  989. context.data = function() {
  990. if (!this._data) {
  991. if (this.indices && this.values && this.indices.length === this.values.length) {
  992. const size = context.shape.reduce((a, b) => a * b, 1);
  993. const indices = this.indices;
  994. const values = this.values;
  995. const array = new values.constructor(size);
  996. switch (this.dataType) {
  997. case 'boolean':
  998. array.fill(false);
  999. break;
  1000. case 'int64':
  1001. case 'uint64':
  1002. break;
  1003. default:
  1004. break;
  1005. }
  1006. if (indices.length > 0) {
  1007. if (Object.prototype.hasOwnProperty.call(indices[0], 'low')) {
  1008. for (let i = 0; i < indices.length; i++) {
  1009. const index = indices[i];
  1010. array[index.high === 0 ? index.low : index.toNumber()] = values[i];
  1011. }
  1012. }
  1013. else {
  1014. for (let i = 0; i < indices.length; i++) {
  1015. array[indices[i]] = values[i];
  1016. }
  1017. }
  1018. }
  1019. this._data = array;
  1020. }
  1021. else {
  1022. this._data = this.values;
  1023. }
  1024. }
  1025. return this._data;
  1026. };
  1027. return context;
  1028. }
  1029. _decode(context, dimension) {
  1030. const shape = context.shape.length !== 0 ? context.shape : [ 1 ];
  1031. const results = [];
  1032. const size = shape[dimension];
  1033. const data = context.data();
  1034. if (dimension == shape.length - 1) {
  1035. for (let i = 0; i < size; i++) {
  1036. if (context.index > context.limit) {
  1037. results.push('...');
  1038. return results;
  1039. }
  1040. results.push(data[context.index++]);
  1041. }
  1042. }
  1043. else {
  1044. for (let j = 0; j < size; j++) {
  1045. if (context.index > context.limit) {
  1046. results.push('...');
  1047. return results;
  1048. }
  1049. results.push(this._decode(context, dimension + 1));
  1050. }
  1051. }
  1052. if (context.shape.length == 0) {
  1053. return results[0];
  1054. }
  1055. return results;
  1056. }
  1057. static _stringify(value, indentation, indent) {
  1058. if (Array.isArray(value)) {
  1059. const result = [];
  1060. result.push(indentation + '[');
  1061. const items = value.map((item) => onnx.Tensor._stringify(item, indentation + indent, indent));
  1062. if (items.length > 0) {
  1063. result.push(items.join(',\n'));
  1064. }
  1065. result.push(indentation + ']');
  1066. return result.join('\n');
  1067. }
  1068. switch (typeof value) {
  1069. case 'string':
  1070. return indentation + value;
  1071. case 'number':
  1072. if (value == Infinity) {
  1073. return indentation + 'Infinity';
  1074. }
  1075. if (value == -Infinity) {
  1076. return indentation + '-Infinity';
  1077. }
  1078. if (isNaN(value)) {
  1079. return indentation + 'NaN';
  1080. }
  1081. return indentation + value.toString();
  1082. default:
  1083. if (value && value.toString) {
  1084. return indentation + value.toString();
  1085. }
  1086. return indentation + '(undefined)';
  1087. }
  1088. }
  1089. };
  1090. onnx.TensorType = class {
  1091. constructor(dataType, shape, denotation) {
  1092. this._dataType = dataType;
  1093. this._shape = shape;
  1094. this._denotation = denotation || null;
  1095. }
  1096. get dataType() {
  1097. return this._dataType;
  1098. }
  1099. get shape() {
  1100. return this._shape;
  1101. }
  1102. get denotation() {
  1103. return this._denotation;
  1104. }
  1105. toString() {
  1106. return this.dataType + this._shape.toString();
  1107. }
  1108. };
  1109. onnx.TensorShape = class {
  1110. constructor(dimensions) {
  1111. this._dimensions = dimensions;
  1112. }
  1113. get dimensions() {
  1114. return this._dimensions;
  1115. }
  1116. toString() {
  1117. if (!this._dimensions || this._dimensions.length == 0) {
  1118. return '';
  1119. }
  1120. return '[' + this._dimensions.map((dim) => dim ? dim.toString() : '?').join(',') + ']';
  1121. }
  1122. };
  1123. onnx.SequenceType = class {
  1124. constructor(elementType, denotation) {
  1125. this._elementType = elementType;
  1126. this._denotation = denotation;
  1127. }
  1128. get elementType() {
  1129. return this._elementType;
  1130. }
  1131. get dennotation() {
  1132. return this._dennotation;
  1133. }
  1134. toString() {
  1135. return 'sequence<' + this._elementType.toString() + '>';
  1136. }
  1137. };
  1138. onnx.MapType = class {
  1139. constructor(keyType, valueType, denotation) {
  1140. this._keyType = keyType;
  1141. this._valueType = valueType;
  1142. this._denotation = denotation;
  1143. }
  1144. get keyType() {
  1145. return this._keyType;
  1146. }
  1147. get valueType() {
  1148. return this._valueType;
  1149. }
  1150. get denotation() {
  1151. return this._denotation;
  1152. }
  1153. toString() {
  1154. return 'map<' + this._keyType + ',' + this._valueType.toString() + '>';
  1155. }
  1156. };
  1157. onnx.OpaqueType = class {
  1158. constructor(domain, name) {
  1159. this._domain = domain;
  1160. this._name = name;
  1161. }
  1162. toString() {
  1163. const name = (this._domain ? (this._domain + '.') : '') + this._name;
  1164. return 'opaque<' + name + '>';
  1165. }
  1166. };
  1167. onnx.OptionalType = class {
  1168. constructor(type) {
  1169. this._type = type;
  1170. }
  1171. get type() {
  1172. return this._type;
  1173. }
  1174. toString() {
  1175. return 'optional<' + this._type.toString() + '>';
  1176. }
  1177. };
  1178. onnx.Function = class {
  1179. constructor(context, func) {
  1180. this._name = func.name;
  1181. this._domain = func.domain;
  1182. this._description = func.doc_string;
  1183. this._inputs = [];
  1184. this._outputs = [];
  1185. this._attributes = func.attribute.map((attribtue) => { return { name: attribtue }; });
  1186. context = new onnx.GraphContext(context, func.node);
  1187. func.input = func.input.map((input) => context.tensor(input));
  1188. func.output = func.output.map((output) => context.tensor(output));
  1189. context.push(func.node, func.input, func.output);
  1190. this._nodes = context.pop();
  1191. for (const input of func.input) {
  1192. const argument = context.argument(input.name);
  1193. if (!argument.initializer) {
  1194. this._inputs.push(new onnx.Parameter(input.name, [ argument ]));
  1195. }
  1196. }
  1197. for (const output of func.output) {
  1198. const argument = context.argument(output.name);
  1199. if (!argument.initializer) {
  1200. this._outputs.push(new onnx.Parameter(output.name, [ argument ]));
  1201. }
  1202. }
  1203. }
  1204. get type() {
  1205. return 'function';
  1206. }
  1207. get name() {
  1208. return this._name;
  1209. }
  1210. get module() {
  1211. return this._domain;
  1212. }
  1213. get description() {
  1214. return this._description;
  1215. }
  1216. get inputs() {
  1217. return this._inputs;
  1218. }
  1219. get outputs() {
  1220. return this._outputs;
  1221. }
  1222. get attributes() {
  1223. return this._attributes;
  1224. }
  1225. get nodes() {
  1226. return this._nodes;
  1227. }
  1228. };
  1229. onnx.GraphMetadata = class {
  1230. constructor(metadata, imports) {
  1231. this._metadata = metadata;
  1232. this._imports = imports;
  1233. this._cache = new Map();
  1234. this._attributes = new Map();
  1235. this._functions = new Map();
  1236. }
  1237. add(func) {
  1238. if (!this._functions.has(func.module)) {
  1239. this._functions.set(func.module, new Map());
  1240. }
  1241. const map = this._functions.get(func.module);
  1242. if (map.has(func.name)) {
  1243. throw new onnx.Error("Duplicate function identifier '" + func.module + '.' + func.name + "'.");
  1244. }
  1245. map.set(func.name, func);
  1246. }
  1247. type(name, domain) {
  1248. domain = domain || 'ai.onnx';
  1249. const key = domain + ':' + name;
  1250. if (!this._cache.has(key)) {
  1251. let value = this._metadata.type(name, domain, this._imports);
  1252. if (!value) {
  1253. if (this._functions.has(domain)) {
  1254. const map = this._functions.get(domain);
  1255. if (map.has(name)) {
  1256. value = map.get(name);
  1257. }
  1258. }
  1259. }
  1260. this._cache.set(key, value);
  1261. }
  1262. return this._cache.get(key);
  1263. }
  1264. attribute(type, domain, name) {
  1265. const key = domain + ':' + type + ':' + name;
  1266. if (!this._attributes.has(key)) {
  1267. this._attributes.set(key, null);
  1268. const metadata = this.type(type, domain);
  1269. if (metadata && metadata.attributes && metadata.attributes.length > 0) {
  1270. for (const attribute of metadata.attributes) {
  1271. this._attributes.set(key, attribute);
  1272. }
  1273. }
  1274. }
  1275. return this._attributes.get(key);
  1276. }
  1277. };
  1278. onnx.Metadata = class {
  1279. static open(context) {
  1280. if (onnx.Metadata._metadata) {
  1281. return Promise.resolve(onnx.Metadata._metadata);
  1282. }
  1283. return context.request('onnx-metadata.json', 'utf-8', null).then((data) => {
  1284. onnx.Metadata._metadata = new onnx.Metadata(data);
  1285. return onnx.Metadata._metadata;
  1286. }).catch(() => {
  1287. onnx.Metadata._metadata = new onnx.Metadata(null);
  1288. return onnx.Metadata._metadata;
  1289. });
  1290. }
  1291. constructor(data) {
  1292. this._map = new Map();
  1293. if (data) {
  1294. const metadata = JSON.parse(data);
  1295. for (const item of metadata) {
  1296. if (!this._map.has(item.module)) {
  1297. this._map.set(item.module, new Map());
  1298. }
  1299. const map = this._map.get(item.module);
  1300. if (!map.has(item.name)) {
  1301. map.set(item.name, []);
  1302. }
  1303. map.get(item.name).push(item);
  1304. }
  1305. }
  1306. }
  1307. type(name, domain, imports) {
  1308. domain = domain || 'ai.onnx';
  1309. let current = null;
  1310. if (this._map.has(domain)) {
  1311. const map = this._map.get(domain);
  1312. if (map.has(name)) {
  1313. for (const metadata of map.get(name)) {
  1314. const matchVersion = current ? current.version : -1;
  1315. const importVersion = imports.get(metadata.module) || 0;
  1316. if (importVersion >= metadata.version && matchVersion < metadata.version) {
  1317. current = metadata;
  1318. }
  1319. }
  1320. }
  1321. }
  1322. return current;
  1323. }
  1324. };
  1325. onnx.Inference = class {
  1326. constructor(nodes, outputs) {
  1327. this._outputs = new Map();
  1328. for (const node of nodes) {
  1329. for (const output of node.output) {
  1330. this._outputs.set(output.name, node);
  1331. }
  1332. }
  1333. for (const output of outputs) {
  1334. this._infer(output.name);
  1335. }
  1336. }
  1337. _infer(output) {
  1338. if (this._outputs.has(output)) {
  1339. let hasInputShapes = true;
  1340. const node = this._outputs.get(output);
  1341. for (const input of node.input) {
  1342. if (!input.type) {
  1343. this._infer(input);
  1344. if (!input.type) {
  1345. hasInputShapes = false;
  1346. break;
  1347. }
  1348. }
  1349. }
  1350. if (hasInputShapes) {
  1351. // continue
  1352. }
  1353. }
  1354. }
  1355. };
  1356. onnx.DataLocation = {
  1357. DEFAULT: 0,
  1358. EXTERNAL: 1
  1359. };
  1360. onnx.DataType = {
  1361. UNDEFINED: 0,
  1362. FLOAT: 1,
  1363. UINT8: 2,
  1364. INT8: 3,
  1365. UINT16: 4,
  1366. INT16: 5,
  1367. INT32: 6,
  1368. INT64: 7,
  1369. STRING: 8,
  1370. BOOL: 9,
  1371. FLOAT16: 10,
  1372. DOUBLE: 11,
  1373. UINT32: 12,
  1374. UINT64: 13,
  1375. COMPLEX64: 14,
  1376. COMPLEX128: 15,
  1377. BFLOAT16: 16
  1378. };
  1379. onnx.AttributeType = {
  1380. UNDEFINED: 0,
  1381. FLOAT: 1,
  1382. INT: 2,
  1383. STRING: 3,
  1384. TENSOR: 4,
  1385. GRAPH: 5,
  1386. FLOATS: 6,
  1387. INTS: 7,
  1388. STRINGS: 8,
  1389. TENSORS: 9,
  1390. GRAPHS: 10,
  1391. SPARSE_TENSOR: 11,
  1392. SPARSE_TENSORS: 12,
  1393. TYPE_PROTO: 13,
  1394. TYPE_PROTOS: 14
  1395. };
  1396. onnx.ModelContext = class {
  1397. constructor(metadata, imageFormat) {
  1398. this._metadata = metadata;
  1399. this._imageFormat = imageFormat;
  1400. this._graphs = new Map();
  1401. }
  1402. get metadata() {
  1403. return this._metadata;
  1404. }
  1405. get imageFormat() {
  1406. return this._imageFormat;
  1407. }
  1408. graph(value) {
  1409. if (!this._graphs.has(value)) {
  1410. this._graphs.set(value, new onnx.Graph(this, value));
  1411. }
  1412. return this._graphs.get(value);
  1413. }
  1414. };
  1415. onnx.GraphContext = class {
  1416. constructor(context, nodes) {
  1417. this._context = context;
  1418. this._dataTypes = new Map(Object.entries(onnx.DataType).map((entry) => [ entry[1], entry[0].toLowerCase() ]));
  1419. this._dataTypes.set(onnx.DataType.UNDEFINED, 'UNDEFINED');
  1420. this._dataTypes.set(onnx.DataType.BOOL, 'boolean');
  1421. this._dataTypes.set(onnx.DataType.FLOAT, 'float32');
  1422. this._dataTypes.set(onnx.DataType.DOUBLE, 'float64');
  1423. this._tensors = new Map();
  1424. this._arguments = new Map();
  1425. this._groups = new Map();
  1426. this._nodes = [];
  1427. for (const node of nodes) {
  1428. node.input = node.input.map((name) => this.tensor(name));
  1429. node.output = node.output.map((name) => this.tensor(name));
  1430. node.param = {};
  1431. for (const attribute of node.attribute) {
  1432. if (attribute.type) {
  1433. continue;
  1434. }
  1435. if (attribute.ints && attribute.ints.length > 0) {
  1436. attribute.type = onnx.AttributeType.INTS;
  1437. }
  1438. else if (attribute.floats && attribute.floats.length > 0) {
  1439. attribute.type = onnx.AttributeType.FLOATS;
  1440. }
  1441. else if (attribute.strings && attribute.strings.length > 0) {
  1442. attribute.type = onnx.AttributeType.STRINGS;
  1443. }
  1444. else if (attribute.graphs && attribute.graphs.length > 0) {
  1445. attribute.type = onnx.AttributeType.GRAPHS;
  1446. }
  1447. else if (attribute.s && attribute.s.length > 0) {
  1448. attribute.type = onnx.AttributeType.STRING;
  1449. }
  1450. else if (Object.prototype.hasOwnProperty.call(attribute, 'f')) {
  1451. attribute.type = onnx.AttributeType.FLOAT;
  1452. }
  1453. else if (Object.prototype.hasOwnProperty.call(attribute, 'i')) {
  1454. attribute.type = onnx.AttributeType.INT;
  1455. }
  1456. else if (Object.prototype.hasOwnProperty.call(attribute, 't')) {
  1457. attribute.type = onnx.AttributeType.TENSOR;
  1458. }
  1459. else if (Object.prototype.hasOwnProperty.call(attribute, 'g')) {
  1460. attribute.type = onnx.AttributeType.GRAPH;
  1461. }
  1462. else if (Object.prototype.hasOwnProperty.call(attribute, 'sparse_tensor')) {
  1463. attribute.type =onnx.AttributeType.SPARSE_TENSOR;
  1464. }
  1465. else {
  1466. attribute.type = onnx.AttributeType.UNDEFINED;
  1467. }
  1468. }
  1469. }
  1470. }
  1471. get metadata() {
  1472. return this._context.metadata;
  1473. }
  1474. graph(name) {
  1475. return this._context.graph(name);
  1476. }
  1477. tensor(name) {
  1478. if (!this._tensors.has(name)) {
  1479. this._tensors.set(name, { name: name });
  1480. }
  1481. return this._tensors.get(name);
  1482. }
  1483. group(name) {
  1484. if (!this._groups.has(name)) {
  1485. const path = name.split('/');
  1486. if (path.length > 1) {
  1487. path.pop();
  1488. return this.group(path.join('/'));
  1489. }
  1490. this._groups.set(name, new Map([ [ '', [] ]]));
  1491. }
  1492. return this._groups.get(name);
  1493. }
  1494. argument(name) {
  1495. if (!this._arguments.has(name)) {
  1496. const tensor = this.tensor(name);
  1497. const type = tensor.initializer ? tensor.initializer.type : tensor.type || null;
  1498. this._arguments.set(name, new onnx.Argument(name, type, tensor.initializer, tensor.annotation, tensor.description));
  1499. }
  1500. return this._arguments.get(name);
  1501. }
  1502. createType(type) {
  1503. if (!type) {
  1504. return null;
  1505. }
  1506. let denotation = '';
  1507. switch (type.denotation) {
  1508. case undefined:
  1509. case null:
  1510. case '':
  1511. break;
  1512. case 'TENSOR':
  1513. denotation = 'Tensor';
  1514. break;
  1515. case 'IMAGE':
  1516. denotation = 'Image' + (this._context.imageFormat ? '(' + this._context.imageFormat.join(',') + ')' : '');
  1517. break;
  1518. case 'AUDIO':
  1519. denotation = 'Audio';
  1520. break;
  1521. case 'TEXT':
  1522. denotation = 'Text';
  1523. break;
  1524. default:
  1525. throw new onnx.Error("Unsuppored tensor type denotation '" + type.denotation + "'.");
  1526. }
  1527. if (type.tensor_type) {
  1528. const tensor_type = type.tensor_type;
  1529. 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) : [];
  1530. return this.createTensorType(tensor_type.elem_type, shape, denotation);
  1531. }
  1532. else if (type.sparse_tensor_type) {
  1533. const tensor_type = type.sparse_tensor_type;
  1534. 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) : [];
  1535. return this.createTensorType(tensor_type.elem_type, shape, denotation);
  1536. }
  1537. else if (type.map_type) {
  1538. return this.createMapType(type.map_type.key_type, this.createType(type.map_type.value_type), denotation);
  1539. }
  1540. else if (type.sequence_type) {
  1541. return new onnx.SequenceType(this.createType(type.sequence_type.elem_type), denotation);
  1542. }
  1543. else if (type.opaque_type) {
  1544. return new onnx.OpaqueType(type.opaque_type.domain, type.opaque_type.name);
  1545. }
  1546. else if (type.optional_type) {
  1547. return new onnx.OptionalType(this.createType(type.optional_type.elem_type), denotation);
  1548. }
  1549. throw new onnx.Error("Unsupported tensor type '" + JSON.stringify(type) + "'.");
  1550. }
  1551. createTensorType(dataType, shape, denotation) {
  1552. dataType = this.createDataType(dataType);
  1553. return new onnx.TensorType(dataType, new onnx.TensorShape(shape), denotation);
  1554. }
  1555. createMapType(keyType, valueType, denotation) {
  1556. keyType = this.createDataType(keyType);
  1557. return new onnx.MapType(keyType, valueType, denotation);
  1558. }
  1559. createDataType(value) {
  1560. return this._dataTypes.has(value) ? this._dataTypes.get(value) : this._dataTypes.get(onnx.DataType.UNDEFINED);
  1561. }
  1562. createLocation(value) {
  1563. switch (value) {
  1564. case onnx.DataLocation.DEFAULT: return 'default';
  1565. case onnx.DataLocation.EXTERNAL: return 'external';
  1566. default: return 'UNDEFINED';
  1567. }
  1568. }
  1569. decodeText(value) {
  1570. if (typeof value === 'string') {
  1571. return value;
  1572. }
  1573. this._decoder = this._decoder || new TextDecoder('utf-8');
  1574. return this._decoder.decode(value);
  1575. }
  1576. push(nodes, inputs, outputs) {
  1577. const inputMap = new Map();
  1578. const outputMap = new Map();
  1579. for (const node of nodes) {
  1580. node.input.every((input) => inputMap.set(input.name, (inputMap.get(input) || 0) + 1));
  1581. node.output.every((output) => outputMap.set(output.name, (outputMap.get(output) || 0) + 1));
  1582. }
  1583. inputs.every((input) => inputMap.delete(input.name));
  1584. outputs.every((output) => outputMap.delete(output.name));
  1585. nodes = nodes.filter((node) => {
  1586. const constant = node &&
  1587. node.op_type === 'Constant' &&
  1588. node.attribute.length === 1 && node.attribute[0] &&
  1589. node.input.length === 0 &&
  1590. node.output.length === 1 && node.output[0] && inputMap.get(node.output[0].name) === 1 && outputMap.get(node.output[0].name) === 1;
  1591. const attribute = constant ? node.attribute[0] : null;
  1592. if (attribute && attribute.name === 'value' && attribute.type === onnx.AttributeType.TENSOR && attribute.t) {
  1593. const tensor = this.tensor(node.output[0].name);
  1594. tensor.initializer = new onnx.Tensor(this, attribute.t, 'Constant');
  1595. return false;
  1596. }
  1597. else if (attribute && attribute.name === 'sparse_value' && attribute.type === onnx.AttributeType.SPARSE_TENSOR && attribute.sparse_tensor) {
  1598. const tensor = this.tensor(node.output[0].name);
  1599. tensor.initializer = new onnx.Tensor(this, attribute.sparse_tensor, 'Sparse Constant');
  1600. return false;
  1601. }
  1602. return true;
  1603. });
  1604. for (let node of nodes) {
  1605. const schema = this._context.metadata.type(node.op_type, node.domain);
  1606. const inputs = [];
  1607. node.input = node.input || [];
  1608. for (let i = 0; i < node.input.length; ) {
  1609. const input = schema && schema.inputs && i < schema.inputs.length ? schema.inputs[i] : { name: i.toString() };
  1610. const count = input.list ? node.input.length - i : 1;
  1611. const list = node.input.slice(i, i + count).map((input) => this.argument(input.name));
  1612. inputs.push(new onnx.Parameter(input.name, list));
  1613. i += count;
  1614. }
  1615. const outputs = [];
  1616. node.output = node.output || [];
  1617. for (let i = 0; i < node.output.length; ) {
  1618. const output = schema && schema.outputs && i < schema.outputs.length ? schema.outputs[i] : { name: i.toString() };
  1619. const count = output.list ? node.output.length - i : 1;
  1620. const list = node.output.slice(i, i + count).map((output) => this.argument(output.name));
  1621. outputs.push(new onnx.Parameter(output.name, list));
  1622. i += count;
  1623. }
  1624. node = new onnx.Node(this, node.op_type, node.domain, node.name, node.doc_string, node.attribute, inputs, outputs);
  1625. this._nodes.push(node);
  1626. // const path = (node.name || '').split('/');
  1627. // path.pop();
  1628. // this.group(path.join('/')).get('').push(node);
  1629. }
  1630. }
  1631. pop() {
  1632. /*
  1633. const nodes = [];
  1634. for (const entry of this._groups) {
  1635. if (entry[0] === '') {
  1636. for (const node of entry[1].get('')) {
  1637. nodes.push(node);
  1638. }
  1639. continue;
  1640. }
  1641. nodes.push(new onnx.Group(entry[0], entry[1]));
  1642. }
  1643. return nodes;
  1644. */
  1645. return this._nodes;
  1646. }
  1647. };
  1648. onnx.Runtime = {};
  1649. onnx.Runtime.Reader = class {
  1650. static open(stream, extension) {
  1651. if (stream.length >= 8) {
  1652. const buffer = stream.peek(Math.min(32, stream.length));
  1653. const reader = flatbuffers.BinaryReader.open(buffer);
  1654. const identifier = reader.identifier;
  1655. if (identifier === 'ORTM') {
  1656. return new onnx.Runtime.Reader(stream);
  1657. }
  1658. if (extension === 'ort') {
  1659. const signature = [ 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ];
  1660. if (signature.length <= stream.length && stream.peek(signature.length).every((value, index) => value === signature[index])) {
  1661. return new onnx.Runtime.Reader(stream);
  1662. }
  1663. }
  1664. }
  1665. return null;
  1666. }
  1667. constructor(stream) {
  1668. this._stream = stream;
  1669. }
  1670. read() {
  1671. this._graphs = new Set();
  1672. const reader = flatbuffers.BinaryReader.open(this._stream);
  1673. const session = onnx.schema.InferenceSession.create(reader);
  1674. const model = session.model;
  1675. const graph = model.graph;
  1676. graph.doc_string = model.graph_doc_string;
  1677. delete model.graph_doc_string;
  1678. this._graph(graph);
  1679. return model;
  1680. }
  1681. _graph(graph) {
  1682. if (this._graphs.has(graph)) {
  1683. return;
  1684. }
  1685. this._graphs.add(graph);
  1686. graph.name = this._graphs.size.toString();
  1687. graph.node = graph.nodes.map((node) => {
  1688. this._node(node);
  1689. return node;
  1690. });
  1691. delete graph.nodes;
  1692. graph.value_info = graph.node_args.map((valueInfo) => {
  1693. return {
  1694. name: valueInfo.name,
  1695. doc_string: valueInfo.doc_string,
  1696. type: this._type(valueInfo.type)
  1697. };
  1698. });
  1699. delete graph.node_args;
  1700. const value_info = new Map(graph.value_info.map((entry) => [ entry.name, entry ]));
  1701. graph.input = graph.inputs.map((input) => {
  1702. return value_info.has(input) ? value_info.get(input) : { name: input };
  1703. });
  1704. delete graph.inputs;
  1705. graph.output = graph.outputs.map((output) => {
  1706. return value_info.has(output) ? value_info.get(output) : { name: output };
  1707. });
  1708. delete graph.outputs;
  1709. graph.initializer = graph.initializers.map((tensor) => {
  1710. tensor.data_location = onnx.DataLocation.DEFAULT;
  1711. return tensor;
  1712. });
  1713. delete graph.initializers;
  1714. graph.sparse_initializer = graph.sparse_initializers.map((tensor) => {
  1715. tensor.values.data_location = onnx.DataLocation.DEFAULT;
  1716. tensor.indices.data_location = onnx.DataLocation.DEFAULT;
  1717. return tensor;
  1718. });
  1719. delete graph.sparse_initializers;
  1720. }
  1721. _node(node) {
  1722. node.input = node.inputs;
  1723. node.output = node.outputs;
  1724. node.attribute = node.attributes.map((attribute) => {
  1725. const type = attribute.type;
  1726. if (type === onnx.AttributeType.GRAPH) {
  1727. this._graph(attribute.g);
  1728. }
  1729. else if (type === onnx.AttributeType.GRAPHS) {
  1730. for (const graph of attribute.graphs) {
  1731. this._graph(graph);
  1732. }
  1733. }
  1734. else if (type === onnx.AttributeType.TYPE_PROTO) {
  1735. attribute.tp = this._type(attribute.tp);
  1736. }
  1737. else if (type === onnx.AttributeType.TYPE_PROTOS) {
  1738. attribute.type_protos = attribute.type_protos.map((type) => this._type(type));
  1739. }
  1740. return attribute;
  1741. });
  1742. delete node.inputs;
  1743. delete node.outputs;
  1744. delete node.attributes;
  1745. }
  1746. _type(type) {
  1747. if (type) {
  1748. const value = type.value;
  1749. if (value && value instanceof onnx.schema.TensorTypeAndShape) {
  1750. return {
  1751. tensor_type: { elem_type: value.elem_type, shape: this._shape(value.shape) },
  1752. denotation: value.denotation
  1753. };
  1754. }
  1755. if (value && value instanceof onnx.schema.SequenceType) {
  1756. return {
  1757. sequence_type: { elem_type: this._type(value.elem_type) },
  1758. denotation: value.denotation
  1759. };
  1760. }
  1761. if (value && value instanceof onnx.schema.MapType) {
  1762. return {
  1763. map_type: { key_type: value.key_type, value_type: this._type(value.value_type) },
  1764. denotation: value.denotation
  1765. };
  1766. }
  1767. throw new onnx.Error("Unsupported type value '" + JSON.stringify(type.value));
  1768. }
  1769. return null;
  1770. }
  1771. _shape(shape) {
  1772. if (shape && shape.dim && Array.isArray(shape.dim)) {
  1773. const dimensions = shape.dim.map((dim) => {
  1774. switch (dim.value.dim_type) {
  1775. case 0:
  1776. return {};
  1777. case 1:
  1778. return { dim_value: dim.value.dim_value, denotation: dim.denotation };
  1779. case 2:
  1780. return { dim_param: dim.value.dim_param, denotation: dim.denotation };
  1781. default:
  1782. throw new onnx.Error("Unknown shape dimension '" + JSON.stringify(dim.value) + "'.");
  1783. }
  1784. });
  1785. return { dim: dimensions };
  1786. }
  1787. return shape;
  1788. }
  1789. };
  1790. onnx.Text = {};
  1791. onnx.Text.Reader = class {
  1792. static open(stream) {
  1793. try {
  1794. if (stream.length > 0 && stream.peek(1)[0] < 0x80 || stream.peek(1)[0] >= 0xFE) {
  1795. const reader = text.Reader.open(stream);
  1796. const lines = [];
  1797. for (let i = 0; i < 32; i++) {
  1798. const line = reader.read();
  1799. if (line === undefined) {
  1800. break;
  1801. }
  1802. lines.push(line);
  1803. }
  1804. const content = lines.join('\n');
  1805. if (/^\s*<\s*ir_version\s*:/m.exec(content) ||
  1806. /^\s*[a-zA-Z][a-zA-Z0-9]*\s*\(.*\)\s=>\s\(/m.exec(content)) {
  1807. return new onnx.Text.Reader(stream);
  1808. }
  1809. }
  1810. }
  1811. catch (err) {
  1812. // continue regardless of error
  1813. }
  1814. return null;
  1815. }
  1816. constructor(stream) {
  1817. this._stream = stream;
  1818. this._dataTypes = new Map([
  1819. [ 'float', 1 ], [ 'uint8', 2 ], [ 'int8', 3 ], [ 'uint16', 4 ],
  1820. [ 'int16', 5 ], [ 'int32', 6 ], [ 'int64', 7 ], [ 'string', 8 ],
  1821. [ 'bool', 9 ], [ 'float16', 10 ], [ 'double', 11 ], [ 'uint32', 12 ],
  1822. [ 'uint64', 13 ], [ 'complex64', 14 ], [ 'complex128', 15 ], [ 'bfloat16', 16 ]
  1823. ]);
  1824. this._attributeTypes = new Map([
  1825. [ 'float', 1 ], [ 'int', 2 ], [ 'string', 3 ],
  1826. [ 'tensor', 4 ], [ 'graph', 5 ], [ 'sparse_tensor', 11 ], [ 'type_proto', 13 ],
  1827. [ 'floats', 6 ], [ 'ints', 7 ], [ 'strings', 8 ],
  1828. [ 'tensors', 9 ], [ 'graphs', 10 ], [ 'sparse_tensors', 12 ], [ 'type_protos', 14 ]
  1829. ]);
  1830. }
  1831. read() {
  1832. const decoder = text.Decoder.open(this._stream);
  1833. this._decoder = decoder;
  1834. this._position = 0;
  1835. this._char = decoder.decode();
  1836. return this._model();
  1837. }
  1838. _seek(position) {
  1839. this._decoder.position = position;
  1840. this._char = '';
  1841. this._next();
  1842. }
  1843. _model() {
  1844. this._whitespace();
  1845. const model = new onnx.proto.ModelProto();
  1846. if (this._match('<')) {
  1847. do {
  1848. const keyword = this._identifier();
  1849. this._expect(':');
  1850. switch (keyword) {
  1851. case 'ir_version':
  1852. case 'model_version':
  1853. model[keyword] = this._integer();
  1854. break;
  1855. case 'opset_import':
  1856. model[keyword] = this._operatorSetId();
  1857. break;
  1858. case 'producer_name':
  1859. case 'producer_version':
  1860. case 'domain':
  1861. case 'doc_string':
  1862. model[keyword] = this._string();
  1863. break;
  1864. case 'metadata_props':
  1865. this._expect('[');
  1866. if (!this._match(']')) {
  1867. do {
  1868. const entry = new onnx.proto.StringStringEntryProto();
  1869. entry.key = this._string();
  1870. this._expect(':');
  1871. entry.value = this._string();
  1872. model.metadata_props.push(entry);
  1873. } while (this._match(','));
  1874. this._expect(']');
  1875. }
  1876. break;
  1877. default:
  1878. this._throw("Unknown keyword '" + keyword + "'.");
  1879. break;
  1880. }
  1881. } while (this._match(','));
  1882. this._expect('>');
  1883. }
  1884. model.graph = this._graph();
  1885. this._whitespace();
  1886. while (this._char !== undefined) {
  1887. const func = this._function();
  1888. if (func) {
  1889. model.functions.push(func);
  1890. }
  1891. this._whitespace();
  1892. }
  1893. return model;
  1894. }
  1895. _graph() {
  1896. const graph = new onnx.proto.GraphProto();
  1897. graph.name = this._identifier();
  1898. if (this._match('(')) {
  1899. if (!this._match(')')) {
  1900. do {
  1901. const valueInfo = this._valueInfo();
  1902. if (this._match('=')) {
  1903. const tensor = this._tensor(valueInfo.type);
  1904. tensor.name = valueInfo.name;
  1905. graph.initializer.push(tensor);
  1906. }
  1907. graph.input.push(valueInfo);
  1908. }
  1909. while (this._match(','));
  1910. this._expect(')');
  1911. }
  1912. }
  1913. this._expect('=>');
  1914. graph.output = this._valueInfoList();
  1915. if (this._match('<')) {
  1916. if (!this._match('>')) {
  1917. do {
  1918. const valueInfo = this._valueInfo();
  1919. if (this._match('=')) {
  1920. const tensor = this._tensor(valueInfo.type);
  1921. tensor.name = valueInfo.name;
  1922. graph.initializer.push(tensor);
  1923. }
  1924. else {
  1925. graph.value_info.push(valueInfo);
  1926. }
  1927. }
  1928. while (this._match(','));
  1929. this._expect('>');
  1930. }
  1931. }
  1932. graph.node = this._nodeList();
  1933. return graph;
  1934. }
  1935. _nodeList() {
  1936. const list = [];
  1937. this._expect('{');
  1938. while (!this._match('}')) {
  1939. list.push(this._node());
  1940. }
  1941. return list;
  1942. }
  1943. _node() {
  1944. const node = new onnx.proto.NodeProto();
  1945. node.output = this._identifierList();
  1946. this._expect('=');
  1947. let identifier = this._identifier();
  1948. let domain = '';
  1949. while (this._match('.')) {
  1950. if (domain) {
  1951. domain += '.';
  1952. }
  1953. domain += identifier;
  1954. identifier = this._identifier();
  1955. }
  1956. node.domain = domain;
  1957. node.op_type = identifier;
  1958. node.attribute = this._attributeList();
  1959. this._expect('(');
  1960. node.input = this._identifierList();
  1961. this._expect(')');
  1962. if (!node.attribute || node.attribute.length === 0) {
  1963. node.attribute = this._attributeList();
  1964. }
  1965. return node;
  1966. }
  1967. _attributeList() {
  1968. const list = [];
  1969. if (this._match('<')) {
  1970. do {
  1971. list.push(this._attribute());
  1972. }
  1973. while (this._match(','));
  1974. this._expect('>');
  1975. }
  1976. return list;
  1977. }
  1978. _attribute() {
  1979. const attribute = new onnx.proto.AttributeProto();
  1980. attribute.name = this._identifier();
  1981. if (this._match(':')) {
  1982. const type = this._identifier();
  1983. if (!this._attributeTypes.has(type)) {
  1984. this._throw("Unexpected attribute type '" + type + "'.");
  1985. }
  1986. attribute.type = this._attributeTypes.get(type);
  1987. }
  1988. this._expect('=');
  1989. if (this._match('[')) {
  1990. const list = [];
  1991. do {
  1992. list.push(this._literal());
  1993. }
  1994. while (this._match(','));
  1995. this._expect(']');
  1996. if (list.every((value) => typeof value === 'string')) {
  1997. attribute.type = onnx.AttributeType.STRINGS;
  1998. attribute.strings = list;
  1999. }
  2000. else if (list.every((value) => typeof value === 'number' && Number.isInteger(value))) {
  2001. attribute.type = onnx.AttributeType.INTS;
  2002. attribute.ints = list;
  2003. }
  2004. else if (list.every((value) => typeof value === 'number')) {
  2005. attribute.type = onnx.AttributeType.FLOATS;
  2006. attribute.floats = list;
  2007. }
  2008. else {
  2009. this._throw("Unexpected value '" + JSON.stringify(list) + "'.");
  2010. }
  2011. }
  2012. else if ((this._char >= 'a' && this._char <= 'z') || (this._char >= 'A' && this._char <= 'Z') || this._char === '_') {
  2013. const identifier = this._identifier();
  2014. if (this._dataTypes.has(identifier)) {
  2015. attribute.type = onnx.AttributeType.TENSOR;
  2016. if (!this._dataTypes.has(identifier)) {
  2017. this._throw("Unexpected type '" + identifier + "'.");
  2018. }
  2019. const type = this._type(this._dataTypes.get(identifier));
  2020. if (!type.tensor_type.elem_type) {
  2021. this._throw('Expected tensor data type.');
  2022. }
  2023. if (!type.tensor_type.shape || !type.tensor_type.shape.dim) {
  2024. this._throw('Expected tensor shape.');
  2025. }
  2026. attribute.t = this._tensor(type);
  2027. }
  2028. else {
  2029. attribute.type = onnx.AttributeType.GRAPH;
  2030. attribute.g = this._graph();
  2031. }
  2032. }
  2033. else if (this._match('@')) {
  2034. attribute.ref_attr_name = this._identifier();
  2035. }
  2036. else {
  2037. const value = this._literal();
  2038. switch (typeof value) {
  2039. case 'number':
  2040. if (Number.isInteger(value)) {
  2041. attribute.type = onnx.AttributeType.INT;
  2042. attribute.i = value;
  2043. }
  2044. else {
  2045. attribute.type = onnx.AttributeType.FLOAT;
  2046. attribute.f = value;
  2047. }
  2048. break;
  2049. case 'string':
  2050. attribute.type = onnx.AttributeType.STRING;
  2051. attribute.s = value;
  2052. break;
  2053. default: {
  2054. this._throw("Unexpected value '" + JSON.stringify(value) + "'.");
  2055. }
  2056. }
  2057. }
  2058. return attribute;
  2059. }
  2060. _valueInfoList() {
  2061. const list = [];
  2062. this._expect('(');
  2063. if (!this._match(')')) {
  2064. do {
  2065. list.push(this._valueInfo());
  2066. } while (this._match(','));
  2067. this._expect(')');
  2068. }
  2069. return list;
  2070. }
  2071. _valueInfo() {
  2072. const valueInfo = new onnx.proto.ValueInfoProto();
  2073. let identifier = this._identifier();
  2074. if (this._dataTypes.has(identifier)) {
  2075. valueInfo.type = this._type(this._dataTypes.get(identifier));
  2076. identifier = this._identifier();
  2077. }
  2078. valueInfo.name = identifier;
  2079. return valueInfo;
  2080. }
  2081. _type(elem_type) {
  2082. const type = new onnx.proto.TypeProto();
  2083. type.tensor_type = new onnx.proto.TypeProto.Tensor();
  2084. type.tensor_type.elem_type = elem_type;
  2085. if (this._match('[')) {
  2086. if (!this._match(']')) {
  2087. type.tensor_type.shape = this._shape();
  2088. this._expect(']');
  2089. }
  2090. }
  2091. else {
  2092. type.tensor_type.shape = new onnx.proto.TensorShapeProto();
  2093. }
  2094. return type;
  2095. }
  2096. _shape() {
  2097. const shape = new onnx.proto.TensorShapeProto();
  2098. do {
  2099. const dimension = new onnx.proto.TensorShapeProto.Dimension();
  2100. if (!this._match('?')) {
  2101. const identifier = this._identifier(true);
  2102. if (identifier) {
  2103. dimension.dim_param = identifier;
  2104. }
  2105. else {
  2106. dimension.dim_value = this._integer();
  2107. }
  2108. }
  2109. shape.dim.push(dimension);
  2110. }
  2111. while (this._match(','));
  2112. return shape;
  2113. }
  2114. _tensor(type) {
  2115. const tensor = new onnx.proto.TensorProto();
  2116. if (!type.tensor_type || !type.tensor_type.elem_type) {
  2117. this._throw('Expected tensor type.');
  2118. }
  2119. if (!type.tensor_type.shape || !type.tensor_type.shape.dim || !type.tensor_type.shape.dim.every((dim) => dim.dim_value)) {
  2120. this._throw('Expected numeric tensor shape.');
  2121. }
  2122. const elem_type = type.tensor_type.elem_type;
  2123. tensor.data_type = elem_type;
  2124. tensor.dims = type.tensor_type.shape.dim.map((dim) => dim.dim_value);
  2125. this._match('=');
  2126. this._expect('{');
  2127. if (!this._match('}')) {
  2128. do {
  2129. switch (elem_type) {
  2130. case onnx.DataType.INT8:
  2131. case onnx.DataType.INT16:
  2132. case onnx.DataType.INT32:
  2133. case onnx.DataType.UINT8:
  2134. case onnx.DataType.UINT16:
  2135. case onnx.DataType.BOOL:
  2136. tensor.int32_data.push(this._integer());
  2137. break;
  2138. case onnx.DataType.INT64:
  2139. tensor.int64_data.push(this._integer());
  2140. break;
  2141. case onnx.DataType.UINT32:
  2142. case onnx.DataType.UINT64:
  2143. tensor.uint64_data.push(this._integer());
  2144. break;
  2145. case onnx.DataType.FLOAT:
  2146. tensor.float_data.push(this._float());
  2147. break;
  2148. case onnx.DataType.DOUBLE:
  2149. tensor.double_data.push(this._float());
  2150. break;
  2151. case onnx.DataType.STRING:
  2152. tensor.string_data.push(this.string());
  2153. break;
  2154. default:
  2155. return this._throw("Unsupported tensor element type '" + elem_type.toString() + "'.");
  2156. }
  2157. } while (this._match(','));
  2158. this._expect('}');
  2159. }
  2160. return tensor;
  2161. }
  2162. _function() {
  2163. const func = new onnx.proto.FunctionProto();
  2164. if (this._match('<')) {
  2165. do {
  2166. const keyword = this._identifier();
  2167. this._expect(':');
  2168. switch (keyword) {
  2169. case 'opset_import':
  2170. func[keyword] = this._operatorSetId();
  2171. break;
  2172. case 'domain':
  2173. case 'doc_string':
  2174. func[keyword] = this._string();
  2175. break;
  2176. default:
  2177. this._throw("Unknown keyword '" + keyword + "'.");
  2178. break;
  2179. }
  2180. }
  2181. while (this._match(','));
  2182. this._expect('>');
  2183. }
  2184. func.name = this._identifier();
  2185. if (this._match('<')) {
  2186. func.attribute = this._identifierList();
  2187. this._expect('>');
  2188. }
  2189. if (this._match('(')) {
  2190. func.input = this._identifierList();
  2191. this._expect(')');
  2192. }
  2193. this._expect('=>');
  2194. if (this._match('(')) {
  2195. func.output = this._identifierList();
  2196. this._expect(')');
  2197. }
  2198. func.node = this._nodeList();
  2199. return func;
  2200. }
  2201. _identifierList() {
  2202. const list = [];
  2203. const identifier = this._identifier(true);
  2204. if (identifier) {
  2205. list.push(identifier);
  2206. while (this._match(',')) {
  2207. list.push(this._identifier());
  2208. }
  2209. }
  2210. return list;
  2211. }
  2212. _identifier(optional) {
  2213. this._whitespace();
  2214. const value = [];
  2215. if ((this._char >= 'a' && this._char <= 'z') || (this._char >= 'A' && this._char <= 'Z')) {
  2216. value.push(this._char);
  2217. this._next();
  2218. while ((this._char >= 'a' && this._char <= 'z') || (this._char >= 'A' && this._char <= 'Z') || (this._char >= '0' && this._char <= '9') || this._char === '_') {
  2219. value.push(this._char);
  2220. this._next();
  2221. }
  2222. }
  2223. if (optional !== true && value.length == 0) {
  2224. this._throw('Identifier expected.');
  2225. }
  2226. return value.join('');
  2227. }
  2228. _literal() {
  2229. this._whitespace();
  2230. let decimal_point = false;
  2231. if (this._char === '"') {
  2232. const value = [];
  2233. this._next();
  2234. while (this._char !== undefined && this._char !== '"') {
  2235. value.push(this._char);
  2236. this._next();
  2237. }
  2238. if (this._char !== undefined) {
  2239. this._next();
  2240. }
  2241. return value.join('');
  2242. }
  2243. else if ((this._char >= '0' && this._char <= '9') || this._char === '-') {
  2244. const value = [ this._char ];
  2245. this._next();
  2246. while ((this._char >= '0' && this._char <= '9') || this._char === '.') {
  2247. if (this._char === '.') {
  2248. if (decimal_point) {
  2249. this._throw();
  2250. }
  2251. decimal_point = true;
  2252. }
  2253. value.push(this._char);
  2254. this._next();
  2255. }
  2256. if (value.length === 0) {
  2257. this._throw('Value expected.');
  2258. }
  2259. if (this._char === 'e' || this._char === 'E') {
  2260. decimal_point = true;
  2261. value.push(this._char);
  2262. this._next();
  2263. if (this._char === '+' || this._char === '-') {
  2264. value.push(this._char);
  2265. this._next();
  2266. }
  2267. while ((this._char >= '0' && this._char <= '9')) {
  2268. value.push(this._char);
  2269. this._next();
  2270. }
  2271. }
  2272. return decimal_point ? Number.parseFloat(value.join('')) : Number.parseInt(value.join(''), 10);
  2273. }
  2274. return undefined;
  2275. }
  2276. _integer() {
  2277. const value = this._literal();
  2278. if (!Number.isInteger(value)) {
  2279. this._throw('Integer value expected.');
  2280. }
  2281. return value;
  2282. }
  2283. _float() {
  2284. const value = this._literal();
  2285. if (typeof value !== 'number') {
  2286. this._throw('Float value expected.');
  2287. }
  2288. return value;
  2289. }
  2290. _string() {
  2291. const value = this._literal();
  2292. if (typeof value !== 'string') {
  2293. this._throw('String value expected.');
  2294. }
  2295. return value;
  2296. }
  2297. _operatorSetId() {
  2298. const list = [];
  2299. this._expect('[');
  2300. if (!this._match(']')) {
  2301. do {
  2302. const value = new onnx.proto.OperatorSetIdProto();
  2303. value.domain = this._string();
  2304. this._expect(':');
  2305. value.version = this._integer();
  2306. list.push(value);
  2307. }
  2308. while (this._match(','));
  2309. this._expect(']');
  2310. }
  2311. return list;
  2312. }
  2313. _match(value) {
  2314. this._whitespace();
  2315. if (this._char !== value[0]) {
  2316. return false;
  2317. }
  2318. if (value.length === 1) {
  2319. this._next();
  2320. return true;
  2321. }
  2322. const position = this._position;
  2323. for (let i = 0; i < value.length; i++) {
  2324. if (this._char !== value[i]) {
  2325. this._seek(position);
  2326. return false;
  2327. }
  2328. this._next();
  2329. }
  2330. return true;
  2331. }
  2332. _expect(value) {
  2333. if (!this._match(value)) {
  2334. this._unexpected();
  2335. }
  2336. return true;
  2337. }
  2338. _whitespace() {
  2339. for (;;) {
  2340. while (this._char === ' ' || this._char === '\n' || this._char === '\r' || this._char === '\t') {
  2341. this._next();
  2342. }
  2343. if (this._char === undefined || this._char !== '#') {
  2344. break;
  2345. }
  2346. while (this._char !== undefined && this._char !== '\n') {
  2347. this._next();
  2348. }
  2349. }
  2350. }
  2351. _next() {
  2352. if (this._char === undefined) {
  2353. this._unexpected();
  2354. }
  2355. this._position = this._decoder.position;
  2356. this._char = this._decoder.decode();
  2357. }
  2358. _unexpected() {
  2359. let c = this._char;
  2360. if (c === undefined) {
  2361. throw new onnx.Error('Unexpected end of input.');
  2362. }
  2363. else if (c === '"') {
  2364. c = 'string';
  2365. }
  2366. else if ((c >= '0' && c <= '9') || c === '-') {
  2367. c = 'number';
  2368. }
  2369. else {
  2370. if (c < ' ' || c > '\x7F') {
  2371. const name = Object.keys(this._escape).filter((key) => this._escape[key] === c);
  2372. c = (name.length === 1) ? '\\' + name : '\\u' + ('000' + c.charCodeAt(0).toString(16)).slice(-4);
  2373. }
  2374. c = "token '" + c + "'";
  2375. }
  2376. this._throw('Unexpected ' + c);
  2377. }
  2378. _throw(message) {
  2379. throw new onnx.Error(message.replace(/\.$/, '') + this._location());
  2380. }
  2381. _location() {
  2382. let line = 1;
  2383. let column = 1;
  2384. this._decoder.position = 0;
  2385. let c;
  2386. do {
  2387. if (this._decoder.position === this._position) {
  2388. return ' at ' + line.toString() + ':' + column.toString() + '.';
  2389. }
  2390. c = this._decoder.decode();
  2391. if (c === '\n') {
  2392. line++;
  2393. column = 1;
  2394. }
  2395. else {
  2396. column++;
  2397. }
  2398. }
  2399. while (c !== undefined);
  2400. return ' at ' + line.toString() + ':' + column.toString() + '.';
  2401. }
  2402. };
  2403. onnx.Error = class extends Error {
  2404. constructor(message) {
  2405. super(message);
  2406. this.name = 'Error loading ONNX model.';
  2407. }
  2408. };
  2409. if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  2410. module.exports.ModelFactory = onnx.ModelFactory;
  2411. }