tf.js 111 KB

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