onnx.js 91 KB

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