tf.js 104 KB

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