onnx.js 109 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919
  1. import * as protobuf from './protobuf.js';
  2. const onnx = {};
  3. onnx.ModelFactory = class {
  4. async match(context) {
  5. const identifier = context.identifier;
  6. const extensions = [
  7. 'saved_model.pb', 'predict_net.pb', 'init_net.pb',
  8. 'predict_net.pbtxt', 'init_net.pbtxt', 'predict_net.prototxt', 'init_net.prototxt'
  9. ];
  10. if (!extensions.some((extension) => identifier.endsWith(extension))) {
  11. const entries = [
  12. onnx.OrtReader,
  13. onnx.ProtoReader,
  14. onnx.TextReader,
  15. onnx.JsonReader,
  16. onnx.PickleReader,
  17. onnx.DataReader,
  18. onnx.MetaReader
  19. ];
  20. for (const entry of entries) {
  21. /* eslint-disable no-await-in-loop */
  22. const reader = await entry.open(context);
  23. /* eslint-enable no-await-in-loop */
  24. if (reader) {
  25. return context.set(reader.name, reader);
  26. }
  27. }
  28. }
  29. return null;
  30. }
  31. async open(context) {
  32. const target = context.value;
  33. await target.read();
  34. const metadata = await onnx.Metadata.open(context);
  35. return new onnx.Model(metadata, target);
  36. }
  37. filter(context, match) {
  38. return context.type !== 'onnx.proto' || (match.type !== 'onnx.data' && match.type !== 'onnx.meta' && match.type !== 'dot');
  39. }
  40. };
  41. onnx.Model = class {
  42. constructor(metadata, target) {
  43. const model = target.model;
  44. this._modules = [];
  45. this._format = target.format;
  46. 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;
  47. this._domain = model.domain;
  48. this._version = typeof model.model_version === 'number' || typeof model.model_version === 'bigint' ? model.model_version.toString() : '';
  49. this._description = model.doc_string;
  50. this._metadata = [];
  51. this._imports = null;
  52. const imports = new Map();
  53. if (model.opset_import && model.opset_import.length > 0) {
  54. for (const opset_import of model.opset_import) {
  55. const domain = opset_import.domain || 'ai.onnx';
  56. const version = typeof opset_import.version === 'bigint' ? opset_import.version.toNumber() : opset_import.version;
  57. if (!imports.has(domain) || imports.get(domain) > version) {
  58. imports.set(domain, version);
  59. }
  60. }
  61. this._imports = Array.from(imports).map(([name, version]) => `${name} v${version}`);
  62. }
  63. if (imports.size === 0) {
  64. imports.set('ai.onnx', 1);
  65. imports.set('ai.onnx.ml', 1);
  66. }
  67. let imageFormat = '';
  68. const metadata_props = model.metadata_props;
  69. if (metadata_props) {
  70. const metadata = new Map(metadata_props.map((entry) => [entry.key, entry.value]));
  71. const converted_from = metadata.get('converted_from');
  72. if (converted_from) {
  73. this.source = converted_from;
  74. }
  75. const author = metadata.get('author');
  76. if (author) {
  77. this._metadata.push(new onnx.Argument('author', author));
  78. }
  79. const company = metadata.get('company');
  80. if (company) {
  81. this._metadata.push(new onnx.Argument('company', company));
  82. }
  83. let license = metadata.get('license');
  84. const license_url = metadata.get('license_url');
  85. if (license_url) {
  86. license = `<a href='${license_url}'>${license ? license : license_url}</a>`;
  87. }
  88. if (license) {
  89. this._metadata.push(new onnx.Argument('license', license));
  90. }
  91. metadata.delete('author');
  92. metadata.delete('company');
  93. metadata.delete('converted_from');
  94. metadata.delete('license');
  95. metadata.delete('license_url');
  96. const imageMetadata = {};
  97. for (const [name, value] of metadata) {
  98. switch (name) {
  99. case 'Image.BitmapPixelFormat':
  100. case 'Image.ColorSpaceGamma':
  101. case 'Image.NominalPixelRange':
  102. imageMetadata[name] = value;
  103. break;
  104. default:
  105. this._metadata.push(new onnx.Argument(name, value));
  106. break;
  107. }
  108. }
  109. imageFormat = [imageMetadata['Image.BitmapPixelFormat'], imageMetadata['Image.ColorSpaceGamma'], imageMetadata['Image.NominalPixelRange']].filter((item) => item);
  110. }
  111. const context = new onnx.Context.Model(metadata, target.locations, imageFormat, imports, model.graph, model.functions);
  112. const graph = context.graph(null);
  113. if (graph) {
  114. this._modules.push(graph);
  115. }
  116. this._functions = context.functions;
  117. }
  118. get format() {
  119. return this._format;
  120. }
  121. get version() {
  122. return this._version;
  123. }
  124. get imports() {
  125. return this._imports;
  126. }
  127. get producer() {
  128. return this._producer;
  129. }
  130. get source() {
  131. return this._source;
  132. }
  133. get domain() {
  134. return this._domain || null;
  135. }
  136. get description() {
  137. return this._description || null;
  138. }
  139. get metadata() {
  140. return this._metadata;
  141. }
  142. get modules() {
  143. return this._modules;
  144. }
  145. get functions() {
  146. return this._functions;
  147. }
  148. };
  149. onnx.Graph = class {
  150. constructor(context, graph) {
  151. this._description = '';
  152. this._nodes = [];
  153. this._inputs = [];
  154. this._outputs = [];
  155. this._name = graph && graph.name || null;
  156. this._description = graph.doc_string || '';
  157. context = new onnx.Context.Graph(context, graph);
  158. if (Array.isArray(graph.quantization_annotation)) {
  159. for (const tensor_annotation of graph.quantization_annotation) {
  160. const tensor = context.tensor(tensor_annotation.tensor_name);
  161. tensor.annotation = new Map();
  162. for (const entry of tensor_annotation.quant_parameter_tensor_names) {
  163. tensor.annotation.set(entry.key, entry.value);
  164. }
  165. }
  166. }
  167. graph.input = graph.input.map((value) => {
  168. const tensor = context.tensor(value.name);
  169. tensor.type = context.createType(value.type);
  170. tensor.description = value.doc_string;
  171. const metadata_props = value.metadata_props || [];
  172. tensor.metadata = metadata_props.map((metadata) => new onnx.Argument(metadata.key, metadata.value));
  173. return tensor;
  174. });
  175. graph.output = graph.output.map((value) => {
  176. const tensor = context.tensor(value.name);
  177. tensor.type = context.createType(value.type);
  178. tensor.description = value.doc_string;
  179. const metadata_props = value.metadata_props || [];
  180. tensor.metadata = metadata_props.map((metadata) => new onnx.Argument(metadata.key, metadata.value));
  181. return tensor;
  182. });
  183. const inference = new onnx.Inference(graph.node);
  184. for (const output of graph.output) {
  185. inference.infer(output.name);
  186. }
  187. context.push(graph.node, graph.input, graph.output);
  188. this._nodes = context.pop();
  189. for (const input of graph.input) {
  190. const value = context.value(input.name);
  191. value.metadata = input.metadata || [];
  192. if (!value.initializer) {
  193. this._inputs.push(new onnx.Argument(input.name, [value]));
  194. }
  195. }
  196. for (const output of graph.output) {
  197. const value = context.value(output.name);
  198. value.metadata = output.metadata || [];
  199. if (!value.initializer) {
  200. this._outputs.push(new onnx.Argument(output.name, [value]));
  201. }
  202. }
  203. const metadata_props = graph.metadata_props || [];
  204. this.metadata = metadata_props.map((metadata) => new onnx.Argument(metadata.key, metadata.value));
  205. }
  206. get name() {
  207. return this._name;
  208. }
  209. get description() {
  210. return this._description;
  211. }
  212. get inputs() {
  213. return this._inputs;
  214. }
  215. get outputs() {
  216. return this._outputs;
  217. }
  218. get nodes() {
  219. return this._nodes;
  220. }
  221. toString() {
  222. return `graph(${this.name})`;
  223. }
  224. };
  225. onnx.Argument = class {
  226. constructor(name, value, type, description, visible) {
  227. this.name = name;
  228. this.value = value;
  229. this.type = type || null;
  230. this.description = description || null;
  231. this.visible = visible !== false;
  232. }
  233. };
  234. onnx.Value = class {
  235. constructor(name, type, initializer, annotation, description) {
  236. if (typeof name !== 'string') {
  237. throw new onnx.Error(`Invalid value identifier '${JSON.stringify(name)}'.`);
  238. }
  239. this._name = name;
  240. this._type = type || null;
  241. this._initializer = initializer || null;
  242. this._description = description || '';
  243. this._quantization = annotation ? { type: 'annotation', value: annotation } : null;
  244. }
  245. get name() {
  246. return this._name;
  247. }
  248. get type() {
  249. return this._type;
  250. }
  251. get description() {
  252. return this._description;
  253. }
  254. get quantization() {
  255. return this._quantization;
  256. }
  257. get initializer() {
  258. return this._initializer;
  259. }
  260. };
  261. onnx.Node = class {
  262. constructor(context, node) {
  263. const attributes = node.attribute || [];
  264. const metadata_props = node.metadata_props || [];
  265. const domain = node.domain || 'ai.onnx';
  266. let op_type = node.op_type;
  267. let overload = node.overload || '';
  268. if (domain === 'pkg.torch.ops') {
  269. const path = op_type.split('.');
  270. overload = path.pop();
  271. op_type = path.join('.');
  272. }
  273. this.type = context.type(domain, op_type, overload);
  274. if (!this.type || (this.type.module !== domain && !(this.type instanceof onnx.Function))) {
  275. this.type = { ...this.type };
  276. this.type.name = op_type;
  277. this.type.module = domain;
  278. this.type.overload = overload;
  279. this.type.identifier = overload ? `${op_type}.${overload}` : `${op_type}`;
  280. }
  281. this.metadata = [];
  282. for (const metadata of metadata_props) {
  283. const key = metadata.key;
  284. const value = metadata.value;
  285. if (key === 'input_names' && value.startsWith('[') && value.endsWith(']') && !Array.isArray(this.type.inputs)) {
  286. const input_names = value.slice(1, -1).split(', ');
  287. if (input_names.every((item) => /^'.*'$/.test(item))) {
  288. this.type.inputs = input_names.map((item) => ({ name: item.slice(1, -1) }));
  289. continue;
  290. }
  291. }
  292. const argument = new onnx.Argument(metadata.key, metadata.value);
  293. this.metadata.push(argument);
  294. }
  295. const inputs = [];
  296. node.input = node.input || [];
  297. for (let i = 0; i < node.input.length;) {
  298. const input = this.type && Array.isArray(this.type.inputs) && i < this.type.inputs.length ? this.type.inputs[i] : { name: i.toString() };
  299. const count = input.list ? node.input.length - i : 1;
  300. const list = node.input.slice(i, i + count).filter((value) => value.name !== '' || value.initializer);
  301. const values = list.map((input) => context.value(input.name));
  302. const argument = new onnx.Argument(input.name, values);
  303. inputs.push(argument);
  304. i += count;
  305. }
  306. const outputs = [];
  307. node.output = node.output || [];
  308. for (let i = 0; i < node.output.length;) {
  309. const output = this.type && Array.isArray(this.type.outputs) && i < this.type.outputs.length ? this.type.outputs[i] : { name: i.toString() };
  310. const count = output.list ? node.output.length - i : 1;
  311. const list = node.output.slice(i, i + count).filter((value) => value.name !== '' || value.initializer);
  312. const values = list.map((output) => context.value(output.name));
  313. const argument = new onnx.Argument(output.name, values);
  314. outputs.push(argument);
  315. i += count;
  316. }
  317. this.name = node.name || '';
  318. this.description = node.doc_string || '';
  319. this.inputs = inputs || [];
  320. this.outputs = outputs || [];
  321. this.attributes = attributes.map((attr) => {
  322. if (op_type === 'Int8GivenTensorFill' && attr.s && attr.s.length > 0) {
  323. return new onnx.Argument(attr.name, Array.from(attr.s), 'byte[]');
  324. }
  325. const metadata = context.attribute(domain, op_type, overload, attr.name);
  326. return context.createAttribute(attr, metadata);
  327. });
  328. this.chain = [];
  329. const identifier = domain ? `${domain}.${op_type}` : op_type;
  330. if (identifier === 'com.microsoft.FusedConv') {
  331. const activation = attributes.find((attribute) => attribute.name === 'activation');
  332. if (activation) {
  333. const type = context.decodeText(activation.s);
  334. const node = new onnx.Node(context, { op_type: type });
  335. this.chain.push(node);
  336. }
  337. }
  338. }
  339. };
  340. onnx.Group = class {
  341. constructor(name, groups) {
  342. this._type = { name: 'Scope' };
  343. this._name = name;
  344. this._nodes = [];
  345. for (const [key, value] of groups) {
  346. if (key === '') {
  347. for (const node of value) {
  348. this._nodes.push(node);
  349. }
  350. } else {
  351. this._nodes.push(new onnx.Group(name === '' ? key : `${name}/${key}`, value));
  352. }
  353. }
  354. const set = new Set();
  355. const inputs = [];
  356. const outputs = [];
  357. for (const node of this._nodes) {
  358. if (node instanceof onnx.Group) {
  359. node.freeze();
  360. }
  361. for (const parameter of node.outputs) {
  362. for (const value of parameter.value) {
  363. if (!value.initializer) {
  364. outputs.push(value);
  365. set.add(value.name);
  366. }
  367. }
  368. }
  369. }
  370. for (const node of this._nodes) {
  371. for (const parameter of node.inputs) {
  372. for (const value of parameter.value) {
  373. if (!set.has(value.name) && !value.initializer) {
  374. inputs.push(value);
  375. }
  376. }
  377. }
  378. }
  379. this._inputs = [new onnx.Argument('inputs', inputs)];
  380. this._outputs = [new onnx.Argument('outputs', outputs)];
  381. this._attributes = [];
  382. }
  383. get name() {
  384. return this._name;
  385. }
  386. get type() {
  387. return this._type;
  388. }
  389. get inputs() {
  390. return this._inputs;
  391. }
  392. get outputs() {
  393. return this._outputs;
  394. }
  395. get attributes() {
  396. return this._attributes;
  397. }
  398. get nodes() {
  399. return this._nodes;
  400. }
  401. };
  402. onnx.Tensor = class {
  403. constructor(context, tensor, category) {
  404. this._category = category || null;
  405. if (tensor.indices && tensor.values) {
  406. this._name = tensor.values.name || '';
  407. this._type = context.createTensorType(tensor.values.data_type, tensor.dims, 'sparse');
  408. this._location = context.createLocation(tensor.values.data_location);
  409. this._values = new onnx.Tensor(context, tensor.values);
  410. this._indices = new onnx.Tensor(context, tensor.indices);
  411. } else {
  412. this._name = tensor.name || '';
  413. this._type = context.createTensorType(tensor.data_type, tensor.dims);
  414. this._location = context.createLocation(tensor.data_location);
  415. switch (tensor.data_location) {
  416. case onnx.DataLocation.DEFAULT: {
  417. switch (tensor.data_type) {
  418. case onnx.DataType.UNDEFINED: {
  419. break;
  420. }
  421. case onnx.DataType.FLOAT:
  422. this._data = new Float32Array(tensor.float_data);
  423. this._encoding = '|';
  424. break;
  425. case onnx.DataType.DOUBLE:
  426. this._data = new Float64Array(tensor.double_data);
  427. this._encoding = '|';
  428. break;
  429. case onnx.DataType.BOOL:
  430. if (tensor.int32_data && tensor.int32_data.length > 0) {
  431. const array = tensor.int32_data;
  432. this._data = new Array(array.length);
  433. for (let i = 0; i < this._data.length; i++) {
  434. this._data[i] = array[i] === 0 ? false : true;
  435. }
  436. this._encoding = '|';
  437. }
  438. break;
  439. case onnx.DataType.INT8:
  440. this._data = new Int8Array(tensor.int32_data);
  441. this._encoding = '|';
  442. break;
  443. case onnx.DataType.UINT8:
  444. this._data = new Uint8Array(tensor.int32_data);
  445. this._encoding = '|';
  446. break;
  447. case onnx.DataType.INT16:
  448. this._data = new Int32Array(tensor.int32_data);
  449. this._encoding = '|';
  450. break;
  451. case onnx.DataType.UINT16:
  452. this._data = new Int32Array(tensor.int32_data);
  453. this._encoding = '|';
  454. break;
  455. case onnx.DataType.INT32:
  456. this._data = new Int32Array(tensor.int32_data);
  457. this._encoding = '|';
  458. break;
  459. case onnx.DataType.UINT32:
  460. case onnx.DataType.UINT64:
  461. this._data = tensor.uint64_data;
  462. this._encoding = '|';
  463. break;
  464. case onnx.DataType.INT64:
  465. this._data = tensor.int64_data;
  466. this._encoding = '|';
  467. break;
  468. case onnx.DataType.STRING:
  469. this._data = tensor.string_data;
  470. this._encoding = '|';
  471. break;
  472. case onnx.DataType.COMPLEX64:
  473. case onnx.DataType.COMPLEX128:
  474. break;
  475. case onnx.DataType.FLOAT16:
  476. case onnx.DataType.BFLOAT16:
  477. if (tensor.int32_data && tensor.int32_data.length > 0) {
  478. const array = tensor.int32_data;
  479. const buffer = new Uint8Array(array.length << 1);
  480. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  481. for (let i = 0; i < array.length; i++) {
  482. view.setUint16(i << 1, array[i], true);
  483. }
  484. this._data = buffer;
  485. this._encoding = '<';
  486. }
  487. break;
  488. case onnx.DataType.FLOAT4E2M1:
  489. case onnx.DataType.FLOAT8E4M3FN:
  490. case onnx.DataType.FLOAT8E4M3FNUZ:
  491. case onnx.DataType.FLOAT8E5M2:
  492. case onnx.DataType.FLOAT8E5M2FNUZ:
  493. if (tensor.int32_data && tensor.int32_data.length > 0) {
  494. this._data = new Uint8Array(Array.from(tensor.int32_data));
  495. this._encoding = '<';
  496. }
  497. break;
  498. case onnx.DataType.UINT4:
  499. case onnx.DataType.INT4:
  500. if (tensor.int32_data && tensor.int32_data.length > 0) {
  501. this._data = new Uint8Array(Array.from(tensor.int32_data));
  502. this._encoding = '<';
  503. }
  504. break;
  505. default:
  506. throw new onnx.Error(`Unsupported tensor data type '${tensor.data_type}'.`);
  507. }
  508. if (this._data && (Array.isArray(this._data) || ArrayBuffer.isView(this._data)) && this._data.length === 0) {
  509. this._data = undefined;
  510. }
  511. if (!this._data && tensor.raw_data && tensor.raw_data.length > 0) {
  512. this._data = tensor.raw_data;
  513. this._encoding = '<';
  514. }
  515. break;
  516. }
  517. case onnx.DataLocation.EXTERNAL: {
  518. if (Array.isArray(tensor.external_data)) {
  519. const data = new Map();
  520. for (const entry of tensor.external_data) {
  521. data.set(entry.key, entry.value);
  522. }
  523. if (data.has('location')) {
  524. this._location = data.get('location').toString();
  525. const location = context.location(this._location);
  526. const offset = data.has('offset') ? parseInt(data.get('offset'), 10) : 0;
  527. const length = data.has('length') ? parseInt(data.get('length'), 10) : -1;
  528. this._request = { location, offset, length };
  529. this._encoding = '<';
  530. }
  531. }
  532. break;
  533. }
  534. default: {
  535. break;
  536. }
  537. }
  538. }
  539. }
  540. peek() {
  541. return !this._request;
  542. }
  543. async read() {
  544. if (this._request) {
  545. const location = this._request.location;
  546. const offset = this._request.offset;
  547. const length = this._request.length;
  548. this._data = await location.read(offset, length);
  549. delete this._request;
  550. }
  551. }
  552. get name() {
  553. return this._name;
  554. }
  555. get category() {
  556. return this._category;
  557. }
  558. get encoding() {
  559. return this._encoding;
  560. }
  561. get location() {
  562. return this._location;
  563. }
  564. get type() {
  565. return this._type;
  566. }
  567. get indices() {
  568. return this._indices;
  569. }
  570. get values() {
  571. if (this._request) {
  572. throw new onnx.Error('Tensor data not loaded.');
  573. }
  574. switch (this.type.layout) {
  575. case 'sparse': {
  576. return this._values;
  577. }
  578. default: {
  579. if (!this._data || this._data instanceof Uint8Array) {
  580. return this._data;
  581. }
  582. if (Array.isArray(this._data) || ArrayBuffer.isView(this._data)) {
  583. return this._data;
  584. }
  585. return this._data.peek();
  586. }
  587. }
  588. }
  589. };
  590. onnx.TensorType = class {
  591. constructor(dataType, shape, layout, denotation) {
  592. this._dataType = dataType;
  593. this._shape = shape;
  594. this._layout = layout || null;
  595. this._denotation = denotation || null;
  596. }
  597. get dataType() {
  598. return this._dataType;
  599. }
  600. get shape() {
  601. return this._shape;
  602. }
  603. get layout() {
  604. return this._layout;
  605. }
  606. get denotation() {
  607. return this._denotation;
  608. }
  609. toString() {
  610. return this.dataType + this._shape.toString();
  611. }
  612. };
  613. onnx.TensorShape = class {
  614. constructor(dimensions) {
  615. this._dimensions = dimensions.map((dim) => typeof dim === 'bigint' ? dim.toNumber() : dim);
  616. }
  617. get dimensions() {
  618. return this._dimensions;
  619. }
  620. toString() {
  621. if (!this._dimensions || this._dimensions.length === 0) {
  622. return '';
  623. }
  624. return `[${this._dimensions.map((dim) => dim || Number.isInteger(dim) ? dim.toString() : '?').join(',')}]`;
  625. }
  626. };
  627. onnx.SequenceType = class {
  628. constructor(elementType, denotation) {
  629. this._elementType = elementType;
  630. this._denotation = denotation;
  631. }
  632. get elementType() {
  633. return this._elementType;
  634. }
  635. get dennotation() {
  636. return this._dennotation;
  637. }
  638. toString() {
  639. const elementType = this._elementType ? this._elementType.toString() : '';
  640. return `sequence<${elementType}>`;
  641. }
  642. };
  643. onnx.MapType = class {
  644. constructor(keyType, valueType, denotation) {
  645. this._keyType = keyType;
  646. this._valueType = valueType;
  647. this._denotation = denotation;
  648. }
  649. get keyType() {
  650. return this._keyType;
  651. }
  652. get valueType() {
  653. return this._valueType;
  654. }
  655. get denotation() {
  656. return this._denotation;
  657. }
  658. toString() {
  659. return `map<${this._keyType},${this._valueType}>`;
  660. }
  661. };
  662. onnx.OpaqueType = class {
  663. constructor(domain, name) {
  664. this._domain = domain;
  665. this._name = name;
  666. }
  667. toString() {
  668. const name = (this._domain ? (`${this._domain}.`) : '') + this._name;
  669. return `opaque<${name}>`;
  670. }
  671. };
  672. onnx.OptionalType = class {
  673. constructor(type) {
  674. this._type = type;
  675. }
  676. get type() {
  677. return this._type;
  678. }
  679. toString() {
  680. return `optional<${this._type}>`;
  681. }
  682. };
  683. onnx.Function = class {
  684. constructor(context, func) {
  685. this.type = 'function';
  686. this.name = func.name;
  687. this.module = func.domain;
  688. this.overload = func.overload || '';
  689. this.identifier = this.overload ? `${this.name}:${this.overload}` : this.name;
  690. this.description = func.doc_string;
  691. this.inputs = [];
  692. this.outputs = [];
  693. this.attributes = [];
  694. for (let i = 0; i < func.attribute.length; i++) {
  695. const attribute = new onnx.Argument(i.toString(), func.attribute[i]);
  696. this.attributes.push(attribute);
  697. }
  698. for (const attr of func.attribute_proto) {
  699. const attribute = context.createAttribute(attr, func.domain, func.name, func.overload);
  700. this.attributes.push(attribute);
  701. }
  702. context = new onnx.Context.Graph(context, func);
  703. func.input = func.input.map((input) => context.tensor(input));
  704. func.output = func.output.map((output) => context.tensor(output));
  705. context.push(func.node, func.input, func.output);
  706. this.nodes = context.pop();
  707. for (const input of func.input) {
  708. const value = context.value(input.name);
  709. if (!value.initializer) {
  710. this.inputs.push(new onnx.Argument(input.name, [value]));
  711. }
  712. }
  713. for (const output of func.output) {
  714. const value = context.value(output.name);
  715. if (!value.initializer) {
  716. this.outputs.push(new onnx.Argument(output.name, [value]));
  717. }
  718. }
  719. }
  720. };
  721. onnx.Context = class {};
  722. onnx.Context.Model = class {
  723. constructor(metadata, locations, imageFormat, imports, graph, functions) {
  724. this._metadata = metadata;
  725. this._locations = locations;
  726. this._dataTypes = new Map(Object.entries(onnx.DataType).map(([name, value]) => [value, name.toLowerCase()]));
  727. this._dataTypes.set(onnx.DataType.UNDEFINED, 'undefined');
  728. this._dataTypes.set(onnx.DataType.BOOL, 'boolean');
  729. this._dataTypes.set(onnx.DataType.FLOAT, 'float32');
  730. this._dataTypes.set(onnx.DataType.DOUBLE, 'float64');
  731. this._imageFormat = imageFormat;
  732. this._imports = imports;
  733. this._types = new Map();
  734. this._attributes = new Map();
  735. this._graph = null;
  736. this._graphs = new Map();
  737. this._functions = new Map();
  738. for (const func of functions || []) {
  739. const key = func.overload ? `${func.domain}:${func.name}:${func.overload}` : `${func.domain}:${func.name}`;
  740. func.initializer = [];
  741. func.uses = [];
  742. func.callers = new Set();
  743. this._functions.set(key, func);
  744. }
  745. if (graph) {
  746. if (this._functions.size > 0) { // #1208
  747. const queue = [graph].concat(Array.from(this._functions.values()));
  748. for (const graph of queue) {
  749. const graphs = [graph];
  750. while (graphs.length > 0) {
  751. const graph = graphs.shift();
  752. for (const node of graph.node) {
  753. const key = node.overload ? `${node.domain}:${node.op_type}:${node.overload}` : `${node.domain}:${node.op_type}`;
  754. if (this._functions.has(key)) {
  755. this._functions.get(key).callers.add(graph);
  756. }
  757. for (const attribute of node.attribute) {
  758. if (attribute.g) {
  759. graphs.push(attribute.g);
  760. }
  761. if (Array.isArray(attribute.graphs) && attribute.graphs.length > 0) {
  762. graphs.push(...attribute.graphs);
  763. }
  764. }
  765. }
  766. }
  767. }
  768. const visited = new Set();
  769. const graphs = new Set([graph]);
  770. while (graphs.size > 0) {
  771. const graph = graphs.values().next().value;
  772. graphs.delete(graph);
  773. if (visited.has(graph)) {
  774. continue;
  775. }
  776. if (graph.callers && !Array.from(graph.callers).every((caller) => visited.has(caller))) {
  777. graphs.add(graph);
  778. continue;
  779. }
  780. visited.add(graph);
  781. graph.initializer = graph.initializer || [];
  782. const initializers = new Map();
  783. for (const initializer of graph.initializer) {
  784. initializers.set(initializer.name, { uses: [], initializer, visible: true });
  785. }
  786. for (const node of graph.node) {
  787. const key = node.overload ? `${node.domain}:${node.op_type}:${node.overload}` : `${node.domain}:${node.op_type}`;
  788. if (this._functions.has(key)) {
  789. this._functions.get(key).uses.push(node);
  790. }
  791. for (const input of node.input) {
  792. if (initializers.has(input)) {
  793. initializers.get(input).uses.push(node);
  794. }
  795. }
  796. for (const attribute of node.attribute) {
  797. if (attribute.g) {
  798. graphs.add(attribute.g);
  799. }
  800. if (Array.isArray(attribute.graphs) && attribute.graphs.length > 0) {
  801. for (const graph of attribute.graphs) {
  802. graphs.add(graph);
  803. }
  804. }
  805. }
  806. }
  807. const queue = [];
  808. for (const [name, entry] of initializers) {
  809. if (entry.uses.length === 1) {
  810. const [node] = entry.uses;
  811. const key = node.overload ? `${node.domain}:${node.op_type}:${node.overload}` : `${node.domain}:${node.op_type}`;
  812. if (this._functions.has(key)) {
  813. const func = this._functions.get(key);
  814. if (func.uses.length === 1 && func.callers.size === 1) {
  815. const index = node.input.indexOf(name);
  816. if (Array.isArray(func.input) && index < func.input.length && func.input[index] === name) {
  817. func.initializer.push(entry.initializer);
  818. graphs.add(func);
  819. queue.push([index, node]);
  820. }
  821. }
  822. }
  823. }
  824. }
  825. queue.sort((a, b) => b[0] - a[0]);
  826. for (const [index, node] of queue) {
  827. node.input.splice(index, 1);
  828. }
  829. }
  830. }
  831. this._graph = new onnx.Graph(this, graph);
  832. }
  833. }
  834. graph(value) {
  835. if (value === null) {
  836. return this._graph;
  837. }
  838. if (!this._graphs.has(value)) {
  839. this._graphs.set(value, new onnx.Graph(this, value));
  840. }
  841. return this._graphs.get(value);
  842. }
  843. get functions() {
  844. for (const [, func] of this._functions) {
  845. if (func instanceof onnx.Function === false) {
  846. this.type(func.domain, func.name, func.overload);
  847. }
  848. }
  849. return Array.from(this._functions.values());
  850. }
  851. location(name) {
  852. if (this._locations.has(name)) {
  853. return this._locations.get(name);
  854. }
  855. return null;
  856. }
  857. initializer(/* name */) {
  858. return null;
  859. }
  860. type(domain, name, overload) {
  861. const key = overload ? `${domain}:${name}:${overload}` : `${domain}:${name}`;
  862. if (!this._types.has(key)) {
  863. let value = null;
  864. if (this._functions.has(key)) {
  865. value = this._functions.get(key);
  866. if (value && value instanceof onnx.Function === false) {
  867. value = new onnx.Function(this, value);
  868. this._functions.set(key, value);
  869. }
  870. }
  871. if (!value) {
  872. value = this._metadata.type(domain, name, this._imports);
  873. }
  874. this._types.set(key, value);
  875. }
  876. return this._types.get(key);
  877. }
  878. attribute(domain, type, overload, name) {
  879. const key = overload ? `${domain}:${type}:${overload}::${name}` : `${domain}:${type}::${name}`;
  880. if (!this._attributes.has(key)) {
  881. this._attributes.set(key, null);
  882. const metadata = this.type(domain, type);
  883. if (metadata && Array.isArray(metadata.attributes) && metadata.attributes.length > 0) {
  884. for (const attribute of metadata.attributes) {
  885. const name = attribute.name;
  886. const key = overload ? `${domain}:${type}:${overload}::${name}` : `${domain}:${type}::${name}`;
  887. this._attributes.set(key, attribute);
  888. }
  889. }
  890. }
  891. return this._attributes.get(key);
  892. }
  893. decodeText(value) {
  894. if (typeof value === 'string') {
  895. return value;
  896. }
  897. this._decoder = this._decoder || new TextDecoder('utf-8');
  898. return this._decoder.decode(value);
  899. }
  900. createAttribute(attribute, metadata) {
  901. const name = attribute.name;
  902. let type = null;
  903. let value = null;
  904. let visible = true;
  905. if (attribute.ref_attr_name) {
  906. value = attribute.ref_attr_name;
  907. type = 'reference';
  908. } else {
  909. switch (attribute.type) {
  910. case onnx.AttributeType.UNDEFINED:
  911. break;
  912. case onnx.AttributeType.FLOAT:
  913. value = attribute.f;
  914. type = 'float32';
  915. break;
  916. case onnx.AttributeType.INT:
  917. value = BigInt(attribute.i);
  918. type = 'int64';
  919. break;
  920. case onnx.AttributeType.STRING:
  921. value = this.decodeText(attribute.s);
  922. type = 'string';
  923. break;
  924. case onnx.AttributeType.TENSOR:
  925. value = new onnx.Tensor(this, attribute.t);
  926. type = 'tensor';
  927. break;
  928. case onnx.AttributeType.GRAPH:
  929. value = this.graph(attribute.g);
  930. type = 'graph';
  931. break;
  932. case onnx.AttributeType.FLOATS:
  933. value = ArrayBuffer.isView(attribute.floats) ? Array.from(attribute.floats) : attribute.floats;
  934. type = 'float32[]';
  935. break;
  936. case onnx.AttributeType.INTS:
  937. value = ArrayBuffer.isView(attribute.ints) ? Array.from(attribute.ints) : attribute.ints.map((value) => BigInt(value));
  938. type = 'int64[]';
  939. break;
  940. case onnx.AttributeType.STRINGS:
  941. value = attribute.strings.map((s) => this.decodeText(s));
  942. type = 'string[]';
  943. break;
  944. case onnx.AttributeType.TENSORS:
  945. value = attribute.tensors.map((tensor) => new onnx.Tensor(this, tensor));
  946. type = 'tensor[]';
  947. break;
  948. case onnx.AttributeType.GRAPHS:
  949. value = attribute.graphs.map((graph) => this.graph(graph));
  950. type = 'graph[]';
  951. break;
  952. case onnx.AttributeType.SPARSE_TENSOR:
  953. value = new onnx.Tensor(this, attribute.sparse_tensor);
  954. type = 'tensor';
  955. break;
  956. case onnx.AttributeType.SPARSE_TENSORS:
  957. value = attribute.sparse_tensors.map((tensor) => new onnx.Tensor(this, tensor));
  958. type = 'tensor[]';
  959. break;
  960. case onnx.AttributeType.TYPE_PROTO:
  961. value = this.createType(attribute.tp);
  962. type = 'type';
  963. break;
  964. case onnx.AttributeType.TYPE_PROTOS:
  965. value = attribute.type_protos.map((type) => this.createType(type));
  966. type = 'type[]';
  967. break;
  968. default:
  969. throw new onnx.Error(`Unsupported attribute type '${attribute.type}'.`);
  970. }
  971. if (metadata) {
  972. if (metadata.default !== undefined) {
  973. const defaultValue = type === 'int64' ? BigInt(metadata.default) : metadata.default;
  974. if (value === defaultValue) {
  975. visible = false;
  976. }
  977. }
  978. if (metadata.type === 'DataType') {
  979. type = metadata.type;
  980. value = this.createDataType(value);
  981. }
  982. }
  983. }
  984. return new onnx.Argument(name, value, type, attribute.doc_string, visible);
  985. }
  986. createType(type) {
  987. if (!type) {
  988. return null;
  989. }
  990. let denotation = '';
  991. switch (type.denotation) {
  992. case undefined:
  993. case null:
  994. case '':
  995. break;
  996. case 'TENSOR':
  997. denotation = 'Tensor';
  998. break;
  999. case 'IMAGE':
  1000. denotation = `Image${this._imageFormat ? `(${this._imageFormat.join(',')})` : ''}`;
  1001. break;
  1002. case 'AUDIO':
  1003. denotation = 'Audio';
  1004. break;
  1005. case 'TEXT':
  1006. denotation = 'Text';
  1007. break;
  1008. default:
  1009. throw new onnx.Error(`Unsupported tensor type denotation '${type.denotation}'.`);
  1010. }
  1011. if (type.tensor_type) {
  1012. const tensor_type = type.tensor_type;
  1013. const shape = tensor_type.shape && tensor_type.shape.dim ? tensor_type.shape.dim.map((dim) => dim.dim_param ? dim.dim_param : dim.dim_value || null) : [];
  1014. return this.createTensorType(tensor_type.elem_type, shape, null, denotation);
  1015. } else if (type.sparse_tensor_type) {
  1016. type = type.sparse_tensor_type;
  1017. const shape = type.shape && type.shape.dim ? type.shape.dim.map((dim) => dim.dim_param ? dim.dim_param : dim.dim_value || null) : [];
  1018. return this.createTensorType(type.elem_type, shape, 'sparse', denotation);
  1019. } else if (type.map_type) {
  1020. const keyType = this.createDataType(type.map_type.key_type);
  1021. const valueType = this.createType(type.map_type.value_type);
  1022. return new onnx.MapType(keyType, valueType, denotation);
  1023. } else if (type.sequence_type) {
  1024. return new onnx.SequenceType(this.createType(type.sequence_type.elem_type), denotation);
  1025. } else if (type.opaque_type) {
  1026. return new onnx.OpaqueType(type.opaque_type.domain, type.opaque_type.name);
  1027. } else if (type.optional_type) {
  1028. return new onnx.OptionalType(this.createType(type.optional_type.elem_type), denotation);
  1029. } else if (Object.keys(type).length === 0) {
  1030. return null;
  1031. }
  1032. throw new onnx.Error(`Unsupported tensor type '${JSON.stringify(type)}'.`);
  1033. }
  1034. createDataType(value) {
  1035. if (!Number.isInteger(value)) {
  1036. if (typeof value === 'bigint') {
  1037. value = value.toNumber();
  1038. } else if (value && typeof value === 'string' && onnx.DataType[value.toUpperCase()] !== undefined) {
  1039. value = onnx.DataType[value.toUpperCase()];
  1040. } else {
  1041. throw new onnx.Error(`Unsupported data type '${JSON.stringify(value)}'.`);
  1042. }
  1043. }
  1044. if (this._dataTypes.has(value)) {
  1045. return this._dataTypes.get(value);
  1046. }
  1047. throw new onnx.Error(`Unsupported data type '${JSON.stringify(value)}'.`);
  1048. }
  1049. createLocation(value) {
  1050. switch (value) {
  1051. case undefined:
  1052. case onnx.DataLocation.DEFAULT: return '';
  1053. case onnx.DataLocation.EXTERNAL: return 'external';
  1054. default: return 'undefined';
  1055. }
  1056. }
  1057. createTensorType(dataType, shape, layout, denotation) {
  1058. dataType = this.createDataType(dataType);
  1059. return new onnx.TensorType(dataType, new onnx.TensorShape(shape), layout, denotation);
  1060. }
  1061. };
  1062. onnx.Metadata = class {
  1063. static async open(context) {
  1064. if (!onnx.Metadata._metadata) {
  1065. let data = null;
  1066. try {
  1067. data = await context.request('onnx-metadata.json');
  1068. } catch {
  1069. // continue regardless of error
  1070. }
  1071. onnx.Metadata._metadata = new onnx.Metadata(data);
  1072. }
  1073. return onnx.Metadata._metadata;
  1074. }
  1075. constructor(data) {
  1076. this._types = new Map();
  1077. if (data) {
  1078. const types = JSON.parse(data);
  1079. for (const type of types) {
  1080. if (!this._types.has(type.module)) {
  1081. this._types.set(type.module, new Map());
  1082. }
  1083. const types = this._types.get(type.module);
  1084. if (!types.has(type.name)) {
  1085. types.set(type.name, []);
  1086. }
  1087. types.get(type.name).push(type);
  1088. }
  1089. }
  1090. }
  1091. type(domain, name, imports) {
  1092. domain = domain || 'ai.onnx';
  1093. let current = null;
  1094. if (this._types.has(domain)) {
  1095. const types = this._types.get(domain);
  1096. if (types.has(name)) {
  1097. for (const type of types.get(name)) {
  1098. const matchVersion = current ? current.version : -1;
  1099. const importVersion = imports.get(type.module) || 0;
  1100. if (importVersion >= type.version && matchVersion < type.version) {
  1101. current = type;
  1102. }
  1103. }
  1104. }
  1105. }
  1106. return current;
  1107. }
  1108. };
  1109. onnx.Inference = class {
  1110. constructor(nodes) {
  1111. this._outputs = new Map();
  1112. for (const node of nodes) {
  1113. for (const output of node.output) {
  1114. this._outputs.set(output.name, node);
  1115. }
  1116. }
  1117. }
  1118. infer(output) {
  1119. if (this._outputs.has(output)) {
  1120. let hasInputShapes = true;
  1121. const node = this._outputs.get(output);
  1122. for (const input of node.input) {
  1123. if (!input.type) {
  1124. this.infer(input);
  1125. if (!input.type) {
  1126. hasInputShapes = false;
  1127. break;
  1128. }
  1129. }
  1130. }
  1131. if (hasInputShapes) {
  1132. // continue
  1133. }
  1134. }
  1135. }
  1136. };
  1137. onnx.DataLocation = {
  1138. DEFAULT: 0,
  1139. EXTERNAL: 1
  1140. };
  1141. onnx.DataType = {
  1142. UNDEFINED: 0,
  1143. FLOAT: 1,
  1144. UINT8: 2,
  1145. INT8: 3,
  1146. UINT16: 4,
  1147. INT16: 5,
  1148. INT32: 6,
  1149. INT64: 7,
  1150. STRING: 8,
  1151. BOOL: 9,
  1152. FLOAT16: 10,
  1153. DOUBLE: 11,
  1154. UINT32: 12,
  1155. UINT64: 13,
  1156. COMPLEX64: 14,
  1157. COMPLEX128: 15,
  1158. BFLOAT16: 16,
  1159. FLOAT8E4M3FN: 17,
  1160. FLOAT8E4M3FNUZ: 18,
  1161. FLOAT8E5M2: 19,
  1162. FLOAT8E5M2FNUZ: 20,
  1163. UINT4: 21,
  1164. INT4: 22,
  1165. FLOAT4E2M1: 23
  1166. };
  1167. onnx.AttributeType = {
  1168. UNDEFINED: 0,
  1169. FLOAT: 1,
  1170. INT: 2,
  1171. STRING: 3,
  1172. TENSOR: 4,
  1173. GRAPH: 5,
  1174. FLOATS: 6,
  1175. INTS: 7,
  1176. STRINGS: 8,
  1177. TENSORS: 9,
  1178. GRAPHS: 10,
  1179. SPARSE_TENSOR: 11,
  1180. SPARSE_TENSORS: 12,
  1181. TYPE_PROTO: 13,
  1182. TYPE_PROTOS: 14
  1183. };
  1184. onnx.Context.Graph = class {
  1185. constructor(context, graph) {
  1186. this._context = context;
  1187. this._initializers = new Map();
  1188. this._tensors = new Map();
  1189. this._values = new Map();
  1190. this._groups = new Map();
  1191. this._nodes = [];
  1192. if (Array.isArray(graph.initializer)) {
  1193. for (const initializer of graph.initializer) {
  1194. const tensor = new onnx.Tensor(this, initializer, 'Initializer');
  1195. this._initializers.set(initializer.name, tensor);
  1196. }
  1197. }
  1198. if (Array.isArray(graph.sparse_initializer)) {
  1199. for (const sparse_initializer of graph.sparse_initializer) {
  1200. const tensor = new onnx.Tensor(this, sparse_initializer, 'Initializer');
  1201. this._initializers.set(sparse_initializer.values.name, tensor);
  1202. }
  1203. }
  1204. if (Array.isArray(graph.value_info)) {
  1205. for (const value of graph.value_info) {
  1206. const tensor = this.tensor(value.name);
  1207. tensor.type = this.createType(value.type);
  1208. tensor.description = value.doc_string;
  1209. }
  1210. }
  1211. for (const node of graph.node) {
  1212. node.input = node.input.map((name) => this.tensor(name));
  1213. node.output = node.output.map((name) => this.tensor(name));
  1214. node.param = {};
  1215. if (Array.isArray(node.attribute)) {
  1216. for (const attribute of node.attribute) {
  1217. if (attribute.type) {
  1218. continue;
  1219. }
  1220. if (Array.isArray(attribute.ints) && attribute.ints.length > 0) {
  1221. attribute.type = onnx.AttributeType.INTS;
  1222. } else if (Array.isArray(attribute.floats) && attribute.floats.length > 0) {
  1223. attribute.type = onnx.AttributeType.FLOATS;
  1224. } else if (Array.isArray(attribute.strings) && attribute.strings.length > 0) {
  1225. attribute.type = onnx.AttributeType.STRINGS;
  1226. } else if (Array.isArray(attribute.graphs) && attribute.graphs.length > 0) {
  1227. attribute.type = onnx.AttributeType.GRAPHS;
  1228. } else if (Array.isArray(attribute.s) && attribute.s.length > 0) {
  1229. attribute.type = onnx.AttributeType.STRING;
  1230. } else if (attribute.f !== undefined) {
  1231. attribute.type = onnx.AttributeType.FLOAT;
  1232. } else if (attribute.i !== undefined) {
  1233. attribute.type = onnx.AttributeType.INT;
  1234. } else if (attribute.t !== undefined) {
  1235. attribute.type = onnx.AttributeType.TENSOR;
  1236. } else if (attribute.g !== undefined) {
  1237. attribute.type = onnx.AttributeType.GRAPH;
  1238. } else if (attribute.sparse_tensor) {
  1239. attribute.type = onnx.AttributeType.SPARSE_TENSOR;
  1240. } else {
  1241. attribute.type = onnx.AttributeType.UNDEFINED;
  1242. }
  1243. }
  1244. }
  1245. }
  1246. }
  1247. type(domain, name, overload) {
  1248. return this._context.type(domain, name, overload);
  1249. }
  1250. attribute(domain, type, overload, name) {
  1251. return this._context.attribute(domain, type, overload, name);
  1252. }
  1253. initializer(name) {
  1254. if (this._initializers.has(name)) {
  1255. return this._initializers.get(name);
  1256. }
  1257. return this._context.initializer(name);
  1258. }
  1259. tensor(name) {
  1260. if (!this._tensors.has(name)) {
  1261. this._tensors.set(name, { name, initializer: this.initializer(name) });
  1262. }
  1263. return this._tensors.get(name);
  1264. }
  1265. location(name) {
  1266. return this._context.location(name);
  1267. }
  1268. group(name) {
  1269. if (!this._groups.has(name)) {
  1270. const path = name.split('/');
  1271. if (path.length > 1) {
  1272. path.pop();
  1273. return this.group(path.join('/'));
  1274. }
  1275. this._groups.set(name, new Map([['', []]]));
  1276. }
  1277. return this._groups.get(name);
  1278. }
  1279. value(name) {
  1280. if (!this._values.has(name)) {
  1281. const tensor = this.tensor(name);
  1282. const type = tensor.initializer ? tensor.initializer.type : tensor.type || null;
  1283. this._values.set(name, new onnx.Value(name, type, tensor.initializer, tensor.annotation, tensor.description));
  1284. }
  1285. return this._values.get(name);
  1286. }
  1287. createType(type) {
  1288. return this._context.createType(type);
  1289. }
  1290. createTensorType(dataType, shape, layout, denotation) {
  1291. return this._context.createTensorType(dataType, shape, layout, denotation);
  1292. }
  1293. createDataType(value) {
  1294. return this._context.createDataType(value);
  1295. }
  1296. createLocation(value) {
  1297. return this._context.createLocation(value);
  1298. }
  1299. createAttribute(attribute, metadata) {
  1300. return this._context.createAttribute(attribute, metadata);
  1301. }
  1302. decodeText(value) {
  1303. return this._context.decodeText(value);
  1304. }
  1305. push(nodes, inputs, outputs) {
  1306. const inputMap = new Map();
  1307. const outputMap = new Map();
  1308. for (const node of nodes) {
  1309. for (const input of node.input) {
  1310. inputMap.set(input.name, (inputMap.get(input) || 0) + 1);
  1311. }
  1312. for (const output of node.output) {
  1313. outputMap.set(output.name, (outputMap.get(output) || 0) + 1);
  1314. }
  1315. }
  1316. inputs.every((input) => inputMap.delete(input.name));
  1317. outputs.every((output) => outputMap.delete(output.name));
  1318. nodes = nodes.filter((node) => {
  1319. const constant = node &&
  1320. node.op_type === 'Constant' &&
  1321. node.attribute.length === 1 && node.attribute[0] &&
  1322. node.input.length === 0 &&
  1323. node.output.length === 1 && node.output[0] && inputMap.get(node.output[0].name) === 1 && outputMap.get(node.output[0].name) === 1;
  1324. const attribute = constant ? node.attribute[0] : null;
  1325. if (attribute && attribute.name === 'value' && attribute.type === onnx.AttributeType.TENSOR && attribute.t) {
  1326. const tensor = this.tensor(node.output[0].name);
  1327. tensor.initializer = new onnx.Tensor(this, attribute.t, 'Constant');
  1328. return false;
  1329. } else if (attribute && attribute.name === 'sparse_value' && attribute.type === onnx.AttributeType.SPARSE_TENSOR && attribute.sparse_tensor) {
  1330. const tensor = this.tensor(node.output[0].name);
  1331. tensor.initializer = new onnx.Tensor(this, attribute.sparse_tensor, 'Constant');
  1332. return false;
  1333. }
  1334. return true;
  1335. });
  1336. for (let node of nodes) {
  1337. node = new onnx.Node(this, node);
  1338. this._nodes.push(node);
  1339. // const path = (node.name || '').split('/');
  1340. // path.pop();
  1341. // this.group(path.join('/')).get('').push(node);
  1342. }
  1343. }
  1344. pop() {
  1345. /*
  1346. const nodes = [];
  1347. for (const [name, value] of this._groups) {
  1348. if (name === '') {
  1349. for (const node of value.get('')) {
  1350. nodes.push(node);
  1351. }
  1352. continue;
  1353. }
  1354. nodes.push(new onnx.Group(name, value));
  1355. }
  1356. return nodes;
  1357. */
  1358. return this._nodes;
  1359. }
  1360. };
  1361. onnx.ProtoReader = class {
  1362. static async open(context) {
  1363. const identifier = context.identifier;
  1364. const stream = context.stream;
  1365. let offset = 0;
  1366. if (stream && stream.length > 5) {
  1367. const buffer = stream.peek(Math.min(stream.length, 256));
  1368. if (buffer[0] === 0x08 && buffer[1] < 0x0B && buffer[2] === 0x12 && buffer[3] < 64 && (buffer[3] + 4) <= stream.length) {
  1369. if (buffer[3] === 0x00 && buffer[4] === 0x1A && buffer[5] === 0x00) {
  1370. return new onnx.ProtoReader(context, 'binary', 'model');
  1371. }
  1372. const producer = String.fromCharCode.apply(null, buffer.subarray(4, 4 + buffer[3]));
  1373. if (producer.match(/^[A-Za-z][A-Za-z0-9_+-. ]+$/)) {
  1374. return new onnx.ProtoReader(context, 'binary', 'model');
  1375. }
  1376. }
  1377. const length = buffer[0] | (buffer[1] << 8) | (buffer[2] << 16) | (buffer[3] << 24);
  1378. if (length === stream.length - 4 && (buffer[4] === 0x08 || buffer[4] === 0x0A)) {
  1379. offset = 4;
  1380. }
  1381. }
  1382. stream.seek(offset);
  1383. const binaryTags = await context.tags('pb');
  1384. stream.seek(0);
  1385. if (binaryTags.size > 0) {
  1386. const tags = binaryTags;
  1387. if (tags.size === 1 && tags.get(1) === 2) {
  1388. stream.seek(offset);
  1389. const tags = await context.tags('pb+');
  1390. stream.seek(0);
  1391. const match = (tags, schema) => {
  1392. for (const [key, inner] of schema) {
  1393. const value = tags[key];
  1394. if (value === undefined) {
  1395. continue;
  1396. }
  1397. if (inner === false) {
  1398. return false;
  1399. }
  1400. if (Array.isArray(inner)) {
  1401. if (typeof value !== 'object' || !match(value, inner)) {
  1402. return false;
  1403. }
  1404. } else if (inner !== value) {
  1405. if (inner === 2 && !Array.isArray(value) && Object(value) === (value) && Object.keys(value).length === 0) {
  1406. return true;
  1407. }
  1408. return false;
  1409. }
  1410. }
  1411. return true;
  1412. };
  1413. // mediapipe.BoxDetectorIndex
  1414. 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]])) {
  1415. return undefined;
  1416. }
  1417. // third_party.tensorflow.python.keras.protobuf.SavedMetadata
  1418. if (match(tags, [[1,[[1,[[1,0],[2,0]]],[2,0],[3,2],[4,2],[5,2]]]])) {
  1419. return undefined;
  1420. }
  1421. }
  1422. if (Array.from(tags.keys()).every((tag) => tag <= 100) &&
  1423. Array.from(tags.values()).every((type) => type < 5)) {
  1424. // TensorProto
  1425. if (tags.get(1) === 0 && tags.get(2) === 0 && [3, 4, 5, 6].filter((tag) => tags.get(tag)).length <= 1) {
  1426. const schema = [[1,0],[2,0],[4,2],[5,2],[7,2],[8,2],[9,2]];
  1427. if (schema.every(([key, value]) => !tags.has(key) || tags.get(key) === value)) {
  1428. return new onnx.ProtoReader(context, 'binary', 'tensor', offset);
  1429. }
  1430. }
  1431. // GraphProto
  1432. if (tags.get(1) === 2 && (identifier !== 'preloaded_data.pb' || tags.size !== 1)) {
  1433. 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]];
  1434. if (schema.every(([key, value]) => !tags.has(key) || tags.get(key) === value)) {
  1435. const decode = (buffer, value) => {
  1436. const reader = protobuf.BinaryReader.open(buffer);
  1437. const length = reader.length;
  1438. while (reader.position < length) {
  1439. const tag = reader.uint32();
  1440. const number = tag >>> 3;
  1441. const type = tag & 7;
  1442. if (value === number) {
  1443. return type === 2 ? reader.bytes() : null;
  1444. }
  1445. reader.skipType(type);
  1446. }
  1447. return null;
  1448. };
  1449. const stream = context.stream;
  1450. const buffer = stream.peek();
  1451. const nodeBuffer = decode(buffer, 1);
  1452. if (nodeBuffer) {
  1453. const nameBuffer = decode(nodeBuffer, 4);
  1454. if (nameBuffer && nameBuffer.every((c) => c > 0x20 && c < 0x7f)) {
  1455. return new onnx.ProtoReader(context, 'binary', 'graph', offset);
  1456. }
  1457. }
  1458. }
  1459. }
  1460. // ModelProto
  1461. if (tags.get(7) === 2) {
  1462. const schema = [[1,0],[2,2],[3,2],[4,2],[5,0],[6,2],[7,2],[8,2],[14,2],[20,2]];
  1463. if (schema.every(([key, value]) => !tags.has(key) || tags.get(key) === value)) {
  1464. return new onnx.ProtoReader(context, 'binary', 'model', offset);
  1465. }
  1466. }
  1467. }
  1468. }
  1469. const textTags = await context.tags('pbtxt');
  1470. if (textTags.size > 0) {
  1471. const tags = textTags;
  1472. if (tags.has('ir_version')) {
  1473. return new onnx.ProtoReader(context, 'text', 'model');
  1474. }
  1475. const identifier = context.identifier;
  1476. const extension = identifier.lastIndexOf('.') > 0 ? identifier.split('.').pop().toLowerCase() : '';
  1477. if (tags.has('graph') && extension !== 'model') {
  1478. return new onnx.ProtoReader(context, 'text', 'model');
  1479. }
  1480. }
  1481. const obj = await context.peek('json');
  1482. if (obj && (obj.ir_version === undefined && obj.producer_name === undefined && !Array.isArray(obj.opset_import) && !Array.isArray(obj.metadata_props)) &&
  1483. (obj.irVersion !== undefined || obj.producerName !== undefined || Array.isArray(obj.opsetImport) || Array.isArray(obj.metadataProps) || (Array.isArray(obj.graph) && Array.isArray(obj.graph.node)))) {
  1484. return new onnx.ProtoReader(context, 'json', 'model');
  1485. }
  1486. return undefined;
  1487. }
  1488. constructor(context, encoding, type, offset) {
  1489. this.name = 'onnx.proto';
  1490. this.context = context;
  1491. this.encoding = encoding;
  1492. this.type = type;
  1493. this.offset = offset || 0;
  1494. this.locations = new Map();
  1495. }
  1496. async read() {
  1497. onnx.proto = await this.context.require('./onnx-proto');
  1498. onnx.proto = onnx.proto.onnx;
  1499. const context = this.context;
  1500. switch (this.encoding) {
  1501. case 'text': {
  1502. try {
  1503. const reader = await context.read('protobuf.text');
  1504. this.model = onnx.proto.ModelProto.decodeText(reader);
  1505. this.format = `ONNX${this.model.ir_version ? ` v${this.model.ir_version}` : ''}`;
  1506. } catch (error) {
  1507. const message = error && error.message ? error.message : error.toString();
  1508. throw new onnx.Error(`File text format is not onnx.ModelProto (${message.replace(/\.$/, '')}).`);
  1509. }
  1510. break;
  1511. }
  1512. case 'json': {
  1513. try {
  1514. const obj = await context.read('json');
  1515. this.model = onnx.proto.ModelProto.decodeJson(obj);
  1516. this.format = `ONNX${this.model.ir_version ? ` v${this.model.ir_version}` : ''}`;
  1517. } catch (error) {
  1518. const message = error && error.message ? error.message : error.toString();
  1519. throw new onnx.Error(`File JSON format is not onnx.ModelProto (${message.replace(/\.$/, '')}).`);
  1520. }
  1521. break;
  1522. }
  1523. case 'binary': {
  1524. const stream = context.stream;
  1525. if (this.offset) {
  1526. stream.seek(this.offset);
  1527. }
  1528. switch (this.type) {
  1529. case 'tensor': {
  1530. // TensorProto
  1531. // input_0.pb, output_0.pb
  1532. try {
  1533. const reader = await context.read('protobuf.binary');
  1534. const tensor = onnx.proto.TensorProto.decode(reader);
  1535. tensor.name = tensor.name || this.context.identifier;
  1536. const attribute = new onnx.proto.AttributeProto();
  1537. attribute.name = 'value';
  1538. attribute.type = onnx.AttributeType.TENSOR;
  1539. attribute.t = tensor;
  1540. const node = new onnx.proto.NodeProto();
  1541. node.op_type = 'Constant';
  1542. node.attribute = [attribute];
  1543. const graph = new onnx.proto.GraphProto();
  1544. graph.node = [node];
  1545. this.model = new onnx.proto.ModelProto();
  1546. this.model.graph = graph;
  1547. this.format = 'ONNX Tensor';
  1548. } catch (error) {
  1549. const message = error && error.message ? error.message : error.toString();
  1550. throw new onnx.Error(`File format is not onnx.TensorProto (${message.replace(/\.$/, '')}).`);
  1551. }
  1552. break;
  1553. }
  1554. case 'graph': {
  1555. // GraphProto
  1556. try {
  1557. const reader = await context.read('protobuf.binary');
  1558. if (this.offset) {
  1559. stream.seek(0);
  1560. }
  1561. this.model = new onnx.proto.ModelProto();
  1562. this.model.graph = onnx.proto.GraphProto.decode(reader);
  1563. this.format = 'ONNX';
  1564. } catch (error) {
  1565. const message = error && error.message ? error.message : error.toString();
  1566. throw new onnx.Error(`File format is not onnx.GraphProto (${message.replace(/\.$/, '')}).`);
  1567. }
  1568. break;
  1569. }
  1570. case 'model': {
  1571. // ModelProto
  1572. try {
  1573. const reader = await context.read('protobuf.binary');
  1574. this.model = onnx.proto.ModelProto.decode(reader);
  1575. this.format = `ONNX${this.model.ir_version ? ` v${this.model.ir_version}` : ''}`;
  1576. } catch (error) {
  1577. const message = error && error.message ? error.message : error.toString();
  1578. throw new onnx.Error(`File format is not onnx.ModelProto (${message.replace(/\.$/, '')}).`);
  1579. }
  1580. break;
  1581. }
  1582. default: {
  1583. throw new onnx.Error('Unsupported ONNX format type.');
  1584. }
  1585. }
  1586. if (this.offset) {
  1587. stream.seek(0);
  1588. }
  1589. break;
  1590. }
  1591. default: {
  1592. throw new onnx.Error('Unsupported ONNX format encoding.');
  1593. }
  1594. }
  1595. const locations = new Set();
  1596. const location = (tensor) => {
  1597. if (onnx.proto && tensor instanceof onnx.proto.SparseTensorProto) {
  1598. location(tensor.indices);
  1599. location(tensor.values);
  1600. } else if (tensor.data_location === onnx.DataLocation.EXTERNAL && Array.isArray(tensor.external_data)) {
  1601. for (const entry of tensor.external_data) {
  1602. if (entry.key === 'location') {
  1603. locations.add(entry.value);
  1604. }
  1605. }
  1606. }
  1607. };
  1608. const model = this.model;
  1609. const queue = model.graph ? [model.graph] : [];
  1610. while (queue.length > 0) {
  1611. const graph = queue.shift();
  1612. if (Array.isArray(graph.initializer)) {
  1613. for (const initializer of graph.initializer) {
  1614. location(initializer);
  1615. }
  1616. }
  1617. if (Array.isArray(graph.sparse_initializer)) {
  1618. for (const sparse_initializer of graph.sparse_initializer) {
  1619. location(sparse_initializer);
  1620. }
  1621. }
  1622. if (Array.isArray(graph.node)) {
  1623. for (const node of graph.node) {
  1624. if (Array.isArray(node.attribute)) {
  1625. for (const attribute of node.attribute) {
  1626. if (attribute.g) {
  1627. queue.push(attribute.g);
  1628. } else if (attribute.t) {
  1629. location(attribute.t);
  1630. } else if (attribute.sparse_tensor) {
  1631. location(attribute.sparse_tensor);
  1632. } else if (Array.isArray(attribute.graphs) && attribute.graphs.length > 0) {
  1633. for (const graph of attribute.graphs) {
  1634. queue.push(graph);
  1635. }
  1636. } else if (Array.isArray(attribute.tensors) && attribute.tensors.length > 0) {
  1637. for (const tensor of attribute.tensors) {
  1638. location(tensor);
  1639. }
  1640. } else if (Array.isArray(attribute.sparse_tensors) && attribute.sparse_tensors.length > 0) {
  1641. for (const tensor of attribute.sparse_tensors) {
  1642. location(tensor);
  1643. }
  1644. }
  1645. }
  1646. }
  1647. }
  1648. }
  1649. }
  1650. for (const name of this.locations.keys()) {
  1651. locations.delete(name);
  1652. }
  1653. for (const name of locations) {
  1654. const location = new onnx.Location(this.context, name);
  1655. this.locations.set(name, location);
  1656. }
  1657. }
  1658. };
  1659. onnx.OrtReader = class {
  1660. static async open(context) {
  1661. const identifier = context.identifier;
  1662. const extension = identifier.lastIndexOf('.') > 0 ? identifier.split('.').pop().toLowerCase() : '';
  1663. const reader = await context.peek('flatbuffers.binary');
  1664. if (reader && reader.identifier === 'ORTM') {
  1665. return new onnx.OrtReader(context);
  1666. }
  1667. const stream = context.stream;
  1668. if (stream && stream.length >= 8 && extension === 'ort') {
  1669. const signature = [0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
  1670. if (signature.length <= stream.length && stream.peek(signature.length).every((value, index) => value === signature[index])) {
  1671. return new onnx.OrtReader(context);
  1672. }
  1673. }
  1674. return null;
  1675. }
  1676. constructor(context) {
  1677. this.name = 'onnx.ort';
  1678. this.context = context;
  1679. }
  1680. async read() {
  1681. onnx.schema = await this.context.require('./onnx-schema');
  1682. onnx.schema = onnx.schema.onnxruntime.fbs;
  1683. try {
  1684. this.graphs = new Set();
  1685. const reader = await this.context.read('flatbuffers.binary');
  1686. const session = onnx.schema.InferenceSession.create(reader);
  1687. this.model = session.model;
  1688. } catch (error) {
  1689. const message = error && error.message ? error.message : error.toString();
  1690. throw new onnx.Error(`File format is not ort.Model (${message.replace(/\.$/, '')}).`);
  1691. }
  1692. const tensor_shape = (value) => {
  1693. if (value && value.dim && Array.isArray(value.dim)) {
  1694. for (const dimension of value.dim) {
  1695. switch (dimension.value.dim_type) {
  1696. case 0:
  1697. return {};
  1698. case 1:
  1699. dimension.dim_value = dimension.value.dim_value;
  1700. delete dimension.value;
  1701. break;
  1702. case 2:
  1703. dimension.dim_param = dimension.value.dim_param;
  1704. delete dimension.value.dim_param;
  1705. break;
  1706. default:
  1707. throw new onnx.Error(`Unknown shape dimension '${JSON.stringify(dimension.value)}'.`);
  1708. }
  1709. }
  1710. }
  1711. return value;
  1712. };
  1713. /* eslint-disable no-use-before-define */
  1714. const node = (value) => {
  1715. value.input = value.inputs;
  1716. value.output = value.outputs;
  1717. value.attribute = value.attributes.map((attribute) => {
  1718. const type = attribute.type;
  1719. if (type === onnx.AttributeType.GRAPH) {
  1720. graph(attribute.g);
  1721. } else if (type === onnx.AttributeType.GRAPHS) {
  1722. for (const graph of attribute.graphs) {
  1723. graph(graph);
  1724. }
  1725. } else if (type === onnx.AttributeType.TYPE_PROTO) {
  1726. attribute.tp = type(attribute.tp);
  1727. } else if (type === onnx.AttributeType.TYPE_PROTOS) {
  1728. attribute.type_protos = attribute.type_protos.map((type) => type(type));
  1729. }
  1730. return attribute;
  1731. });
  1732. delete value.inputs;
  1733. delete value.outputs;
  1734. delete value.attributes;
  1735. return value;
  1736. };
  1737. const tensor_type = (value) => {
  1738. value.shape = tensor_shape(value.shape);
  1739. return value;
  1740. };
  1741. const sequence_type = (value) => {
  1742. value.shape = type(value.elem_type);
  1743. return value;
  1744. };
  1745. const map_type = (value) => {
  1746. value.value_type = type(value.value_type);
  1747. return value;
  1748. };
  1749. /* eslint-enable no-use-before-define */
  1750. const type = (value) => {
  1751. if (value) {
  1752. const type = value.value;
  1753. if (type && type instanceof onnx.schema.TensorTypeAndShape) {
  1754. value.tensor_type = tensor_type(type);
  1755. return value;
  1756. }
  1757. if (type && type instanceof onnx.schema.SequenceType) {
  1758. value.sequence_type = sequence_type(type);
  1759. return value;
  1760. }
  1761. if (type && type instanceof onnx.schema.MapType) {
  1762. value.map_type = map_type(type);
  1763. return value;
  1764. }
  1765. throw new onnx.Error(`Unsupported type value '${JSON.stringify(value.value)}`);
  1766. }
  1767. return null;
  1768. };
  1769. const graph = (value) => {
  1770. if (this.graphs.has(value)) {
  1771. return;
  1772. }
  1773. this.graphs.add(value);
  1774. value.name = this.graphs.size.toString();
  1775. value.node = value.nodes.map((value) => node(value));
  1776. delete value.nodes;
  1777. value.value_info = value.node_args.map((arg) => {
  1778. return {
  1779. name: arg.name,
  1780. doc_string: arg.doc_string,
  1781. type: type(arg.type)
  1782. };
  1783. });
  1784. delete value.node_args;
  1785. const value_info = new Map(value.value_info.map((entry) => [entry.name, entry]));
  1786. value.input = value.inputs.map((input) => {
  1787. return value_info.has(input) ? value_info.get(input) : { name: input };
  1788. });
  1789. delete value.inputs;
  1790. value.output = value.outputs.map((output) => {
  1791. return value_info.has(output) ? value_info.get(output) : { name: output };
  1792. });
  1793. delete value.outputs;
  1794. value.initializer = value.initializers.map((tensor) => {
  1795. tensor.data_location = onnx.DataLocation.DEFAULT;
  1796. return tensor;
  1797. });
  1798. delete value.initializers;
  1799. value.sparse_initializer = value.sparse_initializers.map((tensor) => {
  1800. tensor.values.data_location = onnx.DataLocation.DEFAULT;
  1801. tensor.indices.data_location = onnx.DataLocation.DEFAULT;
  1802. return tensor;
  1803. });
  1804. delete value.sparse_initializers;
  1805. };
  1806. graph(this.model.graph);
  1807. this.model.graph.doc_string = this.model.graph_doc_string;
  1808. delete this.model.graph_doc_string;
  1809. this.format = `ONNX Runtime${this.model.ir_version ? ` v${this.model.ir_version}` : ''}`;
  1810. }
  1811. };
  1812. onnx.JsonReader = class {
  1813. static async open(context) {
  1814. const obj = await context.peek('json');
  1815. if (obj && obj.framework === undefined && obj.graph &&
  1816. (obj.ir_version !== undefined || obj.producer_name !== undefined || Array.isArray(obj.opset_import))) {
  1817. return new onnx.JsonReader(obj);
  1818. }
  1819. return null;
  1820. }
  1821. constructor(obj) {
  1822. this.name = 'onnx.json';
  1823. this.model = obj;
  1824. }
  1825. async read() {
  1826. this.model = this._model(this.model);
  1827. this.format = `ONNX JSON${this.model.ir_version ? ` v${this.model.ir_version}` : ''}`;
  1828. }
  1829. _tensor(value) {
  1830. value.dims = Array.isArray(value.dims) ? value.dims : [];
  1831. if (value.raw_data !== undefined) {
  1832. if (value.raw_data && value.raw_data instanceof Uint8Array === false && value.raw_data.type === 'Buffer' && Array.isArray(value.raw_data.data)) {
  1833. value.data_location = onnx.DataLocation.DEFAULT;
  1834. value.raw_data = new Uint8Array(value.raw_data.data);
  1835. }
  1836. } else if ((Array.isArray(value.float_data) && value.float_data.length > 0) ||
  1837. (Array.isArray(value.int32_data) && value.int32_data.length > 0) ||
  1838. (Array.isArray(value.int64_data) && value.int64_data.length > 0)) {
  1839. value.data_location = onnx.DataLocation.DEFAULT;
  1840. } else {
  1841. throw new onnx.Error(`Unsupported ONNX JSON tensor data type '${JSON.stringify(value.data_type)}'.`);
  1842. }
  1843. return value;
  1844. }
  1845. _sparse_tensor(value) {
  1846. value.indices = this._tensor(value.indices);
  1847. value.values = this._tensor(value.values);
  1848. return value;
  1849. }
  1850. _attribute(value) {
  1851. if (value.ref_attr_name) {
  1852. value.ref_attr_name = value.ref_attr_name.toString();
  1853. } else if (value.type === onnx.AttributeType.FLOATS || (Array.isArray(value.floats) && value.floats.length > 0)) {
  1854. value.floats = value.floats.map((value) => parseFloat(value));
  1855. } else if (value.type === onnx.AttributeType.INTS || (Array.isArray(value.ints) && value.ints.length > 0)) {
  1856. value.ints = value.ints.map((value) => parseInt(value, 10));
  1857. } else if (value.type === onnx.AttributeType.STRINGS || (Array.isArray(value.strings) && value.strings.length > 0)) {
  1858. value.strings = value.strings.map((value) => atob(value));
  1859. } else if (value.type === onnx.AttributeType.TENSORS || (Array.isArray(value.tensors) && value.tensors.length > 0)) {
  1860. value.tensors = value.tensors.map((value) => this._tensor(value));
  1861. } else if (value.type === onnx.AttributeType.GRAPHS || (Array.isArray(value.graphs) && value.graphs.length > 0)) {
  1862. value.graphs = value.graphs.map((value) => this._graph(value));
  1863. } else if (value.type === onnx.AttributeType.SPARSE_TENSORS || (Array.isArray(value.sparse_tensors) && value.sparse_tensors.length > 0)) {
  1864. value.sparse_tensors = value.sparse_tensors.map((item) => this._sparse_tensor(item));
  1865. } else if (value.type === onnx.AttributeType.FLOAT || value.f !== undefined) {
  1866. // continue
  1867. } else if (value.type === onnx.AttributeType.INT || value.i !== undefined) {
  1868. // continue
  1869. } else if (value.type === onnx.AttributeType.STRING || value.s !== undefined) {
  1870. value.s = atob(value.s);
  1871. } else if (value.type === onnx.AttributeType.TENSOR || value.t !== undefined) {
  1872. value.t = this._tensor(value.t);
  1873. } else if (value.type === onnx.AttributeType.GRAPH || value.g !== undefined) {
  1874. value.g = this._graph(value.g);
  1875. } else if (value.type === onnx.AttributeType.SPARSE_TENSOR || value.sparse_tensor !== undefined) {
  1876. value.sparse_tensor = this._sparse_tensor(value.sparse_tensor);
  1877. } else {
  1878. throw new onnx.Error(`Unsupported ONNX JSON attribute type '${JSON.stringify(value.type)}'.`);
  1879. }
  1880. return value;
  1881. }
  1882. _node(value) {
  1883. value.input = Array.isArray(value.input) ? value.input : [];
  1884. value.output = Array.isArray(value.output) ? value.output : [];
  1885. value.attribute = Array.isArray(value.attribute) ? value.attribute.map((value) => this._attribute(value)) : [];
  1886. return value;
  1887. }
  1888. _graph(value) {
  1889. value.node = value.node.map((value) => this._node(value));
  1890. value.initializer = Array.isArray(value.initializer) ? value.initializer.map((value) => this._tensor(value)) : [];
  1891. value.sparse_initializer = Array.isArray(value.sparse_initializer) ? value.sparse_initializer.map((item) => this._sparse_tensor(item)) : [];
  1892. value.input = Array.isArray(value.input) ? value.input : [];
  1893. value.output = Array.isArray(value.output) ? value.output : [];
  1894. return value;
  1895. }
  1896. _function(value) {
  1897. value.node = value.node.map((value) => this._node(value));
  1898. value.input = Array.isArray(value.input) ? value.input : [];
  1899. value.output = Array.isArray(value.output) ? value.output : [];
  1900. value.attribute = Array.isArray(value.attribute) ? value.attribute : [];
  1901. value.attribute_proto = Array.isArray(value.attribute_proto) ? value.attribute_proto.map((value) => this._attribute(value)) : [];
  1902. return value;
  1903. }
  1904. _model(value) {
  1905. value.graph = this._graph(value.graph);
  1906. value.functions = Array.isArray(value.functions) ? value.functions.map((item) => this._function(item)) : [];
  1907. return value;
  1908. }
  1909. };
  1910. onnx.TextReader = class {
  1911. static async open(context) {
  1912. const extension = context.identifier.split('.').pop().toLowerCase();
  1913. const extensions = new Set(['onnx', 'bin', 'data', 'onnxmodel', 'pt', 'pth']);
  1914. if (!extensions.has(extension)) {
  1915. try {
  1916. const stream = context.stream;
  1917. if (stream && stream.length > 2) {
  1918. const buffer = stream.peek(2);
  1919. if (buffer[0] < 0x80 || buffer[0] >= 0xFE) {
  1920. const reader = await context.read('text', 0x10000);
  1921. const lines = [];
  1922. for (let i = 0; i < 32; i++) {
  1923. const line = reader.read('\n');
  1924. if (line === undefined) {
  1925. break;
  1926. }
  1927. lines.push(line);
  1928. }
  1929. const content = lines.join('\n');
  1930. if (/^\s*<\s*ir_version\s*:/m.exec(content) ||
  1931. /^\s*[a-zA-Z][a-zA-Z0-9]*\s*\(.*\)\s=>\s\(/m.exec(content)) {
  1932. return new onnx.TextReader(context);
  1933. }
  1934. }
  1935. }
  1936. } catch {
  1937. // continue regardless of error
  1938. }
  1939. }
  1940. return null;
  1941. }
  1942. constructor(context) {
  1943. this.name = 'onnx.text';
  1944. this._context = context;
  1945. this._dataTypes = new Map(Object.entries(onnx.DataType).map(([key, value]) => [key.toLowerCase(), value]));
  1946. this._attributeTypes = new Map(Object.entries(onnx.AttributeType).map(([key, value]) => [key.toLowerCase(), value]));
  1947. }
  1948. async read() {
  1949. onnx.proto = await this._context.require('./onnx-proto');
  1950. onnx.proto = onnx.proto.onnx;
  1951. try {
  1952. this._decoder = await this._context.read('text.decoder');
  1953. this._position = 0;
  1954. this._char = this._decoder.decode();
  1955. this.model = this._parseModel();
  1956. this.format = 'ONNX Text';
  1957. if (this.model.ir_version !== undefined) {
  1958. const version = typeof this.model.ir_version === 'bigint' ? this.model.ir_version.toNumber() : this.model.ir_version;
  1959. this.format += ` v${version}`;
  1960. }
  1961. delete this._decoder;
  1962. delete this._position;
  1963. delete this._char;
  1964. } catch (error) {
  1965. const message = error && error.message ? error.message : error.toString();
  1966. throw new onnx.Error(`File format is not onnx.ModelProto (${message.replace(/\.$/, '')}).`);
  1967. }
  1968. }
  1969. _seek(position) {
  1970. this._decoder.position = position;
  1971. this._char = '';
  1972. this._next();
  1973. }
  1974. _parseModel() {
  1975. this._skipWhitespace();
  1976. const model = new onnx.proto.ModelProto();
  1977. if (this._match('<')) {
  1978. do {
  1979. const keyword = this._parseIdentifier();
  1980. this._expect(':');
  1981. switch (keyword) {
  1982. case 'ir_version':
  1983. case 'model_version':
  1984. model[keyword] = this._parseInteger();
  1985. break;
  1986. case 'opset_import':
  1987. model[keyword] = this._parseOperatorSetId();
  1988. break;
  1989. case 'producer_name':
  1990. case 'producer_version':
  1991. case 'domain':
  1992. case 'doc_string':
  1993. model[keyword] = this._parseString();
  1994. break;
  1995. case 'metadata_props':
  1996. this._expect('[');
  1997. if (!this._match(']')) {
  1998. do {
  1999. const entry = new onnx.proto.StringStringEntryProto();
  2000. entry.key = this._parseString();
  2001. this._expect(':');
  2002. entry.value = this._parseString();
  2003. model.metadata_props.push(entry);
  2004. } while (this._match(','));
  2005. this._expect(']');
  2006. }
  2007. break;
  2008. default:
  2009. this._throw(`Unknown keyword '${keyword}'.`);
  2010. break;
  2011. }
  2012. } while (this._match(','));
  2013. this._expect('>');
  2014. }
  2015. model.graph = this._parseGraph();
  2016. this._skipWhitespace();
  2017. while (this._char !== undefined) {
  2018. const func = this._parseFunction();
  2019. if (func) {
  2020. model.functions.push(func);
  2021. }
  2022. this._skipWhitespace();
  2023. }
  2024. return model;
  2025. }
  2026. _parseGraph() {
  2027. const graph = new onnx.proto.GraphProto();
  2028. graph.name = this._parseIdentifier();
  2029. if (this._match('(')) {
  2030. if (!this._match(')')) {
  2031. do {
  2032. const valueInfo = this._parseValueInfo();
  2033. if (this._match('=')) {
  2034. const tensor = this._parseTensor(valueInfo.type);
  2035. tensor.name = valueInfo.name;
  2036. graph.initializer.push(tensor);
  2037. }
  2038. graph.input.push(valueInfo);
  2039. }
  2040. while (this._match(','));
  2041. this._expect(')');
  2042. }
  2043. }
  2044. this._expect('=>');
  2045. graph.output = this._parseValueInfoList();
  2046. if (this._match('<')) {
  2047. if (!this._match('>')) {
  2048. do {
  2049. const valueInfo = this._parseValueInfo();
  2050. if (this._match('=')) {
  2051. const tensor = this._parseTensor(valueInfo.type);
  2052. tensor.name = valueInfo.name;
  2053. graph.initializer.push(tensor);
  2054. } else {
  2055. graph.value_info.push(valueInfo);
  2056. }
  2057. }
  2058. while (this._match(','));
  2059. this._expect('>');
  2060. }
  2061. }
  2062. graph.node = this._parseNodeList();
  2063. return graph;
  2064. }
  2065. _parseNodeList() {
  2066. const list = [];
  2067. this._expect('{');
  2068. while (!this._match('}')) {
  2069. list.push(this._parseNode());
  2070. }
  2071. return list;
  2072. }
  2073. _parseNode() {
  2074. const node = new onnx.proto.NodeProto();
  2075. node.output = this._parseIdentifierList();
  2076. this._expect('=');
  2077. let identifier = this._parseIdentifier();
  2078. let domain = '';
  2079. while (this._match('.')) {
  2080. if (domain) {
  2081. domain += '.';
  2082. }
  2083. domain += identifier;
  2084. identifier = this._parseIdentifier();
  2085. }
  2086. node.domain = domain;
  2087. node.op_type = identifier;
  2088. if (this._match(':')) {
  2089. node.overload = this._parseIdentifier();
  2090. }
  2091. node.attribute = this._parseAttributeList();
  2092. this._expect('(');
  2093. node.input = this._parseIdentifierList();
  2094. this._expect(')');
  2095. if (!node.attribute || node.attribute.length === 0) {
  2096. node.attribute = this._parseAttributeList();
  2097. }
  2098. return node;
  2099. }
  2100. _parseAttributeList() {
  2101. const list = [];
  2102. if (this._match('<')) {
  2103. do {
  2104. list.push(this._parseAttribute());
  2105. }
  2106. while (this._match(','));
  2107. this._expect('>');
  2108. }
  2109. return list;
  2110. }
  2111. _parseAttribute() {
  2112. const attribute = new onnx.proto.AttributeProto();
  2113. attribute.name = this._parseIdentifier();
  2114. if (this._match(':')) {
  2115. const type = this._parseIdentifier();
  2116. if (!this._attributeTypes.has(type)) {
  2117. this._throw(`Unexpected attribute type '${type}'.`);
  2118. }
  2119. attribute.type = this._attributeTypes.get(type);
  2120. }
  2121. this._expect('=');
  2122. if (this._match('[')) {
  2123. if (this._match(']')) {
  2124. if (attribute.type === onnx.AttributeType.UNDEFINED) {
  2125. this._throw('Empty list attribute value requires type annotation.');
  2126. }
  2127. switch (attribute.type) {
  2128. case onnx.AttributeType.FLOAT:
  2129. case onnx.AttributeType.INT:
  2130. case onnx.AttributeType.STRING:
  2131. case onnx.AttributeType.TENSOR:
  2132. case onnx.AttributeType.GRAPH:
  2133. case onnx.AttributeType.SPARSE_TENSOR:
  2134. case onnx.AttributeType.TYPE_PROTO:
  2135. this._throw("Singleton attribute value cannot be specified as a list.");
  2136. break;
  2137. default:
  2138. break;
  2139. }
  2140. } else {
  2141. do {
  2142. const value = new onnx.proto.AttributeProto();
  2143. let type = onnx.AttributeType.UNDEFINED;
  2144. switch (attribute.type) {
  2145. case onnx.AttributeType.FLOATS: type = onnx.AttributeType.FLOAT; break;
  2146. case onnx.AttributeType.INTS: type = onnx.AttributeType.INT; break;
  2147. case onnx.AttributeType.STRINGS: type = onnx.AttributeType.STRING; break;
  2148. case onnx.AttributeType.TENSORS: type = onnx.AttributeType.TENSOR; break;
  2149. case onnx.AttributeType.GRAPHS: type = onnx.AttributeType.GRAPH; break;
  2150. case onnx.AttributeType.SPARSE_TENSORS: type = onnx.AttributeType.SPARSE_TENSOR; break;
  2151. case onnx.AttributeType.TYPE_PROTOS: type = onnx.AttributeType.TYPE_PROTO; break;
  2152. default: type = attribute.type; break;
  2153. }
  2154. this._parseAttributeValue(value, type);
  2155. switch (value.type) {
  2156. case onnx.AttributeType.INT:
  2157. attribute.type = onnx.AttributeType.INTS;
  2158. attribute.ints.push(value.i);
  2159. break;
  2160. case onnx.AttributeType.FLOAT:
  2161. attribute.type = onnx.AttributeType.FLOATS;
  2162. attribute.floats.push(value.f);
  2163. break;
  2164. case onnx.AttributeType.STRING:
  2165. attribute.type = onnx.AttributeType.STRINGS;
  2166. attribute.strings.push(value.s);
  2167. break;
  2168. default:
  2169. break;
  2170. }
  2171. }
  2172. while (this._match(','));
  2173. }
  2174. this._expect(']');
  2175. } else {
  2176. this._parseAttributeValue(attribute, attribute.type);
  2177. }
  2178. return attribute;
  2179. }
  2180. _parseAttributeValue(attribute, type) {
  2181. if (this._isAlpha(this._char) || this._char === '_') {
  2182. const identifier = this._peekIdentifier();
  2183. if (this._isType(identifier)) {
  2184. const type = this._parseType(this._parseIdentifier());
  2185. if (!type.tensor_type.elem_type) {
  2186. this._throw('Expected tensor data type.');
  2187. }
  2188. if (!type.tensor_type.shape || !type.tensor_type.shape.dim) {
  2189. this._throw('Expected tensor shape.');
  2190. }
  2191. this._skipWhitespace();
  2192. if (this._char === '{' || this._char === '=' || this._peekIdentifier()) {
  2193. attribute.type = onnx.AttributeType.TENSOR;
  2194. const name = this._parseIdentifier(true);
  2195. this._match('=');
  2196. attribute.t = this._parseTensor(type);
  2197. if (name) {
  2198. attribute.t.name = name;
  2199. }
  2200. } else {
  2201. attribute.type = onnx.AttributeType.TYPE_PROTO;
  2202. attribute.tp = type;
  2203. }
  2204. } else {
  2205. const value = this._peekIdentifier();
  2206. if (value === 'inf' || value === 'infinity' || value === 'nan') {
  2207. attribute.type = onnx.AttributeType.FLOAT;
  2208. attribute.f = this._parseLiteral();
  2209. } else {
  2210. attribute.type = onnx.AttributeType.GRAPH;
  2211. attribute.g = this._parseGraph();
  2212. }
  2213. }
  2214. } else if (this._match('@')) {
  2215. attribute.ref_attr_name = this._parseIdentifier();
  2216. } else {
  2217. const value = this._parseLiteral();
  2218. switch (typeof value) {
  2219. case 'number':
  2220. if (Number.isInteger(value)) {
  2221. attribute.type = onnx.AttributeType.INT;
  2222. attribute.i = value;
  2223. } else {
  2224. attribute.type = onnx.AttributeType.FLOAT;
  2225. attribute.f = value;
  2226. }
  2227. break;
  2228. case 'string':
  2229. attribute.type = onnx.AttributeType.STRING;
  2230. attribute.s = value;
  2231. break;
  2232. default: {
  2233. this._throw(`Unexpected value '${JSON.stringify(value)}'.`);
  2234. }
  2235. }
  2236. }
  2237. if (type !== onnx.AttributeType.UNDEFINED && type !== attribute.type) {
  2238. if (type === onnx.AttributeType.FLOAT && attribute.type === onnx.AttributeType.INT) {
  2239. attribute.type = onnx.AttributeType.FLOAT;
  2240. attribute.f = attribute.i;
  2241. delete attribute.i;
  2242. } else {
  2243. this._throw('Attribute type mismatch.');
  2244. }
  2245. }
  2246. }
  2247. _parseValueInfoList() {
  2248. const list = [];
  2249. this._expect('(');
  2250. if (!this._match(')')) {
  2251. do {
  2252. const value = this._parseValueInfo();
  2253. list.push(value);
  2254. } while (this._match(','));
  2255. this._expect(')');
  2256. }
  2257. return list;
  2258. }
  2259. _parseValueInfo() {
  2260. const valueInfo = new onnx.proto.ValueInfoProto();
  2261. let identifier = this._parseIdentifier();
  2262. if (this._isType(identifier)) {
  2263. valueInfo.type = this._parseType(identifier);
  2264. identifier = this._parseIdentifier();
  2265. }
  2266. valueInfo.name = identifier;
  2267. return valueInfo;
  2268. }
  2269. _parseType(elem_type) {
  2270. const type = new onnx.proto.TypeProto();
  2271. type.tensor_type = new onnx.proto.TypeProto.Tensor();
  2272. type.tensor_type.elem_type = this._dataTypes.get(elem_type);
  2273. if (this._match('[')) {
  2274. if (!this._match(']')) {
  2275. type.tensor_type.shape = this._parseTensorShape();
  2276. this._expect(']');
  2277. }
  2278. } else {
  2279. type.tensor_type.shape = new onnx.proto.TensorShapeProto();
  2280. }
  2281. return type;
  2282. }
  2283. _parseTensorShape() {
  2284. const shape = new onnx.proto.TensorShapeProto();
  2285. do {
  2286. const dimension = new onnx.proto.TensorShapeProto.Dimension();
  2287. if (!this._match('?')) {
  2288. const identifier = this._parseIdentifier(true);
  2289. if (identifier) {
  2290. dimension.dim_param = identifier;
  2291. } else {
  2292. dimension.dim_value = this._parseInteger();
  2293. }
  2294. }
  2295. shape.dim.push(dimension);
  2296. }
  2297. while (this._match(','));
  2298. return shape;
  2299. }
  2300. _parseTensor(type) {
  2301. const tensor = new onnx.proto.TensorProto();
  2302. if (!type.tensor_type || !type.tensor_type.elem_type) {
  2303. this._throw('Expected tensor type.');
  2304. }
  2305. if (!type.tensor_type.shape || !type.tensor_type.shape.dim || !type.tensor_type.shape.dim.every((dim) => dim.dim_value)) {
  2306. this._throw('Expected numeric tensor shape.');
  2307. }
  2308. const elem_type = type.tensor_type.elem_type;
  2309. tensor.data_type = elem_type;
  2310. tensor.dims = type.tensor_type.shape.dim.map((dim) => dim.dim_value);
  2311. this._match('=');
  2312. this._expect('{');
  2313. if (!this._match('}')) {
  2314. do {
  2315. switch (elem_type) {
  2316. case onnx.DataType.INT8:
  2317. case onnx.DataType.INT16:
  2318. case onnx.DataType.INT32:
  2319. case onnx.DataType.UINT8:
  2320. case onnx.DataType.UINT16:
  2321. case onnx.DataType.BOOL:
  2322. tensor.int32_data.push(this._parseInteger());
  2323. break;
  2324. case onnx.DataType.INT64:
  2325. tensor.int64_data.push(this._parseInteger());
  2326. break;
  2327. case onnx.DataType.UINT32:
  2328. case onnx.DataType.UINT64:
  2329. tensor.uint64_data.push(this._parseInteger());
  2330. break;
  2331. case onnx.DataType.FLOAT:
  2332. tensor.float_data.push(this._parseFloat());
  2333. break;
  2334. case onnx.DataType.DOUBLE:
  2335. tensor.double_data.push(this._parseFloat());
  2336. break;
  2337. case onnx.DataType.STRING:
  2338. tensor.string_data.push(this.string());
  2339. break;
  2340. default:
  2341. return this._throw(`Unsupported tensor element type '${elem_type}'.`);
  2342. }
  2343. } while (this._match(','));
  2344. this._expect('}');
  2345. }
  2346. return tensor;
  2347. }
  2348. _parseFunction() {
  2349. const func = new onnx.proto.FunctionProto();
  2350. if (this._match('<')) {
  2351. do {
  2352. const keyword = this._parseIdentifier();
  2353. this._expect(':');
  2354. switch (keyword) {
  2355. case 'opset_import':
  2356. func[keyword] = this._parseOperatorSetId();
  2357. break;
  2358. case 'domain':
  2359. case 'doc_string':
  2360. func[keyword] = this._parseString();
  2361. break;
  2362. case 'overload':
  2363. func[keyword] = this._parseString();
  2364. break;
  2365. default:
  2366. this._throw(`Unknown keyword '${keyword}'.`);
  2367. break;
  2368. }
  2369. }
  2370. while (this._match(','));
  2371. this._expect('>');
  2372. }
  2373. func.name = this._parseIdentifier();
  2374. if (this._match('<')) {
  2375. func.attribute = this._parseIdentifierList();
  2376. this._expect('>');
  2377. }
  2378. if (this._match('(')) {
  2379. func.input = this._parseIdentifierList();
  2380. this._expect(')');
  2381. }
  2382. this._expect('=>');
  2383. if (this._match('(')) {
  2384. func.output = this._parseIdentifierList();
  2385. this._expect(')');
  2386. }
  2387. func.node = this._parseNodeList();
  2388. return func;
  2389. }
  2390. _parseIdentifierList() {
  2391. const list = [];
  2392. const identifier = this._parseIdentifier(true);
  2393. if (identifier) {
  2394. list.push(identifier);
  2395. while (this._match(',')) {
  2396. list.push(this._parseIdentifier());
  2397. }
  2398. }
  2399. return list;
  2400. }
  2401. _peekIdentifier() {
  2402. const index = this._decoder.position;
  2403. const position = this._position;
  2404. const char = this._char;
  2405. const value = this._parseIdentifier(true);
  2406. this._char = char;
  2407. this._position = position;
  2408. this._decoder.position = index;
  2409. return value;
  2410. }
  2411. _parseIdentifier(optional) {
  2412. this._skipWhitespace();
  2413. const value = [];
  2414. if (this._isAlpha(this._char) || this._char === '_') {
  2415. value.push(this._char);
  2416. this._next();
  2417. while (this._isAlpha(this._char) || (this._char >= '0' && this._char <= '9') || this._char === '_') {
  2418. value.push(this._char);
  2419. this._next();
  2420. }
  2421. }
  2422. if (!optional && value.length === 0) {
  2423. this._throw('Identifier expected.');
  2424. }
  2425. return value.join('');
  2426. }
  2427. _parseLiteral() {
  2428. this._skipWhitespace();
  2429. let decimal_point = false;
  2430. if (this._char === '"') {
  2431. const value = [];
  2432. this._next();
  2433. while (this._char !== undefined && this._char !== '"') {
  2434. value.push(this._char);
  2435. this._next();
  2436. }
  2437. if (this._char !== undefined) {
  2438. this._next();
  2439. }
  2440. return value.join('');
  2441. } else if ((this._char >= '0' && this._char <= '9') || this._char === '-') {
  2442. const value = [this._char];
  2443. this._next();
  2444. while ((this._char >= '0' && this._char <= '9') || this._char === '.') {
  2445. if (this._char === '.') {
  2446. if (decimal_point) {
  2447. this._throw();
  2448. }
  2449. decimal_point = true;
  2450. }
  2451. value.push(this._char);
  2452. this._next();
  2453. }
  2454. if (value.length === 0) {
  2455. this._throw('Value expected.');
  2456. }
  2457. if (this._char === 'e' || this._char === 'E') {
  2458. decimal_point = true;
  2459. value.push(this._char);
  2460. this._next();
  2461. if (this._char === '+' || this._char === '-') {
  2462. value.push(this._char);
  2463. this._next();
  2464. }
  2465. while ((this._char >= '0' && this._char <= '9')) {
  2466. value.push(this._char);
  2467. this._next();
  2468. }
  2469. }
  2470. return decimal_point ? Number.parseFloat(value.join('')) : Number.parseInt(value.join(''), 10);
  2471. }
  2472. return undefined;
  2473. }
  2474. _parseInteger() {
  2475. const value = this._parseLiteral();
  2476. if (!Number.isInteger(value)) {
  2477. this._throw('Integer value expected.');
  2478. }
  2479. return value;
  2480. }
  2481. _parseFloat() {
  2482. const value = this._parseLiteral();
  2483. if (typeof value !== 'number') {
  2484. this._throw('Float value expected.');
  2485. }
  2486. return value;
  2487. }
  2488. _parseString() {
  2489. const value = this._parseLiteral();
  2490. if (typeof value !== 'string') {
  2491. this._throw('String value expected.');
  2492. }
  2493. return value;
  2494. }
  2495. _parseOperatorSetId() {
  2496. const list = [];
  2497. this._expect('[');
  2498. if (!this._match(']')) {
  2499. do {
  2500. const value = new onnx.proto.OperatorSetIdProto();
  2501. value.domain = this._parseString();
  2502. this._expect(':');
  2503. value.version = this._parseInteger();
  2504. list.push(value);
  2505. }
  2506. while (this._match(','));
  2507. this._expect(']');
  2508. }
  2509. return list;
  2510. }
  2511. _isAlpha(value) {
  2512. return (value >= 'a' && value <= 'z') || (value >= 'A' && value <= 'Z');
  2513. }
  2514. _isType(identifier) {
  2515. return this._dataTypes.has(identifier) ||
  2516. identifier === 'seq' ||
  2517. identifier === 'map' ||
  2518. identifier === 'optional' ||
  2519. identifier === 'sparse_tensor';
  2520. }
  2521. _match(value) {
  2522. this._skipWhitespace();
  2523. if (this._char !== value[0]) {
  2524. return false;
  2525. }
  2526. if (value.length === 1) {
  2527. this._next();
  2528. return true;
  2529. }
  2530. const position = this._position;
  2531. for (let i = 0; i < value.length; i++) {
  2532. if (this._char !== value[i]) {
  2533. this._seek(position);
  2534. return false;
  2535. }
  2536. this._next();
  2537. }
  2538. return true;
  2539. }
  2540. _expect(value) {
  2541. if (!this._match(value)) {
  2542. this._unexpected();
  2543. }
  2544. return true;
  2545. }
  2546. _skipWhitespace() {
  2547. for (;;) {
  2548. while (this._char === ' ' || this._char === '\n' || this._char === '\r' || this._char === '\t') {
  2549. this._next();
  2550. }
  2551. if (this._char === undefined || this._char !== '#') {
  2552. break;
  2553. }
  2554. while (this._char !== undefined && this._char !== '\n') {
  2555. this._next();
  2556. }
  2557. }
  2558. }
  2559. _next() {
  2560. if (this._char === undefined) {
  2561. this._unexpected();
  2562. }
  2563. this._position = this._decoder.position;
  2564. this._char = this._decoder.decode();
  2565. }
  2566. _unexpected() {
  2567. let c = this._char;
  2568. if (c === undefined) {
  2569. throw new onnx.Error('Unexpected end of input.');
  2570. } else if (c === '"') {
  2571. c = 'string';
  2572. } else if ((c >= '0' && c <= '9') || c === '-') {
  2573. c = 'number';
  2574. } else {
  2575. if (c < ' ' || c > '\x7F') {
  2576. const name = Object.keys(this._escape).filter((key) => this._escape[key] === c);
  2577. c = (name.length === 1) ? `\\${name}` : `\\u${(`000${c.charCodeAt(0).toString(16)}`).slice(-4)}`;
  2578. }
  2579. c = `token '${c}'`;
  2580. }
  2581. this._throw(`Unexpected ${c}`);
  2582. }
  2583. _throw(message) {
  2584. message = message.replace(/\.$/, '');
  2585. throw new onnx.Error(`${message} ${this._location()}`);
  2586. }
  2587. _location() {
  2588. let line = 1;
  2589. let column = 1;
  2590. this._decoder.position = 0;
  2591. let c = '';
  2592. do {
  2593. if (this._decoder.position === this._position) {
  2594. return `at ${line}:${column}.`;
  2595. }
  2596. c = this._decoder.decode();
  2597. if (c === '\n') {
  2598. line++;
  2599. column = 1;
  2600. } else {
  2601. column++;
  2602. }
  2603. }
  2604. while (c !== undefined);
  2605. return `at ${line}:${column}.`;
  2606. }
  2607. };
  2608. onnx.PickleReader = class {
  2609. static async open(context) {
  2610. const identifier = context.identifier;
  2611. const extension = identifier.lastIndexOf('.') > 0 ? identifier.split('.').pop().toLowerCase() : '';
  2612. const stream = context.stream;
  2613. if (extension === 'onnx' && stream && stream.length > 3) {
  2614. const signature = stream.peek(2);
  2615. if (signature[0] === 0x80 && signature[1] < 7) {
  2616. return new onnx.PickleReader();
  2617. }
  2618. }
  2619. return null;
  2620. }
  2621. constructor() {
  2622. this.name = 'onnx.pickle';
  2623. }
  2624. async read() {
  2625. throw new onnx.Error('Unsupported Pickle content.');
  2626. }
  2627. };
  2628. onnx.DataReader = class {
  2629. static async open(context) {
  2630. const identifier = context.identifier.toLowerCase();
  2631. if (identifier.endsWith('.onnx_data') || identifier.endsWith('.onnx.data')) {
  2632. return new onnx.DataReader(context, identifier);
  2633. }
  2634. return null;
  2635. }
  2636. constructor(context, identifier) {
  2637. this.name = 'onnx.data';
  2638. this.context = context;
  2639. this.identifier = identifier;
  2640. this.locations = new Map();
  2641. this.locations.set(identifier, context.stream);
  2642. }
  2643. async read() {
  2644. const file = this.identifier.substring(0, this.identifier.length - 5);
  2645. const context = await this.context.fetch(file);
  2646. const reader = new onnx.ProtoReader(context, 'binary', 'model');
  2647. reader.locations = this.locations;
  2648. await reader.read();
  2649. this.format = reader.format;
  2650. this.model = reader.model;
  2651. }
  2652. };
  2653. onnx.MetaReader = class {
  2654. static async open(context) {
  2655. const identifier = context.identifier.toLowerCase();
  2656. if (identifier.endsWith('.onnx.meta')) {
  2657. const stream = context.stream;
  2658. const buffer = context.stream.peek(Math.min(stream.length, 32));
  2659. const content = String.fromCharCode.apply(null, buffer);
  2660. if (content.startsWith('fileFormatVersion:') || content.startsWith('- !<AssetImportMetadata/')) {
  2661. return new onnx.MetaReader(context, identifier);
  2662. }
  2663. }
  2664. return null;
  2665. }
  2666. constructor(context, identifier) {
  2667. this.name = 'onnx.meta';
  2668. this.context = context;
  2669. this.identifier = identifier;
  2670. this.locations = new Map();
  2671. }
  2672. async read() {
  2673. const file = this.identifier.substring(0, this.identifier.length - 5);
  2674. const context = await this.context.fetch(file);
  2675. const reader = new onnx.ProtoReader(context, 'binary', 'model');
  2676. reader.locations = this.locations;
  2677. await reader.read();
  2678. this.format = reader.format;
  2679. this.model = reader.model;
  2680. }
  2681. };
  2682. onnx.Location = class {
  2683. constructor(context, name) {
  2684. this.context = context;
  2685. this.name = name;
  2686. this.content = new Map();
  2687. }
  2688. async read(offset, length) {
  2689. const key = `${offset}:${length}`;
  2690. if (this.content.has(key)) {
  2691. return this.content.get(key);
  2692. }
  2693. if (!this.promise) {
  2694. this.promise = this.context.fetch(this.name);
  2695. }
  2696. return this.promise.then((content) => {
  2697. const stream = content.stream;
  2698. const position = stream.position;
  2699. stream.seek(offset);
  2700. length = length === -1 ? stream.length - offset : length;
  2701. content = stream.stream(length);
  2702. stream.seek(position);
  2703. this.content.set(key, content);
  2704. return content;
  2705. }).catch(() => {
  2706. return null;
  2707. });
  2708. }
  2709. };
  2710. onnx.Error = class extends Error {
  2711. constructor(message) {
  2712. super(message);
  2713. this.name = 'Error loading ONNX model.';
  2714. }
  2715. };
  2716. export const ModelFactory = onnx.ModelFactory;