tf.js 113 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718
  1. // Experimental
  2. var tf = tf || {};
  3. var base = base || require('./base');
  4. var gzip = gzip || require('./gzip');
  5. var json = json || require('./json');
  6. var protobuf = protobuf || require('./protobuf');
  7. tf.ModelFactory = class {
  8. match(context) {
  9. const identifier = context.identifier;
  10. const extension = identifier.split('.').pop().toLowerCase();
  11. if (extension === 'pbtxt' || extension === 'prototxt' || extension === 'pt' || extension === 'txt') {
  12. if (identifier.endsWith('predict_net.pbtxt') || identifier.endsWith('predict_net.prototxt') ||
  13. identifier.endsWith('init_net.pbtxt') || identifier.endsWith('init_net.prototxt')) {
  14. return undefined;
  15. }
  16. const tags = context.tags('pbtxt');
  17. if (['input_stream', 'output_stream', 'input_side_packet', 'output_side_packet'].some((key) => tags.has(key) || tags.has('node.' + key))) {
  18. return undefined;
  19. }
  20. if (tags.has('saved_model_schema_version') || tags.has('meta_graphs')) {
  21. return 'tf.pbtxt.SavedModel';
  22. }
  23. if (tags.has('graph_def')) {
  24. return 'tf.pbtxt.MetaGraphDef';
  25. }
  26. if (tags.has('node')) {
  27. return 'tf.pbtxt.GraphDef';
  28. }
  29. }
  30. if (extension === 'pb' || extension === 'pbtxt' || extension === 'prototxt' || extension === 'graphdef' || extension === 'meta') {
  31. if (identifier.endsWith('predict_net.pb') || identifier.endsWith('init_net.pb')) {
  32. return undefined;
  33. }
  34. if (identifier == 'tfhub_module.pb') {
  35. const stream = context.stream;
  36. const signature = [ 0x08, 0x03 ];
  37. if (signature.length === stream.length && stream.peek(signature.length).every((value, index) => value === signature[index])) {
  38. return undefined;
  39. }
  40. }
  41. const tags = context.tags('pb');
  42. if (tags.size > 0) {
  43. if (Array.from(tags).every((pair) => pair[0] < 8 && pair[1] !== 5)) {
  44. const match = (tags, schema) => {
  45. for (const pair of schema) {
  46. const key = pair[0];
  47. const inner = pair[1];
  48. const value = tags[key];
  49. if (value === undefined) {
  50. continue;
  51. }
  52. if (inner === false) {
  53. return false;
  54. }
  55. if (Array.isArray(inner)) {
  56. if (typeof value !== 'object' || !match(value, inner)) {
  57. return false;
  58. }
  59. }
  60. else if (inner !== value) {
  61. if (inner === 2 && !Array.isArray(value) && Object(value) === (value) && Object.keys(value).length === 0) {
  62. return true;
  63. }
  64. return false;
  65. }
  66. }
  67. return true;
  68. };
  69. const signatureGraphDef = [
  70. [1 /* node */, [
  71. [1 /* name */, 2],
  72. [2 /* op */, 2],
  73. [3 /* input */, 2],
  74. [4 /* device */,2],
  75. [5 /* attr */, [
  76. [1,2],
  77. [2,[]]
  78. ]],
  79. [6 /* experimental_debug_info */, []]
  80. ]],
  81. [2 /* library */, []],
  82. [3 /* version */, 0],
  83. [4 /* versions */, [[1,0],[2,0]]]
  84. ];
  85. const signatureMetaGraphDef = [
  86. [1 /* meta_info_def */, [[1,2],[2,[]],[3,[]],[4,2],[6,2],[7,0],[8,[]]]],
  87. [2 /* graph_def */, signatureGraphDef],
  88. [3 /* saver_def */, [[1,2],[2,2],[3,2],[4,0],[5,0],[6,5],[7,0]]],
  89. [4 /* collection_def */,[]],
  90. [5 /* signature_def */, []],
  91. [6 /* asset_file_def */, []],
  92. [7 /* object_graph_def */, []]
  93. ];
  94. const signatureSavedModel = [[1,0],[2,signatureMetaGraphDef]];
  95. if (tags.size === 1 && tags.get(1) === 2) {
  96. const tags = context.tags('pb+');
  97. // mediapipe.BoxDetectorIndex
  98. if (match(tags, [[1,[[1,[[1,[[1,5],[2,5],[3,5],[4,5],[6,0],[7,5],[8,5],[10,5],[11,0],[12,0]]],[2,5],[3,[]]]],[2,false],[3,false],[4,false],[5,false]]],[2,false],[3,false]] )) {
  99. return undefined;
  100. }
  101. // third_party.tensorflow.python.keras.protobuf.SavedMetadata
  102. if (match(tags, [[1,[[1,[[1,0],[2,0]]],[2,0],[3,2],[4,2],[5,2]]]])) {
  103. return 'tf.pb.keras.SavedMetadata';
  104. }
  105. }
  106. if ((!tags.has(1) || tags.get(1) === 0) && tags.get(2) === 2) {
  107. const tags = context.tags('pb+');
  108. if (match(tags, signatureSavedModel)) {
  109. return 'tf.pb.SavedModel';
  110. }
  111. }
  112. if ((!tags.has(1) || tags.get(1) === 2) &&
  113. (!tags.has(2) || tags.get(2) === 2) &&
  114. (!tags.has(3) || tags.get(3) === 2) &&
  115. (!tags.has(4) || tags.get(4) === 2)) {
  116. const tags = context.tags('pb+');
  117. if (match(tags, signatureMetaGraphDef)) {
  118. return 'tf.pb.MetaGraphDef';
  119. }
  120. }
  121. if (tags.get(1) !== 2) {
  122. const tags = context.tags('pb+');
  123. if (match(tags, signatureGraphDef)) {
  124. return 'tf.pb.GraphDef';
  125. }
  126. }
  127. const decode = (buffer, value) => {
  128. const reader = protobuf.BinaryReader.open(buffer);
  129. const length = reader.length;
  130. while (reader.position < length) {
  131. const tag = reader.uint32();
  132. const number = tag >>> 3;
  133. const type = tag & 7;
  134. if (value === number) {
  135. return type === 2 ? reader.bytes() : null;
  136. }
  137. reader.skipType(type);
  138. }
  139. return null;
  140. };
  141. const stream = context.stream;
  142. const buffer = stream.peek();
  143. const nodeBuffer = decode(buffer, 1);
  144. if (nodeBuffer) {
  145. const nameBuffer = decode(nodeBuffer, 1);
  146. if (nameBuffer) {
  147. const decoder = new TextDecoder('utf-8');
  148. const name = decoder.decode(nameBuffer);
  149. if (Array.from(name).filter((c) => c <= ' ').length < 256) {
  150. return 'tf.pb.GraphDef';
  151. }
  152. }
  153. }
  154. }
  155. }
  156. else {
  157. const tags = context.tags('pbtxt');
  158. if (['input_stream', 'output_stream', 'input_side_packet', 'output_side_packet'].some((key) => tags.has(key) || tags.has('node.' + key))) {
  159. return undefined;
  160. }
  161. if (tags.has('node')) {
  162. return 'tf.pbtxt.GraphDef';
  163. }
  164. if (tags.has('graph_def')) {
  165. return 'tf.pbtxt.MetaGraphDef';
  166. }
  167. if (tags.has('saved_model_schema_version') || tags.has('meta_graphs')) {
  168. return 'tf.pbtxt.SavedModel';
  169. }
  170. }
  171. }
  172. if (extension === 'json') {
  173. for (const type of [ 'json', 'json.gz' ]) {
  174. const obj = context.open(type);
  175. if (obj && obj.modelTopology && (obj.format === 'graph-model' || Array.isArray(obj.modelTopology.node))) {
  176. return 'tf.' + type;
  177. }
  178. }
  179. }
  180. if (extension === 'index' || extension === 'ckpt') {
  181. const stream = context.stream;
  182. if (stream.length > 8) {
  183. stream.seek(-8);
  184. const buffer = stream.read(8);
  185. stream.seek(0);
  186. const signature = [ 0x57, 0xfb, 0x80, 0x8b, 0x24, 0x75, 0x47, 0xdb ];
  187. if (buffer.every((value, index) => value === signature[index])) {
  188. return 'tf.bundle';
  189. }
  190. }
  191. }
  192. if (/.data-[0-9][0-9][0-9][0-9][0-9]-of-[0-9][0-9][0-9][0-9][0-9]$/.exec(identifier)) {
  193. return 'tf.data';
  194. }
  195. if (/^events.out.tfevents./.exec(identifier)) {
  196. const stream = context.stream;
  197. if (tf.EventFileReader.open(stream)) {
  198. return 'tf.events';
  199. }
  200. }
  201. if (extension === 'pbmm') {
  202. const stream = context.stream;
  203. if (stream.length > 8) {
  204. stream.seek(-8);
  205. const buffer = stream.read(8);
  206. stream.seek(0);
  207. const offset = new base.BinaryReader(buffer).uint64();
  208. if (offset < stream.length) {
  209. return 'tf.pb.mmap';
  210. }
  211. }
  212. }
  213. return undefined;
  214. }
  215. open(context, match) {
  216. return context.require('./tf-proto').then(() => {
  217. tf.proto = protobuf.get('tf');
  218. const openModel = (saved_model, format, producer, bundle) => {
  219. return tf.Metadata.open(context).then((metadata) => {
  220. return new tf.Model(metadata, saved_model, format, producer, bundle);
  221. });
  222. };
  223. const openSavedModel = (saved_model, format, producer) => {
  224. if (saved_model.meta_graphs.length === 1 &&
  225. saved_model.meta_graphs[0].object_graph_def &&
  226. saved_model.meta_graphs[0].object_graph_def.nodes &&
  227. saved_model.meta_graphs[0].object_graph_def.nodes.length > 0) {
  228. const identifier = 'variables/variables.index';
  229. return context.request(identifier, null).then((stream) => {
  230. return tf.TensorBundle.open(stream, identifier, context).then((bundle) => {
  231. return openModel(saved_model, format, producer, bundle);
  232. });
  233. }).catch(() => {
  234. return openModel(saved_model, format, producer, null);
  235. });
  236. }
  237. if (saved_model && saved_model.meta_graphs && saved_model.meta_graphs.length > 0 &&
  238. saved_model.meta_graphs[0].meta_info_def &&
  239. Object.prototype.hasOwnProperty.call(saved_model.meta_graphs[0].meta_info_def, 'tensorflow_version')) {
  240. producer = 'TensorFlow v' + saved_model.meta_graphs[0].meta_info_def.tensorflow_version;
  241. }
  242. return openModel(saved_model, format, producer, null);
  243. };
  244. const openBundle = (context, stream, identifier) => {
  245. stream = stream || context.stream;
  246. identifier = identifier || context.identifier;
  247. return tf.TensorBundle.open(stream, identifier, context).then((bundle) => {
  248. return openModel(null, 'TensorFlow Tensor Bundle v' + bundle.format.toString(), null, bundle);
  249. }).catch((error) => {
  250. context.exception(error, false);
  251. const message = error && error.message ? error.message : error.toString();
  252. throw new tf.Error(message.replace(/\.$/, '') + " in '" + identifier + "'.");
  253. });
  254. };
  255. const openData = (context) => {
  256. const identifier = context.identifier;
  257. const base = identifier.split('.');
  258. base.pop();
  259. const file = base.join('.') + '.index';
  260. return context.request(file, null).then((stream) => {
  261. return openBundle(context, stream, file);
  262. }).catch((/* error */) => {
  263. const file = base.join('.') + '.ckpt';
  264. return context.request(file, null).then((stream) => {
  265. openBundle(context, stream, file);
  266. });
  267. });
  268. };
  269. const openEventFile = (context) => {
  270. let format = 'TensorFlow Event File';
  271. let producer = null;
  272. const stream = context.stream;
  273. const eventFileReader = tf.EventFileReader.open(stream);
  274. const saved_model = new tf.proto.tensorflow.SavedModel();
  275. const run_metadata = [];
  276. const summaries = [];
  277. for (;;) {
  278. const event = eventFileReader.read();
  279. if (!event) {
  280. break;
  281. }
  282. switch (event.what) {
  283. case 'file_version': {
  284. const formats = new Map([
  285. [ 'brain.Event:1', 'TensorFlow Event File v1' ],
  286. [ 'brain.Event:2', 'TensorFlow Event File v2' ]
  287. ]);
  288. if (!formats.has(event.file_version)) {
  289. throw new tf.Error("Unsupported event file version '" + event.file_version + "'.");
  290. }
  291. format = formats.get(event.file_version);
  292. break;
  293. }
  294. case 'graph_def': {
  295. const buffer = event.graph_def;
  296. const reader = protobuf.BinaryReader.open(buffer);
  297. const graph_def = tf.proto.tensorflow.GraphDef.decode(reader);
  298. const meta_graph_def = new tf.proto.tensorflow.MetaGraphDef();
  299. meta_graph_def.meta_info_def = new tf.proto.tensorflow.MetaGraphDef.MetaInfoDef();
  300. meta_graph_def.meta_info_def.any_info = event.wall_time.toString();
  301. meta_graph_def.graph_def = graph_def;
  302. saved_model.meta_graphs.push(meta_graph_def);
  303. break;
  304. }
  305. case 'meta_graph_def': {
  306. const buffer = event.meta_graph_def;
  307. const reader = protobuf.BinaryReader.open(buffer);
  308. const meta_graph_def = tf.proto.tensorflow.MetaGraphDef.decode(reader);
  309. saved_model.meta_graphs.push(meta_graph_def);
  310. break;
  311. }
  312. case 'summary': {
  313. for (const value of event.summary.value) {
  314. summaries.push(value);
  315. }
  316. break;
  317. }
  318. case 'tagged_run_metadata': {
  319. const entry = event.tagged_run_metadata;
  320. const buffer = entry.run_metadata;
  321. const reader = protobuf.BinaryReader.open(buffer);
  322. const metadata = tf.proto.tensorflow.RunMetadata.decode(reader);
  323. run_metadata.push(metadata);
  324. break;
  325. }
  326. default: {
  327. throw new tf.Error("Unsupported event type '" + event.what + "'.");
  328. }
  329. }
  330. }
  331. if (saved_model.meta_graphs.every((meta_graph) => meta_graph.graph_def.node.every((node) => node.op.startsWith('aten::') || node.op.startsWith('prim::') || node.op === 'IO Node'))) {
  332. producer = 'PyTorch';
  333. const openPyTorchMetadata = (context, saved_model) => {
  334. return context.request('pytorch-metadata.json', 'utf-8', null).then((data) => {
  335. const metadata = new Map();
  336. for (const item of JSON.parse(data)) {
  337. const index = item.name.indexOf(':');
  338. const key = (index !== -1) ? item.name.substring(0, index) : item.name;
  339. const name = key.replace(/^torch\./, 'aten::');
  340. if (!metadata.has(name)) {
  341. metadata.set(name, []);
  342. }
  343. metadata.get(name).push(item);
  344. }
  345. for (const meta_graph of saved_model.meta_graphs) {
  346. for (const node of meta_graph.graph_def.node) {
  347. node.__metadata__ = Array.from(metadata.get(node.op) || []);
  348. }
  349. }
  350. return saved_model;
  351. }).catch(() => {
  352. return saved_model;
  353. });
  354. };
  355. return openPyTorchMetadata(context, saved_model).then((saved_model) => {
  356. return openModel(saved_model, format, producer, null);
  357. });
  358. }
  359. return openSavedModel(saved_model, format, producer);
  360. };
  361. const openJson = (context, type) => {
  362. try {
  363. const obj = context.open(type);
  364. const format = 'TensorFlow.js ' + (obj.format || 'graph-model');
  365. const producer = obj.convertedBy || obj.generatedBy || '';
  366. const meta_graph = new tf.proto.tensorflow.MetaGraphDef();
  367. meta_graph.graph_def = tf.JsonReader.decodeGraphDef(obj.modelTopology);
  368. const saved_model = new tf.proto.tensorflow.SavedModel();
  369. saved_model.meta_graphs.push(meta_graph);
  370. const nodes = new Map();
  371. for (const node of meta_graph.graph_def.node) {
  372. node.input = node.input || [];
  373. if (node.op === 'Const') {
  374. nodes.set(node.name, node);
  375. }
  376. }
  377. const shards = new Map();
  378. const manifests = Array.isArray(obj.weightsManifest) ? obj.weightsManifest : [];
  379. for (const manifest of manifests) {
  380. for (const path of manifest.paths) {
  381. if (!shards.has(path)) {
  382. shards.set(path, context.request(path, null));
  383. }
  384. }
  385. }
  386. const openShards = (shards) => {
  387. const dtype_size_map = new Map([ [ 'float16', 2 ], [ 'float32', 4 ], [ 'float64', 8 ], [ 'int8', 1 ], [ 'int16', 2 ], [ 'int32', 4 ], [ 'int64', 8 ], [ 'uint8', 1 ], [ 'uint16', 2 ], [ 'uint32', 4 ], [ 'uint64', 8 ], [ 'bool', 1 ] ]);
  388. for (const manifest of manifests) {
  389. let buffer = null;
  390. if (Array.isArray(manifest.paths) && manifest.paths.length > 0 && manifest.paths.every((path) => shards.has(path))) {
  391. const list = manifest.paths.map((path) => shards.get(path));
  392. const size = list.reduce((a, b) => a + b.length, 0);
  393. buffer = new Uint8Array(size);
  394. let offset = 0;
  395. for (const item of list) {
  396. buffer.set(item, offset);
  397. offset += item.length;
  398. }
  399. }
  400. let offset = 0;
  401. for (const weight of manifest.weights) {
  402. const dtype = weight.quantization && weight.quantization.dtype ? weight.quantization.dtype : weight.dtype;
  403. const size = weight.shape.reduce((a, b) => a * b, 1);
  404. switch (dtype) {
  405. case 'string': {
  406. const data = [];
  407. if (buffer && size > 0) {
  408. const reader = new tf.BinaryReader(buffer.subarray(offset));
  409. for (let i = 0; i < size; i++) {
  410. data[i] = reader.string();
  411. }
  412. offset += reader.position;
  413. }
  414. if (nodes.has(weight.name)) {
  415. const node = nodes.get(weight.name);
  416. node.attr.value.tensor.dtype = tf.Utility.dataTypeKey(dtype);
  417. node.attr.value.tensor.string_val = data;
  418. }
  419. break;
  420. }
  421. default: {
  422. if (!dtype_size_map.has(dtype)) {
  423. throw new tf.Error("Unsupported weight data type size '" + dtype + "'.");
  424. }
  425. const itemsize = dtype_size_map.get(dtype);
  426. const length = itemsize * size;
  427. const tensor_content = buffer ? buffer.slice(offset, offset + length) : null;
  428. offset += length;
  429. if (nodes.has(weight.name)) {
  430. const node = nodes.get(weight.name);
  431. node.attr.value.tensor.dtype = tf.Utility.dataTypeKey(dtype);
  432. node.attr.value.tensor.tensor_content = tensor_content;
  433. }
  434. break;
  435. }
  436. }
  437. }
  438. }
  439. return openSavedModel(saved_model, format, producer, null);
  440. };
  441. return Promise.all(shards.values()).then((streams) => {
  442. for (const key of shards.keys()) {
  443. const stream = streams.shift();
  444. const buffer = stream.peek();
  445. shards.set(key, buffer);
  446. }
  447. if (type === 'json.gz') {
  448. try {
  449. for (const key of shards.keys()) {
  450. const stream = shards.get(key);
  451. const archive = gzip.Archive.open(stream);
  452. if (archive) {
  453. const entries = archive.entries;
  454. if (entries.size === 1) {
  455. const stream = entries.values().next().value;
  456. const buffer = stream.peek();
  457. shards.set(key, buffer);
  458. }
  459. }
  460. }
  461. }
  462. catch (error) {
  463. // continue regardless of error
  464. }
  465. }
  466. return openShards(shards);
  467. }).catch(() => {
  468. shards.clear();
  469. return openShards(shards);
  470. });
  471. }
  472. catch (error) {
  473. throw new tf.Error('File text format is not TensorFlow.js graph-model (' + error.message + ').');
  474. }
  475. };
  476. const openTextGraphDef = (context) => {
  477. try {
  478. const stream = context.stream;
  479. const reader = protobuf.TextReader.open(stream);
  480. const graph_def = tf.proto.tensorflow.GraphDef.decodeText(reader);
  481. const meta_graph = new tf.proto.tensorflow.MetaGraphDef();
  482. meta_graph.graph_def = graph_def;
  483. const saved_model = new tf.proto.tensorflow.SavedModel();
  484. saved_model.meta_graphs.push(meta_graph);
  485. const format = 'TensorFlow Graph';
  486. return openSavedModel(saved_model, format, null);
  487. }
  488. catch (error) {
  489. const message = error && error.message ? error.message : error.toString();
  490. throw new tf.Error('File text format is not tensorflow.GraphDef (' + message.replace(/\.$/, '') + ').');
  491. }
  492. };
  493. const openTextMetaGraphDef = (context) => {
  494. try {
  495. const stream = context.stream;
  496. const reader = protobuf.TextReader.open(stream);
  497. const meta_graph = tf.proto.tensorflow.MetaGraphDef.decodeText(reader);
  498. const saved_model = new tf.proto.tensorflow.SavedModel();
  499. saved_model.meta_graphs.push(meta_graph);
  500. const format = 'TensorFlow MetaGraph';
  501. return openSavedModel(saved_model, format, null);
  502. }
  503. catch (error) {
  504. throw new tf.Error('File text format is not tensorflow.MetaGraphDef (' + error.message + ').');
  505. }
  506. };
  507. const openTextSavedModel = (context) => {
  508. try {
  509. const stream = context.stream;
  510. const reader = protobuf.TextReader.open(stream);
  511. const saved_model = tf.proto.tensorflow.SavedModel.decodeText(reader);
  512. let format = 'TensorFlow Saved Model';
  513. if (saved_model && Object.prototype.hasOwnProperty.call(saved_model, 'saved_model_schema_version')) {
  514. format = format + ' v' + saved_model.saved_model_schema_version.toString();
  515. }
  516. return openSavedModel(saved_model, format, null);
  517. }
  518. catch (error) {
  519. throw new tf.Error('File text format is not tensorflow.SavedModel (' + error.message + ').');
  520. }
  521. };
  522. const openBinaryGraphDef = (context) => {
  523. let saved_model = null;
  524. const format = 'TensorFlow Graph';
  525. try {
  526. const stream = context.stream;
  527. const reader = protobuf.BinaryReader.open(stream);
  528. const graph_def = tf.proto.tensorflow.GraphDef.decode(reader);
  529. const meta_graph = new tf.proto.tensorflow.MetaGraphDef();
  530. meta_graph.graph_def = graph_def;
  531. saved_model = new tf.proto.tensorflow.SavedModel();
  532. saved_model.meta_graphs.push(meta_graph);
  533. }
  534. catch (error) {
  535. const message = error && error.message ? error.message : error.toString();
  536. throw new tf.Error('File format is not tensorflow.GraphDef (' + message.replace(/\.$/, '') + ').');
  537. }
  538. return openSavedModel(saved_model, format, null);
  539. };
  540. const openBinaryMetaGraphDef = (context) => {
  541. let saved_model = null;
  542. const format = 'TensorFlow MetaGraph';
  543. try {
  544. const stream = context.stream;
  545. const reader = protobuf.BinaryReader.open(stream);
  546. const meta_graph = tf.proto.tensorflow.MetaGraphDef.decode(reader);
  547. saved_model = new tf.proto.tensorflow.SavedModel();
  548. saved_model.meta_graphs.push(meta_graph);
  549. }
  550. catch (error) {
  551. const message = error && error.message ? error.message : error.toString();
  552. throw new tf.Error('File format is not tensorflow.MetaGraphDef (' + message.replace(/\.$/, '') + ').');
  553. }
  554. return openSavedModel(saved_model, format, null);
  555. };
  556. const openBinarySavedModel = (context) => {
  557. let saved_model = null;
  558. let format = 'TensorFlow Saved Model';
  559. try {
  560. const stream = context.stream;
  561. const reader = protobuf.BinaryReader.open(stream);
  562. saved_model = tf.proto.tensorflow.SavedModel.decode(reader);
  563. if (saved_model && Object.prototype.hasOwnProperty.call(saved_model, 'saved_model_schema_version')) {
  564. format = format + ' v' + saved_model.saved_model_schema_version.toString();
  565. }
  566. }
  567. catch (error) {
  568. const message = error && error.message ? error.message : error.toString();
  569. throw new tf.Error('File format is not tensorflow.SavedModel (' + message.replace(/\.$/, '') + ').');
  570. }
  571. return openSavedModel(saved_model, format, null);
  572. };
  573. const openSavedMetadata = (context) => {
  574. /*
  575. const stream = context.stream;
  576. const reader = protobuf.BinaryReader.open(stream);
  577. const saved_metadata = tf.proto.third_party.tensorflow.python.keras.protobuf.SavedMetadata.decode(reader);
  578. debugger;
  579. */
  580. const identifier = 'saved_model.pb';
  581. return context.request(identifier, null).then((stream) => {
  582. return openBinarySavedModel({ stream: stream });
  583. });
  584. };
  585. const openMemmapped = (context) => {
  586. const stream = context.stream;
  587. const readDirectoryOffset = (stream) => {
  588. stream.seek(-8);
  589. const buffer = stream.read(8);
  590. const reader = new base.BinaryReader(buffer);
  591. return reader.uint64();
  592. };
  593. const readDirectory = (stream, offset) => {
  594. const end = stream.position - 8;
  595. stream.seek(offset);
  596. const buffer = stream.read(end - offset);
  597. const reader = protobuf.BinaryReader.open(buffer);
  598. return tf.proto.tensorflow.MemmappedFileSystemDirectory.decode(reader);
  599. };
  600. const offset = readDirectoryOffset(stream);
  601. const directory = readDirectory(stream, offset);
  602. const elements = new Map();
  603. for (const element of directory.element) {
  604. const name = element.name;
  605. if (elements.has(name)) {
  606. throw new tf.Error("Memory mapped file directory contains duplicate '" + name + "'.");
  607. }
  608. elements.set(name, {
  609. offset: element.offset ? element.offset.toNumber() : 0,
  610. length: element.length ? element.length.toNumber() : 0
  611. });
  612. }
  613. const offsets = Array.from(elements).map((entry) => entry[1].offset);
  614. offsets.push(offset);
  615. for (const value of elements.values()) {
  616. if (value.length === 0) {
  617. const min = Math.min.apply(null, offsets.filter((offset) => offset > value.offset));
  618. if (Number.isInteger(min)) {
  619. value.length = min - value.offset;
  620. }
  621. }
  622. }
  623. for (const entry of elements) {
  624. const offset = entry[1].offset;
  625. const length = entry[1].length;
  626. stream.seek(offset);
  627. entry[1].buffer = stream.read(length);
  628. }
  629. if (!elements.has('memmapped_package://.')) {
  630. throw new tf.Error('Memory mapped file directory does not contain tensorflow.GraphDef root.');
  631. }
  632. const element = elements.get('memmapped_package://.');
  633. const buffer = element.buffer;
  634. const reader = protobuf.BinaryReader.open(buffer);
  635. const graph_def = tf.proto.tensorflow.GraphDef.decode(reader);
  636. const format = 'TensorFlow GraphDef Memmapped';
  637. const meta_graph = new tf.proto.tensorflow.MetaGraphDef();
  638. meta_graph.graph_def = graph_def;
  639. const saved_model = new tf.proto.tensorflow.SavedModel();
  640. saved_model.meta_graphs.push(meta_graph);
  641. return openSavedModel(saved_model, format, null);
  642. };
  643. switch (match) {
  644. case 'tf.bundle':
  645. return openBundle(context);
  646. case 'tf.data':
  647. return openData(context);
  648. case 'tf.events':
  649. return openEventFile(context);
  650. case 'tf.json':
  651. return openJson(context, 'json');
  652. case 'tf.json.gz':
  653. return openJson(context, 'json.gz');
  654. case 'tf.pbtxt.GraphDef':
  655. return openTextGraphDef(context);
  656. case 'tf.pbtxt.MetaGraphDef':
  657. return openTextMetaGraphDef(context);
  658. case 'tf.pbtxt.SavedModel':
  659. return openTextSavedModel(context);
  660. case 'tf.pb.GraphDef':
  661. return openBinaryGraphDef(context);
  662. case 'tf.pb.MetaGraphDef':
  663. return openBinaryMetaGraphDef(context);
  664. case 'tf.pb.SavedModel':
  665. return openBinarySavedModel(context);
  666. case 'tf.pb.keras.SavedMetadata':
  667. return openSavedMetadata(context);
  668. case 'tf.pb.mmap':
  669. return openMemmapped(context);
  670. default:
  671. throw new tf.Error("Unsupported TensorFlow format '" + match + "'.");
  672. }
  673. });
  674. }
  675. };
  676. tf.Model = class {
  677. constructor(metadata, model, format, producer, bundle) {
  678. this._format = format;
  679. this._producer = producer || '';
  680. this._graphs = [];
  681. if (model) {
  682. for (let i = 0; i < model.meta_graphs.length; i++) {
  683. const meta_graph = model.meta_graphs[i];
  684. const name = (meta_graph.meta_info_def && meta_graph.meta_info_def.any_info) ? meta_graph.meta_info_def.any_info.toString() : ((model.meta_graphs.length > 1) ? i.toString() : '-');
  685. const graph = new tf.Graph(metadata, meta_graph, name, bundle);
  686. this._graphs.push(graph);
  687. }
  688. }
  689. else {
  690. const graph = new tf.Graph(metadata, null, '', bundle);
  691. this._graphs.push(graph);
  692. }
  693. }
  694. get format() {
  695. return this._format;
  696. }
  697. get producer() {
  698. return this._producer;
  699. }
  700. get description() {
  701. return null;
  702. }
  703. get graphs() {
  704. return this._graphs;
  705. }
  706. };
  707. tf.Graph = class {
  708. constructor(metadata, meta_graph, name, bundle) {
  709. this._name = name;
  710. this._inputs = [];
  711. this._outputs = [];
  712. this._nodes = [];
  713. this._version = null;
  714. if (meta_graph && meta_graph.graph_def) {
  715. const graph = meta_graph.graph_def;
  716. if (graph.versions) {
  717. this._version = 'v' + graph.versions.producer.toString();
  718. }
  719. else if (graph.version) {
  720. this._version = graph.version;
  721. }
  722. else if (meta_graph.meta_info_def && meta_graph.meta_info_def.tensorflow_version) {
  723. this._version = meta_graph.meta_info_def.tensorflow_version;
  724. }
  725. if (meta_graph.meta_info_def && meta_graph.meta_info_def.tags) {
  726. this._tags = meta_graph.meta_info_def.tags.join(', ');
  727. }
  728. metadata = new tf.GraphMetadata(metadata, graph.library);
  729. const nodes = graph.node || [];
  730. const context = tf.Utility.createGraph(metadata, nodes);
  731. this._nodes = context.nodes;
  732. this._inputs = context.inputs;
  733. this._outputs = context.outputs;
  734. }
  735. else if (bundle) {
  736. const nodes = new Map();
  737. for (const tensor of bundle.tensors) {
  738. const parts = tensor.name.split('/');
  739. if (bundle.format === 2) {
  740. if (tensor.name === '_CHECKPOINTABLE_OBJECT_GRAPH' ||
  741. tensor.name.startsWith('optimizer/') ||
  742. tensor.name.startsWith('keras_api/metrics/') ||
  743. tensor.name.endsWith('/ExponentialMovingAverage') ||
  744. tensor.name.indexOf('.OPTIMIZER_SLOT') !== -1) {
  745. continue;
  746. }
  747. if (tensor.name.endsWith('/.ATTRIBUTES/VARIABLE_VALUE')) {
  748. parts.pop();
  749. parts.pop();
  750. }
  751. }
  752. const tensorName = parts.pop();
  753. const name = parts.join('/');
  754. if (!nodes.has(name)) {
  755. nodes.set(name, []);
  756. }
  757. nodes.get(name).push({ name: tensorName, value: tensor });
  758. }
  759. const namespaces = new Set();
  760. this._nodes = Array.from(nodes).map((entry) => {
  761. const node = { op: 'Node', name: entry[0] };
  762. return new tf.Node(metadata, node, namespaces, null, entry[1]);
  763. });
  764. }
  765. }
  766. get name() {
  767. return this._name;
  768. }
  769. get version() {
  770. return this._version;
  771. }
  772. get tags() {
  773. return this._tags;
  774. }
  775. get groups() {
  776. return false;
  777. // TODO return true;
  778. }
  779. get inputs() {
  780. return this._inputs;
  781. }
  782. get outputs() {
  783. return this._outputs;
  784. }
  785. get nodes() {
  786. return this._nodes;
  787. }
  788. get metadata() {
  789. return this._metadata;
  790. }
  791. };
  792. tf.Parameter = class {
  793. constructor(name, args) {
  794. this._name = name;
  795. this._arguments = args;
  796. }
  797. get name() {
  798. return this._name;
  799. }
  800. get visible() {
  801. return true;
  802. }
  803. get arguments() {
  804. return this._arguments;
  805. }
  806. };
  807. tf.Argument = class {
  808. constructor(name, type, initializer) {
  809. if (typeof name !== 'string') {
  810. throw new tf.Error("Invalid argument identifier '" + JSON.stringify(name) + "'.");
  811. }
  812. this._name = name;
  813. this._type = type || null;
  814. this._initializer = initializer || null;
  815. }
  816. get name() {
  817. return this._name;
  818. }
  819. get type() {
  820. if (this._initializer) {
  821. return this._initializer.type;
  822. }
  823. return this._type;
  824. }
  825. get initializer() {
  826. return this._initializer;
  827. }
  828. };
  829. tf.Function = class {
  830. constructor(metadata, name, func) {
  831. this._name = name;
  832. this._version = null;
  833. this._tags = null;
  834. this._inputs = [];
  835. this._outputs = [];
  836. this._nodes = [];
  837. this._description = !func ? 'Function definition not found.' : null;
  838. const input_arg = func && func.signature ? func.signature.input_arg : [];
  839. const output_arg = func && func.signature ? func.signature.output_arg : [];
  840. const ret = func && func.ret ? func.ret : {};
  841. const nodes = func && func.node_def ? func.node_def : [];
  842. if (input_arg) {
  843. for (const input of input_arg) {
  844. const argument = new tf.Argument(input.name, new tf.TensorType(input.type, null), null);
  845. this._inputs.push(new tf.Parameter(input.name, [ argument ]));
  846. }
  847. }
  848. const output_arg_map = new Map();
  849. if (output_arg) {
  850. const ret_map = new Map();
  851. for (const key of Object.keys(ret)) {
  852. const value = func.ret[key];
  853. const split = value.split(':', 2);
  854. ret_map.set(key, split[0]);
  855. }
  856. for (const output of output_arg) {
  857. const name = ret_map.get(output.name);
  858. this._outputs.push(new tf.Parameter(output.name, [
  859. new tf.Argument(name, new tf.TensorType(output.type, null), null)
  860. ]));
  861. output_arg_map.set(name, output.name);
  862. }
  863. }
  864. const context = tf.Utility.createGraph(metadata, nodes, output_arg_map);
  865. this._nodes = context.nodes;
  866. this._inputs = this._inputs.concat(context.inputs);
  867. this._outputs = this._outputs.concat(context.outputs);
  868. }
  869. get type() {
  870. return 'function';
  871. }
  872. get name() {
  873. return this._name;
  874. }
  875. get description() {
  876. return this._description || '';
  877. }
  878. get version() {
  879. return this._version;
  880. }
  881. get tags() {
  882. return this._tags;
  883. }
  884. get groups() {
  885. return false;
  886. // TODO return true;
  887. }
  888. get inputs() {
  889. return this._inputs;
  890. }
  891. get outputs() {
  892. return this._outputs;
  893. }
  894. get nodes() {
  895. return this._nodes;
  896. }
  897. };
  898. tf.Node = class {
  899. constructor(metadata, node, namespaces, initializers, tensors) {
  900. this._type = node.metadata || metadata.type(node.op) || { name: node.op };
  901. this._name = node.name;
  902. this._attributes = [];
  903. this._inputs = [];
  904. this._outputs = [];
  905. this._group = '';
  906. if (node.name) {
  907. if (namespaces.has(node.name)) {
  908. this._group = node.name;
  909. }
  910. else {
  911. const lastIndex = node.name.lastIndexOf('/');
  912. if (lastIndex != -1) {
  913. const namespace = node.name.substring(0, lastIndex);
  914. if (namespaces.has(namespace)) {
  915. this._group = namespace;
  916. }
  917. }
  918. }
  919. }
  920. if (tensors) {
  921. for (const tensor of tensors) {
  922. this._inputs.push(new tf.Parameter(tensor.name, [
  923. new tf.Argument(tensor.value.name, null, tensor.value)
  924. ]));
  925. }
  926. }
  927. else {
  928. if (node.device !== undefined) {
  929. this._device = node.device;
  930. }
  931. if (node.attr) {
  932. this._attributes = Object.entries(node.attr).map((entry) => {
  933. return new tf.Attribute(metadata, node.op, entry[0], entry[1]);
  934. });
  935. }
  936. let inputIndex = 0;
  937. const inputs = (node.input || []).filter((input) => !input.name.startsWith('^'));
  938. if (this._type && this._type.inputs) {
  939. for (const input of this._type.inputs) {
  940. let inputCount = 1;
  941. if (input.numberAttr) {
  942. const inputNumber = node.attr[input.numberAttr];
  943. if (inputNumber && inputNumber.i) {
  944. inputCount = inputNumber.i;
  945. }
  946. }
  947. else if (input.typeListAttr) {
  948. const inputTypeListAttr = node.attr[input.typeListAttr];
  949. if (inputTypeListAttr && inputTypeListAttr.list && inputTypeListAttr.list.type) {
  950. inputCount = inputTypeListAttr.list.type.length;
  951. }
  952. }
  953. const inputArguments = inputs.slice(inputIndex, inputIndex + inputCount).map((input) => {
  954. return initializers.has(input.name) ? initializers.get(input.name) : new tf.Argument(input.name, null, null);
  955. });
  956. this._inputs.push(new tf.Parameter(input.name, inputArguments));
  957. inputIndex += inputCount;
  958. }
  959. }
  960. this._inputs.push(...inputs.slice(inputIndex).map((input, index) => {
  961. return new tf.Parameter(input.label ? input.label : (inputIndex + index).toString(), [
  962. initializers.has(input.name) ? initializers.get(input.name) : new tf.Argument(input.name, null, null)
  963. ]);
  964. }));
  965. let outputIndex = 0;
  966. const outputs = node.output || [];
  967. if (this._type && this._type.outputs) {
  968. for (const output of this._type.outputs) {
  969. let outputCount = 1;
  970. if (output.numberAttr) {
  971. const outputNumber = node.attr[output.numberAttr];
  972. if (outputNumber && outputNumber.i) {
  973. outputCount = outputNumber.i;
  974. }
  975. }
  976. else if (output.typeListAttr) {
  977. const outputTypeListAttr = node.attr[output.typeListAttr];
  978. if (outputTypeListAttr && outputTypeListAttr.list && outputTypeListAttr.list.type) {
  979. outputCount = outputTypeListAttr.list.type.length;
  980. }
  981. }
  982. const outputArguments = outputs.slice(outputIndex, outputIndex + outputCount).map((output) => {
  983. return new tf.Argument(output.name ? output.name : '-', null, null);
  984. });
  985. this._outputs.push(new tf.Parameter(output.name, outputArguments));
  986. outputIndex += outputCount;
  987. }
  988. }
  989. this._outputs.push(...outputs.slice(outputIndex).map((output, index) => {
  990. return new tf.Parameter((outputIndex + index).toString(), [
  991. new tf.Argument(output.name ? output.name : '-', null, null)
  992. ]);
  993. }));
  994. const controlDependencies = node.controlDependencies || [];
  995. this._controlDependencies = controlDependencies.map((input) => new tf.Argument(input.name));
  996. }
  997. }
  998. get type() {
  999. return this._type;
  1000. }
  1001. get name() {
  1002. return this._name;
  1003. }
  1004. get device() {
  1005. return this._device || null;
  1006. }
  1007. get group() {
  1008. return this._group;
  1009. }
  1010. get description() {
  1011. return '';
  1012. }
  1013. get inputs() {
  1014. return this._inputs;
  1015. }
  1016. get outputs() {
  1017. return this._outputs;
  1018. }
  1019. get controlDependencies() {
  1020. return this._controlDependencies;
  1021. }
  1022. get attributes() {
  1023. return this._attributes;
  1024. }
  1025. };
  1026. tf.Attribute = class {
  1027. constructor(metadata, op, name, value) {
  1028. this._name = name;
  1029. this._value = null;
  1030. this._type = null;
  1031. const schema = value && value.metadata ? value.metadata : metadata.attribute(op, name);
  1032. const visible = metadata.visible(op, name);
  1033. if (schema && schema.type) {
  1034. this._type = schema.type;
  1035. }
  1036. switch (value.value) {
  1037. case 'type':
  1038. this._type = 'type';
  1039. this._value = tf.Utility.dataType(value.type);
  1040. break;
  1041. case 'i':
  1042. this._value = value.i;
  1043. break;
  1044. case 'f':
  1045. this._value = value.f;
  1046. break;
  1047. case 'b':
  1048. this._value = value.b;
  1049. break;
  1050. case 'shape':
  1051. this._type = 'shape';
  1052. this._value = new tf.TensorShape(value.shape);
  1053. break;
  1054. case 's':
  1055. this._value = tf.Utility.decodeText(value.s);
  1056. break;
  1057. case 'tensor': {
  1058. this._type = 'tensor';
  1059. this._value = new tf.Tensor(value.tensor);
  1060. break;
  1061. }
  1062. case 'func': {
  1063. this._type = 'function';
  1064. this._value = new tf.Node(metadata, { op: value.func.name, attr: value.func.attr });
  1065. break;
  1066. }
  1067. case 'placeholder': {
  1068. this._type = 'placeholder';
  1069. this._value = value;
  1070. break;
  1071. }
  1072. case 'list': {
  1073. const list = value.list;
  1074. if (list.s && list.s.length > 0) {
  1075. this._value = list.s.map((s) => tf.Utility.decodeText(s));
  1076. }
  1077. else if (list.i && list.i.length > 0) {
  1078. this._value = list.i;
  1079. }
  1080. else if (list.f && list.f.length > 0) {
  1081. this._value = list.f;
  1082. }
  1083. else if (list.type && list.type.length > 0) {
  1084. this._type = 'type[]';
  1085. this._value = list.type.map((type) => tf.Utility.dataType(type));
  1086. }
  1087. else if (list.shape && list.shape.length > 0) {
  1088. this._type = 'shape[]';
  1089. this._value = list.shape.map((shape) => new tf.TensorShape(shape));
  1090. }
  1091. else if (list.func && list.func.length > 0) {
  1092. this._type = 'function[]';
  1093. this._value = list.func.map((func) => new tf.Node(metadata, { op: func.name, attr: func.attr }));
  1094. }
  1095. else {
  1096. this._value = [];
  1097. }
  1098. break;
  1099. }
  1100. default: {
  1101. throw new tf.Error("Unsupported attribute value type '" + JSON.stringify(value).substring(0, 32) + "'.");
  1102. }
  1103. }
  1104. if (schema) {
  1105. if (Object.prototype.hasOwnProperty.call(schema, 'visible') && !schema.visible) {
  1106. this._visible = false;
  1107. }
  1108. else if (Object.prototype.hasOwnProperty.call(schema, 'default')) {
  1109. const equals = (value, defaultValue) => {
  1110. if (!Array.isArray(defaultValue) && defaultValue === Object(defaultValue)) {
  1111. switch (defaultValue.type) {
  1112. case 'type':
  1113. defaultValue = tf.Utility.dataType(defaultValue.value);
  1114. break;
  1115. case 'shape':
  1116. case 'tensor':
  1117. defaultValue = defaultValue.value;
  1118. break;
  1119. default:
  1120. throw new tf.Error(JSON.stringify(defaultValue));
  1121. }
  1122. }
  1123. if (typeof value === 'boolean' || typeof value === 'number' || typeof value === 'string') {
  1124. return value === defaultValue;
  1125. }
  1126. if (value instanceof base.Int64 || value instanceof base.Uint64) {
  1127. return value.toNumber() === defaultValue;
  1128. }
  1129. return false;
  1130. };
  1131. const value = this._value;
  1132. const defaultValue = schema.default;
  1133. if (Array.isArray(value) && Array.isArray(defaultValue)) {
  1134. if (value.length === defaultValue.length && value.every((item, index) => equals(item, defaultValue[index]))) {
  1135. this._visible = false;
  1136. }
  1137. }
  1138. else if (equals(value, defaultValue)) {
  1139. this._visible = false;
  1140. }
  1141. }
  1142. }
  1143. if (name == '_output_shapes') {
  1144. this._visible = false;
  1145. }
  1146. if (name == '_class') {
  1147. this._visible = false;
  1148. }
  1149. if (visible === false) {
  1150. this._visible = false;
  1151. }
  1152. }
  1153. get name() {
  1154. return this._name;
  1155. }
  1156. get type() {
  1157. return this._type;
  1158. }
  1159. get value() {
  1160. return this._value;
  1161. }
  1162. get visible() {
  1163. return this._visible == false ? false : true;
  1164. }
  1165. };
  1166. tf.Tensor = class {
  1167. constructor(tensor, name, kind) {
  1168. this._name = name;
  1169. this._kind = kind || null;
  1170. if (tensor) {
  1171. this._type = new tf.TensorType(tensor.dtype, tensor.tensor_shape || tensor.tensorShape);
  1172. this._tensor = tensor;
  1173. if (Object.prototype.hasOwnProperty.call(tensor, 'tensor_content')) {
  1174. this._buffer = tensor.tensor_content;
  1175. }
  1176. else {
  1177. const DataType = tf.proto.tensorflow.DataType;
  1178. switch (tensor.dtype) {
  1179. case DataType.DT_BFLOAT16: {
  1180. const values = tensor.half_val || [];
  1181. this._buffer = new Uint8Array(values.length << 2);
  1182. const view = new DataView(this._buffer.buffer, this._buffer.byteOffset, this._buffer.byteLength);
  1183. for (let i = 0; i < values.length; i++) {
  1184. view.setUint32(i << 2, values[i] << 16, true);
  1185. }
  1186. break;
  1187. }
  1188. case DataType.DT_HALF: {
  1189. const values = tensor.half_val || [];
  1190. this._buffer = new Uint8Array(values.length << 1);
  1191. const view = new DataView(this._buffer.buffer, this._buffer.byteOffset, this._buffer.byteLength);
  1192. for (let i = 0; i < values.length; i++) {
  1193. view.setUint16(i << 1, values[i], true);
  1194. }
  1195. break;
  1196. }
  1197. case DataType.DT_FLOAT: {
  1198. this._data = tensor.float_val || null;
  1199. break;
  1200. }
  1201. case DataType.DT_DOUBLE: {
  1202. this._data = tensor.double_val || null;
  1203. break;
  1204. }
  1205. case DataType.DT_UINT8:
  1206. case DataType.DT_UINT16:
  1207. case DataType.DT_INT8:
  1208. case DataType.DT_INT16:
  1209. case DataType.DT_INT32: {
  1210. this._data = tensor.int_val || null;
  1211. break;
  1212. }
  1213. case DataType.DT_UINT32: {
  1214. this._data = tensor.uint32_val || null;
  1215. break;
  1216. }
  1217. case DataType.DT_INT64: {
  1218. this._data = tensor.int64_val || null;
  1219. break;
  1220. }
  1221. case DataType.DT_UINT64: {
  1222. this._data = tensor.uint64_val || null;
  1223. break;
  1224. }
  1225. case DataType.DT_BOOL: {
  1226. this._data = tensor.bool_val || null;
  1227. break;
  1228. }
  1229. case DataType.DT_STRING: {
  1230. this._data = tensor.string_val || null;
  1231. break;
  1232. }
  1233. default: {
  1234. throw new tf.Error("Unsupported tensor data type '" + tensor.dtype + "'.");
  1235. }
  1236. }
  1237. }
  1238. }
  1239. else {
  1240. this._type = new tf.TensorType('?', null);
  1241. this._tensor = null;
  1242. }
  1243. }
  1244. get name() {
  1245. return this._name;
  1246. }
  1247. get type() {
  1248. return this._type;
  1249. }
  1250. get kind() {
  1251. return this._kind;
  1252. }
  1253. set kind(value) {
  1254. this._kind = value;
  1255. }
  1256. get state() {
  1257. return this._context().state;
  1258. }
  1259. get value() {
  1260. const context = this._context();
  1261. if (context.state) {
  1262. return null;
  1263. }
  1264. context.limit = Number.MAX_SAFE_INTEGER;
  1265. return this._decode(context, 0);
  1266. }
  1267. toString() {
  1268. const context = this._context();
  1269. if (context.state) {
  1270. return '';
  1271. }
  1272. context.limit = 10000;
  1273. const value = this._decode(context, 0);
  1274. return tf.Tensor._stringify(value, '', ' ');
  1275. }
  1276. _context() {
  1277. const context = {};
  1278. context.state = null;
  1279. context.index = 0;
  1280. context.count = 0;
  1281. context.size = 1;
  1282. if (!this._tensor) {
  1283. context.state = 'Tensor has content.';
  1284. return context;
  1285. }
  1286. if (!this._tensor.dtype) {
  1287. context.state = 'Tensor has no data type.';
  1288. return context;
  1289. }
  1290. const shape = this._tensor.tensor_shape || this._tensor.tensorShape;
  1291. if (!shape || !shape.dim) {
  1292. context.state = 'Tensor has no dimensions.';
  1293. return context;
  1294. }
  1295. for (const dim of shape.dim) {
  1296. context.size = context.size * (dim.size ? dim.size : 0);
  1297. }
  1298. if (this._buffer) {
  1299. const DataType = tf.proto.tensorflow.DataType;
  1300. switch (this._tensor.dtype) {
  1301. case DataType.DT_BFLOAT16:
  1302. case DataType.DT_HALF:
  1303. case DataType.DT_FLOAT:
  1304. case DataType.DT_DOUBLE:
  1305. case DataType.DT_QINT8:
  1306. case DataType.DT_QUINT8:
  1307. case DataType.DT_INT8:
  1308. case DataType.DT_UINT8:
  1309. case DataType.DT_INT16:
  1310. case DataType.DT_UINT16:
  1311. case DataType.DT_INT32:
  1312. case DataType.DT_UINT32:
  1313. case DataType.DT_INT64:
  1314. case DataType.DT_UINT64:
  1315. if (!this._buffer || this._buffer.length === 0) {
  1316. context.state = 'Tensor has content.';
  1317. return context;
  1318. }
  1319. context.rawData = new DataView(this._buffer.buffer, this._buffer.byteOffset, this._buffer.byteLength);
  1320. break;
  1321. default:
  1322. break;
  1323. }
  1324. }
  1325. else if (this._data) {
  1326. if (this._data.length == context.size) {
  1327. context.data = this._data;
  1328. }
  1329. else if (this._data.length === 1) {
  1330. context.data = new Array(context.size).fill(this._data[0]);
  1331. }
  1332. else {
  1333. context.state = "Tensor has no data.";
  1334. return context;
  1335. }
  1336. }
  1337. else {
  1338. context.state = "Tensor has no data.";
  1339. return context;
  1340. }
  1341. if (!context.data && !context.rawData) {
  1342. context.state = "Tensor data type '" + this.type.dataType + "' is not implemented.";
  1343. return context;
  1344. }
  1345. context.shape = shape.dim.map((dim) => dim.size);
  1346. return context;
  1347. }
  1348. _decode(context, dimension) {
  1349. let shape = context.shape;
  1350. if (shape.length == 0) {
  1351. shape = [ 1 ];
  1352. }
  1353. const results = [];
  1354. const size = shape[dimension];
  1355. if (dimension == shape.length - 1) {
  1356. for (let i = 0; i < size; i++) {
  1357. if (context.count > context.limit) {
  1358. results.push('...');
  1359. return results;
  1360. }
  1361. if (context.data) {
  1362. const value = context.data[context.index++];
  1363. results.push((this._tensor.dtype == tf.proto.tensorflow.DataType.DT_STRING) ? tf.Utility.decodeText(value) : value);
  1364. context.count++;
  1365. }
  1366. else if (context.rawData) {
  1367. switch (this._tensor.dtype) {
  1368. case tf.proto.tensorflow.DataType.DT_HALF:
  1369. results.push(context.rawData.getFloat16(context.index, true));
  1370. context.index += 2;
  1371. context.count++;
  1372. break;
  1373. case tf.proto.tensorflow.DataType.DT_BFLOAT16:
  1374. case tf.proto.tensorflow.DataType.DT_FLOAT:
  1375. results.push(context.rawData.getFloat32(context.index, true));
  1376. context.index += 4;
  1377. context.count++;
  1378. break;
  1379. case tf.proto.tensorflow.DataType.DT_DOUBLE:
  1380. results.push(context.rawData.getFloat64(context.index, true));
  1381. context.index += 8;
  1382. context.count++;
  1383. break;
  1384. case tf.proto.tensorflow.DataType.DT_INT8:
  1385. results.push(context.rawData.getInt8(context.index));
  1386. context.index += 1;
  1387. context.count++;
  1388. break;
  1389. case tf.proto.tensorflow.DataType.DT_UINT8:
  1390. results.push(context.rawData.getUint8(context.index));
  1391. context.index += 1;
  1392. context.count++;
  1393. break;
  1394. case tf.proto.tensorflow.DataType.DT_INT16:
  1395. results.push(context.rawData.getInt16(context.index));
  1396. context.index += 2;
  1397. context.count++;
  1398. break;
  1399. case tf.proto.tensorflow.DataType.DT_UINT16:
  1400. results.push(context.rawData.getUint16(context.index));
  1401. context.index += 2;
  1402. context.count++;
  1403. break;
  1404. case tf.proto.tensorflow.DataType.DT_INT32:
  1405. results.push(context.rawData.getInt32(context.index, true));
  1406. context.index += 4;
  1407. context.count++;
  1408. break;
  1409. case tf.proto.tensorflow.DataType.DT_UINT32:
  1410. results.push(context.rawData.getUint32(context.index, true));
  1411. context.index += 4;
  1412. context.count++;
  1413. break;
  1414. case tf.proto.tensorflow.DataType.DT_INT64:
  1415. results.push(context.rawData.getInt64(context.index, true));
  1416. context.index += 8;
  1417. context.count++;
  1418. break;
  1419. case tf.proto.tensorflow.DataType.DT_UINT64:
  1420. results.push(context.rawData.getUint64(context.index, true));
  1421. context.index += 8;
  1422. context.count++;
  1423. break;
  1424. case tf.proto.tensorflow.DataType.DT_QINT8:
  1425. results.push(context.rawData.getInt8(context.index, true));
  1426. context.index += 1;
  1427. context.count++;
  1428. break;
  1429. case tf.proto.tensorflow.DataType.DT_QUINT8:
  1430. results.push(context.rawData.getUint8(context.index, true));
  1431. context.index += 1;
  1432. context.count++;
  1433. break;
  1434. default:
  1435. throw new tf.Error("Unsupported data type '" + this._tensor.dtype + "'.");
  1436. }
  1437. }
  1438. }
  1439. }
  1440. else {
  1441. for (let j = 0; j < size; j++) {
  1442. if (context.count > context.limit) {
  1443. results.push('...');
  1444. return results;
  1445. }
  1446. results.push(this._decode(context, dimension + 1, shape));
  1447. }
  1448. }
  1449. if (context.shape.length == 0) {
  1450. return results[0];
  1451. }
  1452. return results;
  1453. }
  1454. static _stringify(value, indentation, indent) {
  1455. if (Array.isArray(value)) {
  1456. const result = [];
  1457. result.push(indentation + '[');
  1458. const items = value.map((item) => tf.Tensor._stringify(item, indentation + indent, indent));
  1459. if (items.length > 0) {
  1460. result.push(items.join(',\n'));
  1461. }
  1462. result.push(indentation + ']');
  1463. return result.join('\n');
  1464. }
  1465. if (typeof value == 'string') {
  1466. return indentation + value;
  1467. }
  1468. if (value == Infinity) {
  1469. return indentation + 'Infinity';
  1470. }
  1471. if (value == -Infinity) {
  1472. return indentation + '-Infinity';
  1473. }
  1474. if (isNaN(value)) {
  1475. return indentation + 'NaN';
  1476. }
  1477. return indentation + value.toString();
  1478. }
  1479. };
  1480. tf.TensorType = class {
  1481. constructor(dtype, shape) {
  1482. this._dtype = dtype;
  1483. this._shape = new tf.TensorShape(shape);
  1484. }
  1485. get dataType() {
  1486. return this._dtype ? tf.Utility.dataType(this._dtype) : '?';
  1487. }
  1488. get shape() {
  1489. return this._shape;
  1490. }
  1491. toString() {
  1492. return this.dataType + this._shape.toString();
  1493. }
  1494. };
  1495. tf.TensorShape = class {
  1496. constructor(shape) {
  1497. this._shape = shape;
  1498. }
  1499. get dimensions() {
  1500. if (this._shape && this._shape.dim) {
  1501. if (this._shape.unknown_rank) {
  1502. return null;
  1503. }
  1504. if (this._shape.dim.length == 0) {
  1505. return [];
  1506. }
  1507. if (this._shape.dim.length == 1 && !this._shape.dim[0].size) {
  1508. return [ 0 ];
  1509. }
  1510. return this._shape.dim.map((dim) => (dim.size && dim.size != -1) ? dim.size : '?');
  1511. }
  1512. return null;
  1513. }
  1514. toString() {
  1515. if (this._shape && this._shape.dim) {
  1516. if (this._shape.unknown_rank) {
  1517. return '[-]';
  1518. }
  1519. if (this._shape.dim.length == 0) {
  1520. return '';
  1521. }
  1522. if (this._shape.dim.length == 1 && !this._shape.dim[0].size) {
  1523. return '[0]';
  1524. }
  1525. return '[' + this._shape.dim.map((dim) => (dim.size && dim.size != -1) ? dim.size.toString() : '?').join(',') + ']';
  1526. }
  1527. return '?';
  1528. }
  1529. };
  1530. tf.TensorBundle = class {
  1531. static open(stream, identifier, context) {
  1532. const format = !identifier.toLowerCase().endsWith('.index') ? 1 : 2;
  1533. const table = new tf.TensorBundle.Table(stream);
  1534. if (!table.entries.has('')) {
  1535. throw new tf.Error('Bundle header not available.');
  1536. }
  1537. if (format === 1) {
  1538. return Promise.resolve(new tf.TensorBundle(format, table.entries, []));
  1539. }
  1540. const buffer = table.entries.get('');
  1541. const reader = protobuf.BinaryReader.open(buffer);
  1542. const header = tf.proto.tensorflow.BundleHeaderProto.decode(reader);
  1543. const numShards = header.num_shards;
  1544. const promises = [];
  1545. for (let i = 0; i < numShards; i++) {
  1546. const shardIndex = ('0000' + i).slice(-5);
  1547. const shardCount = ('0000' + numShards).slice(-5);
  1548. const filename = identifier.split('.');
  1549. filename.pop();
  1550. const basename = filename.join('.');
  1551. const name = basename + '.data-' + shardIndex + '-of-' + shardCount;
  1552. promises.push(context.request(name, null));
  1553. }
  1554. return Promise.all(promises).then((streams) => {
  1555. return new tf.TensorBundle(format, table.entries, streams);
  1556. }).catch((error) => {
  1557. context.exception(error, false);
  1558. return new tf.TensorBundle(format, table.entries, null);
  1559. });
  1560. }
  1561. constructor(format, entries, streams) {
  1562. this._format = format;
  1563. this._tensors = [];
  1564. switch (format) {
  1565. case 1: {
  1566. const buffer = entries.get('');
  1567. const reader = protobuf.BinaryReader.open(buffer);
  1568. const header = tf.proto.tensorflow.SavedTensorSlices.decode(reader);
  1569. const data = new Map();
  1570. for (const pair of entries) {
  1571. if (pair[0] !== '' && pair[0] !== 'global_step') {
  1572. const buffer = pair[1];
  1573. const reader = protobuf.BinaryReader.open(buffer);
  1574. const slices = tf.proto.tensorflow.SavedTensorSlices.decode(reader);
  1575. const name = slices.data.name;
  1576. const tensor = slices.data.data;
  1577. if (!data.has(name)) {
  1578. if (tensor.tensor_content && tensor.tensor_content.length > 0) {
  1579. data.set(name, { key: 'tensor_content', value: tensor.tensor_content });
  1580. }
  1581. else {
  1582. const keys = Object.keys(tensor).filter((key) => key.endsWith('_val') && tensor[key] && tensor[key].length > 0);
  1583. data.set(name, keys.length == 1 ? { key: keys[0], value: tensor[keys[0]] } : null);
  1584. }
  1585. }
  1586. else {
  1587. const item = data.get(name);
  1588. if (item !== null) {
  1589. if (tensor[item.key] && tensor[item.key].length > 0) {
  1590. item.value = item.value.concat(tensor[item.key]);
  1591. }
  1592. else {
  1593. data.set(name, null);
  1594. }
  1595. }
  1596. }
  1597. }
  1598. }
  1599. for (const meta of header.meta.tensor) {
  1600. if (meta.name !== 'global_step') {
  1601. const tensor = new tf.proto.tensorflow.TensorProto();
  1602. tensor.dtype = meta.type;
  1603. tensor.tensor_shape = meta.shape;
  1604. const item = data.get(meta.name);
  1605. if (item) {
  1606. tensor[item.key] = item.value;
  1607. }
  1608. this._tensors.push(new tf.Tensor(tensor, meta.name, null));
  1609. }
  1610. }
  1611. break;
  1612. }
  1613. case 2: {
  1614. entries.forEach((buffer, name) => {
  1615. if (name !== '') {
  1616. const reader = protobuf.BinaryReader.open(buffer);
  1617. const entry = tf.proto.tensorflow.BundleEntryProto.decode(reader);
  1618. const tensor = new tf.proto.tensorflow.TensorProto();
  1619. tensor.dtype = entry.dtype;
  1620. tensor.tensor_shape = entry.shape;
  1621. const offset = Number.isInteger(entry.offset) ? entry.offset : entry.offset.toNumber();
  1622. const size = Number.isInteger(entry.size) ? entry.size : entry.size.toNumber();
  1623. if (streams) {
  1624. const stream = streams[entry.shard_id];
  1625. stream.seek(offset);
  1626. tensor.tensor_content = stream.peek(size);
  1627. }
  1628. this._tensors.push(new tf.Tensor(tensor, name, null));
  1629. }
  1630. });
  1631. break;
  1632. }
  1633. default: {
  1634. throw new tf.Error("Unsupported Tensor Bundle format '" + format + "'.");
  1635. }
  1636. }
  1637. }
  1638. get format() {
  1639. return this._format;
  1640. }
  1641. get tensors() {
  1642. return this._tensors;
  1643. }
  1644. };
  1645. tf.TensorBundle.Table = class {
  1646. constructor(stream) {
  1647. // https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/lib/io/table.cc
  1648. this.entries = new Map();
  1649. if (stream.length <= 54) {
  1650. throw new tf.Error('Invalid index file size.');
  1651. }
  1652. stream.seek(-48);
  1653. const buffer = stream.peek(48);
  1654. const reader = new tf.BinaryReader(buffer);
  1655. reader.seek(-8);
  1656. const signature = [ 0x57, 0xfb, 0x80, 0x8b, 0x24, 0x75, 0x47, 0xdb ];
  1657. if (!reader.read(8).every((value, index) => value === signature[index])) {
  1658. throw new tf.Error('Invalid table signature.');
  1659. }
  1660. reader.seek(-48); // kEncodedLength
  1661. reader.varint64(); // metaindex offset
  1662. reader.varint64(); // metaindex size
  1663. const indexOffset = reader.varint64();
  1664. const indexSize = reader.varint64();
  1665. const indexBlock = new tf.TensorBundle.Table.Block(stream, indexOffset, indexSize);
  1666. for (const entry of indexBlock.entries) {
  1667. const valueReader = new tf.BinaryReader(entry[1]);
  1668. const offset = valueReader.varint64();
  1669. const size = valueReader.varint64();
  1670. const block = new tf.TensorBundle.Table.Block(stream, offset, size);
  1671. for (const pair of block.entries) {
  1672. this.entries.set(pair[0], pair[1]);
  1673. }
  1674. }
  1675. stream.seek(0);
  1676. }
  1677. };
  1678. tf.TensorBundle.Table.Block = class {
  1679. constructor(stream, offset, size) {
  1680. // https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/lib/io/block.cc
  1681. this.entries = new Map();
  1682. stream.seek(offset);
  1683. const buffer = stream.read(size); // blockContents
  1684. const compression = stream.byte();
  1685. stream.skip(4); // crc32
  1686. let reader = new tf.BinaryReader(buffer);
  1687. switch (compression) {
  1688. case 0: // kNoCompression
  1689. break;
  1690. case 1: // kSnappyCompression
  1691. reader = new tf.BinaryReader(reader.unsnappy());
  1692. break;
  1693. default:
  1694. throw new tf.Error("Unsupported block compression '" + compression + "'.");
  1695. }
  1696. reader.seek(-4);
  1697. const numRestarts = reader.int32();
  1698. reader.seek(-4 - (4 * numRestarts));
  1699. const restartOffsets = [];
  1700. for (let i = 0; i < numRestarts; i++) {
  1701. restartOffsets.push(reader.int32());
  1702. }
  1703. const decoder = new TextDecoder();
  1704. for (let i = 0; i < numRestarts; i++) {
  1705. reader.seek(restartOffsets[i]);
  1706. let key = '';
  1707. while (reader.position < reader.length) {
  1708. const sharedSize = reader.varint32(); // index shared size
  1709. const nonSharedSize = reader.varint32(); // index non shared size
  1710. const valueSize = reader.varint32();
  1711. if (sharedSize === 0 && nonSharedSize === 0 && valueSize === 0) {
  1712. break;
  1713. }
  1714. key = key.substring(0, sharedSize);
  1715. key = key + decoder.decode(reader.read(nonSharedSize));
  1716. const value = reader.read(valueSize);
  1717. this.entries.set(key, value);
  1718. }
  1719. }
  1720. }
  1721. };
  1722. tf.BinaryReader = class {
  1723. constructor(buffer) {
  1724. this._buffer = buffer;
  1725. this._position = 0;
  1726. this._length = this._buffer.length;
  1727. this._dataView = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  1728. this._decoder = new TextDecoder('utf-8');
  1729. }
  1730. get position() {
  1731. return this._position;
  1732. }
  1733. get length() {
  1734. return this._length;
  1735. }
  1736. seek(position) {
  1737. this._position = position >= 0 ? position : this._length + position;
  1738. if (this._position > this._length) {
  1739. throw new tf.Error('Expected ' + (this._position - this._length) + ' more bytes. The file might be corrupted. Unexpected end of file.');
  1740. }
  1741. }
  1742. skip(offset) {
  1743. this._position += offset;
  1744. if (this._position > this._length) {
  1745. throw new tf.Error('Expected ' + (this._position - this._length) + ' more bytes. The file might be corrupted. Unexpected end of file.');
  1746. }
  1747. }
  1748. read(size) {
  1749. const position = this._position;
  1750. this.skip(size);
  1751. return this._buffer.subarray(position, this._position);
  1752. }
  1753. byte() {
  1754. const position = this._position;
  1755. this.skip(1);
  1756. return this._dataView.getUint8(position);
  1757. }
  1758. uint16() {
  1759. const position = this._position;
  1760. this.skip(2);
  1761. return this._dataView.getUint16(position, true);
  1762. }
  1763. int32() {
  1764. const position = this._position;
  1765. this.skip(4);
  1766. return this._dataView.getInt32(position, true);
  1767. }
  1768. uint32() {
  1769. const position = this._position;
  1770. this.skip(4);
  1771. return this._dataView.getUint32(position, true);
  1772. }
  1773. uint64() {
  1774. const position = this._position;
  1775. this.skip(4);
  1776. return this._dataView.getUint64(position, true);
  1777. }
  1778. string() {
  1779. const size = this.uint32();
  1780. const buffer = this.read(size);
  1781. return this._decoder.decode(buffer);
  1782. }
  1783. varint32() {
  1784. return this.varint64();
  1785. }
  1786. varint64() {
  1787. let result = 0;
  1788. for (let shift = 0; shift <= 63; shift += 7) {
  1789. const byte = this.byte();
  1790. if (byte & 128) {
  1791. result |= (byte & 127) << shift;
  1792. }
  1793. else {
  1794. result |= byte << shift;
  1795. break;
  1796. }
  1797. }
  1798. return result;
  1799. }
  1800. unsnappy() {
  1801. const data = new Uint8Array(this.varint64());
  1802. const mask = [0, 0xff, 0xffff, 0xffffff, 0xffffffff];
  1803. let position = 0;
  1804. while (this._position < this._length) {
  1805. let length = 0;
  1806. const c = this.byte();
  1807. switch (c & 0x03) {
  1808. case 0: {
  1809. length = (c >>> 2) + 1;
  1810. if (length > 60) {
  1811. const short = length - 60;
  1812. length = (this.uint32() & mask[short]) + 1;
  1813. this._position += short - 4;
  1814. }
  1815. data.set(this.read(length), position);
  1816. break;
  1817. }
  1818. case 1: {
  1819. length = ((c >>> 2) & 0x07) + 4;
  1820. const offset = this.byte() + ((c >>> 5) << 8);
  1821. data.set(data.subarray(position - offset, position - offset + length), position);
  1822. break;
  1823. }
  1824. case 2: {
  1825. length = (c >>> 2) + 1;
  1826. const offset = this.uint16();
  1827. data.set(data.subarray(position - offset, position - offset + length), position);
  1828. break;
  1829. }
  1830. case 3: {
  1831. length = (c >>> 2) + 1;
  1832. const offset = this.uint32();
  1833. data.set(data.subarray(position - offset, position - offset + length), position);
  1834. break;
  1835. }
  1836. default: {
  1837. break;
  1838. }
  1839. }
  1840. position += length;
  1841. }
  1842. return data;
  1843. }
  1844. };
  1845. tf.EventFileReader = class {
  1846. static open(stream) {
  1847. if (stream.length < 16) {
  1848. return null;
  1849. }
  1850. const masked_crc32c = (bytes) => {
  1851. const poly = 0x82f63b78;
  1852. let crc = 0xffffffff;
  1853. for (let n = 0; n < bytes.length; n++) {
  1854. crc ^= bytes[n];
  1855. crc = crc & 1 ? (crc >>> 1) ^ poly : crc >>> 1;
  1856. crc = crc & 1 ? (crc >>> 1) ^ poly : crc >>> 1;
  1857. crc = crc & 1 ? (crc >>> 1) ^ poly : crc >>> 1;
  1858. crc = crc & 1 ? (crc >>> 1) ^ poly : crc >>> 1;
  1859. crc = crc & 1 ? (crc >>> 1) ^ poly : crc >>> 1;
  1860. crc = crc & 1 ? (crc >>> 1) ^ poly : crc >>> 1;
  1861. crc = crc & 1 ? (crc >>> 1) ^ poly : crc >>> 1;
  1862. crc = crc & 1 ? (crc >>> 1) ^ poly : crc >>> 1;
  1863. crc = crc >>> 0;
  1864. }
  1865. crc = crc ^ 0xffffffff;
  1866. crc = crc >>> 0;
  1867. crc = ((crc >> 15) | (crc << 17)) + 0xa282ead8;
  1868. crc = crc >>> 0;
  1869. return crc;
  1870. };
  1871. const buffer = stream.peek(12);
  1872. const reader = new tf.BinaryReader(buffer);
  1873. const length_bytes = reader.read(8);
  1874. const length_crc = reader.uint32();
  1875. if (masked_crc32c(length_bytes) !== length_crc) {
  1876. return null;
  1877. }
  1878. return new tf.EventFileReader(stream);
  1879. }
  1880. constructor(stream) {
  1881. this._stream = stream;
  1882. }
  1883. read() {
  1884. if (this._stream.position < this._stream.length) {
  1885. const uint64 = (stream) => {
  1886. const buffer = stream.read(8);
  1887. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  1888. return view.getUint64(0, true).toNumber();
  1889. };
  1890. const length = uint64(this._stream);
  1891. this._stream.skip(4); // masked crc of length
  1892. const buffer = this._stream.read(length);
  1893. const reader = protobuf.BinaryReader.open(buffer);
  1894. const event = tf.proto.tensorflow.Event.decode(reader);
  1895. this._stream.skip(4); // masked crc of data
  1896. return event;
  1897. }
  1898. return null;
  1899. }
  1900. };
  1901. tf.GraphMetadata = class {
  1902. constructor(metadata, library) {
  1903. this._metadata = metadata;
  1904. this._functions = new Map();
  1905. this._attributes = new Map();
  1906. this._visibleCache = new Map();
  1907. if (library && Array.isArray(library.function)) {
  1908. for (const func of library.function) {
  1909. const name = func.signature.name;
  1910. if (this._functions.has(func.name)) {
  1911. throw new tf.Error("Duplicate function name '" + func.name + "'.");
  1912. }
  1913. this._functions.set(name, func);
  1914. }
  1915. }
  1916. }
  1917. type(name) {
  1918. if (this._functions.has(name)) {
  1919. const func = this._functions.get(name);
  1920. if (func instanceof tf.Function) {
  1921. return func;
  1922. }
  1923. this._functions.set(name, new tf.Function(this, func.signature.name, func));
  1924. return this._functions.get(name);
  1925. }
  1926. const type = this._metadata.type(name);
  1927. if (!type) {
  1928. this._functions.set(name, new tf.Function(this, name, null));
  1929. return this._functions.get(name);
  1930. }
  1931. return type;
  1932. }
  1933. attribute(type, name) {
  1934. const key = type + '::' + name;
  1935. if (!this._attributes.has(key)) {
  1936. const schema = this.type(type);
  1937. if (schema && schema.attributes) {
  1938. for (const attribute of schema.attributes) {
  1939. const key = type + '::' + attribute.name;
  1940. this._attributes.set(key, attribute);
  1941. }
  1942. }
  1943. }
  1944. return this._attributes.get(key);
  1945. }
  1946. visible(type, name) {
  1947. if (!this._visibleCache.has(type)) {
  1948. const set = new Set();
  1949. const schema = this.type(type);
  1950. if (schema && schema.inputs) {
  1951. for (const input of schema.inputs) {
  1952. if (input.typeAttr) {
  1953. set.add(input.typeAttr);
  1954. }
  1955. else if (input.typeListAttr) {
  1956. set.add(input.typeListAttr);
  1957. }
  1958. if (input.numberAttr) {
  1959. set.add(input.numberAttr);
  1960. }
  1961. }
  1962. }
  1963. if (schema && schema.outputs) {
  1964. for (const output of schema.outputs) {
  1965. if (output.typeAttr) {
  1966. set.add(output.typeAttr);
  1967. }
  1968. else if (output.typeListAttr) {
  1969. set.add(output.typeListAttr);
  1970. }
  1971. if (output.numberAttr) {
  1972. set.add(output.numberAttr);
  1973. }
  1974. }
  1975. }
  1976. this._visibleCache.set(type, set);
  1977. }
  1978. return !this._visibleCache.get(type).has(name);
  1979. }
  1980. };
  1981. tf.Metadata = class {
  1982. static open(context) {
  1983. if (tf.Metadata._metadata) {
  1984. return Promise.resolve(tf.Metadata._metadata);
  1985. }
  1986. return context.request('tf-metadata.json', 'utf-8', null).then((data) => {
  1987. tf.Metadata._metadata = new tf.Metadata(data);
  1988. return tf.Metadata._metadata;
  1989. }).catch(() => {
  1990. tf.Metadata._metadata = new tf.Metadata(null);
  1991. return tf.Metadata._metadata;
  1992. });
  1993. }
  1994. constructor(data) {
  1995. this._map = new Map();
  1996. if (data) {
  1997. const metadata = JSON.parse(data);
  1998. this._map = new Map(metadata.map((item) => [ item.name, item ]));
  1999. }
  2000. }
  2001. type(operator) {
  2002. return this._map.get(operator);
  2003. }
  2004. };
  2005. tf.Utility = class {
  2006. static decodeText(value) {
  2007. if (typeof value === 'string') {
  2008. return value;
  2009. }
  2010. if (value.length === 0) {
  2011. return '';
  2012. }
  2013. tf.Utility._utf8Decoder = tf.Utility._utf8Decoder || new TextDecoder('utf-8');
  2014. return tf.Utility._utf8Decoder.decode(value);
  2015. }
  2016. static dataType(type) {
  2017. if (!tf.Utility._dataTypes) {
  2018. const dataTypes = new Map();
  2019. const DataType = tf.proto.tensorflow.DataType;
  2020. for (let key of Object.keys(DataType)) {
  2021. const value = DataType[key];
  2022. key = key.startsWith('DT_') ? key.substring(3) : key;
  2023. dataTypes.set(value, key.toLowerCase());
  2024. }
  2025. dataTypes.set(DataType.DT_HALF, 'float16');
  2026. dataTypes.set(DataType.DT_FLOAT, 'float32');
  2027. dataTypes.set(DataType.DT_DOUBLE, 'float64');
  2028. tf.Utility._dataTypes = dataTypes;
  2029. }
  2030. return tf.Utility._dataTypes.has(type) ? tf.Utility._dataTypes.get(type) : '?';
  2031. }
  2032. static dataTypeKey(type) {
  2033. if (!tf.Utility._dataTypeKeys) {
  2034. const dataTypeKeys = new Map();
  2035. const DataType = tf.proto.tensorflow.DataType;
  2036. for (let key of Object.keys(DataType)) {
  2037. const value = DataType[key];
  2038. key = key.startsWith('DT_') ? key.substring(3) : key;
  2039. dataTypeKeys.set(key.toLowerCase(), value);
  2040. }
  2041. dataTypeKeys.set('float16', DataType.DT_HALF);
  2042. dataTypeKeys.set('float32', DataType.DT_FLOAT);
  2043. dataTypeKeys.set('float64', DataType.DT_DOUBLE);
  2044. tf.Utility._dataTypeKeys = dataTypeKeys;
  2045. }
  2046. return tf.Utility._dataTypeKeys.get(type);
  2047. }
  2048. static createGraph(metadata, nodes, output_arg_map) {
  2049. const context = {};
  2050. context.inputs = [];
  2051. context.outputs = [];
  2052. context.nodes = [];
  2053. const namespaces = new Set();
  2054. const node_map = new Map();
  2055. for (const node of nodes) {
  2056. const nodeName = node.name;
  2057. node_map.set(nodeName, node);
  2058. if (node.op != 'Const') {
  2059. const index = nodeName.lastIndexOf('/');
  2060. if (index != -1) {
  2061. const namespace = nodeName.substring(0, index);
  2062. namespaces.add(namespace);
  2063. }
  2064. }
  2065. node.output = [];
  2066. }
  2067. for (const node of nodes) {
  2068. const inputs = node.input;
  2069. node.input = [];
  2070. node.controlDependencies = [];
  2071. for (const input of inputs) {
  2072. const split = input.split(':', 3);
  2073. const input_name = split[0];
  2074. const input_index = split.length == 1 ? 0 : parseInt(split[split.length - 1]);
  2075. const from_name = input_name.startsWith('^') ? input_name.substring(1) : input_name;
  2076. const from = node_map.get(from_name);
  2077. const output_name = input_index == 0 ? from_name : from_name + ':' + input_index.toString();
  2078. const input_arg = from ? { name: output_name, from: from } : { name: output_name };
  2079. if (input_name.startsWith('^')) {
  2080. node.controlDependencies.push(input_arg);
  2081. }
  2082. else {
  2083. node.input.push(input_arg);
  2084. }
  2085. if (from) {
  2086. for (let i = from.output.length; i <= input_index; i++) {
  2087. from.output.push({ name: i === 0 ? from_name : from_name + ':' + i.toString(), to: [] });
  2088. }
  2089. from.output[input_index].to.push(node);
  2090. }
  2091. }
  2092. }
  2093. if (output_arg_map) {
  2094. for (const node of nodes) {
  2095. if (output_arg_map.has(node.name)) {
  2096. node.output.push({ name: node.name, to: [] });
  2097. }
  2098. }
  2099. }
  2100. const initializers = new Map();
  2101. const map_tensor = (name, node, kind) => {
  2102. if (node && node.op === 'Const' && node.input.length === 0 && node.output.length === 1 && node.output[0].to.length === 1 && node.controlDependencies.length === 0) {
  2103. const value = node.attr.value;
  2104. if (value && Object.prototype.hasOwnProperty.call(value, 'tensor')) {
  2105. const tensor = new tf.Tensor(value.tensor, name, kind);
  2106. return new tf.Argument(name, tensor.type, tensor);
  2107. }
  2108. }
  2109. return null;
  2110. };
  2111. const map_resource = (name, node, tensor) => {
  2112. if (node && node.op === 'Placeholder' && node.input.length === 0 && node.output.length === 1 && node.controlDependencies.length === 0) {
  2113. const dtype = node.attr.dtype.type;
  2114. if (dtype === tf.proto.tensorflow.DataType.DT_RESOURCE) {
  2115. return new tf.Argument(name, null, tensor);
  2116. }
  2117. }
  2118. return null;
  2119. };
  2120. for (const node of node_map.values()) {
  2121. if (node.op === 'Identity' && node.input.length === 1 && node.output.length === 1 && node.output[0].to.length === 1 && node.controlDependencies.length === 0) {
  2122. const initializer = map_tensor(node.name, node.input[0].from, 'Identity Constant');
  2123. if (initializer) {
  2124. initializers.set(initializer.name, initializer);
  2125. node_map.delete(initializer.name);
  2126. node_map.delete(node.input[0].name);
  2127. }
  2128. const identity = node.input[0].from;
  2129. if (identity && identity.op === 'Identity' && identity.input.length === 1 && identity.output.length === 1 && node.output[0].to.length === 1 && node.controlDependencies.length === 0) {
  2130. const initializer = map_tensor(node.name, identity.input[0].from, 'Identity Constant');
  2131. if (initializer) {
  2132. initializers.set(initializer.name, initializer);
  2133. node_map.delete(initializer.name);
  2134. node_map.delete(initializer.name);
  2135. node_map.delete(identity.name);
  2136. node_map.delete(node.name);
  2137. }
  2138. }
  2139. }
  2140. }
  2141. for (const node of node_map.values()) {
  2142. const initializer = map_tensor(node.name, node, 'Const');
  2143. if (initializer) {
  2144. initializers.set(initializer.name, initializer);
  2145. node_map.delete(node.name);
  2146. node_map.delete(initializer.name);
  2147. }
  2148. }
  2149. for (const node of node_map.values()) {
  2150. if (node.op === 'ReadVariableOp' && node.input.length === 1 && node.output.length === 1 && node.output[0].to.length === 1 && node.controlDependencies.length === 0) {
  2151. if (node.attr && node.attr.dtype && node.attr._output_shapes && node.attr._output_shapes.list && node.attr._output_shapes.list.shape) {
  2152. const tensor = new tf.proto.tensorflow.TensorProto();
  2153. tensor.dtype = node.attr.dtype.type;
  2154. tensor.tensor_shape = node.attr._output_shapes.list.shape[0];
  2155. const name = node.name;
  2156. const initializer = map_resource(name, node.input[0].from, new tf.Tensor(tensor, name, 'Resource Variable'));
  2157. if (initializer) {
  2158. initializers.set(initializer.name, initializer);
  2159. node_map.delete(initializer.name);
  2160. node_map.delete(node.input[0].name);
  2161. }
  2162. }
  2163. }
  2164. }
  2165. const input_map = new Map();
  2166. for (const node of node_map.values()) {
  2167. if (node.op == 'Placeholder' && node.input.length === 0 && node.output.length === 1 && node.controlDependencies.length === 0) {
  2168. const dtype = node.attr.dtype;
  2169. const shape = node.attr.shape;
  2170. if (dtype && dtype.type && shape && shape.shape) {
  2171. const name = node.name;
  2172. const type = new tf.TensorType(dtype.type, shape.shape);
  2173. const argument = new tf.Argument(name, type, null);
  2174. input_map.set(name, new tf.Parameter(name, [ argument ]));
  2175. node_map.delete(name);
  2176. }
  2177. }
  2178. }
  2179. const updatePyTorch = (node_map) => {
  2180. for (const node of node_map.values()) {
  2181. if (node.op === 'prim::Constant' && node.input.length === 0 && node.controlDependencies.length === 0 && node.attr && Object.keys(node.attr).length === 1 && node.attr.attr && node.attr.attr.s) {
  2182. const value = tf.Utility.decodeText(node.attr.attr.s);
  2183. const match = /{\s*value\s*:\s*(.*)\s*}/.exec(value);
  2184. if (match) {
  2185. node.value = match[1].trim();
  2186. }
  2187. const empty = /{\s*}/.exec(value);
  2188. if (empty) {
  2189. node.value = null;
  2190. }
  2191. }
  2192. if (node.op === 'prim::GetAttr' && node.input.length === 1 && node.controlDependencies.length === 0 && node.attr && Object.keys(node.attr).length === 1 && node.attr.attr && node.attr.attr.s) {
  2193. const value = tf.Utility.decodeText(node.attr.attr.s);
  2194. const match = /{\s*name\s*:\s*([A-za-z0-9_]*)\s*}/.exec(value);
  2195. if (match) {
  2196. node.value = match[1].trim();
  2197. }
  2198. }
  2199. if (node.op === 'IO Node' && node.controlDependencies.length === 0) {
  2200. const shape = node.attr && node.attr._output_shapes && node.attr._output_shapes.list && node.attr._output_shapes.list.shape ? node.attr._output_shapes.list.shape[0] : null;
  2201. const type = shape ? new tf.TensorType('?', shape) : null;
  2202. if (node.input.length === 0 && node.output.length === 1) {
  2203. context.inputs.push(new tf.Parameter(node.name, [
  2204. new tf.Argument(node.output[0].name, type, null)
  2205. ]));
  2206. node_map.delete(node.name);
  2207. }
  2208. if (node.input.length === 1 && node.output.length === 0) {
  2209. context.outputs.push(new tf.Parameter(node.name, [
  2210. new tf.Argument(node.input[0].name, type, null)
  2211. ]));
  2212. node_map.delete(node.name);
  2213. }
  2214. }
  2215. if (Object.keys(node.attr).length === 2 &&
  2216. node.attr.attr && node.attr.attr.s && node.attr._output_shapes) {
  2217. const value = tf.Utility.decodeText(node.attr.attr.s);
  2218. if (/\s*/.exec(value) || /{\s*}/.exec(value)) {
  2219. node.attr = {};
  2220. delete node._output_shapes;
  2221. }
  2222. }
  2223. }
  2224. const remove_input = (input, node) => {
  2225. const from = input.from;
  2226. if (from) {
  2227. for (const output of from.output) {
  2228. output.to = output.to.filter((to) => to !== node);
  2229. }
  2230. if (from.output.every((output) => output.to.length === 0) && from.controlDependencies.length === 0) {
  2231. from.remove = true;
  2232. }
  2233. delete input.from;
  2234. }
  2235. };
  2236. for (const node of node_map.values()) {
  2237. if (node.op === 'prim::ListConstruct' && node.input.every((input) => input.from.value !== undefined) && node.controlDependencies.length === 0) {
  2238. node.value = node.input.map((input) => input.from.value);
  2239. for (const input of node.input) {
  2240. remove_input(input, node);
  2241. }
  2242. node.input = [];
  2243. }
  2244. }
  2245. for (const node of node_map.values()) {
  2246. const remove = new Set();
  2247. for (let i = 0; i < node.input.length; i++) {
  2248. const input = node.input[i];
  2249. const from = input.from;
  2250. if (from) {
  2251. if (from.op === 'prim::GetAttr' && from.input.length === 1 && from.output.length === 1 && from.controlDependencies.length === 0 && from.value !== undefined) {
  2252. remove_input(input, node);
  2253. input.label = from.value;
  2254. const tensor = new tf.Tensor(null, input.name, from.op);
  2255. const argument = new tf.Argument(input.name, null, tensor);
  2256. initializers.set(input.name, argument);
  2257. }
  2258. if (from.op === 'prim::Constant' && from.input.length === 0 && from.controlDependencies.length === 0 && from.value !== undefined) {
  2259. input.constant = from.value;
  2260. remove_input(input, node);
  2261. remove.add(input.name);
  2262. }
  2263. if (from.op === 'prim::ListConstruct' && from.output.length === 1 && from.controlDependencies.length === 0 && from.value !== undefined) {
  2264. input.list = from.value;
  2265. remove_input(input, node);
  2266. remove.add(input.name);
  2267. }
  2268. }
  2269. }
  2270. if (node.__metadata__) {
  2271. for (const metadata of node.__metadata__) {
  2272. const parameters = Array.prototype.slice.call(metadata.inputs || []).concat(Array.prototype.slice.call(metadata.attributes || []));
  2273. let match = true;
  2274. const inputs = Array.from(node.input);
  2275. if (inputs.length > parameters.length) {
  2276. match = false;
  2277. }
  2278. while (inputs.length > 0 && match) {
  2279. match = false;
  2280. const input = inputs.shift();
  2281. delete input.metadata;
  2282. const parameter = parameters.shift();
  2283. switch (parameter.type) {
  2284. case 'Tensor': {
  2285. if ((input.constant === undefined && input.list === undefined) || input.constant === null) {
  2286. input.metadata = parameter;
  2287. match = true;
  2288. }
  2289. else {
  2290. inputs.unshift(input);
  2291. match = true;
  2292. }
  2293. break;
  2294. }
  2295. case 'int64': {
  2296. const value = parseInt(input.constant);
  2297. if (input.constant !== undefined && Number.isInteger(value)) {
  2298. input.attr = new tf.proto.tensorflow.AttrValue();
  2299. input.attr.i = value;
  2300. input.attr.metadata = parameter;
  2301. match = true;
  2302. }
  2303. break;
  2304. }
  2305. case 'float32': {
  2306. const value = parseFloat(input.constant);
  2307. if (input.constant !== undefined && !isNaN(value)) {
  2308. input.attr = new tf.proto.tensorflow.AttrValue();
  2309. input.attr.f = value;
  2310. input.attr.metadata = parameter;
  2311. match = true;
  2312. }
  2313. break;
  2314. }
  2315. case 'int64[]': {
  2316. if (Array.isArray(input.list)) {
  2317. const list = input.list.map((item) => parseInt(item));
  2318. if (list.every((value) => Number.isInteger(value))) {
  2319. input.attr = new tf.proto.tensorflow.AttrValue();
  2320. input.attr.list = new tf.proto.tensorflow.ListValue();
  2321. input.attr.list.i = list;
  2322. input.attr.metadata = parameter;
  2323. match = true;
  2324. }
  2325. }
  2326. break;
  2327. }
  2328. case 'boolean': {
  2329. if (input.constant === 'false' || input.constant === '0') {
  2330. input.attr = new tf.proto.tensorflow.AttrValue();
  2331. input.attr.b = false;
  2332. input.attr.metadata = parameter;
  2333. match = true;
  2334. }
  2335. else if (input.constant === 'true' || input.constant === '1') {
  2336. input.attr = new tf.proto.tensorflow.AttrValue();
  2337. input.attr.b = true;
  2338. input.attr.metadata = parameter;
  2339. match = true;
  2340. }
  2341. break;
  2342. }
  2343. case 'Scalar': {
  2344. const value = parseInt(input.constant);
  2345. if (input.constant !== undefined && Number.isInteger(value)) {
  2346. input.attr = new tf.proto.tensorflow.AttrValue();
  2347. input.attr.i = value;
  2348. input.attr.metadata = parameter;
  2349. match = true;
  2350. }
  2351. break;
  2352. }
  2353. default:
  2354. break;
  2355. }
  2356. }
  2357. if (match) {
  2358. node.metadata = Object.assign({}, metadata);
  2359. node.metadata.name = node.op;
  2360. break;
  2361. }
  2362. else {
  2363. for (const input of node.input) {
  2364. delete input.metadata;
  2365. delete input.attr;
  2366. }
  2367. }
  2368. }
  2369. }
  2370. node.input = node.input.filter((input, index) => {
  2371. if (input.attr) {
  2372. const name = input.attr.metadata ? input.attr.metadata.name : index.toString();
  2373. node.attr[name] = input.attr;
  2374. }
  2375. else if (input.constant !== undefined && input.constant !== null) {
  2376. const attr = new tf.proto.tensorflow.AttrValue();
  2377. attr.s = input.constant;
  2378. node.attr[index.toString()] = attr;
  2379. }
  2380. else if (input.list !== undefined) {
  2381. const attr = new tf.proto.tensorflow.AttrValue();
  2382. attr.list = new tf.proto.tensorflow.ListValue();
  2383. attr.list.s = input.list;
  2384. node.attr[index.toString()] = attr;
  2385. }
  2386. return !remove.has(input.name);
  2387. });
  2388. }
  2389. for (const node of node_map.values()) {
  2390. if (node.op === 'prim::GetAttr' && node.remove) {
  2391. node_map.delete(node.name);
  2392. }
  2393. if (node.op === 'prim::Constant' && node.remove) {
  2394. node_map.delete(node.name);
  2395. }
  2396. if (node.op === 'prim::ListConstruct' && node.remove) {
  2397. node_map.delete(node.name);
  2398. }
  2399. }
  2400. };
  2401. updatePyTorch(node_map);
  2402. for (const input of input_map.values()) {
  2403. context.inputs.push(input);
  2404. }
  2405. for (const node of node_map.values()) {
  2406. context.nodes.push(new tf.Node(metadata, node, namespaces, initializers));
  2407. }
  2408. return context;
  2409. }
  2410. };
  2411. tf.JsonReader = class {
  2412. static decodeGraphDef(json) {
  2413. const message = new tf.proto.tensorflow.GraphDef();
  2414. message.node = json.node.map((node) => tf.JsonReader.decodeNodeDef(node));
  2415. message.library = tf.JsonReader.decodeFunctionDefLibrary(json.library);
  2416. if (message.versions) {
  2417. message.versions = tf.JsonReader.decodeVersionDef(json.versions);
  2418. }
  2419. return message;
  2420. }
  2421. static decodeNodeDef(json) {
  2422. const message = new tf.proto.tensorflow.NodeDef();
  2423. message.name = json.name;
  2424. message.op = json.op;
  2425. message.input = json.input || [];
  2426. if (json.device) {
  2427. message.device = json.device;
  2428. }
  2429. message.attr = {};
  2430. if (json.attr) {
  2431. for (const entry of Object.entries(json.attr)) {
  2432. message.attr[entry[0]] = tf.JsonReader.decodeAttrValue(entry[1]);
  2433. }
  2434. }
  2435. return message;
  2436. }
  2437. static decodeAttrValue(json) {
  2438. const message = new tf.proto.tensorflow.AttrValue();
  2439. const keys = Object.keys(json);
  2440. if (keys.length !== 1) {
  2441. throw new tf.Error("Unsupported JSON tensorflow.AttrValue '" + JSON.stringify(keys) + "'.");
  2442. }
  2443. const key = keys[0];
  2444. const value = json[key];
  2445. switch (key) {
  2446. case 'type':
  2447. message.type = typeof value === 'number' ? value : tf.proto.tensorflow.DataType[value];
  2448. break;
  2449. case 'shape':
  2450. message.shape = tf.JsonReader.decodeTensorShapeProto(value);
  2451. break;
  2452. case 'tensor':
  2453. message.tensor = tf.JsonReader.decodeTensorProto(value);
  2454. break;
  2455. case 'b':
  2456. message[key] = value;
  2457. break;
  2458. case 'f':
  2459. message[key] = parseFloat(value);
  2460. break;
  2461. case 'i':
  2462. message[key] = parseInt(value, 10);
  2463. break;
  2464. case 's':
  2465. message[key] = typeof value === 'string' ? atob(value) : tf.Utility.decodeText(Uint8Array.from(value));
  2466. break;
  2467. case 'list':
  2468. message.list = tf.JsonReader.decodeAttrValueListValue(json.list);
  2469. break;
  2470. case 'func':
  2471. message[key]= value;
  2472. break;
  2473. default:
  2474. throw new tf.Error("Unsupported JSON 'tensorflow.AttrValue." + key + "'.");
  2475. }
  2476. return message;
  2477. }
  2478. static decodeAttrValueListValue(json) {
  2479. const message = new tf.proto.tensorflow.AttrValue.ListValue();
  2480. const properties = Object.keys(json);
  2481. if (properties.length > 0) {
  2482. const keys = properties.filter((key) => Array.isArray(json[key]) && json[key].length > 0);
  2483. if (keys.length !== 1) {
  2484. throw new tf.Error("Unsupported JSON tensorflow.AttrValue.ListValue '" + JSON.stringify(keys) + "'.");
  2485. }
  2486. const key = keys[0];
  2487. const list = json[key];
  2488. switch (key) {
  2489. case 'i':
  2490. message[key] = list.map((value) => parseInt(value, 10));
  2491. break;
  2492. case 's':
  2493. message[key] = list.map((value) => typeof value === 'string' ? atob(value) : tf.Utility.decodeText(Uint8Array.from(value)));
  2494. break;
  2495. case 'type':
  2496. message[key] = list.map((value) => tf.proto.tensorflow.DataType[value]);
  2497. break;
  2498. case 'shape':
  2499. message[key] = list.map((shape) => tf.JsonReader.decodeTensorShapeProto(shape));
  2500. break;
  2501. default:
  2502. throw new tf.Error("Unsupported JSON 'tensorflow.AttrValue.ListValue." + key + "'.");
  2503. }
  2504. }
  2505. return message;
  2506. }
  2507. static decodeTensorProto(json) {
  2508. const message = new tf.proto.tensorflow.TensorProto();
  2509. message.dtype = tf.proto.tensorflow.DataType[json.dtype];
  2510. message.tensor_shape = tf.JsonReader.decodeTensorShapeProto(json.tensorShape);
  2511. return message;
  2512. }
  2513. static decodeTensorShapeProto(json) {
  2514. const message = new tf.proto.tensorflow.TensorShapeProto();
  2515. message.dim = (json.dim || []).map((json) => {
  2516. const message = new tf.proto.tensorflow.TensorShapeProto.Dim();
  2517. message.size = json.size;
  2518. message.name = json.name;
  2519. return message;
  2520. });
  2521. return message;
  2522. }
  2523. static decodeVersionDef(json) {
  2524. const message = new tf.proto.tensorflow.VersionDef();
  2525. message.producer = json.producer;
  2526. message.min_consumer = json.min_consumer;
  2527. message.bad_consumers = json.bad_consumers ? json.bad_consumers : [];
  2528. return message;
  2529. }
  2530. static decodeFunctionDefLibrary(json) {
  2531. const message = new tf.proto.tensorflow.FunctionDefLibrary();
  2532. message.function = json ? (json.function || []).map((json) => tf.JsonReader.decodeFunctionDef(json)) : [];
  2533. return message;
  2534. }
  2535. static decodeFunctionDef(json) {
  2536. const message = new tf.proto.tensorflow.FunctionDef();
  2537. message.signature = tf.JsonReader.decodeOpDef(json.signature);
  2538. message.attr = {};
  2539. if (json.attr) {
  2540. for (const entry of Object.entries(json.attr)) {
  2541. message.attr[entry[0]] = tf.JsonReader.decodeAttrValue(entry[1]);
  2542. }
  2543. }
  2544. message.nodeDef = (json.nodeDef || []).map((json) => tf.JsonReader.decodeNodeDef(json));
  2545. message.ret = json.ret;
  2546. message.control_ret = json.control_ret;
  2547. return message;
  2548. }
  2549. static decodeOpDef(json) {
  2550. const message = new tf.proto.tensorflow.OpDef();
  2551. message.name = json.name;
  2552. message.input_arg = json.inputArg.map((json) => tf.JsonReader.decodeArgDef(json));
  2553. message.output_arg = json.outputArg.map((json) => tf.JsonReader.decodeArgDef(json));
  2554. return message;
  2555. }
  2556. static decodeArgDef(json) {
  2557. const message = new tf.proto.tensorflow.OpDef.ArgDef();
  2558. message.name = json.name;
  2559. message.description = json.decscription;
  2560. return message;
  2561. }
  2562. };
  2563. tf.Error = class extends Error {
  2564. constructor(message) {
  2565. super(message);
  2566. this.name = 'Error loading TensorFlow model.';
  2567. }
  2568. };
  2569. if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  2570. module.exports.ModelFactory = tf.ModelFactory;
  2571. }