onnx.js 109 KB

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