onnx.js 87 KB

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