tf.js 112 KB

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