pytorch.js 161 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814
  1. /* jshint esversion: 6 */
  2. // Experimental
  3. var pytorch = pytorch || {};
  4. var python = python || require('./python');
  5. var base = base || require('./base');
  6. pytorch.ModelFactory = class {
  7. match(context) {
  8. if (pytorch.Container.open(context)) {
  9. return true;
  10. }
  11. return false;
  12. }
  13. open(context) {
  14. const identifier = context.identifier;
  15. return pytorch.Metadata.open(context).then((metadata) => {
  16. let container = null;
  17. try {
  18. container = pytorch.Container.open(context, metadata, (error, fatal) => {
  19. const message = error && error.message ? error.message : error.toString();
  20. context.exception(new pytorch.Error(message.replace(/\.$/, '') + " in '" + identifier + "'."), fatal);
  21. });
  22. }
  23. catch (error) {
  24. const message = error && error.message ? error.message : error.toString();
  25. throw new pytorch.Error('File format is not PyTorch (' + message.replace(/\.$/, '') + ').');
  26. }
  27. return new pytorch.Model(metadata, container);
  28. });
  29. }
  30. };
  31. pytorch.Model = class {
  32. constructor(metadata, container) {
  33. this._format = container.format;
  34. this._producer = container.producer || '';
  35. this._graphs = [];
  36. const type = container.type;
  37. switch (type) {
  38. case 'script':
  39. this._graphs.push(new pytorch.Graph(metadata, type, container.data, container));
  40. break;
  41. case 'module':
  42. case 'weights':
  43. for (const data of container.data) {
  44. this._graphs.push(new pytorch.Graph(metadata, type, data, container));
  45. }
  46. break;
  47. }
  48. }
  49. get format() {
  50. return this._format;
  51. }
  52. get graphs() {
  53. return this._graphs;
  54. }
  55. };
  56. pytorch.Graph = class {
  57. constructor(metadata, type, data, container) {
  58. this._nodes = [];
  59. this._inputs = [];
  60. this._outputs = [];
  61. this._groups = true;
  62. this._littleEndian = container.littleEndian;
  63. switch (type) {
  64. case 'script': {
  65. this._name = container.name;
  66. const traced = container.trace();
  67. const initializers = new Map();
  68. if (container.constants) {
  69. for (const constant of container.constants) {
  70. if (pytorch.Utility.isTensor(constant)) {
  71. constant.initializer = new pytorch.Tensor(constant.__variable__, constant, this._littleEndian);
  72. initializers.set(constant.__variable__, constant);
  73. }
  74. else if (constant && constant.__class__ && constant.__class__.__module__ === '__torch__.torch.classes.xnnpack') {
  75. switch (constant.__class__.__name__) {
  76. case 'LinearOpContext':
  77. case 'Conv2dOpContext':
  78. for (const key of Object.keys(constant)) {
  79. const value = constant[key];
  80. if (pytorch.Utility.isTensor(value)) {
  81. value.initializer = new pytorch.Tensor(value.__variable__, value, this._littleEndian);
  82. initializers.set(value.__variable__, value);
  83. }
  84. }
  85. break;
  86. default:
  87. throw new pytorch.Error("Unsupported constant context '" + constant.__class__.__name__ + "'.");
  88. }
  89. }
  90. else {
  91. throw new pytorch.Error('Unsupported constant.');
  92. }
  93. }
  94. }
  95. if (data) {
  96. const queue = [ data ];
  97. while (queue.length > 0) {
  98. const module = queue.shift();
  99. if (module.__class__ && module.__class__.__module__ === '__torch__.torch.classes._nnapi' && module.__class__.__name__ === 'Compilation') {
  100. continue;
  101. }
  102. for (const key of Object.keys(module)) {
  103. if (key !== '__module__' && key !== '__name__' && key !== '__class__' && key !== '__parent__') {
  104. const obj = module[key];
  105. if (!Array.isArray(obj) && obj === Object(obj)) {
  106. if (pytorch.Utility.isTensor(obj)) {
  107. const parameter = obj;
  108. parameter.__parent__ = module;
  109. if (!parameter.initializer && parameter.storage()) {
  110. parameter.initializer = new pytorch.Tensor(parameter.name, parameter, this._littleEndian);
  111. }
  112. if (parameter.__variable__ && parameter.__count__ === 1) {
  113. initializers.set(parameter.__variable__, parameter);
  114. }
  115. }
  116. else if (obj && obj.__class__) {
  117. obj.__parent__ = module;
  118. if (!obj.__id__) {
  119. obj.__id__ = key;
  120. }
  121. queue.push(obj);
  122. }
  123. }
  124. }
  125. }
  126. }
  127. }
  128. if (traced) {
  129. if (container.inputs) {
  130. for (const input of container.inputs) {
  131. this._inputs.push(new pytorch.Parameter(input, true, [
  132. new pytorch.Argument(input, null, null)
  133. ]));
  134. }
  135. }
  136. if (container.outputs) {
  137. for (const output of container.outputs) {
  138. this._outputs.push(new pytorch.Parameter(output, true, [
  139. new pytorch.Argument(output, null, null)
  140. ]));
  141. }
  142. }
  143. if (container.nodes) {
  144. for (const node of container.nodes) {
  145. const item = {
  146. type: node.type,
  147. node: node
  148. };
  149. this._nodes.push(new pytorch.Node(metadata, '', item, initializers));
  150. }
  151. }
  152. }
  153. if (data) {
  154. this._loadScriptModule(metadata, container, data, initializers);
  155. }
  156. break;
  157. }
  158. case 'module': {
  159. this._name = data.name || '';
  160. this._type = (data.obj.__module__ && data.obj.__name__) ? (data.obj.__module__ + '.' + data.obj.__name__) : '';
  161. this._loadModule(metadata, data.obj, [], []);
  162. break;
  163. }
  164. case 'weights': {
  165. this._name = data.name || '';
  166. for (const state_group of data.layers) {
  167. const attributes = state_group.attributes || [];
  168. const inputs = state_group.states.map((parameter) => {
  169. return new pytorch.Parameter(parameter.name, true,
  170. parameter.arguments.map((state) => {
  171. const tensor = new pytorch.Tensor(state.id, pytorch.Utility.toTensor(state.value), this._littleEndian);
  172. return new pytorch.Argument(state.id, null, tensor);
  173. }));
  174. });
  175. const obj = {
  176. name: state_group.name,
  177. type: state_group.type || 'torch.nn.Module',
  178. attributes: attributes,
  179. inputs: inputs,
  180. outputs: []
  181. };
  182. this._nodes.push(new pytorch.Node(metadata, '', obj, null));
  183. }
  184. }
  185. }
  186. }
  187. _loadModule(metadata, current, groups, inputs) {
  188. if (current.__class__ && current.__class__.__module__ !== 'torch.nn.modules.container' && (!current._modules || current._modules.size == 0)) {
  189. this._createNode(metadata, groups, '', current, inputs, false);
  190. return [];
  191. }
  192. if (!current._modules) {
  193. throw new pytorch.Error('Module does not contain modules.');
  194. }
  195. const sequential = current.__class__ && current.__class__.__module__ === 'torch.nn.modules.container' && current.__class__.__name__ === 'Sequential';
  196. for (const pair of current._modules) {
  197. const key = pair[0];
  198. const value = pair[1];
  199. if (value) {
  200. const type = value.__class__.__module__ + '.' + value.__class__.__name__;
  201. switch (type) {
  202. case 'torch.nn.modules.container.Sequential':
  203. groups.push(key);
  204. inputs = this._loadModule(metadata, value, groups, sequential ? inputs : []);
  205. groups.pop(key);
  206. break;
  207. default: {
  208. inputs = this._createNode(metadata, groups, key, value, sequential ? inputs : [], sequential);
  209. break;
  210. }
  211. }
  212. }
  213. }
  214. return inputs;
  215. }
  216. _createNode(metadata, groups, key, obj, args, output) {
  217. const type = obj.__class__.__module__ + '.' + obj.__class__.__name__;
  218. const schema = metadata.type(type);
  219. let inputSchema = [ { name: 'input'} ];
  220. if (schema && schema.inputs && schema.inputs.length > 0) {
  221. inputSchema = schema.inputs.slice();
  222. }
  223. const inputName = inputSchema.shift().name;
  224. const inputs = [];
  225. if (args.length > 0) {
  226. inputs.push(new pytorch.Parameter(inputName, true, args.map((argument) => {
  227. return new pytorch.Argument(argument, null, null);
  228. })));
  229. }
  230. const parameters = obj._parameters || obj._buffers || [];
  231. for (const parameter of parameters) {
  232. const key = parameter[0];
  233. const value = pytorch.Utility.toTensor(parameter[1]);
  234. let visible = true;
  235. let inputName = '';
  236. if (inputSchema.length > 0) {
  237. const input = inputSchema.shift();
  238. inputName = input.name;
  239. visible = input.visible === false ? false : true;
  240. }
  241. if (value) {
  242. const initializer = new pytorch.Tensor('', value, this._littleEndian);
  243. inputs.push(new pytorch.Parameter(inputName || key, visible, [ new pytorch.Argument('', null, initializer) ]));
  244. }
  245. }
  246. const group = groups.join('/');
  247. const name = group ? (group + '/' + key) : key;
  248. const outputs = output ? [ new pytorch.Parameter('output', true, [ new pytorch.Argument(name, null, null) ]) ] : [];
  249. const attributes = [];
  250. for (const name of Object.keys(obj)) {
  251. if (name.startsWith('_')) {
  252. continue;
  253. }
  254. attributes.push({ name: name, value: obj[name] });
  255. }
  256. const item = {
  257. name: name,
  258. type: type,
  259. attributes: attributes,
  260. children: obj._modules && obj._modules.size > 0 ? true : false,
  261. inputs: inputs,
  262. outputs: outputs
  263. };
  264. const node = new pytorch.Node(metadata, group, item, {});
  265. this._nodes.push(node);
  266. return [ node.name ];
  267. }
  268. _loadScriptModule(metadata, container, module, initializers) {
  269. if (module) {
  270. if (pytorch.Graph._getParameters(module).length > 0 && !module.__hide__) {
  271. const item = { module: module };
  272. this._nodes.push(new pytorch.Node(metadata, '', item, initializers));
  273. }
  274. const submodules = pytorch.Graph._getSubmodules(module);
  275. for (const submodule of submodules) {
  276. this._loadScriptModule(metadata, container, submodule, initializers);
  277. }
  278. }
  279. }
  280. static _getParameters(module) {
  281. const parameters = [];
  282. if (module && module.__class__.__module__ && module.__class__.__name__) {
  283. for (const key of Object.keys(module)) {
  284. if (pytorch.Utility.isTensor(module[key])) {
  285. const parameter = module[key];
  286. parameter.__id__ = key;
  287. parameters.push(parameter);
  288. }
  289. }
  290. }
  291. return parameters;
  292. }
  293. static _getSubmodules(module) {
  294. const submodules = [];
  295. if (module && module.__class__ && module.__class__.__module__ && module.__class__.__name__) {
  296. for (const key of Object.keys(module)) {
  297. if (!key.startsWith('__')) {
  298. const value = module[key];
  299. if (value && value.__class__ && value.__module__ && value.__name__ && !pytorch.Utility.isTensor(value)) {
  300. submodules.push(value);
  301. }
  302. }
  303. }
  304. }
  305. return submodules;
  306. }
  307. get type() {
  308. return this._type;
  309. }
  310. get name() {
  311. return this._name;
  312. }
  313. get groups() {
  314. return this._groups;
  315. }
  316. get inputs() {
  317. return this._inputs;
  318. }
  319. get outputs() {
  320. return this._outputs;
  321. }
  322. get nodes() {
  323. return this._nodes;
  324. }
  325. };
  326. pytorch.Parameter = class {
  327. constructor(name, visible, args) {
  328. this._name = name;
  329. this._visible = visible;
  330. this._arguments = args;
  331. }
  332. get name() {
  333. return this._name;
  334. }
  335. get visible() {
  336. return this._visible;
  337. }
  338. get arguments() {
  339. return this._arguments;
  340. }
  341. };
  342. pytorch.Argument = class {
  343. constructor(name, type, initializer) {
  344. if (typeof name !== 'string') {
  345. throw new pytorch.Error("Invalid argument identifier '" + JSON.stringify(name) + "'.");
  346. }
  347. this._name = name;
  348. this._type = type;
  349. this._initializer = initializer;
  350. }
  351. get name() {
  352. return this._name;
  353. }
  354. get type() {
  355. if (this._initializer) {
  356. return this._initializer.type;
  357. }
  358. return this._type;
  359. }
  360. get initializer() {
  361. return this._initializer;
  362. }
  363. };
  364. pytorch.Node = class {
  365. constructor(metadata, group, item, initializers) {
  366. this._metadata = metadata;
  367. this._group = group || '';
  368. this._name = item.name || '';
  369. if (!item.module && !item.node) {
  370. this._type = item.type;
  371. this._function = item.children;
  372. this._inputs = item.inputs;
  373. this._outputs = item.outputs;
  374. this._attributes = item.attributes.map((attribute) => {
  375. const schema = metadata.attribute(this._type, attribute.name);
  376. return new pytorch.Attribute(schema, attribute.name, attribute.value);
  377. });
  378. }
  379. else {
  380. this._attributes = [];
  381. this._inputs = [];
  382. this._outputs = [];
  383. let module = item.module;
  384. if (module) {
  385. this._type = 'torch.nn.modules.module.Module';
  386. for (const parameter of pytorch.Graph._getParameters(module)) {
  387. this._inputs.push(new pytorch.Parameter(parameter.__id__, true, [
  388. new pytorch.Argument('', null, parameter.initializer || null)
  389. ]));
  390. if (parameter.__variable__) {
  391. this._outputs.push(new pytorch.Parameter(parameter.__id__, true, [
  392. new pytorch.Argument(parameter.__variable__, null, null)
  393. ]));
  394. }
  395. }
  396. }
  397. if (item.node) {
  398. this._type = item.type;
  399. const schema = metadata.type(this._type);
  400. module = null;
  401. let match = true;
  402. let count = 0;
  403. for (const input of item.node.inputs) {
  404. for (const argument of input) {
  405. const parameter = initializers.get(argument.id);
  406. if (parameter) {
  407. if (parameter.__parent__ && (module == null || module == parameter.__parent__)) {
  408. module = parameter.__parent__;
  409. count++;
  410. }
  411. else if (parameter.__variable__.startsWith('CONSTANTS.c')) {
  412. argument.initializer = parameter.initializer;
  413. count++;
  414. }
  415. else {
  416. match = false;
  417. break;
  418. }
  419. }
  420. }
  421. if (!match) {
  422. break;
  423. }
  424. }
  425. if (module) {
  426. const params = pytorch.Graph._getParameters(module).filter((p) => p.__id__ !== 'num_batches_tracked');
  427. if (params.length == count && match) {
  428. module.__hide__ = true;
  429. for (const input of item.node.inputs) {
  430. for (const argument of input) {
  431. const parameter = initializers.get(argument.id);
  432. if (parameter && parameter.initializer) {
  433. argument.initializer = parameter.initializer;
  434. }
  435. }
  436. }
  437. }
  438. else {
  439. module = null;
  440. }
  441. }
  442. for (let inputIndex = 0; inputIndex < item.node.inputs.length; inputIndex++) {
  443. let inputName = inputIndex.toString();
  444. if (schema && schema.inputs && schema.inputs.length > inputIndex) {
  445. inputName = schema.inputs[inputIndex].name;
  446. }
  447. this._inputs.push(new pytorch.Parameter(inputName, true,
  448. item.node.inputs[inputIndex].map((input) => new pytorch.Argument(input.id, null, input.initializer || null))
  449. ));
  450. }
  451. for (let outputIndex = 0; outputIndex < item.node.outputs.length; outputIndex++) {
  452. let outputName = outputIndex.toString();
  453. if (schema && schema.outputs && schema.outputs.length > outputIndex) {
  454. outputName = schema.outputs[outputIndex].name;
  455. }
  456. this._outputs.push(new pytorch.Parameter(outputName, true,
  457. item.node.outputs[outputIndex].map((output) => new pytorch.Argument(output.id, null, null))
  458. ));
  459. }
  460. for (const attribute of item.node.attributes) {
  461. const name = attribute.name;
  462. const value = attribute.value;
  463. const schema = metadata.attribute(this._type, name);
  464. this._attributes.push(new pytorch.Attribute(schema, name, value));
  465. }
  466. }
  467. if (module) {
  468. if (module.__id__) {
  469. let current = module;
  470. this._name = current.__id__;
  471. while (current.__parent__ != null) {
  472. current = current.__parent__;
  473. if (!current.__parent__ && !current.__id__) {
  474. break;
  475. }
  476. this._name = [ current.__id__, this._name ].join('.');
  477. }
  478. }
  479. }
  480. }
  481. }
  482. get name() {
  483. return this._name;
  484. }
  485. get group() {
  486. return this._group;
  487. }
  488. get type() {
  489. const index = this._type.indexOf(':');
  490. return index === -1 ? this._type : this._type.substring(0, index);
  491. }
  492. get metadata() {
  493. return this._metadata.type(this._type);
  494. }
  495. get function() {
  496. return this._function;
  497. }
  498. get attributes() {
  499. return this._attributes;
  500. }
  501. get inputs() {
  502. return this._inputs;
  503. }
  504. get outputs() {
  505. return this._outputs;
  506. }
  507. };
  508. pytorch.Attribute = class {
  509. constructor(schema, name, value) {
  510. this._name = name;
  511. this._value = value;
  512. if (this._name === 'training') {
  513. this._visible = false;
  514. this._type = 'boolean';
  515. return;
  516. }
  517. if (schema) {
  518. if (Object.prototype.hasOwnProperty.call(schema, 'type')) {
  519. this._type = schema.type;
  520. }
  521. if (schema.visible === false) {
  522. this._visible = false;
  523. }
  524. else if (Object.prototype.hasOwnProperty.call(schema, 'default')) {
  525. if (JSON.stringify(schema.default) == JSON.stringify(this._value)) {
  526. this._visible = false;
  527. }
  528. else if (Array.isArray(this._value) && !Array.isArray(schema.default) && this.value.every((item) => item == schema.default)) {
  529. this._visible = false;
  530. }
  531. }
  532. }
  533. if (Array.isArray(value) && value.length > 0 && value.every((obj) => obj && obj.__class__ && obj.__class__.__module__ && obj.__class__.__module__.startsWith('torch.nn'))) {
  534. this._value = '?';
  535. }
  536. }
  537. get type() {
  538. return this._type;
  539. }
  540. get name() {
  541. return this._name;
  542. }
  543. get value() {
  544. return this._value;
  545. }
  546. get visible() {
  547. return this._visible == false ? false : true;
  548. }
  549. };
  550. pytorch.Tensor = class {
  551. constructor(name, tensor, littleEndian) {
  552. const storage = tensor.storage();
  553. const size = tensor.size();
  554. this._name = name || '';
  555. this._type = new pytorch.TensorType(storage.dtype, new pytorch.TensorShape(size));
  556. this._data = storage.data;
  557. this._littleEndian = littleEndian;
  558. }
  559. get kind() {
  560. return 'Tensor';
  561. }
  562. get name() {
  563. return this._name;
  564. }
  565. get type() {
  566. return this._type;
  567. }
  568. get state() {
  569. return this._context().state;
  570. }
  571. get value() {
  572. const context = this._context();
  573. if (context.state) {
  574. return null;
  575. }
  576. context.limit = Number.MAX_SAFE_INTEGER;
  577. return this._decode(context, 0);
  578. }
  579. toString() {
  580. const context = this._context();
  581. if (context.state) {
  582. return '';
  583. }
  584. context.limit = 10000;
  585. const value = this._decode(context, 0);
  586. return pytorch.Tensor._stringify(value, '', ' ');
  587. }
  588. _context() {
  589. const context = {};
  590. context.state = null;
  591. context.index = 0;
  592. context.count = 0;
  593. if (!this._type.dataType) {
  594. context.state = 'Tensor has no data type.';
  595. return context;
  596. }
  597. switch (this._type.dataType) {
  598. case 'boolean':
  599. case 'uint8':
  600. case 'qint8':
  601. case 'int8':
  602. case 'int16':
  603. case 'int32':
  604. case 'int64':
  605. case 'float16':
  606. case 'float32':
  607. case 'float64':
  608. break;
  609. default:
  610. context.state = "Tensor data type '" + this._type.dataType + "' is not supported.";
  611. return context;
  612. }
  613. if (!this._type.shape) {
  614. context.state = 'Tensor has no dimensions.';
  615. return context;
  616. }
  617. if (!this._data) {
  618. context.state = 'Tensor data is empty.';
  619. return context;
  620. }
  621. try {
  622. context.data = this._data instanceof Uint8Array ? this._data : this._data.peek();
  623. }
  624. catch (err) {
  625. context.state = err.message;
  626. return context;
  627. }
  628. context.dataType = this._type.dataType;
  629. context.dimensions = this._type.shape.dimensions;
  630. context.dataView = new DataView(context.data.buffer, context.data.byteOffset, context.data.byteLength);
  631. return context;
  632. }
  633. _decode(context, dimension) {
  634. const results = [];
  635. const dimensions = (context.dimensions.length == 0) ? [ 1 ] : context.dimensions;
  636. const size = dimensions[dimension];
  637. if (dimension == dimensions.length - 1) {
  638. for (let i = 0; i < size; i++) {
  639. if (context.count > context.limit) {
  640. results.push('...');
  641. return results;
  642. }
  643. switch (context.dataType) {
  644. case 'boolean':
  645. results.push(context.dataView.getUint8(context.index) === 0 ? false : true);
  646. context.index++;
  647. context.count++;
  648. break;
  649. case 'uint8':
  650. results.push(context.dataView.getUint8(context.index));
  651. context.index++;
  652. context.count++;
  653. break;
  654. case 'qint8':
  655. case 'int8':
  656. results.push(context.dataView.getInt8(context.index));
  657. context.index++;
  658. context.count++;
  659. break;
  660. case 'int16':
  661. results.push(context.dataView.getInt16(context.index, this._littleEndian));
  662. context.index += 2;
  663. context.count++;
  664. break;
  665. case 'int32':
  666. results.push(context.dataView.getInt32(context.index, this._littleEndian));
  667. context.index += 4;
  668. context.count++;
  669. break;
  670. case 'int64':
  671. results.push(context.dataView.getInt64(context.index, this._littleEndian));
  672. context.index += 8;
  673. context.count++;
  674. break;
  675. case 'float16':
  676. results.push(context.dataView.getFloat16(context.index, this._littleEndian));
  677. context.index += 2;
  678. context.count++;
  679. break;
  680. case 'float32':
  681. results.push(context.dataView.getFloat32(context.index, this._littleEndian));
  682. context.index += 4;
  683. context.count++;
  684. break;
  685. case 'float64':
  686. results.push(context.dataView.getFloat64(context.index, this._littleEndian));
  687. context.index += 8;
  688. context.count++;
  689. break;
  690. }
  691. }
  692. }
  693. else {
  694. for (let j = 0; j < size; j++) {
  695. if (context.count > context.limit) {
  696. results.push('...');
  697. return results;
  698. }
  699. results.push(this._decode(context, dimension + 1));
  700. }
  701. }
  702. if (context.dimensions.length == 0) {
  703. return results[0];
  704. }
  705. return results;
  706. }
  707. static _stringify(value, indentation, indent) {
  708. if (Array.isArray(value)) {
  709. const result = [];
  710. result.push(indentation + '[');
  711. const items = value.map((item) => pytorch.Tensor._stringify(item, indentation + indent, indent));
  712. if (items.length > 0) {
  713. result.push(items.join(',\n'));
  714. }
  715. result.push(indentation + ']');
  716. return result.join('\n');
  717. }
  718. if (value && (value instanceof base.Int64 || value instanceof base.Uint64)) {
  719. return indentation + value.toString();
  720. }
  721. if (typeof value == 'string') {
  722. return indentation + value;
  723. }
  724. if (value == Infinity) {
  725. return indentation + 'Infinity';
  726. }
  727. if (value == -Infinity) {
  728. return indentation + '-Infinity';
  729. }
  730. if (isNaN(value)) {
  731. return indentation + 'NaN';
  732. }
  733. return indentation + value.toString();
  734. }
  735. };
  736. pytorch.TensorType = class {
  737. constructor(dtype, shape) {
  738. this._dataType = dtype.__reduce__();
  739. this._shape = shape;
  740. }
  741. get dataType() {
  742. return this._dataType;
  743. }
  744. get shape() {
  745. return this._shape;
  746. }
  747. toString() {
  748. return this._dataType + this._shape.toString();
  749. }
  750. };
  751. pytorch.TensorShape = class {
  752. constructor(dimensions) {
  753. this._dimensions = dimensions || [];
  754. }
  755. get dimensions() {
  756. return this._dimensions;
  757. }
  758. toString() {
  759. if (this._dimensions && this._dimensions.length > 0) {
  760. return '[' + this._dimensions.map((dimension) => dimension.toString()).join(',') + ']';
  761. }
  762. return '';
  763. }
  764. };
  765. pytorch.Execution = class extends python.Execution {
  766. constructor(sources, exceptionCallback) {
  767. super(sources, exceptionCallback);
  768. this.registerModule('ops');
  769. this.registerModule('ops.torchvision');
  770. this.registerModule('torch');
  771. this.registerModule('torchvision');
  772. this.context.scope.ops._caffe2 = { __name__: 'torch', __class__: this.context.scope.builtins.module };
  773. const self = this;
  774. const torch = this.context.scope.torch;
  775. this.registerType('builtins.number', class {});
  776. this.registerType('__torch__.torch.classes._nnapi.Compilation', class {
  777. constructor() {
  778. this.__hide__ = true;
  779. }
  780. __init__() {
  781. }
  782. init(serialized_model_tensor, parameter_buffers) {
  783. this.serialized_model_tensor = serialized_model_tensor;
  784. this.parameter_buffers = parameter_buffers;
  785. const storage = serialized_model_tensor.storage();
  786. new pytorch.nnapi.SerializedModel(storage.data, parameter_buffers);
  787. }
  788. run(inputs, outputs) {
  789. this.serialized_model_tensor.__variable__ = this.serialized_model_tensor.__variable__ || self.variable();
  790. this.serialized_model_tensor.__count__ = (this.serialized_model_tensor.__count__ || 0) + 1;
  791. self.push({
  792. type: 'torch.classes._nnapi.Compilation',
  793. attributes: [],
  794. inputs: [
  795. [ { id: this.serialized_model_tensor.__variable__ } ],
  796. inputs.map((input) => { return { id: input.__variable__ }; }),
  797. this.parameter_buffers.map((buffer) => { return { id: buffer.__variable__ }; })
  798. ],
  799. outputs: [
  800. outputs.map((output) => { return { id: output.__variable__ }; })
  801. ],
  802. });
  803. }
  804. });
  805. this.registerType('torch.autograd.variable.Variable', class {});
  806. this.registerType('torch.backends.cudnn.rnn.Unserializable', class {});
  807. this.registerType('torch.distributions.constraints._LowerCholesky', class {});
  808. this.registerType('torch.distributions.constraints._Real', class {});
  809. this.registerType('torch.distributions.multivariate_normal.MultivariateNormal', class {});
  810. this.registerType('torch.distributions.transforms.LowerCholeskyTransform', class {});
  811. this.registerType('torch.nn.backends.thnn._get_thnn_function_backend', class {});
  812. this.registerType('torch.nn.intrinsic.modules.fused.ConvReLU2d', class {});
  813. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvReLU2d', class {});
  814. this.registerType('torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', class {});
  815. this.registerType('torch.nn.intrinsic.quantized.modules.linear_relu.LinearReLU', class {});
  816. this.registerType('torch.nn.modules.activation.CELU', class {});
  817. this.registerType('torch.nn.modules.activation.ELU', class {});
  818. this.registerType('torch.nn.modules.activation.GELU', class {});
  819. this.registerType('torch.nn.modules.activation.GLU', class {});
  820. this.registerType('torch.nn.modules.activation.Hardtanh', class {});
  821. this.registerType('torch.nn.modules.activation.Hardswish', class {});
  822. this.registerType('torch.nn.modules.activation.Hardsigmoid', class {});
  823. this.registerType('torch.nn.modules.activation.LeakyReLU', class {});
  824. this.registerType('torch.nn.modules.activation.LogSigmoid', class {});
  825. this.registerType('torch.nn.modules.activation.LogSoftmax', class {});
  826. this.registerType('torch.nn.modules.activation.MultiheadAttention', class {});
  827. this.registerType('torch.nn.modules.activation.ReLU', class {});
  828. this.registerType('torch.nn.modules.activation.ReLU6', class {});
  829. this.registerType('torch.nn.modules.activation.PReLU', class {});
  830. this.registerType('torch.nn.modules.activation.RReLU', class {});
  831. this.registerType('torch.nn.modules.activation.SELU', class {});
  832. this.registerType('torch.nn.modules.activation.Sigmoid', class {});
  833. this.registerType('torch.nn.modules.activation.SiLU', class {});
  834. this.registerType('torch.nn.modules.activation.Softmax', class {});
  835. this.registerType('torch.nn.modules.activation.Softmax2d', class {});
  836. this.registerType('torch.nn.modules.activation.Softplus', class {});
  837. this.registerType('torch.nn.modules.activation.Tanh', class {});
  838. this.registerType('torch.nn.modules.activation.Threshold', class {});
  839. this.registerType('torch.nn.modules.batchnorm.BatchNorm1d', class {});
  840. this.registerType('torch.nn.modules.batchnorm.BatchNorm2d', class {});
  841. this.registerType('torch.nn.modules.batchnorm.BatchNorm3d', class {});
  842. this.registerType('torch.nn.modules.batchnorm.SyncBatchNorm', class {});
  843. this.registerType('torch.nn.modules.container.ModuleDict', class {});
  844. this.registerType('torch.nn.modules.container.ModuleList', class {});
  845. this.registerType('torch.nn.modules.container.ParameterList', class {});
  846. this.registerType('torch.nn.modules.container.Sequential', class {});
  847. this.registerType('torch.nn.modules.conv.Conv1d', class {});
  848. this.registerType('torch.nn.modules.conv.Conv2d', class {});
  849. this.registerType('torch.nn.modules.conv.Conv3d', class {});
  850. this.registerType('torch.nn.modules.conv.ConvTranspose1d', class {});
  851. this.registerType('torch.nn.modules.conv.ConvTranspose2d', class {});
  852. this.registerType('torch.nn.modules.conv.ConvTranspose3d', class {});
  853. this.registerType('torch.nn.modules.distance.CosineSimilarity', class {});
  854. this.registerType('torch.nn.modules.dropout.AlphaDropout', class {});
  855. this.registerType('torch.nn.modules.dropout.Dropout', class {});
  856. this.registerType('torch.nn.modules.dropout.Dropout2d', class {});
  857. this.registerType('torch.nn.modules.dropout.Dropout3d', class {});
  858. this.registerType('torch.nn.modules.fold.Fold', class {});
  859. this.registerType('torch.nn.modules.fold.Unfold', class {});
  860. this.registerType('torch.nn.modules.flatten.Flatten', class {});
  861. this.registerType('torch.nn.modules.flatten.Unflatten', class {});
  862. this.registerType('torch.nn.modules.instancenorm.InstanceNorm1d', class {});
  863. this.registerType('torch.nn.modules.instancenorm.InstanceNorm2d', class {});
  864. this.registerType('torch.nn.modules.instancenorm.InstanceNorm3d', class {});
  865. this.registerType('torch.nn.modules.linear._LinearWithBias', class {});
  866. this.registerType('torch.nn.modules.linear.Bilinear', class {});
  867. this.registerType('torch.nn.modules.linear.LazyLinear', class {});
  868. this.registerType('torch.nn.modules.linear.Linear', class {});
  869. this.registerType('torch.nn.modules.linear.Identity', class {});
  870. this.registerType('torch.nn.modules.loss.BCELoss', class {});
  871. this.registerType('torch.nn.modules.loss.BCEWithLogitsLoss', class {});
  872. this.registerType('torch.nn.modules.loss.CrossEntropyLoss', class {});
  873. this.registerType('torch.nn.modules.loss.CTCLoss', class {});
  874. this.registerType('torch.nn.modules.loss.KLDivLoss', class {});
  875. this.registerType('torch.nn.modules.loss.L1Loss', class {});
  876. this.registerType('torch.nn.modules.loss.MarginRankingLoss', class {});
  877. this.registerType('torch.nn.modules.loss.MSELoss', class {});
  878. this.registerType('torch.nn.modules.loss.NLLLoss', class {});
  879. this.registerType('torch.nn.modules.loss.NLLLoss2d', class {});
  880. this.registerType('torch.nn.modules.loss.SmoothL1Loss', class {});
  881. this.registerType('torch.nn.modules.module._IncompatibleKeys', class {});
  882. this.registerType('torch.nn.modules.module.Module', class {});
  883. this.registerType('torch.nn.modules.normalization.CrossMapLRN2d', class {});
  884. this.registerType('torch.nn.modules.normalization.GroupNorm', class {});
  885. this.registerType('torch.nn.modules.normalization.LayerNorm', class {});
  886. this.registerType('torch.nn.modules.normalization.LocalResponseNorm', class {});
  887. this.registerType('torch.nn.modules.padding.ReflectionPad1d', class {});
  888. this.registerType('torch.nn.modules.padding.ReflectionPad2d', class {});
  889. this.registerType('torch.nn.modules.padding.ReplicationPad1d', class {});
  890. this.registerType('torch.nn.modules.padding.ReplicationPad2d', class {});
  891. this.registerType('torch.nn.modules.padding.ReplicationPad3d', class {});
  892. this.registerType('torch.nn.modules.padding.ZeroPad2d', class {});
  893. this.registerType('torch.nn.modules.padding.ConstantPad1d', class {});
  894. this.registerType('torch.nn.modules.padding.ConstantPad2d', class {});
  895. this.registerType('torch.nn.modules.padding.ConstantPad3d', class {});
  896. this.registerType('torch.nn.modules.pixelshuffle.PixelShuffle', class {});
  897. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool1d', class {});
  898. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool2d', class {});
  899. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool3d', class {});
  900. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool1d', class {});
  901. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool2d', class {});
  902. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool3d', class {});
  903. this.registerType('torch.nn.modules.pooling.AvgPool1d', class {});
  904. this.registerType('torch.nn.modules.pooling.AvgPool2d', class {});
  905. this.registerType('torch.nn.modules.pooling.AvgPool3d', class {});
  906. this.registerType('torch.nn.modules.pooling.FractionalMaxPool2d', class {});
  907. this.registerType('torch.nn.modules.pooling.LPPool2d', class {});
  908. this.registerType('torch.nn.modules.pooling.MaxPool1d', class {});
  909. this.registerType('torch.nn.modules.pooling.MaxPool2d', class {});
  910. this.registerType('torch.nn.modules.pooling.MaxPool3d', class {});
  911. this.registerType('torch.nn.modules.pooling.MaxUnpool1d', class {});
  912. this.registerType('torch.nn.modules.pooling.MaxUnpool2d', class {});
  913. this.registerType('torch.nn.modules.pooling.MaxUnpool3d', class {});
  914. this.registerType('torch.nn.modules.rnn.GRU', class {});
  915. this.registerType('torch.nn.modules.rnn.GRUCell', class {});
  916. this.registerType('torch.nn.modules.rnn.LSTM', class {});
  917. this.registerType('torch.nn.modules.rnn.LSTMCell', class {});
  918. this.registerType('torch.nn.modules.rnn.RNN', class {});
  919. this.registerType('torch.nn.modules.sparse.Embedding', class {});
  920. this.registerType('torch.nn.modules.sparse.EmbeddingBag', class {});
  921. this.registerType('torch.nn.modules.transformer.Transformer', class {});
  922. this.registerType('torch.nn.modules.transformer.TransformerDecoder', class {});
  923. this.registerType('torch.nn.modules.transformer.TransformerDecoderLayer', class {});
  924. this.registerType('torch.nn.modules.transformer.TransformerEncoder', class {});
  925. this.registerType('torch.nn.modules.transformer.TransformerEncoderLayer', class {});
  926. this.registerType('torch.nn.modules.upsampling.Upsample', class {});
  927. this.registerType('torch.nn.modules.upsampling.UpsamplingBilinear2d', class {});
  928. this.registerType('torch.nn.modules.upsampling.UpsamplingNearest2d', class {});
  929. this.registerType('torch.nn.parallel.data_parallel.DataParallel', class {});
  930. this.registerType('torch.nn.parallel.distributed.DistributedDataParallel', class {});
  931. this.registerType('torch.nn.qat.modules.conv.Conv2d', class {});
  932. this.registerType('torch.nn.quantized.modules.activation.ReLU', class {});
  933. this.registerType('torch.nn.quantized.modules.activation.ReLU6', class {});
  934. this.registerType('torch.nn.quantized.modules.batchnorm.BatchNorm2d', class {});
  935. this.registerType('torch.nn.quantized.modules.conv.Conv2d', class {});
  936. this.registerType('torch.nn.quantized.modules.conv.ConvTranspose2d', class {});
  937. this.registerType('torch.nn.quantized.modules.DeQuantize', class {});
  938. this.registerType('torch.nn.quantized.modules.functional_modules.FloatFunctional', class {});
  939. this.registerType('torch.nn.quantized.modules.functional_modules.QFunctional', class {});
  940. this.registerType('torch.nn.quantized.modules.linear.Linear', class {});
  941. this.registerType('torch.nn.quantized.modules.linear.LinearPackedParams', class {});
  942. this.registerType('torch.nn.quantized.modules.Quantize', class {});
  943. this.registerType('torch.nn.utils.prune.L1Unstructured', class {});
  944. this.registerType('torch.nn.utils.spectral_norm.SpectralNorm', class {});
  945. this.registerType('torch.nn.utils.spectral_norm.SpectralNormStateDictHook', class {});
  946. this.registerType('torch.nn.utils.spectral_norm.SpectralNormLoadStateDictPreHook', class {});
  947. this.registerType('torch.nn.utils.weight_norm.WeightNorm', class {});
  948. this.registerType('torch.optim.adam.Adam', class {});
  949. this.registerType('torch.optim.adamw.AdamW', class {});
  950. this.registerType('torch.optim.adagrad.Adagrad', class {});
  951. this.registerType('torch.optim.adadelta.Adadelta', class {});
  952. this.registerType('torch.optim.lr_scheduler.CosineAnnealingLR', class {});
  953. this.registerType('torch.optim.lr_scheduler.CyclicLR', class {});
  954. this.registerType('torch.optim.lr_scheduler.ExponentialLR', class {});
  955. this.registerType('torch.optim.lr_scheduler.LambdaLR', class {});
  956. this.registerType('torch.optim.lr_scheduler.MultiStepLR', class {});
  957. this.registerType('torch.optim.lr_scheduler.OneCycleLR', class {});
  958. this.registerType('torch.optim.lr_scheduler.ReduceLROnPlateau', class {});
  959. this.registerType('torch.optim.lr_scheduler.StepLR', class {});
  960. this.registerType('torch.optim.optimizer._RequiredParameter', class {});
  961. this.registerType('torch.optim.rmsprop.RMSprop', class {});
  962. this.registerType('torch.optim.sgd.SGD', class {});
  963. this.registerType('torch.quantization.fake_quantize.FakeQuantize', class {});
  964. this.registerType('torch.quantization.observer._PartialWrapper', class {});
  965. this.registerType('torch.quantization.observer.MinMaxObserver', class {});
  966. this.registerType('torch.quantization.QConfig.QConfig', class {});
  967. this.registerType('torch.quantization.stubs.DeQuantStub', class {});
  968. this.registerType('torch.quantization.stubs.QuantStub', class {});
  969. this.registerType('torch.utils.data.dataloader.DataLoader', class {});
  970. this.registerType('torch.utils.data.dataset.Subset', class {});
  971. this.registerType('torch.utils.data.dataset.ConcatDataset', class {});
  972. this.registerType('torch.utils.data.sampler.BatchSampler', class {});
  973. this.registerType('torch.utils.data.sampler.RandomSampler', class {});
  974. this.registerType('torch.utils.data.sampler.SequentialSampler', class {});
  975. this.registerType('torchvision.datasets.folder.ImageFolder', class {});
  976. this.registerType('torchvision.datasets.mnist.MNIST', class {});
  977. this.registerType('torchvision.datasets.vision.StandardTransform', class {});
  978. this.registerType('torchvision.models.alexnet.AlexNet', class {});
  979. this.registerType('torchvision.models.densenet.DenseNet', class {});
  980. this.registerType('torchvision.models.densenet._DenseBlock', class {});
  981. this.registerType('torchvision.models.densenet._DenseLayer', class {});
  982. this.registerType('torchvision.models.densenet._Transition', class {});
  983. this.registerType('torchvision.models.detection._utils.BalancedPositiveNegativeSampler', class {});
  984. this.registerType('torchvision.models.detection._utils.BoxCoder', class {});
  985. this.registerType('torchvision.models.detection._utils.Matcher', class {});
  986. this.registerType('torchvision.models.detection.anchor_utils.AnchorGenerator', class {});
  987. this.registerType('torchvision.models.detection.backbone_utils.BackboneWithFPN', class {});
  988. this.registerType('torchvision.models.detection.faster_rcnn.FasterRCNN', class {});
  989. this.registerType('torchvision.models.detection.faster_rcnn.FastRCNNPredictor', class {});
  990. this.registerType('torchvision.models.detection.faster_rcnn.TwoMLPHead', class {});
  991. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNN', class {});
  992. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNHeads', class {});
  993. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNPredictor', class {});
  994. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNN', class {});
  995. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNHeads', class {});
  996. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNPredictor', class {});
  997. this.registerType('torchvision.models.detection.retinanet.RetinaNetClassificationHead', class {});
  998. this.registerType('torchvision.models.detection.retinanet.RetinaNetHead', class {});
  999. this.registerType('torchvision.models.detection.retinanet.RetinaNetRegressionHead', class {});
  1000. this.registerType('torchvision.models.detection.roi_heads.RoIHeads', class {});
  1001. this.registerType('torchvision.models.detection.rpn.AnchorGenerator', class {});
  1002. this.registerType('torchvision.models.detection.rpn.RegionProposalNetwork', class {});
  1003. this.registerType('torchvision.models.detection.rpn.RPNHead', class {});
  1004. this.registerType('torchvision.models.detection.transform.GeneralizedRCNNTransform', class {});
  1005. this.registerType('torchvision.models.googlenet.BasicConv2d', class {});
  1006. this.registerType('torchvision.models.googlenet.GoogLeNet', class {});
  1007. this.registerType('torchvision.models.googlenet.Inception', class {});
  1008. this.registerType('torchvision.models.googlenet.InceptionAux', class {});
  1009. this.registerType('torchvision.models.inception.BasicConv2d', class {});
  1010. this.registerType('torchvision.models.inception.Inception3', class {});
  1011. this.registerType('torchvision.models.inception.InceptionAux', class {});
  1012. this.registerType('torchvision.models.inception.InceptionA', class {});
  1013. this.registerType('torchvision.models.inception.InceptionB', class {});
  1014. this.registerType('torchvision.models.inception.InceptionC', class {});
  1015. this.registerType('torchvision.models.inception.InceptionD', class {});
  1016. this.registerType('torchvision.models.inception.InceptionE', class {});
  1017. this.registerType('torchvision.models.mnasnet._InvertedResidual', class {});
  1018. this.registerType('torchvision.models.mnasnet.MNASNet', class {});
  1019. this.registerType('torchvision.models.mobilenet.ConvBNReLU', class {});
  1020. this.registerType('torchvision.models.mobilenet.MobileNetV2', class {});
  1021. this.registerType('torchvision.models.mobilenet.InvertedResidual', class {});
  1022. this.registerType('torchvision.models.mobilenetv2.ConvBNActivation', class {});
  1023. this.registerType('torchvision.models.mobilenetv2.InvertedResidual', class {});
  1024. this.registerType('torchvision.models.mobilenetv2.MobileNetV2', class {});
  1025. this.registerType('torchvision.models.mobilenetv3.InvertedResidual', class {});
  1026. this.registerType('torchvision.models.mobilenetv3.MobileNetV3', class {});
  1027. this.registerType('torchvision.models.mobilenetv3.SqueezeExcitation', class {});
  1028. this.registerType('torchvision.models.resnet.Bottleneck', class {});
  1029. this.registerType('torchvision.models.resnet.BasicBlock', class {});
  1030. this.registerType('torchvision.models.quantization.mobilenet.QuantizableInvertedResidual', class {});
  1031. this.registerType('torchvision.models.quantization.mobilenet.QuantizableMobileNetV2', class {});
  1032. this.registerType('torchvision.models.quantization.resnet.QuantizableBasicBlock', class {});
  1033. this.registerType('torchvision.models.quantization.resnet.QuantizableBottleneck', class {});
  1034. this.registerType('torchvision.models.quantization.resnet.QuantizableResNet', class {});
  1035. this.registerType('torchvision.models.segmentation.deeplabv3.ASPP', class {});
  1036. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPConv', class {});
  1037. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPPooling', class {});
  1038. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabHead', class {});
  1039. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabV3', class {});
  1040. this.registerType('torchvision.models.segmentation.fcn.FCN', class {});
  1041. this.registerType('torchvision.models.segmentation.fcn.FCNHead', class {});
  1042. this.registerType('torchvision.models.shufflenetv2.ShuffleNetV2', class {});
  1043. this.registerType('torchvision.models.shufflenetv2.InvertedResidual', class {});
  1044. this.registerType('torchvision.models.squeezenet.Fire', class {});
  1045. this.registerType('torchvision.models.squeezenet.SqueezeNet', class {});
  1046. this.registerType('torchvision.models.resnet.ResNet', class {});
  1047. this.registerType('torchvision.models.vgg.VGG', class {});
  1048. this.registerType('torchvision.models.video.resnet.BasicBlock', class {});
  1049. this.registerType('torchvision.models.video.resnet.BasicStem', class {});
  1050. this.registerType('torchvision.models.video.resnet.Conv2Plus1D', class {});
  1051. this.registerType('torchvision.models.video.resnet.Conv3DNoTemporal', class {});
  1052. this.registerType('torchvision.models.video.resnet.Conv3DSimple', class {});
  1053. this.registerType('torchvision.models.video.resnet.R2Plus1dStem', class {});
  1054. this.registerType('torchvision.models.video.resnet.VideoResNet', class {});
  1055. this.registerType('torchvision.models._utils.IntermediateLayerGetter', class {});
  1056. this.registerType('torchvision.ops.deform_conv.DeformConv2d', class {});
  1057. this.registerType('torchvision.ops.feature_pyramid_network.FeaturePyramidNetwork', class {});
  1058. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelMaxPool', class {});
  1059. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelP6P7', class {});
  1060. this.registerType('torchvision.ops.misc.ConvTranspose2d', class {});
  1061. this.registerType('torchvision.ops.misc.FrozenBatchNorm2d', class {});
  1062. this.registerType('torchvision.ops.poolers.LevelMapper', class {});
  1063. this.registerType('torchvision.ops.poolers.MultiScaleRoIAlign', class {});
  1064. this.registerType('torchvision.transforms.functional.InterpolationMode', class {});
  1065. this.registerType('torchvision.transforms.transforms.Compose', class {});
  1066. this.registerType('torchvision.transforms.transforms.Grayscale', class {});
  1067. this.registerType('torchvision.transforms.transforms.Normalize', class {});
  1068. this.registerType('torchvision.transforms.transforms.RandomAffine', class {});
  1069. this.registerType('torchvision.transforms.transforms.Resize', class {});
  1070. this.registerType('torchvision.transforms.transforms.ToPILImage', class {});
  1071. this.registerType('torchvision.transforms.transforms.ToTensor', class {});
  1072. this.registerFunction('annotate', function(type, value) {
  1073. if (type === self.context.scope.builtins.int) {
  1074. return Number.isInteger(value) ? value : NaN;
  1075. }
  1076. if (type === self.context.scope.builtins.float) {
  1077. return typeof value === 'number' ? value : NaN;
  1078. }
  1079. if (type === self.context.scope.builtins.number) {
  1080. if (pytorch.Utility.isTensor(value)) {
  1081. value.resize_([]);
  1082. }
  1083. }
  1084. return value;
  1085. });
  1086. this.registerFunction('int', function(value) {
  1087. if (pytorch.Utility.isTensor(value)) {
  1088. const storage = value.storage();
  1089. if (storage && storage.dtype.__reduce__() === 'int64' && storage.data.length === 8) {
  1090. const buffer = storage.data;
  1091. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  1092. return view.getInt64(0, true);
  1093. }
  1094. }
  1095. if (Number.isInteger(value)) {
  1096. return value;
  1097. }
  1098. return NaN;
  1099. });
  1100. this.registerFunction('float', function(value) {
  1101. if (pytorch.Utility.isTensor(value)) {
  1102. const storage = value.storage();
  1103. if (storage && storage.dtype.__reduce__() === 'float32') {
  1104. if (storage.size() !== undefined && storage.data.length === 4) {
  1105. const buffer = storage.data;
  1106. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  1107. return view.getFloat32(0, true);
  1108. }
  1109. return NaN;
  1110. }
  1111. }
  1112. if (Number(value) === value) {
  1113. return value;
  1114. }
  1115. return NaN;
  1116. });
  1117. this.registerFunction('str', function(value) {
  1118. return JSON.stringify(value);
  1119. });
  1120. this.registerFunction('unchecked_cast', function(type, value) {
  1121. return value;
  1122. });
  1123. this.registerFunction('ops.prim.data', function(tensor) {
  1124. return tensor;
  1125. });
  1126. this.registerFunction('ops.prim.device', function(tensor) {
  1127. return tensor.device;
  1128. });
  1129. this.registerFunction('ops.prim.dtype', function(tensor) {
  1130. return tensor.dtype.scalar_type();
  1131. });
  1132. this.registerFunction('ops.prim.unchecked_unwrap_optional', function(value) {
  1133. return value;
  1134. });
  1135. this.registerFunction('ops.prim.NumToTensor', function(value) {
  1136. const tensor = self.invoke('torch.Tensor', []);
  1137. tensor.value = value; // TODO
  1138. return tensor;
  1139. });
  1140. this.registerFunction('ops.prim.min', function(value) {
  1141. if (Array.isArray(value)) {
  1142. return Math.min.apply(null, value);
  1143. }
  1144. return Math.min.apply(null, arguments);
  1145. });
  1146. this.registerFunction('ops.prim.shape', function(tensor) {
  1147. return tensor && tensor.size ? tensor.size() : undefined;
  1148. });
  1149. this.registerFunction('ops.quantized.conv_prepack', function(weight, bias, stride, padding, dilation, groups) {
  1150. return {
  1151. __class__: {
  1152. __module__: '__torch__.torch.classes.quantized',
  1153. __name__: 'Conv2dPackedParamsBase'
  1154. },
  1155. weight: weight,
  1156. bias: bias,
  1157. stride: stride,
  1158. padding: padding,
  1159. dilation: dilation,
  1160. groups: groups
  1161. };
  1162. });
  1163. this.registerFunction('ops.quantized.conv1d_prepack', function(weight, bias, stride, padding, dilation, groups) {
  1164. return {
  1165. __class__: {
  1166. __module__: '__torch__.torch.classes.quantized',
  1167. __name__: 'Conv2dPackedParamsBase'
  1168. },
  1169. weight: weight,
  1170. bias: bias,
  1171. stride: stride,
  1172. padding: padding,
  1173. dilation: dilation,
  1174. groups: groups
  1175. };
  1176. });
  1177. this.registerFunction('ops.quantized.conv2d_prepack', function(weight, bias, stride, padding, dilation, groups) {
  1178. return {
  1179. __class__: {
  1180. __module__: '__torch__.torch.classes.quantized',
  1181. __name__: 'Conv2dPackedParamsBase'
  1182. },
  1183. weight: weight,
  1184. bias: bias,
  1185. stride: stride,
  1186. padding: padding,
  1187. dilation: dilation,
  1188. groups: groups
  1189. };
  1190. });
  1191. this.registerFunction('ops.quantized.conv3d_prepack', function(weight, bias, stride, padding, dilation, groups) {
  1192. return {
  1193. __class__: {
  1194. __module__: '__torch__.torch.classes.quantized',
  1195. __name__: 'Conv3dPackedParamsBase'
  1196. },
  1197. weight: weight,
  1198. bias: bias,
  1199. stride: stride,
  1200. padding: padding,
  1201. dilation: dilation,
  1202. groups: groups
  1203. };
  1204. });
  1205. this.registerFunction('ops.quantized.conv_transpose2d_prepack', function(weight, bias, stride, padding, dilation, groups) {
  1206. return {
  1207. __class__: {
  1208. __module__: '__torch__.torch.classes.quantized',
  1209. __name__: 'Conv2dPackedParamsBase'
  1210. },
  1211. weight: weight,
  1212. bias: bias,
  1213. stride: stride,
  1214. padding: padding,
  1215. dilation: dilation,
  1216. groups: groups
  1217. };
  1218. });
  1219. this.registerFunction('ops.quantized.linear_prepack', function(weight, bias) {
  1220. return {
  1221. __class__: {
  1222. __module__: '__torch__.torch.classes.quantized',
  1223. __name__: 'LinearPackedParamsBase'
  1224. },
  1225. weight: weight,
  1226. bias: bias
  1227. };
  1228. });
  1229. this.registerFunction('ops.prim.RaiseException', function(message) {
  1230. throw new pytorch.Error(message);
  1231. });
  1232. this.registerFunction('range', function(start, stop, step) {
  1233. if (start !== undefined && Number.isInteger(start) && stop === undefined && step === undefined) {
  1234. return Array(start).keys();
  1235. }
  1236. throw new pytorch.Error('Unsupported function range(' + JSON.stringify(start) + ', ' + JSON.stringify(stop) + ', ' + JSON.stringify(step) + ')');
  1237. });
  1238. this.registerFunction('torch._utils._rebuild_tensor', function (storage, storage_offset, size, stride) {
  1239. const name = storage.__class__.__module__ + '.' + storage.__class__.__name__.replace('Storage', 'Tensor');
  1240. const tensor = self.invoke(name, []);
  1241. tensor.__setstate__([ storage, storage_offset, size, stride ]);
  1242. return tensor;
  1243. });
  1244. this.registerFunction('torch._utils._rebuild_tensor_v2', function (storage, storage_offset, size, stride, requires_grad, backward_hooks) {
  1245. const name = storage.__class__.__module__ + '.' + storage.__class__.__name__.replace('Storage', 'Tensor');
  1246. const tensor = self.invoke(name, []);
  1247. tensor.__setstate__([ storage, storage_offset, size, stride ]);
  1248. tensor.requires_grad = requires_grad;
  1249. tensor.backward_hooks = backward_hooks;
  1250. return tensor;
  1251. });
  1252. this.registerFunction('torch._utils._rebuild_parameter', function(data, requires_grad, backward_hooks) {
  1253. const obj = self.invoke('torch.nn.parameter.Parameter', [ data, requires_grad ]);
  1254. obj.backward_hooks = backward_hooks;
  1255. return obj;
  1256. });
  1257. this.registerFunction('torch._utils._rebuild_qtensor', function(storage, storage_offset, size, stride, quantizer_params, requires_grad, backward_hooks) {
  1258. const name = storage.__class__.__module__ + '.' + storage.__class__.__name__.replace('Storage', 'Tensor');
  1259. const tensor = self.invoke(name, []);
  1260. tensor.__setstate__([ storage, storage_offset, size, stride ]);
  1261. tensor.quantizer_params = quantizer_params;
  1262. tensor.requires_grad = requires_grad;
  1263. tensor.backward_hooks = backward_hooks;
  1264. return tensor;
  1265. });
  1266. this.registerFunction('torch._set_item', function(dict, key, value) {
  1267. dict[key] = value;
  1268. });
  1269. this.registerFunction('torch.__and__', function(left, right) {
  1270. return left && right;
  1271. });
  1272. this.registerFunction('torch.__contains__', function(dict, key) {
  1273. return dict[key] !== undefined;
  1274. });
  1275. this.registerFunction('torch.__derive_index', function(index, start, step) {
  1276. return start + index * step;
  1277. });
  1278. this.registerFunction('torch.__is__', function(left, right) {
  1279. if (left === null && right === null) {
  1280. return true;
  1281. }
  1282. if ((left !== null && right === null) || (left === null && right !== null)) {
  1283. return false;
  1284. }
  1285. throw new pytorch.Error("Unknown 'torch.__is__' expression type.");
  1286. });
  1287. this.registerFunction('torch.__isnot__', function(left, right) {
  1288. if (left === null && right === null) {
  1289. return false;
  1290. }
  1291. if ((left !== null && right === null) || (left === null && right !== null)) {
  1292. return true;
  1293. }
  1294. throw new pytorch.Error("Unknown 'torch.__isnot__' expression type.");
  1295. });
  1296. this.registerFunction('torch.__not__', function(value) {
  1297. if (typeof value === 'boolean') {
  1298. return !value;
  1299. }
  1300. throw new pytorch.Error("Unknown 'torch.__not__' expression type.");
  1301. });
  1302. this.registerFunction('torch.__range_length', function(lo, hi, step) {
  1303. if (step === 0) {
  1304. throw new pytorch.Error('range() arg 3 must not be zero');
  1305. }
  1306. if (step > 0 && lo < hi) {
  1307. return 1 + (hi - 1 - lo) / step;
  1308. }
  1309. else if (step < 0 && lo > hi) {
  1310. return 1 + (lo - 1 - hi) / (0 - step);
  1311. }
  1312. return 0;
  1313. });
  1314. this.registerFunction('torch._unwrap_optional', function(value) {
  1315. return value; // TODO
  1316. });
  1317. this.registerFunction('torch.add', function(left, right) {
  1318. if (typeof left === 'number' && typeof right === 'number') {
  1319. return left * right;
  1320. }
  1321. if (Array.isArray(left) && Array.isArray(right)) {
  1322. return left.concat(right);
  1323. }
  1324. if (typeof left === 'string' && typeof right === 'string') {
  1325. return left + right;
  1326. }
  1327. throw new pytorch.Error('Unknown torch.add expression type.');
  1328. });
  1329. this.registerFunction('torch.append', function(list, value) {
  1330. list.push(value);
  1331. return value;
  1332. });
  1333. this.registerFunction('torch.extend', function(list, value) {
  1334. list.push(...value);
  1335. });
  1336. this.registerFunction('torch.insert', function(list, index, value) {
  1337. list.splice(index, 0, value);
  1338. return value;
  1339. });
  1340. this.registerFunction('torch.clear', function(value) {
  1341. if (Object(value) === value) {
  1342. for (const key of Object.keys(value)) {
  1343. delete value[key];
  1344. }
  1345. }
  1346. });
  1347. this.registerFunction('torch.dict', function(args) {
  1348. const obj = {};
  1349. if (args) {
  1350. if (Array.isArray(args)) {
  1351. for (const pair of args) {
  1352. const key = pair[0];
  1353. const value = pair[1];
  1354. obj[key] = value;
  1355. }
  1356. }
  1357. else {
  1358. throw new pytorch.Error("'torch.dict' arguments not supported.");
  1359. }
  1360. }
  1361. return obj;
  1362. });
  1363. this.registerFunction('torch.dim', function(tensor) {
  1364. if (tensor && tensor.size) {
  1365. const size = tensor.size();
  1366. if (size) {
  1367. return size.length;
  1368. }
  1369. }
  1370. return 0; // TODO
  1371. });
  1372. this.registerFunction('torch.numel', function(tensor) {
  1373. if (tensor && tensor.size) {
  1374. const size = tensor.size();
  1375. if (size) {
  1376. return size.reduce((a, b) => a * b, 1);
  1377. }
  1378. }
  1379. return NaN;
  1380. });
  1381. this.registerFunction('torch.eq', function(left, right) {
  1382. if (typeof left === 'string' && typeof right === 'string') {
  1383. return left === right;
  1384. }
  1385. if (typeof left === 'number' && typeof right === 'number') {
  1386. return left === right;
  1387. }
  1388. throw new pytorch.Error("Unknown 'torch.eq' expression type.");
  1389. });
  1390. this.registerFunction('torch.floor', function(value) {
  1391. return Math.floor(value);
  1392. });
  1393. this.registerFunction('torch.ceil', function(value) {
  1394. return Math.ceil(value);
  1395. });
  1396. this.registerFunction('torch.floordiv', function(left, right) {
  1397. return Math.floor(left / right);
  1398. });
  1399. this.registerFunction('torch.format', function() {
  1400. const args = Array.from(arguments);
  1401. const list = args.shift().split(/({}D?)/);
  1402. return list.map((text) => {
  1403. if (text === '{}' || text === '{}D') {
  1404. const arg = args.shift();
  1405. return Array.isArray(arg) ? '[' + arg.map((item) => item.toString()).join(', ') + ']' : arg.toString();
  1406. }
  1407. return text;
  1408. }).join('');
  1409. });
  1410. this.registerFunction('torch.gt', function(left, right) {
  1411. if (typeof left === 'number' && typeof right === 'number') {
  1412. if (!isNaN(left) && !isNaN(right)) {
  1413. return left > right;
  1414. }
  1415. }
  1416. if (isNaN(left) && !isNaN(right)) {
  1417. return true;
  1418. }
  1419. throw new pytorch.Error("Unknown 'torch.gt' expression type.");
  1420. });
  1421. this.registerFunction('torch.ge', function(left, right) {
  1422. if (typeof left === 'number' && typeof right === 'number') {
  1423. if (!isNaN(left) && !isNaN(right)) {
  1424. return left > right;
  1425. }
  1426. }
  1427. if (isNaN(left) && !isNaN(right)) {
  1428. return true;
  1429. }
  1430. throw new pytorch.Error("Unknown 'torch.ge' expression type.");
  1431. });
  1432. this.registerFunction('torch.jit._pickle.build_boollist', function(data) {
  1433. return data;
  1434. });
  1435. this.registerFunction('torch.jit._pickle.build_doublelist', function(data) {
  1436. return data;
  1437. });
  1438. this.registerFunction('torch.jit._pickle.build_intlist', function(data) {
  1439. return data;
  1440. });
  1441. this.registerFunction('torch.jit._pickle.build_tensorlist', function(data) {
  1442. return data;
  1443. });
  1444. this.registerFunction('torch.jit._pickle.build_tensor_from_id', function(data) {
  1445. const constants = self.context.getx('CONSTANTS');
  1446. return constants['c' + data.toString()];
  1447. });
  1448. this.registerFunction('torch.jit._pickle.restore_type_tag', function(value /*, type_str */) {
  1449. return value;
  1450. });
  1451. this.registerFunction('torch.keys', function(dict) {
  1452. return Object.keys(dict);
  1453. });
  1454. this.registerFunction('torch.len', function(value) {
  1455. if (Array.isArray(value)) {
  1456. return value.length;
  1457. }
  1458. if (value && value.__len__) {
  1459. return value.__len__();
  1460. }
  1461. return NaN;
  1462. });
  1463. this.registerFunction('torch.le', function(left, right) {
  1464. if (typeof left === 'number' && typeof right === 'number') {
  1465. if (isNaN(left) || isNaN(right)) {
  1466. return false;
  1467. }
  1468. return left <= right;
  1469. }
  1470. throw new pytorch.Error("Unknown 'torch.le' expression type.");
  1471. });
  1472. this.registerFunction('torch.list', function(args) {
  1473. return args;
  1474. });
  1475. this.registerFunction('torch.list_with_default', function(size /*, defaults */) {
  1476. return size;
  1477. });
  1478. this.registerFunction('torch.lt', function(left, right) {
  1479. if (typeof left === 'number' && typeof right === 'number') {
  1480. return left < right;
  1481. }
  1482. throw new pytorch.Error("Unknown 'torch.lt' expression type.");
  1483. });
  1484. this.registerFunction('torch.mul', function(left, right) {
  1485. if (typeof left === 'number' && typeof right === 'number') {
  1486. return left * right;
  1487. }
  1488. if (isNaN(left) || isNaN(right)) {
  1489. return NaN;
  1490. }
  1491. throw new pytorch.Error("Unknown 'torch.mul' expression type.");
  1492. });
  1493. this.registerFunction('torch.div', function(left, right) {
  1494. if (typeof left === 'number' && typeof right === 'number') {
  1495. return left / right;
  1496. }
  1497. if (isNaN(left) || isNaN(right)) {
  1498. return NaN;
  1499. }
  1500. throw new pytorch.Error("Unknown 'torch.div' expression type.");
  1501. });
  1502. this.registerFunction('torch.remainder', function(left, right) {
  1503. if (typeof left === 'number' && typeof right === 'number') {
  1504. return left % right;
  1505. }
  1506. if (isNaN(left) || isNaN(right)) {
  1507. return NaN;
  1508. }
  1509. throw new pytorch.Error("Unknown 'torch.remainder' expression type.");
  1510. });
  1511. this.registerFunction('torch.ne', function(left, right) {
  1512. if (typeof left === 'number' && typeof right === 'number') {
  1513. if (isNaN(left) || isNaN(right)) {
  1514. return false;
  1515. }
  1516. return left !== right;
  1517. }
  1518. if (Array.isArray(left) && Array.isArray(right) && left.length === right.length) {
  1519. return false;
  1520. }
  1521. if (typeof left === 'string' && typeof right === 'string') {
  1522. return left !== right;
  1523. }
  1524. throw new pytorch.Error("Unknown 'torch.ne' expression type.");
  1525. });
  1526. this.registerFunction('torch.neg', function(value) {
  1527. if (typeof value === 'number') {
  1528. return -value;
  1529. }
  1530. throw new pytorch.Error("Unknown 'torch.neg' expression type.");
  1531. });
  1532. this.registerFunction('torch.q_scale', function(/* tensor */) {
  1533. return -1; // TODO
  1534. });
  1535. this.registerFunction('torch.t', function(tensor) {
  1536. return tensor;
  1537. });
  1538. this.registerFunction('torch.size', function(tensor, dim) {
  1539. if (tensor && tensor.size) {
  1540. const size = tensor.size();
  1541. if (Array.isArray(size)) {
  1542. if (dim === undefined) {
  1543. return size;
  1544. }
  1545. if (Number.isInteger(dim)) {
  1546. if (dim >= 0 && dim < size.length) {
  1547. return size[dim];
  1548. }
  1549. if (dim < 0 && -dim < size.length) {
  1550. return size[size.length + dim];
  1551. }
  1552. }
  1553. throw new pytorch.Error('Dimension out of range (expected to be in range of ' + JSON.stringify(size) + ', but got ' + JSON.stringify(dim) + ').');
  1554. }
  1555. }
  1556. return NaN;
  1557. });
  1558. this.registerFunction('torch.slice', function(l, start, end, step) {
  1559. if (step !== 1) {
  1560. throw new pytorch.Error('Slicing only supports step=1');
  1561. }
  1562. start = Math.max(0, start >= 0 ? start : l.length + start);
  1563. end = Math.min(l.length, end);
  1564. return l.slice(start, end);
  1565. });
  1566. this.registerFunction('torch.sub', function(left, right) {
  1567. if (typeof left === 'number' && typeof right === 'number') {
  1568. return left - right;
  1569. }
  1570. throw new pytorch.Error("Unknown 'torch.sub' expression type.");
  1571. });
  1572. this.registerFunction('torch.values', function(dict) {
  1573. return Object.keys(dict).map((key) => dict[key]);
  1574. });
  1575. this.registerFunction('torch.warn', function() {
  1576. });
  1577. this.registerFunction('uninitialized', function(/* type */) {
  1578. return undefined;
  1579. });
  1580. this.registerType('torch.device', class {
  1581. constructor(type, index) {
  1582. this.type = type;
  1583. if (index) {
  1584. this.index = index;
  1585. }
  1586. }
  1587. });
  1588. this.registerType('torch.dtype', class {
  1589. constructor(type) {
  1590. this._type = type;
  1591. this._data = pytorch.Utility.getScalarType(type);
  1592. }
  1593. scalar_type() {
  1594. return this._type;
  1595. }
  1596. itemsize() {
  1597. return this._data.itemsize;
  1598. }
  1599. __reduce__() {
  1600. return this._data.name;
  1601. }
  1602. __str__() {
  1603. return 'torch.' + this._data.name;
  1604. }
  1605. });
  1606. this.registerType('torch.utils.hooks.RemovableHandle', class {
  1607. __setstate__(state) {
  1608. this.hooks_dict_ref = state[0] || new Map();
  1609. this.id = state[1];
  1610. }
  1611. });
  1612. this.registerType('torch.storage._StorageBase', class {
  1613. constructor(size, dtype) {
  1614. this._size = size;
  1615. this._dtype = dtype;
  1616. }
  1617. get dtype() {
  1618. return this._dtype;
  1619. }
  1620. get data() {
  1621. return this._cdata;
  1622. }
  1623. element_size() {
  1624. return this._dtype.element_size;
  1625. }
  1626. size() {
  1627. return this._size;
  1628. }
  1629. _set_cdata(data) {
  1630. const length = this.size() * this.dtype.itemsize();
  1631. if (length !== data.length) {
  1632. throw new pytorch.Error('Storage data size mismatch.');
  1633. }
  1634. this._cdata = data;
  1635. }
  1636. _set_from_file(unpickler) {
  1637. const size = unpickler.int64();
  1638. if (size !== this.size()) {
  1639. throw new pytorch.Error('Storage size mismatch.');
  1640. }
  1641. const itemsize = this.dtype.itemsize();
  1642. const data = unpickler.stream(itemsize * size);
  1643. this._set_cdata(data);
  1644. }
  1645. static _new_with_file(unpickler) {
  1646. const size = unpickler.int64();
  1647. const storage = new this(size);
  1648. const itemsize = storage.dtype.itemsize();
  1649. const data = unpickler.stream(itemsize * size);
  1650. storage._set_cdata(data);
  1651. return storage;
  1652. }
  1653. });
  1654. this.registerType('torch.BoolStorage', class extends torch.storage._StorageBase {
  1655. constructor(size) {
  1656. super(size, torch.bool);
  1657. }
  1658. });
  1659. this.registerType('torch.ByteStorage', class extends torch.storage._StorageBase {
  1660. constructor(size) {
  1661. super(size, torch.uint8);
  1662. }
  1663. });
  1664. this.registerType('torch.CharStorage', class extends torch.storage._StorageBase {
  1665. constructor(size) {
  1666. super(size, torch.int8);
  1667. }
  1668. });
  1669. this.registerType('torch.ShortStorage', class extends torch.storage._StorageBase {
  1670. constructor(size) {
  1671. super(size, torch.int16);
  1672. }
  1673. });
  1674. this.registerType('torch.IntStorage', class extends torch.storage._StorageBase {
  1675. constructor(size) {
  1676. super(size, torch.int32);
  1677. }
  1678. });
  1679. this.registerType('torch.LongStorage', class extends torch.storage._StorageBase {
  1680. constructor(size) {
  1681. super(size, torch.int64);
  1682. }
  1683. });
  1684. this.registerType('torch.HalfStorage', class extends torch.storage._StorageBase {
  1685. constructor(size) {
  1686. super(size, torch.float16);
  1687. }
  1688. });
  1689. this.registerType('torch.FloatStorage', class extends torch.storage._StorageBase {
  1690. constructor(size) {
  1691. super(size, torch.float32);
  1692. }
  1693. });
  1694. this.registerType('torch.DoubleStorage', class extends torch.storage._StorageBase {
  1695. constructor(size) {
  1696. super(size, torch.float64);
  1697. }
  1698. });
  1699. this.registerType('torch.QInt8Storage', class extends torch.storage._StorageBase {
  1700. constructor(size) {
  1701. super(size, torch.qint8);
  1702. }
  1703. });
  1704. this.registerType('torch.QUInt8Storage', class extends torch.storage._StorageBase {
  1705. constructor(size) {
  1706. super(size, torch.quint8);
  1707. }
  1708. });
  1709. this.registerType('torch.Tensor', class {
  1710. constructor() {
  1711. }
  1712. get dtype() {
  1713. return this.storage().dtype;
  1714. }
  1715. get shape() {
  1716. return this._shape;
  1717. }
  1718. size() {
  1719. return this._shape;
  1720. }
  1721. storage() {
  1722. if (!this._storage) {
  1723. const name = this.__class__.__name__ == 'Tensor' ? 'FloatStorage' : this.__storage__.__name__.replace('Tensor', 'Storage');
  1724. this._storage = self.invoke(this.__class__.__module__ + '.' + name, []);
  1725. }
  1726. return this._storage;
  1727. }
  1728. storage_offset() {
  1729. return this._storage_offset;
  1730. }
  1731. stride() {
  1732. return this._stride;
  1733. }
  1734. resize_(shape) {
  1735. this._shape = shape;
  1736. }
  1737. __len__() {
  1738. return this._shape[0];
  1739. }
  1740. __setstate__(state) {
  1741. this._storage = state[0];
  1742. this._storage_offset = state[1];
  1743. this._shape = state[2];
  1744. this._stride = state[3];
  1745. }
  1746. tolist() {
  1747. }
  1748. });
  1749. this.registerType('torch.nn.parameter.Parameter', class extends torch.Tensor {
  1750. constructor(data, requires_grad) {
  1751. super();
  1752. if (!data) {
  1753. data = self.invoke('torch.Tensor', [[]]);
  1754. }
  1755. this.data = data;
  1756. this.requires_grad = requires_grad !== undefined ? requires_grad : true;
  1757. }
  1758. __setstate__(state) {
  1759. switch (state.length) {
  1760. case 4:
  1761. this.data = state[0];
  1762. break;
  1763. case 5:
  1764. this.data = state[0];
  1765. break;
  1766. }
  1767. }
  1768. });
  1769. this.registerType('torch.nn.parameter.UninitializedParameter', class extends torch.nn.parameter.Parameter {
  1770. constructor(requires_grad /*, device, dtype */) {
  1771. super(undefined, requires_grad);
  1772. }
  1773. });
  1774. this.registerType('torch.BoolTensor', class extends torch.Tensor {});
  1775. this.registerType('torch.ByteTensor', class extends torch.Tensor {});
  1776. this.registerType('torch.CharTensor', class extends torch.Tensor {});
  1777. this.registerType('torch.ShortTensor', class extends torch.Tensor {});
  1778. this.registerType('torch.IntTensor', class extends torch.Tensor {});
  1779. this.registerType('torch.LongTensor', class extends torch.Tensor {});
  1780. this.registerType('torch.HalfTensor', class extends torch.Tensor {});
  1781. this.registerType('torch.FloatTensor', class extends torch.Tensor {});
  1782. this.registerType('torch.DoubleTensor', class extends torch.Tensor {});
  1783. this.registerType('torch.QInt8Tensor', class extends torch.Tensor {});
  1784. this.registerType('torch.QUInt8Tensor', class extends torch.Tensor {});
  1785. this.registerType('torch.cuda.FloatTensor', class extends torch.Tensor {});
  1786. this.registerType('torch.cuda.DoubleTensor', class extends torch.Tensor {});
  1787. torch.uint8 = new torch.dtype(pytorch.ScalarType.uint8);
  1788. torch.int8 = new torch.dtype(pytorch.ScalarType.int8);
  1789. torch.int16 = new torch.dtype(pytorch.ScalarType.int16);
  1790. torch.int32 = new torch.dtype(pytorch.ScalarType.int32);
  1791. torch.int64 = new torch.dtype(pytorch.ScalarType.int64);
  1792. torch.float16 = new torch.dtype(pytorch.ScalarType.float16);
  1793. torch.float32 = new torch.dtype(pytorch.ScalarType.float32);
  1794. torch.float64 = new torch.dtype(pytorch.ScalarType.float64);
  1795. torch.complex32 = new torch.dtype(pytorch.ScalarType.complex32);
  1796. torch.complex64 = new torch.dtype(pytorch.ScalarType.complex64);
  1797. torch.complex128 = new torch.dtype(pytorch.ScalarType.complex128);
  1798. torch.bool = new torch.dtype(pytorch.ScalarType.boolean);
  1799. torch.qint8 = new torch.dtype(pytorch.ScalarType.qint8);
  1800. torch.quint8 = new torch.dtype(pytorch.ScalarType.quint8);
  1801. torch.qint32 = new torch.dtype(pytorch.ScalarType.qint32);
  1802. torch.bfloat16 = new torch.dtype(pytorch.ScalarType.bfloat16);
  1803. }
  1804. debug(file) {
  1805. const buffer = this.source(file + '.debug_pkl');
  1806. if (buffer) {
  1807. return null;
  1808. // const unpickler = python.Unpickler.open(buffer);
  1809. // return unpickler.load((name, args) => this.invoke(name, args), null);
  1810. }
  1811. return null;
  1812. }
  1813. };
  1814. pytorch.Container = class {
  1815. static open(context, metadata, exception) {
  1816. const zip = pytorch.Container.Zip.open(context.entries('zip'), metadata, exception);
  1817. if (zip) {
  1818. return zip;
  1819. }
  1820. const stream = context.stream;
  1821. const signature = [ 0x80, undefined, 0x8a, 0x0a, 0x6c, 0xfc, 0x9c, 0x46, 0xf9, 0x20, 0x6a, 0xa8, 0x50, 0x19 ];
  1822. if (signature.length <= stream.length && stream.peek(signature.length).every((value, index) => signature[index] === undefined || signature[index] === value)) {
  1823. return new pytorch.Container.Pickle(stream, exception);
  1824. }
  1825. const entries = context.entries('tar');
  1826. if (entries.has('pickle')) {
  1827. return new pytorch.Container.Tar(entries, exception);
  1828. }
  1829. return null;
  1830. }
  1831. };
  1832. pytorch.Container.Tar = class {
  1833. constructor(entries, exceptionCallback) {
  1834. this._entries = entries;
  1835. this._exceptionCallack = exceptionCallback;
  1836. }
  1837. get format() {
  1838. return 'PyTorch v0.1.1';
  1839. }
  1840. get type() {
  1841. this._unpickle();
  1842. return this._type;
  1843. }
  1844. get data() {
  1845. this._unpickle();
  1846. return this._data;
  1847. }
  1848. get littleEndian() {
  1849. this._unpickle();
  1850. return this._littleEndian;
  1851. }
  1852. _unpickle() {
  1853. if (!this._entries) {
  1854. return;
  1855. }
  1856. this._type = '';
  1857. this._data = null;
  1858. this._littleEndian = true;
  1859. const execution = new pytorch.Execution(null, this._exceptionCallback);
  1860. const entries = {};
  1861. for (const entry of this._entries) {
  1862. switch (entry.name) {
  1863. case 'sys_info': entries.sys_info = entry.stream.peek(); break;
  1864. case 'pickle': entries.pickle = entry.stream.peek(); break;
  1865. case 'storages': entries.storages = entry.stream.peek(); break;
  1866. case 'tensors': entries.tensors = entry.stream.peek(); break;
  1867. }
  1868. }
  1869. this._exceptionCallback = null;
  1870. this._entries = null;
  1871. if (entries.sys_info) {
  1872. const unpickler = python.Unpickler.open(entries.sys_info);
  1873. const sys_info = unpickler.load((name, args) => execution.invoke(name, args));
  1874. if (sys_info.protocol_version != 1000) {
  1875. throw new pytorch.Error("Unsupported protocol version '" + sys_info.protocol_version + "'.");
  1876. }
  1877. if (sys_info.type_sizes &&
  1878. ((sys_info.type_sizes.int && sys_info.type_sizes.int != 4) ||
  1879. (sys_info.type_sizes.long && sys_info.type_sizes.long != 4) ||
  1880. (sys_info.type_sizes.short && sys_info.type_sizes.short != 2))) {
  1881. throw new pytorch.Error('Unsupported type sizes.');
  1882. }
  1883. this._littleEndian = sys_info.little_endian;
  1884. }
  1885. const deserialized_objects = {};
  1886. if (entries.storages) {
  1887. const unpickler = python.Unpickler.open(entries.storages);
  1888. const num_storages = unpickler.load((name, args) => execution.invoke(name, args));
  1889. for (let i = 0; i < num_storages; i++) {
  1890. const args = unpickler.load();
  1891. const key = args[0];
  1892. const storage_type = execution.type(args[2]);
  1893. const obj = storage_type._new_with_file(unpickler);
  1894. deserialized_objects[key] = obj;
  1895. }
  1896. /*
  1897. let storage_views = unpickler.load();
  1898. for target_cdata, root_cdata, offset, size in storage_views:
  1899. root = deserialized_objects[root_cdata]
  1900. deserialized_objects[target_cdata] = root[offset:offset + size]
  1901. */
  1902. }
  1903. if (entries.tensors) {
  1904. const unpickler = python.Unpickler.open(entries.tensors);
  1905. const num_tensors = unpickler.load((name, args) => execution.invoke(name, args));
  1906. for (let i = 0; i < num_tensors; i++) {
  1907. const args = unpickler.load();
  1908. const key = args[0];
  1909. const storage_id = args[1];
  1910. const storage = deserialized_objects[storage_id];
  1911. const ndim = unpickler.int32();
  1912. unpickler.read(4);
  1913. const shape = new Array(ndim);
  1914. for (let j = 0; j < ndim; j++) {
  1915. shape[j] = unpickler.int64();
  1916. }
  1917. const stride = new Array(ndim);
  1918. for (let j = 0; j < ndim; j++) {
  1919. stride[j] = unpickler.int64();
  1920. }
  1921. const storage_offset = unpickler.int64();
  1922. const tensor = execution.invoke('torch._utils._rebuild_tensor', [ storage, storage_offset, shape, stride ]);
  1923. deserialized_objects[key] = tensor;
  1924. }
  1925. }
  1926. if (entries.pickle) {
  1927. const unpickler = python.Unpickler.open(entries.pickle);
  1928. const persistent_load = (saved_id) => {
  1929. return deserialized_objects[saved_id];
  1930. };
  1931. const obj = unpickler.load((name, args) => execution.invoke(name, args), persistent_load);
  1932. const weights = pytorch.Utility.findWeights(obj);
  1933. if (weights) {
  1934. this._type = 'weights';
  1935. this._data = weights;
  1936. }
  1937. else {
  1938. throw new pytorch.Error('File does not contain root module or state dictionary.');
  1939. }
  1940. }
  1941. }
  1942. };
  1943. pytorch.Container.Pickle = class {
  1944. constructor(stream, exception) {
  1945. this._stream = stream;
  1946. this._exceptionCallback = exception;
  1947. }
  1948. get format() {
  1949. return 'PyTorch v0.1.10';
  1950. }
  1951. get type() {
  1952. this._unpickle();
  1953. return this._type;
  1954. }
  1955. get data() {
  1956. this._unpickle();
  1957. return this._data;
  1958. }
  1959. get littleEndian() {
  1960. this._unpickle();
  1961. return this._littleEndian;
  1962. }
  1963. _unpickle() {
  1964. if (!this._stream) {
  1965. return;
  1966. }
  1967. const execution = new pytorch.Execution(null, this._exceptionCallback);
  1968. const unpickler = python.Unpickler.open(this._stream.length < 0x7ffff000 ? this._stream.peek() : this._stream);
  1969. this._stream = null;
  1970. this._exceptionCallback = null;
  1971. unpickler.load(); // magic_number
  1972. const protocol_version = unpickler.load();
  1973. if (protocol_version != 1001) {
  1974. throw new pytorch.Error("Unsupported protocol version '" + protocol_version + "'.");
  1975. }
  1976. const sys_info = unpickler.load();
  1977. if (sys_info.protocol_version != 1001) {
  1978. throw new pytorch.Error("Unsupported protocol version '" + sys_info.protocol_version + "'.");
  1979. }
  1980. this._littleEndian = sys_info.little_endian;
  1981. const module_source_map = new Map();
  1982. const deserialized_objects = new Map();
  1983. const persistent_load = (saved_id) => {
  1984. const typename = saved_id.shift();
  1985. const data = saved_id;
  1986. switch (typename) {
  1987. case 'module': {
  1988. const module = data[0];
  1989. const source = data[2];
  1990. module_source_map.set(module, source);
  1991. return data[0];
  1992. }
  1993. case 'storage': {
  1994. const data_type = execution.type(data.shift());
  1995. const root_key = data.shift();
  1996. data.shift(); // location
  1997. const size = data.shift();
  1998. const view_metadata = data.shift();
  1999. if (!deserialized_objects.has(root_key)) {
  2000. const obj = new data_type(size);
  2001. deserialized_objects.set(root_key, obj);
  2002. }
  2003. if (view_metadata) {
  2004. const view_key = view_metadata.shift();
  2005. view_metadata.shift(); // view_offset
  2006. view_metadata.shift(); // view_size
  2007. if (!deserialized_objects.has(view_key)) {
  2008. const view = null; // storage.slice(view_offset, view_offset + view_size);
  2009. deserialized_objects.set(view_key, view);
  2010. }
  2011. return deserialized_objects.get(view_key);
  2012. }
  2013. return deserialized_objects.get(root_key);
  2014. }
  2015. }
  2016. throw new pytorch.Error("Unknown persistent load type '" + typename + "'.");
  2017. };
  2018. const obj = unpickler.load((name, args) => execution.invoke(name, args), persistent_load);
  2019. if (!obj) {
  2020. throw new pytorch.Error('File format is not PyTorch.');
  2021. }
  2022. if (obj === 'None') {
  2023. throw new pytorch.Error("File contains 'None' root object.");
  2024. }
  2025. const deserialized_storage_keys = unpickler.load();
  2026. for (const deserialized_storage_key of deserialized_storage_keys) {
  2027. const storage = deserialized_objects.get(deserialized_storage_key);
  2028. storage._set_from_file(unpickler);
  2029. }
  2030. const root = pytorch.Utility.findModule(obj);
  2031. if (root) {
  2032. this._type = 'module';
  2033. this._data = root;
  2034. }
  2035. else {
  2036. const weights = pytorch.Utility.findWeights(obj);
  2037. if (weights) {
  2038. this._type = 'weights';
  2039. this._data = weights;
  2040. }
  2041. else {
  2042. throw new pytorch.Error('File does not contain root module or state dictionary.');
  2043. }
  2044. }
  2045. }
  2046. };
  2047. pytorch.Container.Zip = class {
  2048. static open(entries, metadata, exception) {
  2049. const name = Array.from(entries.keys()).find((name) => name == 'model.json' || name == 'data.pkl' || name.endsWith('/model.json') || name.endsWith('/data.pkl'));
  2050. if (!name) {
  2051. return null;
  2052. }
  2053. let model = null;
  2054. if (name.endsWith('.json')) {
  2055. try {
  2056. const stream = entries.get(name);
  2057. const buffer = stream.peek();
  2058. const decoder = new TextDecoder('utf-8');
  2059. const text = decoder.decode(buffer);
  2060. model = JSON.parse(text);
  2061. if (!model.mainModule) {
  2062. return null;
  2063. }
  2064. }
  2065. catch (error) {
  2066. return null;
  2067. }
  2068. }
  2069. return new pytorch.Container.Zip(entries, name, model, metadata, exception);
  2070. }
  2071. constructor(entries, name, model, metadata, exception) {
  2072. this._entries = entries;
  2073. this._metadata = metadata;
  2074. this._exceptionCallback = exception;
  2075. // https://github.com/pytorch/pytorch/blob/master/torch/csrc/jit/docs/serialization.md
  2076. this._model = model;
  2077. const lastIndex = name.lastIndexOf('/');
  2078. this._prefix = lastIndex === -1 ? '' : name.substring(0, lastIndex + 1);
  2079. }
  2080. get format() {
  2081. if (this._format === undefined) {
  2082. if (this._entry('model.json')) {
  2083. this._format = this._entry('attributes.pkl') ? 'TorchScript v1.1' : 'TorchScript v1.0';
  2084. }
  2085. else if (this._entry('data.pkl')) {
  2086. const stream = this._entry('version');
  2087. const decoder = new TextDecoder('utf-8');
  2088. const versionNumber = stream ? decoder.decode(stream.peek()).split('\n').shift() : '';
  2089. // https://github.com/pytorch/pytorch/blob/master/caffe2/serialize/inline_container.h
  2090. // kProducedFileFormatVersion
  2091. const versionTable = {
  2092. '1': 'v1.3',
  2093. '2': 'v1.5', // 7a2889b014ce36fcc333b2c6de6f29f976652f84 (#28122)
  2094. '3': 'v1.6', // 2ec6a30722b0ef85632a2f3e7ce6f80da403008a (#36085)
  2095. '4': 'v1.6', // 95489b590f00801bdee7f41783f30874883cf6bb (#38620)
  2096. '5': 'v1.7' // cb26661fe4faf26386703180a9045e6ac6d157df (#40364)
  2097. };
  2098. const version = versionTable[versionNumber];
  2099. if (!version) {
  2100. this._exceptionCallback(new pytorch.Error("Unsupported PyTorch Zip version '" + versionNumber + "'."));
  2101. }
  2102. const constants = this._entry('constants.pkl');
  2103. this._format = (constants ? 'TorchScript' : 'PyTorch') + ' ' + (version || 'v-' + versionNumber.toString() );
  2104. }
  2105. }
  2106. return this._format;
  2107. }
  2108. get producer() {
  2109. return this.data ? this._producer : '';
  2110. }
  2111. get name() {
  2112. return this._name;
  2113. }
  2114. get littleEndian() {
  2115. return true;
  2116. }
  2117. get type() {
  2118. this._load();
  2119. return this._type;
  2120. }
  2121. get data() {
  2122. this._load();
  2123. return this._data;
  2124. }
  2125. get constants() {
  2126. if (this._constants === undefined) {
  2127. this._constants = [];
  2128. const stream = this._entry('constants.pkl');
  2129. if (stream) {
  2130. const buffer = stream.peek();
  2131. this._constants = this._unpickle(buffer, this._storage('constants'));
  2132. for (let i = 0; i < this._constants.length; i++) {
  2133. const constant = this._constants[i];
  2134. const variable = 'CONSTANTS.c' + i.toString();
  2135. if (pytorch.Utility.isTensor(constant)) {
  2136. constant.__variable__ = variable;
  2137. }
  2138. else if (constant && constant.__class__ && constant.__class__.__module__ === '__torch__.torch.classes.xnnpack') {
  2139. switch (constant.__class__.__name__) {
  2140. case 'LinearOpContext':
  2141. case 'Conv2dOpContext':
  2142. if (pytorch.Utility.isTensor(constant[0])) {
  2143. constant[0].__variable__ = variable + '.weight';
  2144. }
  2145. if (pytorch.Utility.isTensor(constant[1])) {
  2146. constant[1].__variable__ = variable + '.bias';
  2147. }
  2148. break;
  2149. default:
  2150. throw new pytorch.Error("Unsupported constant context '" + constant.__class__.__name__ + "'.");
  2151. }
  2152. }
  2153. else {
  2154. throw new pytorch.Error('Unsupported constant.');
  2155. }
  2156. }
  2157. }
  2158. }
  2159. return this._constants;
  2160. }
  2161. get execution() {
  2162. if (this._execution === undefined) {
  2163. const sources = new Map();
  2164. for (const entry of this._entries) {
  2165. const name = entry[0];
  2166. if (name.startsWith(this._prefix + 'code')) {
  2167. const file = name.substring(this._prefix.length);
  2168. if (sources.has(file)) {
  2169. throw new pytorch.Error("Duplicate source file '" + file + "'.");
  2170. }
  2171. const stream = entry[1];
  2172. const buffer = stream.peek();
  2173. sources.set(file, buffer);
  2174. }
  2175. }
  2176. this._execution = new pytorch.Container.Zip.Execution(sources, this._exceptionCallback, this._metadata);
  2177. const constants = {};
  2178. for (let i = 0; i < this.constants.length; i++) {
  2179. constants['c' + i.toString()] = this.constants[i];
  2180. }
  2181. this._execution.context.set('CONSTANTS', constants);
  2182. }
  2183. return this._execution;
  2184. }
  2185. _entry(name) {
  2186. return this._entries.get(this._prefix + name);
  2187. }
  2188. _load() {
  2189. if (this._data === undefined) {
  2190. this._data = null;
  2191. const stream = this._entry('data.pkl');
  2192. if (stream) {
  2193. const buffer = stream.peek();
  2194. this._data = this._unpickle(buffer, this._storage('data'));
  2195. }
  2196. else {
  2197. if (this._model) {
  2198. this._producer = this._model.producerName + (this._model.producerVersion ? ' v' + this._model.producerVersion : '');
  2199. this._data = this._model.mainModule || {};
  2200. this._name = this._data.name || '';
  2201. if (this._data.torchscriptArena) {
  2202. this._torchscriptArena = this._data.torchscriptArena.key;
  2203. }
  2204. const queue = [ this._data ];
  2205. const entries = new Map();
  2206. for (const entry of this._entries) {
  2207. const name = entry[0];
  2208. const stream = entry[1];
  2209. const buffer = stream.peek();
  2210. entries.set(name, buffer);
  2211. }
  2212. const tensorTypeMap = new Map([
  2213. [ 'FLOAT', 'Float' ],
  2214. [ 'FLOAT16', 'Half' ],
  2215. [ 'DOUBLE', 'Double' ],
  2216. [ 'INT8', 'Char' ],
  2217. [ 'INT32', 'Int' ],
  2218. [ 'INT64', 'Long' ]
  2219. ]);
  2220. const constants = this._model.tensors || [];
  2221. this._constants = constants.map((constant) => {
  2222. const key = this._prefix + constant.data.key;
  2223. if (!tensorTypeMap.has(constant.dataType)) {
  2224. throw new pytorch.Error("Unknown tensor data type '" + constant.dataType + "'.");
  2225. }
  2226. const type = tensorTypeMap.get(constant.dataType);
  2227. const shape = constant.dims ? constant.dims.map((dim) => parseInt(dim, 10)) : null;
  2228. const storage_type = this.execution.type('torch.' + type + 'Storage');
  2229. const size = (shape || []).reduce((a, b) => a * b, 1);
  2230. const offset = parseInt(constant.offset, 10) || 0;
  2231. const storage = new storage_type([ size ]);
  2232. const itemsize = storage.dtype.itemsize();
  2233. const buffer = entries.get(key);
  2234. const length = size * itemsize;
  2235. const data = buffer.slice(offset, offset + length);
  2236. storage._set_cdata(data);
  2237. const tensor = this.execution.invoke('torch._utils._rebuild_tensor', [ storage, 0, shape, 0 ]);
  2238. tensor.name = constant.data.key;
  2239. return tensor;
  2240. });
  2241. this._attributes = [];
  2242. const stream = this._entry('attributes.pkl');
  2243. if (stream) {
  2244. const buffer = stream.peek();
  2245. const unpickler = python.Unpickler.open(buffer);
  2246. this._attributes.push(...unpickler.load((name, args) => this.execution.invoke(name, args)));
  2247. }
  2248. while (queue.length > 0) {
  2249. const module = queue.shift();
  2250. if (!module.__class__) {
  2251. module.__class__ = {
  2252. __module__: 'torch.nn.modules.module',
  2253. __name__: 'Module'
  2254. };
  2255. }
  2256. if (module.name) {
  2257. module.__id__ = module.name;
  2258. }
  2259. if (module.submodules) {
  2260. for (const submodule of module.submodules) {
  2261. module[submodule.name] = submodule;
  2262. submodule.__parent__ = module;
  2263. queue.push(submodule);
  2264. }
  2265. delete module.submodules;
  2266. }
  2267. const attributes = [];
  2268. if (module.attributes) {
  2269. attributes.push(...module.attributes);
  2270. delete module.attributes;
  2271. }
  2272. const parameters = [];
  2273. if (module.parameters) {
  2274. parameters.push(...module.parameters);
  2275. delete module.parameters;
  2276. }
  2277. if (module.arguments) {
  2278. parameters.push(...module.arguments);
  2279. delete module.arguments;
  2280. }
  2281. for (const parameter of parameters) {
  2282. const tensor = this._constants[parameter.tensorId];
  2283. module[parameter.name] = tensor;
  2284. if (!parameter.__class__) {
  2285. parameter.__class__ = {
  2286. __module__: 'torch',
  2287. __name__: 'Tensor'
  2288. };
  2289. }
  2290. }
  2291. for (const attribute of attributes) {
  2292. module[attribute.name] = this._attributes[attribute.id];
  2293. }
  2294. }
  2295. delete this._model;
  2296. }
  2297. }
  2298. if (this.format.startsWith('TorchScript ')) {
  2299. this._type = 'script';
  2300. }
  2301. else {
  2302. const obj = this._data;
  2303. const root = pytorch.Utility.findModule(obj);
  2304. if (root) {
  2305. this._type = 'module';
  2306. this._data = root;
  2307. }
  2308. else {
  2309. const weights = pytorch.Utility.findWeights(obj);
  2310. if (weights) {
  2311. this._type = 'weights';
  2312. this._data = weights;
  2313. }
  2314. else {
  2315. throw new pytorch.Error('File does not contain root module or state dictionary.');
  2316. }
  2317. }
  2318. }
  2319. }
  2320. }
  2321. _unpickle(data, storage_map) {
  2322. const loaded_storages = new Map();
  2323. const persistent_load = (saved_id) => {
  2324. const typename = saved_id.shift();
  2325. if (typename !== 'storage') {
  2326. throw new pytorch.Error("Unknown persistent load type '" + typename + "'.");
  2327. }
  2328. const data_type = this.execution.type(saved_id.shift());
  2329. const root_key = saved_id.shift();
  2330. /* const location = */ saved_id.shift();
  2331. const size = saved_id.shift();
  2332. if (!loaded_storages.has(root_key)) {
  2333. const storage = new data_type(size);
  2334. storage._set_cdata(storage_map.get(root_key));
  2335. loaded_storages.set(root_key, storage);
  2336. }
  2337. const storage = loaded_storages.get(root_key);
  2338. const view_metadata = saved_id.shift();
  2339. if (view_metadata) {
  2340. const view_key = view_metadata.shift();
  2341. view_metadata.shift(); // view_offset
  2342. view_metadata.shift(); // view_size
  2343. let view = null;
  2344. if (loaded_storages.has(view_key)) {
  2345. view = loaded_storages.get(root_key);
  2346. }
  2347. else {
  2348. view = null; // storage.slice(view_offset, view_offset + view_size);
  2349. loaded_storages.set(view_key, view);
  2350. }
  2351. return view;
  2352. }
  2353. return storage;
  2354. };
  2355. return python.Unpickler.open(data).load((name, args) => this.execution.invoke(name, args), persistent_load);
  2356. }
  2357. _storage(dirname) {
  2358. const map = new Map();
  2359. const prefix = this._prefix + dirname + '/';
  2360. for (const entry of this._entries) {
  2361. if (entry[0].startsWith(prefix)) {
  2362. const key = entry[0].substring(prefix.length);
  2363. const buffer = entry[1].peek();
  2364. map.set(key, buffer);
  2365. }
  2366. }
  2367. return map;
  2368. }
  2369. trace() {
  2370. this._inputs = [];
  2371. this._outputs = [];
  2372. this.execution.reset();
  2373. if (this._torchscriptArena) {
  2374. const program = this.execution.parse(this._torchscriptArena);
  2375. for (const statement of program.body) {
  2376. if (statement.type == 'def') {
  2377. const self = this;
  2378. const globals = this.execution.context;
  2379. const func = {
  2380. __class__: this.execution.context.scope.builtins.function,
  2381. __name__: statement.name,
  2382. __code__: statement,
  2383. __call__: function(args) {
  2384. return self.execution.apply(this.__code__, args, globals);
  2385. }
  2386. };
  2387. this.data[statement.name] = func;
  2388. }
  2389. }
  2390. }
  2391. if (this.data.forward) {
  2392. const args = [ this.data ]; // self
  2393. if (this.data.forward.__code__ && this.data.forward.__code__.parameters) {
  2394. for (const parameter of this.data.forward.__code__.parameters) {
  2395. const defaultValue = (type, name) => {
  2396. if (type.type === 'type' && type.name.type) {
  2397. switch (type.name.value) {
  2398. case 'Tensor': {
  2399. const tensor = this.execution.invoke('torch.Tensor', []);
  2400. tensor.__variable__ = name;
  2401. tensor.__origin__ = 'graph-input';
  2402. return tensor;
  2403. }
  2404. case 'Tuple':
  2405. return type.arguments.map((type, index) => defaultValue(type, name + '[' + index.toString() + ']'));
  2406. case 'List':
  2407. return type.arguments.map((type, index) => defaultValue(type, name + '[' + index.toString() + ']' ));
  2408. case 'Dict':
  2409. return {};
  2410. case 'int':
  2411. return 0;
  2412. case 'float':
  2413. return 0.0;
  2414. case 'bool':
  2415. return false;
  2416. case 'Optional':
  2417. return undefined;
  2418. }
  2419. }
  2420. throw new pytorch.Error("Unknown function parameter type '" + JSON.stringify(type) + "'.");
  2421. };
  2422. if (parameter.name !== 'self') {
  2423. const type = parameter.parameterType;
  2424. const value = defaultValue(type, parameter.name);
  2425. if (pytorch.Utility.isTensor(value)) {
  2426. value.__variable__ = parameter.name;
  2427. value.__origin__ = 'graph-input';
  2428. this._inputs.push(parameter.name);
  2429. }
  2430. args.push(value);
  2431. }
  2432. }
  2433. }
  2434. const result = this.data.forward.__call__(args);
  2435. if (Array.isArray(result)) {
  2436. for (const output of result) {
  2437. if (pytorch.Utility.isTensor(output)) {
  2438. this._outputs.push(output.__variable__);
  2439. }
  2440. }
  2441. }
  2442. else if (pytorch.Utility.isTensor(result)) {
  2443. this._outputs.push(result.__variable__);
  2444. }
  2445. else if (Object(result) === result) {
  2446. for (const key of Object.keys(result)) {
  2447. const value = result[key];
  2448. if (Array.isArray(value)) {
  2449. for (const output of value) {
  2450. if (pytorch.Utility.isTensor(output)) {
  2451. this._outputs.push(output.__variable__);
  2452. }
  2453. }
  2454. }
  2455. else if (pytorch.Utility.isTensor(value)) {
  2456. this._outputs.push(value.__variable__);
  2457. }
  2458. }
  2459. }
  2460. this._nodes = this.execution.nodes;
  2461. return true;
  2462. }
  2463. throw new pytorch.Error("Module 'forward' not implemented.");
  2464. }
  2465. get inputs() {
  2466. return this._inputs;
  2467. }
  2468. get outputs() {
  2469. return this._outputs;
  2470. }
  2471. get nodes() {
  2472. return this._nodes;
  2473. }
  2474. };
  2475. pytorch.Container.Zip.Execution = class extends pytorch.Execution {
  2476. constructor(sources, exceptionCallback, metadata) {
  2477. super(sources, exceptionCallback);
  2478. this._metadata = metadata;
  2479. this.reset();
  2480. }
  2481. reset() {
  2482. this._nodes = [];
  2483. this._variableIndex = 0;
  2484. }
  2485. get nodes() {
  2486. return this._nodes;
  2487. }
  2488. call(target, name, args, context) {
  2489. let resolvedTarget = pytorch.Utility.target(target);
  2490. let outputTypes = null;
  2491. if (resolvedTarget && resolvedTarget + '.' + name === 'ops.prim.NumToTensor' &&
  2492. args.length === 1 && args[0].type === 'call' && args[0].target.member.type == 'id') {
  2493. const innerCall = args[0];
  2494. resolvedTarget = pytorch.Utility.target(innerCall.target.target);
  2495. name = innerCall.target.member.value;
  2496. args = innerCall.arguments;
  2497. outputTypes = [ 'int64' ];
  2498. }
  2499. if (resolvedTarget) {
  2500. const type = resolvedTarget + '.' + name;
  2501. // https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/native_functions.yaml
  2502. let schemas = this._metadata.type(type);
  2503. if (schemas) {
  2504. schemas = !Array.isArray(schemas) ? [ schemas ] : schemas;
  2505. const evalArgs = args.map((argument) => argument.type === '=' && argument.target && argument.target.type === 'id' ? this.expression(argument.expression, context) : this.expression(argument, context));
  2506. for (const schema of schemas) {
  2507. const copyArgs = Array.prototype.slice.call(args);
  2508. const copyEvalArgs = Array.prototype.slice.call(evalArgs);
  2509. const node = {
  2510. type: schema.name,
  2511. inputs: [],
  2512. attributes: [],
  2513. outputs: []
  2514. };
  2515. const referencedParameters = [];
  2516. let next = false;
  2517. const parameters = Array.prototype.slice.call(schema.inputs || []).concat(Array.prototype.slice.call(schema.attributes || []));
  2518. while (copyEvalArgs.length > 0) {
  2519. if (parameters.length <= 0) {
  2520. next = true;
  2521. break;
  2522. }
  2523. const paramsBase = copyEvalArgs[0];
  2524. if (paramsBase && paramsBase.__class__ && paramsBase.__class__.__module__ === '__torch__.torch.classes.quantized') {
  2525. switch (paramsBase.__class__.__name__) {
  2526. case 'Conv2dPackedParamsBase':
  2527. case 'Conv3dPackedParamsBase': {
  2528. copyArgs.shift();
  2529. copyEvalArgs.shift();
  2530. copyArgs.unshift({ type: null });
  2531. copyEvalArgs.unshift(paramsBase.bias);
  2532. copyArgs.unshift({ type: null });
  2533. copyEvalArgs.unshift(paramsBase.weight);
  2534. break;
  2535. }
  2536. case 'LinearPackedParamsBase': {
  2537. copyArgs.shift();
  2538. copyEvalArgs.shift();
  2539. copyArgs.unshift({ type: null });
  2540. copyEvalArgs.unshift(paramsBase.bias);
  2541. copyArgs.unshift({ type: null });
  2542. copyEvalArgs.unshift(paramsBase.weight);
  2543. break;
  2544. }
  2545. default:
  2546. throw new pytorch.Error("Unsupported type '" + paramsBase.__name__ + "'.");
  2547. }
  2548. }
  2549. const op_context = copyEvalArgs[0];
  2550. if (op_context && op_context.__class__ && op_context.__class__.__module__ === '__torch__.torch.classes.xnnpack') {
  2551. switch (op_context.__class__.__name__) {
  2552. case 'LinearOpContext':
  2553. case 'Conv2dOpContext':
  2554. copyArgs.shift();
  2555. copyEvalArgs.shift();
  2556. for (const key of Object.keys(op_context).filter((key) => Number.isInteger(parseInt(key, 10)))) {
  2557. copyArgs.push({ type: null });
  2558. copyEvalArgs.push(op_context[key]);
  2559. }
  2560. break;
  2561. default:
  2562. throw new pytorch.Error("Unsupported type '" + paramsBase.__name__ + "'.");
  2563. }
  2564. }
  2565. if (copyArgs.every((arg) => arg.type === '=' && arg.target && arg.target.type === 'id') &&
  2566. parameters.every((parameter) => parameter.type !== 'Tensor' && parameter.type !== 'Tensor[]')) {
  2567. const map = new Map();
  2568. for (const parameter of parameters) {
  2569. map.set(parameter.name, parameter);
  2570. }
  2571. while (copyArgs.length > 0) {
  2572. const argument = copyArgs.shift();
  2573. const value = copyEvalArgs.shift();
  2574. const parameter = map.get(argument.target.value);
  2575. if (!parameter) {
  2576. next = true;
  2577. break;
  2578. }
  2579. if (!pytorch.Utility.isType(value, parameter.type)) {
  2580. if (parameter.optional) {
  2581. continue;
  2582. }
  2583. next = true;
  2584. break;
  2585. }
  2586. node.attributes.push({ name: parameter.name, value: value });
  2587. }
  2588. continue;
  2589. }
  2590. if (next) {
  2591. break;
  2592. }
  2593. const parameter = parameters.shift();
  2594. const argument = copyEvalArgs[0];
  2595. switch (parameter.type) {
  2596. case 'Tensor': {
  2597. if (Array.isArray(argument) || (!pytorch.Utility.isTensor(argument) && argument !== null && argument !== undefined)) {
  2598. if (parameter.optional) {
  2599. if (argument === undefined) {
  2600. copyArgs.shift();
  2601. copyEvalArgs.shift();
  2602. }
  2603. continue;
  2604. }
  2605. next = true;
  2606. break;
  2607. }
  2608. copyArgs.shift();
  2609. copyEvalArgs.shift();
  2610. const item = (argument === null || argument === undefined) ? {} : argument;
  2611. item.__variable__ = item.__variable__ || this.variable();
  2612. const inputs = [];
  2613. inputs.push({ id: item.__variable__ });
  2614. referencedParameters.push(item);
  2615. node.inputs.push(inputs);
  2616. break;
  2617. }
  2618. case 'Tensor[]': {
  2619. const argument = copyEvalArgs[0];
  2620. if (!Array.isArray(argument) || !argument.every((item) => pytorch.Utility.isTensor(item) || item === null)) {
  2621. if (parameter.optional) {
  2622. continue;
  2623. }
  2624. next = true;
  2625. break;
  2626. }
  2627. copyArgs.shift();
  2628. copyEvalArgs.shift();
  2629. const inputs = [];
  2630. for (let item of argument) {
  2631. if (item === null) {
  2632. item = {};
  2633. }
  2634. item.__variable__ = item.__variable__ || this.variable();
  2635. inputs.push({ id: item.__variable__ });
  2636. referencedParameters.push(item);
  2637. }
  2638. node.inputs.push(inputs);
  2639. break;
  2640. }
  2641. default: {
  2642. const arg = copyArgs[0];
  2643. if (!pytorch.Utility.isType(argument, parameter.type) && argument !== null) {
  2644. if (parameter.optional) {
  2645. continue;
  2646. }
  2647. next = true;
  2648. break;
  2649. }
  2650. if (arg.type !== '=') {
  2651. copyArgs.shift();
  2652. copyEvalArgs.shift();
  2653. node.attributes.push({ name: parameter.name, value: argument });
  2654. }
  2655. else {
  2656. throw new pytorch.Error('Expected named argument.');
  2657. }
  2658. break;
  2659. }
  2660. }
  2661. if (next) {
  2662. break;
  2663. }
  2664. }
  2665. if (next) {
  2666. continue;
  2667. }
  2668. const result = [];
  2669. for (let i = 0; i < schema.outputs.length; i++) {
  2670. const parameter = schema.outputs[i];
  2671. switch (parameter.type) {
  2672. case 'Tensor': {
  2673. const parameter = this.invoke('torch.Tensor', []);
  2674. parameter.__origin__ = type;
  2675. if (i === 0) {
  2676. switch (type) {
  2677. case 'torch.cat':
  2678. case 'torch.conv2d':
  2679. case 'torch.dropout':
  2680. case 'torch.flatten':
  2681. case 'torch.max_pool2d':
  2682. case 'torch.adaptive_avg_pool2d':
  2683. case 'torch.avg_pool2d':
  2684. case 'torch.quantize_per_tensor':
  2685. case 'torch.relu_':
  2686. case 'torch.hardtanh_':
  2687. case 'torch.unsqueeze':
  2688. case 'torch.slice': {
  2689. parameter.resize_([ NaN, NaN, NaN, NaN ]);
  2690. break;
  2691. }
  2692. case 'torch.conv3d': {
  2693. parameter.resize_([ NaN, NaN, NaN, NaN, NaN ]);
  2694. break;
  2695. }
  2696. case 'torch.embedding': {
  2697. parameter.resize_([ NaN, NaN, NaN ]);
  2698. break;
  2699. }
  2700. case 'torch.mul':
  2701. case 'torch.add':
  2702. case 'torch.batch_norm':
  2703. case 'torch.relu': {
  2704. const input = this.expression(args[0], context);
  2705. if (pytorch.Utility.isTensor(input) && Array.isArray(input.size())) {
  2706. parameter.resize_(input.size());
  2707. }
  2708. break;
  2709. }
  2710. case 'torch.ones':
  2711. case 'torch.zeros':
  2712. case 'torch.zeros_like': {
  2713. parameter.resize_(this.expression(args[0], context));
  2714. break;
  2715. }
  2716. case 'torch.new_full': {
  2717. parameter.resize_(this.expression(args[1], context));
  2718. break;
  2719. }
  2720. case 'ops.quantized.cat':
  2721. case 'ops.quantized.cat_relu':
  2722. case 'ops.quantized.linear':
  2723. case 'ops.quantized.conv2d':
  2724. case 'ops.quantized.conv2d_relu':
  2725. case 'ops.quantized.add_relu':
  2726. parameter.resize_([ NaN, NaN, NaN, NaN ]);
  2727. break;
  2728. }
  2729. }
  2730. parameter.__variable__ = this.variable();
  2731. result.push(parameter);
  2732. node.outputs.push([ { id: parameter.__variable__ } ]);
  2733. break;
  2734. }
  2735. case 'Tensor[]': {
  2736. let count = 1;
  2737. switch (type) {
  2738. case 'torch.chunk':
  2739. count = node.attributes.filter((attribute) => attribute.name == 'chunks')[0].value;
  2740. break;
  2741. case 'torch.meshgrid':
  2742. count = node.inputs[0].length;
  2743. break;
  2744. case 'torch.unbind':
  2745. count = args[0].__tuple__ || count;
  2746. break;
  2747. }
  2748. const tensors = [];
  2749. const outputs = [];
  2750. for (let i = 0; i < count; i ++) {
  2751. const tensor = this.invoke('torch.Tensor', []);
  2752. tensor.__origin__ = type;
  2753. tensor.__variable__ = this.variable();
  2754. tensors.push(tensor);
  2755. outputs.push({ id: tensor.__variable__ });
  2756. }
  2757. result.push(tensors);
  2758. node.outputs.push(outputs);
  2759. break;
  2760. }
  2761. default: {
  2762. if (!outputTypes || schema.outputs.length !== 1 || schema.outputs[0].type !== outputTypes[0]) {
  2763. next = true;
  2764. break;
  2765. }
  2766. const tensor = this.invoke('torch.Tensor', []);
  2767. tensor.resize_([]);
  2768. tensor.__origin__ = type;
  2769. tensor.__variable__ = this.variable();
  2770. result.push(tensor);
  2771. node.outputs.push([ { id: tensor.__variable__ } ]);
  2772. break;
  2773. }
  2774. }
  2775. }
  2776. if (next) {
  2777. continue;
  2778. }
  2779. for (const parameter of referencedParameters) {
  2780. parameter.__count__ = (parameter.__count__ || 0) + 1;
  2781. }
  2782. this.push(node);
  2783. if (result.length > 1) {
  2784. return result;
  2785. }
  2786. return result[0];
  2787. }
  2788. }
  2789. }
  2790. return super.call(target, name, args, context);
  2791. }
  2792. block(statements, context) {
  2793. statements = Array.prototype.slice.call(statements);
  2794. while (statements.length > 0) {
  2795. if (statements.length > 1) {
  2796. const assign = statements[0];
  2797. const condition = statements[1];
  2798. // _x = torch.ne(torch.len(torch.size(input)), 5)
  2799. // if _x:
  2800. // ops.prim.RaiseException(...)
  2801. if (assign.type === '=' &&
  2802. condition.type === 'if' &&
  2803. pytorch.Utility.isEqual(assign.target, condition.condition) &&
  2804. pytorch.Utility.isCall(assign.expression, 'torch.ne', 2) &&
  2805. pytorch.Utility.isCall(assign.expression.arguments[0], 'torch.len', 1) &&
  2806. pytorch.Utility.isCall(assign.expression.arguments[0].arguments[0], 'torch.size', 1) &&
  2807. condition.then.statements.length == 1 &&
  2808. pytorch.Utility.isCall(condition.then.statements[0], 'ops.prim.RaiseException', 1)) {
  2809. const tensor = this.expression(assign.expression.arguments[0].arguments[0].arguments[0], context);
  2810. if (tensor && tensor.size) {
  2811. const number = this.expression(assign.expression.arguments[1], context);
  2812. const size = tensor.size();
  2813. if (size && size.length && size.length !== number &&
  2814. size.every((item) => isNaN(item)) && number >= 3 && number <= 5) {
  2815. if (tensor.__origin__ === 'torch.quantize_per_tensor') {
  2816. tensor.resize_(Array(number).fill(NaN));
  2817. }
  2818. }
  2819. }
  2820. }
  2821. }
  2822. const statement = statements.shift();
  2823. // input_shape = torch.slice(torch.size(x), -2, 9223372036854775807, 1)
  2824. if (statement.type === '=' &&
  2825. pytorch.Utility.isCall(statement.expression, 'torch.slice', 4) &&
  2826. pytorch.Utility.isCall(statement.expression.arguments[0], 'torch.size', 1)) {
  2827. const tensor = this.expression(statement.expression.arguments[0].arguments[0], context);
  2828. if (tensor && tensor.shape === undefined) {
  2829. tensor.resize_([ 1, 3, 299, 299 ]);
  2830. }
  2831. }
  2832. // torch.slice(ops.prim.shape(input), 0, 2, 1)
  2833. if (statement.type === '=' &&
  2834. pytorch.Utility.isCall(statement.expression, 'torch.slice', 4) &&
  2835. pytorch.Utility.isCall(statement.expression.arguments[0], 'ops.prim.shape', 1)) {
  2836. const tensor = this.expression(statement.expression.arguments[0].arguments[0], context);
  2837. if (tensor && tensor.__origin__ === 'graph-input' && tensor.shape === undefined) {
  2838. tensor.resize_([ NaN, NaN, NaN, NaN ]);
  2839. }
  2840. }
  2841. // _3 = torch.le(xxxx, torch.dim(f0))
  2842. if (statement.type === '=' &&
  2843. pytorch.Utility.isCall(statement.expression, 'torch.le', 2) &&
  2844. pytorch.Utility.isCall(statement.expression.arguments[1], 'torch.dim', 1)) {
  2845. const tensor = this.expression(statement.expression.arguments[1].arguments[0], context);
  2846. if (tensor && tensor.__origin__ === 'graph-input' && tensor.shape === undefined) {
  2847. tensor.resize_([ NaN, NaN, NaN, NaN ]);
  2848. }
  2849. }
  2850. // if torch.ne(torch.dim(image), 3):
  2851. // xxxx
  2852. // ops.prim.RaiseException(_7)
  2853. if (statement.type === 'if' &&
  2854. pytorch.Utility.isCall(statement.condition, 'torch.ne', 2) &&
  2855. pytorch.Utility.isCall(statement.condition.arguments[0], 'torch.dim', 1) &&
  2856. statement.then.statements.length > 0 &&
  2857. pytorch.Utility.isCall(statement.then.statements.slice(-1).pop(), 'ops.prim.RaiseException', 1)) {
  2858. const tensor = this.expression(statement.condition.arguments[0].arguments[0], context);
  2859. const size = this.expression(statement.condition.arguments[1], context);
  2860. if (tensor && Number.isInteger(size) && size < 10) {
  2861. tensor.resize_(Array.isArray(tensor.shape) && tensor.shape.length > size ? tensor.shape.slice(-size) : Array(size).fill(NaN));
  2862. }
  2863. }
  2864. // dim = torch.sub(torch.dim(input), 2)
  2865. if (statement.type === '=' &&
  2866. statement.target.type === 'id' && statement.target.value === 'dim' &&
  2867. pytorch.Utility.isCall(statement.expression, 'torch.sub', 2) &&
  2868. pytorch.Utility.isCall(statement.expression.arguments[0], 'torch.dim', 1)) {
  2869. const tensor = this.expression(statement.expression.arguments[0].arguments[0], context);
  2870. if (tensor && tensor.__origin__ === 'graph-input' && tensor.shape === undefined) {
  2871. tensor.resize_([ NaN, NaN, NaN, NaN ]);
  2872. }
  2873. }
  2874. // a, b = torch.unbind(size, 0)
  2875. if (statement.type === '=' &&
  2876. statement.target.type === 'tuple' &&
  2877. pytorch.Utility.isCall(statement.expression, 'torch.unbind', 2)) {
  2878. statement.expression.arguments[0].__tuple__ = statement.target.value.length;
  2879. }
  2880. // x = torch.len(input)
  2881. if (statement.type === '=' &&
  2882. statement.target.type === 'id' &&
  2883. pytorch.Utility.isCall(statement.expression, 'torch.len', 1)) {
  2884. const tensor = this.expression(statement.expression.arguments[0], context);
  2885. if (tensor && tensor.__origin__ === 'graph-input' && tensor.shape === undefined) {
  2886. tensor.resize_([ NaN, NaN, NaN, NaN ]);
  2887. }
  2888. }
  2889. const value = this.statement(statement, context);
  2890. if (value !== undefined) {
  2891. return value;
  2892. }
  2893. }
  2894. }
  2895. push(node) {
  2896. this._nodes.push(node);
  2897. }
  2898. variable() {
  2899. this._variableIndex++;
  2900. return this._variableIndex.toString();
  2901. }
  2902. };
  2903. pytorch.ScalarType = {
  2904. uint8: 0,
  2905. int8: 1,
  2906. int16: 2,
  2907. int32: 3,
  2908. int64: 4,
  2909. float16: 5,
  2910. float32: 6,
  2911. float64: 7,
  2912. complex32: 8,
  2913. complex64: 9,
  2914. complex128: 10,
  2915. boolean: 11,
  2916. qint8: 12,
  2917. quint8: 13,
  2918. qint32: 14,
  2919. bfloat16: 15,
  2920. quint4x2: 16
  2921. };
  2922. pytorch.MemoryFormat = {
  2923. Contiguous: 0,
  2924. Preserve: 1,
  2925. ChannelsLast: 2,
  2926. ChannelsLast3d: 3
  2927. };
  2928. pytorch.Layout = {
  2929. Strided: 0,
  2930. Sparse: 1,
  2931. Mkldnn: 2
  2932. };
  2933. pytorch.Utility = class {
  2934. static getScalarType(scalarType) {
  2935. if (!pytorch.Utility._scalarTypes) {
  2936. pytorch.Utility._scalarTypes = [
  2937. { name: 'uint8', itemsize: 1 },
  2938. { name: 'int8', itemsize: 1 },
  2939. { name: 'int16', itemsize: 2 },
  2940. { name: 'int32', itemsize: 4 },
  2941. { name: 'int64', itemsize: 8 },
  2942. { name: 'float16', itemsize: 2 },
  2943. { name: 'float32', itemsize: 4 },
  2944. { name: 'float64', itemsize: 8 },
  2945. { name: 'complex32', itemsize: 4 },
  2946. { name: 'complex64', itemsize: 8 },
  2947. { name: 'complex128', itemsize: 16 },
  2948. { name: 'boolean', itemsize: 1 },
  2949. { name: 'qint8', itemsize: 1 },
  2950. { name: 'quint8', itemsize: 1 },
  2951. { name: 'qint32', itemsize: 4 },
  2952. { name: 'bfloat16', itemsize: 2 },
  2953. { name: 'quint4x2' }
  2954. ];
  2955. }
  2956. if (scalarType < pytorch.Utility._scalarTypes.length) {
  2957. return pytorch.Utility._scalarTypes[scalarType];
  2958. }
  2959. throw new pytorch.Error("Unknown scalar type '" + scalarType + "'.");
  2960. }
  2961. static target(expression) {
  2962. if (expression.type == 'id') {
  2963. return expression.value;
  2964. }
  2965. if (expression.type == '.') {
  2966. return pytorch.Utility.target(expression.target) + '.' + pytorch.Utility.target(expression.member);
  2967. }
  2968. return null;
  2969. }
  2970. static isTensor(obj) {
  2971. if (obj && obj.__class__) {
  2972. switch (obj.__class__.__module__) {
  2973. case 'torch':
  2974. case 'torch.cuda':
  2975. return obj.__class__.__name__.endsWith('Tensor');
  2976. case 'torch.nn.parameter':
  2977. return obj.__class__.__name__ === 'Parameter';
  2978. }
  2979. }
  2980. return false;
  2981. }
  2982. static toTensor(obj) {
  2983. if (obj && obj.__class__) {
  2984. switch (obj.__class__.__module__) {
  2985. case 'torch':
  2986. case 'torch.cuda':
  2987. return obj.__class__.__name__.endsWith('Tensor') ? obj : null;
  2988. case 'torch.nn.parameter':
  2989. return obj.__class__.__name__ === 'Parameter' ? obj.data : null;
  2990. }
  2991. }
  2992. return null;
  2993. }
  2994. static isType(obj, type) {
  2995. switch (type) {
  2996. case 'Tensor':
  2997. return !Array.isArray(obj) && (pytorch.Utility.isTensor(obj) || obj === null);
  2998. case 'Tensor[]':
  2999. return Array.isArray(obj) && obj.length > 0 && obj.every((tensor) => pytorch.Utility.isTensor(tensor) || tensor === null);
  3000. case 'Scalar':
  3001. return (obj !== null && obj !== Object(obj)) || (pytorch.Utility.isTensor(obj) && Array.isArray(obj.size()) && obj.size().length === 0);
  3002. case 'boolean':
  3003. return obj === true || obj === false;
  3004. case 'int64':
  3005. return Number.isInteger(obj) || obj instanceof base.Int64 || (typeof obj === 'number' && isNaN(obj));
  3006. case 'int64[]':
  3007. return Array.isArray(obj) && obj.every((item) => Number.isInteger(item) || (typeof item === 'number' && isNaN(item)) || item === undefined);
  3008. case 'int64[1]':
  3009. return pytorch.Utility.isType(obj, 'int64') || pytorch.Utility.isType(obj, 'int64[]');
  3010. case 'float32':
  3011. case 'float64':
  3012. return obj !== null && obj !== Object(obj);
  3013. case 'Layout':
  3014. case 'ScalarType':
  3015. case 'MemoryFormat':
  3016. return Number.isInteger(obj) || obj === null;
  3017. case 'Device':
  3018. return obj === null || obj === Object(obj);
  3019. }
  3020. return true;
  3021. }
  3022. static isCall(expression, name, size) {
  3023. if (expression.type === 'call' &&
  3024. expression.arguments.length === size &&
  3025. pytorch.Utility.target(expression.target) === name) {
  3026. return true;
  3027. }
  3028. return false;
  3029. }
  3030. static isEqual(a, b) {
  3031. return (a.type === 'id' && b.type === 'id' && a.value === b.value);
  3032. }
  3033. static findModule(root) {
  3034. if (root) {
  3035. const keys = [ '', 'model', 'net' ];
  3036. for (const key of keys) {
  3037. const obj = key === '' ? root : root[key];
  3038. if (obj) {
  3039. if (obj._modules) {
  3040. return [ { name: '', obj: obj } ];
  3041. }
  3042. const objKeys = Object.keys(obj).filter((key) => obj[key] && obj[key]._modules);
  3043. if (objKeys.length > 1) {
  3044. return objKeys.map((key) => { return { name: key, obj: obj[key] }; });
  3045. }
  3046. }
  3047. }
  3048. }
  3049. return null;
  3050. }
  3051. static findWeights(root) {
  3052. if (!root) {
  3053. return null;
  3054. }
  3055. if (root instanceof Map) {
  3056. const obj = {};
  3057. for (const pair of root) {
  3058. const key = pair[0];
  3059. const value = pair[1];
  3060. obj[key] = value;
  3061. }
  3062. root = obj;
  3063. }
  3064. const keys = root && !Array.isArray(root) ? Object.keys(root) : [];
  3065. if (keys.length > 1) {
  3066. keys.splice(0, keys.length);
  3067. }
  3068. keys.push(...[
  3069. 'state_dict', 'state', 'model_state', 'model', 'model_state_dict', 'model_dict', 'net_dict', 'params', 'generator',
  3070. 'discriminator', 'g_state', 'network', 'net', 'netG', 'net_states', 'state_dict_stylepredictor', 'state_dict_ghiasi', 'runner', ''
  3071. ]);
  3072. for (const key of keys) {
  3073. const obj = key === '' ? root : root[key];
  3074. let graphs = null;
  3075. graphs = graphs || pytorch.Utility._convertTensor(obj);
  3076. graphs = graphs || pytorch.Utility._convertObjectList(obj);
  3077. graphs = graphs || pytorch.Utility._convertStateDict(obj);
  3078. if (graphs) {
  3079. return graphs;
  3080. }
  3081. }
  3082. return null;
  3083. }
  3084. static _convertTensor(obj) {
  3085. if (obj && pytorch.Utility.isTensor(obj)) {
  3086. const layers = [];
  3087. const argument = { id: '', value: obj };
  3088. const parameter = { name: 'value', arguments: [ argument ] };
  3089. layers.push({ states: [ parameter ] });
  3090. return [ { layers: layers } ];
  3091. }
  3092. return null;
  3093. }
  3094. static _convertObjectList(list) {
  3095. if (list && Array.isArray(list) && list.every((obj) => obj.__class__ && Object.keys(obj).filter((key) => pytorch.Utility.isTensor(obj[key]).length > 0))) {
  3096. const layers = [];
  3097. for (const obj of list) {
  3098. const layer = { type: obj.__class__.__module__ + '.' + obj.__class__.__name__, states: [], attributes: [] };
  3099. for (const key of Object.keys(obj)) {
  3100. const value = obj[key];
  3101. if (pytorch.Utility.isTensor(value)) {
  3102. layer.states.push({ name: key, arguments: [ { id: '', value: value } ] });
  3103. }
  3104. else {
  3105. layer.attributes.push({ name: key, value: value });
  3106. }
  3107. }
  3108. layers.push(layer);
  3109. }
  3110. return [ { layers: layers } ];
  3111. }
  3112. return null;
  3113. }
  3114. static _convertStateDict(obj) {
  3115. const clean = (obj) => {
  3116. if (obj && Array.isArray(obj)) {
  3117. return obj;
  3118. }
  3119. if (obj && obj instanceof Map) {
  3120. return obj;
  3121. }
  3122. if (obj && Object(obj) === obj) {
  3123. const integer = new Set([ 'epoch', 'i_batch', 'num_vid', 'seen' ]);
  3124. const target = {};
  3125. for (const key of Object.keys(obj)) {
  3126. const value = obj[key];
  3127. if (key.indexOf('optim') !== -1 || key.indexOf('opt') !== -1) {
  3128. if (value.state && value.param_groups) {
  3129. continue;
  3130. }
  3131. }
  3132. if (key.indexOf('loss') !== -1 && Array.isArray(value)) {
  3133. continue;
  3134. }
  3135. if (integer.has(key) && Number.isInteger(value)) {
  3136. continue;
  3137. }
  3138. target[key] = value;
  3139. }
  3140. return target;
  3141. }
  3142. return obj;
  3143. };
  3144. const validate = (map) => {
  3145. let tensor = false;
  3146. if (map && map instanceof Map) {
  3147. for (const pair of map) {
  3148. const key = pair[0];
  3149. const value = pair[1];
  3150. if (key.split('.').pop() === '_metadata') {
  3151. continue;
  3152. }
  3153. if (pytorch.Utility.isTensor(value)) {
  3154. tensor = true;
  3155. continue;
  3156. }
  3157. else if (value && Array.isArray(value) && value.every((item) => pytorch.Utility.isTensor(item))) {
  3158. tensor = true;
  3159. continue;
  3160. }
  3161. else if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
  3162. continue;
  3163. }
  3164. return false;
  3165. }
  3166. }
  3167. return tensor;
  3168. };
  3169. const flatten = (obj) => {
  3170. if (!obj || Array.isArray(obj)) {
  3171. return null;
  3172. }
  3173. if (obj instanceof Map) {
  3174. if (validate(obj)) {
  3175. return obj;
  3176. }
  3177. return null;
  3178. }
  3179. if (Object(obj) !== obj) {
  3180. return null;
  3181. }
  3182. const map = new Map(Object.keys(obj).map((key) => [ key, obj[key] ]));
  3183. if (validate(map)) {
  3184. return map;
  3185. }
  3186. map.clear();
  3187. for (const key of Object.keys(obj)) {
  3188. const value = flatten(obj[key]);
  3189. if (value && value instanceof Map) {
  3190. for (const pair of value) {
  3191. map.set(key + '.' + pair[0], pair[1]);
  3192. }
  3193. continue;
  3194. }
  3195. return null;
  3196. }
  3197. return map;
  3198. };
  3199. if (!obj) {
  3200. return null;
  3201. }
  3202. obj = clean(obj);
  3203. const map = new Map();
  3204. if (Array.isArray(obj) && obj.every((item) => validate(item))) {
  3205. for (let i = 0; i < obj.length; i++) {
  3206. map.set(i.toString(), flatten(obj[i]));
  3207. }
  3208. }
  3209. else if (obj instanceof Map && validate(obj)) {
  3210. map.set('', flatten(obj));
  3211. }
  3212. else if (Object(obj) === obj && Object.keys(obj).every((key) => validate(obj[key]))) {
  3213. for (const key of Object.keys(obj)) {
  3214. map.set(key, obj[key]);
  3215. }
  3216. }
  3217. else if (Object(obj) === obj && Object.keys(obj).every((key) => pytorch.Utility.isTensor(obj[key]))) {
  3218. map.set('', new Map(Object.keys(obj).map((key) => [ key, obj[key] ])));
  3219. }
  3220. else {
  3221. const value = flatten(obj);
  3222. if (value) {
  3223. map.set('', value);
  3224. }
  3225. }
  3226. if (map.size > 0) {
  3227. const graphs = [];
  3228. for (const pair of map) {
  3229. const graph_key = pair[0];
  3230. const layer_map = pair[1];
  3231. const layers = new Map();
  3232. for (const item of layer_map) {
  3233. const key = item[0];
  3234. const value = item[1];
  3235. let layerName = '';
  3236. let parameter = '';
  3237. const keys = key.split('.');
  3238. if (keys[keys.length - 1] === '_metadata') {
  3239. continue;
  3240. }
  3241. if (keys.length >= 2 && keys[keys.length - 2] === '_packed_params') {
  3242. parameter = keys.slice(-2).join('.');
  3243. keys.pop();
  3244. keys.pop();
  3245. }
  3246. else {
  3247. parameter = keys.pop();
  3248. if (keys.length < 0) {
  3249. keys.push('');
  3250. }
  3251. }
  3252. layerName = keys.join('.');
  3253. if (!layers.has(layerName)) {
  3254. layers.set(layerName, { name: layerName, states: [], attributes: [] });
  3255. }
  3256. const layer = layers.get(layerName);
  3257. if (pytorch.Utility.isTensor(value)) {
  3258. layer.states.push({ name: parameter, arguments: [ { id: key, value: value } ] });
  3259. if (layer.name == '' && layer.states.length > 12) {
  3260. return null;
  3261. }
  3262. }
  3263. else if (value && Array.isArray(value) && value.every((item) => pytorch.Utility.isTensor(item))) {
  3264. layer.states.push({ name: parameter, arguments: value.map((item) => { return { id: '', value: item }; }) });
  3265. }
  3266. else if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
  3267. layer.attributes.push({ name: parameter, value: value });
  3268. }
  3269. }
  3270. graphs.push({
  3271. name: graph_key,
  3272. layers: layers.values()
  3273. });
  3274. }
  3275. return graphs;
  3276. }
  3277. return null;
  3278. }
  3279. };
  3280. pytorch.nnapi = {};
  3281. pytorch.nnapi.SerializedModel = class {
  3282. constructor(serialized_model /*, buffer_ptrs */) {
  3283. const reader = new pytorch.nnapi.SerializedModel.BinaryReader(serialized_model);
  3284. this.version = reader.int32();
  3285. if (this.version !== 1) {
  3286. throw new pytorch.Error('Invalid NNAPI serialized model version.');
  3287. }
  3288. const operands = new Array(reader.int32());
  3289. const values = new Array(reader.int32());
  3290. this.operations = new Array(reader.int32());
  3291. this.inputs = new Array(reader.int32());
  3292. this.outputs = new Array(reader.int32());
  3293. const types = new Map([
  3294. [ 0, 'float32' ],
  3295. [ 1, 'int32' ],
  3296. [ 2, 'uint32' ],
  3297. [ 3, 'float32' ],
  3298. [ 4, 'int32*' ],
  3299. [ 5, 'quant8_asymm*' ],
  3300. [ 6, 'boolean' ],
  3301. [ 7, 'quant16_symm*' ],
  3302. [ 8, 'float16*' ],
  3303. [ 9, 'boolean*' ],
  3304. [ 10, 'float16' ],
  3305. [ 11, 'quant8_symm_per_channel*' ],
  3306. [ 12, 'quant16_asymm*' ],
  3307. [ 13, 'quant8_symm*' ],
  3308. [ 14, 'quant8_asymm_signed*' ],
  3309. [ 16, 'model' ]
  3310. ]);
  3311. const operations = new Map([
  3312. [ 0, 'ADD' ],
  3313. [ 1, 'AVERAGE_POOL_2D' ],
  3314. [ 2, 'CONCATENATION' ],
  3315. [ 3, 'CONV_2D' ],
  3316. [ 4, 'DEPTHWISE_CONV_2D' ],
  3317. [ 5, 'DEPTH_TO_SPACE' ],
  3318. [ 6, 'DEQUANTIZE' ],
  3319. [ 7, 'EMBEDDING_LOOKUP' ],
  3320. [ 8, 'FLOOR' ],
  3321. [ 9, 'FULLY_CONNECTED' ],
  3322. [ 10, 'HASHTABLE_LOOKUP' ],
  3323. [ 11, 'L2_NORMALIZATION' ],
  3324. [ 12, 'L2_POOL_2D' ],
  3325. [ 13, 'LOCAL_RESPONSE_NORMALIZATION' ],
  3326. [ 14, 'LOGISTIC' ],
  3327. [ 15, 'LSH_PROJECTION' ],
  3328. [ 16, 'LSTM' ],
  3329. [ 17, 'MAX_POOL_2D' ],
  3330. [ 18, 'MUL' ],
  3331. [ 19, 'RELU' ],
  3332. [ 20, 'RELU1' ],
  3333. [ 21, 'RELU6' ],
  3334. [ 22, 'RESHAPE' ],
  3335. [ 23, 'RESIZE_BILINEAR' ],
  3336. [ 24, 'RNN' ],
  3337. [ 25, 'SOFTMAX' ],
  3338. [ 26, 'SPACE_TO_DEPTH' ],
  3339. [ 27, 'SVDF' ],
  3340. [ 28, 'TANH' ],
  3341. [ 29, 'BATCH_TO_SPACE_ND' ],
  3342. [ 30, 'DIV' ],
  3343. [ 31, 'MEAN' ],
  3344. [ 32, 'PAD' ],
  3345. [ 33, 'SPACE_TO_BATCH_ND' ],
  3346. [ 34, 'SQUEEZE' ],
  3347. [ 35, 'STRIDED_SLICE' ],
  3348. [ 36, 'SUB' ],
  3349. [ 37, 'TRANSPOSE' ],
  3350. [ 38, 'ABS' ],
  3351. [ 39, 'ARGMAX' ],
  3352. [ 40, 'ARGMIN' ],
  3353. [ 41, 'AXIS_ALIGNED_BBOX_TRANSFORM' ],
  3354. [ 42, 'BIDIRECTIONAL_SEQUENCE_LSTM' ],
  3355. [ 43, 'BIDIRECTIONAL_SEQUENCE_RNN' ],
  3356. [ 44, 'BOX_WITH_NMS_LIMIT' ],
  3357. [ 45, 'CAST' ],
  3358. [ 46, 'CHANNEL_SHUFFLE' ],
  3359. [ 47, 'DETECTION_POSTPROCESSING' ],
  3360. [ 48, 'EQUAL' ],
  3361. [ 49, 'EXP' ],
  3362. [ 50, 'EXPAND_DIMS' ],
  3363. [ 51, 'GATHER' ],
  3364. [ 52, 'GENERATE_PROPOSALS' ],
  3365. [ 53, 'GREATER' ],
  3366. [ 54, 'GREATER_EQUAL' ],
  3367. [ 55, 'GROUPED_CONV_2D' ],
  3368. [ 56, 'HEATMAP_MAX_KEYPOINT' ],
  3369. [ 57, 'INSTANCE_NORMALIZATION' ],
  3370. [ 58, 'LESS' ],
  3371. [ 59, 'LESS_EQUAL' ],
  3372. [ 60, 'LOG' ],
  3373. [ 61, 'LOGICAL_AND' ],
  3374. [ 62, 'LOGICAL_NOT' ],
  3375. [ 63, 'LOGICAL_OR' ],
  3376. [ 64, 'LOG_SOFTMAX' ],
  3377. [ 65, 'MAXIMUM' ],
  3378. [ 66, 'MINIMUM' ],
  3379. [ 67, 'NEG' ],
  3380. [ 68, 'NOT_EQUAL' ],
  3381. [ 69, 'PAD_V2' ],
  3382. [ 70, 'POW' ],
  3383. [ 71, 'PRELU' ],
  3384. [ 72, 'QUANTIZE' ],
  3385. [ 73, 'QUANTIZED_16BIT_LSTM' ],
  3386. [ 74, 'RANDOM_MULTINOMIAL' ],
  3387. [ 75, 'REDUCE_ALL' ],
  3388. [ 76, 'REDUCE_ANY' ],
  3389. [ 77, 'REDUCE_MAX' ],
  3390. [ 78, 'REDUCE_MIN' ],
  3391. [ 79, 'REDUCE_PROD' ],
  3392. [ 80, 'REDUCE_SUM' ],
  3393. [ 81, 'ROI_ALIGN' ],
  3394. [ 82, 'ROI_POOLING' ],
  3395. [ 83, 'RSQRT' ],
  3396. [ 84, 'SELECT' ],
  3397. [ 85, 'SIN' ],
  3398. [ 86, 'SLICE' ],
  3399. [ 87, 'SPLIT' ],
  3400. [ 88, 'SQRT' ],
  3401. [ 89, 'TILE' ],
  3402. [ 90, 'TOPK_V2' ],
  3403. [ 91, 'TRANSPOSE_CONV_2D' ],
  3404. [ 92, 'UNIDIRECTIONAL_SEQUENCE_LSTM' ],
  3405. [ 93, 'UNIDIRECTIONAL_SEQUENCE_RNN' ],
  3406. [ 94, 'RESIZE_NEAREST_NEIGHBOR' ],
  3407. [ 95, 'QUANTIZED_LSTM' ],
  3408. [ 96, 'IF' ],
  3409. [ 97, 'WHILE' ],
  3410. [ 98, 'ELU' ],
  3411. [ 99, 'HARD_SWISH' ],
  3412. [ 100, 'FILL' ],
  3413. [ 101, 'RANK' ],
  3414. ]);
  3415. for (let i = 0; i < operands.length; i++) {
  3416. const type = reader.int32();
  3417. operands[i] = {
  3418. type: types.has(type) ? types.get(type) : type,
  3419. dimensions: new Array(reader.uint32()),
  3420. scale: reader.float32(),
  3421. zero_point: reader.int32()
  3422. };
  3423. }
  3424. for (let i = 0; i < values.length; i++) {
  3425. values[i] = {
  3426. index: reader.int32(),
  3427. source_type: reader.int32(),
  3428. source_length: reader.uint32()
  3429. };
  3430. }
  3431. for (let i = 0; i < this.operations.length; i++) {
  3432. const operation_type = reader.int32();
  3433. this.operations[i] = {
  3434. operation_type: operations.has(operation_type) ? operations.get(operation_type) : operation_type,
  3435. inputs: new Array(reader.uint32()),
  3436. outputs: new Array(reader.uint32())
  3437. };
  3438. }
  3439. for (const operand of operands) {
  3440. for (let i = 0; i< operand.dimensions.length; i++) {
  3441. operand.dimensions[i] = reader.uint32();
  3442. }
  3443. }
  3444. for (const value of values) {
  3445. const operand = operands[value.index];
  3446. switch (value.source_type) {
  3447. case 0: { // immediate
  3448. switch (operand.type) {
  3449. case 'boolean':
  3450. operand.value = reader.byte() ? true : false;
  3451. reader.skip(3);
  3452. break;
  3453. case 'int32':
  3454. operand.value = reader.int32();
  3455. break;
  3456. case 'float32':
  3457. operand.value = reader.float32();
  3458. break;
  3459. case 'int32*':
  3460. operand.value = reader.read(value.source_length);
  3461. break;
  3462. default:
  3463. throw new pytorch.Error("Unsupported NNAPI operand type '" + operand.type.toString() + "'.");
  3464. }
  3465. break;
  3466. }
  3467. case 2: { // numbered buffer
  3468. if (value.source_length !== 12) {
  3469. throw new pytorch.Error('Invalid NNAPI numbered buffer source length.');
  3470. }
  3471. const number = reader.uint32();
  3472. const offset = reader.uint32();
  3473. const operand_length = reader.uint32();
  3474. operand.value = [ number, offset, operand_length ];
  3475. break;
  3476. }
  3477. case 3: { // numbered memory
  3478. throw new pytorch.Error('NNAPI numbered memory buffer not implemented.');
  3479. }
  3480. default: {
  3481. throw new pytorch.Error('Unsupported NNAPI value source type.');
  3482. }
  3483. }
  3484. }
  3485. for (const operation of this.operations) {
  3486. for (let i = 0; i< operation.inputs.length; i++) {
  3487. operation.inputs[i] = operands[reader.uint32()];
  3488. }
  3489. for (let i = 0; i< operation.outputs.length; i++) {
  3490. operation.outputs[i] = operands[reader.uint32()];
  3491. }
  3492. }
  3493. for (let i = 0; i< this.inputs.length; i++) {
  3494. this.inputs[i] = operands[reader.uint32()];
  3495. }
  3496. for (let i = 0; i< this.outputs.length; i++) {
  3497. this.outputs[i] = operands[reader.uint32()];
  3498. }
  3499. if (!reader.end()) {
  3500. throw new pytorch.Error('Invalid NNAPI serialized model length.');
  3501. }
  3502. }
  3503. };
  3504. pytorch.nnapi.SerializedModel.BinaryReader = class {
  3505. constructor(buffer) {
  3506. this._buffer = buffer;
  3507. this._dataView = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  3508. this._position = 0;
  3509. }
  3510. end() {
  3511. return this._position >= this._buffer.length;
  3512. }
  3513. skip(offset) {
  3514. this._position += offset;
  3515. if (this._position > this._buffer.length) {
  3516. throw new pytorch.Error('Expected ' + (this._position - this._buffer.length) + ' more bytes. The file might be corrupted. Unexpected end of file.');
  3517. }
  3518. }
  3519. read(length) {
  3520. const position = this._position;
  3521. this.skip(length);
  3522. return this._buffer.subarray(position, this._position);
  3523. }
  3524. byte() {
  3525. const position = this._position;
  3526. this.skip(1);
  3527. return this._dataView.getUint8(position, true);
  3528. }
  3529. int32() {
  3530. const position = this._position;
  3531. this.skip(4);
  3532. return this._dataView.getInt32(position, true);
  3533. }
  3534. uint32() {
  3535. const position = this._position;
  3536. this.skip(4);
  3537. return this._dataView.getUint32(position, true);
  3538. }
  3539. int64() {
  3540. const value = this.int32();
  3541. if (this.int32() !== 0) {
  3542. throw new pytorch.Error('Invalid int64 value.');
  3543. }
  3544. return value;
  3545. }
  3546. float32() {
  3547. const position = this._position;
  3548. this.skip(4);
  3549. return this._dataView.getFloat32(position, true);
  3550. }
  3551. };
  3552. pytorch.Metadata = class {
  3553. static open(context) {
  3554. if (pytorch.Metadata._metadata) {
  3555. return Promise.resolve(pytorch.Metadata._metadata);
  3556. }
  3557. else {
  3558. return context.request('pytorch-metadata.json', 'utf-8', null).then((data) => {
  3559. pytorch.Metadata._metadata = new pytorch.Metadata(data);
  3560. return pytorch.Metadata._metadata;
  3561. }).catch(() => {
  3562. pytorch.Metadata._metadata = new pytorch.Metadata(null);
  3563. return pytorch.Metadata._metadata;
  3564. });
  3565. }
  3566. }
  3567. constructor(data) {
  3568. this._map = new Map();
  3569. this._attributeCache = new Map();
  3570. if (data) {
  3571. const items = JSON.parse(data);
  3572. for (const item of items) {
  3573. this._map.set(item.name, item);
  3574. const index = item.name.indexOf(':');
  3575. if (index !== -1) {
  3576. const name = item.name.substring(0, index);
  3577. if (!this._map.has(name)) {
  3578. this._map.set(name, []);
  3579. }
  3580. this._map.get(name).push(item.name);
  3581. }
  3582. }
  3583. }
  3584. }
  3585. type(name) {
  3586. const schema = this._map.get(name);
  3587. if (schema) {
  3588. return Array.isArray(schema) ? schema.map((name) => this._map.get(name)) : schema;
  3589. }
  3590. return null;
  3591. }
  3592. attribute(type, name) {
  3593. const attributeName = type + ':' + name;
  3594. if (!this._attributeCache.has(attributeName)) {
  3595. this._attributeCache.set(attributeName, null);
  3596. const schema = this.type(type);
  3597. if (schema) {
  3598. if (schema.inputs) {
  3599. for (const input of schema.inputs) {
  3600. this._attributeCache.set(type + ':' + input.name, input);
  3601. }
  3602. }
  3603. if (schema.attributes) {
  3604. for (const attribute of schema.attributes) {
  3605. this._attributeCache.set(type + ':' + attribute.name, attribute);
  3606. }
  3607. }
  3608. }
  3609. }
  3610. return this._attributeCache.get(attributeName);
  3611. }
  3612. };
  3613. pytorch.Error = class extends Error {
  3614. constructor(message) {
  3615. super(message);
  3616. this.name = 'Error loading PyTorch model.';
  3617. }
  3618. };
  3619. if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  3620. module.exports.ModelFactory = pytorch.ModelFactory;
  3621. }