tf.js 99 KB

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