pytorch.js 119 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604
  1. // Experimental
  2. import * as base from './base.js';
  3. import * as flatbuffers from './flatbuffers.js';
  4. import * as python from './python.js';
  5. const pytorch = {};
  6. const numpy = {};
  7. pytorch.ModelFactory = class {
  8. async match(context) {
  9. const container = await pytorch.Container.open(context);
  10. if (container) {
  11. return context.set(container.type, container);
  12. }
  13. return null;
  14. }
  15. filter(context, match) {
  16. if (context.type === 'pytorch.export' && match.type === 'pytorch.zip') {
  17. return false;
  18. }
  19. if (context.type === 'pytorch.index' && match.type === 'pytorch.zip') {
  20. return false;
  21. }
  22. if (context.type === 'pytorch.model.json' && match.type === 'pytorch.data.pkl') {
  23. return false;
  24. }
  25. if (context.type === 'pytorch.model.json' && match.type === 'pickle') {
  26. return false;
  27. }
  28. return true;
  29. }
  30. async open(context) {
  31. const metadata = await pytorch.Metadata.open(context);
  32. const target = context.value;
  33. target.on('resolve', (sender, name) => {
  34. context.error(new pytorch.Error(`Unknown type name '${name}'.`), false);
  35. });
  36. await target.read(metadata);
  37. if (!target.format || (!target.modules && !target.module)) {
  38. throw new pytorch.Error("Container not implemented.");
  39. }
  40. return new pytorch.Model(metadata, target);
  41. }
  42. };
  43. pytorch.Model = class {
  44. constructor(metadata, target) {
  45. this.format = target.format;
  46. this.producer = target.producer || '';
  47. this.modules = [];
  48. if (target.module) {
  49. const graph = new pytorch.Graph(target.execution, metadata, null, '', target.module);
  50. this.modules.push(graph);
  51. delete target.execution;
  52. } else if (target.modules) {
  53. for (const [name, value] of target.modules) {
  54. const graph = new pytorch.Graph(target.execution, metadata, null, name, value);
  55. this.modules.push(graph);
  56. delete target.execution;
  57. }
  58. }
  59. }
  60. };
  61. pytorch.Graph = class {
  62. constructor(execution, metadata, type, name, module) {
  63. this.nodes = [];
  64. this.inputs = [];
  65. this.outputs = [];
  66. this.name = name || '';
  67. this.type = type;
  68. const values = new Map();
  69. values.map = (name, type, tensor) => {
  70. if (tensor) {
  71. return new pytorch.Value(name, type, null, tensor);
  72. }
  73. if (!values.has(name)) {
  74. values.set(name, new pytorch.Value(name, type, null, tensor));
  75. } else if (type || tensor) {
  76. throw new pytorch.Error(`Duplicate value '${name}'.`);
  77. }
  78. return values.get(name);
  79. };
  80. const torch = execution ? execution.torch : null;
  81. if (torch && module instanceof torch.jit._script.RecursiveScriptModule && module._c._has_method('forward')) {
  82. const initializers = new Map();
  83. const graph = module.graph;
  84. const constants = module.code_with_constants[1].const_mapping;
  85. if (constants) {
  86. for (const [key, value] of constants) {
  87. const name = `CONSTANTS.${key}`;
  88. if (pytorch.Utility.isTensor(value)) {
  89. initializers.set(value, new pytorch.Tensor(name, value));
  90. } else if (pytorch.Utility.isObject(value)) {
  91. initializers.set(value, value);
  92. } else {
  93. // throw new pytorch.Error('Unsupported constant.');
  94. }
  95. }
  96. }
  97. const deleted = new Set();
  98. const param_node = graph.param_node();
  99. const self = param_node && param_node.outputs().length > 0 && param_node.outputs()[0].type() === module._c._type() ? param_node.outputs()[0] : null;
  100. if (self) {
  101. const getattr = (value) => {
  102. if (value.value === undefined) {
  103. const node = value.node();
  104. if (node.kind() === 'prim::GetAttr') {
  105. const [input] = node.inputs();
  106. getattr(input);
  107. if (input.value !== undefined) {
  108. const name = node.s('name');
  109. value.value = input.value.__getattr__(name);
  110. value.identifier = input.identifier ? `${input.identifier}.${name}` : name;
  111. }
  112. }
  113. if (node === param_node && value === param_node.outputs()[0]) {
  114. value.value = module;
  115. value.identifier = '';
  116. }
  117. }
  118. };
  119. for (const node of graph.nodes()) {
  120. for (const input of node.inputs()) {
  121. getattr(input, node);
  122. }
  123. }
  124. const delattr = (value) => {
  125. for (const use of Array.from(value.uses())) {
  126. const node = use.user;
  127. if (node.kind() === 'prim::GetAttr') {
  128. for (const output of node.outputs()) {
  129. delattr(output);
  130. }
  131. // deleted.add(node);
  132. node.destroy();
  133. }
  134. }
  135. };
  136. delattr(param_node.outputs()[0], '');
  137. }
  138. for (const node of graph.nodes()) {
  139. if (node.kind() === 'prim::Constant' && node.outputs().length === 1) {
  140. const output = node.output();
  141. output.identifier = output.debugName();
  142. if (node.hasAttribute('value')) {
  143. const kind = node.kindOf('value');
  144. output.value = node[kind]('value');
  145. } else if (node.output().type() instanceof torch.NoneType) {
  146. output.value = null;
  147. }
  148. // deleted.add(node);
  149. node.destroy();
  150. }
  151. }
  152. for (const node of graph.nodes()) {
  153. if (node.kind() === 'prim::TupleUnpack') {
  154. const value = node.inputs()[0].value;
  155. if (Array.isArray(value) && value.length === node.outputs().length && value.every((value) => typeof value === 'number' || typeof value === 'string' || typeof value === 'boolean')) {
  156. for (let i = 0; i < node.outputs().length; i++) {
  157. const output = node.outputs()[i];
  158. output.value = value[i];
  159. }
  160. // deleted.add(node);
  161. node.destroy();
  162. }
  163. }
  164. }
  165. for (const node of graph.nodes()) {
  166. if (node.kind() === 'prim::ListConstruct' &&
  167. node.inputs().every((value) => typeof value.value === 'number' || typeof value.value === 'string' || typeof value.value === 'boolean') &&
  168. node.outputs().every((value) => value.uses().every((use) => use.user.kind() !== 'prim::CallMethod'))) {
  169. node.outputs()[0].value = node.inputs().map((value) => value.value);
  170. // deleted.add(node);
  171. node.destroy();
  172. }
  173. }
  174. for (const v of graph.inputs()) {
  175. if (self.uses().length === 0 && v === self) {
  176. continue;
  177. }
  178. const identifier = pytorch.Utility.unique(v);
  179. const name = v.debugName() || identifier;
  180. const value = values.map(identifier);
  181. this.inputs.push(new pytorch.Argument(name, [value]));
  182. }
  183. for (const value of graph.outputs()) {
  184. const identifier = pytorch.Utility.unique(value);
  185. this.outputs.push(new pytorch.Argument(identifier, [values.map(identifier)]));
  186. }
  187. for (const node of graph.nodes()) {
  188. if (deleted.has(node)) {
  189. continue;
  190. }
  191. if (node === graph.param_node() ||
  192. node === graph.return_node()) {
  193. continue;
  194. }
  195. if (node.kind() === 'prim::ListConstruct') {
  196. if (node.outputs().length === 1 &&
  197. node.outputs().every((output) => output.uses().length === 1) &&
  198. node.inputs().every((input) => pytorch.Utility.isTensor(input.value) || input instanceof torch.Value)) {
  199. continue;
  200. }
  201. }
  202. this.nodes.push(new pytorch.Node(execution, metadata, null, null, node, initializers, values));
  203. }
  204. } else if (torch && module instanceof torch.export.exported_program.ExportedProgram && module.graph) {
  205. const exported_program = module;
  206. const graph = exported_program.graph;
  207. const inputs_to_parameters = exported_program.graph_signature.inputs_to_parameters;
  208. const inputs_to_buffers = exported_program.graph_signature.inputs_to_buffers;
  209. const inputs_to_lifted_tensor_constants = exported_program.graph_signature.inputs_to_lifted_tensor_constants;
  210. const values = new Map();
  211. values.map = (obj) => {
  212. if (!values.has(obj)) {
  213. let type = null;
  214. const val = obj.meta.get('val');
  215. if (val && val.dtype) {
  216. const dataType = val.dtype.__reduce__();
  217. const shape = new pytorch.TensorShape(val.shape);
  218. type = new pytorch.TensorType(dataType, shape);
  219. }
  220. const value = new pytorch.Value(obj.name, type);
  221. values.set(obj, value);
  222. }
  223. return values.get(obj);
  224. };
  225. const nodes = new Map(graph.nodes.map((node) => [node.name, node]));
  226. for (const obj of graph.nodes) {
  227. if (obj.op === 'placeholder') {
  228. if (inputs_to_parameters.has(obj.name)) {
  229. const key = inputs_to_parameters.get(obj.name);
  230. const parameter = exported_program.state_dict.get(key);
  231. const tensor = parameter && parameter.data ? parameter.data : obj.meta.get('val');
  232. const initializer = new pytorch.Tensor(key, tensor);
  233. const value = new pytorch.Value(key, null, null, initializer);
  234. values.set(obj, value);
  235. } else if (inputs_to_buffers.has(obj.name)) {
  236. const key = inputs_to_buffers.get(obj.name);
  237. const buffer = exported_program.state_dict.get(key);
  238. const tensor = buffer || obj.meta.get('val');
  239. const initializer = new pytorch.Tensor(key, tensor);
  240. const value = new pytorch.Value(key, null, null, initializer);
  241. values.set(obj, value);
  242. } else if (inputs_to_lifted_tensor_constants.has(obj.name)) {
  243. const key = inputs_to_lifted_tensor_constants.get(obj.name);
  244. const constant = exported_program.constants.get(key);
  245. const tensor = constant && constant.data ? constant.data : obj.meta.get('val');
  246. const initializer = new pytorch.Tensor(key, tensor);
  247. const value = new pytorch.Value(key, null, null, initializer);
  248. values.set(obj, value);
  249. }
  250. if (obj.users.size > 1 && values.has(obj)) {
  251. const node = new pytorch.Node(execution, metadata, obj.name, null, obj, null, values);
  252. this.nodes.push(node);
  253. values.set(obj, node.outputs[0].value[0]);
  254. }
  255. }
  256. }
  257. for (const obj of graph.nodes) {
  258. if (obj.op === 'placeholder') {
  259. continue;
  260. }
  261. if (obj.op === 'call_function') {
  262. if (obj.target.__module__ === 'operator' && obj.target.__name__ === 'getitem') {
  263. continue;
  264. }
  265. }
  266. if (obj.op === 'output') {
  267. for (const output of obj.args) {
  268. if (output.op === 'call_function' && output.target.__module__ === 'operator' && output.target.__name__ === 'getitem') {
  269. continue;
  270. }
  271. const value = values.map(output);
  272. const argument = new pytorch.Argument(output.name, [value]);
  273. this.outputs.push(argument);
  274. }
  275. continue;
  276. }
  277. const node = new pytorch.Node(execution, metadata, obj.name, null, obj, null, values);
  278. this.nodes.push(node);
  279. }
  280. for (const input_spec of exported_program.graph_signature.user_inputs) {
  281. if (nodes.has(input_spec)) {
  282. const node = nodes.get(input_spec);
  283. const value = values.map(node);
  284. const argument = new pytorch.Argument(input_spec, [value]);
  285. this.inputs.push(argument);
  286. }
  287. }
  288. } else if (pytorch.Utility.isTensor(module)) {
  289. const node = new pytorch.Node(execution, metadata, null, type, { value: module });
  290. this.nodes.push(node);
  291. } else {
  292. const weights = this.type === 'weights' ? module : pytorch.Utility.weights(module);
  293. if (weights) {
  294. this.name = !this.name && typeof module.__name__ === 'string' ? module.__name__ : this.name;
  295. for (const [name, module] of weights) {
  296. const node = new pytorch.Node(execution, metadata, name, 'Weights', module);
  297. this.nodes.push(node);
  298. }
  299. } else {
  300. const modules = Array.isArray(module) && module.every((module) => module && !pytorch.Utility.isTensor(module) && (module._modules !== undefined || module.__class__)) ? module : [module];
  301. for (const module of modules) {
  302. const type = this.type === 'weights' ? 'Weights' : null;
  303. const node = new pytorch.Node(execution, metadata, null, type, module, null, values);
  304. this.nodes.push(node);
  305. }
  306. }
  307. }
  308. }
  309. };
  310. pytorch.Argument = class {
  311. constructor(name, value, type, visible) {
  312. this.name = name;
  313. this.value = value;
  314. this.type = type || null;
  315. this.visible = visible !== false;
  316. }
  317. };
  318. pytorch.Value = class Value {
  319. constructor(name, type, quantization, initializer) {
  320. if (typeof name !== 'string') {
  321. throw new pytorch.Error(`Invalid value identifier '${JSON.stringify(name)}'.`);
  322. }
  323. this.name = name;
  324. this.type = initializer && initializer.type ? initializer.type : type || null;
  325. this.quantization = quantization;
  326. this.initializer = initializer || null;
  327. }
  328. };
  329. pytorch.Node = class {
  330. constructor(execution, metadata, name, type, obj, initializers, values, stack) {
  331. const torch = execution ? execution.torch : null;
  332. const builtins = execution ? execution.builtins : null;
  333. this.name = name || '';
  334. this.nodes = [];
  335. this.attributes = [];
  336. this.inputs = [];
  337. this.outputs = [];
  338. this.metadata = [];
  339. if (torch && obj instanceof torch.Node) {
  340. const node = obj;
  341. const kind = node.kind();
  342. const schema = node.schema();
  343. const inputs = node.inputs();
  344. const outputs = node.outputs();
  345. this.type = {
  346. name: kind.indexOf('::') === -1 ? kind : kind.split('::').pop().split('.')[0],
  347. identifier: kind
  348. };
  349. if (schema && schema.category) {
  350. this.type.category = schema.category;
  351. }
  352. const getAttribute = (node, name) => {
  353. const kind = node.kindOf(name);
  354. let value = null;
  355. let type = null;
  356. switch (kind) {
  357. case 's': value = node.s(name); type = 'string'; break;
  358. case 'i': value = node.i(name); type = 'int64'; break;
  359. case 'f': value = node.f(name); type = 'float32'; break;
  360. case 't': value = node.t(name); type = 'tensor'; break;
  361. case 'ss': value = node.ss(name); type = 'string[]'; break;
  362. case 'tys': value = node.tys(name).map((ty) => pytorch.Utility.toType(ty)); type = 'type[]'; break;
  363. case 'ival': value = node.ival(name); break;
  364. default: throw new pytorch.Error(`Unsupported attribute kind '${kind}'.`);
  365. }
  366. return [type, value];
  367. };
  368. for (const name of node.attributeNames()) {
  369. const [type, value] = getAttribute(node, name);
  370. const attribute = new pytorch.Argument(name, value, type);
  371. this.attributes.push(attribute);
  372. }
  373. const mapTensor = (value) => {
  374. if (value.identifier && pytorch.Utility.isTensor(value.value)) {
  375. const identifier = value.identifier;
  376. if (!values.has(identifier)) {
  377. const tensor = new pytorch.Tensor(identifier, value.value);
  378. values.set(identifier, new pytorch.Value(identifier, null, null, tensor));
  379. }
  380. return values.map(identifier);
  381. }
  382. let initializer = null;
  383. let identifier = value.hasDebugName() ? `%${value.debugName().toString()}` : `%${value.unique().toString()}`;
  384. if (value.value) {
  385. const obj = value.value;
  386. const hide = obj.__parent__ ? obj.__parent__.__hide__ : true;
  387. initializer = hide ? initializers.get(obj) : null;
  388. identifier = initializer ? initializer.name : identifier;
  389. }
  390. if (initializer) {
  391. return new pytorch.Value(identifier, null, null, initializer);
  392. }
  393. return values.map(identifier);
  394. };
  395. for (let i = 0; i < inputs.length; i++) {
  396. const input = inputs[i];
  397. const arg = schema && schema.arguments && i < schema.arguments.length ? schema.arguments[i] : null;
  398. const name = arg && arg.name ? arg.name : i.toString();
  399. let type = arg ? arg.real_type : null;
  400. let array = false;
  401. if (type instanceof torch.ListType) {
  402. array = true;
  403. type = type.getElementType();
  404. }
  405. let argument = null;
  406. if (type && type instanceof torch.ClassType) {
  407. const obj = input.value;
  408. if (!array && initializers.has(obj)) {
  409. const node = new pytorch.Node(execution, metadata, name, type.qualified_name(), obj, initializers, values);
  410. argument = new pytorch.Argument(name, node, 'object');
  411. } else if (array && Array.isArray(obj) && obj.every((obj) => initializers.has(obj))) {
  412. const node = obj.map((obj) => new pytorch.Node(execution, metadata, name, type.qualified_name(), obj, initializers, values));
  413. argument = new pytorch.Argument(name, node, 'object[]');
  414. } else if (array && input.node().kind() === 'prim::ListConstruct' && input.uses().length === 1 && input.node().inputs().every((input) => input.value)) {
  415. const node = input.node().inputs().map((input) => new pytorch.Node(execution, metadata, name, null, input.value, initializers, values));
  416. argument = new pytorch.Argument(name, node, 'object[]');
  417. } else if (input.value === undefined) {
  418. const identifier = pytorch.Utility.unique(input);
  419. const value = values.map(identifier);
  420. argument = new pytorch.Argument(name, [value]);
  421. } else {
  422. const node = new pytorch.Node(execution, metadata, null, null, input.value, initializers, values);
  423. argument = new pytorch.Argument(name, node, 'object');
  424. }
  425. } else if ((input.type() instanceof torch.TensorType || (input.type() instanceof torch.OptionalType && input.type().getElementType() instanceof torch.TensorType)) && pytorch.Utility.isTensor(input.value)) {
  426. const value = mapTensor(input);
  427. argument = new pytorch.Argument(name, [value]);
  428. } else if (input instanceof torch.Value && !pytorch.Utility.isTensor(input.value)) {
  429. if (input.value !== undefined) {
  430. if (Array.isArray(input.value) && input.value.every((value) => pytorch.Utility.isTensor(value))) {
  431. continue;
  432. }
  433. const type = input.type() ? pytorch.Utility.toType(input.type()) : null;
  434. let value = input.value;
  435. if (value && value instanceof torch._C.IValue) {
  436. value = pytorch.Utility.toString(value);
  437. }
  438. argument = new pytorch.Argument(name, value, type || 'attribute');
  439. } else if (input.type() instanceof torch.ListType) {
  440. if (input.node() && input.node().kind() === 'prim::ListConstruct' && input.uses().length === 1 &&
  441. input.node().inputs().every((value) => value instanceof torch.Value || value.type() instanceof torch.IntType || value.type() instanceof torch.FloatType || value.type() instanceof torch.StringType || value.type() instanceof torch.ComplexType || value.type() instanceof torch.TensorType)) {
  442. const list = input.node().inputs();
  443. const args = list.map((value) => {
  444. if (pytorch.Utility.isTensor(value.value)) {
  445. return mapTensor(value);
  446. }
  447. if (value.value !== undefined) {
  448. return value.value;
  449. }
  450. const identifier = pytorch.Utility.unique(value);
  451. return values.map(identifier);
  452. });
  453. const type = list.every((value) => (pytorch.Utility.isTensor(value.value)) || value.value === null) ? null : pytorch.Utility.toType(input.type());
  454. argument = new pytorch.Argument(name, args, type);
  455. } else {
  456. const identifier = pytorch.Utility.unique(input);
  457. argument = new pytorch.Argument(name, [values.map(identifier)]);
  458. }
  459. } else if (input.type() instanceof torch.StringType && typeof input.value === 'string') {
  460. argument = new pytorch.Argument(name, input.value, 'string');
  461. } else if (input.type() instanceof torch.BoolType && (typeof input.value === 'boolean' || input.value === 0 || input.value === 1)) {
  462. argument = new pytorch.Argument(name, Boolean(input.value), 'boolean');
  463. } else if (input.type() instanceof torch.IntType && typeof input.value === 'number') {
  464. argument = new pytorch.Argument(name, input.value, 'int64');
  465. } else if (input.type() instanceof torch.FloatType && typeof input.value === 'number') {
  466. argument = new pytorch.Argument(name, input.value, 'float32');
  467. } else if (input.type() instanceof torch.NoneType && input.value === null) {
  468. argument = new pytorch.Argument(name, null, 'attribute');
  469. } else {
  470. const identifier = pytorch.Utility.unique(input);
  471. const value = values.map(identifier);
  472. argument = new pytorch.Argument(name, [value]);
  473. }
  474. } else if (pytorch.Utility.isTensor(input.value) || input.value === undefined || input.value === null) {
  475. let list = [input];
  476. if (input.node() && node !== input.node() &&
  477. input.node().kind() === 'prim::ListConstruct' &&
  478. input.uses().length === 1 &&
  479. input.node().inputs().every((input) => pytorch.Utility.isTensor(input.value))) {
  480. list = input.node().inputs();
  481. }
  482. const args = list.map((input) => {
  483. let initializer = null;
  484. let identifier = pytorch.Utility.unique(input);
  485. if (input.value) {
  486. const value = input.value;
  487. const hide = value.__parent__ ? value.__parent__.__hide__ : true;
  488. initializer = hide ? initializers.get(value) : null;
  489. identifier = initializer ? initializer.name : identifier;
  490. }
  491. if (initializer) {
  492. return new pytorch.Value(identifier, null, null, initializer);
  493. }
  494. return values.map(identifier);
  495. });
  496. argument = new pytorch.Argument(name, args);
  497. } else if (Array.isArray(input.value) && input.value.some((value) => value instanceof torch.Value)) {
  498. const args = input.value.map((value) => {
  499. if (value instanceof torch.Value) {
  500. const identifier = pytorch.Utility.unique(value);
  501. return values.map(identifier);
  502. }
  503. return value;
  504. });
  505. argument = new pytorch.Argument(name, args, pytorch.Utility.toType(type));
  506. } else {
  507. throw new pytorch.Error('Unsupported input value');
  508. }
  509. this.inputs.push(argument);
  510. }
  511. for (let i = 0; i < outputs.length; i++) {
  512. const output = outputs[i];
  513. const ret = schema && schema.returns && i < schema.returns.length ? schema.returns[i] : null;
  514. if (ret && ret.name) {
  515. name = ret.name;
  516. } else {
  517. name = i === 0 && outputs.length === 1 ? 'output' : `${i}`;
  518. }
  519. let list = [output];
  520. if (output.uses().length === 1 &&
  521. output.uses()[0].user &&
  522. output.uses()[0].user.kind() === 'prim::ListUnpack' &&
  523. output.uses()[0].user.outputs().every((output) => pytorch.Utility.isTensor(output.value))) {
  524. list = output.uses()[0].user.outputs();
  525. }
  526. const args = list.map((output) => values.map(pytorch.Utility.unique(output)));
  527. const argument = new pytorch.Argument(name, args);
  528. this.outputs.push(argument);
  529. }
  530. const blocks = node.blocks();
  531. for (let i = 0; i < blocks.length; i++) {
  532. const block = blocks[i];
  533. if (block.nodes().length > 2) {
  534. const name = `block${i.toString()}`;
  535. const graph = { name: '', nodes: [] }; // new pytorch.Graph(execution, metadata, null, name, blocks[i]);
  536. const argument = new pytorch.Argument(name, graph, 'graph');
  537. this.inputs.push(argument);
  538. }
  539. }
  540. const sourceRange = node.sourceRange();
  541. if (sourceRange) {
  542. this.metadata.push(new pytorch.Argument('source', sourceRange.toString().replace(/^at\s/, '').replace(/\.$/, ''), 'attribute'));
  543. if (sourceRange.source()) {
  544. const orig = sourceRange.source().findSourceRangeThatGenerated(sourceRange);
  545. if (orig) {
  546. this.metadata.push(new pytorch.Argument('generated', orig.toString(), 'attribute'));
  547. }
  548. }
  549. }
  550. } else if (torch && obj instanceof torch.fx.node.Node) {
  551. if (obj.op === 'call_function') {
  552. let name = null;
  553. const target = obj.target;
  554. if (target instanceof torch._ops.OpOverload) {
  555. name = target.name();
  556. } else if (builtins.isinstance(target, builtins.function)) {
  557. name = target.__name__;
  558. } else {
  559. throw new pytorch.Error(`Unsupported target '${target}'.`);
  560. }
  561. this.type = {
  562. identifier: name,
  563. name: name.indexOf('::') === -1 ? name : name.split('::').pop().split('.')[0]
  564. };
  565. const schema = obj.target._schema;
  566. if (schema && schema.category) {
  567. this.type.category = schema.category;
  568. }
  569. let args = obj.args.map((arg, index) => {
  570. const name = schema && Array.isArray(schema.arguments) ? schema.arguments[index].name : '';
  571. return [name, arg];
  572. });
  573. const inputs = new Map((schema ? schema.arguments : []).map((arg) => [arg.name, arg]));
  574. args = args.concat(Array.from(obj.kwargs));
  575. for (const [name, arg] of args) {
  576. const type = inputs.has(name) ? pytorch.Utility.toType(inputs.get(name).real_type) : null;
  577. if (arg instanceof torch.fx.node.Node) {
  578. const value = values.map(arg);
  579. const argument = new pytorch.Argument(name, [value]);
  580. this.inputs.push(argument);
  581. } else if (Array.isArray(arg) && arg.every((arg) => arg instanceof torch.fx.node.Node || arg === null)) {
  582. const list = arg.map((arg) => arg === null ? null : values.map(arg));
  583. const argument = new pytorch.Argument(name, list);
  584. this.inputs.push(argument);
  585. } else if (Array.isArray(arg)) {
  586. const list = arg.map((arg) => arg instanceof torch.fx.node.Node ? values.map(arg) : arg);
  587. const argument = new pytorch.Argument(name, list, type || 'attribute');
  588. this.inputs.push(argument);
  589. } else if (arg instanceof torch.dtype || arg instanceof torch.device || arg instanceof torch.layout || arg instanceof torch.memory_format) {
  590. const argument = new pytorch.Argument(name, arg.toString(), type || 'attribute');
  591. this.inputs.push(argument);
  592. } else {
  593. const argument = new pytorch.Argument(name, arg, type || 'attribute');
  594. this.inputs.push(argument);
  595. }
  596. }
  597. let outputs = [obj];
  598. if (obj.users.size > 1) {
  599. const users = Array.from(obj.users.keys());
  600. if (users.every((user) => user.op === 'call_function' && user.target.__module__ === 'operator' && user.target.__name__ === 'getitem')) {
  601. outputs = new Array(obj.users.size);
  602. for (const user of users) {
  603. const [, index] = user.args;
  604. outputs[index] = user;
  605. }
  606. }
  607. }
  608. for (let i = 0; i < outputs.length; i++) {
  609. const node = outputs[i];
  610. const value = values.map(node);
  611. const name = schema && schema.returns && schema.returns[i] ? schema.returns[i].name || 'output' : 'output';
  612. const argument = new pytorch.Argument(name, [value]);
  613. this.outputs.push(argument);
  614. }
  615. for (const [name, value] of obj.meta) {
  616. if (name === 'val' || name === 'torch_fn' ||
  617. (Array.isArray(value) && value.length === 0) ||
  618. (value instanceof Map && value.size === 0)) {
  619. continue;
  620. }
  621. if (typeof value === 'string') {
  622. const argument = new pytorch.Argument(name, value, 'string');
  623. this.metadata.push(argument);
  624. } else if (Array.isArray(value) && value.every((item) => typeof item === 'string')) {
  625. const argument = new pytorch.Argument(name, value, 'string[]');
  626. this.metadata.push(argument);
  627. } else if (value instanceof Map && value.size > 0) {
  628. // const argument = new pytorch.Argument(name, Object.fromEntries(Array.from(value)));
  629. // this.metadata.push(argument);
  630. } else {
  631. // const argument = new pytorch.Argument(name, value);
  632. // this.metadata.push(argument);
  633. }
  634. }
  635. } else if (obj.op === 'placeholder') {
  636. this.type = { name: obj.op };
  637. {
  638. const value = values.map(obj);
  639. const argument = new pytorch.Argument('value', [value]);
  640. this.inputs.push(argument);
  641. }
  642. {
  643. const value = values.map({ name: obj.name, meta: obj.meta });
  644. const argument = new pytorch.Argument('value', [value]);
  645. this.outputs.push(argument);
  646. }
  647. } else if (obj.op === 'root') {
  648. this.type = { name: obj.op };
  649. } else {
  650. throw new pytorch.Error(`Unsupported node operation '${obj.op}'.`);
  651. }
  652. } else {
  653. if (torch && obj instanceof torch.ScriptObject) {
  654. type = obj._type().qualified_name();
  655. obj = obj._ivalue;
  656. } else if (torch && obj instanceof torch.jit._script.RecursiveScriptModule && obj._c && obj._c.qualified_name) {
  657. type = obj._c._type();
  658. const target = {
  659. _modules: obj._modules,
  660. _parameters: obj._parameters,
  661. _buffers: obj._buffers,
  662. };
  663. for (let i = 0; i < type.numAttributes(); i++) {
  664. if (!type.is_parameter(i) && !type.is_buffer(i) && !type.getAttribute(i).is_module()) {
  665. const k = type.getAttributeName(i);
  666. target[k] = obj.__getattr__(k);
  667. }
  668. }
  669. type = obj._c.qualified_name;
  670. obj = target;
  671. }
  672. if (!type) {
  673. if (torch && obj instanceof torch.jit._script.RecursiveScriptModule && obj._c && obj._c.qualified_name) {
  674. type = obj._c.qualified_name;
  675. } else if (pytorch.Utility.isInstance(obj, 'builtins.function')) {
  676. type = `${obj.__module__}.${obj.__name__}`;
  677. obj = {};
  678. } else if (obj && obj.__class__ && obj.__class__.__module__ && obj.__class__.__name__) {
  679. type = `${obj.__class__.__module__}.${obj.__class__.__name__}`;
  680. } else {
  681. type = 'builtins.object';
  682. }
  683. }
  684. if (type instanceof pytorch.nnapi.Graph) {
  685. this.type = type;
  686. } else {
  687. const key = type.startsWith('__torch__.') ? type.substring(10) : type;
  688. const value = metadata.type(key);
  689. this.type = value ? { ...value } : { name: type };
  690. this.type.identifier = type;
  691. }
  692. stack = stack || new Set();
  693. const weights = pytorch.Utility.weights(obj);
  694. if (weights) {
  695. const type = this.type.name;
  696. this.type = new pytorch.Graph(execution, metadata, 'weights', '', weights);
  697. this.type.name = type;
  698. } else if (obj && pytorch.Utility.isInstance(obj, 'fastai.data.core.DataLoaders')) {
  699. // continue
  700. } else if (obj && pytorch.Utility.isInstance(obj, '__torch__.torch.classes._nnapi.Compilation')) {
  701. // continue
  702. } else if (obj && type === 'builtins.bytearray') {
  703. const argument = new pytorch.Argument('value', Array.from(obj), 'byte[]');
  704. this.inputs.push(argument);
  705. } else if (obj) {
  706. const inputs = new Map(Array.isArray(this.type.inputs) ? this.type.inputs.map((input) => [input.name, input]) : []);
  707. const list = obj instanceof Map ? Array.from(obj) : Object.entries(obj);
  708. for (const [name, value] of list) {
  709. if (name === '__class__' || name === '__name__') {
  710. continue;
  711. } else if (pytorch.Utility.isInstance(value, 'collections.OrderedDict') && value instanceof Map && value.size === 0) {
  712. continue;
  713. } else if (pytorch.Utility.isInstance(value, 'builtins.set') && value instanceof Set && value.size === 0) {
  714. continue;
  715. } else if (pytorch.Utility.isInstance(value, 'builtins.list') && Array.isArray(value) && value.length === 0) {
  716. continue;
  717. } else if (pytorch.Utility.isInstance(value, 'torch.Size') && Array.isArray(value) && value.length === 0) {
  718. continue;
  719. }
  720. let parameters = null;
  721. if ((name === '_parameters' || name === '_buffers') && value instanceof Map) {
  722. parameters = value;
  723. } else if (pytorch.Utility.isTensor(value) || (Array.isArray(value) && value.every((tensor) => pytorch.Utility.isTensor(tensor)))) {
  724. parameters = new Map([[name, value]]);
  725. }
  726. if (parameters) {
  727. for (const [name, value] of parameters) {
  728. const list = Array.isArray(value) ? value.map((item) => pytorch.Utility.toTensor(item)) : [pytorch.Utility.toTensor(value)];
  729. const visible = inputs.has(name) ? inputs.get(name).visible || true : true;
  730. const args = list.filter((value) => value !== null && !value.__origin__).map((value) => {
  731. const name = value && value.name ? value.name : '';
  732. const identifier = list.length === 1 && value && value.__name__ ? value.__name__ : name;
  733. let tensor = null;
  734. if (initializers && initializers.has(value)) {
  735. tensor = initializers.get(value);
  736. } else {
  737. value = value.__source__ ? value.__source__ : value;
  738. tensor = value ? new pytorch.Tensor(identifier, value) : null;
  739. }
  740. return new pytorch.Value(identifier, null, null, tensor);
  741. });
  742. const argument = new pytorch.Argument(name, args, null, visible);
  743. this.inputs.push(argument);
  744. if (value && value.__variable__) {
  745. const argument = new pytorch.Argument(name, [values.map(value.__variable__)]);
  746. this.outputs.push(argument);
  747. }
  748. }
  749. continue;
  750. }
  751. if (pytorch.Utility.isTensor(value)) {
  752. const tensor = new pytorch.Tensor('', value);
  753. const argument = new pytorch.Argument(name, tensor, 'tensor');
  754. this.inputs.push(argument);
  755. } else if (value && pytorch.Utility.isInstance(value, 'torch.dtype')) {
  756. const node = new pytorch.Node(execution, metadata, null, value.toString(), {});
  757. const argument = new pytorch.Argument(name, node, 'object');
  758. this.inputs.push(argument);
  759. } else if (Array.isArray(value) && value.some((value) => pytorch.Utility.isTensor(value)) && value.every((value) => pytorch.Utility.isTensor(value) || value === null)) {
  760. const tensors = value.map((value) => value === null ? value : new pytorch.Tensor('', value));
  761. const argument = new pytorch.Argument(name, tensors, 'tensor[]');
  762. this.inputs.push(argument);
  763. } else if (pytorch.Utility.isInstance(value, 'numpy.ndarray') || pytorch.Utility.isInstance(value, 'numpy.matrix')) {
  764. const tensor = new numpy.Tensor(value);
  765. const argument = new pytorch.Argument(name, tensor, 'tensor');
  766. this.inputs.push(argument);
  767. } else if (Array.isArray(value) && value.every((value) => typeof value === 'string')) {
  768. const argument = new pytorch.Argument(name, value, 'string[]');
  769. this.inputs.push(argument);
  770. } else if (Array.isArray(value) && value.every((value) => typeof value === 'number')) {
  771. const argument = new pytorch.Argument(name, value, 'attribute');
  772. this.inputs.push(argument);
  773. } else if (name === '_modules' && pytorch.Utility.isInstance(value, 'collections.OrderedDict') &&
  774. value instanceof Map && Array.from(value).every(([, value]) => value === null || value.__class__)) {
  775. const list = Array.from(value).filter(([, value]) => !stack.has(value)).map(([name, obj]) => {
  776. stack.add(value);
  777. const type = obj === null ? 'builtins.NoneType' : `${obj.__class__.__module__}.${obj.__class__.__name__}`;
  778. const node = new pytorch.Node(execution, metadata, this.name ? `${this.name}.${name}` : name, type, obj, initializers, values, stack);
  779. stack.delete(value);
  780. return node;
  781. });
  782. const argument = new pytorch.Argument(name, list, 'object[]');
  783. this.inputs.push(argument);
  784. } else if (value && Array.isArray(value) && value.length > 0 && value.every((obj) => Array.isArray(obj) && obj.every((item) => typeof item === 'string' || typeof item === 'number'))) {
  785. const argument = new pytorch.Argument(name, value, 'attribute');
  786. this.inputs.push(argument);
  787. } else if (value && Array.isArray(value) && value.length > 0 && value.every((obj) => obj && (obj.__class__ || obj === Object(obj)))) {
  788. const list = value.filter((value) => !stack.has(value));
  789. const nodes = list.map((value) => {
  790. stack.add(value);
  791. const node = new pytorch.Node(execution, metadata, null, null, value, initializers, values, stack);
  792. stack.delete(value);
  793. return node;
  794. });
  795. const argument = new pytorch.Argument(name, nodes, 'object[]');
  796. this.inputs.push(argument);
  797. } else if (value && (value.__class__ || typeof value === 'object') && !stack.has(value)) {
  798. stack.add(value);
  799. const node = new pytorch.Node(execution, metadata, null, null, value, initializers, values, stack);
  800. stack.delete(value);
  801. const visible = name !== '_metadata' || !pytorch.Utility.isMetadataObject(value);
  802. const argument = new pytorch.Argument(name, node, 'object', visible);
  803. this.inputs.push(argument);
  804. } else {
  805. let schema = metadata.attribute(this.type.identifier, name);
  806. schema = name === 'training' ? { type: 'boolean', visible: false } : schema;
  807. let visible = true;
  808. let obj = value;
  809. const type = schema && schema.type ? schema.type : 'attribute';
  810. if (schema) {
  811. if (schema.visible === false) {
  812. visible = false;
  813. } else if (schema.default !== undefined) {
  814. if (Array.isArray(obj)) {
  815. if (Array.isArray(schema.default)) {
  816. visible = obj.length !== schema.default || !obj.every((item, index) => item === schema.default[index]);
  817. } else {
  818. visible = !obj.every((item) => item === schema.default);
  819. }
  820. } else {
  821. visible = obj !== schema.default;
  822. }
  823. }
  824. }
  825. if (Array.isArray(obj) && obj.length > 0 && obj.every((obj) => obj && obj.__class__ && obj.__class__.__module__ && obj.__class__.__module__.startsWith('torch.nn'))) {
  826. obj = '?';
  827. }
  828. const argument = new pytorch.Argument(name, obj, type, visible);
  829. this.inputs.push(argument);
  830. }
  831. }
  832. }
  833. }
  834. }
  835. };
  836. pytorch.Tensor = class {
  837. constructor(name, tensor) {
  838. this.name = name || '';
  839. tensor = tensor.data ? tensor.data : tensor;
  840. const layout = tensor.layout ? tensor.layout.__str__() : null;
  841. const storage = tensor.storage();
  842. const size = tensor.size() || [];
  843. if (layout && layout.startsWith('torch.sparse_')) {
  844. this.type = new pytorch.TensorType(tensor.dtype.__reduce__(), new pytorch.TensorShape(size), layout.split('.').pop().replace('_', '.'));
  845. this.indices = new pytorch.Tensor('', tensor.indices);
  846. this._values = new pytorch.Tensor('', tensor.values);
  847. } else if (!layout || layout === 'torch.strided') {
  848. this.type = new pytorch.TensorType(tensor.dtype.__reduce__(), new pytorch.TensorShape(size));
  849. this.encoding = '<';
  850. this.indices = null;
  851. this.stride = tensor.stride();
  852. const stride = this.stride;
  853. const offset = tensor.storage_offset();
  854. if (storage) {
  855. this._data = storage.data;
  856. let length = 0;
  857. if (!Array.isArray(stride)) {
  858. length = storage.size();
  859. } else if (size.every((v) => v !== 0)) {
  860. length = size.reduce((a, v, i) => a + stride[i] * (v - 1), 1);
  861. }
  862. if (offset !== 0 || length !== storage.size()) {
  863. const itemsize = storage.dtype.itemsize();
  864. this._offset = itemsize * offset;
  865. this._length = itemsize * length;
  866. }
  867. }
  868. } else {
  869. throw new pytorch.Error(`Unsupported tensor layout '${layout}'.`);
  870. }
  871. }
  872. get values() {
  873. const type = this.type.layout;
  874. if (type && type.startsWith('sparse.')) {
  875. return this._values;
  876. }
  877. if (this._data instanceof Uint8Array) {
  878. return this._data;
  879. }
  880. if (this._data && this._offset !== undefined) {
  881. const stream = this._data;
  882. const position = stream.position;
  883. stream.seek(this._offset);
  884. const values = stream.peek(this._length);
  885. stream.seek(position);
  886. return values;
  887. }
  888. if (this._data) {
  889. return this._data.peek();
  890. }
  891. return null;
  892. }
  893. decode() {
  894. if (this.encoding !== '<') {
  895. throw new pytorch.Error(`Tensor encoding '${this.encoding}' not implemented.`);
  896. }
  897. const type = this.type;
  898. const data = this.values;
  899. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  900. switch (type.dataType) {
  901. case 'int16': {
  902. const array = new Uint16Array(data.length >> 1);
  903. for (let i = 0; i < array.length; i++) {
  904. array[i] = view.getInt16(i << 1, true);
  905. }
  906. return array;
  907. }
  908. case 'int64': {
  909. const array = new Uint32Array(data.length >> 3);
  910. for (let i = 0; i < array.length; i++) {
  911. array[i] = view.getUint32(i << 3, true);
  912. if (view.getUint32((i << 3) + 4, true) !== 0) {
  913. throw new pytorch.Error('Signed 64-bit value exceeds 32-bit range.');
  914. }
  915. }
  916. return array;
  917. }
  918. default: {
  919. throw new pytorch.Error(`Tensor data type '${type.dataType}' not implemented.`);
  920. }
  921. }
  922. }
  923. };
  924. pytorch.TensorType = class {
  925. constructor(dataType, shape, layout) {
  926. this.dataType = dataType;
  927. this.shape = shape;
  928. this.layout = layout;
  929. }
  930. toString() {
  931. return this.dataType + this.shape.toString();
  932. }
  933. };
  934. pytorch.TensorShape = class {
  935. constructor(dimensions) {
  936. this.dimensions = dimensions || [];
  937. }
  938. toString() {
  939. if (this.dimensions && this.dimensions.length > 0) {
  940. return `[${this.dimensions.map((dimension) => dimension.toString()).join(',')}]`;
  941. }
  942. return '';
  943. }
  944. };
  945. pytorch.Container = class {
  946. static async open(context) {
  947. const types = [
  948. pytorch.Container.Zip,
  949. pytorch.Container.Pickle,
  950. pytorch.Container.Tar,
  951. pytorch.Container.data_pkl,
  952. pytorch.Container.torch_utils,
  953. pytorch.Container.Mobile,
  954. pytorch.Container.ModelJson,
  955. pytorch.Container.IR,
  956. pytorch.Container.Index,
  957. pytorch.Container.ExportedProgram
  958. ];
  959. for (const type of types) {
  960. /* eslint-disable no-await-in-loop */
  961. const container = await type.open(context);
  962. /* eslint-enable no-await-in-loop */
  963. if (container) {
  964. return container;
  965. }
  966. }
  967. return null;
  968. }
  969. constructor() {
  970. this._events = [];
  971. }
  972. async read() {
  973. }
  974. on(event, callback) {
  975. this._events.push([event, callback]);
  976. }
  977. };
  978. pytorch.Container.Tar = class extends pytorch.Container {
  979. static async open(context) {
  980. const entries = await context.peek('tar');
  981. if (entries instanceof Map && entries.has('pickle')) {
  982. return new pytorch.Container.Tar(entries);
  983. }
  984. return null;
  985. }
  986. constructor(entries) {
  987. super();
  988. this.type = 'pytorch.tar';
  989. this.entries = entries;
  990. }
  991. async read() {
  992. this.format = 'PyTorch v0.1.1';
  993. const execution = new python.Execution();
  994. for (const event of this._events) {
  995. execution.on(event[0], event[1]);
  996. }
  997. const torch = execution.__import__('torch');
  998. this.module = torch.load(this.entries);
  999. delete this.entries;
  1000. }
  1001. };
  1002. pytorch.Container.Pickle = class extends pytorch.Container {
  1003. static async open(context) {
  1004. const stream = context.stream;
  1005. const signature = [0x80, undefined, 0x8a, 0x0a, 0x6c, 0xfc, 0x9c, 0x46, 0xf9, 0x20, 0x6a, 0xa8, 0x50, 0x19];
  1006. if (stream && signature.length <= stream.length && stream.peek(signature.length).every((value, index) => signature[index] === undefined || signature[index] === value)) {
  1007. return new pytorch.Container.Pickle(stream);
  1008. }
  1009. return null;
  1010. }
  1011. constructor(stream) {
  1012. super();
  1013. this.type = 'pytorch.pickle';
  1014. this.stream = stream;
  1015. }
  1016. async read() {
  1017. this.format = 'PyTorch v0.1.10';
  1018. const data = this.stream.length < 0x7ffff000 ? this.stream.peek() : this.stream;
  1019. delete this.stream;
  1020. const execution = new python.Execution();
  1021. for (const event of this._events) {
  1022. execution.on(event[0], event[1]);
  1023. }
  1024. const torch = execution.__import__('torch');
  1025. this.module = torch.load(data);
  1026. }
  1027. };
  1028. pytorch.Container.data_pkl = class extends pytorch.Container {
  1029. static async open(context) {
  1030. const obj = await context.peek('pkl');
  1031. if (obj) {
  1032. if (obj.__class__ && obj.__class__.__module__ && obj.__class__.__name__) {
  1033. const name = `${obj.__class__.__module__}.${obj.__class__.__name__}`;
  1034. if (name.startsWith('__torch__.')) {
  1035. return new pytorch.Container.data_pkl('', obj);
  1036. }
  1037. }
  1038. if (pytorch.Utility.isTensor(obj)) {
  1039. return new pytorch.Container.data_pkl('tensor', obj);
  1040. }
  1041. if (Array.isArray(obj) && obj.length > 0 && obj.every((tensor) => pytorch.Utility.isTensor(tensor))) {
  1042. return new pytorch.Container.data_pkl('tensor', obj);
  1043. }
  1044. if (obj instanceof Map) {
  1045. const entries = Array.from(obj).filter(([, value]) => pytorch.Utility.isTensor(value));
  1046. if (entries.length > 0) {
  1047. return new pytorch.Container.data_pkl('tensor', obj);
  1048. }
  1049. } else if (!Array.isArray(obj)) {
  1050. const entries = Object.entries(obj).filter(([, value]) => pytorch.Utility.isTensor(value));
  1051. if (entries.length > 0) {
  1052. return new pytorch.Container.data_pkl('tensor', obj);
  1053. }
  1054. }
  1055. for (const key of ['', 'model', 'net']) {
  1056. const module = key === '' ? obj : obj[key];
  1057. if (module && module._modules && pytorch.Utility.isInstance(module._modules, 'collections.OrderedDict')) {
  1058. return new pytorch.Container.data_pkl('module', module);
  1059. }
  1060. }
  1061. }
  1062. return null;
  1063. }
  1064. constructor(type, module) {
  1065. super();
  1066. this.type = 'pytorch.data.pkl';
  1067. this.format = 'PyTorch Pickle';
  1068. this.module = module;
  1069. }
  1070. async read() {
  1071. }
  1072. };
  1073. pytorch.Container.torch_utils = class extends pytorch.Container {
  1074. static async open(context) {
  1075. const stream = context.stream;
  1076. if (stream && stream.length > 1) {
  1077. const buffer = stream.peek(Math.min(1024, stream.length));
  1078. if (buffer[0] === 0x80) {
  1079. const content = String.fromCharCode.apply(null, buffer);
  1080. if (content.indexOf('torch_utils') !== -1) {
  1081. const obj = await context.peek('pkl');
  1082. if (obj && Object.entries(obj).some(([, value]) => pytorch.Utility.isInstance(value, 'torch.nn.modules.module.Module'))) {
  1083. return new pytorch.Container.torch_utils(obj);
  1084. }
  1085. }
  1086. }
  1087. }
  1088. return null;
  1089. }
  1090. constructor(obj) {
  1091. super();
  1092. this.type = 'pytorch.torch_utils';
  1093. this.obj = obj;
  1094. }
  1095. async read() {
  1096. this.format = 'PyTorch torch_utils';
  1097. this.module = this.obj;
  1098. delete this.obj;
  1099. }
  1100. };
  1101. pytorch.Container.Mobile = class extends pytorch.Container {
  1102. static async open(context) {
  1103. const reader = await context.peek('flatbuffers.binary');
  1104. if (reader && reader.identifier === 'PTMF') {
  1105. return new pytorch.Container.Mobile(context);
  1106. }
  1107. return null;
  1108. }
  1109. constructor(context) {
  1110. super();
  1111. this.type = 'pytorch.mobile';
  1112. this.context = context;
  1113. }
  1114. async read(metadata) {
  1115. const execution = new pytorch.Execution(null, metadata);
  1116. for (const event of this._events) {
  1117. execution.on(event[0], event[1]);
  1118. }
  1119. const stream = this.context.stream;
  1120. const torch = execution.__import__('torch');
  1121. torch.mobile = await this.context.require('./pytorch-schema');
  1122. torch.mobile = torch.mobile.torch.jit.mobile;
  1123. this.module = torch.jit.jit_module_from_flatbuffer(stream);
  1124. const version = this.module._c._bytecode_version.toString();
  1125. this.format = pytorch.Utility.format('PyTorch Mobile', version);
  1126. delete this.context;
  1127. }
  1128. };
  1129. pytorch.Container.Zip = class extends pytorch.Container {
  1130. static async open(context) {
  1131. const entries = await context.peek('zip');
  1132. if (entries instanceof Map && entries.size > 0) {
  1133. let prefix = 0;
  1134. const paths = Array.from(entries.keys()).map((path) => path.replace(/\\/g, '/').split('/').reverse());
  1135. for (let set = new Set(); set && paths.length > 0;) {
  1136. set = new Set(paths.map((path) => path.length > 1 ? path.pop() : null));
  1137. set = set.size > 1 || set.keys().next().value === null ? null : set;
  1138. prefix += set ? set.keys().next().value.length + 1 : 0;
  1139. }
  1140. const records = new Map(Array.from(entries).map(([name, value]) => [name.substring(prefix), value]));
  1141. if (records.has('model.json')) {
  1142. return null;
  1143. }
  1144. if (records.has('data.pkl')) {
  1145. return new pytorch.Container.Zip(entries);
  1146. }
  1147. if (records.has('.data/version') && !records.has('archive_format')) {
  1148. return new pytorch.Container.Package(entries);
  1149. }
  1150. }
  1151. return null;
  1152. }
  1153. constructor(entries) {
  1154. super();
  1155. this.type = 'pytorch.zip';
  1156. // https://github.com/pytorch/pytorch/blob/main/torch/csrc/jit/OVERVIEW.md
  1157. // https://github.com/pytorch/pytorch/blob/master/torch/csrc/jit/docs/serialization.md
  1158. this._entries = entries;
  1159. }
  1160. async read(metadata) {
  1161. this.execution = new pytorch.Execution(null, metadata);
  1162. for (const event of this._events) {
  1163. this.execution.on(event[0], event[1]);
  1164. }
  1165. const torch = this.execution.__import__('torch');
  1166. const reader = new torch.PyTorchFileReader(this._entries);
  1167. let torchscript = reader.has_record('constants.pkl');
  1168. const version = reader.version();
  1169. if (torchscript) {
  1170. metadata.register(this.execution);
  1171. this.module = torch.jit.load(reader);
  1172. torchscript = this.module._c._has_method('forward');
  1173. if (torchscript) {
  1174. // console.log(this.module.graph.toString());
  1175. torch._C._jit_pass_inline(this.module.graph);
  1176. // console.log(this.module.graph.toString());
  1177. }
  1178. } else {
  1179. const records = reader.get_all_records().map((key) => [key, reader.get_record(key)]);
  1180. const entries = new Map(records);
  1181. this.module = torch.load(entries);
  1182. }
  1183. const name = torchscript ? 'TorchScript' : 'PyTorch';
  1184. this.format = pytorch.Utility.format(name, version);
  1185. delete this._model;
  1186. delete this._entries;
  1187. }
  1188. };
  1189. pytorch.Container.ModelJson = class extends pytorch.Container {
  1190. static async open(context) {
  1191. const identifier = context.identifier;
  1192. if (identifier === 'model.json') {
  1193. const model = await context.peek('json');
  1194. if (model && model.mainModule) {
  1195. const entries = new Map();
  1196. entries.set('model.json', context.stream);
  1197. return new pytorch.Container.ModelJson(context, entries, model);
  1198. }
  1199. }
  1200. return null;
  1201. }
  1202. constructor(context, entries, model) {
  1203. super();
  1204. this.type = 'pytorch.model.json';
  1205. this._context = context;
  1206. this._entries = entries;
  1207. this._model = model;
  1208. }
  1209. async read(metadata) {
  1210. pytorch.proto = await this._context.require('./pytorch-proto');
  1211. const keys = [
  1212. 'attributes.pkl',
  1213. 'version',
  1214. ...this._model.tensors.filter((tensor) => tensor && tensor.data && tensor.data.key).map((tensor) => tensor.data.key)
  1215. ];
  1216. const walk = (module) => {
  1217. if (module.torchscriptArena && module.torchscriptArena.key) {
  1218. keys.push(module.torchscriptArena.key);
  1219. }
  1220. for (const submodule of module.submodules || []) {
  1221. walk(submodule);
  1222. }
  1223. };
  1224. walk(this._model.mainModule);
  1225. const values = await Promise.all(keys.map((name) => this._context.fetch(name).then((context) => context.stream).catch(() => null)));
  1226. for (let i = 0; i < keys.length; i++) {
  1227. if (values[i]) {
  1228. this._entries.set(keys[i], values[i]);
  1229. }
  1230. }
  1231. this.execution = new pytorch.Execution(null, metadata);
  1232. this.execution.proto = pytorch.proto;
  1233. for (const event of this._events) {
  1234. this.execution.on(event[0], event[1]);
  1235. }
  1236. const torch = this.execution.__import__('torch');
  1237. const reader = new torch.PyTorchFileReader(this._entries);
  1238. if (this._model && this._model.producerName) {
  1239. this.producer = this._model.producerName + (this._model.producerVersion ? ` v${this._model.producerVersion}` : '');
  1240. }
  1241. this.format = reader.has_record('attributes.pkl') ? 'TorchScript v1.1' : 'TorchScript v1.0';
  1242. metadata.register(this.execution);
  1243. this.module = torch.jit.load(reader);
  1244. if (this.module._c._has_method('forward')) {
  1245. // console.log(this.module.graph.toString());
  1246. torch._C._jit_pass_inline(this.module.graph);
  1247. // console.log(this.module.graph.toString());
  1248. }
  1249. delete this._context;
  1250. delete this._model;
  1251. delete this._entries;
  1252. }
  1253. };
  1254. pytorch.Container.IR = class extends pytorch.Container {
  1255. static async open(context) {
  1256. const reader = await context.read('text', 0x100);
  1257. if (reader && reader.length > 0) {
  1258. const line = reader.read('\n');
  1259. if (line.startsWith('graph(')) {
  1260. return new pytorch.Container.IR(context);
  1261. }
  1262. }
  1263. return null;
  1264. }
  1265. constructor(context) {
  1266. super();
  1267. this.type = 'pytorch.ir';
  1268. this.context = context;
  1269. }
  1270. async read(metadata) {
  1271. this.format = 'TorchScript IR';
  1272. this.execution = new pytorch.Execution(null, metadata);
  1273. for (const event of this._events) {
  1274. this.execution.on(event[0], event[1]);
  1275. }
  1276. // this.execution.graph;
  1277. // context reader = await context.read('text', 0x100);
  1278. throw new pytorch.Error('TorchScript IR parser not implemented.');
  1279. }
  1280. };
  1281. pytorch.Container.Index = class extends pytorch.Container {
  1282. static async open(context) {
  1283. const obj = await context.peek('json');
  1284. if (obj && obj.weight_map) {
  1285. const entries = Object.entries(obj.weight_map);
  1286. if (entries.length > 0 && entries.every(([, value]) => typeof value === 'string' && value.endsWith('.bin'))) {
  1287. return new pytorch.Container.Index(context, entries);
  1288. }
  1289. }
  1290. return null;
  1291. }
  1292. constructor(context, entries) {
  1293. super();
  1294. this.type = 'pytorch.index';
  1295. this.context = context;
  1296. this._entries = entries;
  1297. }
  1298. async read(metadata) {
  1299. this.format = 'PyTorch';
  1300. const weight_map = new Map(this._entries);
  1301. const keys = new Set(weight_map.keys());
  1302. const files = Array.from(new Set(weight_map.values()));
  1303. const contexts = await Promise.all(files.map((name) => this.context.fetch(name)));
  1304. this.execution = new pytorch.Execution(null, metadata);
  1305. for (const event of this._events) {
  1306. this.execution.on(event[0], event[1]);
  1307. }
  1308. const torch = this.execution.__import__('torch');
  1309. const archives = await Promise.all(contexts.map((context) => context.peek('zip')));
  1310. const formats = new Set(archives.map((entries) => {
  1311. const reader = new torch.PyTorchFileReader(entries);
  1312. const version = reader.version();
  1313. return pytorch.Utility.format('PyTorch', version);
  1314. }));
  1315. if (formats.size === 1) {
  1316. this.format = formats.values().next().value;
  1317. }
  1318. const shards = archives.map((entries) => {
  1319. return torch.load(entries);
  1320. });
  1321. const entries = new Map();
  1322. for (const shard of shards) {
  1323. for (const [key, value] of Array.from(shard)) {
  1324. if (keys.has(key)) {
  1325. entries.set(key, value);
  1326. }
  1327. }
  1328. }
  1329. this.module = entries;
  1330. delete this.context;
  1331. delete this._entries;
  1332. }
  1333. };
  1334. pytorch.Container.ExportedProgram = class extends pytorch.Container {
  1335. static async open(context) {
  1336. const program = await context.peek('json');
  1337. if (program && program.schema_version && program.graph_module) {
  1338. return new pytorch.Container.ExportedProgram(context, program);
  1339. }
  1340. if (context.identifier === 'archive_format' && context.stream && context.stream.length < 10) {
  1341. const buffer = context.stream.peek();
  1342. const archive_format = String.fromCharCode.apply(null, buffer);
  1343. if (archive_format === 'pt2') {
  1344. return new pytorch.Container.ExportedProgram(context, null, context);
  1345. }
  1346. }
  1347. return null;
  1348. }
  1349. constructor(context, exported_program, archive_format) {
  1350. super();
  1351. this.type = 'pytorch.export';
  1352. this.context = context;
  1353. this.archive_format = archive_format;
  1354. this.exported_program = exported_program;
  1355. }
  1356. async read(metadata) {
  1357. this.format = 'PyTorch Export';
  1358. const f = new Map();
  1359. const exported_programs = new Map();
  1360. if (this.archive_format) {
  1361. for (const name of this.context.container.entries.keys()) {
  1362. const match = name.match(/^models\/([^/]+)\.json$/);
  1363. if (match) {
  1364. const [, model_name] = match;
  1365. /* eslint-disable no-await-in-loop */
  1366. const model = await this.context.fetch(`models/${model_name}.json`);
  1367. const constants = await this._fetch(`data/constants/${model_name}.pt`);
  1368. const sample_inputs = await this._fetch(`data/sample_inputs/${model_name}.pt`);
  1369. const weights = await this._fetch(`data/weights/${model_name}.pt`);
  1370. const exported_program = await model.read('json');
  1371. /* eslint-enable no-await-in-loop */
  1372. exported_programs.set(model_name, exported_program);
  1373. f.set(`models/${model_name}.json`, exported_program);
  1374. f.set(`data/weights/${model_name}.pt`, weights);
  1375. f.set(`data/constants/${model_name}.pt`, constants);
  1376. f.set(`data/sample_inputs/${model_name}.pt`, sample_inputs);
  1377. }
  1378. }
  1379. const byteorder = await this._text('byteorder') || 'little';
  1380. f.set('byteorder', byteorder);
  1381. } else {
  1382. this.version = await this._text('version');
  1383. this.version = this.version.split('\n').shift().trim();
  1384. const weights = await this._fetch('serialized_state_dict.pt') || await this._fetch('serialized_state_dict.json');
  1385. const constants = await this._fetch('serialized_constants.pt') || await this._fetch('serialized_constants.json');
  1386. const sample_inputs = await this._fetch('serialized_example_inputs.pt');
  1387. f.set('models/model.json', this.exported_program);
  1388. f.set('data/weights/model.pt', weights);
  1389. f.set('data/constants/model.pt', constants);
  1390. f.set('data/sample_inputs/model.pt', sample_inputs);
  1391. exported_programs.set('', this.exported_program);
  1392. }
  1393. if (!this.version) {
  1394. const versions = new Set();
  1395. for (const exported_program of exported_programs.values()) {
  1396. const schema_version = exported_program.schema_version;
  1397. if (schema_version && schema_version.major && schema_version.minor) {
  1398. versions.add(`${schema_version.major}.${schema_version.minor}`);
  1399. }
  1400. }
  1401. if (versions.size === 1) {
  1402. this.version = versions.values().next().value;
  1403. }
  1404. }
  1405. this.format = this.version ? `${this.format} v${this.version}` : this.format;
  1406. this.execution = new python.Execution();
  1407. for (const event of this._events) {
  1408. this.execution.on(event[0], event[1]);
  1409. }
  1410. metadata.register(this.execution);
  1411. const torch = this.execution.__import__('torch');
  1412. for (const exported_program of exported_programs.values()) {
  1413. if (exported_program.graph_module.graph.constants) {
  1414. /* eslint-disable no-await-in-loop */
  1415. const zip = await import('./zip.js');
  1416. /* eslint-enable no-await-in-loop */
  1417. const constants = exported_program.graph_module.graph.constants;
  1418. for (const key of Object.keys(constants)) {
  1419. const value = constants[key];
  1420. const str = atob(value);
  1421. const buffer = new Uint8Array(str.length);
  1422. for (let i = 0; i < str.length; i++) {
  1423. buffer[i] = str.charCodeAt(i);
  1424. }
  1425. const archive = zip.Archive.open(buffer);
  1426. constants[key] = archive.entries;
  1427. }
  1428. }
  1429. }
  1430. delete this.exported_program;
  1431. delete this.context;
  1432. const pt2_contents = torch.export.pt2_archive._package.load_pt2(f);
  1433. this.modules = pt2_contents.exported_programs;
  1434. }
  1435. async _fetch(name) {
  1436. try {
  1437. const context = await this.context.fetch(name);
  1438. if (context) {
  1439. return await context.peek('zip');
  1440. }
  1441. } catch {
  1442. // continue regardless of error
  1443. }
  1444. return null;
  1445. }
  1446. async _text(name) {
  1447. try {
  1448. const content = await this.context.fetch(name);
  1449. if (content) {
  1450. const reader = await content.read('text');
  1451. if (reader) {
  1452. return reader.read();
  1453. }
  1454. }
  1455. } catch {
  1456. // continue regardless of error
  1457. }
  1458. return '';
  1459. }
  1460. };
  1461. pytorch.Execution = class extends python.Execution {
  1462. constructor(sources, metadata) {
  1463. super(sources);
  1464. this._metadata = metadata;
  1465. /* eslint-disable consistent-this */
  1466. const execution = this;
  1467. /* eslint-enable consistent-this */
  1468. const torch = this.torch;
  1469. this.registerFunction('torch.jit.jit_module_from_flatbuffer', (f) => {
  1470. const cu = new torch.jit.CompilationUnit();
  1471. cu.execution = execution;
  1472. const stream = f;
  1473. const reader = flatbuffers.BinaryReader.open(stream);
  1474. const module = torch.mobile.serialization.Module.create(reader);
  1475. const loader = new torch._C.FlatBuffersLoader(cu);
  1476. const cpp_module = loader.parseModule(module);
  1477. // parse_and_initialize_jit_module
  1478. // const mobilem = parse_and_initialize_mobile_module_for_jit(data, jit_files, jit_constants);
  1479. // const m = jitModuleFromSourceAndConstants(mobilem._ivalue(), jit_files, jit_constants, mobilem.bytecode_version());
  1480. // throw new pytorch.Error('torch.jit.mobile.serialization.Module not supported.');
  1481. return torch.jit._script.wrap_cpp_module(cpp_module);
  1482. });
  1483. this.registerType('__torch__.torch.classes._nnapi.Compilation', class {
  1484. constructor() {
  1485. this.__hide__ = true;
  1486. }
  1487. __init__() {
  1488. }
  1489. init(serialized_model_tensor, parameter_buffers) {
  1490. this.serialized_model_tensor = serialized_model_tensor;
  1491. this.parameter_buffers = parameter_buffers;
  1492. const buffers = parameter_buffers.map((buffer) => buffer.__source__.storage());
  1493. /*
  1494. let buffers = [];
  1495. if (!pytorch.Utility.isInstance(parameter_buffers, 'torch.Value')) {
  1496. buffers = parameter_buffers.map((buffer) => buffer.__source__.storage());
  1497. }
  1498. */
  1499. const serialized_model = serialized_model_tensor.storage().data;
  1500. this.serialized_model = new pytorch.nnapi.SerializedModel(serialized_model, buffers);
  1501. }
  1502. run(inputs, outputs) {
  1503. execution.variable(this.serialized_model_tensor);
  1504. this.serialized_model_tensor.__count__ = (this.serialized_model_tensor.__count__ || 0) + 1;
  1505. const type = new pytorch.nnapi.Graph(this.serialized_model);
  1506. const node = execution.graph.create(type, 0);
  1507. execution.graph.insertNode(node);
  1508. for (const tensor of inputs) {
  1509. const value = execution.variable(tensor);
  1510. node.addInput(value);
  1511. }
  1512. for (const tensor of outputs) {
  1513. execution.variable(tensor, node);
  1514. }
  1515. }
  1516. });
  1517. this.registerType('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', class {
  1518. __setstate__(state) {
  1519. if (state[0] !== '2') {
  1520. throw new pytorch.Error(`Unsupported pack version '${state[0]}'.`);
  1521. }
  1522. const [/* pack_version */, tensors, opt_tensors] = state;
  1523. const packed_config_tensor = new pytorch.Tensor('', tensors[0], true);
  1524. const packed_config = packed_config_tensor.decode();
  1525. /* eslint-disable prefer-destructuring */
  1526. this.weight = tensors[1];
  1527. this.bias = opt_tensors[0];
  1528. this.stride = [packed_config[1], packed_config[2]];
  1529. this.padding = [packed_config[3], packed_config[4]];
  1530. this.dilation = [packed_config[5], packed_config[6]];
  1531. this.output_padding = [packed_config[7], packed_config[8]];
  1532. this.groups = packed_config[9];
  1533. /* eslint-enable prefer-destructuring */
  1534. }
  1535. });
  1536. this.registerType('__torch__.torch.classes.quantized.Conv3dPackedParamsBase', class {
  1537. __setstate__(state) {
  1538. if (state[0] !== '2') {
  1539. throw new pytorch.Error(`Unsupported pack version '${state[0]}'.`);
  1540. }
  1541. const [/* pack_version */, tensors, opt_tensors] = state;
  1542. const packed_config_tensor = new pytorch.Tensor('', tensors[0], true);
  1543. const packed_config = packed_config_tensor.decode();
  1544. /* eslint-disable prefer-destructuring */
  1545. this.weight = tensors[1];
  1546. this.bias = opt_tensors[0];
  1547. this.stride = [packed_config[1], packed_config[2]];
  1548. this.padding = [packed_config[3], packed_config[4]];
  1549. this.dilation = [packed_config[5], packed_config[6]];
  1550. this.output_padding = [packed_config[7], packed_config[8]];
  1551. this.groups = packed_config[9];
  1552. /* eslint-enable prefer-destructuring */
  1553. }
  1554. });
  1555. this.registerType('__torch__.torch.classes.quantized.LinearPackedParamsBase', class {
  1556. __setstate__(state) {
  1557. [this.weight, this.bias] = state;
  1558. }
  1559. });
  1560. this.registerType('__torch__.torch.classes.quantized.EmbeddingPackedParamsBase', class {
  1561. __setstate__(state) {
  1562. [this.version, this.tensors, this.doubles, this.longs] = state;
  1563. }
  1564. });
  1565. this.registerType('__torch__.torch.classes.rnn.CellParamsBase', class {
  1566. __setstate__(state) {
  1567. [this.type, this.tensors, this.doubles, this.longs, this.packed_params] = state;
  1568. }
  1569. });
  1570. this.registerType('__torch__.torch.classes.xnnpack.Conv2dOpContext', class {
  1571. __setstate__(state) {
  1572. [this.weight, this.bias, this.stride, this.padding, this.dilation, this.groups, this.output_min, this.output_max] = state;
  1573. }
  1574. });
  1575. this.registerType('__torch__.torch.classes.xnnpack.LinearOpContext', class {
  1576. __setstate__(state) {
  1577. [this.weight, this.bias, this.output_min, this.output_max] = state;
  1578. }
  1579. });
  1580. this.registerType('__torch__.torch.classes.xnnpack.TransposeConv2dOpContext', class {
  1581. __setstate__(state) {
  1582. [this.weight, this.bias, this.stride, this.padding, this.output_padding, this.dilation, this.groups, this.output_min, this.output_max] = state;
  1583. }
  1584. });
  1585. this.registerType('__torch__.torch.classes.tensorrt.Engine', class {
  1586. __setstate__(state) {
  1587. [this.abi_target, this.name, this.device, this.engine, this.input_binding_names, this.output_binding_names, this.hw_compatible, this.serialized_metadata, this.target_platform] = state;
  1588. }
  1589. });
  1590. const custom_classes = [
  1591. { name: '__torch__.torch.classes._nnapi.Compilation', methods: [
  1592. '__init__(__torch__.torch.classes._nnapi.Compilation self) -> NoneType',
  1593. 'init(__torch__.torch.classes._nnapi.Compilation self, Tensor serialized_model_tensor, Tensor[] parameter_buffers) -> NoneType',
  1594. 'init2(__torch__.torch.classes._nnapi.Compilation self, Tensor serialized_model_tensor, Tensor[] parameter_buffers, int compilation_preference, bool relax_f32_to_f16) -> NoneType',
  1595. 'run(__torch__.torch.classes._nnapi.Compilation self, Tensor[] inputs, Tensor[] outputs) -> NoneType'
  1596. ] },
  1597. { name: '__torch__.torch.classes.quantized.Conv2dPackedParamsBase', attributes: 'Tensor weight, Tensor bias, int[] stride, int[] padding, int[] dilation, int groups', methods: ['unpack(__torch__.torch.classes.quantized.Conv2dPackedParamsBase self) -> ((Tensor, Tensor?))'] },
  1598. { name: '__torch__.torch.classes.quantized.Conv3dPackedParamsBase', attributes: 'Tensor weight, Tensor bias, int[] stride, int[] padding, int[] dilation, int groups', methods: ['unpack(__torch__.torch.classes.quantized.Conv3dPackedParamsBase self) -> ((Tensor, Tensor?))'] },
  1599. { name: '__torch__.torch.classes.quantized.LinearPackedParamsBase', attributes: 'Tensor weight, Tensor? bias' },
  1600. { name: '__torch__.torch.classes.quantized.EmbeddingPackedParamsBase', attributes: 'int version, Tensor[] tensors, float[] doubles, int[] longs', methods: [] },
  1601. { name: '__torch__.torch.classes.rnn.CellParamsBase', attributes: 'str type, Tensor[] tensors, float[] doubles, int[] longs, __torch__.torch.classes.quantized.LinearPackedParamsBase[] packed_params' },
  1602. { name: '__torch__.torch.classes.xnnpack.Conv2dOpContext', attributes: 'Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] dilation, int groups, int[] output_min, int[] output_max' },
  1603. { name: '__torch__.torch.classes.xnnpack.LinearOpContext', attributes: 'Tensor weight, Tensor bias, int[] output_min, int[] output_max' },
  1604. { name: '__torch__.torch.classes.xnnpack.TransposeConv2dOpContext', attributes: 'Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] output_padding, int[] dilation, int groups, int[] output_min, int[] output_max' },
  1605. { name: '__torch__.torch.classes.tensorrt.Engine' }
  1606. ];
  1607. for (const known_type of custom_classes) {
  1608. const prefix = new torch._C.QualifiedName(known_type.name);
  1609. const type = torch.ClassType.create(known_type.name, this._compilation_unit, false);
  1610. for (const known_method of known_type.methods || []) {
  1611. const schema = new torch.FunctionSchema(known_method);
  1612. const name = new torch._C.QualifiedName(prefix, schema.name);
  1613. const fn = new torch._C.BuiltinOpFunction(name, schema);
  1614. type.addMethod(fn);
  1615. }
  1616. if (known_type.attributes) {
  1617. const schema = new torch.FunctionSchema(`(${known_type.attributes}) -> ()`);
  1618. for (const arg of schema.arguments) {
  1619. type.addAttribute(arg.name, arg.real_type);
  1620. }
  1621. }
  1622. torch._C.registerCustomClass(type);
  1623. }
  1624. }
  1625. call(target, name, args, keywords, context) {
  1626. const ast = this.ast;
  1627. const torch = this.torch;
  1628. if (target instanceof ast.Name && target.id === 'torch') {
  1629. const fn = torch.ops.aten.__getattr__(name);
  1630. if (fn) {
  1631. const evalArgs = args.map((arg) => this.expression(arg, context));
  1632. return fn.__call__(...evalArgs);
  1633. }
  1634. }
  1635. if (target instanceof ast.Attribute && target.value instanceof ast.Name && target.value.id === 'ops') {
  1636. const module = torch.ops[target.attr];
  1637. if (!module) {
  1638. throw new pytorch.Error(`Unknown torch.ops module '${target.attr}'.`);
  1639. }
  1640. const fn = module.__getattr__(name);
  1641. if (fn) {
  1642. const evalArgs = args.map((arg) => this.expression(arg, context));
  1643. return fn.__call__(...evalArgs);
  1644. }
  1645. }
  1646. return super.call(target, name, args, keywords, context);
  1647. }
  1648. invoke(target, args) {
  1649. if (target && Array.isArray(target.__bases__) && target.__bases__.length > 0 && target.__bases__[0] === this.enum.Enum) {
  1650. const instance = new target();
  1651. instance.value = args;
  1652. return instance;
  1653. }
  1654. return super.invoke(target, args);
  1655. }
  1656. base(expr, context) {
  1657. const ast = this.ast;
  1658. if (expr instanceof ast.Name) {
  1659. switch (expr.id) {
  1660. case 'Enum': return this.enum.Enum;
  1661. default: break;
  1662. }
  1663. }
  1664. return this.expression(expr, context);
  1665. }
  1666. };
  1667. pytorch.Container.Package = class extends pytorch.Container {
  1668. constructor(entries) {
  1669. super();
  1670. this.type = 'pytorch.package';
  1671. this.entries = entries;
  1672. }
  1673. async read(metadata) {
  1674. this.execution = new pytorch.Execution(null, metadata);
  1675. for (const event of this._events) {
  1676. this.execution.on(event[0], event[1]);
  1677. }
  1678. const torch = this.execution.__import__('torch');
  1679. const reader = new torch.PyTorchFileReader(this.entries);
  1680. const version = reader.version();
  1681. this.format = pytorch.Utility.format('PyTorch Package', version);
  1682. this.modules = new Map();
  1683. const records = reader.get_all_records().filter((name) => {
  1684. if (!name.startsWith('.data/') && !name.endsWith('.py')) {
  1685. const stream = reader.get_record(name);
  1686. if (stream && stream.length > 2) {
  1687. const signature = stream.peek(2);
  1688. if (signature[0] === 0x80 && signature[1] < 7) {
  1689. return true;
  1690. }
  1691. }
  1692. }
  1693. return false;
  1694. });
  1695. const entries = records.map((name) => {
  1696. const parts = name.split('/');
  1697. const resource = parts.pop();
  1698. const module = parts.join('.');
  1699. return [module, resource];
  1700. });
  1701. if (entries.length > 0) {
  1702. for (const name of reader.get_all_records()) {
  1703. if (!name.startsWith('.data/') && name.endsWith('.py')) {
  1704. const stream = reader.get_record(name);
  1705. const buffer = stream.peek();
  1706. this.execution.add(name, buffer);
  1707. }
  1708. }
  1709. metadata.register(this.execution);
  1710. const importer = new torch.package.PackageImporter(reader);
  1711. for (const entry of entries) {
  1712. const module = importer.load_pickle(entry[0], entry[1]);
  1713. const key = `${entry[0].replace(/\./, '/')}/${entry[1]}`;
  1714. this.modules.set(key, module);
  1715. }
  1716. }
  1717. delete this.entries;
  1718. }
  1719. };
  1720. pytorch.MemoryFormat = {
  1721. Contiguous: 0,
  1722. Preserve: 1,
  1723. ChannelsLast: 2,
  1724. ChannelsLast3d: 3
  1725. };
  1726. pytorch.Layout = {
  1727. Strided: 0,
  1728. Sparse: 1,
  1729. Mkldnn: 2
  1730. };
  1731. pytorch.Utility = class {
  1732. static isTensor(obj) {
  1733. const name = obj && obj.__class__ ? obj.__class__.__module__ : null;
  1734. switch (name) {
  1735. case 'torch':
  1736. case 'torch.cuda':
  1737. return obj.__class__.__name__.endsWith('Tensor');
  1738. case 'torch.nn.parameter':
  1739. return obj.__class__.__name__ === 'Parameter';
  1740. default:
  1741. return false;
  1742. }
  1743. }
  1744. static toTensor(obj) {
  1745. const name = obj && obj.__class__ ? obj.__class__.__module__ : null;
  1746. switch (name) {
  1747. case 'torch':
  1748. case 'torch.cuda':
  1749. return obj.__class__.__name__.endsWith('Tensor') ? obj : null;
  1750. case 'torch.nn.parameter':
  1751. if (obj.__class__.__name__ === 'Parameter') {
  1752. const data = obj.data;
  1753. if (typeof obj.__name__ === 'string') {
  1754. data.__name__ = obj.__name__;
  1755. }
  1756. return data;
  1757. }
  1758. return null;
  1759. default:
  1760. return null;
  1761. }
  1762. }
  1763. static toType(type) {
  1764. switch (type.kind()) {
  1765. case 'OptionalType': return `${pytorch.Utility.toType(type.getElementType())}?`;
  1766. case 'ListType': return `${pytorch.Utility.toType(type.getElementType())}[]`;
  1767. case 'BoolType': return 'boolean';
  1768. case 'IntType': return 'int64';
  1769. case 'FloatType': return 'float32';
  1770. case 'StringType': return 'string';
  1771. case 'ComplexType': return 'complex';
  1772. case 'NumberType': return 'scalar';
  1773. case 'TensorType': return 'tensor';
  1774. case 'TupleType': return `tuple<${type.elements().map((type) => pytorch.Utility.toType(type)).join(', ')}>`;
  1775. case 'DictType': return `map<${pytorch.Utility.toType(type.getKeyType())}, ${pytorch.Utility.toType(type.getValueType())}>`;
  1776. case 'DeviceObjType': return 'device';
  1777. case 'SymIntType': return 'SymInt';
  1778. case 'ScalarTypeType': return 'ScalarType';
  1779. case 'MemoryFormat': return 'MemoryFormat';
  1780. case 'Layout': return 'Layout';
  1781. case 'VarType': return type.annotation_str;
  1782. case 'NoneType': return 'None';
  1783. case 'AnyListType': return 'list';
  1784. case 'AnyTupleType': return 'tuple';
  1785. case 'ClassType': return type.annotation_str;
  1786. case 'EnumType': return type.annotation_str;
  1787. default: throw new pytorch.Error(`Unsupported type '${type.kind()}'.`);
  1788. }
  1789. }
  1790. static toString(ivalue) {
  1791. if (ivalue.isInt()) {
  1792. return ivalue.toInt();
  1793. }
  1794. if (ivalue.isDouble()) {
  1795. return ivalue.toDouble();
  1796. }
  1797. if (ivalue.isEnum()) {
  1798. return ivalue.toEnumHolder().name();
  1799. }
  1800. if (ivalue.isList()) {
  1801. return ivalue.toList().map((item) => pytorch.Utility.toString(item));
  1802. }
  1803. throw new pytorch.Error(`Unsupported IValue '${ivalue.tag}.`);
  1804. }
  1805. static constant(node, name) {
  1806. const kind = node.kindOf(name);
  1807. switch (kind) {
  1808. case 's': return node.s(name);
  1809. case 'i': return node.i(name);
  1810. case 'f': return node.f(name);
  1811. case 'ss': return node.ss(name);
  1812. case 'ival': return node.ival(name);
  1813. default: throw new pytorch.Error(`Unsupported attribute kind '${kind}'.`);
  1814. }
  1815. }
  1816. static unique(value) {
  1817. return value.hasDebugName() ? `%${value.debugName().toString()}` : `%${value.unique().toString()}`;
  1818. }
  1819. static isObject(obj) {
  1820. const type = obj && obj.__class__ && obj.__class__.__module__ && obj.__class__.__name__ ? `${obj.__class__.__module__}.${obj.__class__.__name__}` : null;
  1821. switch (type) {
  1822. case '__torch__.torch.classes.xnnpack.LinearOpContext':
  1823. case '__torch__.torch.classes.xnnpack.Conv2dOpContext':
  1824. case '__torch__.torch.classes.xnnpack.TransposeConv2dOpContext':
  1825. case '__torch__.torch.classes.rnn.CellParamsBase':
  1826. case '__torch__.torch.classes.rnn.CellParamsBase[]':
  1827. case '__torch__.torch.classes.quantized.LinearPackedParamsBase':
  1828. case '__torch__.torch.classes.quantized.Conv2dPackedParamsBase':
  1829. case '__torch__.torch.classes.quantized.Conv3dPackedParamsBase':
  1830. case '__torch__.torch.classes.quantized.EmbeddingPackedParamsBase':
  1831. return true;
  1832. default:
  1833. return false;
  1834. }
  1835. }
  1836. static isSubclass(value, name) {
  1837. if (value && value.__module__ && value.__name__) {
  1838. return name === `${value.__module__}.${value.__name__}`;
  1839. } else if (value && value.__bases__) {
  1840. return value.__bases__.some((obj) => pytorch.Utility.isSubclass(obj, name));
  1841. }
  1842. return false;
  1843. }
  1844. static isInstance(value, name) {
  1845. return value && value.__class__ ? pytorch.Utility.isSubclass(value.__class__, name) : false;
  1846. }
  1847. static format(name, value) {
  1848. // https://github.com/pytorch/pytorch/blob/master/caffe2/serialize/inline_container.h
  1849. // kProducedFileFormatVersion
  1850. const versions = new Map([
  1851. ['1', 'v1.3'],
  1852. ['2', 'v1.5'], // 7a2889b014ce36fcc333b2c6de6f29f976652f84 (#28122)
  1853. ['3', 'v1.6'], // 2ec6a30722b0ef85632a2f3e7ce6f80da403008a (#36085)
  1854. ['4', 'v1.6'], // 95489b590f00801bdee7f41783f30874883cf6bb (#38620)
  1855. ['5', 'v1.7'], // cb26661fe4faf26386703180a9045e6ac6d157df (#40364)
  1856. ['6', 'v1.9'], // 3ee7637ffa50df0d9b231c7b40778ac1c390bf4a (#59714)
  1857. ['7', 'v1.10'], // 880098a7e34a20628f960daa8eab0eb1ad566c39 (#63651)
  1858. ['8', 'v1.11'], // b28e696516a7f0c7a6ead6da967590ce6c1d6698 (#71486)
  1859. ['9', 'v1.11'], // 8757e21c6a4fc00e83539aa7f9c28eb11eff53c1 (#72051)
  1860. ['10', 'v1.12'] // 4f8b986e28736b59bc46cd0873a0f36fdaa6f5b8 (#61439)
  1861. ]);
  1862. value = value.toString();
  1863. if (!versions.has(value)) {
  1864. throw new pytorch.Error(`Unsupported '${name}' version '${value}'.`);
  1865. }
  1866. return `${name} ${versions.get(value)}`;
  1867. }
  1868. static weights(obj) {
  1869. let type = obj && obj.__class__ && obj.__class__.__module__ && obj.__class__.__name__ ? `${obj.__class__.__module__}.${obj.__class__.__name__}` : null;
  1870. if (type === 'torch.jit._script.RecursiveScriptModule') {
  1871. type = obj._c._type();
  1872. const target = {};
  1873. for (let i = 0; i < type.numAttributes(); i++) {
  1874. const k = type.getAttributeName(i);
  1875. target[k] = obj.__getattr__(k);
  1876. }
  1877. type = obj._c.qualified_name;
  1878. obj = target;
  1879. } else if (type && type !== 'builtins.dict' && type !== 'builtins.object' && type !== 'collections.OrderedDict' && type !== 'torch.nn.modules.module.Module' && type !== '__torch__.Module') {
  1880. return null;
  1881. }
  1882. if (pytorch.Utility.isTensor(obj)) {
  1883. return null;
  1884. }
  1885. if (obj instanceof Map === false && obj && !Array.isArray(obj) && Object(obj) === obj) {
  1886. const entries = Object.entries(obj);
  1887. const named = entries.filter(([name, value]) => (typeof name === 'string' && (name.indexOf('.') !== -1 || name.indexOf('|') !== -1)) && pytorch.Utility.isTensor(value));
  1888. if (named.length > 0 && (named.length / entries.length) >= 0.8) {
  1889. obj = new Map(entries);
  1890. }
  1891. }
  1892. if (obj instanceof Map) {
  1893. const entries = Array.from(obj).filter(([name]) => name !== '_metadata');
  1894. const names = entries.filter(([name]) => typeof name === 'string' && (name.indexOf('.') !== -1 || name.indexOf('|') !== -1));
  1895. if (names.length > 1 && (names.length / entries.length) >= 0.8 &&
  1896. (entries.every(([, value]) => !pytorch.Utility.isInstance(value, 'builtins.dict') || Array.from(value.values()).every((value) => !pytorch.Utility.isTensor(value)))) &&
  1897. (!entries.every(([, value]) => Array.isArray(value)))) {
  1898. const modules = new Map();
  1899. for (const [name, value] of entries) {
  1900. const separator = name.indexOf('.') === -1 && name.indexOf('|') !== -1 ? '|' : '.';
  1901. const path = name.split(separator);
  1902. let property = path.pop();
  1903. if (path.length > 1 && path[path.length - 1] === '_packed_params') {
  1904. property = `${path.pop()}.${property}`;
  1905. }
  1906. const key = path.join(separator);
  1907. if (!modules.has(key)) {
  1908. modules.set(key, {});
  1909. }
  1910. const module = modules.get(key);
  1911. if (pytorch.Utility.isTensor(value)) {
  1912. value.__name__ = name;
  1913. }
  1914. module[property] = value;
  1915. }
  1916. return modules;
  1917. }
  1918. }
  1919. if (obj && !Array.isArray(obj) && Object(obj) === obj) {
  1920. const modules = new Map();
  1921. const entries = obj instanceof Map ? Array.from(obj) : Object.entries(obj);
  1922. if (entries.length > 0 && entries) {
  1923. for (const [key, value] of entries) {
  1924. const name = key.toString();
  1925. if (!value || Object(value) !== value || pytorch.Utility.isTensor(value) || ArrayBuffer.isView(value) || value._modules instanceof Map) {
  1926. return null;
  1927. }
  1928. if (!modules.has(name)) {
  1929. modules.set(name, {});
  1930. }
  1931. const module = modules.get(name);
  1932. let tensor = false;
  1933. const entries = value instanceof Map ? value : new Map(Object.entries(value));
  1934. for (const [name, value] of entries) {
  1935. if (typeof name !== 'string') {
  1936. return null;
  1937. }
  1938. if (name.indexOf('.') !== -1) {
  1939. return null;
  1940. }
  1941. if (name === '_metadata') {
  1942. continue;
  1943. }
  1944. if (typeof value === 'string' || typeof value === 'number') {
  1945. module[name] = value;
  1946. continue;
  1947. }
  1948. if (pytorch.Utility.isTensor(value)) {
  1949. value.__name__ = name;
  1950. module[name] = value;
  1951. tensor = true;
  1952. }
  1953. }
  1954. if (!tensor) {
  1955. return null;
  1956. }
  1957. }
  1958. return modules;
  1959. }
  1960. }
  1961. return null;
  1962. }
  1963. static isMetadataObject(obj) {
  1964. if (pytorch.Utility.isInstance(obj, 'collections.OrderedDict')) {
  1965. for (const value of obj.values()) {
  1966. if (pytorch.Utility.isInstance(value, 'builtins.dict')) {
  1967. const entries = Array.from(value);
  1968. if (entries.length !== 1 && entries[0] !== 'version' && entries[1] !== 1) {
  1969. return false;
  1970. }
  1971. }
  1972. }
  1973. return true;
  1974. }
  1975. return false;
  1976. }
  1977. };
  1978. pytorch.nnapi = {};
  1979. pytorch.nnapi.SerializedModel = class {
  1980. constructor(serialized_model, buffers) {
  1981. const reader = base.BinaryReader.open(serialized_model);
  1982. this.version = reader.int32();
  1983. if (this.version !== 1) {
  1984. throw new pytorch.Error('Invalid NNAPI serialized model version.');
  1985. }
  1986. const operands = new Array(reader.int32());
  1987. const values = new Array(reader.int32());
  1988. this.operations = new Array(reader.int32());
  1989. this.inputs = new Array(reader.int32());
  1990. this.outputs = new Array(reader.int32());
  1991. const data_types = new Map([
  1992. [0, 'float32'],
  1993. [1, 'int32'],
  1994. [2, 'uint32'],
  1995. [3, 'float32[]'],
  1996. [4, 'int32[]'],
  1997. [5, 'quant8_asymm[]'],
  1998. [6, 'boolean'],
  1999. [7, 'quant16_symm[]'],
  2000. [8, 'float16[]'],
  2001. [9, 'boolean[]'],
  2002. [10, 'float16'],
  2003. [11, 'quant8_symm_per_channel[]'],
  2004. [12, 'quant16_asymm[]'],
  2005. [13, 'quant8_symm[]'],
  2006. [14, 'quant8_asymm_signed[]'],
  2007. [16, 'model']
  2008. ]);
  2009. for (let i = 0; i < operands.length; i++) {
  2010. const data_type = reader.int32();
  2011. operands[i] = {
  2012. index: i,
  2013. data_type: data_types.has(data_type) ? data_types.get(data_type) : data_type,
  2014. dimensions: new Array(reader.uint32()),
  2015. scale: reader.float32(),
  2016. zero_point: reader.int32()
  2017. };
  2018. }
  2019. for (let i = 0; i < values.length; i++) {
  2020. values[i] = {
  2021. index: reader.int32(),
  2022. source_type: reader.int32(),
  2023. source_length: reader.uint32()
  2024. };
  2025. }
  2026. for (let i = 0; i < this.operations.length; i++) {
  2027. this.operations[i] = {
  2028. index: reader.int32(),
  2029. identifier: i,
  2030. inputs: new Array(reader.uint32()),
  2031. outputs: new Array(reader.uint32())
  2032. };
  2033. }
  2034. for (const operand of operands) {
  2035. for (let i = 0; i < operand.dimensions.length; i++) {
  2036. operand.dimensions[i] = reader.uint32();
  2037. }
  2038. }
  2039. for (const value of values) {
  2040. const index = value.index;
  2041. const operand = operands[index];
  2042. switch (value.source_type) {
  2043. case 0: { // immediate
  2044. switch (operand.data_type) {
  2045. case 'boolean':
  2046. operand.value = reader.byte() ? true : false;
  2047. reader.skip(3);
  2048. break;
  2049. case 'int32':
  2050. operand.value = reader.int32();
  2051. break;
  2052. case 'float32':
  2053. operand.value = reader.float32();
  2054. break;
  2055. case 'int32[]':
  2056. operand.data = reader.read(value.source_length);
  2057. break;
  2058. case 'float32[]':
  2059. operand.data = reader.read(value.source_length);
  2060. break;
  2061. default:
  2062. throw new pytorch.Error(`Unsupported NNAPI operand type '${operand.data_type}'.`);
  2063. }
  2064. break;
  2065. }
  2066. case 2: { // numbered buffer
  2067. if (value.source_length !== 12) {
  2068. throw new pytorch.Error('Invalid NNAPI numbered buffer source length.');
  2069. }
  2070. const number = reader.uint32();
  2071. const offset = reader.uint32();
  2072. const operand_length = reader.uint32();
  2073. if (number < buffers.length && buffers[number].data) {
  2074. const storage = buffers[number];
  2075. const data = storage.data && storage.data.peek ? storage.data.peek() : storage.data;
  2076. operand.data = data.slice(offset, operand_length);
  2077. }
  2078. break;
  2079. }
  2080. case 3: { // numbered memory
  2081. throw new pytorch.Error('NNAPI numbered memory buffer not implemented.');
  2082. }
  2083. default: {
  2084. throw new pytorch.Error('Unsupported NNAPI value source type.');
  2085. }
  2086. }
  2087. }
  2088. for (const operation of this.operations) {
  2089. for (let i = 0; i < operation.inputs.length; i++) {
  2090. const index = reader.uint32();
  2091. operation.inputs[i] = operands[index];
  2092. }
  2093. for (let i = 0; i < operation.outputs.length; i++) {
  2094. const index = reader.uint32();
  2095. operation.outputs[i] = operands[index];
  2096. }
  2097. }
  2098. for (let i = 0; i < this.inputs.length; i++) {
  2099. const index = reader.uint32();
  2100. this.inputs[i] = operands[index];
  2101. }
  2102. for (let i = 0; i < this.outputs.length; i++) {
  2103. const index = reader.uint32();
  2104. this.outputs[i] = operands[index];
  2105. }
  2106. if (reader.position !== reader.length) {
  2107. throw new pytorch.Error('Invalid NNAPI serialized model length.');
  2108. }
  2109. }
  2110. };
  2111. pytorch.nnapi.Graph = class {
  2112. constructor(model) {
  2113. this.name = 'torch.classes._nnapi.Compilation';
  2114. this.nodes = [];
  2115. this.inputs = [];
  2116. this.outputs = [];
  2117. const values = new Map();
  2118. values.map = (operand) => {
  2119. if (!values.has(operand.index)) {
  2120. const name = operand.index.toString();
  2121. const dimensions = operand.dimensions;
  2122. const shape = new pytorch.TensorShape(dimensions);
  2123. let dataType = operand.data_type.replace('[]', '');
  2124. let quantization = null;
  2125. switch (dataType) {
  2126. case 'quant8_asymm':
  2127. case 'quant8_symm_per_channel':
  2128. case 'quant8_symm':
  2129. case 'quant8_asymm_signed[]':
  2130. case 'quant16_asymm':
  2131. case 'quant16_symm':
  2132. quantization = dataType;
  2133. dataType = dataType.indexOf('16') === -1 ? 'uint8' : 'uint16';
  2134. break;
  2135. default:
  2136. break;
  2137. }
  2138. const type = new pytorch.TensorType(dataType, shape);
  2139. let initializer = null;
  2140. if (operand.data) {
  2141. const size = dimensions.reduce((a, b) => a * b, 1);
  2142. const tensor = {
  2143. size: () => dimensions,
  2144. stride: () => null,
  2145. storage_offset: () => 0,
  2146. storage: () => ({
  2147. dtype: { __reduce__: () => type.dataType },
  2148. data: operand.data, size: () => size
  2149. })
  2150. };
  2151. initializer = new pytorch.Tensor(null, tensor);
  2152. }
  2153. if (quantization || (operand.scale !== undefined && operand.scale !== 0) || (operand.zero_point !== undefined && operand.zero_point !== 0)) {
  2154. quantization = {
  2155. type: quantization || 'linear',
  2156. scale: [operand.scale],
  2157. offset: [operand.zero_point]
  2158. };
  2159. }
  2160. const value = new pytorch.Value(name, type, quantization, initializer);
  2161. values.set(operand.index, value);
  2162. }
  2163. return values.get(operand.index);
  2164. };
  2165. const metadata = new pytorch.nnapi.Metadata();
  2166. for (const operation of model.operations) {
  2167. const node = new pytorch.nnapi.Node(metadata, operation, values);
  2168. this.nodes.push(node);
  2169. }
  2170. for (let i = 0; i < model.inputs.length; i++) {
  2171. const name = i.toString();
  2172. const operand = model.inputs[i];
  2173. const argument = new pytorch.Argument(name, [values.map(operand)]);
  2174. this.inputs.push(argument);
  2175. }
  2176. for (let i = 0; i < model.outputs.length; i++) {
  2177. const name = i.toString();
  2178. const operand = model.outputs[i];
  2179. const argument = new pytorch.Argument(name, [values.map(operand)]);
  2180. this.outputs.push(argument);
  2181. }
  2182. }
  2183. };
  2184. pytorch.nnapi.Node = class {
  2185. constructor(metadata, operation, values) {
  2186. const signature = (operation.inputs || []).map((input) => input.data_type);
  2187. this.name = '';
  2188. this.type = metadata.type(operation.index, signature);
  2189. this.inputs = [];
  2190. this.outputs = [];
  2191. this.attributes = [];
  2192. this.chain = [];
  2193. if (operation.identifier !== undefined) {
  2194. this.identifier = operation.identifier.toString();
  2195. }
  2196. if (Array.isArray(operation.inputs)) {
  2197. const inputs = this.type.inputs;
  2198. for (let i = 0; i < operation.inputs.length; i++) {
  2199. const name = i < inputs.length ? inputs[i].name : i.toString();
  2200. const operand = operation.inputs[i];
  2201. if (operand.dimensions.length > 0) {
  2202. const value = values.map(operand);
  2203. const argument = new pytorch.Argument(name, [value]);
  2204. this.inputs.push(argument);
  2205. } else if (name === 'activation') {
  2206. const activation = new Map([[1, 19], [2, 20], [3, 21]]).get(operand.value) || 0;
  2207. if (activation !== 0) {
  2208. this.chain.push(new pytorch.nnapi.Node(metadata, { index: activation }));
  2209. }
  2210. } else {
  2211. const attribute = new pytorch.Argument(name, operand.value, operand.data_type, false);
  2212. this.inputs.push(attribute);
  2213. }
  2214. }
  2215. }
  2216. if (Array.isArray(operation.outputs)) {
  2217. const outputs = this.type.outputs;
  2218. for (let i = 0; i < operation.outputs.length; i++) {
  2219. const name = i < outputs.length ? outputs[i].name : i.toString();
  2220. const operand = operation.outputs[i];
  2221. const value = values.map(operand);
  2222. const argument = new pytorch.Argument(name, [value]);
  2223. this.outputs.push(argument);
  2224. }
  2225. }
  2226. }
  2227. };
  2228. pytorch.nnapi.Metadata = class {
  2229. constructor() {
  2230. this._types = new Map();
  2231. // https://developer.android.com/ndk/reference/group/neural-networks
  2232. // https://github.com/pytorch/pytorch/commits/master/torch/backends/_nnapi/serializer.py
  2233. this.register(0, 'ADD', '', ['A', 'B'], [['activation', 'int32']], ['C']);
  2234. this.register(1, 'AVERAGE_POOL_2D', 'Pool', ['input'], [['padding_left', 'int32'], ['padding_right', 'int32'], ['padding_top', 'int32'], ['padding_bottom', 'int32'], ['stride_x', 'int32'], ['stride_y', 'int32'], ['filter_x', 'int32'], ['filter_y', 'int32'], ['activation', 'int32'], ['nchw', 'boolean']], ['output']);
  2235. this.register(1, 'AVERAGE_POOL_2D', 'Pool', ['input'], [['padding_scheme', 'int32'], ['stride_x', 'int32'], ['stride_y', 'int32'], ['filter_x', 'int32'], ['filter_y', 'int32'], ['activation', 'int32'], ['nchw', 'boolean']], ['output']);
  2236. this.register(2, 'CONCATENATION');
  2237. this.register(3, 'CONV_2D', 'Layer', ['input', 'weights', 'bias'], [['padding_left', 'int32'], ['padding_right', 'int32'], ['padding_top', 'int32'], ['padding_bottom', 'int32'], ['stride_x', 'int32'], ['stride_y', 'int32'], ['activation', 'int32'], ['nchw', 'boolean'], ['dilation_width', 'int32'], ['dilation_height', 'int32']], ['output']);
  2238. this.register(3, 'CONV_2D', 'Layer', ['input', 'weights', 'bias'], [['padding_scheme', 'int32'], ['stride_x', 'int32'], ['stride_y', 'int32'], ['activation', 'int32'], ['nchw', 'boolean'], ['dilation_width', 'int32'], ['dilation_height', 'int32']], ['output']);
  2239. this.register(4, 'DEPTHWISE_CONV_2D', 'Layer', ['input', 'weights', 'bias'], [['padding_left', 'int32'], ['padding_right', 'int32'], ['padding_top', 'int32'], ['padding_bottom', 'int32'], ['stride_x', 'int32'], ['stride_y', 'int32'], ['activation', 'int32'], ['nchw', 'boolean'], ['dilation_width', 'int32'], ['dilation_height', 'int32']], ['output']);
  2240. this.register(4, 'DEPTHWISE_CONV_2D', 'Layer', ['input', 'weights', 'bias'], [['padding_scheme', 'int32'], ['stride_x', 'int32'], ['stride_y', 'int32'], ['activation', 'int32'], ['nchw', 'boolean'], ['dilation_width', 'int32'], ['dilation_height', 'int32']], ['output']);
  2241. this.register(5, 'DEPTH_TO_SPACE');
  2242. this.register(6, 'DEQUANTIZE');
  2243. this.register(7, 'EMBEDDING_LOOKUP');
  2244. this.register(8, 'FLOOR');
  2245. this.register(9, 'FULLY_CONNECTED', 'Layer', ['input', 'weights', 'bias'], [['activation', 'int32']], ['output']);
  2246. this.register(10, 'HASHTABLE_LOOKUP');
  2247. this.register(11, 'L2_NORMALIZATION');
  2248. this.register(12, 'L2_POOL_2D', 'Pool');
  2249. this.register(13, 'LOCAL_RESPONSE_NORMALIZATION');
  2250. this.register(14, 'LOGISTIC');
  2251. this.register(15, 'LSH_PROJECTION');
  2252. this.register(16, 'LSTM', 'Layer');
  2253. this.register(17, 'MAX_POOL_2D', 'Pool');
  2254. this.register(18, 'MUL');
  2255. this.register(19, 'RELU', 'Activation', ['input'], [], ['output']);
  2256. this.register(20, 'RELU1', 'Activation');
  2257. this.register(21, 'RELU6', 'Activation');
  2258. this.register(22, 'RESHAPE', 'Shape', ['input', 'shape'], [], ['output']);
  2259. this.register(23, 'RESIZE_BILINEAR');
  2260. this.register(24, 'RNN', 'Layer');
  2261. this.register(25, 'SOFTMAX', 'Activation');
  2262. this.register(26, 'SPACE_TO_DEPTH');
  2263. this.register(27, 'SVDF');
  2264. this.register(28, 'TANH');
  2265. this.register(29, 'BATCH_TO_SPACE_ND');
  2266. this.register(30, 'DIV');
  2267. this.register(31, 'MEAN');
  2268. this.register(32, 'PAD');
  2269. this.register(33, 'SPACE_TO_BATCH_ND');
  2270. this.register(34, 'SQUEEZE');
  2271. this.register(35, 'STRIDED_SLICE');
  2272. this.register(36, 'SUB');
  2273. this.register(37, 'TRANSPOSE');
  2274. this.register(38, 'ABS');
  2275. this.register(39, 'ARGMAX');
  2276. this.register(40, 'ARGMIN');
  2277. this.register(41, 'AXIS_ALIGNED_BBOX_TRANSFORM');
  2278. this.register(42, 'BIDIRECTIONAL_SEQUENCE_LSTM');
  2279. this.register(43, 'BIDIRECTIONAL_SEQUENCE_RNN');
  2280. this.register(44, 'BOX_WITH_NMS_LIMIT');
  2281. this.register(45, 'CAST');
  2282. this.register(46, 'CHANNEL_SHUFFLE');
  2283. this.register(47, 'DETECTION_POSTPROCESSING');
  2284. this.register(48, 'EQUAL');
  2285. this.register(49, 'EXP');
  2286. this.register(50, 'EXPAND_DIMS');
  2287. this.register(51, 'GATHER');
  2288. this.register(52, 'GENERATE_PROPOSALS');
  2289. this.register(53, 'GREATER');
  2290. this.register(54, 'GREATER_EQUAL');
  2291. this.register(55, 'GROUPED_CONV_2D');
  2292. this.register(56, 'HEATMAP_MAX_KEYPOINT');
  2293. this.register(57, 'INSTANCE_NORMALIZATION');
  2294. this.register(58, 'LESS');
  2295. this.register(59, 'LESS_EQUAL');
  2296. this.register(60, 'LOG');
  2297. this.register(61, 'LOGICAL_AND');
  2298. this.register(62, 'LOGICAL_NOT');
  2299. this.register(63, 'LOGICAL_OR');
  2300. this.register(64, 'LOG_SOFTMAX');
  2301. this.register(65, 'MAXIMUM');
  2302. this.register(66, 'MINIMUM');
  2303. this.register(67, 'NEG');
  2304. this.register(68, 'NOT_EQUAL');
  2305. this.register(69, 'PAD_V2');
  2306. this.register(70, 'POW');
  2307. this.register(71, 'PRELU');
  2308. this.register(72, 'QUANTIZE');
  2309. this.register(73, 'QUANTIZED_16BIT_LSTM');
  2310. this.register(74, 'RANDOM_MULTINOMIAL');
  2311. this.register(75, 'REDUCE_ALL');
  2312. this.register(76, 'REDUCE_ANY');
  2313. this.register(77, 'REDUCE_MAX');
  2314. this.register(78, 'REDUCE_MIN');
  2315. this.register(79, 'REDUCE_PROD');
  2316. this.register(80, 'REDUCE_SUM');
  2317. this.register(81, 'ROI_ALIGN');
  2318. this.register(82, 'ROI_POOLING');
  2319. this.register(83, 'RSQRT');
  2320. this.register(84, 'SELECT');
  2321. this.register(85, 'SIN');
  2322. this.register(86, 'SLICE');
  2323. this.register(87, 'SPLIT');
  2324. this.register(88, 'SQRT');
  2325. this.register(89, 'TILE');
  2326. this.register(90, 'TOPK_V2');
  2327. this.register(91, 'TRANSPOSE_CONV_2D', 'Layer');
  2328. this.register(92, 'UNIDIRECTIONAL_SEQUENCE_LSTM', 'Layer');
  2329. this.register(93, 'UNIDIRECTIONAL_SEQUENCE_RNN', 'Layer');
  2330. this.register(94, 'RESIZE_NEAREST_NEIGHBOR');
  2331. this.register(95, 'QUANTIZED_LSTM', 'Layer');
  2332. this.register(96, 'IF');
  2333. this.register(97, 'WHILE');
  2334. this.register(98, 'ELU', 'Activation');
  2335. this.register(99, 'HARD_SWISH', 'Activation');
  2336. this.register(100, 'FILL');
  2337. this.register(101, 'RANK');
  2338. }
  2339. register(index, name, category, inputs, attributes, outputs) {
  2340. inputs = inputs || [];
  2341. outputs = outputs || [];
  2342. attributes = attributes || [];
  2343. const type = {};
  2344. type.name = name;
  2345. type.inputs = inputs.map((name) => ({ name, type: 'Tensor' }));
  2346. type.inputs = type.inputs.concat(attributes.map(([name, type]) => ({ name, type })));
  2347. type.outputs = outputs.map((name) => ({ name, type: 'Tensor' }));
  2348. if (category) {
  2349. type.category = category;
  2350. }
  2351. if (!this._types.has(index)) {
  2352. this._types.set(index, []);
  2353. }
  2354. this._types.get(index).push(type);
  2355. }
  2356. type(index, signature) {
  2357. if (!this._types.has(index)) {
  2358. this._types.set(index, { name: index.toString(), inputs: [], outputs: [], attributes: [] });
  2359. }
  2360. const types = this._types.get(index);
  2361. for (const type of types) {
  2362. const inputs = type.inputs;
  2363. if (signature.length < inputs.length) {
  2364. if (inputs.every((input, i) => input.type === undefined || input.type === 'Tensor' || input.type === signature[i])) {
  2365. return type;
  2366. }
  2367. }
  2368. }
  2369. return types[0];
  2370. }
  2371. };
  2372. pytorch.Metadata = class {
  2373. static async open(context) {
  2374. if (!pytorch.Metadata._metadata) {
  2375. let data = null;
  2376. try {
  2377. data = await context.request('pytorch-metadata.json');
  2378. } catch {
  2379. // continue regardless of error
  2380. }
  2381. pytorch.Metadata._metadata = new pytorch.Metadata(data);
  2382. }
  2383. return pytorch.Metadata._metadata;
  2384. }
  2385. constructor(data) {
  2386. this._types = new Map();
  2387. this._attributes = new Map();
  2388. this._index = new Map();
  2389. if (data) {
  2390. const items = JSON.parse(data);
  2391. for (const item of items) {
  2392. const index = item.name.indexOf('(');
  2393. const key = index === -1 ? item.name : item.name.substring(0, index);
  2394. this._types.set(key, item);
  2395. }
  2396. }
  2397. }
  2398. add(name, value) {
  2399. this._types.set(name, value);
  2400. }
  2401. type(name) {
  2402. return this._types.get(name);
  2403. }
  2404. attribute(type, name) {
  2405. const key = `${type}:${name}`;
  2406. if (!this._attributes.has(key)) {
  2407. this._attributes.set(key, null);
  2408. const metadata = this.type(type);
  2409. if (metadata) {
  2410. if (metadata.inputs) {
  2411. for (const input of metadata.inputs) {
  2412. this._attributes.set(`${type}:${input.name}`, input);
  2413. }
  2414. }
  2415. if (metadata.attributes) {
  2416. for (const attribute of metadata.attributes) {
  2417. this._attributes.set(`${type}:${attribute.name}`, attribute);
  2418. }
  2419. }
  2420. }
  2421. }
  2422. return this._attributes.get(key);
  2423. }
  2424. register(execution) {
  2425. const torch = execution.register('torch');
  2426. const registry = torch._C.getRegistry();
  2427. const modules = new Set();
  2428. for (const [name, type] of this._types) {
  2429. if (name.indexOf('::') !== -1) {
  2430. const schema = torch.FunctionSchema.parse(type.name);
  2431. if (type.category) {
  2432. schema.category = type.category;
  2433. }
  2434. schema.setAliasAnalysis('FROM_SCHEMA');
  2435. const op = new torch._C.Operator(schema);
  2436. registry.registerOperator(op);
  2437. modules.add(type.name.split('::')[0]);
  2438. }
  2439. }
  2440. for (const module of modules) {
  2441. const namespace = new torch._ops._OpNamespace(module);
  2442. execution.register(`torch.ops.${module}`, namespace);
  2443. }
  2444. }
  2445. };
  2446. numpy.Tensor = class {
  2447. constructor(array) {
  2448. this.type = new numpy.TensorType(array.dtype.__name__, new numpy.TensorShape(array.shape));
  2449. this.stride = array.strides.map((stride) => stride / array.itemsize);
  2450. this.encoding = this.type.dataType === 'string' || this.type.dataType === 'object' ? '|' : array.dtype.byteorder;
  2451. this.values = this.type.dataType === 'string' || this.type.dataType === 'object' || this.type.dataType === 'void' ? array.flatten().tolist() : array.tobytes();
  2452. }
  2453. };
  2454. numpy.TensorType = class {
  2455. constructor(dataType, shape) {
  2456. this.dataType = dataType || '?';
  2457. this.shape = shape;
  2458. }
  2459. toString() {
  2460. return this.dataType + this.shape.toString();
  2461. }
  2462. };
  2463. numpy.TensorShape = class {
  2464. constructor(dimensions) {
  2465. this.dimensions = dimensions;
  2466. }
  2467. toString() {
  2468. return this.dimensions && this.dimensions.length > 0 ? `[${this.dimensions.join(',')}]` : '';
  2469. }
  2470. };
  2471. pytorch.Error = class extends Error {
  2472. constructor(message) {
  2473. super(message);
  2474. this.name = 'Error loading PyTorch model.';
  2475. }
  2476. };
  2477. export const Metadata = pytorch.Metadata;
  2478. export const ModelFactory = pytorch.ModelFactory;