pytorch.js 181 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052
  1. // Experimental
  2. import * as base from './base.js';
  3. import * as flatbuffers from './flatbuffers.js';
  4. import * as python from './python.js';
  5. const pytorch = {};
  6. const numpy = {};
  7. pytorch.ModelFactory = class {
  8. match(context) {
  9. const container = pytorch.Container.open(context);
  10. if (container) {
  11. context.type = container.type;
  12. context.target = container;
  13. }
  14. }
  15. filter(context, type) {
  16. if (context.type === 'pytorch.export' && type === 'pytorch.zip') {
  17. return false;
  18. }
  19. if (context.type === 'pytorch.index' && type === 'pytorch.zip') {
  20. return false;
  21. }
  22. if (context.type === 'pytorch.model.json' && type === 'pytorch.data.pkl') {
  23. return false;
  24. }
  25. if (context.type === 'pytorch.model.json' && type === 'pickle') {
  26. return false;
  27. }
  28. return true;
  29. }
  30. async open(context) {
  31. const metadata = await pytorch.Metadata.open(context);
  32. const target = context.target;
  33. target.on('resolve', (_, name) => {
  34. context.error(new pytorch.Error(`Unknown type name '${name}'.`), false);
  35. });
  36. await target.read(metadata);
  37. if (!target.format || (!target.modules && !target.module)) {
  38. throw new pytorch.Error("Container not implemented.");
  39. }
  40. return new pytorch.Model(metadata, target);
  41. }
  42. };
  43. pytorch.Model = class {
  44. constructor(metadata, target) {
  45. this.format = target.format;
  46. this.producer = target.producer || '';
  47. this.graphs = [];
  48. if (target.module) {
  49. const graph = new pytorch.Graph(metadata, null, '', target.module);
  50. this.graphs.push(graph);
  51. } else if (target.modules) {
  52. for (const [name, value] of target.modules) {
  53. const graph = new pytorch.Graph(metadata, null, name, value);
  54. this.graphs.push(graph);
  55. }
  56. }
  57. }
  58. };
  59. pytorch.Graph = class {
  60. constructor(metadata, type, name, module) {
  61. this.nodes = [];
  62. this.inputs = [];
  63. this.outputs = [];
  64. this.groups = true;
  65. this.name = name || '';
  66. this.type = type;
  67. const values = new Map();
  68. values.map = (name, type, tensor) => {
  69. if (tensor) {
  70. return new pytorch.Value(name, type, null, tensor);
  71. }
  72. if (!values.has(name)) {
  73. values.set(name, new pytorch.Value(name, type, null, tensor));
  74. } else if (type || tensor) {
  75. throw new pytorch.Error(`Duplicate value '${name}'.`);
  76. }
  77. return values.get(name);
  78. };
  79. type = module && module.__class__ && module.__class__.__module__ && module.__class__.__name__ ? `${module.__class__.__module__}.${module.__class__.__name__}` : null;
  80. if ((type === 'torch.ScriptModule' || type === 'torch.jit._script.ScriptModule' || type === 'torch.jit._script.RecursiveScriptModule') && module.graph) {
  81. const initializers = new Map();
  82. const graph = module.graph;
  83. const constants = module.code_with_constants[1].const_mapping;
  84. if (constants) {
  85. for (const [key, value] of constants) {
  86. const name = `CONSTANTS.${key}`;
  87. if (pytorch.Utility.isTensor(value)) {
  88. initializers.set(value, new pytorch.Tensor(name, value));
  89. } else if (pytorch.Utility.isObject(value)) {
  90. initializers.set(value, value);
  91. } else {
  92. // throw new pytorch.Error('Unsupported constant.');
  93. }
  94. }
  95. }
  96. const queue = [module.data];
  97. while (queue.length > 0) {
  98. const module = queue.shift();
  99. for (const [key, obj] of Object.entries(module)) {
  100. if (key !== '__module__' && key !== '__name__' && key !== '__class__' && key !== '__parent__') {
  101. if (!Array.isArray(obj) && obj === Object(obj)) {
  102. if (pytorch.Utility.isTensor(obj)) {
  103. const parameter = obj;
  104. parameter.__parent__ = module;
  105. if (parameter.storage() && !parameter.__origin__) {
  106. if (parameter.__count__ === undefined || parameter.__count__ === 1) {
  107. initializers.set(parameter, new pytorch.Tensor(parameter.name, parameter));
  108. }
  109. }
  110. } else if (pytorch.Utility.isObject(obj)) {
  111. if (obj.__count__ === undefined || obj.__count__ === 1) {
  112. initializers.set(obj, obj);
  113. }
  114. queue.push(obj);
  115. } else if (obj && obj.__class__) {
  116. obj.__parent__ = module;
  117. obj.__name__ = obj.__name__ || key;
  118. queue.push(obj);
  119. }
  120. }
  121. }
  122. }
  123. }
  124. for (const value of graph.inputs()) {
  125. const identifier = value.unique().toString();
  126. const name = value.debugName() || identifier;
  127. this.inputs.push(new pytorch.Argument(name, [values.map(identifier)]));
  128. }
  129. for (const value of graph.outputs()) {
  130. const identifier = value.unique().toString();
  131. this.outputs.push(new pytorch.Argument(identifier, [values.map(identifier)]));
  132. }
  133. for (const node of graph.nodes()) {
  134. if (node === graph.param_node() ||
  135. node === graph.return_node()) {
  136. continue;
  137. }
  138. if (node.kind() === 'prim::ListConstruct' &&
  139. node.outputs().length === 1 &&
  140. node.outputs().every((output) => output.uses().length === 1) &&
  141. node.inputs().every((input) => pytorch.Utility.isTensor(input.value))) {
  142. continue;
  143. }
  144. if (node.kind() === 'prim::ListUnpack' &&
  145. node.inputs().length === 1 &&
  146. node.inputs().every((input) => input.uses().length === 1) &&
  147. node.outputs().every((output) => pytorch.Utility.isTensor(output.value))) {
  148. continue;
  149. }
  150. this.nodes.push(new pytorch.Node(metadata, null, null, node, initializers, values));
  151. }
  152. if (module) {
  153. const queue = [module.data];
  154. while (queue.length > 0) {
  155. const module = queue.pop();
  156. if (module && !pytorch.Utility.isObject(module)) {
  157. if (!module.__hide__ && pytorch.Graph._getParameters(module).size > 0) {
  158. for (const [name, obj] of Object.entries(module)) {
  159. if ((obj && obj.__hide__) || (obj !== null && !pytorch.Utility.isTensor(obj)) && typeof obj !== 'boolean' && typeof obj !== 'number' && typeof obj !== 'string') {
  160. delete module[name];
  161. }
  162. }
  163. const node = new pytorch.Node(metadata, null, null, module, initializers, values);
  164. this.nodes.push(node);
  165. }
  166. const modules = [];
  167. if (module.__class__ && module.__class__.__module__ && module.__class__.__name__) {
  168. for (const [key, value] of Object.entries(module)) {
  169. if (!key.startsWith('__') && value && value.__class__ && value.__class__.__module__ && value.__class__.__name__ && !pytorch.Utility.isTensor(value)) {
  170. modules.push(value);
  171. }
  172. }
  173. }
  174. queue.push(...modules.reverse());
  175. }
  176. }
  177. }
  178. } else if (pytorch.Utility.isTensor(module)) {
  179. const node = new pytorch.Node(metadata, null, type, { value: module });
  180. this.nodes.push(node);
  181. } else {
  182. const weights = this.type === 'weights' ? module : pytorch.Utility.weights(module);
  183. if (weights) {
  184. this.name = !this.name && typeof module.__name__ === 'string' ? module.__name__ : this.name;
  185. for (const [name, module] of weights) {
  186. const node = new pytorch.Node(metadata, name, 'Weights', module);
  187. this.nodes.push(node);
  188. }
  189. } else {
  190. const modules = Array.isArray(module) && module.every((module) => module && !pytorch.Utility.isTensor(module) && (module._modules !== undefined || module.__class__)) ? module : [module];
  191. for (const module of modules) {
  192. const type = this.type === 'weights' ? 'Weights' : null;
  193. const node = new pytorch.Node(metadata, null, type, module, null, values);
  194. this.nodes.push(node);
  195. }
  196. }
  197. }
  198. }
  199. static _getParameters(module) {
  200. const parameters = new Map();
  201. if (module && module.__class__.__module__ && module.__class__.__name__) {
  202. for (const [key, value] of Object.entries(module)) {
  203. if (pytorch.Utility.isTensor(value)) {
  204. parameters.set(key, value);
  205. }
  206. }
  207. }
  208. return parameters;
  209. }
  210. };
  211. pytorch.Argument = class {
  212. constructor(name, value, type, visible) {
  213. this.name = name;
  214. this.value = value;
  215. this.type = type || null;
  216. this.visible = visible !== false;
  217. }
  218. };
  219. pytorch.Value = class {
  220. constructor(name, type, quantization, initializer) {
  221. if (typeof name !== 'string') {
  222. throw new pytorch.Error(`Invalid value identifier '${JSON.stringify(name)}'.`);
  223. }
  224. this.name = name;
  225. this.type = initializer && initializer.type ? initializer.type : type || null;
  226. this.quantization = quantization;
  227. this.initializer = initializer || null;
  228. }
  229. };
  230. pytorch.Node = class {
  231. constructor(metadata, name, type, obj, initializers, values, stack) {
  232. this.name = name || '';
  233. this.nodes = [];
  234. this.attributes = [];
  235. this.inputs = [];
  236. this.outputs = [];
  237. const createType = (metadata, name) => {
  238. if (name instanceof pytorch.nnapi.Graph) {
  239. return name;
  240. }
  241. const key = name.startsWith('__torch__.') ? name.substring(10) : name;
  242. const value = metadata.type(key);
  243. const type = value ? { ...value } : { name };
  244. type.identifier = name;
  245. type.name = type.name.indexOf('::') === -1 ? type.name : type.name.split('::').pop().split('.')[0];
  246. return type;
  247. };
  248. const createAttribute = (metadata, name, value) => {
  249. let visible = true;
  250. let type = 'attribute';
  251. metadata = name === 'training' ? { type: 'boolean', visible: false } : metadata;
  252. if (metadata) {
  253. if (metadata.type) {
  254. type = metadata.type;
  255. }
  256. if (metadata.visible === false) {
  257. visible = false;
  258. } else if (metadata.default !== undefined) {
  259. if (Array.isArray(value)) {
  260. if (Array.isArray(metadata.default)) {
  261. visible = value.length !== metadata.default || !value.every((item, index) => item === metadata.default[index]);
  262. } else {
  263. visible = !value.every((item) => item === metadata.default);
  264. }
  265. } else {
  266. visible = value !== metadata.default;
  267. }
  268. }
  269. }
  270. if (Array.isArray(value) && value.length > 0 && value.every((obj) => obj && obj.__class__ && obj.__class__.__module__ && obj.__class__.__module__.startsWith('torch.nn'))) {
  271. value = '?';
  272. }
  273. return new pytorch.Argument(name, value, type, visible);
  274. };
  275. let module = null;
  276. if (pytorch.Utility.isInstance(obj, 'torch.Node')) {
  277. const node = obj;
  278. this.type = createType(metadata, node.kind());
  279. let match = true;
  280. let count = 0;
  281. for (const input of node.inputs()) {
  282. const value = input.value;
  283. let values = [];
  284. if (pytorch.Utility.isObject(value)) {
  285. values = Object.values(value);
  286. } else if (pytorch.Utility.isTensor(value)) {
  287. values = [value];
  288. if (input.node() &&
  289. input.node().kind() === 'prim::ListConstruct' &&
  290. input.uses().length === 1 &&
  291. input.node().inputs().every((input) => pytorch.Utility.isTensor(input.value))) {
  292. values = input.node().inputs().map((input) => input.value);
  293. }
  294. }
  295. for (const value of values) {
  296. const parameter = initializers.get(value);
  297. if (parameter) {
  298. if (value.__parent__ && (module === null || module === value.__parent__)) {
  299. module = value.__parent__;
  300. count++;
  301. } else if (value.__name__ && value.__name__.startsWith('CONSTANTS.c')) {
  302. count++;
  303. } else {
  304. match = false;
  305. break;
  306. }
  307. }
  308. }
  309. if (!match) {
  310. break;
  311. }
  312. }
  313. if (module) {
  314. const parameters = pytorch.Graph._getParameters(module);
  315. parameters.delete('num_batches_tracked');
  316. if (parameters.size === count && match) {
  317. module.__hide__ = true;
  318. } else {
  319. module = null;
  320. }
  321. }
  322. const inputs = node.inputs();
  323. for (let i = 0; i < inputs.length; i++) {
  324. const input = inputs[i];
  325. const schema = this.type && this.type.inputs && i < this.type.inputs.length ? this.type.inputs[i] : null;
  326. const name = schema && schema.name ? schema.name : i.toString();
  327. let type = schema && schema.type ? schema.type : null;
  328. let array = false;
  329. if (type && type.endsWith('[]')) {
  330. array = true;
  331. type = type.slice(0, -2);
  332. }
  333. let argument = null;
  334. if (pytorch.Utility.isObjectType(type)) {
  335. const obj = input.value;
  336. if (!array && initializers.has(obj)) {
  337. const node = new pytorch.Node(metadata, name, type, obj, initializers, values);
  338. argument = new pytorch.Argument(name, node, 'object');
  339. } else if (array && Array.isArray(obj) && obj.every((obj) => initializers.has(obj))) {
  340. const node = obj.map((obj) => new pytorch.Node(metadata, name, type, obj, initializers, values));
  341. argument = new pytorch.Argument(name, node, 'object[]');
  342. } else {
  343. const identifier = input.unique().toString();
  344. const value = values.map(identifier);
  345. argument = new pytorch.Argument(name, [value]);
  346. }
  347. } else if (pytorch.Utility.isTensor(input.value) || input.value === undefined || input.value === null) {
  348. let list = [input];
  349. if (input.node() &&
  350. input.node().kind() === 'prim::ListConstruct' &&
  351. input.uses().length === 1 &&
  352. input.node().inputs().every((input) => pytorch.Utility.isTensor(input.value))) {
  353. list = input.node().inputs();
  354. }
  355. const args = list.map((input) => {
  356. let initializer = null;
  357. let identifier = input.unique().toString();
  358. if (input.value) {
  359. const value = input.value;
  360. const hide = value.__parent__ ? value.__parent__.__hide__ : true;
  361. initializer = hide ? initializers.get(value) : null;
  362. identifier = initializer ? initializer.name : identifier;
  363. }
  364. if (initializer) {
  365. return new pytorch.Value(identifier, null, null, initializer);
  366. }
  367. return values.map(identifier);
  368. });
  369. argument = new pytorch.Argument(name, args);
  370. } else {
  371. argument = createAttribute(schema, schema.name, input.value);
  372. }
  373. this.inputs.push(argument);
  374. }
  375. const outputs = node.outputs();
  376. for (let i = 0; i < outputs.length; i++) {
  377. const output = outputs[i];
  378. const metadata = this.type && this.type.outputs && i < this.type.outputs.length ? this.type.outputs[i] : null;
  379. let name = '';
  380. if (metadata && metadata.name) {
  381. name = metadata.name;
  382. } else {
  383. name = i === 0 ? 'output' : `output${i}`;
  384. }
  385. let list = [output];
  386. if (output.uses().length === 1 &&
  387. output.uses()[0].user &&
  388. output.uses()[0].user.kind() === 'prim::ListUnpack' &&
  389. output.uses()[0].user.outputs().every((output) => pytorch.Utility.isTensor(output.value))) {
  390. list = output.uses()[0].user.outputs();
  391. }
  392. const args = list.map((output) => values.map(output.unique().toString()));
  393. const argument = new pytorch.Argument(name, args);
  394. this.outputs.push(argument);
  395. }
  396. } else {
  397. if (!type) {
  398. if (pytorch.Utility.isInstance(obj, 'torch.jit._script.RecursiveScriptModule') && obj._c && obj._c.qualified_name) {
  399. type = obj._c.qualified_name;
  400. } else if (pytorch.Utility.isInstance(obj, 'builtins.function')) {
  401. type = `${obj.__module__}.${obj.__name__}`;
  402. obj = {};
  403. } else if (obj && obj.__class__ && obj.__class__.__module__ && obj.__class__.__name__) {
  404. type = `${obj.__class__.__module__}.${obj.__class__.__name__}`;
  405. } else {
  406. type = 'builtins.object';
  407. }
  408. }
  409. this.type = createType(metadata, type);
  410. stack = stack || new Set();
  411. const weights = pytorch.Utility.weights(obj);
  412. if (weights) {
  413. const type = this.type.name;
  414. this.type = new pytorch.Graph(metadata, 'weights', '', weights);
  415. this.type.name = type;
  416. } else if (obj && pytorch.Utility.isInstance(obj, 'fastai.data.core.DataLoaders')) {
  417. // continue
  418. } else if (obj && pytorch.Utility.isInstance(obj, '__torch__.torch.classes._nnapi.Compilation')) {
  419. // continue
  420. } else if (obj && type === 'builtins.bytearray') {
  421. const argument = new pytorch.Argument('value', Array.from(obj), 'byte[]');
  422. this.inputs.push(argument);
  423. } else if (obj) {
  424. const inputs = new Map(Array.isArray(this.type.inputs) ? this.type.inputs.map((input) => [input.name, input]) : []);
  425. const list = obj instanceof Map ? Array.from(obj) : Object.entries(obj);
  426. for (const [name, value] of list) {
  427. if (name === '__class__' || name === '__parent__' || name === '__name__') {
  428. continue;
  429. } else if (pytorch.Utility.isInstance(value, 'collections.OrderedDict') && value instanceof Map && value.size === 0) {
  430. continue;
  431. } else if (pytorch.Utility.isInstance(value, 'builtins.set') && value instanceof Set && value.size === 0) {
  432. continue;
  433. } else if (pytorch.Utility.isInstance(value, 'builtins.list') && Array.isArray(value) && value.length === 0) {
  434. continue;
  435. }
  436. const parameters = new Map();
  437. if ((name === '_parameters' || name === '_buffers') && value instanceof Map && value.size > 0) {
  438. for (const [name, obj] of Array.from(value)) {
  439. parameters.set(name, obj);
  440. }
  441. } else if (Array.isArray(value) && value.every((tensor) => pytorch.Utility.isTensor(tensor))) {
  442. parameters.set(name, value);
  443. } else if (pytorch.Utility.isTensor(value)) {
  444. parameters.set(name, value);
  445. }
  446. if (parameters.size > 0) {
  447. for (const [name, value] of parameters) {
  448. const list = Array.isArray(value) ? value.map((item) => pytorch.Utility.toTensor(item)) : [pytorch.Utility.toTensor(value)];
  449. const visible = inputs.has(name) ? inputs.get(name).visible || true : true;
  450. const args = list.filter((value) => value !== null && !value.__origin__).map((value) => {
  451. const name = value && value.name ? value.name : '';
  452. const identifier = list.length === 1 && value && value.__name__ ? value.__name__ : name;
  453. let tensor = null;
  454. if (initializers && initializers.has(value)) {
  455. tensor = initializers.get(value);
  456. } else {
  457. value = value.__source__ ? value.__source__ : value;
  458. tensor = value ? new pytorch.Tensor(identifier, value) : null;
  459. }
  460. return new pytorch.Value(identifier, null, null, tensor);
  461. });
  462. const argument = new pytorch.Argument(name, args, null, visible);
  463. this.inputs.push(argument);
  464. if (value && value.__variable__) {
  465. const argument = new pytorch.Argument(name, [values.map(value.__variable__)]);
  466. this.outputs.push(argument);
  467. }
  468. }
  469. continue;
  470. }
  471. const type = this.type.identifier;
  472. if (pytorch.Utility.isTensor(value)) {
  473. const tensor = new pytorch.Tensor('', value);
  474. const argument = new pytorch.Argument(name, tensor, 'tensor');
  475. this.inputs.push(argument);
  476. } else if (value && pytorch.Utility.isInstance(value, 'torch.dtype')) {
  477. const node = new pytorch.Node(metadata, null, value.toString(), {});
  478. const argument = new pytorch.Argument(name, node, 'object');
  479. this.inputs.push(argument);
  480. } else if (Array.isArray(value) && value.some((value) => pytorch.Utility.isTensor(value)) && value.every((value) => pytorch.Utility.isTensor(value) || value === null)) {
  481. const tensors = value.map((value) => value === null ? value : new pytorch.Tensor('', value));
  482. const argument = new pytorch.Argument(name, tensors, 'tensor[]');
  483. this.inputs.push(argument);
  484. } else if (pytorch.Utility.isInstance(value, 'numpy.ndarray') || pytorch.Utility.isInstance(value, 'numpy.matrix')) {
  485. const tensor = new numpy.Tensor(value);
  486. const argument = new pytorch.Argument(name, tensor, 'tensor');
  487. this.inputs.push(argument);
  488. } else if (Array.isArray(value) && value.every((value) => typeof value === 'string')) {
  489. const argument = new pytorch.Argument(name, value, 'string[]');
  490. this.inputs.push(argument);
  491. } else if (Array.isArray(value) && value.every((value) => typeof value === 'number')) {
  492. const argument = new pytorch.Argument(name, value, 'attribute');
  493. this.inputs.push(argument);
  494. } else if (name === '_modules' && pytorch.Utility.isInstance(value, 'collections.OrderedDict') &&
  495. value instanceof Map && Array.from(value).every(([, value]) => value === null || value.__class__)) {
  496. const values = Array.from(value).filter(([, value]) => !stack.has(value)).map(([name, obj]) => {
  497. stack.add(value);
  498. const type = obj === null ? 'builtins.NoneType' : `${obj.__class__.__module__}.${obj.__class__.__name__}`;
  499. const node = new pytorch.Node(metadata, name, type, obj);
  500. stack.delete(value);
  501. return node;
  502. });
  503. const argument = new pytorch.Argument(name, values, 'object[]');
  504. this.inputs.push(argument);
  505. } else if (value && Array.isArray(value) && value.length > 0 && value.every((obj) => Array.isArray(obj) && obj.every((item) => typeof item === 'string' || typeof item === 'number'))) {
  506. const argument = new pytorch.Argument(name, value, 'attribute');
  507. this.inputs.push(argument);
  508. } else if (value && Array.isArray(value) && value.length > 0 && value.every((obj) => obj && (obj.__class__ || obj === Object(obj)))) {
  509. const list = value.filter((value) => !stack.has(value));
  510. const nodes = list.map((value) => {
  511. stack.add(value);
  512. const node = new pytorch.Node(metadata, null, null, value, initializers, values, stack);
  513. stack.delete(value);
  514. return node;
  515. });
  516. const argument = new pytorch.Argument(name, nodes, 'object[]');
  517. this.inputs.push(argument);
  518. } else if (value && (value.__class__ || typeof value === 'object') && !stack.has(value)) {
  519. stack.add(value);
  520. const node = new pytorch.Node(metadata, null, null, value, initializers, values, stack);
  521. stack.delete(value);
  522. const visible = name !== '_metadata' || !pytorch.Utility.isMetadataObject(value);
  523. const argument = new pytorch.Argument(name, node, 'object', visible);
  524. this.inputs.push(argument);
  525. } else {
  526. const argument = createAttribute(metadata.attribute(type, name), name, value);
  527. this.inputs.push(argument);
  528. }
  529. }
  530. }
  531. }
  532. if (module && module.__name__) {
  533. this.name = module.__name__;
  534. while (module.__parent__) {
  535. module = module.__parent__;
  536. if (module.__name__) {
  537. this.name = `${module.__name__}.${this.name}`;
  538. }
  539. }
  540. }
  541. }
  542. };
  543. pytorch.Tensor = class {
  544. constructor(name, tensor) {
  545. this.name = name || '';
  546. const layout = tensor.layout ? tensor.layout.__str__() : null;
  547. const storage = tensor.storage();
  548. const size = tensor.size() || [];
  549. if (layout && layout.startsWith('torch.sparse_')) {
  550. this.type = new pytorch.TensorType(storage.dtype.__reduce__(), new pytorch.TensorShape(size), layout.split('.').pop().replace('_', '.'));
  551. this.indices = new pytorch.Tensor('', tensor.indices);
  552. this._values = new pytorch.Tensor('', tensor.values);
  553. } else if (!layout || layout === 'torch.strided') {
  554. this.type = new pytorch.TensorType(storage.dtype.__reduce__(), new pytorch.TensorShape(size));
  555. this._data = storage.data;
  556. this.encoding = '<';
  557. this.indices = null;
  558. this.stride = tensor.stride();
  559. const stride = this.stride;
  560. const offset = tensor.storage_offset();
  561. let length = 0;
  562. if (!Array.isArray(stride)) {
  563. length = storage.size();
  564. } else if (size.every((v) => v !== 0)) {
  565. length = size.reduce((a, v, i) => a + stride[i] * (v - 1), 1);
  566. }
  567. if (offset !== 0 || length !== storage.size()) {
  568. const itemsize = storage.dtype.itemsize();
  569. this._offset = itemsize * offset;
  570. this._length = itemsize * length;
  571. }
  572. } else {
  573. throw new pytorch.Error(`Unsupported tensor layout '${layout}'.`);
  574. }
  575. }
  576. get values() {
  577. const type = this.type.layout;
  578. if (type && type.startsWith('sparse.')) {
  579. return this._values;
  580. }
  581. if (this._data instanceof Uint8Array) {
  582. return this._data;
  583. }
  584. if (this._offset !== undefined) {
  585. const stream = this._data;
  586. const position = stream.position;
  587. stream.seek(this._offset);
  588. const values = stream.peek(this._length);
  589. stream.seek(position);
  590. return values;
  591. }
  592. if (this._data) {
  593. return this._data.peek();
  594. }
  595. return null;
  596. }
  597. decode() {
  598. if (this.encoding !== '<') {
  599. throw new pytorch.Error(`Tensor encoding '${this.encoding}' not implemented.`);
  600. }
  601. const type = this.type;
  602. const data = this.values;
  603. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  604. switch (type.dataType) {
  605. case 'int16': {
  606. const array = new Uint16Array(data.length >> 1);
  607. for (let i = 0; i < array.length; i++) {
  608. array[i] = view.getInt16(i << 1, true);
  609. }
  610. return array;
  611. }
  612. case 'int64': {
  613. const array = new Uint32Array(data.length >> 3);
  614. for (let i = 0; i < array.length; i++) {
  615. array[i] = view.getUint32(i << 3, true);
  616. if (view.getUint32((i << 3) + 4, true) !== 0) {
  617. throw new pytorch.Error('Signed 64-bit value exceeds 32-bit range.');
  618. }
  619. }
  620. return array;
  621. }
  622. default: {
  623. throw new pytorch.Error(`Tensor data type '${type.dataType}' not implemented.`);
  624. }
  625. }
  626. }
  627. };
  628. pytorch.TensorType = class {
  629. constructor(dataType, shape, layout) {
  630. this.dataType = dataType;
  631. this.shape = shape;
  632. this.layout = layout;
  633. }
  634. toString() {
  635. return this.dataType + this.shape.toString();
  636. }
  637. };
  638. pytorch.TensorShape = class {
  639. constructor(dimensions) {
  640. this.dimensions = dimensions || [];
  641. }
  642. toString() {
  643. if (this.dimensions && this.dimensions.length > 0) {
  644. return `[${this.dimensions.map((dimension) => dimension.toString()).join(',')}]`;
  645. }
  646. return '';
  647. }
  648. };
  649. pytorch.Container = class {
  650. static open(context) {
  651. const types = [
  652. pytorch.Container.Zip,
  653. pytorch.Container.Pickle,
  654. pytorch.Container.Tar,
  655. pytorch.Container.data_pkl,
  656. pytorch.Container.torch_utils,
  657. pytorch.Container.Mobile,
  658. pytorch.Container.ModelJson,
  659. pytorch.Container.Index,
  660. pytorch.Container.ExportedProgram,
  661. pytorch.Container.ExecuTorch,
  662. ];
  663. for (const type of types) {
  664. const container = type.open(context);
  665. if (container) {
  666. return container;
  667. }
  668. }
  669. return null;
  670. }
  671. constructor() {
  672. this._events = [];
  673. }
  674. async read() {
  675. }
  676. on(event, callback) {
  677. this._events.push([event, callback]);
  678. }
  679. };
  680. pytorch.Container.Tar = class extends pytorch.Container {
  681. static open(context) {
  682. const entries = context.peek('tar');
  683. if (entries instanceof Map && entries.has('pickle')) {
  684. return new pytorch.Container.Tar(entries);
  685. }
  686. return null;
  687. }
  688. constructor(entries) {
  689. super();
  690. this.type = 'pytorch.tar';
  691. this.entries = entries;
  692. }
  693. async read() {
  694. this.format = 'PyTorch v0.1.1';
  695. const execution = new pytorch.Execution();
  696. for (const event of this._events) {
  697. execution.on(event[0], event[1]);
  698. }
  699. const torch = execution.__import__('torch');
  700. this.module = torch.load(this.entries);
  701. delete this.entries;
  702. }
  703. };
  704. pytorch.Container.Pickle = class extends pytorch.Container {
  705. static open(context) {
  706. const stream = context.stream;
  707. const signature = [0x80, undefined, 0x8a, 0x0a, 0x6c, 0xfc, 0x9c, 0x46, 0xf9, 0x20, 0x6a, 0xa8, 0x50, 0x19];
  708. if (stream && signature.length <= stream.length && stream.peek(signature.length).every((value, index) => signature[index] === undefined || signature[index] === value)) {
  709. return new pytorch.Container.Pickle(stream);
  710. }
  711. return null;
  712. }
  713. constructor(stream) {
  714. super();
  715. this.type = 'pytorch.pickle';
  716. this.stream = stream;
  717. }
  718. async read() {
  719. this.format = 'PyTorch v0.1.10';
  720. const data = this.stream.length < 0x7ffff000 ? this.stream.peek() : this.stream;
  721. delete this.stream;
  722. const execution = new pytorch.Execution();
  723. for (const event of this._events) {
  724. execution.on(event[0], event[1]);
  725. }
  726. const torch = execution.__import__('torch');
  727. this.module = torch.load(data);
  728. }
  729. };
  730. pytorch.Container.data_pkl = class extends pytorch.Container {
  731. static open(context) {
  732. const obj = context.peek('pkl');
  733. if (obj) {
  734. if (obj.__class__ && obj.__class__.__module__ && obj.__class__.__name__) {
  735. const name = `${obj.__class__.__module__}.${obj.__class__.__name__}`;
  736. if (name.startsWith('__torch__.')) {
  737. return new pytorch.Container.data_pkl('', obj);
  738. }
  739. }
  740. if (pytorch.Utility.isTensor(obj)) {
  741. return new pytorch.Container.data_pkl('tensor', obj);
  742. }
  743. if (Array.isArray(obj) && obj.length > 0 && obj.every((tensor) => pytorch.Utility.isTensor(tensor))) {
  744. return new pytorch.Container.data_pkl('tensor', obj);
  745. }
  746. if (obj instanceof Map) {
  747. const entries = Array.from(obj).filter(([, value]) => pytorch.Utility.isTensor(value));
  748. if (entries.length > 0) {
  749. return new pytorch.Container.data_pkl('tensor', obj);
  750. }
  751. } else if (!Array.isArray(obj)) {
  752. const entries = Object.entries(obj).filter(([, value]) => pytorch.Utility.isTensor(value));
  753. if (entries.length > 0) {
  754. return new pytorch.Container.data_pkl('tensor', obj);
  755. }
  756. }
  757. for (const key of ['', 'model', 'net']) {
  758. const module = key === '' ? obj : obj[key];
  759. if (module && module._modules && pytorch.Utility.isInstance(module._modules, 'collections.OrderedDict')) {
  760. return new pytorch.Container.data_pkl('module', module);
  761. }
  762. }
  763. }
  764. return null;
  765. }
  766. constructor(type, data) {
  767. super();
  768. this.type = 'pytorch.data.pkl';
  769. this._type = type;
  770. this._data = data;
  771. }
  772. async read() {
  773. this.format = 'PyTorch Pickle';
  774. switch (this._type) {
  775. case 'module': {
  776. if (this._data) {
  777. this.module = this._data;
  778. delete this._data;
  779. }
  780. return this.module;
  781. }
  782. case 'tensor':
  783. case 'tensor[]':
  784. case 'tensor<>': {
  785. if (this._data) {
  786. this.module = this._data;
  787. delete this._data;
  788. }
  789. return this.module;
  790. }
  791. default: {
  792. throw new pytorch.Error("PyTorch standalone 'data.pkl' not supported.");
  793. }
  794. }
  795. }
  796. };
  797. pytorch.Container.torch_utils = class extends pytorch.Container {
  798. static open(context) {
  799. const stream = context.stream;
  800. if (stream && stream.length > 1) {
  801. const buffer = stream.peek(Math.min(1024, stream.length));
  802. if (buffer[0] === 0x80) {
  803. const content = String.fromCharCode.apply(null, buffer);
  804. if (content.indexOf('torch_utils') !== -1) {
  805. const obj = context.peek('pkl');
  806. if (obj && Object.entries(obj).some(([, value]) => pytorch.Utility.isInstance(value, 'torch.nn.modules.module.Module'))) {
  807. return new pytorch.Container.torch_utils(obj);
  808. }
  809. }
  810. }
  811. }
  812. return null;
  813. }
  814. constructor(obj) {
  815. super();
  816. this.type = 'pytorch.torch_utils';
  817. this.obj = obj;
  818. }
  819. async read() {
  820. this.format = 'PyTorch torch_utils';
  821. this.module = this.obj;
  822. delete this.obj;
  823. }
  824. };
  825. pytorch.Container.Mobile = class extends pytorch.Container {
  826. static open(context) {
  827. const reader = context.peek('flatbuffers.binary');
  828. if (reader && reader.identifier === 'PTMF') {
  829. return new pytorch.Container.Mobile(context);
  830. }
  831. return null;
  832. }
  833. constructor(context) {
  834. super();
  835. this.type = 'pytorch.mobile';
  836. this.context = context;
  837. }
  838. async read(metadata) {
  839. pytorch.mobile = await this.context.require('./pytorch-schema');
  840. pytorch.mobile = pytorch.mobile.torch.jit.mobile;
  841. const execution = new pytorch.jit.Execution(null, metadata);
  842. for (const event in this._events) {
  843. execution.on(event[0], event[1]);
  844. }
  845. const stream = this.context.stream;
  846. const torch = execution.__import__('torch');
  847. this.module = torch.jit.jit_module_from_flatbuffer(stream);
  848. const version = this.module._c._bytecode_version.toString();
  849. this.format = pytorch.Utility.format('PyTorch Mobile', version);
  850. delete this.context;
  851. }
  852. };
  853. pytorch.Container.ExecuTorch = class extends pytorch.Container {
  854. static open(context) {
  855. const reader = context.peek('flatbuffers.binary');
  856. if (reader && reader.identifier === 'ET12') {
  857. return new pytorch.Container.ExecuTorch(context);
  858. }
  859. return null;
  860. }
  861. constructor(context) {
  862. super();
  863. this.type = 'pytorch.executorch';
  864. this.context = context;
  865. }
  866. async read() {
  867. pytorch.executorch = await this.context.require('./pytorch-schema');
  868. pytorch.executorch = pytorch.executorch.executorch_flatbuffer;
  869. const reader = this.context.read('flatbuffers.binary');
  870. /* const program = */ pytorch.executorch.Program.create(reader);
  871. throw new pytorch.Error('Invalid file content. File contains executorch.Program data.');
  872. }
  873. };
  874. pytorch.Container.Zip = class extends pytorch.Container {
  875. static open(context) {
  876. const entries = context.peek('zip');
  877. if (entries instanceof Map && entries.size > 0) {
  878. let prefix = 0;
  879. const paths = Array.from(entries.keys()).map((path) => path.replace(/\\/g, '/').split('/').reverse());
  880. for (let set = new Set(); set && paths.length > 0;) {
  881. set = new Set(paths.map((path) => path.length > 1 ? path.pop() : null));
  882. set = set.size > 1 || set.keys().next().value === null ? null : set;
  883. prefix += set ? set.keys().next().value.length + 1 : 0;
  884. }
  885. const records = new Map(Array.from(entries).map(([name, value]) => [name.substring(prefix), value]));
  886. if (records.has('model.json')) {
  887. return null;
  888. }
  889. if (records.has('data.pkl')) {
  890. return new pytorch.Container.Zip(entries);
  891. }
  892. if (records.has('.data/version')) {
  893. return new pytorch.Container.Package(entries);
  894. }
  895. }
  896. return null;
  897. }
  898. constructor(entries) {
  899. super();
  900. this.type = 'pytorch.zip';
  901. // https://github.com/pytorch/pytorch/blob/master/torch/csrc/jit/docs/serialization.md
  902. this._entries = entries;
  903. }
  904. async read(metadata) {
  905. const execution = new pytorch.jit.Execution(null, metadata);
  906. for (const event of this._events) {
  907. execution.on(event[0], event[1]);
  908. }
  909. const torch = execution.__import__('torch');
  910. const reader = new torch.PyTorchFileReader(this._entries);
  911. let torchscript = reader.has_record('constants.pkl');
  912. const version = reader.version();
  913. if (torchscript) {
  914. const module = torch.jit.load(reader);
  915. execution.trace = true;
  916. if (module.data && module.data.forward) {
  917. this.module = module;
  918. } else {
  919. torchscript = false;
  920. this.module = module.data;
  921. }
  922. } else {
  923. const records = reader.get_all_records().map((key) => [key, reader.get_record(key)]);
  924. const entries = new Map(records);
  925. this.module = torch.load(entries);
  926. }
  927. const name = torchscript ? 'TorchScript' : 'PyTorch';
  928. this.format = pytorch.Utility.format(name, version);
  929. delete this._model;
  930. delete this._entries;
  931. }
  932. };
  933. pytorch.Container.ModelJson = class extends pytorch.Container {
  934. static open(context) {
  935. const identifier = context.identifier;
  936. if (identifier === 'model.json') {
  937. const model = context.peek('json');
  938. if (model && model.mainModule) {
  939. const entries = new Map();
  940. entries.set('model.json', context.stream);
  941. return new pytorch.Container.ModelJson(context, entries, model);
  942. }
  943. }
  944. return null;
  945. }
  946. constructor(context, entries, model) {
  947. super();
  948. this.type = 'pytorch.model.json';
  949. this._context = context;
  950. this._entries = entries;
  951. this._model = model;
  952. }
  953. async read(metadata) {
  954. const keys = [
  955. 'attributes.pkl',
  956. 'version',
  957. ...this._model.tensors.filter((tensor) => tensor && tensor.data && tensor.data.key).map((tensor) => tensor.data.key)
  958. ];
  959. if (this._model.mainModule.torchscriptArena && this._model.mainModule.torchscriptArena.key) {
  960. keys.push(this._model.mainModule.torchscriptArena.key);
  961. }
  962. const values = await Promise.all(keys.map((name) => this._context.fetch(name).then((context) => context.stream).catch(() => null)));
  963. for (let i = 0; i < keys.length; i++) {
  964. if (values[i]) {
  965. this._entries.set(keys[i], values[i]);
  966. }
  967. }
  968. const execution = new pytorch.jit.Execution(null, metadata);
  969. for (const event of this._events) {
  970. execution.on(event[0], event[1]);
  971. }
  972. const torch = execution.__import__('torch');
  973. const reader = new torch.PyTorchFileReader(this._entries);
  974. if (this._model && this._model.producerName) {
  975. this.producer = this._model.producerName + (this._model.producerVersion ? ` v${this._model.producerVersion}` : '');
  976. }
  977. this.format = reader.has_record('attributes.pkl') ? 'TorchScript v1.1' : 'TorchScript v1.0';
  978. const module = torch.jit.load(reader);
  979. execution.trace = true;
  980. if (module.data && module.data.forward) {
  981. this.module = module;
  982. } else {
  983. this.module = module.data;
  984. }
  985. delete this._context;
  986. delete this._model;
  987. delete this._entries;
  988. }
  989. };
  990. pytorch.Container.Index = class extends pytorch.Container {
  991. static open(context) {
  992. const obj = context.peek('json');
  993. if (obj && obj.weight_map) {
  994. const entries = Object.entries(obj.weight_map);
  995. if (entries.length > 0 && entries.every(([, value]) => typeof value === 'string' && value.endsWith('.bin'))) {
  996. return new pytorch.Container.Index(context, entries);
  997. }
  998. }
  999. return null;
  1000. }
  1001. constructor(context, entries) {
  1002. super();
  1003. this.type = 'pytorch.index';
  1004. this.context = context;
  1005. this._entries = entries;
  1006. }
  1007. async read(metadata) {
  1008. this.format = 'PyTorch';
  1009. const weight_map = new Map(this._entries);
  1010. const keys = new Set(weight_map.keys());
  1011. const files = Array.from(new Set(weight_map.values()));
  1012. const contexts = await Promise.all(files.map((name) => this.context.fetch(name)));
  1013. const execution = new pytorch.jit.Execution(null, metadata);
  1014. for (const event of this._events) {
  1015. execution.on(event[0], event[1]);
  1016. }
  1017. const torch = execution.__import__('torch');
  1018. const archives = contexts.map((context) => {
  1019. return context.peek('zip');
  1020. });
  1021. const formats = new Set(archives.map((entries) => {
  1022. const reader = new torch.PyTorchFileReader(entries);
  1023. const version = reader.version();
  1024. return pytorch.Utility.format('PyTorch', version);
  1025. }));
  1026. if (formats.size === 1) {
  1027. this.format = formats.values().next().value;
  1028. }
  1029. const shards = archives.map((entries) => {
  1030. return torch.load(entries);
  1031. });
  1032. const entries = new Map();
  1033. for (const shard of shards) {
  1034. for (const [key, value] of Array.from(shard)) {
  1035. if (keys.has(key)) {
  1036. entries.set(key, value);
  1037. }
  1038. }
  1039. }
  1040. this.module = entries;
  1041. delete this.context;
  1042. delete this._entries;
  1043. }
  1044. };
  1045. pytorch.Container.ExportedProgram = class extends pytorch.Container {
  1046. static open(context) {
  1047. const program = context.peek('json');
  1048. if (program && program.schema_version && program.graph_module) {
  1049. return new pytorch.Container.ExportedProgram(context, program);
  1050. }
  1051. return null;
  1052. }
  1053. constructor(context, serialized_exported_program) {
  1054. super();
  1055. this.type = 'pytorch.export';
  1056. this.context = context;
  1057. this.serialized_exported_program = serialized_exported_program;
  1058. }
  1059. async read() {
  1060. this.format = 'PyTorch Export';
  1061. const serialized_state_dict = await this._fetch('serialized_state_dict.pt') || await this._fetch('serialized_state_dict.json');
  1062. const serialized_constants = await this._fetch('serialized_constants.pt') || await this._fetch('serialized_constants.json');
  1063. const f = new Map();
  1064. f.set('serialized_exported_program.json', this.serialized_exported_program);
  1065. f.set('serialized_state_dict.pt', serialized_state_dict);
  1066. f.set('serialized_constants.pt', serialized_constants);
  1067. const execution = new pytorch.Execution();
  1068. for (const event of this._events) {
  1069. execution.on(event[0], event[1]);
  1070. }
  1071. const torch = execution.__import__('torch');
  1072. if (this.serialized_exported_program.graph_module.graph.constants) {
  1073. const zip = await import('./zip.js');
  1074. const constants = this.serialized_exported_program.graph_module.graph.constants;
  1075. for (const key of Object.keys(constants)) {
  1076. const value = constants[key];
  1077. const str = atob(value);
  1078. const buffer = new Uint8Array(str.length);
  1079. for (let i = 0; i < str.length; i++) {
  1080. buffer[i] = str.charCodeAt(i);
  1081. }
  1082. const archive = zip.Archive.open(buffer);
  1083. constants[key] = archive.entries;
  1084. }
  1085. }
  1086. delete this.serialized_exported_program;
  1087. delete this.context;
  1088. /* const exported_program = */ torch._export.load(f);
  1089. throw new pytorch.Error(`'torch.export' not supported.`);
  1090. }
  1091. async _fetch(name) {
  1092. try {
  1093. const context = await this._context.fetch(name);
  1094. if (context) {
  1095. return context.peek('zip');
  1096. }
  1097. } catch {
  1098. // continue regardless of error
  1099. }
  1100. return null;
  1101. }
  1102. };
  1103. pytorch.Execution = class extends python.Execution {
  1104. constructor(sources) {
  1105. super(sources);
  1106. const execution = this;
  1107. const torch = this.register('torch');
  1108. const pickle = this.register('pickle');
  1109. this.register('torch.jit._script');
  1110. this.register('torch.jit._trace');
  1111. this.registerType('torch.package.PackageImporter', class {
  1112. constructor(reader) {
  1113. this.zip_reader = reader;
  1114. }
  1115. load_pickle(module, resource) {
  1116. const name = `${module.replace(/\./, '/')}/${resource}`;
  1117. const stream = this.zip_reader.get_record(name);
  1118. const loaded_reduces = new Map();
  1119. this.storage_context = new torch._C.DeserializationStorageContext();
  1120. const unpickler = new pickle.Unpickler(stream);
  1121. unpickler.persistent_load = (saved_id) => {
  1122. switch (saved_id[0]) {
  1123. case 'storage': {
  1124. const [, storage_type, key, , size] = saved_id;
  1125. if (!this.storage_context.has_storage(key)) {
  1126. const storage = new storage_type(size);
  1127. const stream = this.zip_reader.get_record(`.data/${key}.storage`);
  1128. const buffer = stream.peek();
  1129. storage._set_cdata(buffer);
  1130. this.storage_context.add_storage(key, storage);
  1131. }
  1132. return this.storage_context.get_storage(key);
  1133. }
  1134. case 'reduce_package': {
  1135. if (saved_id.length === 2) {
  1136. const [, func, args] = saved_id;
  1137. return execution.invoke(func, args);
  1138. }
  1139. const [, reduce_id, func, args] = saved_id;
  1140. if (!loaded_reduces.has(reduce_id)) {
  1141. const value = execution.invoke(func, [this].concat(args));
  1142. loaded_reduces.set(reduce_id, value);
  1143. }
  1144. return loaded_reduces.get(reduce_id);
  1145. }
  1146. default: {
  1147. throw new pytorch.Error(`Unknown package typename '${saved_id[0]}'.`);
  1148. }
  1149. }
  1150. };
  1151. const obj = unpickler.load();
  1152. this.storage_context = null;
  1153. return obj;
  1154. }
  1155. import_module(name) {
  1156. return execution.import(name);
  1157. }
  1158. });
  1159. this.registerFunction('torch.jit.load', (file, map_location, extra_files) => {
  1160. const cu = new torch.jit.CompilationUnit();
  1161. cu.execution = execution;
  1162. const cpp_module = torch._C.import_ir_module(cu, file, map_location, extra_files);
  1163. return new torch.jit._script.RecursiveScriptModule(cpp_module);
  1164. });
  1165. this.registerFunction('torch._C.import_ir_module', function(cu, reader, ...args) {
  1166. switch (arguments.length) {
  1167. case 4: {
  1168. const [device, extra_files] = args;
  1169. const deserializer = new pytorch.jit.ScriptModuleDeserializer(cu, reader);
  1170. return deserializer.deserialize(device, extra_files);
  1171. }
  1172. case 5: {
  1173. const [storage_context, device, ts_id] = args;
  1174. const deserializer = new pytorch.jit.ScriptModuleDeserializer(cu, reader, `.data/ts_code/${ts_id}/`, '.data/', storage_context);
  1175. return deserializer.deserialize(device, null);
  1176. }
  1177. default: {
  1178. throw new pytorch.Error("Invalid 'torch._C.import_ir_module' signature.");
  1179. }
  1180. }
  1181. });
  1182. this.registerFunction('torch._C._import_ir_module_from_package', (cu, reader, storage_context, map_location, ts_id) => {
  1183. return torch._C.import_ir_module(cu, reader, storage_context, null, ts_id);
  1184. });
  1185. this.registerFunction('torch._C._jit_pass_inline', (graph) => {
  1186. const tryToGraphFunction = (node) => {
  1187. if (node.kind() === 'prim::CallFunction') {
  1188. //
  1189. }
  1190. if (node.kind() === 'prim::CallMethod') {
  1191. const name = null; // node.s(attr::name);
  1192. const class_type = node.input(0).type();
  1193. if (class_type) {
  1194. const fn = class_type.getMethod(name);
  1195. return tryToGraphFunction(fn);
  1196. }
  1197. }
  1198. return null;
  1199. };
  1200. const inlineCallTo = (/* to_replace, callee, use_graph */) => {
  1201. };
  1202. const inlineCalls = (block) => {
  1203. for (const cur of block.nodes()) {
  1204. switch (cur.kind()) {
  1205. case 'prim::CallFunction': {
  1206. throw new pytorch.Error();
  1207. }
  1208. case 'prim::CallMethod': {
  1209. const graphFunction = tryToGraphFunction(cur);
  1210. inlineCallTo(cur, graphFunction, true);
  1211. break;
  1212. }
  1213. default: {
  1214. for (const b of block.nodes()) {
  1215. inlineCalls(b);
  1216. }
  1217. }
  1218. }
  1219. }
  1220. };
  1221. inlineCalls(graph.blocks());
  1222. });
  1223. this.registerFunction('torch.jit._script.unpackage_script_module', (importer, script_module_id) => {
  1224. const cu = new torch.jit.CompilationUnit();
  1225. cu.execution = execution;
  1226. const cpp_module = torch._C._import_ir_module_from_package(cu, importer.zip_reader, importer.storage_context, importer.last_map_location, script_module_id);
  1227. return new torch.jit._script.RecursiveScriptModule(cpp_module);
  1228. });
  1229. this.registerFunction('torch.jit.jit_module_from_flatbuffer', (f) => {
  1230. const cu = new torch.jit.CompilationUnit();
  1231. cu.execution = execution;
  1232. const stream = f;
  1233. const reader = flatbuffers.BinaryReader.open(stream);
  1234. const module = pytorch.mobile.serialization.Module.create(reader);
  1235. const loader = new pytorch.jit.FlatBuffersLoader(cu);
  1236. const cpp_module = loader.parseModule(module);
  1237. // parse_and_initialize_jit_module
  1238. // const mobilem = parse_and_initialize_mobile_module_for_jit(data, jit_files, jit_constants);
  1239. // const m = jitModuleFromSourceAndConstants(mobilem._ivalue(), jit_files, jit_constants, mobilem.bytecode_version());
  1240. // throw new pytorch.Error('torch.jit.mobile.serialization.Module not supported.');
  1241. return torch.jit._script.wrap_cpp_module(cpp_module);
  1242. });
  1243. this.registerFunction('torch.jit._script.wrap_cpp_module', (cpp_module) => {
  1244. const init_fn = (script_module) => {
  1245. for (const [name, module] of new torch.ModuleDict(script_module._c).items()) {
  1246. script_module.__setattr__(name, torch.jit._script.wrap_cpp_module(module));
  1247. }
  1248. };
  1249. return torch.jit._script.RecursiveScriptModule._construct(cpp_module, init_fn);
  1250. });
  1251. this.registerType('torch._C.DeserializationStorageContext', class extends Map {
  1252. has_storage(name) {
  1253. return this.has(name);
  1254. }
  1255. get_storage(name) {
  1256. return this.get(name);
  1257. }
  1258. add_storage(name, storage) {
  1259. return this.set(name, storage);
  1260. }
  1261. });
  1262. this.registerType('torch.Type', class {});
  1263. this.registerType('torch.ClassType', class extends torch.Type {
  1264. constructor(qualified_name, cu, is_module) {
  1265. super();
  1266. this._qualified_name = qualified_name;
  1267. this._is_module = is_module;
  1268. }
  1269. qualified_name() {
  1270. return this._qualified_name;
  1271. }
  1272. name() {
  1273. return this._qualified_name.split('.').pop();
  1274. }
  1275. is_module() {
  1276. return this._is_module;
  1277. }
  1278. addMethod(/* name, fn */) {
  1279. }
  1280. addAttribute(/* name */) {
  1281. }
  1282. hasAttribute(/* name */) {
  1283. }
  1284. hasConstant(/* name */) {
  1285. }
  1286. methods() {
  1287. }
  1288. });
  1289. this.registerType('torch.TupleType', class extends torch.Type {});
  1290. this.registerType('torch.ScriptFunction', class {
  1291. constructor(name, graph /*, function_creator */) {
  1292. this._name = name;
  1293. this._graph = graph;
  1294. }
  1295. });
  1296. this.registerType('torch.ScriptMethod', class {
  1297. constructor(owner, value) {
  1298. this._owner = owner;
  1299. this._function = value;
  1300. }
  1301. get name() {
  1302. return this._function.name();
  1303. }
  1304. get owner() {
  1305. return this._owner;
  1306. }
  1307. __call__(/* args, kwargs */) {
  1308. throw new pytorch.Error();
  1309. }
  1310. get graph() {
  1311. return this._function.graph();
  1312. }
  1313. get schema() {
  1314. // return this.function().getSchema();
  1315. throw new pytorch.Error();
  1316. }
  1317. get code() {
  1318. throw new pytorch.Error();
  1319. }
  1320. get code_with_constants() {
  1321. throw new pytorch.Error();
  1322. }
  1323. });
  1324. this.registerType('torch.ScriptObject', class {
  1325. constructor(type) {
  1326. this._type = type;
  1327. }
  1328. static create(type) {
  1329. if (type.is_module()) {
  1330. return new torch.ScriptModule(type);
  1331. }
  1332. return new torch.ScriptObject(type);
  1333. }
  1334. _type() {
  1335. return this._type;
  1336. }
  1337. _get_method(name) {
  1338. for (const method of this._type.methods()) {
  1339. if (name === method.name) {
  1340. return method;
  1341. }
  1342. }
  1343. return null;
  1344. }
  1345. _has_method(/* name */) {
  1346. throw new pytorch.Error();
  1347. }
  1348. __setattr__(name, value) {
  1349. // if (this._type.hasContant(name))
  1350. this[name] = value;
  1351. }
  1352. __getattr__(name) {
  1353. return this[name];
  1354. }
  1355. hasattr(name) {
  1356. return this._type.hasAttribute(name) || this._type.hasConstant(name);
  1357. }
  1358. _properties() {
  1359. throw new pytorch.Error();
  1360. }
  1361. });
  1362. this.registerType('torch.ScriptModule', class extends torch.ScriptObject {
  1363. get qualified_name() {
  1364. return this._type.qualified_name();
  1365. }
  1366. get code_with_constants() {
  1367. const const_map = {};
  1368. const_map.const_mapping = new Map(Object.entries(execution.builtins.CONSTANTS));
  1369. return [null, const_map];
  1370. }
  1371. get graph() {
  1372. if (!this._graph) {
  1373. if (!this.data) {
  1374. return null;
  1375. }
  1376. if (!this.data.forward) {
  1377. throw new pytorch.Error("Module 'forward' not implemented.");
  1378. }
  1379. const args = [this.data]; // self
  1380. if (this.data.forward.__code__ && this.data.forward.__code__.args) {
  1381. for (const arg of this.data.forward.__code__.args) {
  1382. const defaultValue = (type, name) => {
  1383. if (type.type === 'type' && type.name.type) {
  1384. switch (type.name.value) {
  1385. case 'Tensor': {
  1386. const tensor = execution.invoke('torch.Tensor', []);
  1387. tensor.__variable__ = name;
  1388. tensor.__origin__ = 'graph-input';
  1389. const value = execution.variable(tensor, execution.graph.param_node());
  1390. if (value && name) {
  1391. value.setDebugName(name);
  1392. }
  1393. return tensor;
  1394. }
  1395. case 'Tuple': {
  1396. return type.arguments.map((type, index) => defaultValue(type, `${name}[${index}]`));
  1397. }
  1398. case 'List': {
  1399. return type.arguments.map((type, index) => defaultValue(type, `${name}[${index}]`));
  1400. }
  1401. case 'Dict': {
  1402. if (type.arguments[1].name.value === 'Tensor') {
  1403. const Dict = class extends Map {
  1404. get(key) {
  1405. if (!super.has(key)) {
  1406. super.set(key, defaultValue(type.arguments[1], `${name}:${key}`));
  1407. }
  1408. return super.get(key);
  1409. }
  1410. };
  1411. return new Dict();
  1412. }
  1413. return new Map();
  1414. }
  1415. case 'int': {
  1416. return 0;
  1417. }
  1418. case 'float': {
  1419. return 0.0;
  1420. }
  1421. case 'bool': {
  1422. return false;
  1423. }
  1424. case 'Optional': {
  1425. return undefined;
  1426. }
  1427. case 'str':
  1428. return '';
  1429. default: {
  1430. break;
  1431. }
  1432. }
  1433. }
  1434. throw new pytorch.Error(`Unsupported parameter type '${JSON.stringify(type)}'.`);
  1435. };
  1436. if (arg.name !== 'self') {
  1437. const type = arg.parameterType;
  1438. const value = defaultValue(type, arg.name);
  1439. if (pytorch.Utility.isTensor(value)) {
  1440. value.__variable__ = arg.name;
  1441. value.__origin__ = 'graph-input';
  1442. }
  1443. args.push(value);
  1444. }
  1445. }
  1446. }
  1447. const result = this.data.forward.__call__(args);
  1448. if (Array.isArray(result)) {
  1449. for (const output of result) {
  1450. if (pytorch.Utility.isTensor(output)) {
  1451. const value = execution.variable(output);
  1452. execution.graph.return_node().addInput(value);
  1453. }
  1454. }
  1455. } else if (pytorch.Utility.isTensor(result)) {
  1456. const value = execution.variable(result);
  1457. execution.graph.return_node().addInput(value);
  1458. } else if (Object(result) === result) {
  1459. for (const key of Object.keys(result)) {
  1460. const item = result[key];
  1461. if (Array.isArray(item)) {
  1462. for (const output of item) {
  1463. if (pytorch.Utility.isTensor(output)) {
  1464. const value = execution.variable(output);
  1465. execution.graph.return_node().addInput(value);
  1466. }
  1467. }
  1468. } else if (pytorch.Utility.isTensor(item)) {
  1469. const value = execution.variable(item);
  1470. execution.graph.return_node().addInput(value);
  1471. }
  1472. }
  1473. }
  1474. this._graph = execution.graph;
  1475. }
  1476. return this._graph;
  1477. }
  1478. });
  1479. this.registerType('torch.ModuleDict', class {
  1480. constructor(module) {
  1481. this._items = Object.entries(module).filter(([, value]) => value instanceof torch.ScriptModule);
  1482. }
  1483. items() {
  1484. return this._items;
  1485. }
  1486. });
  1487. this.registerType('torch.jit.CompilationUnit', class {
  1488. constructor() {
  1489. this._functions = new Map();
  1490. this._classes = new Map();
  1491. }
  1492. register_function(fn) {
  1493. this._functions.set(fn.name, fn);
  1494. }
  1495. define(prefix, properties, propResolvers, definitions /*, defResolvers, self, shouldMangle, operator_set_version */) {
  1496. for (const def of definitions) {
  1497. const name = def.name;
  1498. const qualified_name = prefix ? `${prefix}.${name}` : name;
  1499. const graph = new torch.Graph();
  1500. const fn = new torch.ScriptFunction(qualified_name, graph, null);
  1501. this.register_function(fn);
  1502. }
  1503. }
  1504. get_class(name) {
  1505. return this._classes.get(name);
  1506. }
  1507. register_type(name, cls) {
  1508. this._classes.set(name, cls);
  1509. }
  1510. });
  1511. this.registerType('torch.jit._script.ScriptModule', class extends torch.nn.modules.module.Module {});
  1512. this.registerType('torch.jit._trace.TracedModule', class extends torch.jit._script.ScriptModule {});
  1513. this.registerType('torch.jit._trace.TopLevelTracedModule', class extends torch.jit._trace.TracedModule {});
  1514. this.registerType('torch.jit._script.RecursiveScriptModule', class extends torch.jit._script.ScriptModule {
  1515. constructor(cpp_module) {
  1516. super();
  1517. this._initializing = true;
  1518. this._c = cpp_module;
  1519. }
  1520. static _construct(cpp_module, init_fn) {
  1521. const script_module = new torch.jit._script.RecursiveScriptModule(cpp_module);
  1522. init_fn(script_module);
  1523. torch.jit._script.RecursiveScriptModule._finalize_scriptmodule(script_module);
  1524. return script_module;
  1525. }
  1526. static _finalize_scriptmodule() {
  1527. this._initializing = false;
  1528. }
  1529. get data() {
  1530. return this._c.data;
  1531. }
  1532. get graph() {
  1533. // return this._c._get_method("forward").graph;
  1534. return this._c.graph;
  1535. }
  1536. get code_with_constants() {
  1537. // return this.forward.code_with_constants;
  1538. return this._c.code_with_constants;
  1539. }
  1540. __setattr__(name, value) {
  1541. if (this._initializing) {
  1542. super.__setattr__(name, value);
  1543. } else if (this.modules.has(name)) {
  1544. this.modules.set(name, value);
  1545. } else if (this._c.hasattr(name)) {
  1546. this._c.setattr(name, value);
  1547. } else {
  1548. //
  1549. }
  1550. }
  1551. __getattr__(name) {
  1552. if (this._initializing) {
  1553. return super.__getattr__(name);
  1554. }
  1555. if (this.modules.has(name)) {
  1556. return this.modules.get(name);
  1557. }
  1558. if (this._c.hasattr(name)) {
  1559. return this._c.getattr(name);
  1560. }
  1561. if (this._c._has_method(name)) {
  1562. //
  1563. }
  1564. return super.__getattr__(name);
  1565. }
  1566. });
  1567. torch.jit.ScriptModule = torch.jit._script.ScriptModule;
  1568. torch.jit.RecursiveScriptModule = torch.jit._script.RecursiveScriptModule;
  1569. torch.jit.TopLevelTracedModule = torch.jit._trace.TopLevelTracedModule;
  1570. torch.CompilationUnit = torch.jit.CompilationUnit;
  1571. torch._C.CompilationUnit = torch.jit.CompilationUnit;
  1572. torch._C.ScriptModule = torch.ScriptModule;
  1573. torch._C.ClassType = torch.ClassType;
  1574. }
  1575. };
  1576. pytorch.jit = {};
  1577. pytorch.jit.Execution = class extends pytorch.Execution {
  1578. constructor(sources, metadata) {
  1579. super(sources);
  1580. this._metadata = metadata;
  1581. const execution = this;
  1582. this.registerType('__torch__.torch.classes._nnapi.Compilation', class {
  1583. constructor() {
  1584. this.__hide__ = true;
  1585. }
  1586. __init__() {
  1587. }
  1588. init(serialized_model_tensor, parameter_buffers) {
  1589. this.serialized_model_tensor = serialized_model_tensor;
  1590. this.parameter_buffers = parameter_buffers;
  1591. const buffers = parameter_buffers.map((buffer) => buffer.__source__.storage());
  1592. const serialized_model = serialized_model_tensor.storage().data;
  1593. this.serialized_model = new pytorch.nnapi.SerializedModel(serialized_model, buffers);
  1594. }
  1595. run(inputs, outputs) {
  1596. execution.variable(this.serialized_model_tensor);
  1597. this.serialized_model_tensor.__count__ = (this.serialized_model_tensor.__count__ || 0) + 1;
  1598. const type = new pytorch.nnapi.Graph(this.serialized_model);
  1599. const node = execution._graph.create(type);
  1600. for (const tensor of inputs) {
  1601. const value = execution.variable(tensor);
  1602. node.addInput(value);
  1603. }
  1604. for (const tensor of outputs) {
  1605. execution.variable(tensor, node);
  1606. }
  1607. }
  1608. });
  1609. this.registerType('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', class {
  1610. __setstate__(state) {
  1611. if (state[0] !== '2') {
  1612. throw new pytorch.Error(`Unsupported pack version '${state[0]}'.`);
  1613. }
  1614. const [/* pack_version */, tensors, opt_tensors] = state;
  1615. const packed_config_tensor = new pytorch.Tensor('', tensors[0], true);
  1616. const packed_config = packed_config_tensor.decode();
  1617. /* eslint-disable prefer-destructuring */
  1618. this.weight = tensors[1];
  1619. this.bias = opt_tensors[0];
  1620. this.stride = [packed_config[1], packed_config[2]];
  1621. this.padding = [packed_config[3], packed_config[4]];
  1622. this.dilation = [packed_config[5], packed_config[6]];
  1623. this.output_padding = [packed_config[7], packed_config[8]];
  1624. this.groups = packed_config[9];
  1625. /* eslint-enable prefer-destructuring */
  1626. }
  1627. });
  1628. this.registerType('__torch__.torch.classes.quantized.Conv3dPackedParamsBase', class {
  1629. __setstate__(state) {
  1630. if (state[0] !== '2') {
  1631. throw new pytorch.Error(`Unsupported pack version '${state[0]}'.`);
  1632. }
  1633. const [/* pack_version */, tensors, opt_tensors] = state;
  1634. const packed_config_tensor = new pytorch.Tensor('', tensors[0], true);
  1635. const packed_config = packed_config_tensor.decode();
  1636. /* eslint-disable prefer-destructuring */
  1637. this.weight = tensors[1];
  1638. this.bias = opt_tensors[0];
  1639. this.stride = [packed_config[1], packed_config[2]];
  1640. this.padding = [packed_config[3], packed_config[4]];
  1641. this.dilation = [packed_config[5], packed_config[6]];
  1642. this.output_padding = [packed_config[7], packed_config[8]];
  1643. this.groups = packed_config[9];
  1644. /* eslint-enable prefer-destructuring */
  1645. }
  1646. });
  1647. this.registerType('__torch__.torch.classes.quantized.LinearPackedParamsBase', class {
  1648. __setstate__(state) {
  1649. [this.weight, this.bias] = state;
  1650. }
  1651. });
  1652. this.registerType('__torch__.torch.classes.rnn.CellParamsBase', class {
  1653. __setstate__(state) {
  1654. [this.type, this.tensors, this.doubles, this.longs, this.packed_params] = state;
  1655. }
  1656. });
  1657. this.registerType('__torch__.torch.classes.xnnpack.Conv2dOpContext', class {
  1658. __setstate__(state) {
  1659. [this.weight, this.bias, this.stride, this.padding, this.dilation, this.groups, this.output_min, this.output_max] = state;
  1660. }
  1661. });
  1662. this.registerType('__torch__.torch.classes.xnnpack.LinearOpContext', class {
  1663. __setstate__(state) {
  1664. [this.weight, this.bias, this.output_min, this.output_max] = state;
  1665. }
  1666. });
  1667. this.registerType('__torch__.torch.classes.xnnpack.TransposeConv2dOpContext', class {
  1668. __setstate__(state) {
  1669. [this.weight, this.bias, this.stride, this.padding, this.output_padding, this.dilation, this.groups, this.output_min, this.output_max] = state;
  1670. }
  1671. });
  1672. this.registerType('torch.Graph', class {
  1673. constructor() {
  1674. this._unique = 1;
  1675. this._nodes = [];
  1676. this._block = execution.invoke('torch.Block', [this]);
  1677. }
  1678. create(kind) {
  1679. return execution.invoke('torch.Node', [this, kind]);
  1680. }
  1681. inputs() {
  1682. return this._block.inputs();
  1683. }
  1684. outputs() {
  1685. return this._block.outputs();
  1686. }
  1687. nodes() {
  1688. return this._nodes;
  1689. // return this._block.nodes();
  1690. }
  1691. param_node() {
  1692. return this._block.param_node();
  1693. }
  1694. return_node() {
  1695. return this._block.return_node();
  1696. }
  1697. });
  1698. this.registerType('torch.Block', class {
  1699. constructor(graph) {
  1700. this._unique = 1;
  1701. this._graph = graph;
  1702. this._input = graph.create('prim::Param');
  1703. this._output = graph.create('prim::Return');
  1704. }
  1705. param_node() {
  1706. return this._input;
  1707. }
  1708. return_node() {
  1709. return this._output;
  1710. }
  1711. inputs() {
  1712. return this._input.outputs();
  1713. }
  1714. outputs() {
  1715. return this._output.inputs();
  1716. }
  1717. addInput(name) {
  1718. const value = this._input.addOutput();
  1719. value.setDebugName(name || '');
  1720. return value;
  1721. }
  1722. registerOutput(value) {
  1723. this._output.addInput(value);
  1724. return this.outputs().length - 1;
  1725. }
  1726. });
  1727. this.registerType('torch.Node', class {
  1728. constructor(graph, kind) {
  1729. this._graph = graph;
  1730. this._graph._nodes.push(this);
  1731. this._kind = kind;
  1732. this._inputs = [];
  1733. this._outputs = [];
  1734. this._blocks = [];
  1735. }
  1736. kind() {
  1737. return this._kind;
  1738. }
  1739. inputs() {
  1740. return this._inputs;
  1741. }
  1742. outputs() {
  1743. return this._outputs;
  1744. }
  1745. blocks() {
  1746. return this._blocks;
  1747. }
  1748. addInput(value) {
  1749. const use = execution.invoke('torch.Use', [this]);
  1750. value.uses().push(use);
  1751. this._inputs.push(value);
  1752. return value;
  1753. }
  1754. addOutput() {
  1755. const value = execution.invoke('torch.Value', [this]);
  1756. this._outputs.push(value);
  1757. return value;
  1758. }
  1759. addBlock() {
  1760. const block = execution.invoke('torch.Block', [this._graph, this]);
  1761. this._blocks.push(block);
  1762. return block;
  1763. }
  1764. });
  1765. this.registerType('torch.Value', class {
  1766. constructor(node) {
  1767. this._unique = node && node._unique ? node._unique++ : node._graph._unique++;
  1768. this._node = node && node._unique ? null : node;
  1769. this._uses = [];
  1770. }
  1771. unique() {
  1772. return this._unique;
  1773. }
  1774. node() {
  1775. return this._node;
  1776. }
  1777. uses() {
  1778. return this._uses;
  1779. }
  1780. setDebugName(name) {
  1781. this._unique_name = name;
  1782. }
  1783. debugName() {
  1784. return this._unique_name;
  1785. }
  1786. });
  1787. this.registerType('torch.Use', class {
  1788. constructor(node) {
  1789. this._node = node;
  1790. }
  1791. get user() {
  1792. return this._node;
  1793. }
  1794. });
  1795. this._metadata = metadata;
  1796. this._types = new Map();
  1797. for (const [, value] of this._metadata._types) {
  1798. const name = value.name;
  1799. if (name.indexOf('::') !== -1) {
  1800. const index = name.lastIndexOf('.');
  1801. const key = index === -1 ? name : name.substring(0, index);
  1802. if (!this._types.has(key)) {
  1803. this._types.set(key, []);
  1804. }
  1805. this._types.get(key).push(value);
  1806. }
  1807. }
  1808. this._graph = this.invoke('torch.Graph', []);
  1809. this._values = new Map();
  1810. }
  1811. debug(file) {
  1812. const buffer = this.source(`${file}.debug_pkl`);
  1813. if (buffer) {
  1814. return null;
  1815. // const unpickler = this.invoke('pickle.Unpickler', [ buffer ]);
  1816. // return unpickler.load();
  1817. }
  1818. return null;
  1819. }
  1820. get graph() {
  1821. return this._graph;
  1822. }
  1823. variable(tensor, node) {
  1824. if (this._values.has(tensor)) {
  1825. return this._values.get(tensor);
  1826. }
  1827. const value = node ? node.addOutput() : this.invoke('torch.Value', [node ? node : this._graph]);
  1828. value.value = tensor;
  1829. if (typeof tensor !== 'string' && typeof tensor !== 'number') {
  1830. this._values.set(tensor, value);
  1831. }
  1832. if (pytorch.Utility.isTensor(tensor)) {
  1833. tensor.__variable__ = value.unique().toString();
  1834. }
  1835. return value;
  1836. }
  1837. resolve(name) {
  1838. const index = name.lastIndexOf('.');
  1839. const memberName = index === -1 ? name : name.substring(index + 1, name.length);
  1840. const moduleName = index === -1 ? '' : name.substring(0, index);
  1841. const module = this.import(moduleName);
  1842. let type = module ? module[memberName] : null;
  1843. if (!type) {
  1844. if (name.startsWith('__torch__.')) {
  1845. throw new pytorch.Error(`Unknown type name '${name}'.`);
  1846. }
  1847. type = super.resolve(name);
  1848. }
  1849. return type;
  1850. }
  1851. target(expression, context) {
  1852. if (expression.type === 'id') {
  1853. switch (expression.value) {
  1854. case 'torch':
  1855. case 'ops':
  1856. case 'CONSTANTS':
  1857. case 'uninitialized':
  1858. return this.builtins[expression.value];
  1859. default:
  1860. break;
  1861. }
  1862. }
  1863. let current = expression;
  1864. let path = [];
  1865. for (;;) {
  1866. if (current.type === '.' && current.member && current.member.type === 'id') {
  1867. path.push(current.member.value);
  1868. current = current.target;
  1869. } else if (current.type === 'id' && current.value !== 'self' && current.value !== 'CONSTANTS') {
  1870. path.push(current.value);
  1871. break;
  1872. } else {
  1873. path = null;
  1874. break;
  1875. }
  1876. }
  1877. if (path) {
  1878. let target = null;
  1879. for (let i = path.length - 1; i >= 0; i--) {
  1880. target = target ? target[path[i]] : context.get(path[i]);
  1881. if (!target) {
  1882. break;
  1883. }
  1884. }
  1885. if (!target) {
  1886. path.reverse();
  1887. const name = path.join('.');
  1888. const file = `${path.join('/')}.py`;
  1889. if (this.source(file)) {
  1890. return this.import(name);
  1891. }
  1892. return this.resolve(name);
  1893. }
  1894. }
  1895. return super.target(expression, context);
  1896. }
  1897. call(target, name, args, context) {
  1898. if (this.trace) {
  1899. const overload = this._overload(target, name, args, context);
  1900. if (overload) {
  1901. const [schema, args, evalArgs] = overload;
  1902. const copyArgs = Array.prototype.slice.call(args);
  1903. const copyEvalArgs = Array.prototype.slice.call(evalArgs);
  1904. const node = this._graph.create(schema.name);
  1905. node.schema = schema;
  1906. const referencedParameters = [];
  1907. const parameters = Array.prototype.slice.call(schema.inputs || []).concat(Array.prototype.slice.call(schema.attributes || []));
  1908. while (copyEvalArgs.length > 0) {
  1909. if (parameters.length <= 0) {
  1910. if (schema.name.startsWith('_caffe2::')) {
  1911. break;
  1912. }
  1913. throw new pytorch.Error();
  1914. }
  1915. if (copyArgs.every((arg) => arg.type === '=' && arg.target && arg.target.type === 'id') &&
  1916. parameters.every((parameter) => parameter.type !== 'Tensor' && parameter.type !== 'Tensor[]')) {
  1917. const map = new Map(parameters.map((parameter) => [parameter.name, parameter]));
  1918. while (copyArgs.length > 0) {
  1919. const argument = copyArgs.shift();
  1920. const arg = copyEvalArgs.shift();
  1921. const parameter = map.get(argument.target.value);
  1922. if (!parameter) {
  1923. throw new pytorch.Error();
  1924. }
  1925. if (!pytorch.Utility.isType(arg, parameter.type)) {
  1926. if (parameter.optional) {
  1927. continue;
  1928. }
  1929. throw new pytorch.Error();
  1930. }
  1931. const value = this.variable(arg);
  1932. value.value = arg;
  1933. node.addInput(value);
  1934. }
  1935. continue;
  1936. }
  1937. const parameter = parameters.shift();
  1938. const [argument] = copyEvalArgs;
  1939. if (parameter.type === 'Tensor' || (parameter.type === 'Scalar' && pytorch.Utility.isTensor(argument))) {
  1940. if (Array.isArray(argument) || (!pytorch.Utility.isTensor(argument) && argument !== null && argument !== undefined)) {
  1941. if (parameter.optional) {
  1942. continue;
  1943. }
  1944. throw new pytorch.Error();
  1945. } else {
  1946. copyArgs.shift();
  1947. copyEvalArgs.shift();
  1948. const tensor = (argument === null || argument === undefined) ? {} : argument;
  1949. const value = this.variable(tensor);
  1950. referencedParameters.push(tensor);
  1951. node.addInput(value);
  1952. }
  1953. } else if (parameter.type === 'Tensor[]') {
  1954. const [argument] = copyEvalArgs;
  1955. if (!Array.isArray(argument) || !argument.every((item) => pytorch.Utility.isTensor(item) || item === null)) {
  1956. if (parameter.optional) {
  1957. continue;
  1958. }
  1959. throw new pytorch.Error();
  1960. } else {
  1961. copyArgs.shift();
  1962. copyEvalArgs.shift();
  1963. const list = this._graph.create('prim::ListConstruct');
  1964. for (const arg of argument) {
  1965. const tensor = arg;
  1966. if (tensor) {
  1967. tensor.__count__ = (tensor.__count__ || 0) + 1;
  1968. }
  1969. const value = this.variable(tensor);
  1970. list.addInput(value);
  1971. }
  1972. const value = list.addOutput();
  1973. node.addInput(value);
  1974. }
  1975. } else {
  1976. const [arg] = copyArgs;
  1977. if (!pytorch.Utility.isType(argument, parameter.type) && argument !== null) {
  1978. if (parameter.optional) {
  1979. continue;
  1980. }
  1981. throw new pytorch.Error();
  1982. } else if (arg.type === '=') {
  1983. throw new pytorch.Error('Expected named argument.');
  1984. } else {
  1985. copyArgs.shift();
  1986. copyEvalArgs.shift();
  1987. const value = this.variable(argument);
  1988. node.addInput(value);
  1989. value.value = argument;
  1990. }
  1991. }
  1992. }
  1993. const result = [];
  1994. for (let i = 0; i < schema.outputs.length; i++) {
  1995. const parameter = schema.outputs[i];
  1996. switch (parameter.type) {
  1997. case 'Scalar':
  1998. case 'Tensor': {
  1999. const output = this.invoke('torch.Tensor', []);
  2000. output.__origin__ = schema.name;
  2001. if (i === 0) {
  2002. switch (schema.name) {
  2003. case 'aten::conv1d':
  2004. case 'aten::embedding': {
  2005. output.resize_([NaN, NaN, NaN]);
  2006. break;
  2007. }
  2008. case 'aten::cat':
  2009. case 'aten::conv2d':
  2010. case 'aten::dropout':
  2011. case 'aten::flatten':
  2012. case 'aten::flatten.named_out_dim':
  2013. case 'aten::max_pool2d':
  2014. case 'aten::adaptive_avg_pool2d':
  2015. case 'aten::avg_pool2d':
  2016. case 'aten::quantize_per_tensor':
  2017. case 'aten::relu_':
  2018. case 'aten::prelu':
  2019. case 'aten::hardtanh_':
  2020. case 'aten::upsample_bilinear2d':
  2021. case 'prepacked::conv2d_clamp_run': {
  2022. const [input] = evalArgs;
  2023. if (pytorch.Utility.isTensor(input) && input.size() === undefined) {
  2024. input.resize_([NaN, NaN, NaN, NaN]);
  2025. }
  2026. output.resize_([NaN, NaN, NaN, NaN]);
  2027. break;
  2028. }
  2029. case 'aten::slice':
  2030. case 'aten::slice.Tensor': {
  2031. const [input] = evalArgs;
  2032. if (pytorch.Utility.isTensor(input) && Array.isArray(input.size())) {
  2033. const size = input.size();
  2034. output.resize_(size);
  2035. }
  2036. break;
  2037. }
  2038. case 'aten::to':
  2039. case 'aten::to.device':
  2040. case 'aten::to.dtype':
  2041. case 'aten::to.dtype_layout': {
  2042. const [input] = evalArgs;
  2043. if (pytorch.Utility.isTensor(input) && Array.isArray(input.size())) {
  2044. const size = input.size();
  2045. output.resize_(size);
  2046. }
  2047. break;
  2048. }
  2049. case 'aten::conv3d': {
  2050. output.resize_([NaN, NaN, NaN, NaN, NaN]);
  2051. break;
  2052. }
  2053. case 'aten::roll':
  2054. case 'aten::detach':
  2055. case 'aten::mean':
  2056. case 'aten::mul':
  2057. case 'aten::mul.Scalar':
  2058. case 'aten::div':
  2059. case 'aten::div.Scalar':
  2060. case 'aten::batch_norm':
  2061. case 'aten::gelu':
  2062. case 'aten::relu':
  2063. case 'aten::clamp':
  2064. case 'aten::clamp_':
  2065. case 'aten::_add_relu_':
  2066. case 'aten::hardswish_': {
  2067. const [input] = evalArgs;
  2068. if (pytorch.Utility.isTensor(input) && Array.isArray(input.size())) {
  2069. output.resize_(input.size());
  2070. }
  2071. break;
  2072. }
  2073. case 'aten::add':
  2074. case 'aten::add.Scalar':
  2075. case 'aten::sub':
  2076. case 'aten::sub.Scalar': {
  2077. const [input] = evalArgs;
  2078. if (pytorch.Utility.isTensor(input) && Array.isArray(input.size())) {
  2079. output.resize_(input.size());
  2080. } else {
  2081. const [, other] = evalArgs;
  2082. if (pytorch.Utility.isTensor(other) && Array.isArray(other.size())) {
  2083. output.resize_(other.size());
  2084. }
  2085. }
  2086. break;
  2087. }
  2088. case 'aten::select':
  2089. case 'aten::select.int': {
  2090. const [input] = evalArgs;
  2091. if (pytorch.Utility.isTensor(input) && Array.isArray(input.size())) {
  2092. output.resize_(Array(input.size().length - 1).fill(NaN));
  2093. }
  2094. break;
  2095. }
  2096. case 'aten::layer_norm': {
  2097. const [input, normalized_shape] = evalArgs;
  2098. if (pytorch.Utility.isTensor(input) && Array.isArray(input.size())) {
  2099. const shape = input.size();
  2100. if (Array.isArray(normalized_shape) && normalized_shape.length === 1) {
  2101. const [value] = normalized_shape;
  2102. shape[shape.length - 1] = value;
  2103. }
  2104. output.resize_(shape);
  2105. }
  2106. break;
  2107. }
  2108. case 'aten::empty':
  2109. case 'aten::ones':
  2110. case 'aten::zeros':
  2111. case 'aten::zeros_like': {
  2112. output.resize_(evalArgs[0]);
  2113. break;
  2114. }
  2115. case 'aten::view':
  2116. case 'aten::reshape':
  2117. case 'aten::new_full': {
  2118. output.resize_(evalArgs[1]);
  2119. break;
  2120. }
  2121. case 'aten::squeeze':
  2122. case 'aten::squeeze.dim': {
  2123. const [input] = evalArgs;
  2124. const size = input.size();
  2125. if (Array.isArray(size)) {
  2126. switch (evalArgs.length) {
  2127. case 1: {
  2128. output.resize_(size.filter((value) => value !== 1));
  2129. break;
  2130. }
  2131. case 2: {
  2132. const [, dim] = evalArgs;
  2133. output.resize_(size.filter((value, index) => (value !== 1 && !isNaN(value)) || index !== dim));
  2134. break;
  2135. }
  2136. default: {
  2137. break;
  2138. }
  2139. }
  2140. }
  2141. break;
  2142. }
  2143. case 'aten::unsqueeze': {
  2144. const [input, dim] = evalArgs;
  2145. const size = input.size();
  2146. if (Array.isArray(size) && dim !== undefined) {
  2147. const shape = size.slice();
  2148. shape.splice(dim, 0, 1);
  2149. output.resize_(shape);
  2150. } else {
  2151. output.resize_([NaN, NaN, NaN, NaN]);
  2152. }
  2153. break;
  2154. }
  2155. case 'aten::transpose':
  2156. case 'aten::transpose.int': {
  2157. const [input, dim0, dim1] = evalArgs;
  2158. if (pytorch.Utility.isTensor(input) && Array.isArray(input.size())) {
  2159. const size = input.size().slice();
  2160. const d0 = dim0 >= 0 ? dim0 : size.length + dim0;
  2161. const d1 = dim1 >= 0 ? dim1 : size.length + dim1;
  2162. const value = size[dim0];
  2163. /* eslint-disable prefer-destructuring */
  2164. size[d0] = size[1];
  2165. /* eslint-enable prefer-destructuring */
  2166. size[d1] = value;
  2167. output.resize_(size);
  2168. }
  2169. break;
  2170. }
  2171. case 'aten::contiguous': {
  2172. const [source] = evalArgs;
  2173. output.__source__ = source;
  2174. break;
  2175. }
  2176. case 'quantized::cat':
  2177. case 'quantized::cat_relu':
  2178. case 'quantized::linear':
  2179. case 'quantized::conv2d':
  2180. case 'quantized::conv2d.new':
  2181. case 'quantized::conv2d_relu':
  2182. case 'quantized::conv2d_relu.new':
  2183. case 'quantized::add':
  2184. case 'quantized::add_relu':
  2185. output.resize_([NaN, NaN, NaN, NaN]);
  2186. output.__quantized__ = true;
  2187. break;
  2188. default:
  2189. break;
  2190. }
  2191. }
  2192. this.variable(output, node);
  2193. result.push(output);
  2194. break;
  2195. }
  2196. case 'Tensor[]': {
  2197. let count = 1;
  2198. switch (schema.name) {
  2199. case 'aten::chunk':
  2200. count = node.inputs()[1].value;
  2201. break;
  2202. case 'aten::meshgrid': {
  2203. const list = node.inputs()[0].node();
  2204. if (list.kind() === 'prim::ListConstruct') {
  2205. count = list.inputs().length;
  2206. }
  2207. break;
  2208. }
  2209. case 'aten::unbind':
  2210. case 'aten::unbind.int':
  2211. count = args[0].__tuple__ || count;
  2212. break;
  2213. case 'aten::broadcast_tensors':
  2214. case 'aten::split':
  2215. case 'aten::split.Tensor':
  2216. case 'aten::split_with_sizes':
  2217. if (context.target.length > 0) {
  2218. count = context.target[context.target.length - 1].length;
  2219. }
  2220. break;
  2221. default:
  2222. break;
  2223. }
  2224. const value = node.addOutput();
  2225. const list = this._graph.create('prim::ListUnpack');
  2226. list.addInput(value);
  2227. const tensors = [];
  2228. for (let i = 0; i < count; i ++) {
  2229. const tensor = this.invoke('torch.Tensor', []);
  2230. tensor.__origin__ = schema.name;
  2231. this.variable(tensor, list);
  2232. tensors.push(tensor);
  2233. }
  2234. result.push(tensors);
  2235. break;
  2236. }
  2237. case '__torch__.torch.classes.quantized.Conv2dPackedParamsBase':
  2238. case '__torch__.torch.classes.quantized.Conv3dPackedParamsBase':
  2239. case '__torch__.torch.classes.quantized.LinearPackedParamsBase':
  2240. case '__torch__.torch.classes.rnn.CellParamsBase':
  2241. case '__torch__.torch.classes.xnnpack.Conv2dOpContext':
  2242. case '__torch__.torch.classes.xnnpack.LinearOpContext':
  2243. case '__torch__.torch.classes.xnnpack.TransposeConv2dOpContext': {
  2244. const value = this.invoke(parameter.type, []);
  2245. this.variable(value, node);
  2246. result.push(value);
  2247. break;
  2248. }
  2249. default: {
  2250. const output = this.invoke('torch.Tensor', []);
  2251. output.resize_([]);
  2252. output.__origin__ = schema.name;
  2253. this.variable(output, node);
  2254. result.push(output);
  2255. break;
  2256. }
  2257. }
  2258. }
  2259. for (const referencedParameter of referencedParameters) {
  2260. referencedParameter.__count__ = (referencedParameter.__count__ || 0) + 1;
  2261. }
  2262. if (result.length > 1) {
  2263. return result;
  2264. }
  2265. return result[0];
  2266. }
  2267. }
  2268. return super.call(target, name, args, context);
  2269. }
  2270. _overload(target, name, args, context) {
  2271. let moduleName = pytorch.Utility.target(target);
  2272. if (moduleName) {
  2273. let outputTypes = null;
  2274. let type = name ? `${moduleName}.${name}` : moduleName;
  2275. if (type === 'ops.prim.NumToTensor' && args.length === 1 && args[0].type === 'call' && args[0].target.member.type === 'id') {
  2276. const [arg] = args;
  2277. moduleName = pytorch.Utility.target(arg.target.target);
  2278. name = arg.target.member.value;
  2279. args = arg.args;
  2280. outputTypes = ['int64'];
  2281. type = `${moduleName}.${name}`;
  2282. }
  2283. // https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/native_functions.yaml
  2284. let overloads = null;
  2285. if (type.startsWith('torch.')) {
  2286. overloads = this._types.get(`aten::${type.substring(6)}`);
  2287. /* } else if (type.startsWith('ops.prim.')) {
  2288. overloads = this._types.get(`prim::${type.substring(9)}`);
  2289. } else if (type === 'int') {
  2290. overloads = this._types.get(`aten::Int`);
  2291. // "bool": "aten::Bool"
  2292. // "int": "aten::Int"
  2293. // "float": "aten::Float"
  2294. // "complex": "aten::Complex"
  2295. // "abs": "prim::abs"
  2296. // "max": "prim::max"
  2297. // "min": "prim::min"
  2298. // "range": "fake::does_not_exist"
  2299. */
  2300. } else if (type.startsWith('ops.') && !type.startsWith('ops.prim.')) {
  2301. const path = type.split('.');
  2302. if (path.length === 3) {
  2303. overloads = this._types.get(`${path[1]}::${path[2]}`);
  2304. }
  2305. if (!overloads) {
  2306. const module = this.import(moduleName);
  2307. if (!module || !module[name]) {
  2308. const metadata = {};
  2309. metadata.name = type;
  2310. metadata.inputs = [];
  2311. metadata.outputs = [];
  2312. for (let i = 0; i < args.length; i++) {
  2313. const input = {};
  2314. let argument = args[i];
  2315. input.name = i.toString();
  2316. if (argument.type === '=' && argument.target && argument.target.type === 'id') {
  2317. input.name = this.expression(argument.target, context);
  2318. argument = argument.expression;
  2319. }
  2320. const obj = this.expression(argument, context);
  2321. input.type = pytorch.Utility.getType(obj);
  2322. metadata.inputs.push(input);
  2323. }
  2324. const count = context.target.length > 0 ? context.target[context.target.length - 1].length : 0;
  2325. for (let i = 0; i < count; i++) {
  2326. metadata.outputs.push({ name: '', type: '' });
  2327. }
  2328. this._metadata.add(type, metadata);
  2329. overloads = [metadata];
  2330. }
  2331. }
  2332. }
  2333. if (overloads) {
  2334. overloads = Array.isArray(overloads) ? overloads : [overloads];
  2335. const evalArgs = args.map((argument) => {
  2336. if (argument.type === '=' && argument.target && argument.target.type === 'id') {
  2337. argument = argument.expression;
  2338. }
  2339. return this.expression(argument, context);
  2340. });
  2341. for (const schema of overloads) {
  2342. const copyArgs = Array.prototype.slice.call(args);
  2343. const copyEvalArgs = Array.prototype.slice.call(evalArgs);
  2344. const parameters = Array.prototype.slice.call(schema.inputs || []).concat(Array.prototype.slice.call(schema.attributes || []));
  2345. let next = false;
  2346. while (copyEvalArgs.length > 0) {
  2347. if (parameters.length <= 0) {
  2348. next = !schema.name.startsWith('_caffe2::');
  2349. break;
  2350. }
  2351. if (copyArgs.every((arg) => arg.type === '=' && arg.target && arg.target.type === 'id') &&
  2352. parameters.every((parameter) => parameter.type !== 'Tensor' && parameter.type !== 'Tensor[]')) {
  2353. const map = new Map(parameters.map((parameter) => [parameter.name, parameter]));
  2354. while (copyArgs.length > 0) {
  2355. const argument = copyArgs.shift();
  2356. const arg = copyEvalArgs.shift();
  2357. const parameter = map.get(argument.target.value);
  2358. if (!parameter) {
  2359. next = true;
  2360. break;
  2361. }
  2362. if (!pytorch.Utility.isType(arg, parameter.type)) {
  2363. if (parameter.optional) {
  2364. continue;
  2365. }
  2366. next = true;
  2367. break;
  2368. }
  2369. }
  2370. continue;
  2371. }
  2372. if (next) {
  2373. break;
  2374. }
  2375. const parameter = parameters.shift();
  2376. const [argument] = copyEvalArgs;
  2377. if (parameter.type === 'Tensor' || (parameter.type === 'Scalar' && pytorch.Utility.isTensor(argument))) {
  2378. if (Array.isArray(argument) || (!pytorch.Utility.isTensor(argument) && argument !== null && argument !== undefined)) {
  2379. if (parameter.optional) {
  2380. continue;
  2381. }
  2382. next = true;
  2383. } else {
  2384. copyArgs.shift();
  2385. copyEvalArgs.shift();
  2386. }
  2387. } else if (parameter.type === 'Tensor[]') {
  2388. const [argument] = copyEvalArgs;
  2389. if (!Array.isArray(argument) || !argument.every((item) => pytorch.Utility.isTensor(item) || item === null)) {
  2390. if (parameter.optional) {
  2391. continue;
  2392. }
  2393. next = true;
  2394. } else {
  2395. copyArgs.shift();
  2396. copyEvalArgs.shift();
  2397. }
  2398. } else {
  2399. const [arg] = copyArgs;
  2400. if (!pytorch.Utility.isType(argument, parameter.type) && argument !== null) {
  2401. if (parameter.optional) {
  2402. continue;
  2403. }
  2404. next = true;
  2405. } else if (arg.type === '=') {
  2406. throw new pytorch.Error('Expected named argument.');
  2407. } else {
  2408. copyArgs.shift();
  2409. copyEvalArgs.shift();
  2410. }
  2411. }
  2412. if (next) {
  2413. break;
  2414. }
  2415. }
  2416. if (next) {
  2417. continue;
  2418. }
  2419. for (let i = 0; i < schema.outputs.length; i++) {
  2420. const parameter = schema.outputs[i];
  2421. switch (parameter.type) {
  2422. case 'Scalar':
  2423. case 'Tensor':
  2424. case 'Tensor[]':
  2425. break;
  2426. // case 'int64':
  2427. // break;
  2428. case '__torch__.torch.classes.xnnpack.LinearOpContext':
  2429. case '__torch__.torch.classes.xnnpack.Conv2dOpContext':
  2430. case '__torch__.torch.classes.xnnpack.TransposeConv2dOpContext':
  2431. case '__torch__.torch.classes.rnn.CellParamsBase':
  2432. case '__torch__.torch.classes.quantized.LinearPackedParamsBase':
  2433. case '__torch__.torch.classes.quantized.Conv2dPackedParamsBase':
  2434. case '__torch__.torch.classes.quantized.Conv3dPackedParamsBase':
  2435. break;
  2436. default: {
  2437. if (!outputTypes || schema.outputs.length !== 1 || schema.outputs[0].type !== outputTypes[0]) {
  2438. next = true;
  2439. }
  2440. break;
  2441. }
  2442. }
  2443. }
  2444. if (next) {
  2445. continue;
  2446. }
  2447. return [schema, args, evalArgs];
  2448. }
  2449. }
  2450. }
  2451. return null;
  2452. }
  2453. block(statements, context) {
  2454. statements = Array.prototype.slice.call(statements);
  2455. while (statements.length > 0) {
  2456. if (statements.length > 1) {
  2457. const [assign, condition] = statements;
  2458. // _x = torch.ne(torch.len(torch.size(input)), 5)
  2459. // if _x:
  2460. // ops.prim.RaiseException(...)
  2461. if (assign.type === '=' &&
  2462. condition.type === 'if' &&
  2463. pytorch.Utility.isEqual(assign.target, condition.test) &&
  2464. pytorch.Utility.isCall(assign.expression, 'torch.ne', 2) &&
  2465. pytorch.Utility.isCall(assign.expression.args[0], 'torch.len', 1) &&
  2466. pytorch.Utility.isCall(assign.expression.args[0].args[0], 'torch.size', 1) &&
  2467. condition.body.statements.length === 1 &&
  2468. pytorch.Utility.isCall(condition.body.statements[0], 'ops.prim.RaiseException', 1)) {
  2469. const tensor = this.expression(assign.expression.args[0].args[0].args[0], context);
  2470. if (pytorch.Utility.isTensor(tensor) && tensor.size) {
  2471. const number = this.expression(assign.expression.args[1], context);
  2472. const size = tensor.size();
  2473. if (number >= 3 && number <= 5) {
  2474. if (!Array.isArray(size) || size.length !== number) {
  2475. tensor.resize_(Array(number).fill(NaN));
  2476. }
  2477. }
  2478. }
  2479. }
  2480. // _x = torch.ne(torch.dim(input), 5)
  2481. // if _x:
  2482. // ops.prim.RaiseException(...)
  2483. if (assign.type === '=' &&
  2484. condition.type === 'if' &&
  2485. pytorch.Utility.isEqual(assign.target, condition.test) &&
  2486. pytorch.Utility.isCall(assign.expression, 'torch.ne', 2) &&
  2487. pytorch.Utility.isCall(assign.expression.args[0], 'torch.dim', 1) &&
  2488. condition.body.statements.length > 0 &&
  2489. pytorch.Utility.isCall(condition.body.statements[condition.body.statements.length - 1], 'ops.prim.RaiseException', 1)) {
  2490. const tensor = this.expression(assign.expression.args[0].args[0], context);
  2491. if (pytorch.Utility.isTensor(tensor)) {
  2492. const size = this.expression(assign.expression.args[1], context);
  2493. tensor.resize_(Array(size).fill(NaN));
  2494. }
  2495. }
  2496. // _0 = torch.eq(torch.len(torch.size(x)), 2)
  2497. // if _0:
  2498. // pass
  2499. // else:
  2500. // ops.prim.RaiseException("AssertionError: ")
  2501. if (assign.type === '=' &&
  2502. condition.type === 'if' &&
  2503. pytorch.Utility.isEqual(assign.target, condition.test) &&
  2504. pytorch.Utility.isCall(assign.expression, 'torch.eq', 2) &&
  2505. pytorch.Utility.isCall(assign.expression.args[0], 'torch.len', 1) &&
  2506. pytorch.Utility.isCall(assign.expression.args[0].args[0], 'torch.size', 1) &&
  2507. condition.orelse.statements.length === 1 &&
  2508. pytorch.Utility.isCall(condition.orelse.statements[0], 'ops.prim.RaiseException', 1)) {
  2509. const tensor = this.expression(assign.expression.args[0].args[0].args[0], context);
  2510. if (pytorch.Utility.isTensor(tensor) && tensor.shape === undefined) {
  2511. const number = this.expression(assign.expression.args[1], context);
  2512. tensor.resize_(Array(number).fill(NaN));
  2513. }
  2514. }
  2515. // val = torch.slice(torch.size(img), -2)
  2516. // if torch.eq(torch.len(val), 2):
  2517. // pass
  2518. // else:
  2519. // ops.prim.RaiseException("AssertionError: ")
  2520. if (assign.type === '=' &&
  2521. condition.type === 'if' &&
  2522. pytorch.Utility.isCall(assign.expression, 'torch.slice', 2) &&
  2523. pytorch.Utility.isCall(assign.expression.args[0], 'torch.size', 1) &&
  2524. pytorch.Utility.isCall(condition.test, 'torch.eq', 2) &&
  2525. pytorch.Utility.isCall(condition.test.args[0], 'torch.len', 1) &&
  2526. pytorch.Utility.isEqual(condition.test.args[0].args[0], assign.target) &&
  2527. condition.orelse.statements.length === 1 &&
  2528. pytorch.Utility.isCall(condition.orelse.statements[0], 'ops.prim.RaiseException', 1)) {
  2529. const tensor = this.expression(assign.expression.args[0].args[0], context);
  2530. if (pytorch.Utility.isTensor(tensor) && tensor.shape === undefined) {
  2531. const start = this.expression(assign.expression.args[1], context);
  2532. const value = this.expression(condition.test.args[1], context);
  2533. if (Number.isInteger(start) && start < 0 && Number.isInteger(value) && value > 0) {
  2534. tensor.resize_(Array(value - start).fill(NaN));
  2535. }
  2536. }
  2537. }
  2538. }
  2539. if (statements.length > 1) {
  2540. // getattr_1 = torch.size(x)
  2541. // getitem = torch.slice(getattr_1, -2, 9223372036854775807, 1)
  2542. const [size, statement] = statements;
  2543. if (size.type === '=' && statement.type === '=' &&
  2544. size.target.type === 'id' &&
  2545. pytorch.Utility.isCall(size.expression, 'torch.size', 1) &&
  2546. pytorch.Utility.isCall(statement.expression, 'torch.slice', 4) &&
  2547. statement.expression.arguments[0].type === 'id' && size.target.value === statement.expression.arguments[0].value) {
  2548. const tensor = this.expression(size.expression.arguments[0], context);
  2549. if (pytorch.Utility.isTensor(tensor) && tensor.__origin__ === 'graph-input' && tensor.shape === undefined) {
  2550. tensor.resize_([1, 3, 299, 299]);
  2551. }
  2552. }
  2553. }
  2554. if (statements.length > 1) {
  2555. // _0 = torch.split_with_sizes(...)
  2556. // a, a_1, a_2, = _0
  2557. const [statement, tuple] = statements;
  2558. if (statement.type === '=' && statement.target.type === 'id' && statement.expression.type === 'call' &&
  2559. tuple.type === '=' && tuple.target.type === 'tuple' &&
  2560. tuple.target.value.every((item) => item.type === 'id') &&
  2561. tuple.expression.value === statement.target.value) {
  2562. const containsVariableReference = (queue, value) => {
  2563. while (queue.length > 0) {
  2564. const obj = queue.shift();
  2565. if (obj && obj.type === 'id' && obj.value === value) {
  2566. return true;
  2567. } else if (Array.isArray(obj)) {
  2568. for (const item of obj) {
  2569. if (Array.isArray(item) || (Object(item) === item && item.type)) {
  2570. queue.push(item);
  2571. }
  2572. }
  2573. } else if (Object(obj) === obj) {
  2574. for (const [key, value] of Object.entries(obj)) {
  2575. if (key !== 'identifier') {
  2576. if (Array.isArray(value)) {
  2577. for (const item of value) {
  2578. if (Array.isArray(item) || (Object(item) === item && item.type)) {
  2579. queue.push(item);
  2580. }
  2581. }
  2582. } else if (Object(value) === value && value.type) {
  2583. queue.push(value);
  2584. }
  2585. }
  2586. }
  2587. }
  2588. }
  2589. return false;
  2590. };
  2591. if (!containsVariableReference(statements.slice(2, statements.length - 1), statement.target.value)) {
  2592. statements[0] = { ...statement };
  2593. statements[0].target = tuple.target;
  2594. statements.splice(1, 1);
  2595. }
  2596. }
  2597. }
  2598. const statement = statements.shift();
  2599. // input_shape = torch.slice(torch.size(x), -2, 9223372036854775807, 1)
  2600. if (statement.type === '=' &&
  2601. pytorch.Utility.isCall(statement.expression, 'torch.slice', 4) &&
  2602. pytorch.Utility.isCall(statement.expression.args[0], 'torch.size', 1)) {
  2603. const tensor = this.expression(statement.expression.args[0].args[0], context);
  2604. if (pytorch.Utility.isTensor(tensor) && tensor.shape === undefined) {
  2605. tensor.resize_([1, 3, 299, 299]);
  2606. }
  2607. }
  2608. // torch.slice(ops.prim.shape(input), 0, 2, 1)
  2609. if (statement.type === '=' &&
  2610. pytorch.Utility.isCall(statement.expression, 'torch.slice', 4) &&
  2611. pytorch.Utility.isCall(statement.expression.args[0], 'ops.prim.shape', 1)) {
  2612. const tensor = this.expression(statement.expression.args[0].args[0], context);
  2613. if (pytorch.Utility.isTensor(tensor) && tensor.__origin__ === 'graph-input' && tensor.shape === undefined) {
  2614. tensor.resize_([NaN, NaN, NaN, NaN]);
  2615. }
  2616. }
  2617. // _3 = torch.le(xxxx, torch.dim(f0))
  2618. if (statement.type === '=' &&
  2619. pytorch.Utility.isCall(statement.expression, 'torch.le', 2) &&
  2620. pytorch.Utility.isCall(statement.expression.args[1], 'torch.dim', 1)) {
  2621. const tensor = this.expression(statement.expression.args[1].args[0], context);
  2622. if (pytorch.Utility.isTensor(tensor) && tensor.__origin__ === 'graph-input' && tensor.shape === undefined) {
  2623. tensor.resize_([NaN, NaN, NaN, NaN]);
  2624. }
  2625. }
  2626. // if torch.ne(torch.dim(image), 3):
  2627. // xxxx
  2628. // ops.prim.RaiseException(_7)
  2629. if (statement.type === 'if' &&
  2630. pytorch.Utility.isCall(statement.test, 'torch.ne', 2) &&
  2631. pytorch.Utility.isCall(statement.test.args[0], 'torch.dim', 1) &&
  2632. statement.body.statements.length > 0 &&
  2633. pytorch.Utility.isCall(statement.body.statements.slice(-1).pop(), 'ops.prim.RaiseException', 1)) {
  2634. const tensor = this.expression(statement.test.args[0].args[0], context);
  2635. const size = this.expression(statement.test.args[1], context);
  2636. if (pytorch.Utility.isTensor(tensor) && Number.isInteger(size) && size < 10) {
  2637. tensor.resize_(Array.isArray(tensor.shape) && tensor.shape.length > size ? tensor.shape.slice(-size) : Array(size).fill(NaN));
  2638. }
  2639. }
  2640. // if torch.gt(torch.dim(x), 1):
  2641. // xxxx
  2642. // ops.prim.RaiseException(...)
  2643. if (statement.type === 'if' &&
  2644. pytorch.Utility.isCall(statement.test, 'torch.gt', 2) &&
  2645. pytorch.Utility.isCall(statement.test.args[0], 'torch.dim', 1) &&
  2646. statement.body.statements.length > 0 &&
  2647. pytorch.Utility.isCall(statement.body.statements.slice(-1).pop(), 'ops.prim.RaiseException')) {
  2648. const tensor = this.expression(statement.test.args[0].args[0], context);
  2649. const size = this.expression(statement.test.args[1], context);
  2650. if (pytorch.Utility.isTensor(tensor) && Number.isInteger(size) && size < 10) {
  2651. tensor.resize_(Array.isArray(tensor.shape) && tensor.shape.length > size ? tensor.shape.slice(-size) : Array(size).fill(NaN));
  2652. }
  2653. }
  2654. // if bool(...):
  2655. // ops.prim.RaiseException(torch.format(_1, dtype))
  2656. // else:
  2657. // pass
  2658. if (statement.type === 'if' &&
  2659. pytorch.Utility.isCall(statement.test, 'bool', 1) &&
  2660. statement.body.statements.length > 0 &&
  2661. pytorch.Utility.isCall(statement.body.statements.slice(-1).pop(), 'ops.prim.RaiseException', 1)) {
  2662. statement.test = { type: 'id', value: 'False' };
  2663. }
  2664. // dim = torch.sub(torch.dim(input), 2)
  2665. if (statement.type === '=' &&
  2666. statement.target.type === 'id' && statement.target.value === 'dim' &&
  2667. pytorch.Utility.isCall(statement.expression, 'torch.sub', 2) &&
  2668. pytorch.Utility.isCall(statement.expression.args[0], 'torch.dim', 1)) {
  2669. const tensor = this.expression(statement.expression.args[0].args[0], context);
  2670. if (pytorch.Utility.isTensor(tensor) && tensor.__origin__ === 'graph-input' && tensor.shape === undefined) {
  2671. tensor.resize_([NaN, NaN, NaN, NaN]);
  2672. }
  2673. }
  2674. // a, b = torch.unbind(size, 0)
  2675. if (statement.type === '=' &&
  2676. statement.target.type === 'tuple' &&
  2677. (pytorch.Utility.isCall(statement.expression, 'torch.unbind', 1) ||
  2678. pytorch.Utility.isCall(statement.expression, 'torch.unbind', 2))) {
  2679. statement.expression.args[0].__tuple__ = statement.target.value.length;
  2680. }
  2681. // a, b, c = torch.size(input)
  2682. if (statement.type === '=' &&
  2683. statement.target.type === 'tuple' &&
  2684. pytorch.Utility.isCall(statement.expression, 'torch.size', 1)) {
  2685. const tensor = this.expression(statement.expression.args[0], context);
  2686. if (pytorch.Utility.isTensor(tensor) && tensor.__origin__ === 'graph-input' && tensor.shape === undefined) {
  2687. const dim = statement.target.value.length;
  2688. tensor.resize_(Array(dim).fill(NaN));
  2689. }
  2690. }
  2691. // x = torch.len(input)
  2692. if (statement.type === '=' &&
  2693. statement.target.type === 'id' &&
  2694. pytorch.Utility.isCall(statement.expression, 'torch.len', 1)) {
  2695. const tensor = this.expression(statement.expression.args[0], context);
  2696. if (pytorch.Utility.isTensor(tensor) && tensor.__origin__ === 'graph-input' && tensor.shape === undefined) {
  2697. tensor.resize_([NaN, NaN, NaN, NaN]);
  2698. }
  2699. }
  2700. // x = _(torch.size(foo ,2))
  2701. if (statement.type === '=' &&
  2702. statement.expression.type === 'call' && statement.expression.args.length > 0 &&
  2703. pytorch.Utility.isCall(statement.expression.args[0], 'torch.size', 2)) {
  2704. const tensor = this.expression(statement.expression.args[0].args[0], context);
  2705. const dim = this.expression(statement.expression.args[0].args[1], context);
  2706. if (pytorch.Utility.isTensor(tensor) && Number.isInteger(dim) && dim >= 0) {
  2707. if (tensor.shape === undefined) {
  2708. tensor.resize_(Array(dim + 1).fill(NaN));
  2709. } else if (Array.isArray(tensor.shape) && tensor.shape.length <= dim) {
  2710. tensor.resize_(tensor.shape.concat(Array(dim + 1 - tensor.shape.length).fill(NaN)));
  2711. }
  2712. }
  2713. }
  2714. if (statement.type === '=' && statement.target.type === 'tuple' &&
  2715. statement.expression.type === 'call' && statement.expression.args.length > 0 &&
  2716. pytorch.Utility.isCall(statement.expression, 'torch.size', 1)) {
  2717. const tensor = this.expression(statement.expression.args[0], context);
  2718. if (pytorch.Utility.isTensor(tensor) && tensor.__origin__ === 'graph-input') {
  2719. if (tensor.shape === undefined) {
  2720. tensor.resize_(Array(statement.target.value.length).fill(NaN));
  2721. }
  2722. }
  2723. }
  2724. const value = this.statement(statement, context);
  2725. if (value !== undefined) {
  2726. return value;
  2727. }
  2728. }
  2729. return undefined;
  2730. }
  2731. };
  2732. pytorch.jit.Source = class {
  2733. constructor(text) {
  2734. this._text = text;
  2735. }
  2736. };
  2737. pytorch.jit.SourceLoader = class {
  2738. constructor(reader, code_prefix) {
  2739. this._reader = reader;
  2740. this._code_prefix = code_prefix;
  2741. }
  2742. loadSource(qualifier) {
  2743. const path = `${this._code_prefix}/${qualifier}.py`;
  2744. if (this._reader.has_record(path)) {
  2745. const data = this._reader.get_record(path);
  2746. return new pytorch.jit.Source(data);
  2747. }
  2748. return null;
  2749. }
  2750. };
  2751. pytorch.jit.SourceImporter = class {
  2752. constructor(cu, constant_table, source_loader, version) {
  2753. this._cu = cu;
  2754. this._constant_table = constant_table;
  2755. this._source_loader = source_loader;
  2756. this._version = version;
  2757. }
  2758. loadType(/* name */) {
  2759. //
  2760. }
  2761. resolveType(name) {
  2762. return this.findNamedType(new pytorch.jit.QualifiedName(name));
  2763. }
  2764. findNamedType(name) {
  2765. this.parseSourceIfNeeded(name.prefix());
  2766. }
  2767. parseSourceIfNeeded(/* qualifier */) {
  2768. }
  2769. };
  2770. pytorch.jit.ScriptModuleDeserializer = class {
  2771. constructor(cu, reader, pickle_dir_prefix, tensor_dir_prefix, storage_context) {
  2772. this._compilation_unit = cu;
  2773. this._reader = reader;
  2774. this._storage_context = storage_context;
  2775. this._code_prefix = !pickle_dir_prefix && !tensor_dir_prefix ? 'code/' : '.data/ts_code/code/';
  2776. this._pickle_dir_prefix = pickle_dir_prefix || '';
  2777. this._tensor_dir_prefix = tensor_dir_prefix || '';
  2778. this._source_importer = new pytorch.jit.SourceImporter(
  2779. this._compilation_unit, this._constants_table,
  2780. new pytorch.jit.SourceLoader(this._reader, this._code_prefix), reader.version());
  2781. }
  2782. deserialize() {
  2783. const execution = this._compilation_unit.execution;
  2784. const code_prefix = this._code_prefix;
  2785. for (const name of this._reader.get_all_records()) {
  2786. if (name.startsWith(code_prefix) && name.endsWith('.py')) {
  2787. const file = name.substring(code_prefix.length);
  2788. const stream = this._reader.get_record(name);
  2789. const buffer = stream.peek();
  2790. execution.add(file, buffer);
  2791. }
  2792. }
  2793. const torch = execution.import('torch');
  2794. execution.builtins.torch = torch;
  2795. execution.builtins.Tensor = torch.Tensor;
  2796. execution.builtins.ops = torch.ops;
  2797. execution.builtins.inf = torch.inf;
  2798. execution.builtins.CONSTANTS = {};
  2799. if (this._reader.has_record('model.json')) {
  2800. return this.LEGACY_deserialize();
  2801. }
  2802. const constants = this.readArchive('constants');
  2803. for (let i = 0; i < constants.length; i++) {
  2804. execution.builtins.CONSTANTS[`c${i}`] = constants[i];
  2805. }
  2806. const module = this.readArchive('data');
  2807. const type = new torch.ClassType(`${module.__class__.__module__}.${module.__class__.__name__}`, null, true);
  2808. const result = new torch.ScriptModule(type);
  2809. result.data = module;
  2810. return result;
  2811. }
  2812. LEGACY_deserialize() {
  2813. const execution = this._compilation_unit.execution;
  2814. const torch = execution.import('torch');
  2815. const stream = this._reader.get_record('model.json');
  2816. const buffer = stream.peek();
  2817. const decoder = new TextDecoder('utf-8');
  2818. const content = decoder.decode(buffer);
  2819. const model = JSON.parse(content);
  2820. const data = model.mainModule || {};
  2821. const queue = [data];
  2822. const tensorTypeMap = new Map([
  2823. ['FLOAT', 'Float'],
  2824. ['FLOAT16', 'Half'],
  2825. ['DOUBLE', 'Double'],
  2826. ['INT8', 'Char'],
  2827. ['INT32', 'Int'],
  2828. ['INT64', 'Long']
  2829. ]);
  2830. const constants = (model.tensors || []).map((constant) => {
  2831. const key = constant.data.key;
  2832. if (!tensorTypeMap.has(constant.dataType)) {
  2833. throw new pytorch.Error(`Unsupported tensor data type '${constant.dataType}'.`);
  2834. }
  2835. const type = tensorTypeMap.get(constant.dataType);
  2836. const shape = constant.dims ? constant.dims.map((dim) => parseInt(dim, 10)) : null;
  2837. const strides = constant.strides ? constant.strides.map((dim) => parseInt(dim, 10)) : null;
  2838. const storage_type = execution.resolve(`torch.${type}Storage`);
  2839. const size = (shape || []).reduce((a, b) => a * b, 1);
  2840. const offset = parseInt(constant.offset, 10) || 0;
  2841. const storage = new storage_type(size);
  2842. const itemsize = storage.dtype.itemsize();
  2843. const stream = this._reader.get_record(key);
  2844. if (stream) {
  2845. const buffer = stream.peek();
  2846. const length = size * itemsize;
  2847. const data = buffer.slice(offset, offset + length);
  2848. storage._set_cdata(data);
  2849. }
  2850. const tensor = execution.invoke('torch._utils._rebuild_tensor', [storage, 0, shape, strides]);
  2851. tensor.name = constant.data.key;
  2852. return tensor;
  2853. });
  2854. execution.builtins.CONSTANTS = {};
  2855. for (let i = 0; i < constants.length; i++) {
  2856. execution.builtins.CONSTANTS[`c${i}`] = constants[i];
  2857. }
  2858. const attributes = [];
  2859. if (this._reader.has_record('attributes.pkl')) {
  2860. const stream = this._reader.get_record('attributes.pkl');
  2861. const buffer = stream.peek();
  2862. const unpickler = execution.invoke('pickle.Unpickler', [buffer]);
  2863. const obj = unpickler.load();
  2864. attributes.push(...obj);
  2865. }
  2866. while (queue.length > 0) {
  2867. const module = queue.shift();
  2868. module.__class__ = module.__class__ || { __module__: 'torch.nn.modules.module', __name__: 'Module' };
  2869. if (module.name) {
  2870. module.__name__ = module.name;
  2871. }
  2872. if (module.submodules) {
  2873. for (const submodule of module.submodules) {
  2874. module[submodule.name] = submodule;
  2875. submodule.__parent__ = module;
  2876. queue.push(submodule);
  2877. }
  2878. delete module.submodules;
  2879. }
  2880. const parameters = [];
  2881. if (module.parameters) {
  2882. parameters.push(...module.parameters);
  2883. delete module.parameters;
  2884. }
  2885. if (module.arguments) {
  2886. parameters.push(...module.arguments);
  2887. delete module.arguments;
  2888. }
  2889. for (const parameter of parameters) {
  2890. const tensor = constants[parameter.tensorId];
  2891. module[parameter.name] = tensor;
  2892. parameter.__class__ = parameter.__class__ || { __module__: 'torch', __name__: 'Tensor' };
  2893. }
  2894. for (const attribute of module.attributes || []) {
  2895. module[attribute.name] = attributes[attribute.id];
  2896. }
  2897. delete module.attributes;
  2898. }
  2899. const arena = data.torchscriptArena;
  2900. if (arena && arena.key && arena.key.startsWith('code/')) {
  2901. if (!this._reader.has_record(arena.key)) {
  2902. throw new pytorch.Error(`File '${arena.key}' not found.`);
  2903. }
  2904. const file = arena.key.substring('code/'.length);
  2905. const name = file.replace(/\.py$/, '').split('/').join('.');
  2906. const module = execution.import(name);
  2907. if (module.forward.__class__ === execution.builtins.function) {
  2908. data.forward = module.forward;
  2909. }
  2910. }
  2911. const result = new torch.ScriptModule();
  2912. result.data = data;
  2913. return result;
  2914. }
  2915. readArchive(archive_name) {
  2916. const type_resolver = null;
  2917. const obj_loader = null;
  2918. return this.readArchiveAndTensors(archive_name, this._pickle_dir_prefix, this._tensor_dir_prefix, type_resolver, obj_loader, this._device, this._reader, null, this._storage_context);
  2919. }
  2920. readArchiveAndTensors(archive_name, pickle_prefix, tensor_prefix, type_resolver, obj_loader, device, stream_reader, type_parser, storage_context) {
  2921. const picklename = `${pickle_prefix + archive_name}.pkl`;
  2922. const stream = stream_reader.get_record(picklename);
  2923. if (!stream) {
  2924. throw new pytorch.Error(`File '${picklename}' is not found.`);
  2925. }
  2926. const buffer = stream.peek();
  2927. const tensor_dir_path = tensor_prefix ? tensor_prefix : `${archive_name}/`;
  2928. const read_record = (name) => {
  2929. const stream = stream_reader.get_record(tensor_dir_path + name);
  2930. return stream.length <= 0x40000 ? stream.peek() : stream;
  2931. };
  2932. const execution = this._compilation_unit.execution;
  2933. const pickle = execution.__import__('pickle');
  2934. const Unpickler = class extends pickle.Unpickler {
  2935. find_class(module, name) {
  2936. return super.find_class(module, name);
  2937. }
  2938. };
  2939. const unpickler = new Unpickler(buffer);
  2940. unpickler.persistent_load = (saved_id) => {
  2941. if (saved_id[0] !== 'storage') {
  2942. throw new pytorch.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  2943. }
  2944. const [, storage_type, key, , size] = saved_id;
  2945. if (storage_context && storage_context.has_storage(key)) {
  2946. return storage_context.get_storage(key);
  2947. }
  2948. const storage = new storage_type(size);
  2949. const storage_ptr = read_record(key);
  2950. storage._set_cdata(storage_ptr);
  2951. if (storage_context) {
  2952. storage_context.add_storage(key);
  2953. }
  2954. return storage;
  2955. };
  2956. return unpickler.load();
  2957. }
  2958. };
  2959. pytorch.jit.FlatBuffersLoader = class {
  2960. constructor(cu) {
  2961. this._cu = cu;
  2962. const torch = cu.execution.__import__('torch');
  2963. this._torch = torch;
  2964. const dtypes = Array.from(new Set(Object.values(torch).filter((obj) => obj instanceof torch.dtype)));
  2965. this._dtypes = new Map(dtypes.map((dtype) => [dtype.scalar_type(), dtype]));
  2966. this._ivalue_parsers = new Map();
  2967. this._ivalue_parsers.set(pytorch.mobile.serialization.Int, (ivalue) => ivalue.val.int_val);
  2968. this._ivalue_parsers.set(pytorch.mobile.serialization.Bool, (ivalue) => ivalue.val.bool_val);
  2969. this._ivalue_parsers.set(pytorch.mobile.serialization.Double, (ivalue) => ivalue.val.double_val);
  2970. this._ivalue_parsers.set(pytorch.mobile.serialization.TensorMetadata, (ivalue) => this.parseTensor(ivalue));
  2971. this._ivalue_parsers.set(pytorch.mobile.serialization.Object, (ivalue) => this.parseObject(ivalue));
  2972. }
  2973. parseModule(module) {
  2974. this._module = module;
  2975. this._all_functions = new Map();
  2976. this._all_ivalues = new Array(module.ivalues.length);
  2977. this._all_types = new Array(module.object_types.length);
  2978. const mobile_ivalue_size = module.mobile_ivalue_size ? module.mobile_ivalue_size : module.ivalues.length;
  2979. for (let i = 0; i < mobile_ivalue_size; i++) {
  2980. this.parseAndPopulate(i, module.ivalues[i]);
  2981. }
  2982. const m = this._all_ivalues[module.state_obj];
  2983. for (const [name, value] of this._all_functions) {
  2984. const class_index = module.ivalues[name].val.class_type;
  2985. const class_type = this._all_types[class_index];
  2986. class_type.addMethod(value);
  2987. }
  2988. m._min_operator_version = module.operator_version;
  2989. m._bytecode_version = module.bytecode_version;
  2990. return m;
  2991. }
  2992. parseAndPopulate(i, ivalue) {
  2993. if (ivalue.val instanceof pytorch.mobile.serialization.Function) {
  2994. this._all_functions.set(i, this.parseFunction(ivalue.val));
  2995. } else {
  2996. this._all_ivalues[i] = this.parseIValue(ivalue);
  2997. }
  2998. }
  2999. parseFunction(/* val */) {
  3000. return null;
  3001. }
  3002. parseIValue(ivalue) {
  3003. if (ivalue.val) {
  3004. const callback = this._ivalue_parsers.get(ivalue.val.constructor);
  3005. return callback(ivalue);
  3006. }
  3007. return null;
  3008. }
  3009. parseTensor(ivalue) {
  3010. return this.parseTensorFromMetadata(ivalue.val);
  3011. }
  3012. parseTensorFromMetadata(metadata) {
  3013. if (metadata.quantized_schema) {
  3014. throw new pytorch.Error('Quantized schema not implemented.');
  3015. }
  3016. const index = metadata.storage_location_index;
  3017. const data = this._module.storage_data[index].data;
  3018. const dtype = this._dtypes.get(metadata.scalar_type);
  3019. const size = data.length / dtype.itemsize();
  3020. const storage = this._cu.execution.invoke('torch.storage.TypedStorage', [size, dtype]);
  3021. storage._set_cdata(data);
  3022. const tensor = this._cu.execution.invoke('torch.Tensor', []);
  3023. const shape = Array.from(metadata.sizes);
  3024. const stride = Array.from(metadata.strides);
  3025. tensor.__setstate__([storage, metadata.storage_offset, shape, stride]);
  3026. return tensor;
  3027. }
  3028. parseObject(ivalue) {
  3029. const object = ivalue.val;
  3030. const obj_type = this._module.object_types[object.type_index];
  3031. const cls = this.getOrCreateClassTypeForObject(object);
  3032. switch (obj_type.type) {
  3033. case pytorch.mobile.serialization.TypeType.CLASS_WITH_FIELD: {
  3034. const torch = this._torch;
  3035. const obj = torch.ScriptObject.create(cls);
  3036. for (let i = 0; i < object.attrs.length; i++) {
  3037. const attr_name = obj_type.attr_names[i];
  3038. const val = this._all_ivalues[object.attrs[i]];
  3039. obj.__setattr__(attr_name, val);
  3040. }
  3041. return obj;
  3042. }
  3043. case pytorch.mobile.serialization.TypeType.CUSTOM_CLASS:
  3044. case pytorch.mobile.serialization.TypeType.CLASS_WITH_SETSTATE:
  3045. default: {
  3046. throw new pytorch.Error(`Unknown object type type '${obj_type.type}'.`);
  3047. }
  3048. }
  3049. }
  3050. getOrCreateClassTypeForObject(object) {
  3051. let cls = this._all_types[object.type_index];
  3052. const obj_type = this._module.object_types[object.type_index];
  3053. if (!cls) {
  3054. const name = obj_type.type_name;
  3055. if (name.startsWith('__torch__') || name.startsWith('torch.jit')) {
  3056. cls = this._cu.get_class(name);
  3057. if (!cls) {
  3058. const torch = this._torch;
  3059. cls = new torch.ClassType(name, this._cu, true);
  3060. this._cu.register_type(cls);
  3061. }
  3062. } else {
  3063. // cls = c10::parseType(qn_str)->cast<ClassType>();
  3064. }
  3065. this._all_types[object.type_index] = cls;
  3066. if (obj_type.type === pytorch.mobile.serialization.TypeType.CLASS_WITH_FIELD) {
  3067. for (let i = 0; i < object.attrs.length; i++) {
  3068. // const val = this._all_ivalues[object.attrs[i]];
  3069. cls.addAttribute(obj_type.attr_names[i] /*, null val.type(c10::DynamicType) */);
  3070. }
  3071. }
  3072. }
  3073. return cls;
  3074. }
  3075. };
  3076. pytorch.Container.Package = class extends pytorch.Container {
  3077. constructor(entries) {
  3078. super();
  3079. this.type = 'pytorch.package';
  3080. this.entries = entries;
  3081. }
  3082. async read() {
  3083. const execution = new pytorch.Execution();
  3084. for (const event of this._events) {
  3085. execution.on(event[0], event[1]);
  3086. }
  3087. const torch = execution.__import__('torch');
  3088. const reader = new torch.PyTorchFileReader(this.entries);
  3089. const version = reader.version();
  3090. this.format = pytorch.Utility.format('PyTorch Package', version);
  3091. this.modules = new Map();
  3092. const records = reader.get_all_records().filter((name) => {
  3093. if (!name.startsWith('.data/') && !name.endsWith('.py')) {
  3094. const stream = reader.get_record(name);
  3095. if (stream && stream.length > 2) {
  3096. const signature = stream.peek(2);
  3097. if (signature[0] === 0x80 && signature[1] < 7) {
  3098. return true;
  3099. }
  3100. }
  3101. }
  3102. return false;
  3103. });
  3104. const entries = records.map((name) => {
  3105. const parts = name.split('/');
  3106. const resource = parts.pop();
  3107. const module = parts.join('.');
  3108. return [module, resource];
  3109. });
  3110. if (entries.length > 0) {
  3111. for (const name of reader.get_all_records()) {
  3112. if (!name.startsWith('.data/') && name.endsWith('.py')) {
  3113. const stream = reader.get_record(name);
  3114. const buffer = stream.peek();
  3115. execution.add(name, buffer);
  3116. }
  3117. }
  3118. const importer = new torch.package.PackageImporter(reader);
  3119. for (const entry of entries) {
  3120. const module = importer.load_pickle(entry[0], entry[1]);
  3121. const key = `${entry[0].replace(/\./, '/')}/${entry[1]}`;
  3122. this.modules.set(key, module);
  3123. }
  3124. }
  3125. delete this.entries;
  3126. }
  3127. };
  3128. pytorch.MemoryFormat = {
  3129. Contiguous: 0,
  3130. Preserve: 1,
  3131. ChannelsLast: 2,
  3132. ChannelsLast3d: 3
  3133. };
  3134. pytorch.Layout = {
  3135. Strided: 0,
  3136. Sparse: 1,
  3137. Mkldnn: 2
  3138. };
  3139. pytorch.Utility = class {
  3140. static target(expression) {
  3141. if (expression.type === 'id') {
  3142. return expression.value;
  3143. }
  3144. if (expression.type === '.') {
  3145. return `${pytorch.Utility.target(expression.target)}.${pytorch.Utility.target(expression.member)}`;
  3146. }
  3147. return null;
  3148. }
  3149. static isTensor(obj) {
  3150. const name = obj && obj.__class__ ? obj.__class__.__module__ : null;
  3151. switch (name) {
  3152. case 'torch':
  3153. case 'torch.cuda':
  3154. return obj.__class__.__name__.endsWith('Tensor');
  3155. case 'torch.nn.parameter':
  3156. return obj.__class__.__name__ === 'Parameter';
  3157. default:
  3158. return false;
  3159. }
  3160. }
  3161. static toTensor(obj) {
  3162. const name = obj && obj.__class__ ? obj.__class__.__module__ : null;
  3163. switch (name) {
  3164. case 'torch':
  3165. case 'torch.cuda':
  3166. return obj.__class__.__name__.endsWith('Tensor') ? obj : null;
  3167. case 'torch.nn.parameter':
  3168. return obj.__class__.__name__ === 'Parameter' ? obj.data : null;
  3169. default:
  3170. return null;
  3171. }
  3172. }
  3173. static isObjectType(type) {
  3174. switch (type) {
  3175. case '__torch__.torch.classes.xnnpack.LinearOpContext':
  3176. case '__torch__.torch.classes.xnnpack.Conv2dOpContext':
  3177. case '__torch__.torch.classes.xnnpack.TransposeConv2dOpContext':
  3178. case '__torch__.torch.classes.rnn.CellParamsBase':
  3179. case '__torch__.torch.classes.rnn.CellParamsBase[]':
  3180. case '__torch__.torch.classes.quantized.LinearPackedParamsBase':
  3181. case '__torch__.torch.classes.quantized.Conv2dPackedParamsBase':
  3182. case '__torch__.torch.classes.quantized.Conv3dPackedParamsBase':
  3183. return true;
  3184. default:
  3185. return false;
  3186. }
  3187. }
  3188. static isObject(obj) {
  3189. const type = obj && obj.__class__ && obj.__class__.__module__ && obj.__class__.__name__ ? `${obj.__class__.__module__}.${obj.__class__.__name__}` : null;
  3190. return pytorch.Utility.isObjectType(type);
  3191. }
  3192. static getType(value) {
  3193. if (value === null || value === undefined) {
  3194. return undefined;
  3195. } else if (value === true || value === false) {
  3196. return 'boolean';
  3197. } else if (pytorch.Utility.isTensor(value)) {
  3198. return 'Tensor';
  3199. } else if (typeof value === 'string') {
  3200. return 'string';
  3201. } else if (Number(value) === value && value % 1 === 0) {
  3202. return 'int64';
  3203. } else if (Number(value) === value) {
  3204. return 'float32';
  3205. } else if (Array.isArray(value) && value.every((item) => Number(item) === item && item % 1 === 0)) {
  3206. return 'int64[]';
  3207. } else if (Array.isArray(value) && value.every((item) => Number(item) === item)) {
  3208. return 'float32[]';
  3209. }
  3210. const text = (JSON.stringify(value) || '(undefined)').substring(0, 10);
  3211. throw new pytorch.Error(`Unsupported ops argument type '${text}'.`);
  3212. }
  3213. static isType(obj, type) {
  3214. switch (type) {
  3215. case 'Tensor':
  3216. return !Array.isArray(obj) && (pytorch.Utility.isTensor(obj) || obj === null);
  3217. case 'Tensor[]':
  3218. return Array.isArray(obj) && obj.length > 0 && obj.every((tensor) => pytorch.Utility.isTensor(tensor) || tensor === null);
  3219. case 'Scalar':
  3220. return (obj !== null && (obj !== Object(obj) || obj instanceof Number)) || (pytorch.Utility.isTensor(obj) && Array.isArray(obj.size()) && obj.size().length === 0);
  3221. case 'boolean':
  3222. return obj === true || obj === false;
  3223. case 'string':
  3224. return obj === null || typeof obj === 'string';
  3225. case 'SymInt':
  3226. case 'int64':
  3227. return Number.isInteger(obj) || typeof obj === 'bigint' ||
  3228. (typeof obj === 'number' && isNaN(obj)) || (obj instanceof Number);
  3229. case 'SymInt[]':
  3230. case 'SymInt[2]':
  3231. case 'SymInt[3]':
  3232. case 'SymInt[4]':
  3233. case 'SymInt[5]':
  3234. case 'SymInt[6]':
  3235. return Array.isArray(obj) && obj.every((item) => pytorch.Utility.isType(item, 'SymInt') || item === undefined || (item.__class__ === 'number' && isNaN(item)));
  3236. case 'int64[]':
  3237. case 'int64[2]':
  3238. case 'int64[3]':
  3239. return Array.isArray(obj) && obj.every((item) => pytorch.Utility.isType(item, 'int64') || item === undefined || (item.__class__ === 'number' && isNaN(item)));
  3240. case 'int64[1]':
  3241. case 'SymInt[1]':
  3242. return pytorch.Utility.isType(obj, 'int64') || pytorch.Utility.isType(obj, 'int64[]');
  3243. case 'float32':
  3244. case 'float64':
  3245. return obj !== null && (typeof obj === 'number' || obj instanceof Number);
  3246. case 'float32[]':
  3247. return Array.isArray(obj) && obj.every((item) => (typeof item === 'number' || item instanceof Number) && !isNaN(item));
  3248. case 'string[][]':
  3249. return Array.isArray(obj) && obj.every((item) => Array.isArray(item) && item.every((item) => typeof item === 'string'));
  3250. case 'Layout':
  3251. case 'ScalarType':
  3252. case 'MemoryFormat':
  3253. return Number.isInteger(obj) || obj === null;
  3254. case 'Dimname':
  3255. return obj === null || (typeof obj === 'string' || obj instanceof String);
  3256. case 'Dimname[]':
  3257. return Array.isArray(obj) && obj.every((item) => item === null || typeof item === 'string');
  3258. case 'Device':
  3259. return obj === null || obj === Object(obj);
  3260. default:
  3261. if (type && type.startsWith('__torch__.') &&
  3262. obj && obj.__class__ && obj.__class__.__module__ && obj.__class__.__name__) {
  3263. return type === `${obj.__class__.__module__}.${obj.__class__.__name__}`;
  3264. }
  3265. return true;
  3266. }
  3267. }
  3268. static isSubclass(value, name) {
  3269. if (value && value.__module__ && value.__name__) {
  3270. return name === `${value.__module__}.${value.__name__}`;
  3271. } else if (value && value.__bases__) {
  3272. return value.__bases__.some((obj) => pytorch.Utility.isSubclass(obj, name));
  3273. }
  3274. return false;
  3275. }
  3276. static isInstance(value, name) {
  3277. return value && value.__class__ ? pytorch.Utility.isSubclass(value.__class__, name) : false;
  3278. }
  3279. static isCall(expression, name, size) {
  3280. if (expression.type === 'call' &&
  3281. (size === undefined || size === expression.args.length) &&
  3282. pytorch.Utility.target(expression.target) === name) {
  3283. return true;
  3284. }
  3285. return false;
  3286. }
  3287. static isEqual(a, b) {
  3288. return (a.type === 'id' && b.type === 'id' && a.value === b.value);
  3289. }
  3290. static format(name, value) {
  3291. // https://github.com/pytorch/pytorch/blob/master/caffe2/serialize/inline_container.h
  3292. // kProducedFileFormatVersion
  3293. const versions = new Map([
  3294. ['1', 'v1.3'],
  3295. ['2', 'v1.5'], // 7a2889b014ce36fcc333b2c6de6f29f976652f84 (#28122)
  3296. ['3', 'v1.6'], // 2ec6a30722b0ef85632a2f3e7ce6f80da403008a (#36085)
  3297. ['4', 'v1.6'], // 95489b590f00801bdee7f41783f30874883cf6bb (#38620)
  3298. ['5', 'v1.7'], // cb26661fe4faf26386703180a9045e6ac6d157df (#40364)
  3299. ['6', 'v1.9'], // 3ee7637ffa50df0d9b231c7b40778ac1c390bf4a (#59714)
  3300. ['7', 'v1.10'], // 880098a7e34a20628f960daa8eab0eb1ad566c39 (#63651)
  3301. ['8', 'v1.11'], // b28e696516a7f0c7a6ead6da967590ce6c1d6698 (#71486)
  3302. ['9', 'v1.11'], // 8757e21c6a4fc00e83539aa7f9c28eb11eff53c1 (#72051)
  3303. ['10', 'v1.12'] // 4f8b986e28736b59bc46cd0873a0f36fdaa6f5b8 (#61439)
  3304. ]);
  3305. if (!versions.has(value)) {
  3306. throw new pytorch.Error(`Unsupported '${name}' version '${value}'.`);
  3307. }
  3308. return `${name} ${versions.get(value)}`;
  3309. }
  3310. static weights(obj) {
  3311. const type = obj && obj.__class__ && obj.__class__.__module__ && obj.__class__.__name__ ? `${obj.__class__.__module__}.${obj.__class__.__name__}` : null;
  3312. if (type && type !== 'builtins.dict' && type !== 'builtins.object' && type !== 'collections.OrderedDict' && type !== 'torch.nn.modules.module.Module') {
  3313. return null;
  3314. }
  3315. if (pytorch.Utility.isTensor(obj)) {
  3316. return null;
  3317. }
  3318. if (obj instanceof Map === false && obj && !Array.isArray(obj) && Object(obj) === obj) {
  3319. const entries = Object.entries(obj);
  3320. const named = entries.filter(([name, value]) => (typeof name === 'string' && (name.indexOf('.') !== -1 || name.indexOf('|') !== -1)) && pytorch.Utility.isTensor(value));
  3321. if (named.length > 0 && (named.length / entries.length) >= 0.8) {
  3322. obj = new Map(entries);
  3323. }
  3324. }
  3325. if (obj instanceof Map) {
  3326. const entries = Array.from(obj).filter(([name]) => name !== '_metadata');
  3327. const names = entries.filter(([name]) => typeof name === 'string' && (name.indexOf('.') !== -1 || name.indexOf('|') !== -1));
  3328. if (names.length > 1 &&
  3329. (names.length / entries.length) >= 0.8 &&
  3330. entries.every(([, value]) => !pytorch.Utility.isInstance(value, 'builtins.dict') || Array.from(value.values()).every((value) => !pytorch.Utility.isTensor(value)))) {
  3331. const modules = new Map();
  3332. for (const [name, value] of entries) {
  3333. const separator = name.indexOf('.') === -1 && name.indexOf('|') !== -1 ? '|' : '.';
  3334. const path = name.split(separator);
  3335. let property = path.pop();
  3336. if (path.length > 1 && path[path.length - 1] === '_packed_params') {
  3337. property = `${path.pop()}.${property}`;
  3338. }
  3339. const key = path.join(separator);
  3340. if (!modules.has(key)) {
  3341. modules.set(key, {});
  3342. }
  3343. const module = modules.get(key);
  3344. if (pytorch.Utility.isTensor(value)) {
  3345. value.__name__ = name;
  3346. }
  3347. module[property] = value;
  3348. }
  3349. return modules;
  3350. }
  3351. }
  3352. if (obj && !Array.isArray(obj) && Object(obj) === obj) {
  3353. const modules = new Map();
  3354. const entries = obj instanceof Map ? Array.from(obj) : Object.entries(obj);
  3355. if (entries.length > 0 && entries) {
  3356. for (const [key, value] of entries) {
  3357. const name = key.toString();
  3358. if (!value || Object(value) !== value || pytorch.Utility.isTensor(value) || ArrayBuffer.isView(value)) {
  3359. return null;
  3360. }
  3361. if (!modules.has(name)) {
  3362. modules.set(name, {});
  3363. }
  3364. const module = modules.get(name);
  3365. let tensor = false;
  3366. const entries = value instanceof Map ? value : new Map(Object.entries(value));
  3367. for (const [name, value] of entries) {
  3368. if (typeof name !== 'string') {
  3369. return null;
  3370. }
  3371. if (name.indexOf('.') !== -1) {
  3372. return null;
  3373. }
  3374. if (name === '_metadata') {
  3375. continue;
  3376. }
  3377. if (typeof value === 'string' || typeof value === 'number') {
  3378. module[name] = value;
  3379. continue;
  3380. }
  3381. if (pytorch.Utility.isTensor(value)) {
  3382. value.__name__ = name;
  3383. module[name] = value;
  3384. tensor = true;
  3385. }
  3386. }
  3387. if (!tensor) {
  3388. return null;
  3389. }
  3390. }
  3391. return modules;
  3392. }
  3393. }
  3394. return null;
  3395. }
  3396. static isMetadataObject(obj) {
  3397. if (pytorch.Utility.isInstance(obj, 'collections.OrderedDict')) {
  3398. for (const value of obj.values()) {
  3399. if (pytorch.Utility.isInstance(value, 'builtins.dict')) {
  3400. const entries = Array.from(value);
  3401. if (entries.length !== 1 && entries[0] !== 'version' && entries[1] !== 1) {
  3402. return false;
  3403. }
  3404. }
  3405. }
  3406. return true;
  3407. }
  3408. return false;
  3409. }
  3410. };
  3411. pytorch.nnapi = {};
  3412. pytorch.nnapi.SerializedModel = class {
  3413. constructor(serialized_model, buffers) {
  3414. const reader = base.BinaryReader.open(serialized_model);
  3415. this.version = reader.int32();
  3416. if (this.version !== 1) {
  3417. throw new pytorch.Error('Invalid NNAPI serialized model version.');
  3418. }
  3419. const operands = new Array(reader.int32());
  3420. const values = new Array(reader.int32());
  3421. this.operations = new Array(reader.int32());
  3422. this.inputs = new Array(reader.int32());
  3423. this.outputs = new Array(reader.int32());
  3424. const data_types = new Map([
  3425. [0, 'float32'],
  3426. [1, 'int32'],
  3427. [2, 'uint32'],
  3428. [3, 'float32[]'],
  3429. [4, 'int32[]'],
  3430. [5, 'quant8_asymm[]'],
  3431. [6, 'boolean'],
  3432. [7, 'quant16_symm[]'],
  3433. [8, 'float16[]'],
  3434. [9, 'boolean[]'],
  3435. [10, 'float16'],
  3436. [11, 'quant8_symm_per_channel[]'],
  3437. [12, 'quant16_asymm[]'],
  3438. [13, 'quant8_symm[]'],
  3439. [14, 'quant8_asymm_signed[]'],
  3440. [16, 'model']
  3441. ]);
  3442. for (let i = 0; i < operands.length; i++) {
  3443. const data_type = reader.int32();
  3444. operands[i] = {
  3445. index: i,
  3446. data_type: data_types.has(data_type) ? data_types.get(data_type) : data_type,
  3447. dimensions: new Array(reader.uint32()),
  3448. scale: reader.float32(),
  3449. zero_point: reader.int32()
  3450. };
  3451. }
  3452. for (let i = 0; i < values.length; i++) {
  3453. values[i] = {
  3454. index: reader.int32(),
  3455. source_type: reader.int32(),
  3456. source_length: reader.uint32()
  3457. };
  3458. }
  3459. for (let i = 0; i < this.operations.length; i++) {
  3460. this.operations[i] = {
  3461. index: reader.int32(),
  3462. identifier: i,
  3463. inputs: new Array(reader.uint32()),
  3464. outputs: new Array(reader.uint32())
  3465. };
  3466. }
  3467. for (const operand of operands) {
  3468. for (let i = 0; i < operand.dimensions.length; i++) {
  3469. operand.dimensions[i] = reader.uint32();
  3470. }
  3471. }
  3472. for (const value of values) {
  3473. const index = value.index;
  3474. const operand = operands[index];
  3475. switch (value.source_type) {
  3476. case 0: { // immediate
  3477. switch (operand.data_type) {
  3478. case 'boolean':
  3479. operand.value = reader.byte() ? true : false;
  3480. reader.skip(3);
  3481. break;
  3482. case 'int32':
  3483. operand.value = reader.int32();
  3484. break;
  3485. case 'float32':
  3486. operand.value = reader.float32();
  3487. break;
  3488. case 'int32[]':
  3489. operand.data = reader.read(value.source_length);
  3490. break;
  3491. case 'float32[]':
  3492. operand.data = reader.read(value.source_length);
  3493. break;
  3494. default:
  3495. throw new pytorch.Error(`Unsupported NNAPI operand type '${operand.data_type}'.`);
  3496. }
  3497. break;
  3498. }
  3499. case 2: { // numbered buffer
  3500. if (value.source_length !== 12) {
  3501. throw new pytorch.Error('Invalid NNAPI numbered buffer source length.');
  3502. }
  3503. const number = reader.uint32();
  3504. const offset = reader.uint32();
  3505. const operand_length = reader.uint32();
  3506. const storage = buffers[number];
  3507. const data = storage.data && storage.data.peek ? storage.data.peek() : storage.data;
  3508. operand.data = data.slice(offset, operand_length);
  3509. break;
  3510. }
  3511. case 3: { // numbered memory
  3512. throw new pytorch.Error('NNAPI numbered memory buffer not implemented.');
  3513. }
  3514. default: {
  3515. throw new pytorch.Error('Unsupported NNAPI value source type.');
  3516. }
  3517. }
  3518. }
  3519. for (const operation of this.operations) {
  3520. for (let i = 0; i < operation.inputs.length; i++) {
  3521. const index = reader.uint32();
  3522. operation.inputs[i] = operands[index];
  3523. }
  3524. for (let i = 0; i < operation.outputs.length; i++) {
  3525. const index = reader.uint32();
  3526. operation.outputs[i] = operands[index];
  3527. }
  3528. }
  3529. for (let i = 0; i < this.inputs.length; i++) {
  3530. const index = reader.uint32();
  3531. this.inputs[i] = operands[index];
  3532. }
  3533. for (let i = 0; i < this.outputs.length; i++) {
  3534. const index = reader.uint32();
  3535. this.outputs[i] = operands[index];
  3536. }
  3537. if (reader.position !== reader.length) {
  3538. throw new pytorch.Error('Invalid NNAPI serialized model length.');
  3539. }
  3540. }
  3541. };
  3542. pytorch.nnapi.Graph = class {
  3543. constructor(model) {
  3544. this.name = 'torch.classes._nnapi.Compilation';
  3545. this.nodes = [];
  3546. this.inputs = [];
  3547. this.outputs = [];
  3548. const values = new Map();
  3549. values.map = (operand) => {
  3550. if (!values.has(operand.index)) {
  3551. const name = operand.index.toString();
  3552. const dimensions = operand.dimensions;
  3553. const shape = new pytorch.TensorShape(dimensions);
  3554. let dataType = operand.data_type.replace('[]', '');
  3555. let quantization = null;
  3556. switch (dataType) {
  3557. case 'quant8_asymm':
  3558. case 'quant8_symm_per_channel':
  3559. case 'quant8_symm':
  3560. case 'quant8_asymm_signed[]':
  3561. case 'quant16_asymm':
  3562. case 'quant16_symm':
  3563. quantization = dataType;
  3564. dataType = dataType.indexOf('16') === -1 ? 'uint8' : 'uint16';
  3565. break;
  3566. default:
  3567. break;
  3568. }
  3569. const type = new pytorch.TensorType(dataType, shape);
  3570. let initializer = null;
  3571. if (operand.data) {
  3572. const size = dimensions.reduce((a, b) => a * b, 1);
  3573. const tensor = {
  3574. size: () => dimensions,
  3575. stride: () => null,
  3576. storage_offset: () => 0,
  3577. storage: () => ({
  3578. dtype: { __reduce__: () => type.dataType },
  3579. data: operand.data, size: () => size
  3580. })
  3581. };
  3582. initializer = new pytorch.Tensor(null, tensor);
  3583. }
  3584. if (quantization || (operand.scale !== undefined && operand.scale !== 0) || (operand.zero_point !== undefined && operand.zero_point !== 0)) {
  3585. quantization = {
  3586. type: quantization || 'linear',
  3587. scale: [operand.scale],
  3588. offset: [operand.zero_point]
  3589. };
  3590. }
  3591. const value = new pytorch.Value(name, type, quantization, initializer);
  3592. values.set(operand.index, value);
  3593. }
  3594. return values.get(operand.index);
  3595. };
  3596. const metadata = new pytorch.nnapi.Metadata();
  3597. for (const operation of model.operations) {
  3598. const node = new pytorch.nnapi.Node(metadata, operation, values);
  3599. this.nodes.push(node);
  3600. }
  3601. for (let i = 0; i < model.inputs.length; i++) {
  3602. const name = i.toString();
  3603. const operand = model.inputs[i];
  3604. const argument = new pytorch.Argument(name, [values.map(operand)]);
  3605. this.inputs.push(argument);
  3606. }
  3607. for (let i = 0; i < model.outputs.length; i++) {
  3608. const name = i.toString();
  3609. const operand = model.outputs[i];
  3610. const argument = new pytorch.Argument(name, [values.map(operand)]);
  3611. this.outputs.push(argument);
  3612. }
  3613. }
  3614. };
  3615. pytorch.nnapi.Node = class {
  3616. constructor(metadata, operation, values) {
  3617. const signature = (operation.inputs || []).map((input) => input.data_type);
  3618. this.name = '';
  3619. this.type = metadata.type(operation.index, signature);
  3620. this.inputs = [];
  3621. this.outputs = [];
  3622. this.attributes = [];
  3623. this.chain = [];
  3624. if (operation.identifier !== undefined) {
  3625. this.identifier = operation.identifier.toString();
  3626. }
  3627. if (Array.isArray(operation.inputs)) {
  3628. const inputs = this.type.inputs;
  3629. for (let i = 0; i < operation.inputs.length; i++) {
  3630. const name = i < inputs.length ? inputs[i].name : i.toString();
  3631. const operand = operation.inputs[i];
  3632. if (operand.dimensions.length > 0) {
  3633. const value = values.map(operand);
  3634. const argument = new pytorch.Argument(name, [value]);
  3635. this.inputs.push(argument);
  3636. } else if (name === 'activation') {
  3637. const activation = new Map([[1, 19], [2, 20], [3, 21]]).get(operand.value) || 0;
  3638. if (activation !== 0) {
  3639. this.chain.push(new pytorch.nnapi.Node(metadata, { index: activation }));
  3640. }
  3641. } else {
  3642. const attribute = new pytorch.Argument(name, operand.value, operand.data_type, false);
  3643. this.inputs.push(attribute);
  3644. }
  3645. }
  3646. }
  3647. if (Array.isArray(operation.outputs)) {
  3648. const outputs = this.type.outputs;
  3649. for (let i = 0; i < operation.outputs.length; i++) {
  3650. const name = i < outputs.length ? outputs[i].name : i.toString();
  3651. const operand = operation.outputs[i];
  3652. const value = values.map(operand);
  3653. const argument = new pytorch.Argument(name, [value]);
  3654. this.outputs.push(argument);
  3655. }
  3656. }
  3657. }
  3658. };
  3659. pytorch.nnapi.Metadata = class {
  3660. constructor() {
  3661. this._types = new Map();
  3662. // https://developer.android.com/ndk/reference/group/neural-networks
  3663. // https://github.com/pytorch/pytorch/commits/master/torch/backends/_nnapi/serializer.py
  3664. this.register(0, 'ADD', '', ['A', 'B'], [['activation', 'int32']], ['C']);
  3665. 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']);
  3666. 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']);
  3667. this.register(2, 'CONCATENATION');
  3668. 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']);
  3669. 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']);
  3670. 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']);
  3671. 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']);
  3672. this.register(5, 'DEPTH_TO_SPACE');
  3673. this.register(6, 'DEQUANTIZE');
  3674. this.register(7, 'EMBEDDING_LOOKUP');
  3675. this.register(8, 'FLOOR');
  3676. this.register(9, 'FULLY_CONNECTED', 'Layer', ['input', 'weights', 'bias'], [['activation', 'int32']], ['output']);
  3677. this.register(10, 'HASHTABLE_LOOKUP');
  3678. this.register(11, 'L2_NORMALIZATION');
  3679. this.register(12, 'L2_POOL_2D', 'Pool');
  3680. this.register(13, 'LOCAL_RESPONSE_NORMALIZATION');
  3681. this.register(14, 'LOGISTIC');
  3682. this.register(15, 'LSH_PROJECTION');
  3683. this.register(16, 'LSTM', 'Layer');
  3684. this.register(17, 'MAX_POOL_2D', 'Pool');
  3685. this.register(18, 'MUL');
  3686. this.register(19, 'RELU', 'Activation', ['input'], [], ['output']);
  3687. this.register(20, 'RELU1', 'Activation');
  3688. this.register(21, 'RELU6', 'Activation');
  3689. this.register(22, 'RESHAPE', 'Shape', ['input', 'shape'], [], ['output']);
  3690. this.register(23, 'RESIZE_BILINEAR');
  3691. this.register(24, 'RNN', 'Layer');
  3692. this.register(25, 'SOFTMAX', 'Activation');
  3693. this.register(26, 'SPACE_TO_DEPTH');
  3694. this.register(27, 'SVDF');
  3695. this.register(28, 'TANH');
  3696. this.register(29, 'BATCH_TO_SPACE_ND');
  3697. this.register(30, 'DIV');
  3698. this.register(31, 'MEAN');
  3699. this.register(32, 'PAD');
  3700. this.register(33, 'SPACE_TO_BATCH_ND');
  3701. this.register(34, 'SQUEEZE');
  3702. this.register(35, 'STRIDED_SLICE');
  3703. this.register(36, 'SUB');
  3704. this.register(37, 'TRANSPOSE');
  3705. this.register(38, 'ABS');
  3706. this.register(39, 'ARGMAX');
  3707. this.register(40, 'ARGMIN');
  3708. this.register(41, 'AXIS_ALIGNED_BBOX_TRANSFORM');
  3709. this.register(42, 'BIDIRECTIONAL_SEQUENCE_LSTM');
  3710. this.register(43, 'BIDIRECTIONAL_SEQUENCE_RNN');
  3711. this.register(44, 'BOX_WITH_NMS_LIMIT');
  3712. this.register(45, 'CAST');
  3713. this.register(46, 'CHANNEL_SHUFFLE');
  3714. this.register(47, 'DETECTION_POSTPROCESSING');
  3715. this.register(48, 'EQUAL');
  3716. this.register(49, 'EXP');
  3717. this.register(50, 'EXPAND_DIMS');
  3718. this.register(51, 'GATHER');
  3719. this.register(52, 'GENERATE_PROPOSALS');
  3720. this.register(53, 'GREATER');
  3721. this.register(54, 'GREATER_EQUAL');
  3722. this.register(55, 'GROUPED_CONV_2D');
  3723. this.register(56, 'HEATMAP_MAX_KEYPOINT');
  3724. this.register(57, 'INSTANCE_NORMALIZATION');
  3725. this.register(58, 'LESS');
  3726. this.register(59, 'LESS_EQUAL');
  3727. this.register(60, 'LOG');
  3728. this.register(61, 'LOGICAL_AND');
  3729. this.register(62, 'LOGICAL_NOT');
  3730. this.register(63, 'LOGICAL_OR');
  3731. this.register(64, 'LOG_SOFTMAX');
  3732. this.register(65, 'MAXIMUM');
  3733. this.register(66, 'MINIMUM');
  3734. this.register(67, 'NEG');
  3735. this.register(68, 'NOT_EQUAL');
  3736. this.register(69, 'PAD_V2');
  3737. this.register(70, 'POW');
  3738. this.register(71, 'PRELU');
  3739. this.register(72, 'QUANTIZE');
  3740. this.register(73, 'QUANTIZED_16BIT_LSTM');
  3741. this.register(74, 'RANDOM_MULTINOMIAL');
  3742. this.register(75, 'REDUCE_ALL');
  3743. this.register(76, 'REDUCE_ANY');
  3744. this.register(77, 'REDUCE_MAX');
  3745. this.register(78, 'REDUCE_MIN');
  3746. this.register(79, 'REDUCE_PROD');
  3747. this.register(80, 'REDUCE_SUM');
  3748. this.register(81, 'ROI_ALIGN');
  3749. this.register(82, 'ROI_POOLING');
  3750. this.register(83, 'RSQRT');
  3751. this.register(84, 'SELECT');
  3752. this.register(85, 'SIN');
  3753. this.register(86, 'SLICE');
  3754. this.register(87, 'SPLIT');
  3755. this.register(88, 'SQRT');
  3756. this.register(89, 'TILE');
  3757. this.register(90, 'TOPK_V2');
  3758. this.register(91, 'TRANSPOSE_CONV_2D', 'Layer');
  3759. this.register(92, 'UNIDIRECTIONAL_SEQUENCE_LSTM', 'Layer');
  3760. this.register(93, 'UNIDIRECTIONAL_SEQUENCE_RNN', 'Layer');
  3761. this.register(94, 'RESIZE_NEAREST_NEIGHBOR');
  3762. this.register(95, 'QUANTIZED_LSTM', 'Layer');
  3763. this.register(96, 'IF');
  3764. this.register(97, 'WHILE');
  3765. this.register(98, 'ELU', 'Activation');
  3766. this.register(99, 'HARD_SWISH', 'Activation');
  3767. this.register(100, 'FILL');
  3768. this.register(101, 'RANK');
  3769. }
  3770. register(index, name, category, inputs, attributes, outputs) {
  3771. inputs = inputs || [];
  3772. outputs = outputs || [];
  3773. attributes = attributes || [];
  3774. const type = {};
  3775. type.name = name;
  3776. type.inputs = inputs.map((name) => ({ name, type: 'Tensor' }));
  3777. type.inputs = type.inputs.concat(attributes.map(([name, type]) => ({ name, type })));
  3778. type.outputs = outputs.map((name) => ({ name, type: 'Tensor' }));
  3779. if (category) {
  3780. type.category = category;
  3781. }
  3782. if (!this._types.has(index)) {
  3783. this._types.set(index, []);
  3784. }
  3785. this._types.get(index).push(type);
  3786. }
  3787. type(index, signature) {
  3788. if (!this._types.has(index)) {
  3789. this._types.set(index, { name: index.toString(), inputs: [], outputs: [], attributes: [] });
  3790. }
  3791. const types = this._types.get(index);
  3792. for (const type of types) {
  3793. const inputs = type.inputs;
  3794. if (signature.length < inputs.length) {
  3795. if (inputs.every((input, i) => input.type === undefined || input.type === 'Tensor' || input.type === signature[i])) {
  3796. return type;
  3797. }
  3798. }
  3799. }
  3800. return types[0];
  3801. }
  3802. };
  3803. pytorch.Metadata = class {
  3804. static async open(context) {
  3805. if (!pytorch.Metadata._metadata) {
  3806. let data = null;
  3807. try {
  3808. data = await context.request('pytorch-metadata.json');
  3809. } catch {
  3810. // continue regardless of error
  3811. }
  3812. pytorch.Metadata._metadata = new pytorch.Metadata(data);
  3813. }
  3814. return pytorch.Metadata._metadata;
  3815. }
  3816. constructor(data) {
  3817. this._types = new Map();
  3818. this._attributes = new Map();
  3819. this._index = new Map();
  3820. if (data) {
  3821. const items = JSON.parse(data);
  3822. for (const item of items) {
  3823. this._types.set(item.name, item);
  3824. }
  3825. }
  3826. }
  3827. add(name, value) {
  3828. this._types.set(name, value);
  3829. }
  3830. type(name) {
  3831. return this._types.get(name);
  3832. }
  3833. attribute(type, name) {
  3834. const key = `${type}:${name}`;
  3835. if (!this._attributes.has(key)) {
  3836. this._attributes.set(key, null);
  3837. const metadata = this.type(type);
  3838. if (metadata) {
  3839. if (metadata.inputs) {
  3840. for (const input of metadata.inputs) {
  3841. this._attributes.set(`${type}:${input.name}`, input);
  3842. }
  3843. }
  3844. if (metadata.attributes) {
  3845. for (const attribute of metadata.attributes) {
  3846. this._attributes.set(`${type}:${attribute.name}`, attribute);
  3847. }
  3848. }
  3849. }
  3850. }
  3851. return this._attributes.get(key);
  3852. }
  3853. };
  3854. numpy.Tensor = class {
  3855. constructor(array) {
  3856. this.type = new numpy.TensorType(array.dtype.__name__, new numpy.TensorShape(array.shape));
  3857. this.stride = array.strides.map((stride) => stride / array.itemsize);
  3858. this.values = this.type.dataType === 'string' || this.type.dataType === 'object' || this.type.dataType === 'void' ? array.flatten().tolist() : array.tobytes();
  3859. this.encoding = this.type.dataType === 'string' || this.type.dataType === 'object' ? '|' : array.dtype.byteorder;
  3860. }
  3861. };
  3862. numpy.TensorType = class {
  3863. constructor(dataType, shape) {
  3864. this.dataType = dataType || '?';
  3865. this.shape = shape;
  3866. }
  3867. toString() {
  3868. return this.dataType + this.shape.toString();
  3869. }
  3870. };
  3871. numpy.TensorShape = class {
  3872. constructor(dimensions) {
  3873. this.dimensions = dimensions;
  3874. }
  3875. toString() {
  3876. return this.dimensions && this.dimensions.length > 0 ? `[${this.dimensions.join(',')}]` : '';
  3877. }
  3878. };
  3879. pytorch.Error = class extends Error {
  3880. constructor(message) {
  3881. super(message);
  3882. this.name = 'Error loading PyTorch model.';
  3883. }
  3884. };
  3885. export const ModelFactory = pytorch.ModelFactory;