pytorch.js 153 KB

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