diff --git a/dist/demo-browser-index.js b/dist/demo-browser-index.js index 3a6bdd26..55962386 100644 --- a/dist/demo-browser-index.js +++ b/dist/demo-browser-index.js @@ -1,75 +1,24759 @@ -var pf=Object.defineProperty,ng=N=>pf(N,"__esModule",{value:!0}),Mr=(N,i)=>()=>(i||(i={exports:{}},N(i.exports,i)),i.exports),Kh=(N,i)=>{ng(N);for(var ke in i)pf(N,ke,{get:i[ke],enumerable:!0})},ag=Mr(()=>{}),ig=Mr(()=>{}),Pp=Mr(()=>{}),ml=Mr(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});var i=function(t,e){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,a){n.__proto__=a}||function(n,a){for(var c in a)a.hasOwnProperty(c)&&(n[c]=a[c])},i(t,e)};function ke(t,e){i(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function O(t,e,n,a){return new(n||(n=Promise))(function(c,d){function y(C){try{_(a.next(C))}catch(D){d(D)}}function v(C){try{_(a.throw(C))}catch(D){d(D)}}function _(C){C.done?c(C.value):new n(function(D){D(C.value)}).then(y,v)}_((a=a.apply(t,e||[])).next())})}function H(t,e){var n={label:0,sent:function(){if(d[0]&1)throw d[1];return d[1]},trys:[],ops:[]},a,c,d,y;return y={next:v(0),throw:v(1),return:v(2)},typeof Symbol=="function"&&(y[Symbol.iterator]=function(){return this}),y;function v(C){return function(D){return _([C,D])}}function _(C){if(a)throw new TypeError("Generator is already executing.");for(;n;)try{if(a=1,c&&(d=C[0]&2?c.return:C[0]?c.throw||((d=c.return)&&d.call(c),0):c.next)&&!(d=d.call(c,C[1])).done)return d;(c=0,d)&&(C=[C[0]&2,d.value]);switch(C[0]){case 0:case 1:d=C;break;case 4:return n.label++,{value:C[1],done:!1};case 5:n.label++,c=C[1],C=[0];continue;case 7:C=n.ops.pop(),n.trys.pop();continue;default:if(!(d=n.trys,d=d.length>0&&d[d.length-1])&&(C[0]===6||C[0]===2)){n=0;continue}if(C[0]===3&&(!d||C[1]>d[0]&&C[1]0;)a=Math.random()*e|0,e--,n=t[e],t[e]=t[a],t[a]=n}function me(t,e,n){return Math.max(t,Math.min(e,n))}function ae(t){return t%2===0?t:t+1}function w(t){for(var e=0,n=0;n=n){c();return}setTimeout(y,v)};y()})}function ar(t,e){for(var n=1,a=-1,c=0;c=0)n*=t[c];else if(t[c]===-1){if(a!==-1)throw Error("Shapes can only have 1 implicit size. "+("Found -1 at dim "+a+" and dim "+c));a=c}else if(t[c]<0)throw Error("Shapes can not be < 0. Found "+t[c]+" at dim "+c);if(a===-1){if(e>0&&e!==n)throw Error("Size("+e+") must match the product of shape "+t);return t}if(n===0)throw Error("Cannot infer the missing size in ["+t+"] when there are 0 elements");if(e%n!==0)throw Error("The implicit shape can't be a fractional number. "+("Got "+e+" / "+n));var d=t.slice();return d[a]=e/n,d}function qt(t,e){var n=e.length;return t=t==null?e.map(function(a,c){return c}):[].concat(t),W(t.every(function(a){return a>=-n&&av)&&t[v]===1&&(n.push(t[v]),a.push(v)),d[y]<=v&&y++}t[v]!==1&&(n.push(t[v]),a.push(v))}return{newShape:n,keptDims:a}}function jr(t,e){var n=null;if(t==null||t==="float32")n=new Float32Array(e);else if(t==="int32")n=new Int32Array(e);else if(t==="bool")n=new Uint8Array(e);else throw new Error("Unknown data type "+t);return n}function _r(t,e){var n=null;if(t==null||t==="float32")n=new Float32Array(e);else if(t==="int32")n=new Int32Array(e);else if(t==="bool")n=new Uint8Array(e);else if(t==="string")n=new Array(e);else throw new Error("Unknown data type "+t);return n}function tr(t,e){for(var n=0;n=0;--a)n[a]=n[a+1]*t[a+1];return n}function xn(t,e,n){var a=new Array;if(e.length===1)for(var c=e[0],d=0;d=0,function(){return"Tensor must have a shape comprised of positive integers but got "+("shape ["+t+"].")})})}function jn(t,e,n){if(e===0)return 0;if(e===1)return t[0];for(var a=t[t.length-1],c=0;c0?Pe:"")+" "}}console.log("%c"+_+" %c"+v+" %c"+C+"D "+B+" %c"+D+" %c"+U+" %c"+y,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")},t}();function A(t,e,n){for(var a={},c={},d=0;d=0;d--)for(var y=t[d],v=y.inputs,B=0;B=0;d--)c(d)}var oe=20,ee=3,_e=7;function ce(t,e,n,a){var c=Ca(e),d=de(t,e,n,c),y=e.length,v=Re(t,e,n,c,d),_=["Tensor"];return a&&(_.push(" dtype: "+n),_.push(" rank: "+y),_.push(" shape: ["+e+"]"),_.push(" values:")),_.push(v.map(function(C){return" "+C}).join(` -`)),_.join(` -`)}function de(t,e,n,a){var c=Tt(e),d=a[a.length-1],y=new Array(d).fill(0),v=e.length,_=n==="complex64"?Oe(t):t;if(v>1)for(var C=0;Coe){var D=ee*y,B=Array.from(t.slice(0,D)),U=Array.from(t.slice((v-ee)*y,v*y));return n==="complex64"&&(B=Oe(B),U=Oe(U)),["["+B.map(function(er,mr){return ye(er,c[mr],n)}).join(", ")+", ..., "+U.map(function(er,mr){return ye(er,c[v-ee+mr],n)}).join(", ")+"]"]}var J=n==="complex64"?Oe(t):Array.from(t);return["["+J.map(function(er,mr){return ye(er,c[mr],n)}).join(", ")+"]"]}var fe=e.slice(1),Pe=a.slice(1),Me=a[0]*y,He=[];if(v>oe){for(var ct=0;ct=this.shape[a]){var v="Requested out of range element at "+e+". "+(" Buffer shape="+this.shape);throw new Error(v)}a++}for(var _=e[e.length-1],C=0;C0)throw new Error("Backend '"+this.backendName+"' has an internal memory leak "+("("+v+" data ids) after running '"+e+"'"))},t.prototype.runKernelFunc=function(e,n,a,c,d,y,v){var _=this,C,D=[],B=this.isTapeOn();c==null&&(c=this.state.activeScope!=null?this.state.activeScope.name:"");var U=this.state.numBytes,J=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);var fe,Pe=Bs(c,this.backendName),Me;if(Pe!=null)fe=function(){var It=_.backend.numDataIds();Me=Pe.kernelFunc({inputs:n,attrs:d,backend:_.backend});var Ct=Array.isArray(Me)?Me:[Me];_.shouldCheckForMemLeaks()&&_.checkKernelForMemLeak(c,It,Ct);var Bt=Ct.map(function(mr){var Gr=mr.dataId,en=mr.shape,Qr=mr.dtype;return _.makeTensorFromDataId(Gr,en,Qr)});if(B){var sr=_.getTensorsForGradient(c,n,Bt);if(sr==null){v==null&&(v=[]);var er=Bt.filter(function(mr,Gr){return v[Gr]});sr=(y||[]).slice().concat(er)}D=_.saveTensorsForBackwardMode(sr)}return Bt};else{var He=function(It){if(!B)return;D=It.map(function(Ct){return _.keep(_.clone(Ct))})};fe=function(){var It=_.backend.numDataIds();Me=_.tidy(function(){return e(_.backend,He)});var Ct=Array.isArray(Me)?Me:[Me];return _.shouldCheckForMemLeaks()&&_.checkKernelForMemLeak(c,It,Ct),Ct}}var ct;return this.scopedRun(function(){return _.state.kernelDepth++},function(){return _.state.kernelDepth--},function(){!_.ENV.getBool("DEBUG")&&!_.state.profiling?C=fe():(ct=_.profiler.profileKernel(c,n,function(){return fe()}),_.ENV.getBool("DEBUG")&&_.profiler.logKernelProfile(ct),C=ct.outputs)}),B&&this.addTapeNode(c,n,C,a,D,d),this.state.profiling&&this.state.activeProfile.kernels.push({name:c,bytesAdded:this.state.numBytes-U,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-J,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(n).map(function(It){return n[It]!=null?n[It].shape:null}),outputShapes:C.map(function(It){return It.shape}),kernelTimeMs:ct.timeMs,extraInfo:ct.extraInfo}),Array.isArray(Me)?C:C[0]},t.prototype.saveTensorsForBackwardMode=function(e){var n=this,a=e.map(function(c){return n.keep(n.clone(c))});return a},t.prototype.getTensorsForGradient=function(e,n,a){var c=Ws(e);if(c!=null){var d=c.inputsToSave||[],y=c.outputsToSave||[],v=void 0;c.saveAllInputs?(W(Array.isArray(n),function(){return"saveAllInputs is true, expected inputs to be an array."}),v=Object.keys(n).map(function(C){return n[C]})):v=d.map(function(C){return n[C]});var _=a.filter(function(C,D){return y[D]});return v.concat(_)}return null},t.prototype.makeTensor=function(e,n,a,c){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");a=a||"float32",c=c||this.backend;var d=e;a==="string"&&yn(e[0])&&(d=e.map(function(D){return Xi(D)}));var y=c.write(d,n,a),v=new $(n,a,y,this.nextTensorId());if(this.incRef(v,c),a==="string"){var _=this.state.tensorInfo.get(y),C=Na(d);this.state.numBytes+=C-_.bytes,_.bytes=C}return v},t.prototype.makeTensorFromDataId=function(e,n,a,c){a=a||"float32";var d=new $(n,a,e,this.nextTensorId());return this.incRef(d,c),d},t.prototype.makeVariable=function(e,n,a,c){n===void 0&&(n=!0),a=a||this.nextVariableId().toString(),c!=null&&c!==e.dtype&&(e=e.cast(c));var d=new et(e,n,a,this.nextTensorId());if(this.state.registeredVariables[d.name]!=null)throw new Error("Variable with name "+d.name+" was already registered");return this.state.registeredVariables[d.name]=d,this.incRef(d,this.backend),d},t.prototype.incRef=function(e,n){var a=this.state.tensorInfo.has(e.dataId)?this.state.tensorInfo.get(e.dataId).refCount:0;if(this.state.numTensors++,e.dtype==="string"&&this.state.numStringTensors++,a===0){this.state.numDataBuffers++;var c=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(c=e.size*Wa(e.dtype)),this.state.tensorInfo.set(e.dataId,{backend:n||this.backend,dtype:e.dtype,shape:e.shape,bytes:c,refCount:0}),this.state.numBytes+=c}this.state.tensorInfo.get(e.dataId).refCount++,e instanceof et||this.track(e)},t.prototype.disposeTensor=function(e){if(!this.state.tensorInfo.has(e.dataId))return;this.state.numTensors--,e.dtype==="string"&&this.state.numStringTensors--;var n=this.state.tensorInfo.get(e.dataId),a=n.refCount;a<=1?(e.dtype!=="complex64"&&(this.state.numBytes-=n.bytes),this.state.numDataBuffers--,n.backend.disposeData(e.dataId),this.state.tensorInfo.delete(e.dataId)):this.state.tensorInfo.get(e.dataId).refCount--},t.prototype.disposeVariables=function(){for(var e in this.state.registeredVariables){var n=this.state.registeredVariables[e];this.disposeVariable(n)}},t.prototype.disposeVariable=function(e){this.disposeTensor(e),this.state.registeredVariables[e.name]!=null&&delete this.state.registeredVariables[e.name]},t.prototype.memory=function(){var e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,e.reasons==null&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e},t.prototype.profile=function(e){return O(this,void 0,void 0,function(){var n,a,c,d,y,v,_,C;return H(this,function(D){switch(D.label){case 0:return this.state.profiling=!0,n=this.state.numBytes,a=this.state.numTensors,this.state.activeProfile.kernels=[],c=this.state.activeProfile,[4,e()];case 1:c.result=D.sent(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max.apply(Math,this.state.activeProfile.kernels.map(function(B){return B.totalBytesSnapshot})),this.state.activeProfile.newBytes=this.state.numBytes-n,this.state.activeProfile.newTensors=this.state.numTensors-a,d=0,y=this.state.activeProfile.kernels,D.label=2;case 2:return d0&&this.state.kernelDepth===0},t.prototype.addTapeNode=function(e,n,a,c,d,y){var v=this,_={id:this.state.nextTapeNodeId++,kernelName:e,inputs:n,outputs:a,saved:d},C=Ws(e);C!=null&&(c=C.gradFunc),c!=null&&(_.gradient=function(D){return D=D.map(function(B,U){if(B==null){var J=a[U],fe=ha(J.size,J.dtype);return v.makeTensor(fe,J.shape,J.dtype)}return B}),c(D.length>1?D:D[0],d,y)}),this.state.activeTape.push(_)},t.prototype.keep=function(e){return e.kept=!0,e},t.prototype.startTape=function(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++},t.prototype.endTape=function(){this.state.gradientDepth--},t.prototype.startScope=function(e){var n={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(n.name=e),this.state.scopeStack.push(n),this.state.activeScope=n},t.prototype.endScope=function(e){for(var n=this,a=Ot(e),c=new Set(a.map(function(_){return _.id})),d=0;d0,function(){return"gradients() received an empty list of xs."}),a!=null&&a.dtype!=="float32")throw new Error("dy must have 'float32' dtype, but has '"+a.dtype+"'");var y=this.scopedRun(function(){return d.startTape()},function(){return d.endTape()},function(){return d.tidy("forward",e)});W(y instanceof $,function(){return"The result y returned by f() must be a tensor."});var v=A(this.state.activeTape,n,y);if(!c&&v.length===0&&n.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",function(){var _={};_[y.id]=a??cr(y.shape),V(_,v,function(D){return d.tidy(D)},br);var C=n.map(function(D){return _[D.id]});return d.state.gradientDepth===0&&(d.state.activeTape.forEach(function(D){for(var B=0,U=D.saved;B0,function(){return"Element arr["+n.join("][")+"] should be a primitive, "+("but is an array of "+t.length+" elements")}),W(t.length===e[0],function(){return"Element arr["+n.join("][")+"] should have "+e[0]+" "+("elements, but has "+t.length+" elements")});for(var a=e.slice(1),c=0;c=0&&(c=a),wn(a,c,e,n),t==null||!Tn(t)&&!Array.isArray(t)&&typeof t!="number"&&typeof t!="boolean"&&typeof t!="string"){var d=t==null?"null":t.constructor.name;throw new Error("Argument '"+e+"' passed to '"+n+"' must be a "+("Tensor or TensorLike, but got '"+d+"'"))}var y=Er(t,c);!Tn(t)&&!Array.isArray(t)&&(t=[t]);var v=!0,_=c!=="string"?Si(t,c):nr(t,[],v);return Ie.makeTensor(_,y,c)}function Nn(t,e,n,a){if(a===void 0&&(a="numeric"),!Array.isArray(t))throw new Error("Argument "+e+" passed to "+n+" must be a `Tensor[]` or `TensorLike[]`");var c=t;return c.map(function(d,y){return ie(d,e+"["+y+"]",n)},a)}var bn="__op";function Ee(t){var e=Object.keys(t);if(e.length!==1)throw new Error("Please provide an object with a single key (operation name) mapping to a function. Got an object with "+(e.length+" keys."));var n=e[0],a=t[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n=n+bn;var c=function(){for(var d=[],y=0;y>10]+(v&1023)]+e[v>>10];d[y]=_}return new Float32Array(c)}}var si=function(){function t(){this.saveRouters=[],this.loadRouters=[]}return t.getInstance=function(){return t.instance==null&&(t.instance=new t),t.instance},t.registerSaveRouter=function(e){t.getInstance().saveRouters.push(e)},t.registerLoadRouter=function(e){t.getInstance().loadRouters.push(e)},t.getSaveHandlers=function(e){return t.getHandlers(e,"save")},t.getLoadHandlers=function(e,n){return t.getHandlers(e,"load",n)},t.getHandlers=function(e,n,a){var c=[],d=n==="load"?t.getInstance().loadRouters:t.getInstance().saveRouters;return d.forEach(function(y){var v=y(e,a);v!==null&&c.push(v)}),c},t}(),Su=function(t){return si.registerSaveRouter(t)},Iu=function(t){return si.registerLoadRouter(t)},lc=function(t){return si.getSaveHandlers(t)},xs=function(t,e){return si.getLoadHandlers(t,e)},Ii="tensorflowjs",_s=1,bo="models_store",so="model_info_store";function Nu(){if(!Rr().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var t=typeof window=="undefined"?self:window,e=t.indexedDB||t.mozIndexedDB||t.webkitIndexedDB||t.msIndexedDB||t.shimIndexedDB;if(e==null)throw new Error("The current browser does not appear to support IndexedDB.");return e}function uu(t){var e=t.result;e.createObjectStore(bo,{keyPath:"modelPath"}),e.createObjectStore(so,{keyPath:"modelPath"})}var ws=function(){function t(e){if(this.indexedDB=Nu(),e==null||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}return t.prototype.save=function(e){return O(this,void 0,void 0,function(){return H(this,function(n){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return[2,this.databaseAction(this.modelPath,e)]})})},t.prototype.load=function(){return O(this,void 0,void 0,function(){return H(this,function(e){return[2,this.databaseAction(this.modelPath)]})})},t.prototype.databaseAction=function(e,n){var a=this;return new Promise(function(c,d){var y=a.indexedDB.open(Ii,_s);y.onupgradeneeded=function(){return uu(y)},y.onsuccess=function(){var v=y.result;if(n==null){var _=v.transaction(bo,"readonly"),C=_.objectStore(bo),D=C.get(a.modelPath);D.onsuccess=function(){if(D.result==null)return v.close(),d(new Error("Cannot find model with path '"+a.modelPath+"' in IndexedDB."));c(D.result.modelArtifacts)},D.onerror=function(Me){return v.close(),d(D.error)},_.oncomplete=function(){return v.close()}}else{var B=dn(n),U=v.transaction(so,"readwrite"),J=U.objectStore(so),fe=J.put({modelPath:a.modelPath,modelArtifactsInfo:B}),Pe;fe.onsuccess=function(){Pe=v.transaction(bo,"readwrite");var Me=Pe.objectStore(bo),He=Me.put({modelPath:a.modelPath,modelArtifacts:n,modelArtifactsInfo:B});He.onsuccess=function(){return c({modelArtifactsInfo:B})},He.onerror=function(ct){J=U.objectStore(so);var It=J.delete(a.modelPath);It.onsuccess=function(){return v.close(),d(He.error)},It.onerror=function(Ct){return v.close(),d(He.error)}}},fe.onerror=function(Me){return v.close(),d(fe.error)},U.oncomplete=function(){Pe==null?v.close():Pe.oncomplete=function(){return v.close()}}}},y.onerror=function(v){return d(y.error)}})},t.URL_SCHEME="indexeddb://",t}(),Cu=function(t){return Rr().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(ws.URL_SCHEME)?cu(t.slice(ws.URL_SCHEME.length)):null};si.registerSaveRouter(Cu),si.registerLoadRouter(Cu);function cu(t){return new ws(t)}function Tu(t){return t.startsWith(ws.URL_SCHEME)?t.slice(ws.URL_SCHEME.length):t}var hc=function(){function t(){this.indexedDB=Nu()}return t.prototype.listModels=function(){return O(this,void 0,void 0,function(){var e=this;return H(this,function(n){return[2,new Promise(function(a,c){var d=e.indexedDB.open(Ii,_s);d.onupgradeneeded=function(){return uu(d)},d.onsuccess=function(){var y=d.result,v=y.transaction(so,"readonly"),_=v.objectStore(so),C=_.getAll();C.onsuccess=function(){for(var D={},B=0,U=C.result;B0,function(){return"scheme must not be an empty string."});var a=t.getInstance();W(a.managers[e]==null,function(){return"A model store manager is already registered for scheme '"+e+"'."}),a.managers[e]=n},t.getManager=function(e){var n=this.getInstance().managers[e];if(n==null)throw new Error("Cannot find model manager for scheme '"+e+"'");return n},t.getSchemes=function(){return Object.keys(this.getInstance().managers)},t}();function Uo(t){if(t.indexOf(Wo)===-1)throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+(""+co.getSchemes().join(",")));return{scheme:t.split(Wo)[0],path:t.split(Wo)[1]}}function lu(t,e,n){return n===void 0&&(n=!1),O(this,void 0,void 0,function(){var a,c,d,y,v,_,C,D,B;return H(this,function(U){switch(U.label){case 0:return W(t!==e,function(){return"Old path and new path are the same: '"+t+"'"}),a=si.getLoadHandlers(t),W(a.length>0,function(){return"Copying failed because no load handler is found for source URL "+t+"."}),W(a.length<2,function(){return"Copying failed because more than one ("+a.length+") "+("load handlers for source URL "+t+".")}),c=a[0],d=si.getSaveHandlers(e),W(d.length>0,function(){return"Copying failed because no save handler is found for destination "+("URL "+e+".")}),W(d.length<2,function(){return"Copying failed because more than one ("+a.length+") "+("save handlers for destination URL "+e+".")}),y=d[0],v=Uo(t).scheme,_=Uo(t).path,C=v===Uo(t).scheme,[4,c.load()];case 1:return D=U.sent(),n&&C?[4,co.getManager(v).removeModel(_)]:[3,3];case 2:U.sent(),U.label=3;case 3:return[4,y.save(D)];case 4:return B=U.sent(),n&&!C?[4,co.getManager(v).removeModel(_)]:[3,6];case 5:U.sent(),U.label=6;case 6:return[2,B.modelArtifactsInfo]}})})}function as(){return O(this,void 0,void 0,function(){var t,e,n,a,c,d,y,v;return H(this,function(_){switch(_.label){case 0:t=co.getSchemes(),e={},n=0,a=t,_.label=1;case 1:return n0,function(){return"promises must be a none empty array"})}function v(_,C){W(_>=0&&_<=1,function(){return"Progress fraction must be in range [0, 1], but "+("got startFraction "+_)}),W(C>=0&&C<=1,function(){return"Progress fraction must be in range [0, 1], but "+("got endFraction "+C)}),W(C>=_,function(){return"startFraction must be no more than endFraction, but "+("got startFraction "+_+" and endFraction ")+(""+C)})}return Promise.all(t.map(d))}function pu(t,e){return O(this,void 0,void 0,function(){var n,a,c,d,y,v,_,C,D,B,U;return H(this,function(J){switch(J.label){case 0:return e==null&&(e={}),n=e.fetchFunc==null?Rr().platform.fetch:e.fetchFunc,a=t.map(function(fe){return n(fe,e.requestInit,{isBinary:!0})}),c=0,d=.5,e.onProgress==null?[4,Promise.all(a)]:[3,2];case 1:return v=J.sent(),[3,4];case 2:return[4,Sc(a,e.onProgress,c,d)];case 3:v=J.sent(),J.label=4;case 4:return y=v,_=y.map(function(fe){return fe.arrayBuffer()}),C=.5,D=1,e.onProgress==null?[4,Promise.all(_)]:[3,6];case 5:return U=J.sent(),[3,8];case 6:return[4,Sc(_,e.onProgress,C,D)];case 7:U=J.sent(),J.label=8;case 8:return B=U,[2,B]}})})}function Ic(t,e,n,a){return e===void 0&&(e=""),O(this,void 0,void 0,function(){var c,d;return H(this,function(y){return c=function(v){return pu(v,{requestInit:a})},d=Mu(c),[2,d(t,e,n)]})})}function Mu(t){var e=this;return function(n,a,c){return a===void 0&&(a=""),O(e,void 0,void 0,function(){var d,y,v,_,C,D,B,U,J,fe;return H(this,function(Pe){switch(Pe.label){case 0:if(d=n.map(function(){return!1}),y={},v=c!=null?c.map(function(){return!1}):[],_=[],n.forEach(function(Me,He){var ct=0;Me.weights.forEach(function(It){var Ct="quantization"in It?It.quantization.dtype:It.dtype,Bt=Ya[Ct]*Tt(It.shape),sr=function(){d[He]=!0,y[He]==null&&(y[He]=[]),y[He].push({manifestEntry:It,groupOffset:ct,sizeBytes:Bt})};c!=null?c.forEach(function(er,mr){er===It.name&&(sr(),v[mr]=!0)}):sr(),_.push(It.name),ct+=Bt})}),!v.every(function(Me){return Me}))throw C=c.filter(function(Me,He){return!v[He]}),new Error("Could not find weights in manifest with names: "+(C.join(", ")+`. -`)+"Manifest JSON has weights with names: "+(_.join(", ")+"."));return D=d.reduce(function(Me,He,ct){return He&&Me.push(ct),Me},[]),B=[],D.forEach(function(Me){n[Me].paths.forEach(function(He){var ct=a+(a.endsWith("/")?"":"/")+He;B.push(ct)})}),[4,t(B)];case 1:return U=Pe.sent(),J={},fe=0,D.forEach(function(Me){for(var He=n[Me].paths.length,ct=0,It=0;It0,function(){return"URL path for http must not be null, undefined or empty."}),Array.isArray(e)&&W(e.length===2,function(){return"URL paths for http must have a length of 2, "+("(actual length is "+e.length+").")}),this.path=e,n.requestInit!=null&&n.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=n.requestInit||{}}return t.prototype.save=function(e){return O(this,void 0,void 0,function(){var n,a,c,d;return H(this,function(y){switch(y.label){case 0:if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");return n=Object.assign({method:this.DEFAULT_METHOD},this.requestInit),n.body=new FormData,a=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],c={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,userDefinedMetadata:e.userDefinedMetadata,weightsManifest:a},n.body.append("model.json",new Blob([JSON.stringify(c)],{type:po}),"model.json"),e.weightData!=null&&n.body.append("model.weights.bin",new Blob([e.weightData],{type:Gs}),"model.weights.bin"),[4,this.fetch(this.path,n)];case 1:if(d=y.sent(),d.ok)return[2,{modelArtifactsInfo:dn(e),responses:[d]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+(d.status+"."))}})})},t.prototype.load=function(){return O(this,void 0,void 0,function(){var e,n,a,c,d,y,v,_,C,D,B,U,J,fe,Pe;return H(this,function(Me){switch(Me.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(e=Me.sent(),!e.ok)throw new Error("Request to "+this.path+" failed with status code "+(e.status+". Please verify this URL points to ")+"the model JSON of the model to load.");Me.label=2;case 2:return Me.trys.push([2,4,,5]),[4,e.json()];case 3:return n=Me.sent(),[3,5];case 4:throw a=Me.sent(),c="Failed to parse model JSON of response from "+this.path+".",this.path.endsWith(".pb")?c+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":c+=" Please make sure the server is serving valid JSON for this request.",new Error(c);case 5:if(d=n.modelTopology,y=n.weightsManifest,v=n.generatedBy,_=n.convertedBy,C=n.format,D=n.userDefinedMetadata,d==null&&y==null)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return y!=null?[4,this.loadWeights(y)]:[3,7];case 6:J=Me.sent(),B=J[0],U=J[1],Me.label=7;case 7:return fe={modelTopology:d,weightSpecs:B,weightData:U,userDefinedMetadata:D,generatedBy:v,convertedBy:_,format:C},Pe=n.modelInitializer,Pe&&(fe.modelInitializer=Pe),[2,fe]}})})},t.prototype.loadWeights=function(e){return O(this,void 0,void 0,function(){var n,a,c,d,y,v,_,C,D,B,U,J,fe,Pe,Me,He,ct,It,Ct,Bt,sr;return H(this,function(er){switch(er.label){case 0:for(n=Array.isArray(this.path)?this.path[1]:this.path,a=_l(n),c=a[0],d=a[1],y=this.weightPathPrefix||c,v=[],_=0,C=e;_e?t.substring(n):"";return[a+"/",c]}function zu(t){return t.match(Lu.URL_SCHEME_REGEX)!=null}var Pu=function(t,e){if(typeof fetch=="undefined"&&(e==null||e.fetchFunc==null))return null;var n=!0;return Array.isArray(t)?n=t.every(function(a){return zu(a)}):n=zu(t),n?du(t,e):null};si.registerSaveRouter(Pu),si.registerLoadRouter(Pu);function du(t,e){return new Lu(t,e)}function wl(t,e){return du(t,e)}var fu=function(){function t(e){this.modelArtifacts=e}return t.prototype.load=function(){return O(this,void 0,void 0,function(){return H(this,function(e){return[2,this.modelArtifacts]})})},t}(),mu=function(){function t(e){this.saveHandler=e}return t.prototype.save=function(e){return O(this,void 0,void 0,function(){return H(this,function(n){return[2,this.saveHandler(e)]})})},t}();function Nc(t,e,n,a){if(arguments.length===1){var c=t.modelTopology!=null||t.weightSpecs!=null;return c?new fu(t):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new fu({modelTopology:t}))}else return console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new fu({modelTopology:t,weightSpecs:e,weightData:n,trainingConfig:a})}function Cc(t){return new mu(t)}var Tc={__proto__:null,browserFiles:ho,browserHTTPRequest:wl,concatenateArrayBuffers:rs,decodeWeights:ya,encodeWeights:Qa,fromMemory:Nc,getLoadHandlers:xs,getModelArtifactsInfoForJSON:dn,getSaveHandlers:lc,http:du,isHTTPScheme:zu,loadWeights:Ic,registerLoadRouter:Iu,registerSaveRouter:Su,weightsLoaderFactory:Mu,withSaveHandler:Cc,copyModel:gl,listModels:as,moveModel:xl,removeModel:Vo};function Ec(t,e){var n=ie(t,"x","reshape",null),a={x:n},c={shape:e},d=function(y,v){return e=ar(e,n.size),W(n.size===Tt(e),function(){return"new shape and old shape must have the same number of elements."}),v([n]),y.reshape(n,e)};return Ie.runKernelFunc(d,a,null,Pr,c)}var Ke=Ee({reshape_:Ec});function Rc(t,e,n,a){var c;n===void 0&&(n=!1),a===void 0&&(a=!1);var d=ie(t,"a","matMul"),y=ie(e,"b","matMul");c=Nt(d,y),d=c[0],y=c[1];var v=function(D,B){B([d,y]);var U=n?d.shape[d.rank-2]:d.shape[d.rank-1],J=a?y.shape[y.rank-1]:y.shape[y.rank-2],fe=n?d.shape[d.rank-1]:d.shape[d.rank-2],Pe=a?y.shape[y.rank-2]:y.shape[y.rank-1],Me=d.shape.slice(0,-2),He=y.shape.slice(0,-2),ct=Tt(Me),It=Tt(He),Ct=ct===It||ct===1||It===1;W(d.rank>=2&&y.rank>=2&&Ct,function(){return"Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input "+("batch dimensions of ("+Me+") and ("+He+").")}),W(U===J,function(){return"Error in matMul: inner shapes ("+U+") and ("+(J+") of Tensors with shapes "+d.shape+" and ")+(y.shape+" and transposeA="+n)+(" and transposeB="+a+" must match.")});var Bt=ct>It?Me:He,sr=Bt.concat([fe,Pe]),er=n?Ke(d,[ct,U,fe]):Ke(d,[ct,fe,U]),mr=a?Ke(y,[It,Pe,J]):Ke(y,[It,J,Pe]),Gr=D.batchMatMul(er,mr,n,a);return Ke(Gr,sr)},_={a:d,b:y},C={transposeA:n,transposeB:a};return Ie.runKernelFunc(v,_,null,da,C)}var un=Ee({matMul_:Rc});function Ac(t,e,n,a){if(n===void 0&&(n=1),a===void 0&&(a=0),e<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+e);var c=ie(t,"indices","oneHot","int32"),d=c.shape.concat([e]),y=function(C,D){return D([c]),Ke(C.oneHot(Ke(c,[c.size]),e,n,a),d)},v={indices:c},_={depth:e,onValue:n,offValue:a};return Ie.runKernelFunc(y,v,null,Pi,_)}var Ss=Ee({oneHot_:Ac});function Dc(t,e){var n=ie(t,"x","transpose");if(e==null&&(e=n.shape.map(function(d,y){return y}).reverse()),W(n.rank===e.length,function(){return"Error in transpose: rank of input "+n.rank+" "+("must match length of perm "+e+".")}),e.forEach(function(d){W(d>=0&&d0&&Number.isInteger(n),function(){return"If provided, numClasses must be a positive integer, "+("but got "+n)}),W(a.rank===1,function(){return"Expected the rank of labels to be 1, but got "+a.rank}),W(c.rank===1,function(){return"Expected the rank of predictions to be 1, "+("but got "+c.rank)}),W(a.shape[0]===c.shape[0],function(){return"Mismatch in the number of examples: "+(a.shape[0]+" vs. "+c.shape[0]+". ")+"Labels and predictions should have the same number of elements."}),W(n>0&&Number.isInteger(n),function(){return"numClasses is required to be a positive integer, but got "+(""+n)});var d=Ss(pr(a,"int32"),n),y=Ss(pr(c,"int32"),n),v=$n(d),_=un(v,y);return pr(_,"int32")}var Oc=Ee({confusionMatrix_:Fc}),Mc={__proto__:null,confusionMatrix:Oc};function js(t,e,n){if(tt(t),e!=null&&e.length!==3)throw new Error("tensor3d() requires shape to have three numbers");var a=Er(t,n);if(a.length!==3&&a.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(a.length===1&&e==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return Da(t,e,a,n)}var is;function Lc(t,e){if(e===void 0&&(e=3),e>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(t==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var n=!1,a=!1,c=!1,d=!1,y=!1;if(t.data instanceof Uint8Array)n=!0;else if(typeof ImageData!="undefined"&&t instanceof ImageData)a=!0;else if(typeof HTMLVideoElement!="undefined"&&t instanceof HTMLVideoElement)c=!0;else if(typeof HTMLImageElement!="undefined"&&t instanceof HTMLImageElement)d=!0;else if(t.getContext!=null)y=!0;else throw new Error("pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, "+("but was "+t.constructor.name));if(c){var v=2;if(c&&t.readyState element.")}var _=Bs(xo,Ie.backendName);if(_!=null){var C={pixels:t},D={numChannels:e};return Ie.runKernel(xo,C,D)}var B=c?[t.videoWidth,t.videoHeight]:[t.width,t.height],U=B[0],J=B[1],fe;y?fe=t.getContext("2d").getImageData(0,0,U,J).data:a||n?fe=t.data:(d||c)&&(is==null&&(is=document.createElement("canvas").getContext("2d")),is.canvas.width=U,is.canvas.height=J,is.drawImage(t,0,0,U,J),fe=is.getImageData(0,0,U,J).data);var Pe;if(e===4)Pe=new Int32Array(fe);else{var Me=U*J;Pe=new Int32Array(Me*e);for(var He=0;He4||v===2)throw new Error("toPixels only supports depth of size "+("1, 3 or 4 but got "+v));if(n.dtype!=="float32"&&n.dtype!=="int32")throw new Error("Unsupported type for toPixels: "+n.dtype+". Please use float32 or int32 tensors.");return[4,n.data()];case 1:for(_=ct.sent(),C=n.dtype==="float32"?255:1,D=new Uint8ClampedArray(y*d*4),B=0;B1)throw new Error("Tensor values for a float32 Tensor must be in the "+("range [0 - 1] but encountered "+fe+"."))}else if(n.dtype==="int32"&&(fe<0||fe>255))throw new Error("Tensor values for a int32 Tensor must be in the "+("range [0 - 255] but encountered "+fe+"."));v===1?(U[0]=fe*C,U[1]=fe*C,U[2]=fe*C):U[J]=fe*C}Pe=B*4,D[Pe+0]=Math.round(U[0]),D[Pe+1]=Math.round(U[1]),D[Pe+2]=Math.round(U[2]),D[Pe+3]=Math.round(U[3])}return e!=null&&(e.width=y,e.height=d,Me=e.getContext("2d"),He=new ImageData(D,y,d),Me.putImageData(He,0,0)),n!==t&&n.dispose(),[2,D]}})})}var yu=Ee({fromPixels_:Lc}),Pc={__proto__:null,toPixels:zc,fromPixels:yu};function Bu(t,e){if(t.rank<1)throw new Error("tf.gatherND() expects the input to be rank 1 or higher,"+(" but the rank was "+t.rank+"."));if(e.rank<1)throw new Error("tf.gatherND() expects the indices to be rank 1 or higher,"+(" but the rank was "+e.rank+"."));if(e.dtype!=="int32")throw new Error("tf.gatherND() expects the indices to be int32 type,"+(" but the dtype was "+e.dtype+"."));if(e.shape[e.rank-1]>t.rank)throw new Error("index innermost dimension length must be <= tensor rank; saw: "+(e.shape[e.rank-1]+" vs. "+t.rank));if(t.size===0)throw new Error("Requested more than 0 entries, but input is empty."+(" Input shape: "+t.shape+"."));for(var n=e.shape,a=n[n.length-1],c=1,d=0;d1?e.shape[e.rank-1]:1,c=e.rank>1?e.rank-1:1,d="Must have updates.shape = indices.shape[:batchDim] + "+("shape[sliceDim:], got updates.shape: "+n.shape)+(", indices.shape: "+e.shape+", shape: "+t)+(", sliceDim: "+a+", and batchDim: "+c+".");if(n.rank1?e.shape[a-1]:1,d=n.length,y=1,v=c;v0;)t&1&&e.push(n),t/=2,n++;return e}function Wc(t,e,n){for(var a=[],c=0;c0){var J=e[0],fe=n+1;D=jc(y,J,fe,a,t),B=Uu(v,J,fe,c,t),U=Uc(d,J,fe,t)}else for(var Pe=0;Pe-1)d[v]=0;else{var _=Vc(e,n,v),C=a[_];t&1<<_&&(C=0),d[v]=C}return d}function Uu(t,e,n,a,c){for(var d=c.slice(),y=Hc(n,e),v=0;v-1)d[v]=Number.MAX_SAFE_INTEGER;else{var _=Vc(e,n,v),C=a[_];t&1<<_&&(C=Number.MAX_SAFE_INTEGER),d[v]=C}for(var D=0;D0?y=Number.MIN_SAFE_INTEGER:y=Number.MAX_SAFE_INTEGER);var _=a[c];return y<0&&(y+=_),y=me(0,y,_-1),y}function Kc(t,e,n,a,c,d){var y=e[c],v=n[c]||1;(t&1<0?y=Number.MAX_SAFE_INTEGER:y=Number.MIN_SAFE_INTEGER);var _=a[c];return y<0&&(y+=_),v>0?y=me(0,y,_):y=me(-1,y,_-1),y}function Sl(t,e,n){for(var a=n.length,c=0;c1){a=c;break}for(var c=a+1;c0||n[c]!==t[c])return!1;return!0}function Il(t,e){for(var n=t.length>0?t[t.length-1]:1,a=0;a=0?y:(W(y===-1,function(){return"Negative size values should be exactly -1 but got "+(y+" for the slice() size at index "+v+".")}),t.shape[v]-a[v])}),[a,d]}var Xc={__proto__:null,assertParamsValid:Bc,maskToAxes:vu,computeOutShape:Wc,stridesWithElidedDims:Uc,getNormalizedAxes:Gc,startIndicesWithElidedDims:jc,stopIndicesWithElidedDims:Uu,stridesForAxis:Vu,startForAxis:qc,stopForAxis:Kc,isSliceContinous:Sl,computeFlatOffset:Il,parseSliceParams:Hu},Yc=function(){function t(){}return t.prototype.getClassName=function(){return this.constructor.className},t.fromConfig=function(e,n){return new e(n)},t}(),ss=function(){function t(){this.classNameMap={}}return t.getMap=function(){return t.instance==null&&(t.instance=new t),t.instance},t.register=function(e){t.getMap().classNameMap[e.className]=[e,e.fromConfig]},t}();function jo(t){W(t.className!=null,function(){return"Class being registered does not have the static className property defined."}),W(typeof t.className=="string",function(){return"className is required to be a string, but got type "+typeof t.className}),W(t.className.length>0,function(){return"Class being registered has an empty-string as its className, which is disallowed."}),ss.register(t)}var Nl={__proto__:null,Serializable:Yc,SerializationMap:ss,registerClass:jo},Cl=.001,Gu=.1;function Tl(t,e,n){return n==null&&(n=gu()),ju(t,e,function(a,c){return qs(a,c,n)})}function gu(){return Ie.backend.floatPrecision()===32?Cl:Gu}function ju(t,e,n){var a=!0;if((Tn(t)||Tn(e))&&(a=!1),Tn(t)&&Tn(e)&&(a=!0),a){var c=t.constructor.name,d=e.constructor.name;if(c!==d)throw new Error("Arrays are of different type. Actual: "+c+". "+("Expected: "+d))}if(Array.isArray(t)&&Array.isArray(e)){var y=Er(t),v=Er(e);if(!it(y,v))throw new Error("Arrays have different shapes. "+("Actual: ["+y+"]. Expected: ["+v+"]"))}var _=Tn(t)?t:nr(t),C=Tn(e)?e:nr(e);if(_.length!==C.length)throw new Error("Arrays have different lengths actual: "+_.length+" vs "+("expected: "+C.length+`. -`)+("Actual: "+_+`. -`)+("Expected: "+C+"."));for(var D=0;Dn)}function qu(t,e,n){for(var a=0;an)throw new Error("Value out of range:"+t[a]+" low: "+e+", high: "+n)}function Dl(t,e){expect(new Float32Array(t)).toEqual(new Float32Array(e))}var Fl={__proto__:null,TEST_EPSILON_FLOAT16:Gu,expectArraysClose:Tl,testEpsilon:gu,expectPromiseToFail:El,expectArraysEqual:Rl,expectNumbersClose:Al,expectValuesInRange:qu,expectArrayBuffersEqual:Dl},Ku="2.7.0";function Ol(){Rr().set("PROD",!0)}function Ml(){Rr().set("DEBUG",!0)}function Xu(){Rr().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function Sa(t){Rr().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(t+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function Ll(){Ie.disposeVariables()}function zl(){return Ie}function Pl(){return Ie.memory()}function Qc(t){return Ie.profile(t)}function sa(t,e){return Ie.tidy(t,e)}function Pa(t){var e=Ot(t);e.forEach(function(n){return n.dispose()})}function xu(t){return Ie.keep(t)}function Zc(t){return Ie.time(t)}function Bl(t){return Ie.setBackend(t)}function Wl(){return Ie.ready()}function Ul(){return Ie.backendName}function Vl(t){Ie.removeBackend(t)}function Hl(t){return Ie.findBackend(t)}function Gl(t){return Ie.findBackendFactory(t)}function jl(t,e,n){return n===void 0&&(n=1),Ie.registerBackend(t,e,n)}function ql(){return Ie.backend}function Kl(t,e){Rr().setPlatform(t,e)}function Xl(t,e){var n,a=ie(t,"a","add"),c=ie(e,"b","add");n=Nt(a,c),a=n[0],c=n[1];var d=function(v,_){var C=v.add(a,c);return _([a,c]),C},y={a,b:c};return Ie.runKernelFunc(d,y,null,pa)}var Cr=Ee({add_:Xl});function Yl(t,e){var n,a=ie(t,"a","floorDiv"),c=ie(e,"b","floorDiv");n=Nt(a,c),a=n[0],c=n[1];var d=function(v,_){var C=v.floorDiv(a,c);return _([a,c]),C},y={a,b:c};return Ie.runKernelFunc(d,y,null,k)}var Yu=Ee({floorDiv_:Yl});function Ql(t,e){var n,a=ie(t,"a","div"),c=ie(e,"b","div");if(n=Nt(a,c),a=n[0],c=n[1],a.dtype==="int32"&&c.dtype==="int32")return Yu(a,c);var d=function(_,C){var D=_.realDivide(a,c);return C([a,c]),D},y={a,b:c},v={};return Ie.runKernelFunc(d,y,null,Vr,v)}var Br=Ee({div_:Ql});function Jc(t,e){var n,a=ie(t,"a","mul"),c=ie(e,"b","mul");n=Nt(a,c),a=n[0],c=n[1];var d=function(v,_){var C=v.multiply(a,c);return _([a,c]),C},y={a,b:c};return Ie.runKernelFunc(d,y,null,qr)}var bt=Ee({mul_:Jc});function Zl(t){var e=ie(t,"x","abs"),n={x:e};return Ie.runKernelFunc(function(a,c){return c([e]),e.dtype==="complex64"?a.complexAbs(e):a.abs(e)},n,null,qn)}var ui=Ee({abs_:Zl});function Jl(t){var e=ie(t,"x","acos"),n={x:e};return Ie.runKernelFunc(function(a,c){var d=a.acos(e);return c([e]),d},n,null,ri)}var $c=Ee({acos_:Jl});function $l(t){var e=ie(t,"x","acosh"),n={x:e};return Ie.runKernelFunc(function(a,c){var d=a.acosh(e);return c([e]),d},n,null,pi)}var el=Ee({acosh_:$l});function eh(t){W(Array.isArray(t),function(){return"The argument passed to tf.addN() must be a list of tensors"}),W(t.length>=1,function(){return"Must pass at least one tensor to tf.addN(), but got "+(""+t.length)});var e=t.map(function(d,y){return ie(d,"tensors"+y,"addN")}),n=e[0];e.forEach(function(d){if(d.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),e.forEach(function(d){if(!it(d.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});var a=function(d,y){var v=d.addN(e);return y(e),v},c=e;return Ie.runKernelFunc(a,c,null,di)}var th=Ee({addN_:eh});function Qu(t,e){for(var n=0;n=0&&e=1,function(){return"Pass at least one tensor to concat"});var n=Nn(t,"tensors","concat");n[0].dtype==="complex64"&&n.forEach(function(y){if(y.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor - with dtype `+y.dtype+". ")});var a=function(y,v){var _=qt(e,n[0].shape)[0],C=Ir(n.map(function(U){return U.shape}),_);if(Tt(C)===0)return Dn([],C);if(n=n.filter(function(U){return U.size>0}),n.length===1)return n[0];var D=n.map(function(U){return U.shape});lr(D,_);var B=y.concat(n,_);return v(n),B},c=n,d={axis:e};return Ie.runKernelFunc(a,c,null,Ue,d)}var kr=Ee({concat_:Lr});function Sr(t){var e=ie(t,"x","sigmoid"),n={x:e};return Ie.runKernelFunc(function(a,c){var d=a.sigmoid(e);return c([d]),d},n,null,Ds)}var fn=Ee({sigmoid_:Sr});function Xr(t,e,n){var a=ie(t,"x","slice");if(a.rank===0)throw new Error("Slicing scalar is not possible");var c=function(v,_){var C=Hu(a,e,n),D=C[0],B=C[1];return Bc(a,D,B),_([a]),v.slice(a,D,B)},d={x:a},y={begin:e,size:n};return Ie.runKernelFunc(c,d,null,To,y)}var $t=Ee({slice_:Xr});function On(t){var e=ie(t,"x","tanh"),n={x:e};return Ie.runKernelFunc(function(a,c){var d=a.tanh(e);return c([d]),d},n,null,Ms)}var En=Ee({tanh_:On});function kn(t,e,n,a,c,d){var y=ie(t,"forgetBias","basicLSTMCell"),v=ie(e,"lstmKernel","basicLSTMCell"),_=ie(n,"lstmBias","basicLSTMCell"),C=ie(a,"data","basicLSTMCell"),D=ie(c,"c","basicLSTMCell"),B=ie(d,"h","basicLSTMCell"),U=kr([C,B],1),J=un(U,v),fe=Cr(J,_),Pe=fe.shape[0],Me=fe.shape[1]/4,He=[Pe,Me],ct=$t(fe,[0,0],He),It=$t(fe,[0,Me],He),Ct=$t(fe,[0,Me*2],He),Bt=$t(fe,[0,Me*3],He),sr=Cr(bt(fn(ct),En(It)),bt(D,fn(Cr(y,Ct)))),er=bt(En(sr),fn(Bt));return[sr,er]}var cn=Ee({basicLSTMCell_:kn});function Mn(t,e,n){var a=ie(t,"x","batchToSpaceND"),c=e.reduce(function(_,C){return _*C});W(a.rank>=1+e.length,function(){return"input rank is "+a.rank+" but should be > than blockShape.length "+e.length}),W(n.length===e.length,function(){return"crops.length is "+n.length+" but should be equal to blockShape.length "+e.length}),W(a.shape[0]%c===0,function(){return"input tensor batch is "+a.shape[0]+" but is not divisible by the product of "+("the elements of blockShape "+e.join(" * ")+" === "+c)});var d=function(_){return _.batchToSpaceND(a,e,n)},y={x:a},v={blockShape:e,crops:n};return Ie.runKernelFunc(d,y,null,Mi,v)}var Hr=Ee({batchToSpaceND_:Mn});function ua(t){var e;return t.rank===0||t.rank===1?e=Ke(t,[1,1,1,t.size]):t.rank===2?e=Ke(t,[1,1,t.shape[0],t.shape[1]]):t.rank===3?e=Ke(t,[1,t.shape[0],t.shape[1],t.shape[2]]):e=t,e}function Ci(t,e,n,a,c,d){d==null&&(d=.001);var y=ie(t,"x","batchNorm"),v=ie(e,"mean","batchNorm"),_=ie(n,"variance","batchNorm"),C;c!=null&&(C=ie(c,"scale","batchNorm"));var D;a!=null&&(D=ie(a,"offset","batchNorm")),W(v.rank===_.rank,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."}),W(D==null||v.rank===D.rank,function(){return"Batch normalization gradient requires mean and offset to have equal ranks."}),W(C==null||v.rank===C.rank,function(){return"Batch normalization gradient requires mean and scale to have equal ranks."});var B=ua(y),U=function(Me,He){return He([B,v,_,C]),Me.batchNorm(B,Ui(v),Ui(_),Ui(D),Ui(C),d)},J={x:B,scale:C,offset:D,mean:v,variance:_},fe={varianceEpsilon:d},Pe=Ie.runKernelFunc(U,J,null,K,fe);return Ke(Pe,y.shape)}function Ui(t){return t==null?null:t.rank===0?Ke(t,[t.size]):t.rank===1?t:t.rank===2?Ke(t,[1,1,t.shape[0],t.shape[1]]):t.rank===3?Ke(t,[1,t.shape[0],t.shape[1],t.shape[2]]):t}var Xn=Ee({batchNorm_:Ci});function $i(t,e,n,a,c,d){var y=ie(t,"x","batchNorm"),v=ie(e,"mean","batchNorm"),_=ie(n,"variance","batchNorm"),C;c!=null&&(C=ie(c,"scale","batchNorm"));var D;return a!=null&&(D=ie(a,"offset","batchNorm")),W(y.rank===2,function(){return"Error in batchNorm2D: x must be rank 2 but got rank "+(y.rank+".")}),W(v.rank===2||v.rank===1,function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but "+("got rank "+v.rank+".")}),W(_.rank===2||_.rank===1,function(){return"Error in batchNorm2D: variance must be rank 2 or rank 1 "+("but got rank "+_.rank+".")}),C!=null&&W(C.rank===2||C.rank===1,function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 "+("but got rank "+C.rank+".")}),D!=null&&W(D.rank===2||D.rank===1,function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 "+("but got rank "+D.rank+".")}),Xn(y,v,_,D,C,d)}var Vi=Ee({batchNorm2d_:$i});function Ks(t,e,n,a,c,d){var y=ie(t,"x","batchNorm"),v=ie(e,"mean","batchNorm"),_=ie(n,"variance","batchNorm"),C;c!=null&&(C=ie(c,"scale","batchNorm"));var D;return a!=null&&(D=ie(a,"offset","batchNorm")),W(y.rank===3,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+(y.rank+".")}),W(v.rank===3||v.rank===1,function(){return"Error in batchNorm3D: mean must be rank 3 or rank 1 but "+("got rank "+v.rank+".")}),W(_.rank===3||_.rank===1,function(){return"Error in batchNorm3D: variance must be rank 3 or rank 1 "+("but got rank "+_.rank+".")}),C!=null&&W(C.rank===3||C.rank===1,function(){return"Error in batchNorm3D: scale must be rank 3 or rank 1 "+("but got rank "+C.rank+".")}),D!=null&&W(D.rank===3||D.rank===1,function(){return"Error in batchNorm3D: offset must be rank 3 or rank 1 "+("but got rank "+D.rank+".")}),Xn(y,v,_,D,C,d)}var Zu=Ee({batchNorm3d_:Ks});function al(t,e,n,a,c,d){var y=ie(t,"x","batchNorm"),v=ie(e,"mean","batchNorm"),_=ie(n,"variance","batchNorm"),C;c!=null&&(C=ie(c,"scale","batchNorm"));var D;return a!=null&&(D=ie(a,"offset","batchNorm")),W(y.rank===4,function(){return"Error in batchNorm4D: x must be rank 4 but got rank "+(y.rank+".")}),W(v.rank===4||v.rank===1,function(){return"Error in batchNorm4D: mean must be rank 4 or rank 1 but "+("got rank "+v.rank+".")}),W(_.rank===4||_.rank===1,function(){return"Error in batchNorm4D: variance must be rank 4 or rank 1 "+("but got rank "+_.rank+".")}),C!=null&&W(C.rank===4||C.rank===1,function(){return"Error in batchNorm4D: scale must be rank 4 or rank 1 "+("but got rank "+C.rank+".")}),D!=null&&W(D.rank===4||D.rank===1,function(){return"Error in batchNorm4D: offset must be rank 4 or rank 1 "+("but got rank "+D.rank+".")}),Xn(y,v,_,D,C,d)}var _h=Ee({batchNorm4d_:al});function rh(t,e){var n=ie(t,"broadcastTo","x"),a=n.shape;if(e.some(function(U){return!(U>0)||U%1!==0}))throw new Error("broadcastTo(): Invalid broadcast shape ["+e+"].");if(e.lengthn.rank){for(var c=n.shape.slice();c.length=0;v--)if(d[v]===e[v])y[v]=1;else if(n.shape[v]!==1)throw new Error("broadcastTo(): ["+a+"] cannot be broadcast to ["+e+"].");var _=y.map(function(U,J){return U>1?J:-1}).filter(function(U){return U>=0});if(_.length===0)return Ho(n);var C=function(U){return U.tile(n,y)},D={x:n},B={shape:e,inputShape:d};return Ie.runKernelFunc(C,D,null,pe,B)}var Ju=Ee({broadcastTo_:rh});function nh(t){var e=ie(t,"x","ceil"),n={x:e};return Ie.runKernelFunc(function(a){return a.ceil(e)},n,null,j)}var ah=Ee({ceil_:nh});function ih(t,e,n){var a=ie(t,"x","clipByValue");W(e<=n,function(){return"Error in clip: min ("+e+") must be "+("less than or equal to max ("+n+").")});var c={x:a},d={clipValueMin:e,clipValueMax:n};return Ie.runKernelFunc(function(y,v){var _=y.clip(a,e,n);return v([a]),_},c,null,re,d)}var oh=Ee({clipByValue_:ih});function sh(t){return kr(t,0)}var wh=Ee({concat1d_:sh});function uh(t,e){return kr(t,e)}var $h=Ee({concat2d_:uh});function ch(t,e){return kr(t,e)}var bh=Ee({concat3d_:ch});function ep(t,e){return kr(t,e)}var Wn=Ee({concat4d_:ep});function Is(t,e,n,a,c,d,y){c===void 0&&(c="NHWC"),d===void 0&&(d=[1,1]);var v=ie(t,"x","conv2d"),_=ie(e,"filter","conv2d"),C=v,D=!1;v.rank===3&&(D=!0,C=Ke(v,[1,v.shape[0],v.shape[1],v.shape[2]])),W(C.rank===4,function(){return"Error in conv2d: input must be rank 4, but got rank "+C.rank+"."}),W(_.rank===4,function(){return"Error in conv2d: filter must be rank 4, but got rank "+(_.rank+".")}),y!=null&&W(xt(a),function(){return"Error in conv2d: pad must be an integer when using, "+("dimRoundingMode "+y+" but got pad "+a+".")});var B=c==="NHWC"?C.shape[3]:C.shape[1];W(B===_.shape[2],function(){return"Error in conv2d: depth of input ("+B+") must match "+("input depth for filter "+_.shape[2]+".")}),W(dt(n,d),function(){return"Error in conv2D: Either strides or dilations must be 1. "+("Got strides "+n+" and dilations '"+d+"'")});var U=function(Me,He){var ct=Dt(c),It=T(C.shape,_.shape,n,d,a,y,!1,ct),Ct=Me.conv2d(C,_,It);return He([C,_]),Ct},J={x:C,filter:_},fe={strides:n,pad:a,dataFormat:c,dilations:d,dimRoundingMode:y},Pe=Ie.runKernelFunc(U,J,null,kt,fe);return D?Ke(Pe,[Pe.shape[1],Pe.shape[2],Pe.shape[3]]):Pe}var gi=Ee({conv2d_:Is});function qo(t,e,n,a,c,d,y){c===void 0&&(c="NWC"),d===void 0&&(d=1);var v=ie(t,"x","conv1d"),_=ie(e,"filter","conv1d"),C=v,D=!1;v.rank===2&&(D=!0,C=Ke(v,[1,v.shape[0],v.shape[1]])),W(C.rank===3,function(){return"Error in conv1d: input must be rank 3, but got rank "+C.rank+"."}),W(_.rank===3,function(){return"Error in conv1d: filter must be rank 3, but got rank "+(_.rank+".")}),y!=null&&W(xt(a),function(){return"Error in conv1d: pad must be an integer when using, "+("dimRoundingMode "+y+" but got pad "+a+".")}),W(C.shape[2]===_.shape[1],function(){return"Error in conv1d: depth of input ("+C.shape[2]+") must match "+("input depth for filter "+_.shape[1]+".")}),W(dt(n,d),function(){return"Error in conv1D: Either stride or dilation must be 1. "+("Got stride "+n+" and dilation '"+d+"'")}),W(c==="NWC",function(){return"Error in conv1d: got dataFormat of "+c+" but only NWC is currently supported."});var B=Ke(_,[1,_.shape[0],_.shape[1],_.shape[2]]),U=Ke(C,[C.shape[0],1,C.shape[1],C.shape[2]]),J=[1,n],fe=[1,d],Pe="NHWC",Me=gi(U,B,J,a,Pe,fe,y);return D?Ke(Me,[Me.shape[2],Me.shape[3]]):Ke(Me,[Me.shape[0],Me.shape[2],Me.shape[3]])}var Ns=Ee({conv1d_:qo});function kh(t,e,n,a,c,d,y){d===void 0&&(d="NHWC"),W(t.length===e.rank,function(){return"Length of inShape "+("("+t.length+") and rank of dy ("+e.rank+") must match")});var v=t,_=e,C=!1;e.rank===3&&(C=!0,_=Ke(e,[1,e.shape[0],e.shape[1],e.shape[2]]),v=[1,t[0],t[1],t[2]]),W(v.length===4,function(){return"Error in conv2dDerInput: inShape must be length 4, but got length "+(v.length+".")}),W(_.rank===4,function(){return"Error in conv2dDerInput: dy must be rank 4, but got "+("rank "+_.rank)}),W(n.rank===4,function(){return"Error in conv2dDerInput: filter must be rank 4, but got "+("rank "+n.rank)});var D=d==="NHWC"?v[3]:v[1],B=d==="NHWC"?_.shape[3]:_.shape[1];W(D===n.shape[2],function(){return"Error in conv2dDerInput: depth of input ("+D+") must "+("match input depth for filter "+n.shape[2]+".")}),W(B===n.shape[3],function(){return"Error in conv2dDerInput: depth of output ("+B+") must "+("match output depth for filter "+n.shape[3]+".")}),y!=null&&W(xt(c),function(){return"Error in conv2dDerInput: pad must be an integer when using, "+("dimRoundingMode "+y+" but got pad "+c+".")});var U=function(Me,He){var ct=1,It=Dt(d),Ct=T(v,n.shape,a,ct,c,y,!1,It),Bt=Me.conv2dDerInput(_,n,Ct);return He([_,n]),Bt},J={dy:_,filter:n},fe={strides:a,pad:c,dataFormat:d,dimRoundingMode:y,inputShape:v},Pe=Ie.runKernelFunc(U,J,null,Le,fe);return C?Ke(Pe,[Pe.shape[1],Pe.shape[2],Pe.shape[3]]):Pe}var Ti=Ee({conv2DBackpropInput_:kh});function tp(t,e,n,a,c,d){var y=ie(t,"x","conv2dTranspose"),v=ie(e,"filter","conv2dTranspose");return Ti(n,y,v,a,c,"NHWC",d)}var Xs=Ee({conv2dTranspose_:tp});function rp(t,e,n,a,c,d){c===void 0&&(c="NDHWC"),d===void 0&&(d=[1,1,1]);var y=ie(t,"x","conv3d"),v=ie(e,"filter","conv3d"),_=y,C=!1;y.rank===4&&(C=!0,_=Ke(y,[1,y.shape[0],y.shape[1],y.shape[2],y.shape[3]])),W(_.rank===5,function(){return"Error in conv3d: input must be rank 5, but got rank "+_.rank+"."}),W(v.rank===5,function(){return"Error in conv3d: filter must be rank 5, but got rank "+(v.rank+".")}),W(_.shape[4]===v.shape[3],function(){return"Error in conv3d: depth of input ("+_.shape[4]+") must match "+("input depth for filter "+v.shape[3]+".")}),W(dt(n,d),function(){return"Error in conv3D: Either strides or dilations must be 1. "+("Got strides "+n+" and dilations '"+d+"'")}),W(c==="NDHWC",function(){return"Error in conv3d: got dataFormat of "+c+" but only NDHWC is currently supported."});var D=function(fe,Pe){var Me=M(_.shape,v.shape,n,d,a),He=fe.conv3d(_,v,Me);return Pe([_,v]),He},B={x:_,filter:v},U={strides:n,pad:a,dataFormat:c,dilations:d},J=Ie.runKernelFunc(D,B,null,Ye,U);return C?Ke(J,[J.shape[1],J.shape[2],J.shape[3],J.shape[4]]):J}var np=Ee({conv3d_:rp});function ap(t,e,n,a,c){W(t.length===e.rank,function(){return"Length of inShape "+("("+t.length+") and rank of dy ("+e.rank+") must match")});var d=t,y=e,v=!1;e.rank===4&&(v=!0,y=Ke(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]),d=[1,t[0],t[1],t[2],t[3]]);var _=d[4],C=y.shape[4];W(d.length===5,function(){return"Error in conv3dDerInput: inShape must be length 5, but got length "+(d.length+".")}),W(y.rank===5,function(){return"Error in conv3dDerInput: dy must be rank 5, but got "+("rank "+y.rank)}),W(n.rank===5,function(){return"Error in conv3dDerInput: filter must be rank 5, but got "+("rank "+n.rank)}),W(_===n.shape[3],function(){return"Error in conv3dDerInput: depth of input ("+_+") must "+("match input depth for filter "+n.shape[3]+".")}),W(C===n.shape[4],function(){return"Error in conv3dDerInput: depth of output ("+C+") must "+("match output depth for filter "+n.shape[4]+".")});var D=function(fe){var Pe=1,Me=M(d,n.shape,a,Pe,c);return fe.conv3dDerInput(y,n,Me)},B={dy:y,filter:n},U={pad:c,strides:a,inputShape:d},J=Ie.runKernelFunc(D,B,null,St,U);return v?Ke(J,[J.shape[1],J.shape[2],J.shape[3],J.shape[4]]):J}var Sh=Ee({conv3DBackpropInput_:ap});function If(t,e,n,a,c){var d=ie(t,"x","conv3dTranspose"),y=ie(e,"filter","conv3dTranspose");return Sh(n,d,y,a,c)}var Nf=Ee({conv3dTranspose_:If});function Cf(t){var e=ie(t,"x","cos"),n={x:e};return Ie.runKernelFunc(function(a,c){var d=a.cos(e);return c([e]),d},n,null,Mt)}var Ih=Ee({cos_:Cf});function Tf(t){var e=ie(t,"x","cosh"),n={x:e};return Ie.runKernelFunc(function(a,c){var d=a.cosh(e);return c([e]),d},n,null,dr)}var ip=Ee({cosh_:Tf});function Ef(t,e,n,a){e===void 0&&(e=0),n===void 0&&(n=!1),a===void 0&&(a=!1);var c=ie(t,"x","cumsum"),d=function(_,C){var D=Ji([e],c.rank),B=c;D!=null&&(B=$n(c,D));var U=p(1,c.rank)[0],J=_.cumsum(B,U,n,a);if(C([c]),D!=null){var fe=f(D);J=$n(J,fe)}return J},y={x:c},v={axis:e,exclusive:n,reverse:a};return Ie.runKernelFunc(d,y,null,ir,v)}var op=Ee({cumsum_:Ef});function Rf(t,e,n){n===void 0&&(n="NHWC");var a=ie(t,"x","depthToSpace"),c=n==="NHWC"?a.shape[1]:a.shape[2],d=n==="NHWC"?a.shape[2]:a.shape[3],y=n==="NHWC"?a.shape[3]:a.shape[1];W(c*e>=0,function(){return`Negative dimension size caused by overflow when multiplying - `+c+" and "+e+` for depthToSpace with input shape - `+a.shape}),W(d*e>=0,function(){return`Negative dimension size caused by overflow when multiplying - `+d+" and "+e+` for depthToSpace with input shape - `+a.shape}),W(y%(e*e)===0,function(){return"Dimension size must be evenly divisible by "+e*e+" but is "+y+" for depthToSpace with input shape "+a.shape});var v=function(D){return D.depthToSpace(a,e,n)},_={x:a},C={blockSize:e,dataFormat:n};return Ie.runKernelFunc(v,_,null,fa,C)}var Kp=Ee({depthToSpace_:Rf});function Af(t,e,n,a,c,d,y){c===void 0&&(c="NHWC"),d===void 0&&(d=[1,1]);var v=ie(t,"x","depthwiseConv2d"),_=ie(e,"filter","depthwiseConv2d"),C=v,D=!1;v.rank===3&&(D=!0,C=Ke(v,[1,v.shape[0],v.shape[1],v.shape[2]])),W(C.rank===4,function(){return"Error in depthwiseConv2d: input must be rank 4, but got "+("rank "+C.rank+".")}),W(_.rank===4,function(){return"Error in depthwiseConv2d: filter must be rank 4, but got rank "+(_.rank+".")}),W(C.shape[3]===_.shape[2],function(){return"Error in depthwiseConv2d: number of input channels "+("("+C.shape[3]+") must match the inChannels dimension in ")+("filter "+_.shape[2]+".")}),y!=null&&W(xt(a),function(){return"Error in depthwiseConv2d: pad must be an integer when using, "+("dimRoundingMode "+y+" but got pad "+a+".")});var B=function(Pe,Me){d==null&&(d=[1,1]),W(dt(n,d),function(){return"Error in depthwiseConv2d: Either strides or dilations must be "+("1. Got strides "+n+" and dilations '"+d+"'")});var He=T(C.shape,_.shape,n,d,a,y,!0),ct=Pe.depthwiseConv2D(C,_,He);return Me([C,_]),ct},U={x:C,filter:_},J={strides:n,pad:a,dataFormat:c,dilations:d,dimRoundingMode:y},fe=Ie.runKernelFunc(B,U,null,ra,J);return D?Ke(fe,[fe.shape[1],fe.shape[2],fe.shape[3]]):fe}var lh=Ee({depthwiseConv2d_:Af});function Df(t){var e=ie(t,"x","diag"),n=function(c){var d=Ke(e,[e.size]),y=c.diag(d),v=t.shape.concat(t.shape);return Ke(y,v)},a={x:e};return Ie.runKernelFunc(n,a,null,sn)}var Ff=Ee({diag_:Df});function Of(t,e,n,a,c,d){c===void 0&&(c=[1,1]),d===void 0&&(d="NHWC");var y=ie(t,"x","dilation2d"),v=ie(e,"filter","dilation2d");W(y.rank===3||y.rank===4,function(){return"Error in dilation2d: input must be rank 3 or 4, but got rank "+(y.rank+".")}),W(v.rank===3,function(){return"Error in dilation2d: filter must be rank 3, but got rank "+(v.rank+".")}),W(d==="NHWC",function(){return"Error in dilation2d: Only NHWC is currently supported, "+("but got dataFormat of "+d)});var _=y,C=!1;y.rank===3&&(_=Ke(y,[1,y.shape[0],y.shape[1],y.shape[2]]),C=!0);var D={x:_,filter:v},B={strides:n,pad:a,dilations:c},U=Ie.runKernel(hn,D,B);return C?Ke(U,[U.shape[1],U.shape[2],U.shape[3]]):U}var Xp=Ee({dilation2d_:Of});function Mf(t,e){for(var n=t.length,a=[],c=0;c1&&y===1&&a.unshift(d)}return a}function Ja(t,e){for(var n=[],a=0;a1)&&n.unshift(d)}return n}function ca(t,e){for(var n=[],a=Math.max(t.length,e.length),c=0;ce||a===t?n=!0:a=rn(t,a+1);return a}function Zf(t,e,n){for(var a=[],c=t.length,d=0;d0,function(){return"variableGrads() expects at least one of the input variables to "+("be trainable, but none of the "+d+" variables is ")+"trainable."});var y=!0,v=Ie.gradients(t,e,null,y),_=v.value,C=v.grads;W(C.some(function(B){return B!=null}),function(){return"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."}),W(_.rank===0,function(){return"The f passed in variableGrads(f) must return a scalar, but it "+("returned a rank-"+_.rank+" tensor")});var D={};return e.forEach(function(B,U){C[U]!=null&&(D[B.name]=C[U])}),c!=null&&c.forEach(function(B){return D[B.name]=null}),{value:_,grads:D}}function Cs(t){return Ie.customGrad(t)}function Rh(t){var e=t.filter(function(n){return n==null}).length;if(e>0)throw new Error(`Cannot compute gradient of y=f(x) with respect to x. Make sure that - the f you passed encloses all operations that lead from x to y.`)}function g1(t){var e=ie(t,"x","neg"),n={x:e};return Ie.runKernelFunc(function(a){return a.neg(e)},n,null,Io)}var $a=Ee({neg_:g1});function x1(t){var e=ie(t,"x","softplus"),n={x:e};return Ie.runKernelFunc(function(a,c){var d=a.softplus(e);return c([e]),d},n,null,Xo)}var hp=Ee({softplus_:x1});function _1(t){var e=ie(t,"x","logSigmoid"),n=Cs(function(a){var c=$a(hp($a(a))),d=function(y){var v=bt(y,fn($a(a)));return v};return{value:c,gradFunc:d}});return n(e)}var sd=Ee({logSigmoid_:_1});function w1(t,e,n){e===void 0&&(e=null),n===void 0&&(n=!1);var a=ie(t,"x","max"),c=function(v,_){var C=qt(e,a.shape),D=C,B=Ji(D,a.rank),U=a;B!=null&&(U=$n(a,B),D=p(D.length,U.rank));var J=v.max(U,D);B!=null&&U.dispose();var fe=J;if(n){var Pe=ci(fe.shape,qt(e,a.shape));fe=Ke(fe,Pe),J.dispose()}return _([a,fe]),fe},d={x:a},y={reductionIndices:e,keepDims:n};return Ie.runKernelFunc(c,d,null,$r,y)}var rc=Ee({max_:w1});function b1(t,e){var n,a=ie(t,"a","sub"),c=ie(e,"b","sub");n=Nt(a,c),a=n[0],c=n[1];var d=function(v,_){var C=v.subtract(a,c);return _([a,c]),C},y={a,b:c};return Ie.runKernelFunc(d,y,null,ps)}var zr=Ee({sub_:b1});function k1(t,e,n){e===void 0&&(e=null),n===void 0&&(n=!1);var a=ie(t,"x","sum");a.dtype==="bool"&&(a=pr(a,"int32"));var c=function(v,_){_([a]);var C=qt(e,a.shape),D=Ji(C,a.rank),B=C,U=a;D!=null&&(U=$n(a,D),B=p(B.length,a.rank));var J=v.sum(U,B);if(n){var fe=ci(J.shape,C);J=Ke(J,fe)}return J},d={x:a},y={axis:e,keepDims:n};return Ie.runKernelFunc(c,d,null,Yo,y)}var Yr=Ee({sum_:k1});function S1(t,e){e===void 0&&(e=-1);var n=ie(t,"logits","logSoftmax");if(e===-1&&(e=n.rank-1),e!==n.rank-1)throw Error("Log Softmax along a non-last dimension is not yet supported. "+("Logits was rank "+n.rank+" and axis was "+e));var a=function(y,v){var _=!0,C=rc(t,e,!0),D=zr(t,C),B=zr(pr(D,"float32"),tc(Yr(cs(D),e,_)));return v([B]),B},c={logits:n},d={axis:e};return Ie.runKernelFunc(a,c,null,wa,d)}var ud=Ee({logSoftmax_:S1});function I1(t,e,n){e===void 0&&(e=null),n===void 0&&(n=!1);var a=ie(t,"x","logSumExp"),c=qt(e,a.shape),d=rc(a,c,!0),y=zr(a,d),v=cs(y),_=Yr(v,c),C=tc(_),D=Cr(Ke(d,C.shape),C);if(n){var B=ci(D.shape,c);return Ke(D,B)}return D}var pp=Ee({logSumExp_:I1});function N1(t,e){var n=ie(t,"a","logicalAnd","bool"),a=ie(e,"b","logicalAnd","bool");ca(n.shape,a.shape);var c={a:n,b:a};return Ie.runKernelFunc(function(d){return d.logicalAnd(n,a)},c,null,pn)}var nc=Ee({logicalAnd_:N1});function C1(t){var e=ie(t,"x","logicalNot","bool"),n={x:e};return Ie.runKernelFunc(function(a){return a.logicalNot(e)},n,null,zn)}var Ah=Ee({logicalNot_:C1});function T1(t,e){var n=ie(t,"a","logicalOr","bool"),a=ie(e,"b","logicalOr","bool");ca(n.shape,a.shape);var c={a:n,b:a};return Ie.runKernelFunc(function(d){return d.logicalOr(n,a)},c,null,Fr)}var dp=Ee({logicalOr_:T1});function E1(t,e){var n=ie(t,"a","logicalXor","bool"),a=ie(e,"b","logicalXor","bool");return ca(n.shape,a.shape),nc(dp(t,e),Ah(nc(t,e)))}var cd=Ee({logicalXor_:E1});function R1(t,e,n,a,c){var d=ie(t,"x","maxPool"),y=1,v=d,_=!1;d.rank===3&&(_=!0,v=Ke(d,[1,d.shape[0],d.shape[1],d.shape[2]])),W(v.rank===4,function(){return"Error in maxPool: input must be rank 4 but got rank "+v.rank+"."}),W(dt(n,y),function(){return"Error in maxPool: Either strides or dilations must be 1. "+("Got strides "+n+" and dilations '"+y+"'")}),c!=null&&W(xt(a),function(){return"Error in maxPool: pad must be an integer when using, "+("dimRoundingMode "+c+" but got pad "+a+".")});var C=function(J,fe){var Pe=h(v.shape,e,n,1,a,c),Me;return Pe.filterWidth===1&&Pe.filterHeight===1&&it(Pe.inShape,Pe.outShape)?Me=v.clone():Me=J.maxPool(v,Pe),fe([v,Me]),Me},D={x:v},B={filterSize:e,strides:n,pad:a,dimRoundingMode:c},U=Ie.runKernelFunc(C,D,null,mi,B);return _?Ke(U,[U.shape[1],U.shape[2],U.shape[3]]):U}var fp=Ee({maxPool_:R1});function A1(t,e,n,a,c,d,y){e===void 0&&(e=[1,1,1]),d===void 0&&(d="NDHWC"),y==null?y=[1,1,1]:Sa("dilations is deprecated, this field will be gone in v3.0.0.");var v=ie(t,"x","maxPool3d"),_=v,C=!1;v.rank===4&&(C=!0,_=Ke(v,[1,v.shape[0],v.shape[1],v.shape[2],v.shape[3]])),W(_.rank===5,function(){return"Error in maxPool3d: x must be rank 5 but got rank "+_.rank+"."}),W(d==="NDHWC",function(){return"Error in maxPool3d: Only NDHWC is currently supported, "+("but got dataFormat of "+d)}),W(dt(n,y),function(){return"Error in maxPool3d: Either strides or dilations must be 1. "+("Got strides "+n+" and dilations '"+y+"'")}),c!=null&&W(xt(a),function(){return"Error in maxPool3d: pad must be an integer when using, "+("dimRoundingMode "+c+" but got pad "+a+".")});var D=function(fe,Pe){y==null&&(y=[1,1,1]);var Me=b(_.shape,e,n,y,a,c,d),He=fe.maxPool3d(_,Me);return Pe([_,He]),He},B={x:_},U={filterSize:e,strides:n,pad:a,dimRoundingMode:c,dataFormat:d,dilations:y},J=Ie.runKernelFunc(D,B,null,ja,U);return C?Ke(J,[J.shape[1],J.shape[2],J.shape[3],J.shape[4]]):J}var D1=Ee({maxPool3d_:A1});function F1(t,e,n,a,c){c===void 0&&(c=!1);var d=ie(t,"x","maxPoolWithArgmax"),y={x:d},v={filterSize:e,strides:n,pad:a,includeBatchInIndex:c},_=Ie.runKernel(zi,y,v);return{result:_[0],indexes:_[1]}}var O1=Ee({maxPoolWithArgmax_:F1});function Ys(t,e){if(e===void 0&&(e="float32"),e==="complex64"){var n=Ys(t,"float32"),a=Ys(t,"float32");return Pn(n,a)}var c=ha(Tt(t),e);return Ie.makeTensor(c,t,e)}function sl(t,e){if(e===void 0&&(e="float32"),e==="complex64"){var n=sl(t,"float32"),a=Ys(t,"float32");return Pn(n,a)}var c=_i(Tt(t),e);return Ie.makeTensor(c,t,e)}function M1(t,e,n){e===void 0&&(e=null),n===void 0&&(n=!1);var a=ie(t,"x","mean"),c=qt(e,a.shape),d=rl(a.shape,c),y=d[1],v=Tt(y),_={x:a},C={axis:e,keepDims:n},D=function(){var U=Wr(v),J=U.dtype===a.dtype?a:pr(a,U.dtype),fe=Br(J,U);return Yr(fe,e,n)},B=Cs(function(U){var J=Ie.runKernelFunc(D,_,null,An,C),fe=function(Pe){var Me=U.shape.slice();c.forEach(function(It){Me[It]=1});var He=Ke(Pe,Me),ct=Br(bt(He,sl(U.shape,"float32")),v);return ct};return{value:J,gradFunc:fe}});return B(a)}var ph=Ee({mean_:M1});function L1(t,e,n){e===void 0&&(e=null),n===void 0&&(n=!1);var a=ie(t,"x","min"),c=function(v,_){var C=qt(e,a.shape),D=C,B=Ji(D,a.rank),U=a;B!=null&&(U=$n(a,B),D=p(D.length,a.rank));var J=v.min(U,D);B!=null&&U.dispose();var fe=J;if(n){var Pe=ci(fe.shape,C);fe=Ke(J,Pe),J.dispose()}return _([a,fe]),fe},d={x:a},y={axis:e,keepDims:n};return Ie.runKernelFunc(c,d,null,ba,y)}var Dh=Ee({min_:L1});function z1(t,e){var n,a=ie(t,"a","minimum"),c=ie(e,"b","minimum");n=Nt(a,c),a=n[0],c=n[1],a.dtype==="bool"&&(a=pr(a,"int32"),c=pr(c,"int32")),ca(a.shape,c.shape);var d=function(v,_){var C=v.minimum(a,c);return _([a,c]),C},y={a,b:c};return Ie.runKernelFunc(d,y,null,qi)}var Fh=Ee({minimum_:z1});function P1(t,e,n){W(n==="reflect"||n==="symmetric",function(){return"Invalid mode. Mode must be either reflect or symmetric. "+("Got "+n+".")});var a=ie(t,"x","mirrorPad");if(a.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");W(e.length===a.rank,function(){return"Padding doesn't match input. Must be "+a.rank+". "+("Got "+e.length+".")});for(var c=n==="reflect"?1:0,d=function(C){W(e[C].length===2,function(){return"Invalid number of paddings. Must be length of 2 each."}),W(e[C][0]>=0&&e[C][0]<=a.shape[C]-c&&e[C][1]>=0&&e[C][1]<=a.shape[C]-c,function(){return"Padding in dimension "+C+" cannot be greater than or equal "+("to "+(a.shape[C]-c)+" or less than 0 for input of ")+("shape "+a.shape)})},y=0;y2)throw new Error("Rank of probabilities must be 1 or 2, but is "+y);n=n||Math.random();var v=y===1?Ke(c,[1,-1]):c,_=Ie.runKernelFunc(function(C){return C.multinomial(v,a,e,n)},{logits2D:v});return y===1?Ke(_,[_.size]):_}var q1=Ee({multinomial_:j1});function K1(t,e){var n,a=ie(t,"a","notEqual"),c=ie(e,"b","notEqual");n=Nt(a,c),a=n[0],c=n[1],ca(a.shape,c.shape);var d=function(v){return v.notEqual(a,c)},y={a,b:c};return Ie.runKernelFunc(d,y,null,nn)}var Oh=Ee({notEqual_:K1});function X1(t){var e=ie(t,"input","real"),n=function(c){return c.real(e)},a={input:e};return Ie.runKernelFunc(n,a,null,Co)}var dh=Ee({real_:X1});function Y1(t){var e=ie(t,"x","onesLike"),n=function(c,d){if(e.dtype==="complex64"){var y=yp(dh(e)),v=gn(Th(e));return Pn(y,v)}return c.onesLike(e)},a={x:e};return Ie.runKernelFunc(n,a,null,oi)}var yp=Ee({onesLike_:Y1});function Q1(t,e){var n=ie(t,"v1","outerProduct"),a=ie(e,"v2","outerProduct");W(n.rank===1&&a.rank===1,function(){return"Error in outerProduct: inputs must be rank 1, but got ranks "+(n.rank+" and "+a.rank+".")});var c=Ke(n,[-1,1]),d=Ke(a,[1,-1]);return un(c,d)}var Z1=Ee({outerProduct_:Q1});function J1(t,e,n){n===void 0&&(n=0);var a=ie(t,"x","pad");if(a.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var c=function(v,_){return _([a]),v.pad(a,e,n)},d={paddings:e,constantValue:n},y={x:a};return Ie.runKernelFunc(c,y,null,no,d)}var ac=Ee({pad_:J1});function $1(t,e,n){return n===void 0&&(n=0),W(e.length===2,function(){return"Invalid number of paddings. Must be length of 2."}),ac(t,[e],n)}var em=Ee({pad1d_:$1});function tm(t,e,n){return n===void 0&&(n=0),W(e.length===2&&e[0].length===2&&e[1].length===2,function(){return"Invalid number of paddings. Must be length of 2 each."}),ac(t,e,n)}var rm=Ee({pad2d_:tm});function nm(t,e,n){return n===void 0&&(n=0),W(e.length===3&&e[0].length===2&&e[1].length===2&&e[2].length===2,function(){return"Invalid number of paddings. Must be length of 2 each."}),ac(t,e,n)}var am=Ee({pad3d_:nm});function im(t,e,n){return n===void 0&&(n=0),W(e.length===4&&e[0].length===2&&e[1].length===2&&e[2].length===2&&e[3].length===2,function(){return"Invalid number of paddings. Must be length of 2 each."}),ac(t,e,n)}var om=Ee({pad4d_:im});function sm(t,e,n){var a=ie(t,"x","spaceToBatchND");W(a.rank>=1+e.length,function(){return"input rank "+a.rank+" should be > than [blockShape] "+e.length}),W(n.length===e.length,function(){return"paddings.shape[0] "+n.length+" must be equal to [blockShape] "+e.length}),W(a.shape.reduce(function(v,_,C){return C>0&&C<=e.length?v&&(_+n[C-1][0]+n[C-1][1])%e[C-1]===0:v},!0),function(){return"input spatial dimensions "+a.shape.slice(1)+" with paddings "+n.toString()+" must be divisible by blockShapes "+e.toString()});var c=function(v){return v.spaceToBatchND(a,e,n)},d={x:a},y={blockShape:e,paddings:n};return Ie.runKernelFunc(c,d,null,Ao,y)}var Mh=Ee({spaceToBatchND_:sm});function um(t,e,n,a,c,d){c==null&&(c=[1,1]),d==null&&(d=1),a===0&&(a="valid");var y=ie(t,"x","maxPool"),v=y,_=!1;y.rank===3&&(_=!0,v=Ke(y,[1,y.shape[0],y.shape[1],y.shape[2]])),W(dt(d,c),function(){return"Error in pool: Either strides or dilations must be 1. "+("Got strides "+d+" and dilations '"+c+"'")});var C=h(v.shape,e,d,c,a),D=[C.dilationHeight,C.dilationWidth],B;a==="same"?B=lm([C.filterHeight,C.filterWidth],D):B=[[0,0],[0,0]];var U=D[0]===1&&D[1]===1,J=cm([C.inHeight,C.inWidth],D,B),fe=J[0],Pe=J[1],Me=U?a:"valid",He=U?v:Mh(v,D,fe),ct=n==="avg"?function(){return Xt(He,e,d,Me)}:function(){return fp(He,e,d,Me)},It=ct(),Ct=U?It:Hr(It,D,Pe);return _?Ke(Ct,[Ct.shape[1],Ct.shape[2],Ct.shape[3]]):Ct}function cm(t,e,n){var a=n.map(function(D){return D[0]}),c=n.map(function(D){return D[1]}),d=t.concat(a,c),y=e.map(function(D,B){return(D-d[B]%D)%D}),v=c.map(function(D,B){return D+y[B]}),_=e.map(function(D,B){return[a[B],v[B]]}),C=e.map(function(D,B){return[0,y[B]]});return[_,C]}function lm(t,e){var n=t.map(function(y,v){return y+(y-1)*(e[v]-1)}),a=n.map(function(y){return y-1}),c=a.map(function(y){return Math.floor(y/2)}),d=a.map(function(y,v){return y-c[v]});return a.map(function(y,v){return[c[v],d[v]]})}var hd=Ee({pool_:um});function hm(t,e){var n,a=ie(t,"base","pow"),c=ie(e,"exp","pow");n=Nt(a,c),a=n[0],c=n[1];var d={a,b:c},y=function(v,_){var C=v.pow(a,c);return _([a,c,C]),C};return Ie.runKernelFunc(y,d,null,Ka)}var Qs=Ee({pow_:hm});function pm(t,e){var n=ie(t,"x","prelu"),a=ie(e,"alpha","prelu"),c=function(y,v){var _=y.prelu(n,a);return v([n,a]),_},d={x:n,alpha:a};return Ie.runKernelFunc(c,d,null,ao)}var vp=Ee({prelu_:pm});function dm(t,e,n){e===void 0&&(e=null),n===void 0&&(n=!1);var a=ie(t,"x","prod");a.dtype==="bool"&&(a=pr(a,"int32"));var c=function(v){var _=qt(e,a.shape),C=Ji(_,a.rank),D=_,B=a;C!=null&&(B=$n(a,C),D=p(D.length,a.rank));var U=v.prod(B,D);if(n){var J=ci(U.shape,_);U=Ke(U,J)}return U},d={x:a},y={axis:e,keepDims:n};return Ie.runKernelFunc(c,d,null,Ko,y)}var pd=Ee({prod_:dm});function fm(t,e,n){var a=Tt(t),c=null;if(n==null||n==="float32")c=new Float32Array(a);else if(n==="int32")c=new Int32Array(a);else if(n==="bool")c=new Uint8Array(a);else throw new Error("Unknown data type "+n);for(var d=0;d>>0,U-=_,U*=_,_=U>>>0,U-=_,_+=U*4294967296}return(_>>>0)*23283064365386963e-26};return C}n&&n.exports?n.exports=y:a&&a.amd?a(function(){return y}):this.alea=y})(ul,t,!1)}),vm=ic(function(t){(function(e,n,a){function c(v){var _=this,C="";_.x=0,_.y=0,_.z=0,_.w=0,_.next=function(){var B=_.x^_.x<<11;return _.x=_.y,_.y=_.z,_.z=_.w,_.w^=_.w>>>19^B^B>>>8},v===(v|0)?_.x=v:C+=v;for(var D=0;D>>0)/4294967296};return B.double=function(){do var U=C.next()>>>11,J=(C.next()>>>0)/4294967296,fe=(U+J)/(1<<21);while(fe===0);return fe},B.int32=C.next,B.quick=B,D&&(typeof D=="object"&&d(D,C),B.state=function(){return d(C,{})}),B}n&&n.exports?n.exports=y:a&&a.amd?a(function(){return y}):this.xor128=y})(ul,t,!1)}),gm=ic(function(t){(function(e,n,a){function c(v){var _=this,C="";_.next=function(){var B=_.x^_.x>>>2;return _.x=_.y,_.y=_.z,_.z=_.w,_.w=_.v,(_.d=_.d+362437|0)+(_.v=_.v^_.v<<4^(B^B<<1))|0},_.x=0,_.y=0,_.z=0,_.w=0,_.v=0,v===(v|0)?_.x=v:C+=v;for(var D=0;D>>4),_.next()}function d(v,_){return _.x=v.x,_.y=v.y,_.z=v.z,_.w=v.w,_.v=v.v,_.d=v.d,_}function y(v,_){var C=new c(v),D=_&&_.state,B=function(){return(C.next()>>>0)/4294967296};return B.double=function(){do var U=C.next()>>>11,J=(C.next()>>>0)/4294967296,fe=(U+J)/(1<<21);while(fe===0);return fe},B.int32=C.next,B.quick=B,D&&(typeof D=="object"&&d(D,C),B.state=function(){return d(C,{})}),B}n&&n.exports?n.exports=y:a&&a.amd?a(function(){return y}):this.xorwow=y})(ul,t,!1)}),xm=ic(function(t){(function(e,n,a){function c(v){var _=this;_.next=function(){var D=_.x,B=_.i,U,J;return U=D[B],U^=U>>>7,J=U^U<<24,U=D[B+1&7],J^=U^U>>>10,U=D[B+3&7],J^=U^U>>>3,U=D[B+4&7],J^=U^U<<7,U=D[B+7&7],U=U^U<<13,J^=U^U<<9,D[B]=J,_.i=B+1&7,J};function C(D,B){var U,J,fe=[];if(B===(B|0))J=fe[0]=B;else for(B=""+B,U=0;U0;--U)D.next()}C(_,v)}function d(v,_){return _.x=v.x.slice(),_.i=v.i,_}function y(v,_){v==null&&(v=+new Date);var C=new c(v),D=_&&_.state,B=function(){return(C.next()>>>0)/4294967296};return B.double=function(){do var U=C.next()>>>11,J=(C.next()>>>0)/4294967296,fe=(U+J)/(1<<21);while(fe===0);return fe},B.int32=C.next,B.quick=B,D&&(D.x&&d(D,C),B.state=function(){return d(C,{})}),B}n&&n.exports?n.exports=y:a&&a.amd?a(function(){return y}):this.xorshift7=y})(ul,t,!1)}),_m=ic(function(t){(function(e,n,a){function c(v){var _=this;_.next=function(){var D=_.w,B=_.X,U=_.i,J,fe;return _.w=D=D+1640531527|0,fe=B[U+34&127],J=B[U=U+1&127],fe^=fe<<13,J^=J<<17,fe^=fe>>>15,J^=J>>>12,fe=B[U]=fe^J,_.i=U,fe+(D^D>>>16)|0};function C(D,B){var U,J,fe,Pe,Me,He=[],ct=128;for(B===(B|0)?(J=B,B=null):(B=B+"\0",J=0,ct=Math.max(ct,B.length)),fe=0,Pe=-32;Pe>>15,J^=J<<4,J^=J>>>13,Pe>=0&&(Me=Me+1640531527|0,U=He[Pe&127]^=J+Me,fe=U==0?fe+1:0);for(fe>=128&&(He[(B&&B.length||0)&127]=-1),fe=127,Pe=4*128;Pe>0;--Pe)J=He[fe+34&127],U=He[fe=fe+1&127],J^=J<<13,U^=U<<17,J^=J>>>15,U^=U>>>12,He[fe]=J^U;D.w=Me,D.X=He,D.i=fe}C(_,v)}function d(v,_){return _.i=v.i,_.w=v.w,_.X=v.X.slice(),_}function y(v,_){v==null&&(v=+new Date);var C=new c(v),D=_&&_.state,B=function(){return(C.next()>>>0)/4294967296};return B.double=function(){do var U=C.next()>>>11,J=(C.next()>>>0)/4294967296,fe=(U+J)/(1<<21);while(fe===0);return fe},B.int32=C.next,B.quick=B,D&&(D.X&&d(D,C),B.state=function(){return d(C,{})}),B}n&&n.exports?n.exports=y:a&&a.amd?a(function(){return y}):this.xor4096=y})(ul,t,!1)}),wm=ic(function(t){(function(e,n,a){function c(v){var _=this,C="";_.next=function(){var B=_.b,U=_.c,J=_.d,fe=_.a;return B=B<<25^B>>>7^U,U=U-J|0,J=J<<24^J>>>8^fe,fe=fe-B|0,_.b=B=B<<20^B>>>12^U,_.c=U=U-J|0,_.d=J<<16^U>>>16^fe,_.a=fe-B|0},_.a=0,_.b=0,_.c=2654435769|0,_.d=1367130551,v===Math.floor(v)?(_.a=v/4294967296|0,_.b=v|0):C+=v;for(var D=0;D>>0)/4294967296};return B.double=function(){do var U=C.next()>>>11,J=(C.next()>>>0)/4294967296,fe=(U+J)/(1<<21);while(fe===0);return fe},B.int32=C.next,B.quick=B,D&&(typeof D=="object"&&d(D,C),B.state=function(){return d(C,{})}),B}n&&n.exports?n.exports=y:a&&a.amd?a(function(){return y}):this.tychei=y})(ul,t,!1)}),oc=ic(function(t){(function(e,n){var a=this,c=256,d=6,y=52,v="random",_=n.pow(c,d),C=n.pow(2,y),D=C*2,B=c-1,U;function J(Ct,Bt,sr){var er=[];Bt=Bt==!0?{entropy:!0}:Bt||{};var mr=He(Me(Bt.entropy?[Ct,It(e)]:Ct??ct(),3),er),Gr=new fe(er),en=function(){for(var Qr=Gr.g(d),Zr=_,Kr=0;Qr=D;)Qr/=2,Zr/=2,Kr>>>=1;return(Qr+Kr)/Zr};return en.int32=function(){return Gr.g(4)|0},en.quick=function(){return Gr.g(4)/4294967296},en.double=en,He(It(Gr.S),e),(Bt.pass||sr||function(Qr,Zr,Kr,Un){return Un&&(Un.S&&Pe(Un,Gr),Qr.state=function(){return Pe(Gr,{})}),Kr?(n[v]=Qr,Zr):Qr})(en,mr,"global"in Bt?Bt.global:this==n,Bt.state)}n["seed"+v]=J;function fe(Ct){var Bt,sr=Ct.length,er=this,mr=0,Gr=er.i=er.j=0,en=er.S=[];for(sr||(Ct=[sr++]);mr=1||v===0);var _=Math.sqrt(-2*Math.log(v)/v);n=this.mean+this.stdDev*d*_,a=this.mean+this.stdDev*y*_,(!this.truncated||this.isValidTruncated(n))&&(c=!0)}return(!this.truncated||this.isValidTruncated(a))&&(this.nextVal=this.convertValue(a)),this.convertValue(n)},t.prototype.convertValue=function(e){return this.dtype==null||this.dtype==="float32"?e:Math.round(e)},t.prototype.isValidTruncated=function(e){return e<=this.upper&&e>=this.lower},t}(),km=function(){function t(e,n,a,c){this.alpha=e,this.beta=1/n,this.dtype=a;var d=c||Math.random();this.randu=gp(d.toString()),this.randn=new xp(0,1,a,!1,this.randu()),e<1?this.d=e+2/3:this.d=e-1/3,this.c=1/Math.sqrt(9*this.d)}return t.prototype.nextValue=function(){for(var e,n,a,c,d,y;;){do c=this.randn.nextValue(),y=1+this.c*c;while(y<=0);if(y*=y*y,e=c*c,n=1-.331*e*e,a=.5*e+this.d*(1-y+Math.log(y)),d=this.randu(),d1;if(y||v||_)return Ys([0],a);var C=Math.abs(Math.ceil((e-t)/n)),D=ha(C,a);e0?v+_:v});e[d]=t.shape[n]-y}W(t.shape[n]===e.reduce(function(v,_){return v+_}),function(){return"The sum of sizes must match the size of the axis dimension."}),a=e}return a}function cy(t,e,n){n===void 0&&(n=0);var a=ie(t,"x","split"),c=function(v,_){var C=qt(n,a.shape)[0],D=_d(a,e,C);return v.split(a,D,C)},d={x:a},y={numOrSizeSplits:e,axis:n};return Ie.runKernelFunc(c,d,null,Qo,y)}var ll=Ee({split_:cy});function ly(t,e){W(t.dtype==="float32",function(){return"The dtype for rfft() must be real value but got "+t.dtype});var n=t.shape[t.shape.length-1],a=t.size/n,c;if(e!=null&&en){var v=t.shape.map(function(He){return He});v[t.shape.length-1]=e-n,c=kr([t,Ys(v)],t.shape.length-1),n=e}else c=t;var _=gn(c),C=Ke(Pn(c,_),[a,n]),D=Lh(C),B=Math.floor(n/2)+1,U=dh(D),J=Th(D),fe=ll(U,[B,n-B],U.shape.length-1),Pe=ll(J,[B,n-B],J.shape.length-1),Me=c.shape.slice();return Me[c.shape.length-1]=B,Ke(Pn(fe[0],Pe[0]),Me)}var zh=Ee({rfft_:ly});function hy(t){var e=ie(t,"x","sqrt"),n={x:e};return Ie.runKernelFunc(function(a,c){var d=a.sqrt(e);return c([e]),d},n,null,Ro)}var eo=Ee({sqrt_:hy});function py(t,e){var n,a=ie(t,"a","squaredDifference"),c=ie(e,"b","squaredDifference");n=Nt(a,c),a=n[0],c=n[1],ca(a.shape,c.shape);var d=function(_,C){var D=_.squaredDifference(a,c);return C([a,c]),D},y={a,b:c},v={};return Ie.runKernelFunc(d,y,null,Fs,v)}var Ph=Ee({squaredDifference_:py});function dy(t,e){var n=ie(t,"x","squeeze");return Ke(n,Ur(n.shape,e).newShape)}var Bh=Ee({squeeze_:dy});function fy(t,e){e===void 0&&(e=0);var n=Nn(t,"tensors","stack");if(W(n.length>=1,function(){return"Pass at least one tensor to tf.stack"}),n.length===1)return ls(n[0],e);var a=n[0].rank,c=n[0].shape,d=n[0].dtype;W(e<=a,function(){return"Axis must be <= rank of the tensor"}),n.forEach(function(v){nt(c,v.shape,"All tensors passed to stack must have matching shapes"),W(d===v.dtype,function(){return"All tensors passed to stack must have matching dtypes"})});var y=n.map(function(v){return ls(v,e)});return kr(y,e)}var sc=Ee({stack_:fy});function my(t,e){e===void 0&&(e=0);var n=ie(t,"x","step"),a={x:n},c={alpha:e};return Ie.runKernelFunc(function(d){return d.step(n,e)},a,null,Zo,c)}var hl=Ee({step_:my});function yy(t,e,n,a,c,d,y,v,_){c===void 0&&(c=0),d===void 0&&(d=0),y===void 0&&(y=0),v===void 0&&(v=0),_===void 0&&(_=0);var C=ie(t,"x","stridedSlice"),D=function(J){a==null&&(a=new Array(e.length));var fe=vu(y);if(fe.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(y!==0&&v!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(y!==0&&_!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");var Pe=C.rank-e.length,Me=vu(v),He=C.shape.slice();Me.forEach(function(Qr){e[Qr]=0,n[Qr]=1,He.splice(Qr,0,1)}),C=Ke(C,He);var ct=Gc(C.shape,fe,Pe,e,n,a,c,d,y),It=ct.begin,Ct=ct.end,Bt=ct.strides;e=It,n=Ct,a=Bt;var sr=vu(_);sr.forEach(function(Qr){n[Qr]=e[Qr]+1,a[Qr]=1});var er=Wc(e,n,a),mr=er.filter(function(Qr,Zr){return sr.indexOf(Zr)===-1}),Gr=a.every(function(Qr){return Qr===1});if(Gr)return Ke($t(C,e,er),mr);var en=J.stridedSlice(C,e,n,a);return Ke(en,mr)},B={x:C},U={begin:e,end:n,strides:a,beginMask:c,endMask:d,ellipsisMask:y,newAxisMask:v,shrinkAxisMask:_};return Ie.runKernelFunc(D,B,null,Os,U)}var wd=Ee({stridedSlice_:yy});function vy(t){var e=ie(t,"x","tan"),n={x:e};return Ie.runKernelFunc(function(a,c){var d=a.tan(e);return c([e]),d},n,null,ds)}var bd=Ee({tan_:vy});function yh(t,e,n){if(tt(t),e!=null&&e.length!==2)throw new Error("tensor2d() requires shape to have two numbers");var a=Er(t,n);if(a.length!==2&&a.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(a.length===1&&e==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Da(t,e,a,n)}function gy(t,e,n){if(tt(t),e!=null&&e.length!==4)throw new Error("tensor4d() requires shape to have four numbers");var a=Er(t,n);if(a.length!==4&&a.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(a.length===1&&e==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return Da(t,e,a,n)}function xy(t,e,n){if(tt(t),e!=null&&e.length!==5)throw new Error("tensor5d() requires shape to have five numbers");var a=Er(t,n);if(a.length!==5&&a.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(a.length===1&&e==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return Da(t,e,a,n)}function _y(t,e,n){if(tt(t),e!=null&&e.length!==6)throw new Error("tensor6d() requires shape to have six numbers");var a=Er(t,n);if(a.length!==6&&a.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(a.length===1&&e==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return e=e||a,Da(t,e,a,n)}function wy(t,e,n){e===void 0&&(e=1),n===void 0&&(n=!0);var a=ie(t,"x","topk");if(a.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");var c=a.shape[a.shape.length-1];if(e>c)throw new Error("'k' passed to topk() must be <= the last dimension ("+c+") "+("but got "+e));var d={x:a},y={k:e,sorted:n},v=Ie.runKernelFunc(function(D){return D.topk(a,e,n)},d,null,nu,y),_=v[0],C=v[1];return{values:_,indices:C}}var kd=Ee({topk_:wy});function by(t,e,n,a,c){if(e===void 0&&(e=0),n===void 0&&(n=1),a!=null&&a==="bool")throw new Error("Unsupported data type $ { dtype }");for(var d=new xp(e,n,a,!0,c),y=Qi(t,a),v=0;v0,function(){return"The input tensor must be at least 1D"});var a={x:n},c={axis:e},d=Ie.runKernel(au,a,c),y=d[0],v=d[1];return{values:y,indices:v}}var Sd=Ee({unique_:Sy});function Iy(t,e,n){var a=ie(t,"x","unsortedSegmentSum"),c=ie(e,"segmentIds","unsortedSegmentSum","int32");W(xt(n),function(){return"numSegments must be of dtype int"});var d={x:a,segmentIds:c},y={numSegments:n},v=function(_,C){var D=_.unsortedSegmentSum(a,c,n);return C([c]),D};return Ie.runKernelFunc(v,d,null,Do,y)}var Np=Ee({unsortedSegmentSum_:Iy});function Ny(t,e){e===void 0&&(e=0);var n=ie(t,"x","unstack");W(e>=-n.shape.length&&e0,function(){return"mask cannot be scalar"}),nt(v.slice(d,d+y),c.shape,"mask's shape must match the first K dimensions of tensor's shape,"),_=1,C=d;C2)throw new Error("sparseIndices should be a scalar, vector, or matrix,"+(" but got shape "+t.shape+"."));var c=t.rank>0?t.shape[0]:1,d=t.rank>1?t.shape[1]:1;if(n.length!==d)throw new Error("outputShape has incorrect number of elements:,"+(" "+n.length+", should be: "+d+"."));var y=e.size;if(!(e.rank===0||e.rank===1&&y===c))throw new Error("sparseValues has incorrect shape "+(e.shape+", should be [] or ["+c+"]"));if(e.dtype!==a.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function Jy(t,e,n,a){a===void 0&&(a=0);var c=ie(t,"sparseIndices","sparseToDense","int32"),d=ie(e,"sparseValues","sparseToDense"),y=ie(a,"defaultValue","sparseToDense",d.dtype);Zy(c,d,n,y);var v={sparseIndices:c,sparseValues:d,defaultValue:y},_={outputShape:n};return Ie.runKernelFunc(function(C){return C.sparseToDense(c,d,n,y)},v,null,ru,_)}var $y=Ee({sparseToDense_:Jy});function e0(t,e){var n=ie(e,"indices","gatherND","int32"),a=ie(t,"x","gatherND"),c=function(y){return y.gatherND(a,n)},d={params:a,indices:n};return Ie.runKernelFunc(c,d,null,we)}var t0=Ee({gatherND_:e0});function r0(t,e){if(e==null)return t.shape.slice();if(it(t.shape,e))return e;if(t.shape.length===e.length){for(var n=[],a=0;a=0&&e<1,function(){return"rate must be a float in the range [0, 1), but got "+e+"."}),e===0)return t instanceof $?c.clone():c;var d=r0(c,n),y=1-e,v=Br(Nh(Cr(dd(d,0,1,"float32",a),y)),y);return bt(c,v)}var a0=Ee({dropout_:n0});function Hd(t){return Math.floor(Math.pow(2,Math.ceil(Math.log(t)/Math.log(2))))}function Cp(t,e,n){for(var a=1-t%2,c=new Float32Array(t),d=0;d1,function(){return"inTopK() expects the predictions to be of rank 2 or higher, "+("but got "+a.rank)}),W(a.rank-1===c.rank,function(){return"predictions rank should be 1 larger than targets rank, but got predictions rank "+(a.rank+" and targets rank "+c.rank)}),nt(a.shape.slice(0,a.shape.length-1),c.shape,"predictions's shape should be align with the targets' shape, except the last dimension."),d=a.shape[a.shape.length-1],W(n>0&&n<=d,function(){return"'k' passed to inTopK() must be > 0 && <= the predictions last "+("dimension ("+d+"), but got "+n)}),[4,a.data()];case 1:return y=He.sent(),[4,c.data()];case 2:for(v=He.sent(),_=[y.length/d,d],C=_[0],D=_[1],B=jr("bool",C),U=0;U0&&(n=Yr(n,a)),Ke(n,t.shape)}function Gh(t,e,n){if(e==="linear")return t;if(e==="relu")return fh(t);if(e==="elu")return sp(t);if(e==="relu6")return wp(t);if(e==="prelu")return vp(t,n);throw new Error("Unknown fused activation "+e+".")}var jh=function(t,e){var n=t>0;return!n||e==="linear"};function u0(t){var e=t.x,n=t.filter,a=t.strides,c=t.pad,d=t.dataFormat,y=d===void 0?"NHWC":d,v=t.dilations,_=v===void 0?[1,1]:v,C=t.dimRoundingMode,D=t.bias,B=t.activation,U=B===void 0?"linear":B,J=t.preluActivationWeights;if(U=U||"linear",jh(Ie.state.gradientDepth,U)===!1){var fe=gi(e,n,a,c,y,_,C);return D!=null&&(fe=Cr(fe,D)),Gh(fe,U,J)}var Pe=ie(e,"x","conv2d"),Me=ie(n,"filter","conv2d"),He=Pe,ct=!1;Pe.rank===3&&(ct=!0,He=Ke(Pe,[1,Pe.shape[0],Pe.shape[1],Pe.shape[2]])),W(He.rank===4,function(){return"Error in fused conv2d: input must be rank 4, but got rank "+(He.rank+".")}),W(Me.rank===4,function(){return"Error in fused conv2d: filter must be rank 4, but got rank "+(Me.rank+".")}),C!=null&&W(xt(c),function(){return"Error in fused conv2d: pad must be an integer when using, "+("dimRoundingMode "+C+" but got pad "+c+".")}),W(He.shape[3]===Me.shape[2],function(){return"Error in conv2d: depth of input ("+He.shape[3]+") must match "+("input depth for filter "+Me.shape[2]+".")}),W(dt(a,_),function(){return"Error in conv2D: Either strides or dilations must be 1. "+("Got strides "+a+" and dilations '"+_+"'")}),W(y==="NHWC",function(){return"Error in conv2d: got dataFormat of "+y+" but only NHWC is currently supported."});var It=T(He.shape,Me.shape,a,_,c,C),Ct;D!=null&&(Ct=ie(D,"bias","fused conv2d"),Ct=Nt(Ct,Pe)[0],ca(It.outShape,Ct.shape));var Bt;J!=null&&(Bt=ie(J,"prelu weights","fused conv2d"));var sr=function(Zr,Kr){var Un=Kr,mn=Un[0],Ln=Un[1],$s=Un[2],xi=Un[3],Ba=Vh(Zr,$s,U);W(st(_),function(){return"Error in gradient of fused conv2D: dilation rates greater than 1 "+("are not yet supported in gradients. Got dilations '"+_+"'")});var ko=Ti(Ln.shape,Ba,mn,a,c),So=Tp(Ln,Ba,mn.shape,a,c),bu=[ko,So];if(xi!=null){var zp=Hh(xi,Ba);bu.push(zp)}return bu},er=function(Zr){var Kr=Zr.fusedConv2d({input:He,filter:Me,convInfo:It,bias:Ct,activation:U,preluActivationWeights:Bt});return Kr},mr={x:He,filter:Me,bias:Ct,preluActivationWeights:Bt},Gr={strides:a,pad:c,dataFormat:y,dilations:_,dimRoundingMode:C,activation:U};if(D==null){var en=Cs(function(Zr,Kr,Un){var mn=Ie.runKernelFunc(er,mr,null,Ps,Gr);return Un([Kr,Zr,mn]),ct&&(mn=Ke(mn,[mn.shape[1],mn.shape[2],mn.shape[3]])),{value:mn,gradFunc:sr}});return en(He,Me)}else{var Qr=Cs(function(Zr,Kr,Un,mn){var Ln=Ie.runKernelFunc(er,mr,null,Ps,Gr);return mn([Kr,Zr,Ln,Un]),ct&&(Ln=Ke(Ln,[Ln.shape[1],Ln.shape[2],Ln.shape[3]])),{value:Ln,gradFunc:sr}});return Qr(He,Me,Ct)}}var c0=Ee({fusedConv2d_:u0});function l0(t,e,n,a,c,d,y){d===void 0&&(d=[1,1]);var v=t;t.rank===3&&(v=Ke(t,[1,t.shape[0],t.shape[1],t.shape[2]]));var _=e;_.rank===3&&(_=Ke(e,[1,e.shape[0],e.shape[1],e.shape[2]]));var C=function(U){var J=T(t.shape,n,a,d,c,y,!0);return U.depthwiseConv2DDerFilter(v,_,J)},D={x:v,dy:_},B={strides:a,pad:c,dimRoundingMode:y,dilations:d,filterShape:n};return Ie.runKernelFunc(C,D,null,Ha,B)}var Gd=Ee({depthwiseConv2dNativeBackpropFilter_:l0});function h0(t,e,n,a,c,d,y){d===void 0&&(d=[1,1]);var v=e,_=!1;e.rank===3&&(_=!0,v=Ke(e,[1,e.shape[0],e.shape[1],e.shape[2]]));var C=function(J){var fe=T(t,n.shape,a,d,c,y,!0);return J.depthwiseConv2DDerInput(v,n,fe)},D={dy:v,filter:n},B={strides:a,pad:c,dimRoundingMode:y,dilations:d,inputShape:t},U=Ie.runKernelFunc(C,D,null,ki,B);return _?Ke(U,[U.shape[1],U.shape[2],U.shape[3]]):U}var jd=Ee({depthwiseConv2dNativeBackpropInput_:h0});function p0(t){var e=t.x,n=t.filter,a=t.strides,c=t.pad,d=t.dataFormat,y=d===void 0?"NHWC":d,v=t.dilations,_=v===void 0?[1,1]:v,C=t.dimRoundingMode,D=t.bias,B=t.activation,U=B===void 0?"linear":B,J=t.preluActivationWeights;if(jh(Ie.state.gradientDepth,U)===!1){var fe=lh(e,n,a,c,y,_,C);return D!=null&&(fe=Cr(fe,D)),Gh(fe,U,J)}var Pe=ie(e,"x","depthwiseConv2d"),Me=ie(n,"filter","depthwiseConv2d"),He=Pe,ct=!1;Pe.rank===3&&(ct=!0,He=Ke(Pe,[1,Pe.shape[0],Pe.shape[1],Pe.shape[2]])),W(He.rank===4,function(){return"Error in fused depthwiseConv2d: input must be rank 4, but got "+("rank "+He.rank+".")}),W(Me.rank===4,function(){return"Error in fused depthwiseConv2d: filter must be rank 4, "+("but got rank "+Me.rank+".")}),W(He.shape[3]===Me.shape[2],function(){return"Error in fused depthwiseConv2d: number of input channels "+("("+He.shape[3]+") must match the inChannels dimension in ")+("filter "+Me.shape[2]+".")}),_==null&&(_=[1,1]),W(dt(a,_),function(){return"Error in fused depthwiseConv2d: Either strides or dilations must "+("be 1. Got strides "+a+" and dilations '"+_+"'")}),C!=null&&W(xt(c),function(){return"Error in fused depthwiseConv2d: pad must be an integer when "+("using dimRoundingMode "+C+" but got pad "+c+".")});var It=T(He.shape,Me.shape,a,_,c,C,!0),Ct;D!=null&&(Ct=ie(D,"bias","fused conv2d"),Ct=Nt(Ct,Pe)[0],ca(It.outShape,Ct.shape));var Bt;J!=null&&(Bt=ie(J,"prelu weights","fused depthwiseConv2d"));var sr=function(Zr,Kr){W(st(_),function(){return"Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations "+("'"+_+"'")});var Un=Kr[0],mn=Kr[1],Ln=Kr[2],$s=Kr[3],xi=Vh(Zr,Ln,U),Ba=jd(mn.shape,xi,Un,a,c,_,C),ko=Gd(mn,xi,Un.shape,a,c,_,C);if($s!=null){var So=Hh(Ct,xi);return[Ba,ko,So]}return[Ba,ko]},er=function(Zr){var Kr=Zr.fusedDepthwiseConv2D({input:He,filter:Me,convInfo:It,bias:Ct,activation:U,preluActivationWeights:Bt});return Kr},mr={x:He,filter:Me,bias:Ct,preluActivationWeights:Bt},Gr={strides:a,pad:c,dataFormat:y,dilations:_,dimRoundingMode:C,activation:U};if(D==null){var en=Cs(function(Zr,Kr,Un){var mn=Ie.runKernelFunc(er,mr,null,Jo,Gr);return Un([Kr,Zr,mn]),ct&&(mn=Ke(mn,[mn.shape[1],mn.shape[2],mn.shape[3]])),{value:mn,gradFunc:sr}});return en(He,Me)}else{var Qr=Cs(function(Zr,Kr,Un,mn){var Ln=Ie.runKernelFunc(er,mr,null,Jo,Gr);return mn([Kr,Zr,Ln,Un]),ct&&(Ln=Ke(Ln,[Ln.shape[1],Ln.shape[2],Ln.shape[3]])),{value:Ln,gradFunc:sr}});return Qr(He,Me,Ct)}}var d0=Ee({fusedDepthwiseConv2d_:p0});function f0(t){var e,n=t.a,a=t.b,c=t.transposeA,d=c===void 0?!1:c,y=t.transposeB,v=y===void 0?!1:y,_=t.bias,C=t.activation,D=C===void 0?"linear":C,B=t.preluActivationWeights;if(jh(Ie.state.gradientDepth,D)===!1){var U=un(n,a,d,v);return _!=null&&(U=Cr(U,_)),Gh(U,D,B)}var J=ie(n,"a","fused matMul"),fe=ie(a,"b","fused matMul");e=Nt(J,fe),J=e[0],fe=e[1];var Pe=d?J.shape[J.rank-2]:J.shape[J.rank-1],Me=v?fe.shape[fe.rank-1]:fe.shape[fe.rank-2],He=d?J.shape[J.rank-1]:J.shape[J.rank-2],ct=v?fe.shape[fe.rank-2]:fe.shape[fe.rank-1],It=J.shape.slice(0,-2),Ct=fe.shape.slice(0,-2),Bt=Tt(It),sr=Tt(Ct);W(J.rank>=2&&fe.rank>=2&&J.rank===fe.rank,function(){return"Error in fused matMul: inputs must have the same rank of at least "+("2, got ranks "+J.rank+" and "+fe.rank+".")}),W(it(It,Ct),function(){return"Error in fused matMul: outer dimensions ("+It+") and ("+(Ct+") of Tensors with shapes "+J.shape+" and ")+(fe.shape+" must match.")}),W(Pe===Me,function(){return"Error in fused matMul: inner shapes ("+Pe+") and ("+(Me+") of Tensors with shapes "+J.shape+" and ")+(fe.shape+" and transposeA="+d)+(" and transposeB="+v+" must match.")});var er=J.shape.slice(0,-2).concat([He,ct]),mr=d?Ke(J,[Bt,Pe,He]):Ke(J,[Bt,He,Pe]),Gr=v?Ke(fe,[sr,ct,Me]):Ke(fe,[sr,Me,ct]),en;_!=null&&(en=ie(_,"bias","fused matMul"),en=Nt(en,J)[0],ca(er,en.shape));var Qr;B!=null&&(Qr=ie(B,"prelu weights","fused matMul"));var Zr=function(xi,Ba){var ko=Ba[0],So=Ba[1],bu=Ba[2],zp=Ba[3],eu=Vh(Ke(xi,bu.shape),bu,D),dl,fl;if(!d&&!v?(dl=un(eu,So,!1,!0),fl=un(ko,eu,!0,!1)):!d&&v?(dl=un(eu,So,!1,!1),fl=un(eu,ko,!0,!1)):d&&!v?(dl=un(So,eu,!1,!0),fl=un(ko,eu,!1,!1)):(dl=un(So,eu,!0,!0),fl=un(eu,ko,!0,!0)),_!=null){var rg=Hh(zp,eu);return[dl,fl,rg]}else return[dl,fl]},Kr=function(xi){var Ba=xi.fusedBatchMatMul({a:mr,b:Gr,transposeA:d,transposeB:v,bias:en,activation:D,preluActivationWeights:Qr});return Ba},Un={a:mr,b:Gr,bias:en,preluActivationWeights:Qr},mn={transposeA:d,transposeB:v,activation:D};if(_==null){var Ln=Cs(function(xi,Ba,ko){var So=Ie.runKernelFunc(Kr,Un,null,Fo,mn);return ko([xi,Ba,So]),{value:Ke(So,er),gradFunc:Zr}});return Ln(mr,Gr)}else{var $s=Cs(function(xi,Ba,ko,So){var bu=Ie.runKernelFunc(Kr,Un,null,Fo,mn);return So([xi,Ba,bu,ko]),{value:Ke(bu,er),gradFunc:Zr}});return $s(mr,Gr,en)}}var m0=Ee({fusedMatMul_:f0}),y0={__proto__:null,conv2d:c0,depthwiseConv2d:d0,matMul:m0};function v0(t){return Cp(t,.54,.46)}var g0=Ee({hammingWindow_:v0});function x0(t){return Cp(t,.5,.5)}var qd=Ee({hannWindow_:x0});function _0(t,e,n,a,c){a===void 0&&(a=!1),c===void 0&&(c=0);for(var d=0,y=[];d+e<=t.size;)y.push($t(t,d,e)),d+=n;if(a)for(;d=1&&a[1]>=1,function(){return"cropSize must be atleast [1,1], but was "+a}),W(c==="bilinear"||c==="nearest",function(){return"method must be bilinear or nearest, but was "+c});var D=function(fe){return fe.cropAndResize(y,v,_,a,c,d)},B={image:y,boxes:v,boxInd:_},U={method:c,extrapolationValue:d,cropSize:a},J=Ie.runKernelFunc(D,B,null,ta,U);return J}var S0=Ee({cropAndResize_:k0});function I0(t){var e=ie(t,"image","flipLeftRight","float32");W(e.rank===4,function(){return"Error in flipLeftRight: image must be rank 4,"+("but got rank "+e.rank+".")});var n={image:e},a=Ie.runKernel(S,n,{});return a}var N0=Ee({flipLeftRight_:I0});function C0(t,e,n,a){n===void 0&&(n=0),a===void 0&&(a=.5);var c=ie(t,"image","rotateWithOffset","float32");W(c.rank===4,function(){return"Error in rotateWithOffset: image must be rank 4,"+("but got rank "+c.rank+".")});var d={image:c},y={radians:e,fillValue:n,center:a},v=Ie.runKernel(ys,d,y);return v}var T0=Ee({rotateWithOffset_:C0});function pl(t,e,n,a,c,d){a==null&&(a=.5),c==null&&(c=Number.NEGATIVE_INFINITY),d==null&&(d=0);var y=t.shape[0];return n=Math.min(n,y),W(0<=a&&a<=1,function(){return"iouThreshold must be in [0, 1], but was '"+a+"'"}),W(t.rank===2,function(){return"boxes must be a 2D tensor, but was of rank '"+t.rank+"'"}),W(t.shape[1]===4,function(){return"boxes must have 4 columns, but 2nd dimension was "+t.shape[1]}),W(e.rank===1,function(){return"scores must be a 1D tensor"}),W(e.shape[0]===y,function(){return"scores has incompatible shape with boxes. Expected "+y+", "+("but was "+e.shape[0])}),W(0<=d&&d<=1,function(){return"softNmsSigma must be in [0, 1], but was '"+d+"'"}),{maxOutputSize:n,iouThreshold:a,scoreThreshold:c,softNmsSigma:d}}function E0(t,e,n,a,c){a===void 0&&(a=.5),c===void 0&&(c=Number.NEGATIVE_INFINITY);var d=ie(t,"boxes","nonMaxSuppression"),y=ie(e,"scores","nonMaxSuppression"),v=pl(d,y,n,a,c);n=v.maxOutputSize,a=v.iouThreshold,c=v.scoreThreshold;var _={maxOutputSize:n,iouThreshold:a,scoreThreshold:c};return Ie.runKernelFunc(function(C){return C.nonMaxSuppression(d,y,n,a,c)},{boxes:d,scores:y},null,qa,_)}var R0=Ee({nonMaxSuppression_:E0});function A0(t,e,n){var a=D0(t,e,n),c=a<0?-(a+1):a;t.splice(c,0,e)}function D0(t,e,n){return O0(t,e,n||F0)}function F0(t,e){return t>e?1:t>>1);var v=n(e,t[d]);v>0?a=d+1:(c=d,y=!v)}return y?a:-a-1}function Xd(t,e,n,a,c){return Ep(t,e,n,a,c,0).selectedIndices}function Yd(t,e,n,a,c,d){return Ep(t,e,n,a,c,0,!1,d,!0)}function Qd(t,e,n,a,c,d){return Ep(t,e,n,a,c,d,!0)}function Ep(t,e,n,a,c,d,y,v,_){y===void 0&&(y=!1),v===void 0&&(v=!1),_===void 0&&(_=!1);for(var C=[],D=0;Dc&&C.push({score:e[D],boxIndex:D,suppressBeginIndex:0});C.sort(Zd);for(var B=d>0?-.5/d:0,U=[],J=[];U.length0;){var fe=C.pop(),Pe=fe.score,Me=fe.boxIndex,He=fe.suppressBeginIndex;if(Pe=He;--It){var Ct=M0(t,Me,U[It]);if(Ct>=a){ct=!0;break}if(fe.score=fe.score*L0(a,B,Ct),fe.score<=c)break}fe.suppressBeginIndex=U.length,ct||(fe.score===Pe?(U.push(Me),J.push(fe.score)):fe.score>c&&A0(C,fe,Zd))}var Bt=U.length,sr=n-Bt;v&&sr>0&&(U.push.apply(U,new Array(sr).fill(0)),J.push.apply(J,new Array(sr).fill(0)));var er={selectedIndices:cl(U,"int32")};return y&&(er.selectedScores=cl(J,"float32")),_&&(er.validOutputs=Wr(Bt,"int32")),er}function M0(t,e,n){var a=t.subarray(e*4,e*4+4),c=t.subarray(n*4,n*4+4),d=Math.min(a[0],a[2]),y=Math.min(a[1],a[3]),v=Math.max(a[0],a[2]),_=Math.max(a[1],a[3]),C=Math.min(c[0],c[2]),D=Math.min(c[1],c[3]),B=Math.max(c[0],c[2]),U=Math.max(c[1],c[3]),J=(v-d)*(_-y),fe=(B-C)*(U-D);if(J<=0||fe<=0)return 0;var Pe=Math.max(d,C),Me=Math.max(y,D),He=Math.min(v,B),ct=Math.min(_,U),It=Math.max(He-Pe,0)*Math.max(ct-Me,0);return It/(J+fe-It)}function L0(t,e,n){var a=Math.exp(e*n*n);return n<=t?a:0}function Zd(t,e){return t.score-e.score||t.score===e.score&&e.boxIndex-t.boxIndex}function z0(t,e,n,a,c){return a===void 0&&(a=.5),c===void 0&&(c=Number.NEGATIVE_INFINITY),O(this,void 0,void 0,function(){var d,y,v,_,C,D,B;return H(this,function(U){switch(U.label){case 0:return d=ie(t,"boxes","nonMaxSuppressionAsync"),y=ie(e,"scores","nonMaxSuppressionAsync"),v=pl(d,y,n,a,c),n=v.maxOutputSize,a=v.iouThreshold,c=v.scoreThreshold,[4,Promise.all([d.data(),y.data()])];case 1:return _=U.sent(),C=_[0],D=_[1],B=Xd(C,D,n,a,c),d!==t&&d.dispose(),y!==e&&y.dispose(),[2,B]}})})}var P0=z0;function B0(t,e,n,a,c,d){a===void 0&&(a=.5),c===void 0&&(c=Number.NEGATIVE_INFINITY),d===void 0&&(d=0);var y=ie(t,"boxes","nonMaxSuppression"),v=ie(e,"scores","nonMaxSuppression"),_=pl(y,v,n,a,c,d);n=_.maxOutputSize,a=_.iouThreshold,c=_.scoreThreshold,d=_.softNmsSigma;var C={boxes:y,scores:v},D={maxOutputSize:n,iouThreshold:a,scoreThreshold:c,softNmsSigma:d},B=Ie.runKernel(Ki,C,D);return{selectedIndices:B[0],selectedScores:B[1]}}var W0=Ee({nonMaxSuppressionWithScore_:B0});function U0(t,e,n,a,c,d){return a===void 0&&(a=.5),c===void 0&&(c=Number.NEGATIVE_INFINITY),d===void 0&&(d=0),O(this,void 0,void 0,function(){var y,v,_,C,D,B,U;return H(this,function(J){switch(J.label){case 0:return y=ie(t,"boxes","nonMaxSuppressionAsync"),v=ie(e,"scores","nonMaxSuppressionAsync"),_=pl(y,v,n,a,c,d),n=_.maxOutputSize,a=_.iouThreshold,c=_.scoreThreshold,d=_.softNmsSigma,[4,Promise.all([y.data(),v.data()])];case 1:return C=J.sent(),D=C[0],B=C[1],U=Qd(D,B,n,a,c,d),y!==t&&y.dispose(),v!==e&&v.dispose(),[2,U]}})})}var V0=U0;function H0(t,e,n,a,c,d){a===void 0&&(a=.5),c===void 0&&(c=Number.NEGATIVE_INFINITY),d===void 0&&(d=!1);var y=ie(t,"boxes","nonMaxSuppression"),v=ie(e,"scores","nonMaxSuppression"),_=pl(y,v,n,a,c,null),C=_.maxOutputSize,D=_.iouThreshold,B=_.scoreThreshold,U={boxes:y,scores:v},J={maxOutputSize:C,iouThreshold:D,scoreThreshold:B,padToMaxOutputSize:d},fe=Ie.runKernel(La,U,J);return{selectedIndices:fe[0],validOutputs:fe[1]}}var G0=Ee({nonMaxSuppressionPadded_:H0});function j0(t,e,n,a,c,d){return a===void 0&&(a=.5),c===void 0&&(c=Number.NEGATIVE_INFINITY),d===void 0&&(d=!1),O(this,void 0,void 0,function(){var y,v,_,C,D,B,U,J,fe,Pe;return H(this,function(Me){switch(Me.label){case 0:return y=ie(t,"boxes","nonMaxSuppressionAsync"),v=ie(e,"scores","nonMaxSuppressionAsync"),_=pl(y,v,n,a,c,null),C=_.maxOutputSize,D=_.iouThreshold,B=_.scoreThreshold,[4,Promise.all([y.data(),v.data()])];case 1:return U=Me.sent(),J=U[0],fe=U[1],Pe=Yd(J,fe,C,D,B,d),y!==t&&y.dispose(),v!==e&&v.dispose(),[2,Pe]}})})}var q0=j0;function K0(t,e,n){n===void 0&&(n=!1);var a=ie(t,"images","resizeBilinear");W(a.rank===3||a.rank===4,function(){return"Error in resizeBilinear: x must be rank 3 or 4, but got "+("rank "+a.rank+".")}),W(e.length===2,function(){return"Error in resizeBilinear: new shape must 2D, but got shape "+(e+".")});var c=a,d=!1;a.rank===3&&(d=!0,c=Ke(a,[1,a.shape[0],a.shape[1],a.shape[2]]));var y=e[0],v=e[1],_=function(U,J){return J([c]),U.resizeBilinear(c,y,v,n)},C={images:c},D={alignCorners:n,size:e},B=Ie.runKernelFunc(_,C,null,Qn,D);return d?Ke(B,[B.shape[1],B.shape[2],B.shape[3]]):B}var Jd=Ee({resizeBilinear_:K0});function X0(t,e,n){n===void 0&&(n=!1);var a=ie(t,"images","resizeNearestNeighbor");W(a.rank===3||a.rank===4,function(){return"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got "+("rank "+a.rank+".")}),W(e.length===2,function(){return"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+(e+".")}),W(a.dtype==="float32"||a.dtype==="int32",function(){return"`images` must have `int32` or `float32` as dtype"});var c=a,d=!1;a.rank===3&&(d=!0,c=Ke(a,[1,a.shape[0],a.shape[1],a.shape[2]]));var y=e[0],v=e[1],_={images:c},C={alignCorners:n,size:e},D=function(U,J){return J([c]),U.resizeNearestNeighbor(c,y,v,n)},B=Ie.runKernelFunc(D,_,null,oa,C);return d?Ke(B,[B.shape[1],B.shape[2],B.shape[3]]):B}var $d=Ee({resizeNearestNeighbor_:X0});function Y0(t,e,n){W(e%1===0,function(){return"bandPart(): numLower must be an integer, got "+e+"."}),W(n%1===0,function(){return"bandPart(): numUpper must be an integer, got "+n+"."});var a=ie(t,"a","bandPart");W(a.rank>=2,function(){return"bandPart(): Rank must be at least 2, got "+a.rank+"."});var c=a.shape,d=a.shape.slice(-2),y=d[0],v=d[1];if(!(e<=y))throw new Error("bandPart(): numLower ("+e+")"+(" must not be greater than the number of rows ("+y+")."));if(!(n<=v))throw new Error("bandPart(): numUpper ("+n+")"+(" must not be greater than the number of columns ("+v+")."));e<0&&(e=y),n<0&&(n=v);var _=Ke(_p(0,y,1,"int32"),[-1,1]),C=_p(0,v,1,"int32"),D=zr(_,C),B=nc(ec(D,Wr(+e,"int32")),$u(D,Wr(-n,"int32"))),U=Ys([y,v],a.dtype);return Ke(sc(Wh(Ke(a,[-1,y,v])).map(function(J){return us(B,J,U)})),c)}var Q0=Ee({bandPart_:Y0});function Z0(t){var e;if(Array.isArray(t)){e=!1,W(t!=null&&t.length>0,function(){return"Gram-Schmidt process: input must not be null, undefined, or empty"});for(var n=t[0].shape[0],a=function(_){W(t[_].shape[0]===n,function(){return"Gram-Schmidt: Non-unique lengths found in the input vectors: "+("("+t[_].shape[0]+" vs. "+n+")")})},c=1;c0)for(var B=0;B=2,function(){return"qr() requires input tensor to have a rank >= 2, but got rank "+t.rank}),t.rank===2)return ef(t,e);var n=t.shape.slice(0,t.shape.length-2).reduce(function(_,C){return _*C}),a=Wh(Ke(t,[n,t.shape[t.shape.length-2],t.shape[t.shape.length-1]]),0),c=[],d=[];a.forEach(function(_){var C=ef(_,e),D=C[0],B=C[1];c.push(D),d.push(B)});var y=Ke(sc(c,0),t.shape),v=Ke(sc(d,0),t.shape);return[y,v]}function ef(t,e){return e===void 0&&(e=!1),Ie.tidy(function(){W(t.shape.length===2,function(){return"qr2d() requires a 2D Tensor, but got a "+t.shape.length+"D Tensor."});for(var n=t.shape[0],a=t.shape[1],c=$p(n),d=Ho(t),y=yh([[1]],[1,1]),v=Ho(y),_=n>=a?a:n,C=function(B){var U,J=d,fe=v,Pe=c;U=Ie.tidy(function(){var Me=$t(d,[B,B],[n-B,1]),He=Uh(Me),ct=$t(d,[B,B],[1,1]),It=us(_u(ct,0),yh([[-1]]),yh([[1]])),Ct=zr(ct,bt(It,He)),Bt=Br(Me,Ct);Bt.shape[0]===1?v=Ho(y):v=kr([y,$t(Bt,[1,0],[Bt.shape[0]-1,Bt.shape[1]])],0);var sr=$a(Br(un(It,Ct),He)),er=$t(d,[B,0],[n-B,a]),mr=bt(sr,v),Gr=$n(v);if(B===0)d=zr(er,un(mr,un(Gr,er)));else{var en=zr(er,un(mr,un(Gr,er)));d=kr([$t(d,[0,0],[B,a]),en],0)}var Qr=$n(mr),Zr=$t(c,[0,B],[n,c.shape[1]-B]);if(B===0)c=zr(Zr,un(un(Zr,v),Qr));else{var Kr=zr(Zr,un(un(Zr,v),Qr));c=kr([$t(c,[0,0],[n,B]),Kr],1)}return[v,d,c]}),v=U[0],d=U[1],c=U[2],Pa([J,fe,Pe])},D=0;D<_;++D)C(D);return!e&&n>a&&(c=$t(c,[0,0],[n,a]),d=$t(d,[0,0],[a,a])),[c,d]})}var e2=Ee({qr_:$0});(function(t){t[t.NONE=0]="NONE",t[t.MEAN=1]="MEAN",t[t.SUM=2]="SUM",t[t.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"})(N.Reduction||(N.Reduction={}));function t2(t,e,n){n===void 0&&(n=N.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=ie(t,"losses","computeWeightedLoss"),c=null;e!=null&&(c=ie(e,"weights","computeWeightedLoss"));var d=c==null?a:bt(a,c);if(n===N.Reduction.NONE)return d;if(n===N.Reduction.SUM)return Yr(d);if(n===N.Reduction.MEAN){if(c==null)return ph(d);var y=a.size/c.size,v=Br(Yr(d),Yr(c));return y>1?Br(v,Wr(y)):v}if(n===N.Reduction.SUM_BY_NONZERO_WEIGHTS){if(c==null)return Br(Yr(d),Wr(a.size));var _=bt(c,sl(a.shape)),C=pr(Yr(Oh(_,Wr(0))),"float32");return Br(Yr(d),C)}throw Error("Unknown reduction: "+n)}var Js=Ee({computeWeightedLoss_:t2});function r2(t,e,n,a){a===void 0&&(a=N.Reduction.SUM_BY_NONZERO_WEIGHTS);var c=ie(t,"labels","absoluteDifference"),d=ie(e,"predictions","absoluteDifference"),y=null;n!=null&&(y=ie(n,"weights","absoluteDifference")),nt(c.shape,d.shape,"Error in absoluteDifference: ");var v=ui(zr(c,d));return Js(v,y,a)}var n2=Ee({absoluteDifference_:r2});function a2(t,e,n,a,c){c===void 0&&(c=N.Reduction.SUM_BY_NONZERO_WEIGHTS);var d=ie(t,"labels","cosineDistance"),y=ie(e,"predictions","cosineDistance"),v=null;a!=null&&(v=ie(a,"weights","cosineDistance")),nt(d.shape,y.shape,"Error in cosineDistance: ");var _=Wr(1),C=zr(_,Yr(bt(d,y),n,!0));return Js(C,v,c)}var i2=Ee({cosineDistance_:a2});function o2(t,e,n,a){a===void 0&&(a=N.Reduction.SUM_BY_NONZERO_WEIGHTS);var c=ie(t,"labels","hingeLoss"),d=ie(e,"predictions","hingeLoss"),y=null;n!=null&&(y=ie(n,"weights","hingeLoss")),nt(c.shape,d.shape,"Error in hingeLoss: ");var v=Wr(1);c=zr(bt(Wr(2),c),v);var _=fh(zr(v,bt(c,d)));return Js(_,y,a)}var s2=Ee({hingeLoss_:o2});function u2(t,e,n,a,c){a===void 0&&(a=1),c===void 0&&(c=N.Reduction.SUM_BY_NONZERO_WEIGHTS);var d=ie(t,"labels","huberLoss"),y=ie(e,"predictions","huberLoss"),v=null;n!=null&&(v=ie(n,"weights","huberLoss")),nt(d.shape,y.shape,"Error in huberLoss: ");var _=Wr(a),C=ui(zr(y,d)),D=Fh(C,_),B=zr(C,D),U=Cr(bt(Wr(.5),Yn(D)),bt(_,B));return Js(U,v,c)}var c2=Ee({huberLoss_:u2});function l2(t,e,n,a,c){a===void 0&&(a=1e-7),c===void 0&&(c=N.Reduction.SUM_BY_NONZERO_WEIGHTS);var d=ie(t,"labels","logLoss"),y=ie(e,"predictions","logLoss"),v=null;n!=null&&(v=ie(n,"weights","logLoss")),nt(d.shape,y.shape,"Error in logLoss: ");var _=Wr(1),C=Wr(a),D=$a(bt(d,tc(Cr(y,C)))),B=bt(zr(_,d),tc(Cr(zr(_,y),C))),U=zr(D,B);return Js(U,v,c)}var h2=Ee({logLoss_:l2});function p2(t,e,n,a){a===void 0&&(a=N.Reduction.SUM_BY_NONZERO_WEIGHTS);var c=ie(t,"labels","meanSquaredError"),d=ie(e,"predictions","meanSquaredError"),y=null;n!=null&&(y=ie(n,"weights","meanSquaredError")),nt(c.shape,d.shape,"Error in meanSquaredError: ");var v=Ph(c,d);return Js(v,y,a)}var d2=Ee({meanSquaredError_:p2});function f2(t,e){var n=ie(t,"labels","sigmoidCrossEntropyWithLogits"),a=ie(e,"logits","sigmoidCrossEntropyWithLogits");nt(n.shape,a.shape,"Error in sigmoidCrossEntropyWithLogits: ");var c=fh(a),d=bt(a,n),y=lp(cs($a(ui(a))));return Cr(zr(c,d),y)}function m2(t,e,n,a,c){a===void 0&&(a=0),c===void 0&&(c=N.Reduction.SUM_BY_NONZERO_WEIGHTS);var d=ie(t,"multiClassLabels","sigmoidCrossEntropy"),y=ie(e,"logits","sigmoidCrossEntropy"),v=null;if(n!=null&&(v=ie(n,"weights","sigmoidCrossEntropy")),nt(d.shape,y.shape,"Error in sigmoidCrossEntropy: "),a>0){var _=Wr(a),C=Wr(1),D=Wr(.5);d=Cr(bt(d,zr(C,_)),bt(D,_))}var B=f2(d,y);return Js(B,v,c)}var y2=Ee({sigmoidCrossEntropy_:m2});function v2(t,e,n){if(n===void 0&&(n=-1),n===-1&&(n=e.rank-1),n!==e.rank-1)throw Error("Softmax cross entropy along a non-last dimension is not yet "+("supported. Labels / logits was rank "+e.rank+" ")+("and dim was "+n));var a=Cs(function(c,d,y){var v=!0,_=pp(d,[n],v),C=zr(pr(d,"float32"),_);y([c,C]);var D=$a(bt(C,c)),B=Yr(D,[n]),U=function(J,fe){var Pe=fe[0],Me=fe[1],He=ci(J.shape,[n]);return[bt(Ke(J,He),zr(pr(Pe,"float32"),cs(Me))),bt(Ke(J,He),zr(cs(Me),pr(Pe,"float32")))]};return{value:B,gradFunc:U}});return a(t,e)}function g2(t,e,n,a,c){a===void 0&&(a=0),c===void 0&&(c=N.Reduction.SUM_BY_NONZERO_WEIGHTS);var d=ie(t,"onehotLabels","softmaxCrossEntropy"),y=ie(e,"logits","softmaxCrossEntropy"),v=null;if(n!=null&&(v=ie(n,"weights","softmaxCrossEntropy")),nt(d.shape,y.shape,"Error in softmaxCrossEntropy: "),a>0){var _=Wr(a),C=Wr(1),D=Wr(d.shape[1]);d=Cr(bt(d,zr(C,_)),Br(_,D))}var B=v2(d,y);return Js(B,v,c)}var x2=Ee({softmaxCrossEntropy_:g2}),_2={fft:Lh,ifft:mh,rfft:zh,irfft:Ip},w2={hammingWindow:g0,hannWindow:qd,frame:Kd,stft:b0},b2={flipLeftRight:N0,resizeNearestNeighbor:$d,resizeBilinear:Jd,rotateWithOffset:T0,cropAndResize:S0,nonMaxSuppression:R0,nonMaxSuppressionAsync:P0,nonMaxSuppressionWithScore:W0,nonMaxSuppressionWithScoreAsync:V0,nonMaxSuppressionPadded:G0,nonMaxSuppressionPaddedAsync:q0},k2={bandPart:Q0,gramSchmidt:J0,qr:e2},S2={absoluteDifference:n2,computeWeightedLoss:Js,cosineDistance:i2,hingeLoss:s2,huberLoss:c2,logLoss:h2,meanSquaredError:d2,sigmoidCrossEntropy:y2,softmaxCrossEntropy:x2},wu=function(t){ke(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.minimize=function(n,a,c){a===void 0&&(a=!1);var d=this.computeGradients(n,c),y=d.value,v=d.grads;if(c!=null){var _=c.map(function(C){return{name:C.name,tensor:v[C.name]}});this.applyGradients(_)}else this.applyGradients(v);return Pa(v),a?y:(y.dispose(),null)},Object.defineProperty(e.prototype,"iterations",{get:function(){return this.iterations_==null&&(this.iterations_=0),this.iterations_},enumerable:!0,configurable:!0}),e.prototype.incrementIterations=function(){this.iterations_=this.iterations+1},e.prototype.computeGradients=function(n,a){return od(n,a)},e.prototype.dispose=function(){this.iterations_!=null&&Pa(this.iterations_)},e.prototype.saveIterations=function(){return O(this,void 0,void 0,function(){return H(this,function(n){return this.iterations_==null&&(this.iterations_=0),[2,{name:"iter",tensor:Wr(this.iterations_,"int32")}]})})},e.prototype.getWeights=function(){return O(this,void 0,void 0,function(){return H(this,function(n){throw new Error("getWeights() is not implemented for this optimizer yet.")})})},e.prototype.setWeights=function(n){return O(this,void 0,void 0,function(){return H(this,function(a){throw new Error("setWeights() is not implemented for this optimizer class "+(""+this.getClassName()))})})},e.prototype.extractIterations=function(n){return O(this,void 0,void 0,function(){var a;return H(this,function(c){switch(c.label){case 0:return a=this,[4,n[0].tensor.data()];case 1:return a.iterations_=c.sent()[0],[2,n.slice(1)]}})})},e}(Yc);Object.defineProperty(wu,Symbol.hasInstance,{value:function(t){return t.minimize!=null&&t.computeGradients!=null&&t.applyGradients!=null}});var Rp=function(t){ke(e,t);function e(n,a,c){c===void 0&&(c=null);var d=t.call(this)||this;return d.learningRate=n,d.rho=a,d.epsilon=c,d.accumulatedGrads=[],d.accumulatedUpdates=[],c==null&&(d.epsilon=Ie.backend.epsilon()),d}return e.prototype.applyGradients=function(n){var a=this,c=Array.isArray(n)?n.map(function(d){return d.name}):Object.keys(n);c.forEach(function(d,y){var v=Ie.registeredVariables[d],_=!1;a.accumulatedGrads[y]==null&&(a.accumulatedGrads[y]={originalName:d+"/accum_grad",variable:sa(function(){return gn(v).variable(_)})}),a.accumulatedUpdates[y]==null&&(a.accumulatedUpdates[y]={originalName:d+"/accum_var",variable:sa(function(){return gn(v).variable(_)})});var C=Array.isArray(n)?n[y].tensor:n[d];if(C==null)return;var D=a.accumulatedGrads[y].variable,B=a.accumulatedUpdates[y].variable;sa(function(){var U=Cr(bt(D,a.rho),bt(Yn(C),1-a.rho)),J=bt(Br(eo(Cr(B,a.epsilon)),eo(Cr(D,a.epsilon))),C),fe=Cr(bt(B,a.rho),bt(Yn(J),1-a.rho));D.assign(U),B.assign(fe);var Pe=Cr(bt(J,-a.learningRate),v);v.assign(Pe)})}),this.incrementIterations()},e.prototype.dispose=function(){this.accumulatedUpdates!=null&&(Pa(this.accumulatedGrads.map(function(n){return n.variable})),Pa(this.accumulatedUpdates.map(function(n){return n.variable})))},e.prototype.getWeights=function(){return O(this,void 0,void 0,function(){var n;return H(this,function(a){switch(a.label){case 0:return n=this.accumulatedGrads.concat(this.accumulatedUpdates),[4,this.saveIterations()];case 1:return[2,[a.sent()].concat(n.map(function(c){return{name:c.originalName,tensor:c.variable}}))]}})})},e.prototype.setWeights=function(n){return O(this,void 0,void 0,function(){var a,c;return H(this,function(d){switch(d.label){case 0:return[4,this.extractIterations(n)];case 1:return n=d.sent(),a=n.length/2,c=!1,this.accumulatedGrads=n.slice(0,a).map(function(y){return{originalName:y.name,variable:y.tensor.variable(c)}}),this.accumulatedUpdates=n.slice(a,a*2).map(function(y){return{originalName:y.name,variable:y.tensor.variable(c)}}),[2]}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}},e.fromConfig=function(n,a){return new n(a.learningRate,a.rho,a.epsilon)},e.className="Adadelta",e}(wu);jo(Rp);var Ap=function(t){ke(e,t);function e(n,a){a===void 0&&(a=.1);var c=t.call(this)||this;return c.learningRate=n,c.initialAccumulatorValue=a,c.accumulatedGrads=[],c}return e.prototype.applyGradients=function(n){var a=this,c=Array.isArray(n)?n.map(function(d){return d.name}):Object.keys(n);c.forEach(function(d,y){var v=Ie.registeredVariables[d];if(a.accumulatedGrads[y]==null){var _=!1;a.accumulatedGrads[y]={originalName:d+"/accumulator",variable:sa(function(){return up(v.shape,a.initialAccumulatorValue).variable(_)})}}var C=Array.isArray(n)?n[y].tensor:n[d];if(C==null)return;var D=a.accumulatedGrads[y].variable;sa(function(){var B=Cr(D,Yn(C));D.assign(B);var U=Cr(bt(Br(C,eo(Cr(B,Ie.backend.epsilon()))),-a.learningRate),v);v.assign(U)})}),this.incrementIterations()},e.prototype.dispose=function(){this.accumulatedGrads!=null&&Pa(this.accumulatedGrads.map(function(n){return n.variable}))},e.prototype.getWeights=function(){return O(this,void 0,void 0,function(){return H(this,function(n){switch(n.label){case 0:return[4,this.saveIterations()];case 1:return[2,[n.sent()].concat(this.accumulatedGrads.map(function(a){return{name:a.originalName,tensor:a.variable}}))]}})})},e.prototype.setWeights=function(n){return O(this,void 0,void 0,function(){var a;return H(this,function(c){switch(c.label){case 0:return[4,this.extractIterations(n)];case 1:return n=c.sent(),a=!1,this.accumulatedGrads=n.map(function(d){return{originalName:d.name,variable:d.tensor.variable(a)}}),[2]}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}},e.fromConfig=function(n,a){return new n(a.learningRate,a.initialAccumulatorValue)},e.className="Adagrad",e}(wu);jo(Ap);var Dp=function(t){ke(e,t);function e(n,a,c,d){d===void 0&&(d=null);var y=t.call(this)||this;return y.learningRate=n,y.beta1=a,y.beta2=c,y.epsilon=d,y.accumulatedFirstMoment=[],y.accumulatedSecondMoment=[],sa(function(){y.accBeta1=Wr(a).variable(),y.accBeta2=Wr(c).variable()}),d==null&&(y.epsilon=Ie.backend.epsilon()),y}return e.prototype.applyGradients=function(n){var a=this,c=Array.isArray(n)?n.map(function(d){return d.name}):Object.keys(n);sa(function(){var d=zr(1,a.accBeta1),y=zr(1,a.accBeta2);c.forEach(function(v,_){var C=Ie.registeredVariables[v],D=!1;a.accumulatedFirstMoment[_]==null&&(a.accumulatedFirstMoment[_]={originalName:v+"/m",variable:sa(function(){return gn(C).variable(D)})}),a.accumulatedSecondMoment[_]==null&&(a.accumulatedSecondMoment[_]={originalName:v+"/v",variable:sa(function(){return gn(C).variable(D)})});var B=Array.isArray(n)?n[_].tensor:n[v];if(B==null)return;var U=a.accumulatedFirstMoment[_].variable,J=a.accumulatedSecondMoment[_].variable,fe=Cr(bt(U,a.beta1),bt(B,1-a.beta1)),Pe=Cr(bt(J,a.beta2),bt(Yn(B),1-a.beta2)),Me=Br(fe,d),He=Br(Pe,y);U.assign(fe),J.assign(Pe);var ct=Cr(bt(Br(Me,Cr(eo(He),a.epsilon)),-a.learningRate),C);C.assign(ct)}),a.accBeta1.assign(bt(a.accBeta1,a.beta1)),a.accBeta2.assign(bt(a.accBeta2,a.beta2))}),this.incrementIterations()},e.prototype.dispose=function(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&Pa(this.accumulatedFirstMoment.map(function(n){return n.variable})),this.accumulatedSecondMoment!=null&&Pa(this.accumulatedSecondMoment.map(function(n){return n.variable}))},e.prototype.getWeights=function(){return O(this,void 0,void 0,function(){var n;return H(this,function(a){switch(a.label){case 0:return n=this.accumulatedFirstMoment.concat(this.accumulatedSecondMoment),[4,this.saveIterations()];case 1:return[2,[a.sent()].concat(n.map(function(c){return{name:c.originalName,tensor:c.variable}}))]}})})},e.prototype.setWeights=function(n){return O(this,void 0,void 0,function(){var a,c,d=this;return H(this,function(y){switch(y.label){case 0:return[4,this.extractIterations(n)];case 1:return n=y.sent(),sa(function(){d.accBeta1.assign(Qs(d.beta1,d.iterations_+1)),d.accBeta2.assign(Qs(d.beta2,d.iterations_+1))}),a=n.length/2,c=!1,this.accumulatedFirstMoment=n.slice(0,a).map(function(v){return{originalName:v.name,variable:v.tensor.variable(c)}}),this.accumulatedSecondMoment=n.slice(a,a*2).map(function(v){return{originalName:v.name,variable:v.tensor.variable(c)}}),[2]}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}},e.fromConfig=function(n,a){return new n(a.learningRate,a.beta1,a.beta2,a.epsilon)},e.className="Adam",e}(wu);jo(Dp);var Fp=function(t){ke(e,t);function e(n,a,c,d,y){d===void 0&&(d=null),y===void 0&&(y=0);var v=t.call(this)||this;return v.learningRate=n,v.beta1=a,v.beta2=c,v.epsilon=d,v.decay=y,v.accumulatedFirstMoment=[],v.accumulatedWeightedInfNorm=[],sa(function(){v.iteration=Wr(0).variable(),v.accBeta1=Wr(a).variable()}),d==null&&(v.epsilon=Ie.backend.epsilon()),v}return e.prototype.applyGradients=function(n){var a=this,c=Array.isArray(n)?n.map(function(d){return d.name}):Object.keys(n);sa(function(){var d=zr(1,a.accBeta1),y=Br(-a.learningRate,Cr(bt(a.iteration,a.decay),1));c.forEach(function(v,_){var C=Ie.registeredVariables[v],D=!1;a.accumulatedFirstMoment[_]==null&&(a.accumulatedFirstMoment[_]={originalName:v+"/m",variable:gn(C).variable(D)}),a.accumulatedWeightedInfNorm[_]==null&&(a.accumulatedWeightedInfNorm[_]={originalName:v+"/v",variable:gn(C).variable(D)});var B=Array.isArray(n)?n[_].tensor:n[v];if(B==null)return;var U=a.accumulatedFirstMoment[_].variable,J=a.accumulatedWeightedInfNorm[_].variable,fe=Cr(bt(U,a.beta1),bt(B,1-a.beta1)),Pe=bt(J,a.beta2),Me=ui(B),He=ol(Pe,Me);U.assign(fe),J.assign(He);var ct=Cr(bt(Br(y,d),Br(fe,Cr(He,a.epsilon))),C);C.assign(ct)}),a.iteration.assign(Cr(a.iteration,1)),a.accBeta1.assign(bt(a.accBeta1,a.beta1))}),this.incrementIterations()},e.prototype.dispose=function(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&Pa(this.accumulatedFirstMoment.map(function(n){return n.variable})),this.accumulatedWeightedInfNorm!=null&&Pa(this.accumulatedWeightedInfNorm.map(function(n){return n.variable}))},e.prototype.getWeights=function(){return O(this,void 0,void 0,function(){return H(this,function(n){throw new Error("getWeights() is not implemented for Adamax yet.")})})},e.prototype.setWeights=function(n){return O(this,void 0,void 0,function(){return H(this,function(a){throw new Error("setWeights() is not implemented for Adamax yet.")})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}},e.fromConfig=function(n,a){return new n(a.learningRate,a.beta1,a.beta2,a.epsilon,a.decay)},e.className="Adamax",e}(wu);jo(Fp);var qh=function(t){ke(e,t);function e(n){var a=t.call(this)||this;return a.learningRate=n,a.setLearningRate(n),a}return e.prototype.applyGradients=function(n){var a=this,c=Array.isArray(n)?n.map(function(d){return d.name}):Object.keys(n);c.forEach(function(d,y){var v=Array.isArray(n)?n[y].tensor:n[d];if(v==null)return;var _=Ie.registeredVariables[d];sa(function(){var C=Cr(bt(a.c,v),_);_.assign(C)})}),this.incrementIterations()},e.prototype.setLearningRate=function(n){this.learningRate=n,this.c!=null&&this.c.dispose(),this.c=xu(Wr(-n))},e.prototype.dispose=function(){this.c.dispose()},e.prototype.getWeights=function(){return O(this,void 0,void 0,function(){return H(this,function(n){switch(n.label){case 0:return[4,this.saveIterations()];case 1:return[2,[n.sent()]]}})})},e.prototype.setWeights=function(n){return O(this,void 0,void 0,function(){return H(this,function(a){switch(a.label){case 0:return[4,this.extractIterations(n)];case 1:if(n=a.sent(),n.length!==0)throw new Error("SGD optimizer does not have settable weights.");return[2]}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate}},e.fromConfig=function(n,a){return new n(a.learningRate)},e.className="SGD",e}(wu);jo(qh);var Op=function(t){ke(e,t);function e(n,a,c){c===void 0&&(c=!1);var d=t.call(this,n)||this;return d.learningRate=n,d.momentum=a,d.useNesterov=c,d.accumulations=[],d.m=Wr(d.momentum),d}return e.prototype.applyGradients=function(n){var a=this,c=Array.isArray(n)?n.map(function(d){return d.name}):Object.keys(n);c.forEach(function(d,y){var v=Ie.registeredVariables[d];if(a.accumulations[y]==null){var _=!1;a.accumulations[y]={originalName:d+"/momentum",variable:sa(function(){return gn(v).variable(_)})}}var C=a.accumulations[y].variable,D=Array.isArray(n)?n[y].tensor:n[d];if(D==null)return;sa(function(){var B,U=Cr(bt(a.m,C),D);a.useNesterov?B=Cr(bt(a.c,Cr(D,bt(U,a.m))),v):B=Cr(bt(a.c,U),v),C.assign(U),v.assign(B)})}),this.incrementIterations()},e.prototype.dispose=function(){this.m.dispose(),this.accumulations!=null&&Pa(this.accumulations.map(function(n){return n.variable}))},e.prototype.setMomentum=function(n){this.momentum=n},e.prototype.getWeights=function(){return O(this,void 0,void 0,function(){return H(this,function(n){switch(n.label){case 0:return[4,this.saveIterations()];case 1:return[2,[n.sent()].concat(this.accumulations.map(function(a){return{name:a.originalName,tensor:a.variable}}))]}})})},e.prototype.setWeights=function(n){return O(this,void 0,void 0,function(){var a;return H(this,function(c){switch(c.label){case 0:return[4,this.extractIterations(n)];case 1:return n=c.sent(),a=!1,this.accumulations=n.map(function(d){return{originalName:d.name,variable:d.tensor.variable(a)}}),[2]}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}},e.fromConfig=function(n,a){return new n(a.learningRate,a.momentum,a.useNesterov)},e.className="Momentum",e}(qh);jo(Op);var Mp=function(t){ke(e,t);function e(n,a,c,d,y){a===void 0&&(a=.9),c===void 0&&(c=0),d===void 0&&(d=null),y===void 0&&(y=!1);var v=t.call(this)||this;if(v.learningRate=n,v.decay=a,v.momentum=c,v.epsilon=d,v.accumulatedMeanSquares=[],v.accumulatedMoments=[],v.accumulatedMeanGrads=[],v.centered=y,d==null&&(v.epsilon=Ie.backend.epsilon()),n==null)throw new Error("learningRate for RMSPropOptimizer must be defined.");return v}return e.prototype.applyGradients=function(n){var a=this,c=Array.isArray(n)?n.map(function(d){return d.name}):Object.keys(n);c.forEach(function(d,y){var v=Ie.registeredVariables[d],_=!1;a.accumulatedMeanSquares[y]==null&&(a.accumulatedMeanSquares[y]={originalName:d+"/rms",variable:sa(function(){return gn(v).variable(_)})}),a.accumulatedMoments[y]==null&&(a.accumulatedMoments[y]={originalName:d+"/momentum",variable:sa(function(){return gn(v).variable(_)})}),a.accumulatedMeanGrads[y]==null&&a.centered&&(a.accumulatedMeanGrads[y]={originalName:d+"/mg",variable:sa(function(){return gn(v).variable(_)})});var C=Array.isArray(n)?n[y].tensor:n[d];if(C==null)return;var D=a.accumulatedMeanSquares[y].variable,B=a.accumulatedMoments[y].variable;sa(function(){var U=Cr(bt(D,a.decay),bt(Yn(C),1-a.decay));if(a.centered){var J=a.accumulatedMeanGrads[y].variable,fe=Cr(bt(J,a.decay),bt(C,1-a.decay)),Pe=Br(bt(C,a.learningRate),eo(zr(U,Cr(Yn(fe),a.epsilon)))),Me=Cr(bt(B,a.momentum),Pe);D.assign(U),J.assign(fe),B.assign(Me);var He=zr(v,Me);v.assign(He)}else{var ct=Cr(bt(D,a.decay),bt(Yn(C),1-a.decay)),Me=Cr(bt(B,a.momentum),Br(bt(C,a.learningRate),eo(Cr(ct,a.epsilon))));D.assign(ct),B.assign(Me);var He=zr(v,Me);v.assign(He)}})}),this.incrementIterations()},e.prototype.dispose=function(){this.accumulatedMeanSquares!=null&&Pa(this.accumulatedMeanSquares.map(function(n){return n.variable})),this.accumulatedMeanGrads!=null&&this.centered&&Pa(this.accumulatedMeanGrads.map(function(n){return n.variable})),this.accumulatedMoments!=null&&Pa(this.accumulatedMoments.map(function(n){return n.variable}))},e.prototype.getWeights=function(){return O(this,void 0,void 0,function(){var n;return H(this,function(a){switch(a.label){case 0:return n=this.accumulatedMeanSquares.concat(this.accumulatedMoments),this.centered&&n.push.apply(n,this.accumulatedMeanGrads),[4,this.saveIterations()];case 1:return[2,[a.sent()].concat(n.map(function(c){return{name:c.originalName,tensor:c.variable}}))]}})})},e.prototype.setWeights=function(n){return O(this,void 0,void 0,function(){var a,c;return H(this,function(d){switch(d.label){case 0:return[4,this.extractIterations(n)];case 1:return n=d.sent(),a=this.centered?n.length/3:n.length/2,c=!1,this.accumulatedMeanSquares=n.slice(0,a).map(function(y){return{originalName:y.name,variable:y.tensor.variable(c)}}),this.accumulatedMoments=n.slice(a,a*2).map(function(y){return{originalName:y.name,variable:y.tensor.variable(c)}}),this.centered&&(this.accumulatedMeanGrads=n.slice(a*2,a*3).map(function(y){return{originalName:y.name,variable:y.tensor.variable(c)}})),[2]}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}},e.fromConfig=function(n,a){return new n(a.learningRate,a.decay,a.momentum,a.epsilon,a.centered)},e.className="RMSProp",e}(wu);jo(Mp);var uc=function(){function t(){}return t.sgd=function(e){return new qh(e)},t.momentum=function(e,n,a){return a===void 0&&(a=!1),new Op(e,n,a)},t.rmsprop=function(e,n,a,c,d){return n===void 0&&(n=.9),a===void 0&&(a=0),c===void 0&&(c=null),d===void 0&&(d=!1),new Mp(e,n,a,c,d)},t.adam=function(e,n,a,c){return e===void 0&&(e=.001),n===void 0&&(n=.9),a===void 0&&(a=.999),c===void 0&&(c=null),new Dp(e,n,a,c)},t.adadelta=function(e,n,a){return e===void 0&&(e=.001),n===void 0&&(n=.95),a===void 0&&(a=null),new Rp(e,n,a)},t.adamax=function(e,n,a,c,d){return e===void 0&&(e=.002),n===void 0&&(n=.9),a===void 0&&(a=.999),c===void 0&&(c=null),d===void 0&&(d=0),new Fp(e,n,a,c,d)},t.adagrad=function(e,n){return n===void 0&&(n=.1),new Ap(e,n)},t}(),I2={sgd:uc.sgd,momentum:uc.momentum,adadelta:uc.adadelta,adagrad:uc.adagrad,rmsprop:uc.rmsprop,adamax:uc.adamax,adam:uc.adam},N2=function(){return typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:function(t){return t()}}();function C2(){return new Promise(function(t){return N2(function(){return t()})})}function T2(t,e,n){var a=n*(typeof t=="number"?t:t[0]),c=e*(typeof t=="number"?t:t[1]);return[a,c]}function E2(t,e,n,a){a===void 0&&(a=!0);var c=[];if(a)c=c.concat(e.slice(0)),c.push(t[0]/n),c=c.concat(t.slice(1));else{c=c.concat(t[0]);for(var d=e.length,y=0;y=e*2+1||c%2===1?y.push(c):d.push(c);a.push.apply(a,d),a.push(0),a.push.apply(a,y)}return a}function A2(t,e,n,a){a===void 0&&(a=!0);var c=[];a?c.push(t[0]/n):c.push(t[0]*n);for(var d=1;d0&&(v=Yr(v,_)),Ke(v,n.shape)},y=function(){var v=t,_=Ja(a.shape,c);return _.length>0&&(v=Yr(v,_)),Ke(v,a.shape)};return{a:d,b:y}}},uv={kernelName:di,saveAllInputs:!0,gradFunc:function(t,e){var n={};return e.forEach(function(a,c){n[c]=function(){return t.clone()}}),n}},cv={kernelName:ln,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return gn(n)}}}},lv={kernelName:ni,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return gn(n)}}}},hv={kernelName:gr,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return Br(t,eo(zr(Wr(1),Yn(pr(n,"float32")))))}}}},pv={kernelName:Di,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){var a=eo(Cr(Wr(1),Yn(pr(n,"float32"))));return Br(t,a)}}}},dv={kernelName:Zn,inputsToSave:["a","b"],gradFunc:function(t,e){var n=e[0],a=e[1],c=ca(n.shape,a.shape),d=function(){var v=Cr(Yn(n),Yn(a)),_=bt(t,Br(a,v)),C=Ja(n.shape,c);return C.length>0&&(_=Yr(_,C)),Ke(_,n.shape)},y=function(){var v=Cr(Yn(n),Yn(a)),_=$a(bt(t,Br(n,v))),C=Ja(a.shape,c);return C.length>0&&(_=Yr(_,C)),Ke(_,a.shape)};return{a:d,b:y}}},fv={kernelName:bi,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return Br(t,Cr(Yn(pr(n,"float32")),1))}}}},mv={kernelName:ro,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return Br(t,zr(Wr(1),Yn(pr(n,"float32"))))}}}};function yv(t,e,n,a,c,d,y){c===void 0&&(c=[1,1,1]);var v=ie(t,"dy","avgPool3dBackprop"),_=ie(e,"input","avgPool3dBackprop"),C=v,D=_,B=!1;_.rank===4&&(B=!0,C=Ke(v,[1,v.shape[0],v.shape[1],v.shape[2],v.shape[3]]),D=Ke(_,[1,_.shape[0],_.shape[1],_.shape[2],_.shape[3]])),W(C.rank===5,function(){return"Error in avgPool3dBackprop: dy must be rank 5 but got rank "+(C.rank+".")}),W(D.rank===5,function(){return"Error in avgPool3dBackprop: input must be rank 5 but got rank "+(D.rank+".")}),W(dt(a,c),function(){return"Error in avgPool3dBackprop: Either strides or dilations "+("must be 1. Got strides "+a+" and dilations '"+c+"'")}),y!=null&&W(xt(d),function(){return"Error in maxPool3dBackprop: pad must be an integer when "+("using, dimRoundingMode "+y+" but got pad "+d+".")});var U=function(Me){var He=b(D.shape,n,a,c,d,y);return Me.avgPool3dBackprop(C,D,He)},J={dy:C,input:D},fe={filterSize:n,strides:a,dilations:c,pad:d,dimRoundingMode:y},Pe=Ie.runKernelFunc(U,J,null,Oi,fe);return B?Ke(Pe,[Pe.shape[1],Pe.shape[2],Pe.shape[3],Pe.shape[4]]):Pe}var vv=Ee({avgPool3dBackprop_:yv}),gv={kernelName:ji,inputsToSave:["x"],gradFunc:function(t,e,n){var a=e[0],c=n,d=c.filterSize,y=c.strides,v=c.dilations,_=c.pad,C=c.dimRoundingMode,D=v??[1,1,1];return{x:function(){return vv(t,a,d,y,D,_,C)}}}};function xv(t,e,n,a,c){var d=ie(t,"dy","avgPoolBackprop"),y=ie(e,"input","avgPoolBackprop");W(y.rank===d.rank,function(){return"Rank of input ("+y.rank+") does not match rank of dy ("+d.rank+")"});var v=y,_=d,C=!1;y.rank===3&&(C=!0,v=Ke(y,[1,y.shape[0],y.shape[1],y.shape[2]]),_=Ke(d,[1,d.shape[0],d.shape[1],d.shape[2]])),W(_.rank===4,function(){return"Error in avgPoolBackprop: dy must be rank 4 but got rank "+(_.rank+".")}),W(v.rank===4,function(){return"Error in avgPoolBackprop: input must be rank 4 but got rank "+(v.rank+".")});var D=function(fe){var Pe=h(v.shape,n,a,1,c);return fe.avgPoolBackprop(_,v,Pe)},B={dy:_,input:v},U={filterSize:n,strides:a,pad:c},J=Ie.runKernelFunc(D,B,null,Fi,U);return C?Ke(J,[J.shape[1],J.shape[2],J.shape[3]]):J}var _v=Ee({avgPoolBackprop_:xv}),wv={kernelName:Gi,inputsToSave:["x"],gradFunc:function(t,e,n){var a=e[0],c=n,d=c.filterSize,y=c.strides,v=c.pad;return{x:function(){return _v(t,a,d,y,v)}}}},bv={kernelName:da,inputsToSave:["a","b"],gradFunc:function(t,e,n){var a=e[0],c=e[1],d=n,y=d.transposeA,v=d.transposeB;return!y&&!v?{a:function(){return un(t,c,!1,!0)},b:function(){return un(a,t,!0,!1)}}:!y&&v?{a:function(){return un(t,c,!1,!1)},b:function(){return un(t,a,!0,!1)}}:y&&!v?{a:function(){return un(c,t,!1,!0)},b:function(){return un(a,t,!1,!1)}}:{a:function(){return un(c,t,!0,!0)},b:function(){return un(t,a,!0,!0)}}}},kv={kernelName:Mi,gradFunc:function(t,e,n){var a=n,c=a.blockShape,d=a.crops;return{x:function(){return Mh(t,c,d)}}}},Sv={kernelName:pe,gradFunc:function(t,e,n){for(var a=n,c=a.inputShape,d=a.shape,y=Array.from(d),v=c.length-1;v>=0;v--)if(c[v]===d[v])y[v]=1;else if(c[v]!==1)throw new Error("broadcastTo(): ["+c+"] cannot be broadcast to ["+d+"].");for(var _=[],v=0;v1&&_.push(v);return{x:function(){return Yr(t,_,!0)}}}},Iv={kernelName:X,gradFunc:function(t){return{x:function(){return t.clone()}}}},Nv={kernelName:j,gradFunc:function(t){return{x:function(){return gn(t)}}}},Cv={kernelName:re,inputsToSave:["x"],gradFunc:function(t,e,n){var a=e[0],c=n,d=c.clipValueMin,y=c.clipValueMax;return{x:function(){return us(nc($u(a,d),ec(a,y)),t,gn(t))}}}},Tv={kernelName:Ue,saveAllInputs:!0,gradFunc:function(t,e,n){var a=e.map(function(_){return _.shape}),c=n.axis,d=qt(c,e[0].shape)[0],y=a.map(function(_){return _[d]}),v=ll(t,y,d);return v.map(function(_){return function(){return _}})}},Ev={kernelName:kt,inputsToSave:["x","filter"],gradFunc:function(t,e,n){var a=e,c=a[0],d=a[1],y=n,v=y.dilations,_=y.strides,C=y.pad,D=y.dataFormat;return W(st(v),function(){return"Error in gradient of conv2D: dilation rates greater than 1 "+("are not yet supported in gradients. Got dilations '"+v+"'")}),{x:function(){return Ti(c.shape,t,d,_,C,D)},filter:function(){return Tp(c,t,d.shape,_,C,D)}}}},Rv={kernelName:Le,inputsToSave:["dy","filter"],gradFunc:function(t,e,n){var a=e,c=a[0],d=a[1],y=n,v=y.strides,_=y.pad,C=y.dataFormat,D=y.dimRoundingMode;return{dy:function(){return gi(t,d,v,_,C,1,D)},filter:function(){return Tp(t,c,d.shape,v,_,C,D)}}}};function Av(t,e,n,a,c){var d=t;t.rank===4&&(d=Ke(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]));var y=e;y.rank===4&&(y=Ke(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]])),W(d.rank===5,function(){return"Error in conv3dDerFilter: input must be rank 5, but got shape "+(d.shape+".")}),W(y.rank===5,function(){return"Error in conv3dDerFilter: dy must be rank 5, but got shape "+(y.shape+".")}),W(n.length===5,function(){return"Error in conv3dDerFilter: filterShape must be length 5, but got "+(n+".")}),W(d.shape[4]===n[3],function(){return"Error in conv3dDerFilter: depth of input "+d.shape[4]+") must "+("match input depth in filter ("+n[3]+".")}),W(y.shape[4]===n[4],function(){return"Error in conv3dDerFilter: depth of dy ("+y.shape[4]+") must "+("match output depth for filter ("+n[4]+").")});var v=function(D){var B=1,U=M(d.shape,n,a,B,c);return D.conv3dDerFilter(d,y,U)},_={x:d,dy:y},C={strides:a,pad:c,filterShape:n};return Ie.runKernelFunc(v,_,null,Ft,C)}var Dv=Ee({conv3DBackpropFilter_:Av}),Fv={kernelName:Ye,inputsToSave:["x","filter"],gradFunc:function(t,e,n){var a=n,c=a.dilations,d=a.strides,y=a.pad;W(st(c),function(){return"Error in gradient of conv3D: dilation rates greater than 1 are "+("not yet supported in gradients. Got dilations '"+c+"'")});var v=e[0],_=e[1];return{x:function(){return Sh(v.shape,t,_,d,y)},filter:function(){return Dv(v,t,_.shape,d,y)}}}},Ov={kernelName:Mt,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return bt($a(kp(pr(n,"float32"))),t)}}}},Mv={kernelName:dr,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return bt(Sp(pr(n,"float32")),t)}}}},Lv={kernelName:ir,inputsToSave:["x"],gradFunc:function(t,e,n){var a=e[0],c=n,d=c.axis,y=c.exclusive,v=c.reverse;return{x:function(){var _=Ji([d],a.rank),C=op(t,d,y,!v);return _!=null&&(C=$n(C,_)),C}}}},zv={kernelName:ra,inputsToSave:["x","filter"],gradFunc:function(t,e,n){var a=n,c=a.dilations,d=a.strides,y=a.pad,v=a.dimRoundingMode,_=c??[1,1];W(st(_),function(){return"Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations "+("'"+_+"'")});var C=e,D=C[0],B=C[1];return W(D.rank===4,function(){return"Error in gradient of depthwiseConv2dNative: input must be "+("rank 4, but got rank "+D.rank+".")}),W(B.rank===4,function(){return"Error in gradient of depthwiseConv2dNative: filter must be "+("rank 4, but got rank "+B.rank+".")}),W(D.shape[3]===B.shape[2],function(){return"Error in gradient of depthwiseConv2d: number of input "+("channels ("+D.shape[3]+") must match the inChannels dimension ")+("in filter "+B.shape[2]+".")}),W(dt(d,_),function(){return"Error in gradient of depthwiseConv2d: Either strides or "+("dilations must be 1. Got strides "+d+" and dilations ")+("'"+_+"'.")}),v!=null&&W(xt(y),function(){return"Error in depthwiseConv2d: pad must be an integer when using, "+("dimRoundingMode "+v+" but got pad "+y+".")}),{x:function(){return jd(D.shape,t,B,d,y,c,v)},filter:function(){return Gd(D,t,B.shape,d,y,c,v)}}}},Pv={kernelName:hn,inputsToSave:["x","filter"],gradFunc:function(t,e,n){var a=e,c=a[0],d=a[1],y={x:c,filter:d,dy:t},v={x:c,filter:d,dy:t};return{x:function(){return Ie.runKernel(na,y,n)},filter:function(){return Ie.runKernel(Jr,v,n)}}}},Bv={kernelName:Vr,inputsToSave:["a","b"],gradFunc:function(t,e){var n=e[0],a=e[1],c=ca(n.shape,a.shape),d=function(){var v=Br(t,pr(a,"float32")),_=Ja(n.shape,c);return _.length>0?Ke(Yr(v,_),n.shape):v},y=function(){var v=bt(t,pr(n,"float32")),_=Ja(a.shape,c);_.length>0&&(v=Ke(Yr(v,_),a.shape));var C=Yn(a);return $a(Br(v,pr(C,"float32")))};return{a:d,b:y}}},Wv={kernelName:Jn,outputsToSave:[!0],gradFunc:function(t,e){var n=e[0],a=function(d){return d.eluDer(t,n)},c={dy:t,y:n};return{x:function(){return Ie.runKernelFunc(a,c,null,tn)}}}},Uv={kernelName:Rn,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0],a=bt(cs($a(Yn(n))),2/Math.sqrt(Math.PI));return{x:function(){return bt(t,a)}}}},Vv={kernelName:aa,outputsToSave:[!0],gradFunc:function(t,e){var n=e[0];return{x:function(){return bt(t,n)}}}},Hv={kernelName:ma,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return bt(t,cs(n))}}}},Gv={kernelName:x,gradFunc:function(t){return{x:function(){return gn(t)}}}},jv={kernelName:k,inputsToSave:["a","b"],gradFunc:function(t,e){var n=e[0],a=e[1],c=ca(n.shape,a.shape),d=function(){var v=Br(t,pr(a,"float32")),_=Ja(n.shape,c);return _.length>0?Ke(Yr(v,_),n.shape):v},y=function(){var v=bt(t,pr(n,"float32")),_=Ja(a.shape,c);_.length>0&&(v=Ke(Yr(v,_),a.shape));var C=Yn(a);return $a(Br(v,pr(C,"float32")))};return{a:d,b:y}}},qv={kernelName:K,inputsToSave:["x","mean","variance","scale"],gradFunc:function(t,e,n){var a=n.varianceEpsilon,c=e[0],d=e[1],y=e[2],v=e[3],_=v??Wr(1),C=Ja(d.shape,c.shape),D=[];if(d.rank===1){for(var B=0;B0?Ke(Yr(t,v),n.shape):t},y=function(){var v=bt(t,$a(Nh(Br(n,a)))),_=Ja(a.shape,c);return _.length>0?Ke(Yr(v,_),a.shape):v};return{a:d,b:y}}},y5={kernelName:qr,inputsToSave:["a","b"],gradFunc:function(t,e){var n=e[0],a=e[1],c=ca(n.shape,a.shape),d=function(){var v=bt(t,pr(a,"float32")),_=Ja(n.shape,c);return _.length>0?Ke(Yr(v,_),n.shape):v},y=function(){var v=bt(t,pr(n,"float32")),_=Ja(a.shape,c);return _.length>0?Ke(Yr(v,_),a.shape):v};return{a:d,b:y}}},v5={kernelName:Io,gradFunc:function(t){return{x:function(){return $a(t)}}}},g5={kernelName:Pi,inputsToSave:["indices"],gradFunc:function(t,e){var n=e[0];return{indices:function(){return Ys(n.shape,"float32")}}}},x5={kernelName:oi,gradFunc:function(t){return{x:function(){return gn(t)}}}},uf={kernelName:no,inputsToSave:["x"],gradFunc:function(t,e,n){var a=e[0],c=n.paddings,d=c.map(function(y){return y[0]});return{x:function(){return $t(t,d,a.shape)}}}},_5={kernelName:Ka,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:function(t,e){var n=e[0],a=e[1],c=e[2],d=n,y=a,v=ca(d.shape,y.shape),_=function(){var D=pr(y,"float32"),B=bt(t,bt(D,Qs(d,zr(D,Wr(1))))),U=Ja(d.shape,v);return U.length>0&&(B=Yr(B,U)),Ke(B,d.shape)},C=function(){var D=_u(d,0),B=us(D,tc(d),gn(d)),U=bt(t,bt(c,B)),J=Ja(y.shape,v);return J.length>0&&(U=Yr(U,J)),Ke(U,y.shape)};return{a:_,b:C}}},w5={kernelName:ao,inputsToSave:["x","alpha"],gradFunc:function(t,e){var n=e[0],a=e[1],c=_u(n,0);return{x:function(){return us(c,t,bt(t,a))},alpha:function(){var d=us(c,gn(t),bt(t,n)),y=Ja(a.shape,t.shape);return y.length>0&&(d=Yr(d,y)),Ke(d,a.shape)}}}},b5={kernelName:io,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return Br(t,$a(Yn(n)))}}}},k5={kernelName:ka,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0],a=bt(ec(n,6),hl(n));return{x:function(){return bt(t,pr(a,"float32"))}}}},S5={kernelName:ia,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return bt(t,pr(hl(n),"float32"))}}}},I5={kernelName:Pr,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return Ke(t,n.shape)}}}},N5={kernelName:Qn,inputsToSave:["images"],gradFunc:function(t,e,n){var a=e[0],c=function(v){var _=n.alignCorners;return v.resizeBilinearBackprop(t,a,_)},d={images:a},y=function(){return Ie.runKernelFunc(c,d,null,oo,n)};return{images:y}}},C5={kernelName:oa,inputsToSave:["images"],gradFunc:function(t,e,n){var a=e[0],c=function(v){var _=n.alignCorners;return v.resizeNearestNeighborBackprop(t,a,_)},d={images:a},y=function(){return Ie.runKernelFunc(c,d,null,Xa,n)};return{images:y}}},T5={kernelName:vn,gradFunc:function(t,e,n){var a=n.dims,c=qt(a,t.shape);return{x:function(){return Zs(t,c)}}}},E5={kernelName:Bi,gradFunc:function(t){return{x:function(){return gn(t)}}}},R5={kernelName:yo,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return $a(Br(t,bt(Qs(n,1.5),2)))}}}},A5={kernelName:Aa,inputsToSave:["condition"],gradFunc:function(t,e){var n=e[0];return{condition:function(){return pr(gn(n),"float32")},t:function(){return bt(t,pr(n,t.dtype))},e:function(){return bt(t,pr(Ah(n),t.dtype))}}}},D5={kernelName:go,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){var a=_u(n,Wr(0)),c=Wr(tf),d=Wr(rf),y=bt(t,d),v=bt(bt(t,c),cs(pr(n,"float32")));return us(a,y,v)}}}},F5={kernelName:Ds,outputsToSave:[!0],gradFunc:function(t,e){var n=e[0];return{x:function(){return bt(t,bt(n,zr(Wr(1),n)))}}}},O5={kernelName:As,gradFunc:function(t){return{x:function(){return gn(t)}}}},M5={kernelName:Rs,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return bt(Ih(pr(n,"float32")),t)}}}},L5={kernelName:Eo,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return bt(ip(pr(n,"float32")),t)}}}},z5={kernelName:To,inputsToSave:["x"],gradFunc:function(t,e,n){for(var a=e[0],c=n,d=c.begin,y=c.size,v=a.shape,_=Hu(a,d,y),C=_[0],D=_[1],B=[],U=0;U0&&(v=Yr(v,_)),Ke(v,n.shape)},y=function(){var v=t,_=Ja(a.shape,c);return _.length>0&&(v=Yr(v,_)),Ke($a(v),a.shape)};return{a:d,b:y}}},j5={kernelName:Yo,inputsToSave:["x"],gradFunc:function(t,e,n){var a=e[0],c=a.shape.slice(),d=n.axis,y=qt(d,a.shape);y.forEach(function(C){c[C]=1});var v=Ke(t,c),_=bt(v,sl(a.shape,"float32"));return{x:function(){return _}}}},q5={kernelName:ds,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return Br(t,Yn(Ih(n)))}}}},K5={kernelName:Ms,outputsToSave:[!0],gradFunc:function(t,e){var n=e[0];return{x:function(){return bt(zr(Wr(1),Yn(n)),t)}}}},X5={kernelName:Ls,inputsToSave:["x"],gradFunc:function(t,e,n){var a=e[0],c=n.reps,d=function(){var y=gn(a);if(a.rank===1)for(var v=0;v{"use strict";Object.defineProperty(N,"__esModule",{value:!0});var i=ml(),ke=function(s,u){return ke=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,o){r.__proto__=o}||function(r,o){for(var h in o)o.hasOwnProperty(h)&&(r[h]=o[h])},ke(s,u)};function O(s,u){ke(s,u);function r(){this.constructor=s}s.prototype=u===null?Object.create(u):(r.prototype=u.prototype,new r)}var H=function(){return H=Object.assign||function(s){for(var u,r=1,o=arguments.length;r0&&b[b.length-1])&&(Y[0]===6||Y[0]===2)){r=0;continue}if(Y[0]===3&&(!b||Y[1]>b[0]&&Y[1]u?1:0}function ar(s,u){return-1*Zt(s,u)}function qt(s){if(s==null)return s;for(var u=[],r=0,o=s;r=0),tt(o>=r),Array.isArray(s)&&s.length>=r&&s.length<=o&&s.every(function(h){return typeof h===u})}function tr(s,u){Array.isArray(s)?(i.util.assert(s.length>0,function(){return u+" is unexpectedly an empty array."}),s.forEach(function(r,o){return tr(r,"element "+(o+1)+" of "+u)})):i.util.assert(Number.isInteger(s)&&s>0,function(){return"Expected "+u+" to be a positive integer, but got "+(Fa(s)+".")})}function Fa(s){return s===null?"null":Array.isArray(s)?"["+s.map(function(u){return Fa(u)}).join(",")+"]":typeof s=="string"?'"'+s+'"':""+s}function Oa(s,u){var r=i.util.now(),o,h=function(){for(var b=[],T=0;T0){var r=s+"_"+u;return Ta.set(r,1),r}else return s}var qn=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function ri(s){return!!s.match(qn)}function pi(s){return s===parseInt(s.toString(),10)}function pa(s,u,r){u==null&&(u=0),r==null&&(r=s.length);for(var o=1,h=u;h= 2"+(" but got x shape = "+s.shape+" and y shape = "+u.shape));if(u.rank>=3){var h=s.shape.slice(-1)[0],b=u.shape.slice(-2)[0];if(h!==b)throw new ge("If rank y >= 3, then the second last dim"+(" of y must equal the last dim of x but got x shape = "+s.shape+" and ")+(" y shape = "+u.shape))}if(s.rank===2&&u.rank===2){var T=!1,M=!1;return i.fused.matMul({a:s,b:u,transposeA:T,transposeB:M,bias:o?re(s.rank,o,he()):null,activation:r})}else{var q=s.shape.slice(),Y=q.pop();s=s.reshape([-1,Y]);var le=u.shape.slice(),Ne=le.pop(),b=le.pop(),We=le.concat([Ne]),je=Array.from({length:u.rank},function(dt,Dt){return Dt===0?u.rank-2:Dt<=u.rank-2?Dt-1:Dt});u=u.transpose(je).reshape([b,-1]);var qe=q.concat(We),T=!1,M=!1;return i.fused.matMul({a:s,b:u,transposeA:T,transposeB:M,bias:o?re(s.rank,o,he()):null,activation:r}).reshape(qe)}}function X(s,u,r){return i.tidy(function(){return Array.isArray(u)?u=i.tensor1d(u,"int32"):u=u.toInt(),i.gather(s,u,r)})}function j(s){return i.mul(s,s)}function re(s,u,r){var o=u.shape;if(u.rank!==1&&u.rank!==s)throw new w("Unexpected bias dimensions: "+u.rank+("; expected it to be 1 or "+s));if(s===5){if(r==="channelsFirst")return o.length===1?u.reshape([1,o[0],1,1,1]):u.reshape([1,o[3],o[0],o[1],o[2]]);if(r==="channelsLast")return o.length===1?u.reshape([1,1,1,1,o[0]]):u.reshape([1].concat(o))}else if(s===4){if(r==="channelsFirst")return o.length===1?u.reshape([1,o[0],1,1]):u.reshape([1,o[2],o[0],o[1]]);if(r==="channelsLast")return o.length===1?u.reshape([1,1,1,o[0]]):u.reshape([1].concat(o))}else if(s===3){if(r==="channelsFirst")return o.length===1?u.reshape([1,o[0],1]):u.reshape([1,o[1],o[0]]);if(r==="channelsLast")return o.length===1?u.reshape([1,1,o[0]]):u.reshape([1].concat(o))}else if(s<3)return u;throw new w("Unsupported input rank by biasAdd: "+u.rank)}function te(s,u,r){return i.tidy(function(){return r==null&&(r=he()),on(r),s.add(re(s.rank,u,r))})}function Ue(s,u){if(u===void 0&&(u=1),u!==1)throw new ge("Support for alpha values other than 1 ("+u+") is not implemented yet.");return i.elu(s)}function kt(s){return i.tidy(function(){return i.div(s,i.abs(s).add(1))})}function $e(s,u,r,o){return i.tidy(function(){return i.dropout(s,u,r,o)})}function Le(s){return i.tidy(function(){var u=i.add(.5,i.mul(.2,s));return i.clipByValue(u,0,1)})}function Ye(s,u,r){return r===void 0&&(r=!1),r?s():u()}var Ft=["fanIn","fanOut","fanAvg"],St=["normal","uniform","truncatedNormal"];function Mt(s){jr(Ft,"FanMode",s)}function dr(s){jr(St,"Distribution",s)}var ir=function(s){O(u,s);function u(){return s!==null&&s.apply(this,arguments)||this}return u.prototype.fromConfigUsesCustomObjects=function(){return!1},u.prototype.getConfig=function(){return{}},u}(i.serialization.Serializable),ta=function(s){O(u,s);function u(){return s!==null&&s.apply(this,arguments)||this}return u.prototype.apply=function(r,o){return i.zeros(r,o)},u.className="Zeros",u}(ir);i.serialization.registerClass(ta);var fa=function(s){O(u,s);function u(){return s!==null&&s.apply(this,arguments)||this}return u.prototype.apply=function(r,o){return i.ones(r,o)},u.className="Ones",u}(ir);i.serialization.registerClass(fa);var ra=function(s){O(u,s);function u(r){var o=s.call(this)||this;if(typeof r!="object")throw new w("Expected argument of type ConstantConfig but got "+r);if(r.value===void 0)throw new w("config must have value set but got "+r);return o.value=r.value,o}return u.prototype.apply=function(r,o){var h=this;return i.tidy(function(){return i.mul(i.scalar(h.value),i.ones(r,o))})},u.prototype.getConfig=function(){return{value:this.value}},u.className="Constant",u}(ir);i.serialization.registerClass(ra);var Ha=function(s){O(u,s);function u(r){var o=s.call(this)||this;return o.DEFAULT_MINVAL=-.05,o.DEFAULT_MAXVAL=.05,o.minval=r.minval||o.DEFAULT_MINVAL,o.maxval=r.maxval||o.DEFAULT_MAXVAL,o.seed=r.seed,o}return u.prototype.apply=function(r,o){return i.randomUniform(r,this.minval,this.maxval,o)},u.prototype.getConfig=function(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}},u.className="RandomUniform",u}(ir);i.serialization.registerClass(Ha);var ki=function(s){O(u,s);function u(r){var o=s.call(this)||this;return o.DEFAULT_MEAN=0,o.DEFAULT_STDDEV=.05,o.mean=r.mean||o.DEFAULT_MEAN,o.stddev=r.stddev||o.DEFAULT_STDDEV,o.seed=r.seed,o}return u.prototype.apply=function(r,o){if(o=o||"float32",o!=="float32"&&o!=="int32")throw new ge("randomNormal does not support dType "+o+".");return Mi(r,this.mean,this.stddev,o,this.seed)},u.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}},u.className="RandomNormal",u}(ir);i.serialization.registerClass(ki);var sn=function(s){O(u,s);function u(r){var o=s.call(this)||this;return o.DEFAULT_MEAN=0,o.DEFAULT_STDDEV=.05,o.mean=r.mean||o.DEFAULT_MEAN,o.stddev=r.stddev||o.DEFAULT_STDDEV,o.seed=r.seed,o}return u.prototype.apply=function(r,o){if(o=o||"float32",o!=="float32"&&o!=="int32")throw new ge("truncatedNormal does not support dType "+o+".");return i.truncatedNormal(r,this.mean,this.stddev,o,this.seed)},u.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}},u.className="TruncatedNormal",u}(ir);i.serialization.registerClass(sn);var hn=function(s){O(u,s);function u(r){var o=s.call(this)||this;return o.gain=r.gain!=null?r.gain:1,o}return u.prototype.apply=function(r,o){var h=this;return i.tidy(function(){if(r.length!==2||r[0]!==r[1])throw new w("Identity matrix initializer can only be used for 2D square matrices.");return i.mul(h.gain,i.eye(r[0]))})},u.prototype.getConfig=function(){return{gain:this.gain}},u.className="Identity",u}(ir);i.serialization.registerClass(hn);function na(s,u){u===void 0&&(u="channelsLast");var r,o;if(on(u),s.length===2)r=s[0],o=s[1];else if([3,4,5].indexOf(s.length)!==-1){if(u==="channelsFirst"){var h=pa(s,2);r=s[1]*h,o=s[0]*h}else if(u==="channelsLast"){var h=pa(s,0,s.length-2);r=s[s.length-2]*h,o=s[s.length-1]*h}}else{var b=pa(s);r=Math.sqrt(b),o=Math.sqrt(b)}return[r,o]}var Jr=function(s){O(u,s);function u(r){var o=s.call(this)||this;if(r.scale<0)throw new w("scale must be a positive float. Got: "+r.scale);return o.scale=r.scale==null?1:r.scale,o.mode=r.mode==null?"fanIn":r.mode,Mt(o.mode),o.distribution=r.distribution==null?"normal":r.distribution,dr(o.distribution),o.seed=r.seed,o}return u.prototype.apply=function(r,o){var h=na(r),b=h[0],T=h[1],M=this.scale;if(this.mode==="fanIn"?M/=Math.max(1,b):this.mode==="fanOut"?M/=Math.max(1,T):M/=Math.max(1,(b+T)/2),this.distribution==="normal"){var q=Math.sqrt(M);if(o=o||"float32",o!=="float32"&&o!=="int32")throw new ge(this.getClassName()+" does not support dType "+o+".");return i.truncatedNormal(r,0,q,o,this.seed)}else{var Y=Math.sqrt(3*M);return i.randomUniform(r,-Y,Y,o)}},u.prototype.getConfig=function(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}},u.className="VarianceScaling",u}(ir);i.serialization.registerClass(Jr);var Vr=function(s){O(u,s);function u(r){return s.call(this,{scale:1,mode:"fanAvg",distribution:"uniform",seed:r==null?null:r.seed})||this}return u.prototype.getClassName=function(){return Jr.className},u.className="GlorotUniform",u}(Jr);i.serialization.registerClass(Vr);var Jn=function(s){O(u,s);function u(r){return s.call(this,{scale:1,mode:"fanAvg",distribution:"normal",seed:r==null?null:r.seed})||this}return u.prototype.getClassName=function(){return Jr.className},u.className="GlorotNormal",u}(Jr);i.serialization.registerClass(Jn);var tn=function(s){O(u,s);function u(r){return s.call(this,{scale:2,mode:"fanIn",distribution:"normal",seed:r==null?null:r.seed})||this}return u.prototype.getClassName=function(){return Jr.className},u.className="HeNormal",u}(Jr);i.serialization.registerClass(tn);var Rn=function(s){O(u,s);function u(r){return s.call(this,{scale:2,mode:"fanIn",distribution:"uniform",seed:r==null?null:r.seed})||this}return u.prototype.getClassName=function(){return Jr.className},u.className="HeUniform",u}(Jr);i.serialization.registerClass(Rn);var Kn=function(s){O(u,s);function u(r){return s.call(this,{scale:1,mode:"fanIn",distribution:"normal",seed:r==null?null:r.seed})||this}return u.prototype.getClassName=function(){return Jr.className},u.className="LeCunNormal",u}(Jr);i.serialization.registerClass(Kn);var aa=function(s){O(u,s);function u(r){return s.call(this,{scale:1,mode:"fanIn",distribution:"uniform",seed:r==null?null:r.seed})||this}return u.prototype.getClassName=function(){return Jr.className},u.className="LeCunNormal",u}(Jr);i.serialization.registerClass(aa);var ma=function(s){O(u,s);function u(r){var o=s.call(this)||this;if(o.DEFAULT_GAIN=1,o.gain=r.gain==null?o.DEFAULT_GAIN:r.gain,o.seed=r.seed,o.seed!=null)throw new ge("Random seed is not implemented for Orthogonal Initializer yet.");return o}return u.prototype.apply=function(r,o){var h=this;return i.tidy(function(){if(r.length<2)throw new ge("Shape must be at least 2D.");r[0]*r[1]>2e3&&console.warn("Orthogonal initializer is being called on a matrix with more "+("than 2000 ("+r[0]*r[1]+") elements: ")+"Slowness may result.");var b=r[0]>r[1]?[r[1],r[0]]:r,T=Mi(b,0,1,"float32"),M=i.linalg.gramSchmidt(T);return r[0]>r[1]&&(M=M.transpose()),i.mul(h.gain,M)})},u.prototype.getConfig=function(){return{gain:this.gain,seed:this.seed}},u.className="Orthogonal",u}(ir);i.serialization.registerClass(ma);var Li={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",heUniform:"HeUniform",identity:"Identity",leCunNormal:"LeCunNormal",leCunUniform:"LeCunUniform",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"};function Ea(s,u){return u===void 0&&(u={}),yt(s,i.serialization.SerializationMap.getMap().classNameMap,u,"initializer")}function S(s){return ht(s)}function x(s){if(typeof s=="string"){var u=s in Li?Li[s]:s;if(u==="GlorotNormal")return new Jn;if(u==="GlorotUniform")return new Vr;if(u==="HeNormal")return new tn;if(u==="HeUniform")return new Rn;if(u==="LeCunNormal")return new Kn;if(u==="LeCunUniform")return new aa;var r={};return r.className=u,r.config={},Ea(r)}else return s instanceof ir?s:Ea(s)}function k(){return new ta}function K(){return new fa}function Se(s){return new ra(s)}function we(s){return new Ha(s)}function Je(s){return new ki(s)}function Be(s){return new sn(s)}function vt(s){return new hn(s)}function ft(s){return new Jr(s)}function zt(s){return new Vr(s)}function Wt(s){return new Jn(s)}function Gt(s){return new tn(s)}function Qt(s){return new Rn(s)}function wr(s){return new Kn(s)}function Ar(s){return new aa(s)}function Yt(s){return new ma(s)}var xr={__proto__:null,zeros:k,ones:K,constant:Se,randomUniform:we,randomNormal:Je,truncatedNormal:Be,identity:vt,varianceScaling:ft,glorotUniform:zt,glorotNormal:Wt,heNormal:Gt,heUniform:Qt,leCunNormal:wr,leCunUniform:Ar,orthogonal:Yt},Sn=0;function pn(){return Sn++}var zn={};function Fr(s){return s===void 0&&(s=""),s in zn||(zn[s]=0),zn[s]+=1,s+zn[s].toString()}function wa(s){return Array.isArray(s)&&Array.isArray(s[0])}function In(s){return s.length===0?[]:Array.isArray(s[0])?s:[s]}function ur(s){var u;if(Array.isArray(s)){if(s.length!==1)throw new w("Expected Tensor length to be 1; got "+s.length);u=s[0]}else u=s;return u}function $r(s){if(Array.isArray(s)&&Array.isArray(s[0])){if(s.length===1)return s=s,s[0];throw new w("Expected exactly 1 Shape; got "+s.length)}else return s}function Ra(s){for(var u=0,r=0,o=s;r1)throw new me("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use `getInputAt(nodeIndex)` instead.');if(this.inboundNodes.length===0)throw new me("Layer "+this.name+" is not connected, no input to return.");return Tt(this.getNodeAtIndex(0,"input").inputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(u.prototype,"output",{get:function(){if(this.inboundNodes.length===0)throw new me("Layer "+this.name+" has no inbound nodes.");if(this.inboundNodes.length>1)throw new me("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use `getOutputAt(nodeIndex)` instead.');return Tt(this.getNodeAtIndex(0,"output").outputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(u.prototype,"losses",{get:function(){return this._losses},enumerable:!0,configurable:!0}),u.prototype.calculateLosses=function(){return this.losses.map(function(r){return r()})},Object.defineProperty(u.prototype,"updates",{get:function(){return this._updates},enumerable:!0,configurable:!0}),Object.defineProperty(u.prototype,"built",{get:function(){return this._built},set:function(r){this._built=r},enumerable:!0,configurable:!0}),Object.defineProperty(u.prototype,"trainable",{get:function(){return this.trainable_},set:function(r){this._trainableWeights.forEach(function(o){return o.trainable=r}),this.trainable_=r},enumerable:!0,configurable:!0}),Object.defineProperty(u.prototype,"trainableWeights",{get:function(){return this.trainable_?this._trainableWeights.filter(function(r){return r.trainable}):[]},set:function(r){this._trainableWeights=r},enumerable:!0,configurable:!0}),Object.defineProperty(u.prototype,"nonTrainableWeights",{get:function(){return this.trainable?this._trainableWeights.filter(function(r){return!r.trainable}).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)},set:function(r){this._nonTrainableWeights=r},enumerable:!0,configurable:!0}),Object.defineProperty(u.prototype,"weights",{get:function(){return this.trainableWeights.concat(this.nonTrainableWeights)},enumerable:!0,configurable:!0}),Object.defineProperty(u.prototype,"stateful",{get:function(){return this._stateful},enumerable:!0,configurable:!0}),u.prototype.resetStates=function(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")},u.prototype.assertInputCompatibility=function(r){if(r=Qe(r),this.inputSpec==null||this.inputSpec.length===0)return;var o=Qe(this.inputSpec);if(r.length!==o.length)throw new w("Layer "+this.name+" expects "+o.length+" inputs, "+("but it received "+r.length+" input tensors. ")+("Input received: "+r));for(var h=0;h=0?q[le]:q[q.length+le];if(Ne!=null&&[Ne,null].indexOf(We)===-1)throw new w("Input "+h+" is incompatible with layer "+(this.name+": expected axis "+le+" of input shape to ")+("have value "+Ne+" but got shape "+q+"."))}}if(T.shape!=null)for(var je=0;je0&&Array.isArray(lr[0])?st=lr.map(function(kr,Sr){return new ba(Ir,kr,h,Qe(r),o,h.name,Sr)}):st=new ba(Ir,lr,h,Qe(r),o,h.name),h.addInboundNode(r,st,null,null,vr,lr,o),h._refCount++,h.activityRegularizer!=null)throw new ge("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return st}})},u.prototype.warnOnIncompatibleInputShape=function(r){if(this.batchInputShape==null)return;if(r.length!==this.batchInputShape.length)console.warn("The rank of the input tensor provided (shape: "+(JSON.stringify(r)+") does not match that of the ")+("batchInputShape ("+JSON.stringify(this.batchInputShape)+") ")+("of the layer "+this.name));else{var o=!1;this.batchInputShape.forEach(function(h,b){h!=null&&r[b]!=null&&r[b]!==h&&(o=!0)}),o&&console.warn("The shape of the input tensor "+("("+JSON.stringify(r)+") does not ")+("match the expectation of layer "+this.name+": ")+(""+JSON.stringify(this.batchInputShape)))}},Object.defineProperty(u.prototype,"outputShape",{get:function(){if(this.inboundNodes==null||this.inboundNodes.length===0)throw new me("The layer "+this.name+" has never been called and thus has no defined output shape.");for(var r=[],o=0,h=this.inboundNodes;o0)&&(u=s.sourceLayer,r=s.nodeIndex),u.inboundNodes.length===0)return[s];var o=u.inboundNodes[r];if(o.inboundLayers.length===0)return o.inputTensors;for(var h=[],b=0;b0?[4,Promise.all(u)]:[3,2];case 1:for(M=Y.sent(),q=0;q=0&&Number.isInteger(u),function(){return"Verbosity level is expected to be an integer >= 0, "+("but got "+u)}),s.checkForDuplicate(r),s.constructors[u]==null&&(s.constructors[u]=[]),s.constructors[u].push(r)},s.checkForDuplicate=function(u){for(var r in s.constructors){var o=s.constructors[+r];o.forEach(function(h){if(h===u)throw new w("Duplicate callback constructor.")})}},s.clear=function(){s.constructors={}},s.createCallbacks=function(u){var r=[];for(var o in s.constructors){var h=+o;u>=h&&r.push.apply(r,s.constructors[h])}return r.map(function(b){return new b})},s.constructors={},s}();function Pr(s,u,r,o,h,b,T,M,q){var Y=new No,le=[new Ko].concat(ia.createCallbacks(u));s!=null&&le.push.apply(le,s),le.push(Y);var Ne=new ao(le);return Ne.setParams({epochs:r,initialEpoch:o,samples:h,steps:b,batchSize:T,verbose:u,doValidation:M,metrics:q}),{callbackList:Ne,history:Y}}function oa(s,u,r){return u===void 0&&(u={}),r===void 0&&(r=!1),yt(s,i.serialization.SerializationMap.getMap().classNameMap,u,"layer",r)}function Xa(s,u){return i.tidy(function(){s.dtype!=="float32"&&(s=s.asType("float32"));var r=i.sum(j(s),u,!0),o=i.fill(r.shape,P()),h=i.sqrt(i.maximum(r,o));return i.div(s,h)})}function Qn(s,u){return i.tidy(function(){return i.mean(j(i.sub(u,s)),-1)})}function oo(s,u){return i.tidy(function(){return i.mean(i.abs(i.sub(u,s)),-1)})}function ka(s,u){return i.tidy(function(){var r=i.sub(s,u),o=i.clipByValue(i.abs(s),P(),Number.MAX_VALUE),h=i.abs(i.div(r,o));return i.mul(100,i.mean(h,-1))})}function vn(s,u){return i.tidy(function(){var r=i.clipByValue(u,P(),Number.MAX_VALUE),o=i.log(i.add(1,r)),h=i.clipByValue(s,P(),Number.MAX_VALUE),b=i.log(i.add(1,h));return i.mean(j(i.sub(o,b)),-1)})}function Bi(s,u){return i.tidy(function(){var r=i.maximum(0,i.sub(1,i.mul(s,u)));return i.mean(j(r),-1)})}function yo(s,u){return i.tidy(function(){var r=i.maximum(0,i.sub(1,i.mul(s,u)));return i.mean(r,-1)})}function vo(s,u){return i.tidy(function(){var r=i.sum(i.mul(s,u),-1),o=i.max(i.mul(i.sub(1,s),u),-1);return i.maximum(0,i.add(1,i.sub(o,r)))})}function Aa(s,u){return i.tidy(function(){var r=Math.log(2),o=i.sub(u,s),h=i.sub(i.add(o,i.softplus(i.mul(-2,o))),r);return i.mean(h,-1)})}function go(s,u,r){return r===void 0&&(r=!1),i.tidy(function(){if(r)u=i.softmax(u);else{var o=i.sum(u,u.shape.length-1,!0);u=i.div(u,o)}return u=i.clipByValue(u,P(),1-P()),i.neg(i.sum(i.mul(s.toFloat(),i.log(u)),u.shape.length-1))})}function To(s,u,r){return r===void 0&&(r=!1),i.tidy(function(){var o=i.floor(bi(s)).toInt();u=i.clipByValue(u,P(),1-P());var h=u.shape,b=i.oneHot(o,h[h.length-1]).reshape(h);return go(b,u,r)})}function Rs(s,u){if(!i.util.arraysEqual(s.shape,u.shape))throw new w("logits and labels must have the same shape, but got shapes "+(JSON.stringify(s.shape)+" and "+JSON.stringify(u.shape)));return i.tidy(function(){var r=u.relu(),o=u.abs().neg();return r.sub(u.mul(s)).add(o.exp().log1p())})}function Eo(s,u){return i.tidy(function(){var r;return r=i.clipByValue(u,P(),1-P()),r=i.log(i.div(r,i.sub(1,r))),i.mean(Rs(s,r),-1)})}function As(s,u){return i.tidy(function(){var r=i.clipByValue(s,P(),1),o=i.clipByValue(u,P(),1);return i.sum(i.mul(s,i.log(i.div(r,o))),-1)})}function Ds(s,u){return i.tidy(function(){var r=i.log(i.add(P(),u));return i.mean(i.sub(u,i.mul(s,r)),-1)})}function Xo(s,u){return i.tidy(function(){var r=Xa(s,-1),o=Xa(u,-1),h=i.mul(r,o);return i.neg(i.sum(h,-1))})}var Ro={meanSquaredError:Qn,meanAbsoluteError:oo,meanAbsolutePercentageError:ka,meanSquaredLogarithmicError:vn,squaredHinge:Bi,hinge:yo,categoricalHinge:vo,logcosh:Aa,categoricalCrossentropy:go,sparseCategoricalCrossentropy:To,binaryCrossentropy:Eo,kullbackLeiblerDivergence:As,poisson:Ds,cosineProximity:Xo};function Yo(s){if(typeof s=="string"){if(s in Ro)return Ro[s];var u="Unknown loss "+s;throw s.toLowerCase().includes("softmaxcrossentropy")&&(u="Unknown loss "+s+'. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy'),new w(u)}else return s}function Ao(s,u){return i.tidy(function(){var r=i.mul(.5,i.onesLike(u)),o=ni(i.greater(u,r),s.dtype);return i.mean(i.equal(s,o),-1)})}function Qo(s,u){return i.tidy(function(){return ni(i.equal(i.argMax(s,-1),i.argMax(u,-1)),"float32")})}function vi(s,u){return i.tidy(function(){return i.logicalAnd(s.equal(1),u.equal(1)).sum().cast("float32")})}function Fs(s,u){return i.tidy(function(){return i.logicalAnd(s.equal(1),u.equal(0)).sum().cast("float32")})}function tu(s,u){return i.tidy(function(){return i.logicalAnd(s.equal(0),u.equal(1)).sum().cast("float32")})}function ps(s,u){return i.tidy(function(){var r=vi(s,u),o=tu(s,u),h=r.add(o);return i.where(i.greater(h,0),r.div(h),0).cast("float32")})}function ru(s,u){return i.tidy(function(){var r=vi(s,u),o=Fs(s,u),h=r.add(o);return i.where(i.greater(h,0),r.div(h),0).cast("float32")})}function Os(s,u){return Eo(s,u)}function ds(s,u){return s.rank===u.rank&&(s=s.squeeze([s.rank-1])),u=u.argMax(-1),u.dtype!==s.dtype&&(u=u.asType(s.dtype)),i.equal(s,u).asType("float32")}var Ms=Qn,Ls=Qn,nu=oo,fs=oo,au=ka,ms=ka,Do=go,zs=Xo,Zo=To,xo={binaryAccuracy:Ao,categoricalAccuracy:Qo,precision:ps,categoricalCrossentropy:Do,sparseCategoricalCrossentropy:Zo,mse:Ms,MSE:Ls,mae:nu,MAE:fs,mape:au,MAPE:ms,cosine:zs};function ys(s){if(typeof s=="string"&&s in xo)return xo[s];if(typeof s!="string"&&s!=null)return s;throw new w("Unknown metric "+s)}function Fo(s){if(tt(s!==null,"Unknown LossOrMetricFn "+s),typeof s=="string")return s;for(var u=void 0,r=0,o=Object.keys(Ro);rJo&&console.warn('User-defined metadata of model "'+u+'" is too large in '+("size (length="+o.length+" when serialized). It is not ")+"recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= "+(Jo+"."))}}function wo(s){if(s===null)return!0;if(typeof s=="object")if(Object.getPrototypeOf(s)===Object.prototype){for(var u=Object.keys(s),r=0,o=u;r1||M.length===1&&M[0].inboundLayers.length>1){u=!1;break}o.push.apply(o,M)}if(u)for(var q=0,Y=s.layers;q0&&(o=o.slice(0,o.length-1)+" "),o+=s[h],o=o.slice(0,u[h]),o+=" ".repeat(u[h]-o.length);r(o)}function iu(s,u,r){var o;try{o=JSON.stringify(s.outputShape)}catch(M){o="multiple"}var h=s.name,b=s.getClassName(),T=[h+" ("+b+")",o,s.countParams().toString()];$o(T,u,r)}function ku(s,u,r,o){var h;try{h=JSON.stringify(s.outputShape)}catch(st){h="multiple"}for(var b=[],T=0,M=s.inboundNodes;T0&&r.indexOf(q)===-1)continue;for(var Y=0;Yo.maxNumTensors&&(o.maxNumTensors=Dt),Dt0,function(){return"Expected at least one fetch, got none"});var r=[],o={};if(s.length===1){var h=ue(s[0],u);r=h.sorted,o=h.recipientMap}else for(var b=new Set,T=0,M=s;T0;){var le=q[q.length-1];if(r.has(le.name)){q.pop();continue}var Ne=Y[Y.length-1]===q.length-1;if(le.inputs.length===0||Ne)q.pop(),o.push(le),r.add(le.name),Ne&&Y.pop();else{Y.push(q.length-1);for(var We=0,je=le.inputs;We1 nodes"),tt(le===0,"input layer has >1 tensors"),o.inputLayers.push(q),o.inputLayersNodeIndices.push(Y),o.inputLayersTensorIndices.push(le)}o.inputNames=[],o.outputNames=[],o.feedInputShapes=[],o.feedInputNames=[],o.feedOutputNames=[];for(var je=0;je=0;)gi.splice(gi.indexOf(Ti),1);Xt.push(Ti)},vr=[],lr=[],Ir=0,Lr=o.outputs;IrNs?1:0});for(var Ks=0,Zu=Vi;Ks0)throw new w("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];for(var r=[],o=0,h=this.layers;o0)throw new w(st.length+" of "+b+" weights are not set: "+(""+st))}zi(We)},u.prototype.updatedConfig=function(){var r=this.getConfig(),o={};return o.className=this.getClassName(),o.config=r,o.kerasVersion="tfjs-layers "+gs,o.backend="TensorFlow.js",o},u.prototype.toJSON=function(r,o){o===void 0&&(o=!0);var h=Mo(this.updatedConfig());return o?JSON.stringify(h):h},u.prototype.call=function(r,o){var h=this;return i.tidy(function(){r=Qe(r);for(var b=new Si,T=0;T1)for(var le=0,Ne=Y;le0){for(var mt=[],pt=0;pt0&&cn.apply(Tt(Hr),ua)}function le(cn){var Mn=cn.name,Hr=oa(cn,o.customObjects!=null?o.customObjects:{});Hr.setFastWeightInitDuringBuild(b),T[Mn]=Hr;var ua=cn.inboundNodes;ua.forEach(function(Ci){if(!(Ci instanceof Array))throw new w("Corrupted configuration, expected array for nodeData: "+Ci);q(Hr,Ci)})}for(var Ne=o.name,We=o.layers,je=0,qe=We;je0&&typeof s[Object.keys(s)[0]]=="object"){var h=[];return u.forEach(function(b){b in s?h.push(s[b]):h.push(null)}),h}else throw new Error("The model has multiple ("+o+") outputs, "+("so "+r+" must be either an array with ")+(o+" elements or an object with "+u+" keys. ")+("Provided "+r+" not understood: "+JSON.stringify(s)))}function V(s,u){return A(s,u,"classWeight")}function oe(s,u,r,o){return xe(this,void 0,void 0,function(){var h,b,T,M,q;return Q(this,function(Y){switch(Y.label){case 0:if(u!=null||o!=null)throw new Error("Support sampleWeight is not implemented yet");return r!=null?(h=i.tidy(function(){if(s.shape.length===1)return s.clone();if(s.shape.length===2)if(s.shape[1]>1){var le=1;return s.argMax(le)}else{if(s.shape[1]===1)return s.reshape([s.shape[0]]);throw new Error("Encountered unexpected last-dimension size ("+s.shape[1]+") during handling of class weights. The size is expected to be >= 1.")}else throw new Error("Unexpected rank of target (y) tensor ("+s.rank+") during handling of class weights. The rank is expected to be 1 or 2.")}),M=(T=Array).from,[4,h.data()]):[3,2];case 1:return b=M.apply(T,[Y.sent()]),i.dispose(h),q=[],b.forEach(function(le){if(r[le]==null)throw new Error("classWeight must contain all classes in the training data. "+("The class "+le+" exists in the data but not in ")+"classWeight");q.push(r[le])}),[2,i.tensor1d(q,"float32")];case 2:return[2,null]}})})}function ee(s,u){return i.mul(s,u)}var _e=32;function ce(s,u){var r,o,h=u;r=h.xs,o=h.ys,i.util.assert(r!=null&&o!=null,function(){return"A Dataset iterator for fitDataset() is expected to generate objects of the form `{xs: xVal, ys: yVal}`, where the two values may be `tf.Tensor`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates "+(""+u)});var b=de("input",s.inputNames,r),T=de("output",s.outputNames,o),M=b[0].shape[0];i.util.assert(b.length===s.inputs.length,function(){return"LayersModel has "+s.inputs.length+" inputs, but the dataset "+("provides "+b.length+" inputs. (Expected input keys: ")+(JSON.stringify(s.inputNames)+")")}),i.util.assert(T.length===s.outputs.length,function(){return"LayersModel has "+s.outputs.length+" outputs, but the dataset "+("provides "+T.length+" outputs. (Expected output keys: ")+(JSON.stringify(s.outputNames)+")")});for(var q=function(We){i.util.assert(b[We].shape[0]===M,function(){return"Batch size mismatch: input "+(s.inputNames[We]+" has "+b[We].shape[0]+"; ")+("expected "+M+" based on input "+s.inputNames[0]+".")})},Y=0;Y0&&Number.isInteger(r.epochs),function(){return"For fitDataset(), config.epochs is expected to be a positive "+("integer, but got "+r.epochs)}),i.util.assert(!o||r.batchesPerEpoch>0&&Number.isInteger(r.batchesPerEpoch),function(){return"For fitDataset(), config.batchesPerEpoch is expected to be a "+("positive integer if specified, but got "+r.batchesPerEpoch)}),i.util.assert(r.validationSplit==null,function(){return"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."}),s.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");s.isTraining=!0,Hr.label=1;case 1:return Hr.trys.push([1,,26,27]),h=r.validationData!=null,b=void 0,T=void 0,h&&(Oe(r.validationData)?i.util.assert(r.validationBatches==null||r.validationBatches>0&&Number.isInteger(r.validationBatches),function(){return"For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, "+("but got "+r.validationBatches)}):(M=ye(r.validationData),b=M.xs,T=M.ys)),q=s.makeTrainFunction(),Y=s.getDedupedMetricsNames(),le=void 0,h?le=Y.slice().concat(Y.map(function(ua){return"val_"+ua})):le=Y.slice(),Ne=io(r.callbacks,r.yieldEvery),We=r.verbose==null?1:r.verbose,je=Pr(Ne,We,r.epochs,null,null,Re(u,r),null,h,le),qe=je.callbackList,mt=je.history,qe.setModel(s),s.history=mt,[4,qe.onTrainBegin()];case 2:return Hr.sent(),s.stopTraining_=!1,pt=r.initialEpoch==null?0:r.initialEpoch,[4,u.iterator()];case 3:st=Hr.sent(),Hr.label=4;case 4:return pt=r.batchesPerEpoch:Xt.done)?h?(cn=void 0,Oe(r.validationData)?(Mn=Qe,[4,s.evaluateDataset(r.validationData,{batches:r.validationBatches})]):[3,17]):[3,19]:[3,20];case 16:return cn=Mn.apply(void 0,[Hr.sent()]),[3,18];case 17:cn=Qe(s.evaluate(b,T,{batchSize:r.validationBatchSize==null?_e:r.validationBatchSize,verbose:0})),Hr.label=18;case 18:for(Sr=0;Sr0)throw new ge("Verbose mode is not implemented yet.");return i.util.assert(!o||r.batches>0&&Number.isInteger(r.batches),function(){return"Test loop expects `batches` to be a positive integer, but "+("received "+JSON.stringify(r.batches))}),Fe(u)?(M=u,[3,3]):[3,1];case 1:return[4,u.iterator()];case 2:M=qe.sent(),qe.label=3;case 3:T=M,q=0,Y=0,le=function(){var mt;return Q(this,function(pt){switch(pt.label){case 0:return[4,T.next()];case 1:return mt=pt.sent(),b=i.tidy(function(){if(mt.value){var st=ce(s,mt.value),dt=st.xs,Dt=st.ys,or=dt.concat(Dt),Xt=i.tidy(function(){return h(or)});if(i.dispose(or),Y===0)for(var Jt=0;Jt0&&i.dispose(Sr)},Jt=0;Jt0&&Number.isInteger(s),function(){return"batchSize is required to be a positive integer, but got "+s})}function rt(s,u,r){return s==null?[null]:Array.isArray(s)?s.map(function(o){return Zn(o,u,r-u)}):Zn(s,u,r-u)}function at(s,u){return i.tidy(function(){return s==null?null:Array.isArray(s)?s.map(function(r){return at(r,u)}):X(s,u.dtype==="int32"?u:u.toInt())})}function $(s,u){for(var r=[],o=0,h=null;o=s&&(h=s),r.push([o,h]),o=h;return r}function et(s,u,r,o,h,b,T,M,q,Y,le,Ne,We,je,qe){return xe(this,void 0,void 0,function(){var mt,pt,st,dt,Dt,or,Xt,Jt,vr;return Q(this,function(lr){switch(lr.label){case 0:if(h==null&&(h=32),b==null&&(b=1),le==null&&(le=!0),We==null&&(We=0),mt=!1,q!=null&&Y!=null&&(mt=!0),qe!=null&&(mt=!0,je==null))throw new w("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");return pt=s.checkNumSamples(r,h,je,"steps_per_epoch"),pt!=null&&(st=ln(0,pt)),T==null&&(T=1),dt=Pr(M,T,b,We,pt,je,h,mt,Ne),Dt=dt.callbackList,or=dt.history,Dt.setModel(s),s.history=or,[4,Dt.onTrainBegin()];case 1:lr.sent(),s.stopTraining_=!1,Xt=function(Ir){var Lr,kr,Sr,fn,Xr,$t;return Q(this,function(On){switch(On.label){case 0:return[4,Dt.onEpochBegin(Ir)];case 1:if(On.sent(),Lr={},!(je!=null))return[3,2];throw new ge("stepsPerEpoch mode is not implemented yet.");case 2:if(le==="batch")throw new ge("batch shuffling is not implemneted yet");le&&i.util.shuffle(st),kr=i.tensor1d(st),Sr=$(pt,h),fn=function(En){var kn;return Q(this,function(cn){switch(cn.label){case 0:return kn={},[4,Dt.onBatchBegin(En,kn)];case 1:return cn.sent(),i.tidy(function(){var Mn=Sr[En][0],Hr=Sr[En][1],ua=Zn(kr,Mn,Hr-Mn);kn.batch=En,kn.size=Hr-Mn;for(var Ci=at(r,ua),Ui=u(Ci),Xn=0;Xn0))return[3,4];if(qe=!0,o.validationData.length===2)T=o.validationData[0],M=o.validationData[1];else throw o.validationData.length===3?new ge("validationData including sample weights is not supported yet."):new w("When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; "+(o.validationData+" is invalid."));return pt=!0,[4,s.standardizeUserData(T,M,null,null,pt,Ne)];case 3:return st=kr.sent(),q=st[0],Y=st[1],mt=q.concat(Y),[3,5];case 4:o.validationSplit!=null&&o.validationSplit>0&&o.validationSplit<1?(qe=!0,dt=Math.floor(h[0].shape[0]*(1-o.validationSplit)),Dt=h[0].shape[0],q=rt(h,dt,Dt),h=rt(h,0,dt),Y=rt(b,dt,Dt),b=rt(b,0,dt),mt=q.concat(Y)):o.validationSteps!=null&&(qe=!0),kr.label=5;case 5:return or=h.concat(b).concat(le),s.checkTrainableWeightsConsistency(),Xt=s.makeTrainFunction(),Jt=s.getDedupedMetricsNames(),vr=void 0,lr=void 0,qe?(s.makeTestFunction(),vr=s.testFunction,lr=Jt.slice().concat(Jt.map(function(Sr){return"val_"+Sr}))):(vr=null,mt=[],lr=Jt.slice()),Ir=io(o.callbacks,o.yieldEvery),[4,et(s,Xt,or,Jt,Ne,o.epochs,o.verbose,Ir,vr,mt,o.shuffle,lr,o.initialEpoch,null,null)];case 6:return Lr=kr.sent(),[2,Lr];case 7:return s.isTraining=!1,_t(h,u),_t(b,r),_t(q,T),_t(Y,M),le!=null&&i.dispose(le),[7];case 8:return[2]}})})}function lt(s){var u=[];s instanceof i.Tensor&&(s=[s]);for(var r=0;r0)b=!0;else if(Pt(s)){for(var T in s)if(s.hasOwnProperty(T)){b=!0;break}}else b=!0;if(b)throw new w("Error when checking model "+h+" expected no data, "+("but got "+s))}return[]}if(s==null)return u.map(function(pt){return null});var M;if(Pt(s)){s=s,M=[];for(var q=0,Y=u;q1)throw new w("The model "+h+" expects "+u.length+" Tensor(s), "+("but only received one Tensor. Found: Tensor with shape "+s.shape));M=[s]}if(M=lt(M),r!=null)for(var Ne=0;Ne=0&&qe!==mt)throw new w("Error when checking "+h+": expected "+u[Ne]+" "+("to have shape ["+r[Ne]+"], but got array with shape ")+("["+We.shape+"]."))}}return M}function Nt(s,u,r){var o=qt(s.map(function(b){return b.shape[0]}));o.sort();var h=qt(u.map(function(b){return b.shape[0]}));if(h.sort(),o.length>1)throw new w("All input Tensors (x) should have the same number of samples. Got array shapes: "+(""+JSON.stringify(s.map(function(b){return b.shape}))));if(h.length>1)throw new w("All target Tensors (y) should have the same number of samples. Got array shapes: "+(""+JSON.stringify(u.map(function(b){return b.shape}))));if(o.length>0&&h.length>0&&!i.util.arraysEqual(o,h))throw new w("Input Tensors should have the same number of samples as target "+("Tensors. Found "+o[0]+" input sample(s) and "+h[0]+" target ")+"sample(s).")}function Kt(s,u,r){for(var o=[Qn,Eo,go],h=0;h1)throw new w("The model expects "+u.length+" "+h+" Tensors, but only received one Tensor. Found: array with shape "+(JSON.stringify(s.shape)+"."));b=[s]}if(r!=null)for(var T=0;T1&&(o.metricsTensors.push([dt,st]),o.metricsNames.push(o.outputNames[st]+"_loss"))}});var mt=Ot(r.metrics,this.outputNames),pt=function(st,dt,Dt){o.outputNames.length>1&&(dt=o.outputNames[st]+"_"+dt),o.metricsNames.push(dt),o.metricsTensors.push([Dt,st])};_a("metric",function(){for(var st=function(Dt){if(qe.indexOf(Dt)!==-1)return"continue";var or=mt[Dt],Xt=function(Jt){for(var vr="",lr,Ir,Lr,kr=function($t){if(typeof $t=="string"&&["accuracy","acc","crossentropy","ce"].indexOf($t)!==-1){var On=o.internalOutputShapes[Dt];On[On.length-1]===1||o.lossFunctions[Dt]===Eo?["accuracy","acc"].indexOf($t)!==-1?Ir=Ao:["crossentropy","ce"].indexOf($t)!==-1&&(Ir=Os):o.lossFunctions[Dt]===To?["accuracy","acc"].indexOf($t)!==-1?Ir=ds:["crossentropy","ce"].indexOf($t)!==-1&&(Ir=Zo):["accuracy","acc"].indexOf($t)!==-1?Ir=Qo:["crossentropy","ce"].indexOf($t)!==-1&&(Ir=Do);var En=void 0;["accuracy","acc"].indexOf($t)!==-1?En="acc":["crossentropy","ce"].indexOf($t)!==-1&&(En="ce"),Lr=Ir,lr=vr+En}else{var kn=ys($t);Lr=kn,lr=vr+Fo($t)}var cn;_a(lr,function(){cn=Lr}),pt(Dt,lr,cn)},Sr=0,fn=Jt;Sr0){var We=[];throw o.forEach(function(je,qe){je==null&&We.push(r[qe])}),new w("Cannot find SymbolicTensors for output name(s): "+(""+JSON.stringify(We)))}return o},u.prototype.predictLoop=function(r,o,h){var b=this;return o===void 0&&(o=32),h===void 0&&(h=!1),i.tidy(function(){var T=b.checkNumSamples(r);if(h)throw new ge("Verbose predictLoop() is not implemented yet.");for(var M=$(T,o),q=b.outputs.map(function(Ne){return[]}),Y=function(Ne){var We=i.tidy(function(){var je=M[Ne][0],qe=M[Ne][1],mt=rt(r,je,qe),pt=[];if(Array.isArray(mt))for(var st=0;st0&&r[0].shape[0]%b!==0)throw new w("In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size "+(b+". Found: "+r[0].shape[0]+" sample(s)."));return[r,o]},u.prototype.standardizeUserData=function(r,o,h,b,T,M){return T===void 0&&(T=!0),xe(this,void 0,void 0,function(){var q,Y,le,Ne,We,je,qe,mt;return Q(this,function(pt){switch(pt.label){case 0:if(q=this.standardizeUserDataXY(r,o,T,M),Y=q[0],le=q[1],h!=null)throw new Error("sample weight is not supported yet.");if(Ne=null,!(b!=null))return[3,4];We=V(b,this.outputNames),Ne=[],je=0,pt.label=1;case 1:return je0)throw new ge("Verbose mode is not implemented yet.");if(T!=null)throw new ge("steps mode in testLoop() is not implemented yet");for(var le=$(q,h),Ne=i.tensor1d(ln(0,q)),We=0;We1){var M=nr(r.slice(0,h),b);T+="_"+M}o.push(T)}return o},u.prototype.makeTrainFunction=function(){var r=this;return function(o){var h=[],b=o.slice(0,r.inputs.length),T=o.slice(r.inputs.length,r.inputs.length+r.outputs.length),M=o.slice(r.inputs.length+r.outputs.length,r.inputs.length+r.outputs.length*2),q=[],Y=function(){for(var je=[],qe=0;qe1&&qe1)throw new w("Found more than one ("+h.length+") save handlers for "+("URL '"+r+"'"));r=h[0]}if(r.save==null)throw new w("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return[4,i.io.encodeWeights(this.getNamedWeights(o))];case 1:return b=Dt.sent(),T=!1,M=null,q=this.toJSON(M,T),Y={modelTopology:q,format:Rt,generatedBy:"TensorFlow.js tfjs-layers v"+gs,convertedBy:null},le=o==null?!1:o.includeOptimizer,le&&this.optimizer!=null?(Y.trainingConfig=this.getTrainingConfig(),Ne="optimizer",pt=(mt=i.io).encodeWeights,[4,this.optimizer.getWeights()]):[3,4];case 2:return[4,pt.apply(mt,[Dt.sent(),Ne])];case 3:We=Dt.sent(),je=We.data,qe=We.specs,(dt=b.specs).push.apply(dt,qe),b.data=i.io.concatenateArrayBuffers([b.data,je]),Dt.label=4;case 4:return this.userDefinedMetadata!=null&&(st=!0,_o(this.userDefinedMetadata,this.name,st),Y.userDefinedMetadata=this.userDefinedMetadata),Y.weightData=b.data,Y.weightSpecs=b.specs,[2,r.save(Y)]}})})},u.prototype.setUserDefinedMetadata=function(r){_o(r,this.name),this.userDefinedMetadata=r},u.prototype.getUserDefinedMetadata=function(){return this.userDefinedMetadata},u.className="Model",u}(F);i.serialization.registerClass(wt);var Et=function(s){O(u,s);function u(){return s!==null&&s.apply(this,arguments)||this}return u.className="Functional",u}(wt);i.serialization.registerClass(Et);function Vt(s,u){return xe(this,void 0,void 0,function(){var r,o,h,b,T,M,q,Y;return Q(this,function(le){switch(le.label){case 0:return"modelTopology"in s||(s={modelTopology:s}),s=s,r=s.modelTopology,r.model_config!=null&&(r=r.model_config),o=Oo(r),h=oa(o,u),s.weightsManifest!=null?[4,i.io.loadWeights(s.weightsManifest,s.pathPrefix,h.weights.map(function(Ne){return Ne.originalName}))]:[3,2];case 1:for(b=le.sent(),T={},M=0,q=h.weights;M1)throw new w("Found more than one ("+r.length+") load handlers for "+("URL '"+s+"'"));s=r[0]}return[2,cr(s,void 0,u)]})})}function cr(s,u,r){return xe(this,void 0,void 0,function(){var o,h,b,T,M,q,Y,le,Ne;return Q(this,function(We){switch(We.label){case 0:if(r==null&&(r={}),s.load==null)throw new w("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");return[4,s.load()];case 1:if(o=We.sent(),h=o.modelTopology,h.model_config!=null&&(h=h.model_config),b=r.strict==null?!0:r.strict,T=o.weightData!=null&&o.weightSpecs!=null&&b,M=oa(Oo(h),u,T),q=o.trainingConfig,q!=null&&M.loadTrainingConfig(q),o.userDefinedMetadata!=null&&M.setUserDefinedMetadata(o.userDefinedMetadata),!(o.weightData!=null))return[3,4];if(o.weightSpecs==null)throw new w("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");return Y=rr(o.weightData,o.weightSpecs),le=Y.modelWeights,Ne=Y.optimizerWeights,M.loadWeights(le,b),M.optimizer!=null&&Ne.length>0?[4,M.optimizer.setWeights(Ne)]:[3,3];case 2:We.sent(),We.label=3;case 3:i.dispose(le),i.dispose(Ne.map(function(je){return je.tensor})),We.label=4;case 4:return[2,M]}})})}function rr(s,u){var r=i.io.decodeWeights(s,u),o={},h=[];return u.forEach(function(b){b.group==="optimizer"?h.push({name:b.name,tensor:r[b.name]}):o[b.name]=r[b.name]}),{modelWeights:o,optimizerWeights:h}}var Ie=function(s){O(u,s);function u(r){var o=s.call(this,{inputs:[],outputs:[]})||this;if(r=r||{},o.trainable=!0,o.built=!1,o.name=r.name!=null?r.name:Fr("sequential_"),r.layers!=null)for(var h=0,b=r.layers;h 0 "+("but got "+JSON.stringify(r.filters)))},u}(Cu),Tu=function(s){O(u,s);function u(r){var o=s.call(this,2,r)||this;return u.verifyArgs(r),o}return u.prototype.getConfig=function(){var r=s.prototype.getConfig.call(this);return delete r.rank,r},u.verifyArgs=function(r){if(typeof r.kernelSize!="number"&&!_r(r.kernelSize,"number",1,2))throw new w("Conv2D expects config.kernelSize to be number or number[] with "+("length 1 or 2, but received "+JSON.stringify(r.kernelSize)+"."))},u.className="Conv2D",u}(cu);i.serialization.registerClass(Tu);var hc=function(s){O(u,s);function u(r){var o=s.call(this,3,r)||this;return u.verifyArgs(r),o}return u.prototype.getConfig=function(){var r=s.prototype.getConfig.call(this);return delete r.rank,r},u.verifyArgs=function(r){if(typeof r.kernelSize!="number"&&!(Array.isArray(r.kernelSize)&&(r.kernelSize.length===1||r.kernelSize.length===3)))throw new w("Conv3D expects config.kernelSize to be number or"+(" [number, number, number], but received "+JSON.stringify(r.kernelSize)+"."))},u.className="Conv3D",u}(cu);i.serialization.registerClass(hc);var uo=function(s){O(u,s);function u(r){var o=s.call(this,r)||this;if(o.inputSpec=[new An({ndim:4})],o.padding!=="same"&&o.padding!=="valid")throw new w("Conv2DTranspose currently supports only padding modes 'same' "+("and 'valid', but received padding mode "+o.padding));return o}return u.prototype.build=function(r){var o;if(r=$r(r),r.length!==4)throw new w("Input should have rank 4; Received input shape: "+JSON.stringify(r));var h=this.dataFormat==="channelsFirst"?1:r.length-1;if(r[h]==null)throw new w("The channel dimension of the inputs should be defined. Found `None`.");var b=r[h],T=this.kernelSize.concat([this.filters,b]);this.kernel=this.addWeight("kernel",T,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new An({ndim:4,axes:(o={},o[h]=b,o)})],this.built=!0},u.prototype.call=function(r,o){var h=this;return i.tidy(function(){var b=ur(r);if(b.shape.length!==4)throw new w("Conv2DTranspose.call() expects input tensor to be rank-4, but "+("received a tensor of rank-"+b.shape.length));var T=b.shape,M=T[0],q,Y;h.dataFormat==="channelsFirst"?(q=2,Y=3):(q=1,Y=2);var le=T[q],Ne=T[Y],We=h.kernelSize[0],je=h.kernelSize[1],qe=h.strides[0],mt=h.strides[1],pt=_s(le,qe,We,h.padding),st=_s(Ne,mt,je,h.padding),dt=[M,pt,st,h.filters];h.dataFormat!=="channelsLast"&&(b=i.transpose(b,[0,2,3,1]));var Dt=i.conv2dTranspose(b,h.kernel.read(),dt,h.strides,h.padding);return h.dataFormat!=="channelsLast"&&(Dt=i.transpose(Dt,[0,3,1,2])),h.bias!=null&&(Dt=te(Dt,h.bias.read(),h.dataFormat)),h.activation!=null&&(Dt=h.activation.apply(Dt)),Dt})},u.prototype.computeOutputShape=function(r){r=$r(r);var o=r.slice(),h,b,T;this.dataFormat==="channelsFirst"?(h=1,b=2,T=3):(h=3,b=1,T=2);var M=this.kernelSize[0],q=this.kernelSize[1],Y=this.strides[0],le=this.strides[1];return o[h]=this.filters,o[b]=_s(o[b],Y,M,this.padding),o[T]=_s(o[T],le,q,this.padding),o},u.prototype.getConfig=function(){var r=s.prototype.getConfig.call(this);return delete r.dilationRate,r},u.className="Conv2DTranspose",u}(Tu);i.serialization.registerClass(uo);var bs=function(s){O(u,s);function u(r,o){var h=s.call(this,r,o)||this;if(h.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",h.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",h.depthwiseKernel=null,h.pointwiseKernel=null,o.filters==null)throw new w("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(o.kernelInitializer!=null||o.kernelRegularizer!=null||o.kernelConstraint!=null)throw new w("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(o.padding!=null&&o.padding!=="same"&&o.padding!=="valid")throw new w("SeparableConv"+h.rank+"D supports only padding modes: "+("'same' and 'valid', but received "+JSON.stringify(o.padding)));return h.depthMultiplier=o.depthMultiplier==null?1:o.depthMultiplier,h.depthwiseInitializer=x(o.depthwiseInitializer||h.DEFAULT_DEPTHWISE_INITIALIZER),h.depthwiseRegularizer=Fn(o.depthwiseRegularizer),h.depthwiseConstraint=xn(o.depthwiseConstraint),h.pointwiseInitializer=x(o.depthwiseInitializer||h.DEFAULT_POINTWISE_INITIALIZER),h.pointwiseRegularizer=Fn(o.pointwiseRegularizer),h.pointwiseConstraint=xn(o.pointwiseConstraint),h}return u.prototype.build=function(r){var o;if(r=$r(r),r.length1&&(u=s.slice(1,s.length)),s=s[0]}function h(b){return b==null||Array.isArray(b)?b:[b]}return u=h(u),r=h(r),{inputs:s,initialState:u,constants:r}}function yc(s,u,r,o,h,b,T,M){return o===void 0&&(o=!1),T===void 0&&(T=!1),M===void 0&&(M=!1),i.tidy(function(){var q=u.shape.length;if(q<3)throw new w("Input should be at least 3D, but is "+q+"D.");var Y=[1,0].concat(ln(2,q));if(u=i.transpose(u,Y),b!=null)throw new ge("The rnn() functoin of the deeplearn.js backend does not support constants yet.");T&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),h!=null&&(h=h.asType("bool").asType("float32"),h.rank===q-1&&(h=i.expandDims(h,-1)),h=i.transpose(h,Y)),o&&(u=i.reverse(u,0),h!=null&&(h=i.reverse(h,0)));var le=[],Ne,We=r,je=u.shape[0],qe=i.unstack(u),mt;h!=null&&(mt=i.unstack(h));for(var pt=function(or){var Xt=qe[or],Jt=i.tidy(function(){return s(Xt,We)});if(h==null)Ne=Jt[0],We=Jt[1];else{var vr=i.tidy(function(){var lr=mt[or],Ir=i.onesLike(lr).sub(lr),Lr=Jt[0].mul(lr).add(We[0].mul(Ir)),kr=We.map(function(Sr,fn){return Jt[1][fn].mul(lr).add(Sr.mul(Ir))});return{output:Lr,newStates:kr}});Ne=vr.output,We=vr.newStates}M&&le.push(Ne)},st=0;st1?da(h,[1,b]):h}):o.cell.stateSize>1?[da(h,[1,o.cell.stateSize])]:[h]})},Object.defineProperty(u.prototype,"trainableWeights",{get:function(){return this.trainable?this.cell.trainableWeights:[]},enumerable:!0,configurable:!0}),Object.defineProperty(u.prototype,"nonTrainableWeights",{get:function(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights},enumerable:!0,configurable:!0}),u.prototype.setFastWeightInitDuringBuild=function(r){s.prototype.setFastWeightInitDuringBuild.call(this,r),this.cell!=null&&this.cell.setFastWeightInitDuringBuild(r)},u.prototype.getConfig=function(){var r=s.prototype.getConfig.call(this),o={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};this.numConstants!=null&&(o.numConstants=this.numConstants);var h=this.cell.getConfig();return this.getClassName()===u.className&&(o.cell={className:this.cell.getClassName(),config:h}),H({},h,r,o)},u.fromConfig=function(r,o,h){h===void 0&&(h={});var b=o.cell,T=oa(b,h);return new r(Object.assign(o,{cell:T}))},u.className="RNN",u}(qr);i.serialization.registerClass(Ni);var ns=function(s){O(u,s);function u(){return s!==null&&s.apply(this,arguments)||this}return u}(qr),ks=function(s){O(u,s);function u(r){var o=s.call(this,r)||this;return o.DEFAULT_ACTIVATION="tanh",o.DEFAULT_KERNEL_INITIALIZER="glorotNormal",o.DEFAULT_RECURRENT_INITIALIZER="orthogonal",o.DEFAULT_BIAS_INITIALIZER="zeros",o.units=r.units,tr(o.units,"units"),o.activation=va(r.activation==null?o.DEFAULT_ACTIVATION:r.activation),o.useBias=r.useBias==null?!0:r.useBias,o.kernelInitializer=x(r.kernelInitializer||o.DEFAULT_KERNEL_INITIALIZER),o.recurrentInitializer=x(r.recurrentInitializer||o.DEFAULT_RECURRENT_INITIALIZER),o.biasInitializer=x(r.biasInitializer||o.DEFAULT_BIAS_INITIALIZER),o.kernelRegularizer=Fn(r.kernelRegularizer),o.recurrentRegularizer=Fn(r.recurrentRegularizer),o.biasRegularizer=Fn(r.biasRegularizer),o.kernelConstraint=xn(r.kernelConstraint),o.recurrentConstraint=xn(r.recurrentConstraint),o.biasConstraint=xn(r.biasConstraint),o.dropout=fi([1,Va([0,r.dropout==null?0:r.dropout])]),o.recurrentDropout=fi([1,Va([0,r.recurrentDropout==null?0:r.recurrentDropout])]),o.stateSize=o.units,o.dropoutMask=null,o.recurrentDropoutMask=null,o}return u.prototype.build=function(r){r=$r(r),this.kernel=this.addWeight("kernel",[r[r.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0},u.prototype.call=function(r,o){var h=this;return i.tidy(function(){if(r=r,r.length!==2)throw new w("SimpleRNNCell expects 2 input Tensors, got "+r.length+".");var b=r[1];r=r[0];var T=o.training==null?!1:o.training;01){for(var T=[0],M=2;M1)throw new w("Can not merge tensors with different batch sizes. "+("Got tensors with shapes: "+JSON.stringify(r)+"."));for(var M=r[0]==null?null:r[0].slice(1),q=1;q1){var or=ln(1,Ne).concat([0]);b.push(i.transpose(le,or)),je=!0}else b.push(le)}var Xt=h.mergeFunction(b),Jt=Xt.rank;if(je){if(Jt==null){var vr=Xt.shape,lr=vr.length,st=vr[lr-1],dt=[st].concat(vr.slice(0,vr.length-1));Xt=i.transpose(Xt.reshape([-1,st]),[1,0]).reshape(dt)}else if(Jt>1){var or=[Jt-1].concat(ln(0,Jt-1));Xt=i.transpose(Xt,or)}}return Xt}}else return h.mergeFunction(r)})},u.prototype.computeOutputShape=function(r){r=r;var o;r[0]==null?o=null:o=r[0].slice(1);for(var h=1;h1)throw new w("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(r))},u.prototype.mergeFunction=function(r){var o=this;return i.tidy(function(){return ji(r,o.axis)})},u.prototype.computeOutputShape=function(r){if(!(Array.isArray(r)&&Array.isArray(r[0])))throw new w("A `Concatenate` layer should be called on a list of inputs.");for(var o=r,h=o[0].slice(),b=this.axis<0?h.length+this.axis:this.axis,T=0,M=o.slice(1);T3||u.shape.length>3)throw new ge("batchDot is not implemented for tensors of 4D or higher rank yet");if(i.util.assert(s.shape.length>=2,function(){return"batchDot requires the rank of x to be >= 2, "+("but got "+s.shape.length)}),i.util.assert(s.shape.length>=2,function(){return"batchDot requires the rank of y to be >= 2, "+("but got "+u.shape.length)}),typeof r=="number"&&(r=[r,r]),s.dtype==="complex64"||u.dtype==="complex64")throw new ge("batchDot is not implemented for complex64-type Tensors yet.");var o=s.shape.length,h=u.shape.length;r==null&&(r=[o-1,h-2]);var b=r;return i.tidy(function(){var T;if(o>h){T=o-h;for(var M=[],q=0;qo){T=h-o;for(var M=[],q=0;q0){var We=void 0;o>h?We=o+h-3:We=o-1;for(var je=[],q=We;q3||h.length>3)throw new ge("Dot layer does not support tensors of 4D or higher rank yet.");var b=this.interpretAxes(o,h);if(o[b[0]]!==h[b[1]])throw new w("Dimension incompatibility: "+(o[b[0]]+" !== "+h[b[1]]))},u.prototype.mergeFunction=function(r){if(r.length!==2)throw new w("A `Dot` layer must be called on exactly 2 inputs, "+("but received "+r.length+" input(s)."));var o=r[0],h=r[1],b;return Array.isArray(this.axes)?b=this.axes.map(function(T,M){return ho(T,r[M].shape.length)}):b=[ho(this.axes,o.shape.length),ho(this.axes,h.shape.length)],this.normalize&&(o=Xa(o,b[0]),h=Xa(h,b[1])),Sc(o,h,b)},u.prototype.interpretAxes=function(r,o){var h;return Array.isArray(this.axes)?h=this.axes:h=[ho(this.axes,r.length),ho(this.axes,o.length)],h},u.prototype.computeOutputShape=function(r){i.util.assert(Array.isArray(r)&&r.length===2&&Array.isArray(r[0])&&Array.isArray(r[1]),function(){return"A `Dot` layer should be called on a list of exactly 2 inputs."});var o=r[0].slice(),h=r[1].slice();if(o.length>3||h.length>3)throw new ge("Dot layer does not support tensors of 4D or higher rank yet.");var b=this.interpretAxes(o,h);o.splice(b[0],1),h.splice(b[1],1),h.splice(0,1);var T=o.concat(h);return T.length===1&&T.push(1),T},u.prototype.computeMask=function(r,o){return null},u.prototype.getConfig=function(){var r={axes:this.axes,normalize:this.normalize},o=s.prototype.getConfig.call(this);return Object.assign(r,o),r},u.className="Dot",u}(Go);i.serialization.registerClass(pu);var Ic=function(s){O(u,s);function u(r){var o=s.call(this,r)||this;return o.supportsMasking=!0,o.stddev=r.stddev,o}return u.prototype.computeOutputShape=function(r){return r},u.prototype.getConfig=function(){var r=s.prototype.getConfig.call(this),o={stddev:this.stddev};return Object.assign(o,r),o},u.prototype.call=function(r,o){var h=this;return i.tidy(function(){h.invokeCallHook(r,o);var b=ur(r),T=function(){return Mi(b.shape,0,h.stddev).add(b)},M=Ye(T,function(){return b},o.training||!1);return M})},u.className="GaussianNoise",u}(qr);i.serialization.registerClass(Ic);var Mu=function(s){O(u,s);function u(r){var o=s.call(this,r)||this;return o.supportsMasking=!0,o.rate=r.rate,o}return u.prototype.computeOutputShape=function(r){return r},u.prototype.getConfig=function(){var r=s.prototype.getConfig.call(this),o={rate:this.rate};return Object.assign(o,r),o},u.prototype.call=function(r,o){var h=this;return i.tidy(function(){h.invokeCallHook(r,o);var b=ur(r);if(h.rate>0&&h.rate<1){var T=function(){var M=Math.sqrt(h.rate/(1-h.rate));return b.mul(Mi(b.shape,1,M))};return Ye(T,function(){return b},o.training||!1)}return b})},u.className="GaussianDropout",u}(qr);i.serialization.registerClass(Mu);var Gs=function(s){O(u,s);function u(r){var o=s.call(this,r)||this;return o.supportsMasking=!0,o.rate=r.rate,o.noiseShape=r.noiseShape,o}return u.prototype._getNoiseShape=function(r){return this.noiseShape||ur(r).shape},u.prototype.computeOutputShape=function(r){return r},u.prototype.getConfig=function(){var r=s.prototype.getConfig.call(this),o={rate:this.rate};return Object.assign(o,r),o},u.prototype.call=function(r,o){var h=this;return i.tidy(function(){if(h.rate<1&&h.rate>0){var b=h._getNoiseShape(r),T=function(){var M=ur(r),q=1.6732632423543772,Y=1.0507009873554805,le=-q*Y,Ne=i.greaterEqual(i.randomUniform(b),h.rate);Ne=ni(Ne,"float32");var We=Math.pow((1-h.rate)*(1+h.rate*Math.pow(le,2)),-.5),je=-We*le*h.rate,qe=M.mul(Ne).add(Ne.add(-1).mul(le));return qe.mul(We).add(je)};return Ye(T,function(){return ur(r)},o.training||!1)}return r})},u.className="AlphaDropout",u}(qr);i.serialization.registerClass(Gs);function po(s,u,r,o,h,b){b===void 0&&(b=.001);var T;if(s.rank===2)T=i.batchNorm2d(s,u,r,o,h,b);else if(s.rank===3)T=i.batchNorm3d(s,u,r,o,h,b);else if(s.rank===4)T=i.batchNorm4d(s,u,r,o,h,b);else throw new ge("batchNormalization is not implemented for array of rank "+s.rank+" yet");return T}function Lu(s,u,r,o,h){return h===void 0&&(h=.001),i.tidy(function(){var b=i.moments(s,o),T=b.mean,M=b.variance,q=po(s,T,M,r,u,h);return[q,T,M]})}function _l(s,u,r,o,h){return h===void 0&&(h=.001),i.tidy(function(){for(var b=i.moments(s,o),T=b.mean,M=b.variance,q=[],Y=0,le=ln(0,s.rank);Y=0?this.axis:this.axis+r.length,b=r[h];if(b==null)throw new w("Axis "+h+" of input tensor should have a defined dimension but the layer received an input with shape "+(JSON.stringify(r)+"."));this.inputSpec=[new An({ndim:r.length,axes:(o={},o[h]=b,o)})];var T=[b];this.scale&&(this.gamma=this.addWeight("gamma",T,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",T,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",T,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",T,null,this.movingVarianceInitializer,null,!1),this.built=!0},u.prototype.call=function(r,o){var h=this;return i.tidy(function(){var b=o.training==null?!1:o.training,T=ur(r),M=T.shape,q=M.length,Y=ln(0,q),le=h.axis>=0?h.axis:h.axis+q;Y.splice(le,1);var Ne=nt(1,q);Ne[le]=M[le];var We=Y.slice();We.sort();var je=!i.util.arraysEqual(We,ln(0,q).slice(0,q-1)),qe=function(){if(je){var Xt=h.movingMean.read().reshape(Ne),Jt=h.movingVariance.read().reshape(Ne),vr=h.center?h.beta.read().reshape(Ne):null,lr=h.scale?h.gamma.read().reshape(Ne):null;return po(T,Xt,Jt,vr,lr,h.epsilon)}else return po(T,h.movingMean.read(),h.movingVariance.read(),h.beta==null?null:h.beta.read(),h.gamma==null?null:h.gamma.read(),h.epsilon)};if(!b)return qe();var mt=zu(T,h.gamma.read(),h.beta.read(),Y,h.epsilon),pt=mt[0],st=mt[1],dt=mt[2],Dt=function(Xt,Jt,vr){i.tidy(function(){var lr=1-vr,Ir=Xt.read(),Lr=Ir.sub(Jt).mul(lr);Xt.write(Ir.sub(Lr))})},or=function(){Dt(h.movingMean,st,h.momentum),Dt(h.movingVariance,dt,h.momentum)};return or(),pt})},u.prototype.getConfig=function(){var r={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:S(this.betaInitializer),gammaInitializer:S(this.gammaInitializer),movingMeanInitializer:S(this.movingMeanInitializer),movingVarianceInitializer:S(this.movingVarianceInitializer),betaRegularizer:dn(this.betaRegularizer),gammaRegularizer:dn(this.gammaRegularizer),betaConstraint:rn(this.betaConstraint),gammaConstraint:rn(this.gammaConstraint)},o=s.prototype.getConfig.call(this);return Object.assign(r,o),r},u.className="BatchNormalization",u}(qr);i.serialization.registerClass(Pu);var du=function(s){O(u,s);function u(r){var o=this;if(r==null&&(r={}),o=s.call(this,r)||this,o.axis=r.axis==null?-1:r.axis,typeof o.axis=="number"){if(!Number.isInteger(o.axis))throw new Error("Expected axis to be an integer, but received "+o.axis)}else if(Array.isArray(o.axis))for(var h=0,b=o.axis;h=o)throw new Error("Invalid axis: "+M)}if(this.axis.length!==qt(this.axis).length)throw new Error("Found duplicate axes in: "+this.axis);var q=this.axis.map(function(le){return r[le]}),Y=!0;this.scale?this.gamma=this.addWeight("gamma",q,"float32",this.gammaInitializer,this.gammaRegularizer,Y):this.gamma=null,this.center?this.beta=this.addWeight("beta",q,"float32",this.betaInitializer,this.betaRegularizer,Y):this.beta=null,this.built=!0},u.prototype.call=function(r,o){var h=this,b=ur(r),T=b.shape,M=T.length;return i.tidy(function(){for(var q=!0,Y=i.moments(b,h.axis,q),le=Y.mean,Ne=Y.variance,We=nt(1,M),je=0,qe=h.axis;je=0?o=r[2]+this.padding[0][0]+this.padding[0][1]:o=null,r[3]!=null&&r[3]>=0?h=r[3]+this.padding[1][0]+this.padding[1][1]:h=null,[r[0],r[1],o,h]):(r[1]!=null&&r[1]>=0?o=r[1]+this.padding[0][0]+this.padding[0][1]:o=null,r[2]!=null&&r[2]>=0?h=r[2]+this.padding[1][0]+this.padding[1][1]:h=null,[r[0],o,h,r[3]])},u.prototype.call=function(r,o){var h=this;return i.tidy(function(){return wl(ur(r),h.padding,h.dataFormat)})},u.prototype.getConfig=function(){var r={padding:this.padding,dataFormat:this.dataFormat},o=s.prototype.getConfig.call(this);return Object.assign(r,o),r},u.className="ZeroPadding2D",u}(qr);i.serialization.registerClass(fu);function mu(s,u,r,o,h,b){return i.tidy(function(){on(h),xa(b),_n(o),r==null&&(r=[1,1]),o==null&&(o="valid"),h==null&&(h=he()),b==null&&(b="max"),s=bo(s,h);var T,M=o==="same"?"same":"valid";return b==="max"?T=i.maxPool(s,u,r,M):T=i.avgPool(s,u,r,M),h==="channelsFirst"&&(T=i.transpose(T,[0,3,1,2])),T})}function Nc(s,u,r,o,h,b){return i.tidy(function(){on(h),xa(b),_n(o),r==null&&(r=[1,1,1]),o==null&&(o="valid"),h==null&&(h=he()),b==null&&(b="max"),s=so(s,h);var T,M=o==="same"?"same":"valid";return b==="max"?T=i.maxPool3d(s,u,r,M):T=i.avgPool3d(s,u,r,M),h==="channelsFirst"&&(T=i.transpose(T,[0,4,1,2,3])),T})}var Cc=function(s){O(u,s);function u(r){var o=this;if(r.poolSize==null&&(r.poolSize=2),o=s.call(this,r)||this,typeof r.poolSize=="number")o.poolSize=[r.poolSize];else if(Array.isArray(r.poolSize)&&r.poolSize.length===1&&typeof r.poolSize[0]=="number")o.poolSize=r.poolSize;else throw new w("poolSize for 1D convolutional layer must be a number or an Array of a single number, but received "+(""+JSON.stringify(r.poolSize)));if(tr(o.poolSize,"poolSize"),r.strides==null)o.strides=o.poolSize;else if(typeof r.strides=="number")o.strides=[r.strides];else if(Array.isArray(r.strides)&&r.strides.length===1&&typeof r.strides[0]=="number")o.strides=r.strides;else throw new w("strides for 1D convolutional layer must be a number or an Array of a single number, but received "+(""+JSON.stringify(r.strides)));return tr(o.strides,"strides"),o.padding=r.padding==null?"valid":r.padding,_n(o.padding),o.inputSpec=[new An({ndim:3})],o}return u.prototype.computeOutputShape=function(r){r=$r(r);var o=Ii(r[1],this.poolSize[0],this.padding,this.strides[0]);return[r[0],o,r[2]]},u.prototype.call=function(r,o){var h=this;return i.tidy(function(){h.invokeCallHook(r,o),r=gr(ur(r),2);var b=h.poolingFunction(ur(r),[h.poolSize[0],1],[h.strides[0],1],h.padding,"channelsLast");return i.squeeze(b,[2])})},u.prototype.getConfig=function(){var r={poolSize:this.poolSize,padding:this.padding,strides:this.strides},o=s.prototype.getConfig.call(this);return Object.assign(r,o),r},u}(qr),Tc=function(s){O(u,s);function u(r){return s.call(this,r)||this}return u.prototype.poolingFunction=function(r,o,h,b,T){return on(T),_n(b),mu(r,o,h,b,T,"max")},u.className="MaxPooling1D",u}(Cc);i.serialization.registerClass(Tc);var Ec=function(s){O(u,s);function u(r){return s.call(this,r)||this}return u.prototype.poolingFunction=function(r,o,h,b,T){return on(T),_n(b),mu(r,o,h,b,T,"avg")},u.className="AveragePooling1D",u}(Cc);i.serialization.registerClass(Ec);var Ke=function(s){O(u,s);function u(r){var o=this;if(r.poolSize==null&&(r.poolSize=[2,2]),o=s.call(this,r)||this,o.poolSize=Array.isArray(r.poolSize)?r.poolSize:[r.poolSize,r.poolSize],r.strides==null)o.strides=o.poolSize;else if(Array.isArray(r.strides)){if(r.strides.length!==2)throw new w("If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length "+(r.strides.length+"."));o.strides=r.strides}else o.strides=[r.strides,r.strides];return tr(o.poolSize,"poolSize"),tr(o.strides,"strides"),o.padding=r.padding==null?"valid":r.padding,o.dataFormat=r.dataFormat==null?"channelsLast":r.dataFormat,on(o.dataFormat),_n(o.padding),o.inputSpec=[new An({ndim:4})],o}return u.prototype.computeOutputShape=function(r){r=$r(r);var o=this.dataFormat==="channelsFirst"?r[2]:r[1],h=this.dataFormat==="channelsFirst"?r[3]:r[2];return o=Ii(o,this.poolSize[0],this.padding,this.strides[0]),h=Ii(h,this.poolSize[1],this.padding,this.strides[1]),this.dataFormat==="channelsFirst"?[r[0],r[1],o,h]:[r[0],o,h,r[3]]},u.prototype.call=function(r,o){var h=this;return i.tidy(function(){return h.invokeCallHook(r,o),h.poolingFunction(ur(r),h.poolSize,h.strides,h.padding,h.dataFormat)})},u.prototype.getConfig=function(){var r={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},o=s.prototype.getConfig.call(this);return Object.assign(r,o),r},u}(qr),Rc=function(s){O(u,s);function u(r){return s.call(this,r)||this}return u.prototype.poolingFunction=function(r,o,h,b,T){return on(T),_n(b),mu(r,o,h,b,T,"max")},u.className="MaxPooling2D",u}(Ke);i.serialization.registerClass(Rc);var un=function(s){O(u,s);function u(r){return s.call(this,r)||this}return u.prototype.poolingFunction=function(r,o,h,b,T){return on(T),_n(b),mu(r,o,h,b,T,"avg")},u.className="AveragePooling2D",u}(Ke);i.serialization.registerClass(un);var Ac=function(s){O(u,s);function u(r){var o=this;if(r.poolSize==null&&(r.poolSize=[2,2,2]),o=s.call(this,r)||this,o.poolSize=Array.isArray(r.poolSize)?r.poolSize:[r.poolSize,r.poolSize,r.poolSize],r.strides==null)o.strides=o.poolSize;else if(Array.isArray(r.strides)){if(r.strides.length!==3)throw new w("If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length "+(r.strides.length+"."));o.strides=r.strides}else o.strides=[r.strides,r.strides,r.strides];return tr(o.poolSize,"poolSize"),tr(o.strides,"strides"),o.padding=r.padding==null?"valid":r.padding,o.dataFormat=r.dataFormat==null?"channelsLast":r.dataFormat,on(o.dataFormat),_n(o.padding),o.inputSpec=[new An({ndim:5})],o}return u.prototype.computeOutputShape=function(r){r=$r(r);var o=this.dataFormat==="channelsFirst"?r[2]:r[1],h=this.dataFormat==="channelsFirst"?r[3]:r[2],b=this.dataFormat==="channelsFirst"?r[4]:r[3];return o=Ii(o,this.poolSize[0],this.padding,this.strides[0]),h=Ii(h,this.poolSize[1],this.padding,this.strides[1]),b=Ii(b,this.poolSize[2],this.padding,this.strides[2]),this.dataFormat==="channelsFirst"?[r[0],r[1],o,h,b]:[r[0],o,h,b,r[4]]},u.prototype.call=function(r,o){var h=this;return i.tidy(function(){return h.invokeCallHook(r,o),h.poolingFunction(ur(r),h.poolSize,h.strides,h.padding,h.dataFormat)})},u.prototype.getConfig=function(){var r={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},o=s.prototype.getConfig.call(this);return Object.assign(r,o),r},u}(qr),Ss=function(s){O(u,s);function u(r){return s.call(this,r)||this}return u.prototype.poolingFunction=function(r,o,h,b,T){return on(T),_n(b),Nc(r,o,h,b,T,"max")},u.className="MaxPooling3D",u}(Ac);i.serialization.registerClass(Ss);var Dc=function(s){O(u,s);function u(r){return s.call(this,r)||this}return u.prototype.poolingFunction=function(r,o,h,b,T){return on(T),_n(b),Nc(r,o,h,b,T,"avg")},u.className="AveragePooling3D",u}(Ac);i.serialization.registerClass(Dc);var $n=function(s){O(u,s);function u(r){var o=s.call(this,r)||this;return o.inputSpec=[new An({ndim:3})],o}return u.prototype.computeOutputShape=function(r){return[r[0],r[2]]},u.prototype.call=function(r,o){throw new ge},u}(qr),Fc=function(s){O(u,s);function u(r){return s.call(this,r||{})||this}return u.prototype.call=function(r,o){return i.tidy(function(){var h=ur(r);return i.mean(h,1)})},u.className="GlobalAveragePooling1D",u}($n);i.serialization.registerClass(Fc);var Oc=function(s){O(u,s);function u(r){return s.call(this,r||{})||this}return u.prototype.call=function(r,o){return i.tidy(function(){var h=ur(r);return i.max(h,1)})},u.className="GlobalMaxPooling1D",u}($n);i.serialization.registerClass(Oc);var Mc=function(s){O(u,s);function u(r){var o=s.call(this,r)||this;return o.dataFormat=r.dataFormat==null?"channelsLast":r.dataFormat,on(o.dataFormat),o.inputSpec=[new An({ndim:4})],o}return u.prototype.computeOutputShape=function(r){return r=r,this.dataFormat==="channelsLast"?[r[0],r[3]]:[r[0],r[1]]},u.prototype.call=function(r,o){throw new ge},u.prototype.getConfig=function(){var r={dataFormat:this.dataFormat},o=s.prototype.getConfig.call(this);return Object.assign(r,o),r},u}(qr),js=function(s){O(u,s);function u(){return s!==null&&s.apply(this,arguments)||this}return u.prototype.call=function(r,o){var h=this;return i.tidy(function(){var b=ur(r);return h.dataFormat==="channelsLast"?i.mean(b,[1,2]):i.mean(b,[2,3])})},u.className="GlobalAveragePooling2D",u}(Mc);i.serialization.registerClass(js);var is=function(s){O(u,s);function u(){return s!==null&&s.apply(this,arguments)||this}return u.prototype.call=function(r,o){var h=this;return i.tidy(function(){var b=ur(r);return h.dataFormat==="channelsLast"?i.max(b,[1,2]):i.max(b,[2,3])})},u.className="GlobalMaxPooling2D",u}(Mc);i.serialization.registerClass(is);var Lc=function(s){O(u,s);function u(r){var o=s.call(this,r)||this;return o.layer=r.layer,o}return u.prototype.build=function(r){this.built=!0},Object.defineProperty(u.prototype,"trainable",{get:function(){return this.layer!=null?this.layer.trainable:!1},set:function(r){this.layer!=null&&(this.layer.trainable=r)},enumerable:!0,configurable:!0}),Object.defineProperty(u.prototype,"trainableWeights",{get:function(){return this.layer.trainableWeights},enumerable:!0,configurable:!0}),Object.defineProperty(u.prototype,"nonTrainableWeights",{get:function(){return this.layer.nonTrainableWeights},enumerable:!0,configurable:!0}),Object.defineProperty(u.prototype,"updates",{get:function(){return this.layer._updates},enumerable:!0,configurable:!0}),Object.defineProperty(u.prototype,"losses",{get:function(){return this.layer.losses},enumerable:!0,configurable:!0}),u.prototype.getWeights=function(){return this.layer.getWeights()},u.prototype.setWeights=function(r){this.layer.setWeights(r)},u.prototype.getConfig=function(){var r={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},o=s.prototype.getConfig.call(this);return Object.assign(r,o),r},u.prototype.setFastWeightInitDuringBuild=function(r){s.prototype.setFastWeightInitDuringBuild.call(this,r),this.layer!=null&&this.layer.setFastWeightInitDuringBuild(r)},u.fromConfig=function(r,o,h){h===void 0&&(h={});var b=o.layer,T=oa(b,h);delete o.layer;var M={layer:T};return Object.assign(M,o),new r(M)},u}(qr),zc=function(s){O(u,s);function u(r){var o=s.call(this,r)||this;return o.supportsMasking=!0,o}return u.prototype.build=function(r){if(r=$r(r),r.length<3)throw new w("TimeDistributed layer expects an input shape >= 3D, but received "+("input shape "+JSON.stringify(r)));this.inputSpec=[{shape:r}];var o=[r[0]].concat(r.slice(2));this.layer.built||(this.layer.build(o),this.layer.built=!0),s.prototype.build.call(this,r)},u.prototype.computeOutputShape=function(r){r=$r(r);var o=[r[0]].concat(r.slice(2)),h=this.layer.computeOutputShape(o),b=r[1];return[h[0],b].concat(h.slice(1))},u.prototype.call=function(r,o){var h=this;return i.tidy(function(){r=ur(r);var b=function(q,Y){var le=ur(h.layer.call(q,o));return[le,[]]},T=yc(b,r,[],!1,null,null,!1,!0),M=T[1];return M})},u.className="TimeDistributed",u}(Lc);i.serialization.registerClass(zc);function yu(s){jr(wi,"BidirectionalMergeMode",s)}var Pc="concat",Bu=function(s){O(u,s);function u(r){var o=s.call(this,r)||this,h=r.layer.getConfig(),b={};b.className=r.layer.getClassName(),b.config=h,o.forwardLayer=oa(b),h.goBackwards=!(h.goBackwards===!0);var T={};if(T.className=r.layer.getClassName(),T.config=h,o.backwardLayer=oa(T),o.forwardLayer.name="forward_"+o.forwardLayer.name,o.backwardLayer.name="backward_"+o.backwardLayer.name,o.mergeMode=r.mergeMode===void 0?Pc:r.mergeMode,yu(o.mergeMode),r.weights)throw new ge("weights support is not implemented for Bidirectional layer yet.");return o._stateful=r.layer.stateful,o.returnSequences=r.layer.returnSequences,o.returnState=r.layer.returnState,o.supportsMasking=!0,o._trainable=!0,o.inputSpec=r.layer.inputSpec,o.numConstants=null,o}return Object.defineProperty(u.prototype,"trainable",{get:function(){return this._trainable},set:function(r){this._trainable=r,this.forwardLayer!=null&&(this.forwardLayer.trainable=r),this.backwardLayer!=null&&(this.backwardLayer.trainable=r)},enumerable:!0,configurable:!0}),u.prototype.getWeights=function(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())},u.prototype.setWeights=function(r){var o=r.length,h=Math.floor(o/2);this.forwardLayer.setWeights(r.slice(0,h)),this.backwardLayer.setWeights(r.slice(h))},u.prototype.computeOutputShape=function(r){var o=this.forwardLayer.computeOutputShape(r);Array.isArray(o)&&Array.isArray(o[0])||(o=[o]),o=o;var h,b,T;return this.returnState&&(T=o.slice(1)),h=o[0],h=h,this.mergeMode==="concat"?(h[h.length-1]*=2,b=[h]):this.mergeMode==null?b=[h,h.slice()]:b=[h],this.returnState?this.mergeMode==null?b.concat(T).concat(T.slice()):[h].concat(T).concat(T.slice()):Tt(b)},u.prototype.apply=function(r,o){var h=o==null?null:o.initialState,b=o==null?null:o.constants;o==null&&(o={});var T=mc(r,h,b,this.numConstants);if(r=T.inputs,h=T.initialState,b=T.constants,Array.isArray(r)&&(h=r.slice(1),r=r[0]),(h==null||h.length===0)&&b==null)return s.prototype.apply.call(this,r,o);var M=[],q=[];if(h!=null){var Y=h.length;if(Y%2>0)throw new w("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");o.initialState=h,M.push.apply(M,h);var le=h.map(function(Dt){return new An({shape:Dt.shape})});this.forwardLayer.stateSpec=le.slice(0,Y/2),this.backwardLayer.stateSpec=le.slice(Y/2),q.push.apply(q,le)}if(b!=null)throw new ge("Support for constants in Bidirectional layers is not implemented yet.");for(var Ne=M[0]instanceof ba,We=0,je=M;Weu}var Te=function(s){O(u,s);function u(r){var o=s.call(this)||this;if(r==null&&(r={}),r.restoreBestWeights)throw new ge("restoreBestWeights = True is not implemented in EarlyStopping yet.");return o.monitor=r.monitor||"val_loss",o.minDelta=Math.abs(r.minDelta||0),o.patience=r.patience||0,o.verbose=r.verbose||0,o.mode=r.mode||"auto",o.baseline=r.baseline,["auto","min","max"].indexOf(o.mode)===-1&&(console.warn("EarlyStopping mode '"+o.mode+"' is invalid. Falling back to mode 'auto'."),o.mode="auto"),o.mode==="min"?o.monitorFunc=Ce:o.mode==="max"||o.monitor.indexOf("acc")!==-1?o.monitorFunc=De:o.monitorFunc=Ce,o.monitorFunc===Ce&&(o.minDelta*=-1),o}return u.prototype.onTrainBegin=function(r){return xe(this,void 0,void 0,function(){return Q(this,function(o){return this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===Ce?Infinity:-Infinity,[2]})})},u.prototype.onEpochEnd=function(r,o){return xe(this,void 0,void 0,function(){var h;return Q(this,function(b){switch(b.label){case 0:return[4,oi(o)];case 1:return b.sent(),h=this.getMonitorValue(o),h==null?[2]:(this.monitorFunc(h-this.minDelta,this.best)?(this.best=h,this.wait=0):(this.wait++,this.wait>=this.patience&&(this.stoppedEpoch=r,this.model.stopTraining=!0)),[2])}})})},u.prototype.onTrainEnd=function(r){return xe(this,void 0,void 0,function(){return Q(this,function(o){return this.stoppedEpoch>0&&this.verbose&&console.log("Epoch "+this.stoppedEpoch+": early stopping."),[2]})})},u.prototype.getMonitorValue=function(r){r==null&&(r={});var o=r[this.monitor];return o==null&&console.warn("Metric for EarlyStopping "+this.monitor+" is not available. "+("Available metrics are: "+Object.keys(r))),o},u}(be);function Ge(s){return new Te(s)}var Ze={earlyStopping:Ge};N.Callback=be,N.CallbackList=ao,N.CustomCallback=Co,N.EarlyStopping=Te,N.History=No,N.InputSpec=An,N.LayerVariable=Ga,N.LayersModel=wt,N.RNN=Ni,N.Sequential=Ie,N.SymbolicTensor=ba,N.callbacks=Ze,N.constraints=Gn,N.initializers=xr,N.input=hr,N.layers=$c,N.loadLayersModel=Tr,N.metrics=I,N.model=br,N.models=R,N.registerCallbackConstructor=Dr,N.regularizers=Z,N.sequential=Nr,N.version_layers=gs}),sg=Mr(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});var i=ml(),ke=Object.assign||function(S){for(var x,k=1,K=arguments.length;k0&&we[we.length-1])&&(ft[0]===6||ft[0]===2)){k=0;continue}if(ft[0]===3&&(!we||ft[1]>we[0]&&ft[1]0)&&!(Se=K.next()).done;)we.push(Se.value)}catch(Be){Je={error:Be}}finally{try{Se&&!Se.done&&(k=K.return)&&k.call(K)}finally{if(Je)throw Je.error}}return we}function xe(){for(var S=[],x=0;x0?Object.keys(Wt).forEach(function(Yt){var xr=se(W(Yt),1),Sn=xr[0],pn=vt[Sn];pn&&(pn.signatureKey=Wt[Yt],ft.push(pn))}):ft=we;var wr={};x.library!=null&&x.library.function!=null&&(wr=x.library.function.reduce(function(Yt,xr){return Yt[xr.signature.name]=K.mapFunction(xr),Yt},{}));var Ar={nodes:vt,inputs:ft,outputs:zt,weights:Je,placeholders:we,signature:k,functions:wr};return Be.length>0&&(Ar.initNodes=Be),Ar},S.prototype.mapSignatureEntries=function(x){return Object.keys(x||{}).reduce(function(k,K){return k[x[K].name]=K,k},{})},S.prototype.mapNode=function(x){var k=me(x.op)||this.opMappers[x.op]||{};x.attr==null&&(x.attr={});var K={name:x.name,op:x.op,category:k.category,inputNames:(x.input||[]).map(function(Se){return Se.startsWith("^")?Se.substr(1):Se}),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:x.attr};return k.inputs!=null&&(K.inputParams=k.inputs.reduce(function(Se,we){return Se[we.name]={type:we.type,inputIndexStart:we.start,inputIndexEnd:we.end},Se},{})),k.attrs!=null&&(K.attrParams=k.attrs.reduce(function(Se,we){var Je=we.type,Be=void 0;switch(we.type){case"string":Be=on(x.attr,we.tfName,we.defaultValue),Be===void 0&&!!we.tfDeprecatedName&&(Be=on(x.attr,we.tfDeprecatedName,we.defaultValue));break;case"string[]":Be=ri(x.attr,we.tfName,we.defaultValue),Be===void 0&&!!we.tfDeprecatedName&&(Be=ri(x.attr,we.tfDeprecatedName,we.defaultValue));break;case"number":Be=xa(x.attr,we.tfName,we.defaultValue||0),Be===void 0&&!!we.tfDeprecatedName&&(Be=xa(x.attr,we.tfDeprecatedName,we.defaultValue));break;case"number[]":Be=qn(x.attr,we.tfName,we.defaultValue),Be===void 0&&!!we.tfDeprecatedName&&(Be=qn(x.attr,we.tfDeprecatedName,we.defaultValue));break;case"bool":Be=_n(x.attr,we.tfName,we.defaultValue),Be===void 0&&!!we.tfDeprecatedName&&(Be=_n(x.attr,we.tfDeprecatedName,we.defaultValue));break;case"bool[]":Be=pa(x.attr,we.tfName,we.defaultValue),Be===void 0&&!!we.tfDeprecatedName&&(Be=pa(x.attr,we.tfDeprecatedName,we.defaultValue));break;case"shape":Be=Ai(x.attr,we.tfName,we.defaultValue),Be===void 0&&!!we.tfDeprecatedName&&(Be=Ai(x.attr,we.tfDeprecatedName,we.defaultValue));break;case"shape[]":Be=pi(x.attr,we.tfName,we.defaultValue),Be===void 0&&!!we.tfDeprecatedName&&(Be=pi(x.attr,we.tfDeprecatedName,we.defaultValue));break;case"dtype":Be=_a(x.attr,we.tfName,we.defaultValue),Be===void 0&&!!we.tfDeprecatedName&&(Be=_a(x.attr,we.tfDeprecatedName,we.defaultValue));break;case"dtype[]":Be=Ri(x.attr,we.tfName,we.defaultValue),Be===void 0&&!!we.tfDeprecatedName&&(Be=Ri(x.attr,we.tfDeprecatedName,we.defaultValue));break;case"func":Be=ti(x.attr,we.tfName,we.defaultValue),Be===void 0&&!!we.tfDeprecatedName&&(Be=ti(x.attr,we.tfDeprecatedName,we.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error("Unsupported param type: "+we.type+" for op: "+x.op)}return Se[we.name]={value:Be,type:Je},Se},{})),K},S.prototype.mapFunction=function(x){var k=this,K=x.nodeDef,Se=[],we=[],Je={};K!=null&&(Je=K.reduce(function(Gt,Qt){return Gt[Qt.name]=k.mapNode(Qt),Qt.op==="Const"&&we.push(Gt[Qt.name]),Gt},{}));var Be=[],vt=[];x.signature.inputArg.forEach(function(Gt){var Qt=se(W(Gt.name),1),wr=Qt[0],Ar={name:wr,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:Rr(Gt.type),type:"dtype"}},children:[]};Ar.signatureKey=Gt.name,Be.push(Ar),Je[wr]=Ar});var ft=Object.keys(Je);ft.forEach(function(Gt){var Qt=Je[Gt];Qt.inputNames.forEach(function(wr){var Ar=se(W(wr),1),Yt=Ar[0];Qt.inputs.push(Je[Yt]),Je[Yt].children.push(Qt)})});var zt=x.ret;x.signature.outputArg.forEach(function(Gt){var Qt=se(W(zt[Gt.name]),2),wr=Qt[0],Ar=Qt[1],Yt=Je[wr];Yt!=null&&(Yt.defaultOutput=Ar,vt.push(Yt))});var Wt=this.mapArgsToSignature(x);return{nodes:Je,inputs:Be,outputs:vt,weights:we,placeholders:Se,signature:Wt}},S.prototype.mapArgsToSignature=function(x){var k=this;return{methodName:x.signature.name,inputs:x.signature.inputArg.reduce(function(K,Se){return K[Se.name]=k.mapArgToTensorInfo(Se),K},{}),outputs:x.signature.outputArg.reduce(function(K,Se){return K[Se.name]=k.mapArgToTensorInfo(Se,x.ret),K},{})}},S.prototype.mapArgToTensorInfo=function(x,k){var K=x.name;return k!=null&&(K=k[K]),{name:K,dtype:x.type}},S}();function wi(S){var x=i.env().global;if(typeof x.atob!="undefined")return x.atob(S);if(typeof Buffer!="undefined")return new Buffer(S,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}function Ta(S,x){var k=Array.isArray(S)?String.fromCharCode.apply(null,S):wi(S);return x?k:k.toLowerCase()}function on(S,x,k,K){K===void 0&&(K=!1);var Se=S[x];return Se!=null?Ta(Se.s,K):k}function _n(S,x,k){var K=S[x];return K?K.b:k}function xa(S,x,k){var K=S[x]||{},Se=K.i!=null?K.i:K.f!=null?K.f:k;return typeof Se=="number"?Se:parseInt(Se,10)}function Rr(S){typeof S=="string"&&(S=Q[S]);switch(S){case Q.DT_FLOAT:return"float32";case Q.DT_INT32:case Q.DT_INT64:case Q.DT_INT8:case Q.DT_UINT8:return"int32";case Q.DT_BOOL:return"bool";case Q.DT_DOUBLE:return"float32";case Q.DT_STRING:return"string";default:return null}}function ti(S,x,k){var K=S[x];return K&&K.func?K.func.name:k}function _a(S,x,k){var K=S[x];return K&&K.type?Rr(K.type):k}function Ri(S,x,k){var K=S[x];return K&&K.list&&K.list.type?K.list.type.map(function(Se){return Rr(Se)}):k}function Hi(S){return S.unknownRank?void 0:S.dim!=null?S.dim.map(function(x){return typeof x.size=="number"?x.size:parseInt(x.size,10)}):[]}function Ai(S,x,k){var K=S[x];return K&&K.shape?Hi(K.shape):k}function qn(S,x,k){var K=S[x];return K?((K.list.f&&K.list.f.length?K.list.f:K.list.i)||[]).map(function(Se){return typeof Se=="number"?Se:parseInt(Se,10)}):k}function ri(S,x,k,K){K===void 0&&(K=!1);var Se=S[x];return Se&&Se.list&&Se.list.s?Se.list.s.map(function(we){return Ta(we,K)}):k}function pi(S,x,k){var K=S[x];return K&&K.list&&K.list.shape?K.list.shape.map(function(Se){return Hi(Se)}):k}function pa(S,x,k){var K=S[x];return K&&K.list&&K.list.b?K.list.b:k}var di=function(){function S(x,k,K){var Se=this;this.node=x,this.tensorMap=k,this.context=K,this.inputs=[],this.attrs={},this.inputs=x.inputNames.map(function(we){return Se.getInput(we)}),x.rawAttrs!=null&&(this.attrs=Object.keys(x.rawAttrs).reduce(function(we,Je){return we[Je]=Se.getAttr(Je),we},{}))}return S.prototype.getInput=function(x){return ge(x,this.tensorMap,this.context)},S.prototype.getAttr=function(x,k){var K=this.node.rawAttrs[x];if(K.tensor!=null)return ge(x,this.tensorMap,this.context);if(K.i!=null||K.f!=null)return xa(this.node.rawAttrs,x,k);if(K.s!=null)return on(this.node.rawAttrs,x,k);if(K.b!=null)return _n(this.node.rawAttrs,x,k);if(K.shape!=null)return Ai(this.node.rawAttrs,x,k);if(K.type!=null)return _a(this.node.rawAttrs,x,k);if(K.list!=null){if(K.list.i!=null||K.list.f!=null)return qn(this.node.rawAttrs,x,k);if(K.list.s!=null)return ri(this.node.rawAttrs,x,k);if(K.list.shape!=null)return pi(this.node.rawAttrs,x,k);if(K.list.b!=null)return pa(this.node.rawAttrs,x,k);if(K.list.type!=null)return Ri(this.node.rawAttrs,x,k)}return k},S}(),fi=function(S,x,k){switch(S.op){case"BiasAdd":case"AddV2":case"Add":return[i.add(w("a",S,x,k),w("b",S,x,k))];case"AddN":return[i.addN(w("tensors",S,x,k))];case"FloorMod":case"Mod":return[i.mod(w("a",S,x,k),w("b",S,x,k))];case"Mul":return[i.mul(w("a",S,x,k),w("b",S,x,k))];case"RealDiv":case"Div":return[i.div(w("a",S,x,k),w("b",S,x,k))];case"DivNoNan":return[i.divNoNan(w("a",S,x,k),w("b",S,x,k))];case"FloorDiv":return[i.floorDiv(w("a",S,x,k),w("b",S,x,k))];case"Sub":return[i.sub(w("a",S,x,k),w("b",S,x,k))];case"Minimum":return[i.minimum(w("a",S,x,k),w("b",S,x,k))];case"Maximum":return[i.maximum(w("a",S,x,k),w("b",S,x,k))];case"Pow":return[i.pow(w("a",S,x,k),w("b",S,x,k))];case"SquaredDifference":return[i.squaredDifference(w("a",S,x,k),w("b",S,x,k))];default:throw TypeError("Node type "+S.op+" is not implemented")}},Va=function(S,x,k){switch(S.op){case"Abs":case"ComplexAbs":return[i.abs(w("x",S,x,k))];case"Acos":return[i.acos(w("x",S,x,k))];case"Acosh":return[i.acosh(w("x",S,x,k))];case"Asin":return[i.asin(w("x",S,x,k))];case"Asinh":return[i.asinh(w("x",S,x,k))];case"Atan":return[i.atan(w("x",S,x,k))];case"Atan2":return[i.atan2(w("x",S,x,k),w("y",S,x,k))];case"Atanh":return[i.atanh(w("x",S,x,k))];case"Ceil":return[i.ceil(w("x",S,x,k))];case"Complex":return[i.complex(w("real",S,x,k),w("imag",S,x,k))];case"Cos":return[i.cos(w("x",S,x,k))];case"Cosh":return[i.cosh(w("x",S,x,k))];case"Elu":return[i.elu(w("x",S,x,k))];case"Erf":return[i.erf(w("x",S,x,k))];case"Exp":return[i.exp(w("x",S,x,k))];case"Expm1":return[i.expm1(w("x",S,x,k))];case"Floor":return[i.floor(w("x",S,x,k))];case"Log":return[i.log(w("x",S,x,k))];case"Log1p":return[i.log1p(w("x",S,x,k))];case"Imag":return[i.imag(w("x",S,x,k))];case"Neg":return[i.neg(w("x",S,x,k))];case"Reciprocal":return[i.reciprocal(w("x",S,x,k))];case"Real":return[i.real(w("x",S,x,k))];case"Relu":return[i.relu(w("x",S,x,k))];case"Round":return[i.round(w("x",S,x,k))];case"Selu":return[i.selu(w("x",S,x,k))];case"Sigmoid":return[i.sigmoid(w("x",S,x,k))];case"Sin":return[i.sin(w("x",S,x,k))];case"Sign":return[i.sign(w("x",S,x,k))];case"Sinh":return[i.sinh(w("x",S,x,k))];case"Softplus":return[i.softplus(w("x",S,x,k))];case"Sqrt":return[i.sqrt(w("x",S,x,k))];case"Square":return[i.square(w("x",S,x,k))];case"Tanh":return[i.tanh(w("x",S,x,k))];case"Tan":return[i.tan(w("x",S,x,k))];case"Relu6":case"ClipByValue":return[i.clipByValue(w("x",S,x,k),w("clipValueMin",S,x,k),w("clipValueMax",S,x,k))];case"Rsqrt":return[i.rsqrt(ge(S.inputNames[0],x,k))];case"Prod":return[i.prod(w("x",S,x,k),w("axes",S,x,k))];case"LeakyRelu":return[i.leakyRelu(w("x",S,x,k),w("alpha",S,x,k))];case"Prelu":return[i.prelu(w("x",S,x,k),w("alpha",S,x,k))];default:throw TypeError("Node type "+S.op+" is not implemented")}};function ln(S,x,k){k===void 0&&(k=""),i.util.assert(ni(S,x),function(){return k+(" Shapes "+S+" and "+x+" must match")})}function ni(S,x){if(S.length!==x.length)return!1;for(var k=0;k=this.size())throw new Error("Tried to read from index "+x+", but array size is: "+this.size());var k=this.tensors[x];if(k.cleared)throw new Error("TensorArray "+this.name+": Could not read index "+x+" twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).");return this.clearAfterRead&&(k.cleared=!0),k.read=!0,k.tensor},S.prototype.readMany=function(x){var k=this;return x.map(function(K){return k.read(K)})},S.prototype.write=function(x,k){if(this.closed_)throw new Error("TensorArray "+this.name+" has already been closed.");if(x<0||!this.dynamicSize&&x>=this.maxSize)throw new Error("Tried to write to index "+x+", but array is not resizeable and size is: "+this.maxSize);var K=this.tensors[x]||{};if(k.dtype!==this.dtype)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+x+`, - because the value dtype is `+k.dtype+", but TensorArray dtype is "+this.dtype+".");if(this.size()===0&&(this.elementShape==null||this.elementShape.length===0)&&(this.elementShape=k.shape),ln(this.elementShape,k.shape,"TensorArray "+this.name+": Could not write to TensorArray index "+x+"."),K.read)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+x+", because it has already been read.");if(K.written)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+x+", because it has already been written.");K.tensor=k,i.keep(k),K.written=!0,this.tensors[x]=K},S.prototype.writeMany=function(x,k){var K=this;if(x.length!==k.length)throw new Error("TensorArray "+this.name+": could not write multiple tensors,"+("because the index size: "+x.length+" is not the same as tensors size: "+k.length+"."));x.forEach(function(Se,we){return K.write(Se,k[we])})},S.prototype.gather=function(x,k){if(!!k&&k!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but gather requested dtype "+k);if(x)x=x.slice(0,this.size());else{x=[];for(var K=0;K=this.maxSize)throw new Error("Max index must be < array size ("+K+" vs. "+this.maxSize+")");this.writeMany(x,i.unstack(k,0))},S.prototype.split=function(x,k){var K=this;if(k.dtype!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but tensor has dtype "+k.dtype);var Se=0,we=x.map(function(zt){return Se+=zt,Se});if(Se!==k.shape[0])throw new Error(`Expected sum of lengths to be equal to +// dist/human.esm.js +var Hp = Object.defineProperty; +var eL = (n) => Hp(n, "__esModule", {value: true}); +var we = (n, t) => () => (t || (t = {exports: {}}, n(t.exports, t)), t.exports); +var vs = (n, t) => { + eL(n); + for (var e in t) + Hp(n, e, {get: t[e], enumerable: true}); +}; +var Vp = we(() => { +}); +var Gp = we(() => { +}); +var ws = we(() => { +}); +var ei = we((A) => { + "use strict"; + Object.defineProperty(A, "__esModule", {value: true}); + var uc = function(n, t) { + return uc = Object.setPrototypeOf || {__proto__: []} instanceof Array && function(e, r) { + e.__proto__ = r; + } || function(e, r) { + for (var i in r) + r.hasOwnProperty(i) && (e[i] = r[i]); + }, uc(n, t); + }; + function Yn(n, t) { + uc(n, t); + function e() { + this.constructor = n; + } + n.prototype = t === null ? Object.create(t) : (e.prototype = t.prototype, new e()); + } + function pe(n, t, e, r) { + return new (e || (e = Promise))(function(i, a) { + function s(l) { + try { + c(r.next(l)); + } catch (u) { + a(u); + } + } + function o(l) { + try { + c(r.throw(l)); + } catch (u) { + a(u); + } + } + function c(l) { + l.done ? i(l.value) : new e(function(u) { + u(l.value); + }).then(s, o); + } + c((r = r.apply(n, t || [])).next()); + }); + } + function fe(n, t) { + var e = {label: 0, sent: function() { + if (a[0] & 1) + throw a[1]; + return a[1]; + }, trys: [], ops: []}, r, i, a, s; + return s = {next: o(0), throw: o(1), return: o(2)}, typeof Symbol == "function" && (s[Symbol.iterator] = function() { + return this; + }), s; + function o(l) { + return function(u) { + return c([l, u]); + }; + } + function c(l) { + if (r) + throw new TypeError("Generator is already executing."); + for (; e; ) + try { + if (r = 1, i && (a = l[0] & 2 ? i.return : l[0] ? i.throw || ((a = i.return) && a.call(i), 0) : i.next) && !(a = a.call(i, l[1])).done) + return a; + (i = 0, a) && (l = [l[0] & 2, a.value]); + switch (l[0]) { + case 0: + case 1: + a = l; + break; + case 4: + return e.label++, {value: l[1], done: false}; + case 5: + e.label++, i = l[1], l = [0]; + continue; + case 7: + l = e.ops.pop(), e.trys.pop(); + continue; + default: + if (!(a = e.trys, a = a.length > 0 && a[a.length - 1]) && (l[0] === 6 || l[0] === 2)) { + e = 0; + continue; + } + if (l[0] === 3 && (!a || l[1] > a[0] && l[1] < a[3])) { + e.label = l[1]; + break; + } + if (l[0] === 6 && e.label < a[1]) { + e.label = a[1], a = l; + break; + } + if (a && e.label < a[2]) { + e.label = a[2], e.ops.push(l); + break; + } + a[2] && e.ops.pop(), e.trys.pop(); + continue; + } + l = t.call(n, e); + } catch (u) { + l = [6, u], i = 0; + } finally { + r = a = 0; + } + if (l[0] & 5) + throw l[1]; + return {value: l[0] ? l[1] : void 0, done: true}; + } + } + var tL = 1e-7, nL = 1e-4, rL = function() { + function n(t, e) { + this.backend = t, this.dataMover = e, this.data = new WeakMap(), this.dataIdsCount = 0; + } + return n.prototype.get = function(t) { + return this.data.has(t) || this.dataMover.moveData(this.backend, t), this.data.get(t); + }, n.prototype.set = function(t, e) { + this.dataIdsCount++, this.data.set(t, e); + }, n.prototype.has = function(t) { + return this.data.has(t); + }, n.prototype.delete = function(t) { + return this.dataIdsCount--, this.data.delete(t); + }, n.prototype.numDataIds = function() { + return this.dataIdsCount; + }, n; + }(), qp = function() { + function n() { + } + return n.prototype.time = function(t) { + return X("time"); + }, n.prototype.read = function(t) { + return X("read"); + }, n.prototype.readSync = function(t) { + return X("readSync"); + }, n.prototype.numDataIds = function() { + return X("numDataIds"); + }, n.prototype.disposeData = function(t) { + return X("disposeData"); + }, n.prototype.write = function(t, e, r) { + return X("write"); + }, n.prototype.move = function(t, e, r, i) { + return X("move"); + }, n.prototype.memory = function() { + return X("memory"); + }, n.prototype.floatPrecision = function() { + return X("floatPrecision"); + }, n.prototype.epsilon = function() { + return this.floatPrecision() === 32 ? tL : nL; + }, n.prototype.batchMatMul = function(t, e, r, i) { + return X("batchMatMul"); + }, n.prototype.fusedBatchMatMul = function(t) { + var e = t.a, r = t.b, i = t.transposeA, a = t.transposeB, s = t.bias, o = t.activation, c = t.preluActivationWeights; + return X("fusedBatchMatMul"); + }, n.prototype.slice = function(t, e, r) { + return X("slice"); + }, n.prototype.stridedSlice = function(t, e, r, i) { + return X("stridedSlice"); + }, n.prototype.unstack = function(t, e) { + return X("unstack"); + }, n.prototype.reverse = function(t, e) { + return X("reverse"); + }, n.prototype.concat = function(t, e) { + return X("concat"); + }, n.prototype.neg = function(t) { + return X("neg"); + }, n.prototype.add = function(t, e) { + return X("add"); + }, n.prototype.addN = function(t) { + return X("addN"); + }, n.prototype.subtract = function(t, e) { + return X("subtract"); + }, n.prototype.multiply = function(t, e) { + return X("multiply"); + }, n.prototype.realDivide = function(t, e) { + return X("realDivide"); + }, n.prototype.floorDiv = function(t, e) { + return X("floorDiv"); + }, n.prototype.sum = function(t, e) { + return X("sum"); + }, n.prototype.prod = function(t, e) { + return X("prod"); + }, n.prototype.unsortedSegmentSum = function(t, e, r) { + return X("unsortedSegmentSum"); + }, n.prototype.argMin = function(t, e) { + return X("argMin"); + }, n.prototype.argMax = function(t, e) { + return X("argMax"); + }, n.prototype.equal = function(t, e) { + return X("equal"); + }, n.prototype.notEqual = function(t, e) { + return X("notEqual"); + }, n.prototype.less = function(t, e) { + return X("less"); + }, n.prototype.lessEqual = function(t, e) { + return X("lessEqual"); + }, n.prototype.greater = function(t, e) { + return X("greater"); + }, n.prototype.greaterEqual = function(t, e) { + return X("greaterEqual"); + }, n.prototype.logicalNot = function(t) { + return X("logicalNot"); + }, n.prototype.logicalAnd = function(t, e) { + return X("logicalAnd"); + }, n.prototype.logicalOr = function(t, e) { + return X("logicalOr"); + }, n.prototype.where = function(t) { + return X("where"); + }, n.prototype.select = function(t, e, r) { + return X("select"); + }, n.prototype.topk = function(t, e, r) { + return X("topk"); + }, n.prototype.min = function(t, e) { + return X("min"); + }, n.prototype.minimum = function(t, e) { + return X("minimum"); + }, n.prototype.mod = function(t, e) { + return X("mod"); + }, n.prototype.max = function(t, e) { + return X("max"); + }, n.prototype.maximum = function(t, e) { + return X("maximum"); + }, n.prototype.all = function(t, e) { + return X("all"); + }, n.prototype.any = function(t, e) { + return X("any"); + }, n.prototype.squaredDifference = function(t, e) { + return X("squaredDifference"); + }, n.prototype.ceil = function(t) { + return X("ceil"); + }, n.prototype.floor = function(t) { + return X("floor"); + }, n.prototype.round = function(t) { + return X("round"); + }, n.prototype.sign = function(t) { + return X("sign"); + }, n.prototype.isNaN = function(t) { + return X("isNaN"); + }, n.prototype.isInf = function(t) { + return X("isInf"); + }, n.prototype.isFinite = function(t) { + return X("isFinite"); + }, n.prototype.pow = function(t, e) { + return X("pow"); + }, n.prototype.exp = function(t) { + return X("exp"); + }, n.prototype.expm1 = function(t) { + return X("expm1"); + }, n.prototype.softmax = function(t, e) { + return X("softmax"); + }, n.prototype.log = function(t) { + return X("log"); + }, n.prototype.log1p = function(t) { + return X("log1p"); + }, n.prototype.sqrt = function(t) { + return X("sqrt"); + }, n.prototype.rsqrt = function(t) { + return X("rsqrt"); + }, n.prototype.square = function(t) { + return X("square"); + }, n.prototype.reciprocal = function(t) { + return X("reciprocal"); + }, n.prototype.relu = function(t) { + return X("relu"); + }, n.prototype.relu6 = function(t) { + return X("relu6"); + }, n.prototype.prelu = function(t, e) { + return X("prelu"); + }, n.prototype.elu = function(t) { + return X("elu"); + }, n.prototype.eluDer = function(t, e) { + return X("eluDer"); + }, n.prototype.selu = function(t) { + return X("selu"); + }, n.prototype.int = function(t) { + return X("int"); + }, n.prototype.clip = function(t, e, r) { + return X("clip"); + }, n.prototype.abs = function(t) { + return X("abs"); + }, n.prototype.complexAbs = function(t) { + return X("complexAbs"); + }, n.prototype.sigmoid = function(t) { + return X("sigmoid"); + }, n.prototype.softplus = function(t) { + return X("softplus"); + }, n.prototype.sin = function(t) { + return X("sin"); + }, n.prototype.cos = function(t) { + return X("cos"); + }, n.prototype.tan = function(t) { + return X("tan"); + }, n.prototype.asin = function(t) { + return X("asin"); + }, n.prototype.acos = function(t) { + return X("acos"); + }, n.prototype.atan = function(t) { + return X("atan"); + }, n.prototype.atan2 = function(t, e) { + return X("atan2"); + }, n.prototype.sinh = function(t) { + return X("sinh"); + }, n.prototype.cosh = function(t) { + return X("cosh"); + }, n.prototype.tanh = function(t) { + return X("tanh"); + }, n.prototype.asinh = function(t) { + return X("asinh"); + }, n.prototype.acosh = function(t) { + return X("acosh"); + }, n.prototype.atanh = function(t) { + return X("atanh"); + }, n.prototype.erf = function(t) { + return X("erf"); + }, n.prototype.step = function(t, e) { + return X("step"); + }, n.prototype.fusedConv2d = function(t) { + var e = t.input, r = t.filter, i = t.convInfo, a = t.bias, s = t.activation, o = t.preluActivationWeights; + return X("fusedConv2d"); + }, n.prototype.conv2d = function(t, e, r) { + return X("conv2d"); + }, n.prototype.conv2dDerInput = function(t, e, r) { + return X("conv2dDerInput"); + }, n.prototype.conv2dDerFilter = function(t, e, r) { + return X("conv2dDerFilter"); + }, n.prototype.fusedDepthwiseConv2D = function(t) { + var e = t.input, r = t.filter, i = t.convInfo, a = t.bias, s = t.activation, o = t.preluActivationWeights; + return X("fusedDepthwiseConv2D"); + }, n.prototype.depthwiseConv2D = function(t, e, r) { + return X("depthwiseConv2D"); + }, n.prototype.depthwiseConv2DDerInput = function(t, e, r) { + return X("depthwiseConv2DDerInput"); + }, n.prototype.depthwiseConv2DDerFilter = function(t, e, r) { + return X("depthwiseConv2DDerFilter"); + }, n.prototype.conv3d = function(t, e, r) { + return X("conv3d"); + }, n.prototype.conv3dDerInput = function(t, e, r) { + return X("conv3dDerInput"); + }, n.prototype.conv3dDerFilter = function(t, e, r) { + return X("conv3dDerFilter"); + }, n.prototype.maxPool = function(t, e) { + return X("maxPool"); + }, n.prototype.maxPoolBackprop = function(t, e, r, i) { + return X("maxPoolBackprop"); + }, n.prototype.avgPool = function(t, e) { + return X("avgPool"); + }, n.prototype.avgPoolBackprop = function(t, e, r) { + return X("avgPoolBackprop"); + }, n.prototype.avgPool3d = function(t, e) { + return X("avgPool3d"); + }, n.prototype.avgPool3dBackprop = function(t, e, r) { + return X("avgPool3dBackprop"); + }, n.prototype.maxPool3d = function(t, e) { + return X("maxPool3d"); + }, n.prototype.maxPool3dBackprop = function(t, e, r, i) { + return X("maxPool3dBackprop"); + }, n.prototype.reshape = function(t, e) { + return X("reshape"); + }, n.prototype.cast = function(t, e) { + return X("cast"); + }, n.prototype.tile = function(t, e) { + return X("tile"); + }, n.prototype.pad = function(t, e, r) { + return X("pad"); + }, n.prototype.transpose = function(t, e) { + return X("transpose"); + }, n.prototype.gather = function(t, e, r) { + return X("gather"); + }, n.prototype.gatherND = function(t, e) { + return X("gatherND"); + }, n.prototype.scatterND = function(t, e, r) { + return X("scatterND"); + }, n.prototype.batchToSpaceND = function(t, e, r) { + return X("batchToSpaceND"); + }, n.prototype.spaceToBatchND = function(t, e, r) { + return X("spaceToBatchND"); + }, n.prototype.resizeBilinear = function(t, e, r, i) { + return X("resizeBilinear"); + }, n.prototype.resizeBilinearBackprop = function(t, e, r) { + return X("resizeBilinearBackprop"); + }, n.prototype.resizeNearestNeighbor = function(t, e, r, i) { + return X("resizeNearestNeighbor"); + }, n.prototype.resizeNearestNeighborBackprop = function(t, e, r) { + return X("resizeNearestNeighborBackprop"); + }, n.prototype.batchNorm = function(t, e, r, i, a, s) { + return X("batchNorm"); + }, n.prototype.localResponseNormalization4D = function(t, e, r, i, a) { + return X("localResponseNormalization4D"); + }, n.prototype.LRNGrad = function(t, e, r, i, a, s, o) { + return X("LRNGrad"); + }, n.prototype.multinomial = function(t, e, r, i) { + return X("multinomial"); + }, n.prototype.oneHot = function(t, e, r, i) { + return X("oneHot"); + }, n.prototype.cumsum = function(t, e, r, i) { + return X("cumsum"); + }, n.prototype.nonMaxSuppression = function(t, e, r, i, a) { + return X("nonMaxSuppression"); + }, n.prototype.fft = function(t) { + return X("fft"); + }, n.prototype.ifft = function(t) { + return X("ifft"); + }, n.prototype.complex = function(t, e) { + return X("complex"); + }, n.prototype.real = function(t) { + return X("real"); + }, n.prototype.imag = function(t) { + return X("imag"); + }, n.prototype.cropAndResize = function(t, e, r, i, a, s) { + return X("cropAndResize"); + }, n.prototype.depthToSpace = function(t, e, r) { + return X("depthToSpace"); + }, n.prototype.split = function(t, e, r) { + return X("split"); + }, n.prototype.sparseToDense = function(t, e, r, i) { + return X("sparseToDense"); + }, n.prototype.diag = function(t) { + return X("diag"); + }, n.prototype.fill = function(t, e, r) { + return X("fill"); + }, n.prototype.onesLike = function(t) { + return X("onesLike"); + }, n.prototype.zerosLike = function(t) { + return X("zerosLike"); + }, n.prototype.linspace = function(t, e, r) { + return X("linspace"); + }, n.prototype.dispose = function() { + return X("dispose"); + }, n; + }(); + function X(n) { + throw new Error("'" + n + "' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen"); + } + function Yp(n) { + for (var t = n.length, e = 0, r = 0; t > 0; ) + r = Math.random() * t | 0, t--, e = n[t], n[t] = n[r], n[r] = e; + } + function ga(n, t, e) { + return Math.max(n, Math.min(t, e)); + } + function iL(n) { + return n % 2 === 0 ? n : n + 1; + } + function aL(n) { + for (var t = 0, e = 0; e < n.length; e++) + t += n[e]; + return t; + } + function sL(n, t) { + var e = Math.random(); + return t * e + (1 - e) * n; + } + function oL(n, t) { + for (var e = 0, r = 0; r < n.length; r++) { + var i = Number(n[r]) - Number(t[r]); + e += i * i; + } + return e; + } + function E(n, t) { + if (!n) + throw new Error(typeof t == "string" ? t : t()); + } + function Pe(n, t, e) { + e === void 0 && (e = ""), E(pn(n, t), function() { + return e + (" Shapes " + n + " and " + t + " must match"); + }); + } + function Br(n) { + E(n != null, function() { + return "The input to the tensor constructor must be a non-null value."; + }); + } + function zr(n, t, e) { + if (t === void 0 && (t = []), e === void 0 && (e = false), t == null && (t = []), Array.isArray(n) || Ft(n) && !e) + for (var r = 0; r < n.length; ++r) + zr(n[r], t, e); + else + t.push(n); + return t; + } + function dt(n) { + if (n.length === 0) + return 1; + for (var t = n[0], e = 1; e < n.length; e++) + t *= n[e]; + return t; + } + function cL(n) { + return n.length === 0; + } + function pn(n, t) { + if (n === t) + return true; + if (n == null || t == null) + return false; + if (n.length !== t.length) + return false; + for (var e = 0; e < n.length; e++) + if (n[e] !== t[e]) + return false; + return true; + } + function ot(n) { + return n % 1 === 0; + } + function lL(n) { + if (Math.tanh != null) + return Math.tanh(n); + if (n === Infinity) + return 1; + if (n === -Infinity) + return -1; + var t = Math.exp(2 * n); + return (t - 1) / (t + 1); + } + function uL(n) { + var t = Math.ceil(Math.sqrt(n)); + return [t, Math.ceil(n / t)]; + } + function hL(n) { + for (var t = new Uint32Array(n), e = 0; e < n; ++e) + t[e] = e; + return Yp(t), t; + } + function ya(n, t) { + return t <= n.length ? n : n + " ".repeat(t - n.length); + } + function dL(n, t, e) { + return t === void 0 && (t = function(r) { + return 0; + }), new Promise(function(r, i) { + var a = 0, s = function() { + if (n()) { + r(); + return; + } + a++; + var o = t(a); + if (e != null && a >= e) { + i(); + return; + } + setTimeout(s, o); + }; + s(); + }); + } + function Kp(n, t) { + for (var e = 1, r = -1, i = 0; i < n.length; ++i) + if (n[i] >= 0) + e *= n[i]; + else if (n[i] === -1) { + if (r !== -1) + throw Error("Shapes can only have 1 implicit size. " + ("Found -1 at dim " + r + " and dim " + i)); + r = i; + } else if (n[i] < 0) + throw Error("Shapes can not be < 0. Found " + n[i] + " at dim " + i); + if (r === -1) { + if (t > 0 && t !== e) + throw Error("Size(" + t + ") must match the product of shape " + n); + return n; + } + if (e === 0) + throw Error("Cannot infer the missing size in [" + n + "] when there are 0 elements"); + if (t % e !== 0) + throw Error("The implicit shape can't be a fractional number. " + ("Got " + t + " / " + e)); + var a = n.slice(); + return a[r] = t / e, a; + } + function rt(n, t) { + var e = t.length; + return n = n == null ? t.map(function(r, i) { + return i; + }) : [].concat(n), E(n.every(function(r) { + return r >= -e && r < e; + }), function() { + return "All values in axis param must be in range [-" + e + ", " + e + ") but " + ("got axis " + n); + }), E(n.every(function(r) { + return ot(r); + }), function() { + return "All values in axis param must be integers but " + ("got axis " + n); + }), n.map(function(r) { + return r < 0 ? e + r : r; + }); + } + function jp(n, t) { + for (var e = [], r = [], i = t != null && Array.isArray(t) && t.length === 0, a = t == null || i ? null : rt(t, n).sort(), s = 0, o = 0; o < n.length; ++o) { + if (a != null) { + if (a[s] === o && n[o] !== 1) + throw new Error("Can't squeeze axis " + o + " since its dim '" + n[o] + "' is not 1"); + (a[s] == null || a[s] > o) && n[o] === 1 && (e.push(n[o]), r.push(o)), a[s] <= o && s++; + } + n[o] !== 1 && (e.push(n[o]), r.push(o)); + } + return {newShape: e, keptDims: r}; + } + function bs(n, t) { + var e = null; + if (n == null || n === "float32") + e = new Float32Array(t); + else if (n === "int32") + e = new Int32Array(t); + else if (n === "bool") + e = new Uint8Array(t); + else + throw new Error("Unknown data type " + n); + return e; + } + function $p(n, t) { + var e = null; + if (n == null || n === "float32") + e = new Float32Array(t); + else if (n === "int32") + e = new Int32Array(t); + else if (n === "bool") + e = new Uint8Array(t); + else if (n === "string") + e = new Array(t); + else + throw new Error("Unknown data type " + n); + return e; + } + function Xp(n, t) { + for (var e = 0; e < n.length; e++) { + var r = n[e]; + if (isNaN(r) || !isFinite(r)) + throw Error("A tensor of type " + t + " being uploaded contains " + r + "."); + } + } + function Jp(n) { + return n === "bool" || n === "complex64" || n === "float32" || n === "int32" || n === "string"; + } + function Zp(n, t) { + return t === "complex64" || (t === "float32" && n !== "complex64" || t === "int32" && n !== "float32" && n !== "complex64") ? false : !(t === "bool" && n === "bool"); + } + function Ft(n) { + return n instanceof Float32Array || n instanceof Int32Array || n instanceof Uint8Array; + } + function Qp(n) { + if (n === "float32" || n === "int32") + return 4; + if (n === "complex64") + return 8; + if (n === "bool") + return 1; + throw new Error("Unknown dtype " + n); + } + function ef(n) { + if (n == null) + return 0; + var t = 0; + return n.forEach(function(e) { + return t += e.length; + }), t; + } + function lr(n) { + return typeof n == "string" || n instanceof String; + } + function tf(n) { + return typeof n == "boolean"; + } + function nf(n) { + return typeof n == "number"; + } + function xs(n) { + return Array.isArray(n) ? xs(n[0]) : n instanceof Float32Array ? "float32" : n instanceof Int32Array || n instanceof Uint8Array ? "int32" : nf(n) ? "float32" : lr(n) ? "string" : tf(n) ? "bool" : "float32"; + } + function ur(n) { + return !!(n && n.constructor && n.call && n.apply); + } + function Ls(n, t) { + for (var e = t; e < n; ++e) + if (n % e === 0) + return e; + return n; + } + function xi(n) { + var t = n.length; + if (t < 2) + return []; + var e = new Array(t - 1); + e[t - 2] = n[t - 1]; + for (var r = t - 3; r >= 0; --r) + e[r] = e[r + 1] * n[r + 1]; + return e; + } + function rf(n, t, e) { + var r = new Array(); + if (t.length === 1) + for (var i = t[0], a = 0; a < i; a++) + r[a] = e[n + a]; + else + for (var i = t[0], s = t.slice(1), o = s.reduce(function(l, u) { + return l * u; + }), a = 0; a < i; a++) + r[a] = rf(n + a * o, s, e); + return r; + } + function Li(n, t) { + if (n.length === 0) + return t[0]; + var e = n.reduce(function(r, i) { + return r * i; + }); + if (e === 0) + return []; + if (e !== t.length) + throw new Error("[" + n + "] does not match the input size " + t.length + "."); + return rf(0, n, t); + } + function hc(n, t) { + for (var e = Si(n, t), r = 0; r < e.length; r++) + e[r] = 1; + return e; + } + function Si(n, t) { + if (t == null || t === "float32" || t === "complex64") + return new Float32Array(n); + if (t === "int32") + return new Int32Array(n); + if (t === "bool") + return new Uint8Array(n); + throw new Error("Unknown data type " + t); + } + function pL(n, t) { + var e = n.reduce(function(r, i) { + return r * i; + }, 1); + if (t == null || t === "float32") + return Li(n, new Float32Array(e)); + if (t === "int32") + return Li(n, new Int32Array(e)); + if (t === "bool") + return Li(n, new Uint8Array(e)); + throw new Error("Unknown data type " + t); + } + function dc(n) { + n.forEach(function(t) { + E(Number.isInteger(t) && t >= 0, function() { + return "Tensor must have a shape comprised of positive integers but got " + ("shape [" + n + "]."); + }); + }); + } + function fL(n, t, e) { + if (t === 0) + return 0; + if (t === 1) + return n[0]; + for (var r = n[n.length - 1], i = 0; i < n.length - 1; ++i) + r += e[i] * n[i]; + return r; + } + function mL(n, t, e) { + if (t === 0) + return []; + if (t === 1) + return [n]; + for (var r = new Array(t), i = 0; i < r.length - 1; ++i) + r[i] = Math.floor(n / e[i]), n -= r[i] * e[i]; + return r[r.length - 1] = n, r; + } + function pc(n) { + return n && n.then && typeof n.then == "function"; + } + var af = "tfjsflags", sf = function() { + function n(t) { + this.global = t, this.flags = {}, this.flagRegistry = {}, this.urlFlags = {}, this.populateURLFlags(); + } + return n.prototype.setPlatform = function(t, e) { + this.platform != null && console.warn("Platform " + this.platformName + " has already been set. " + ("Overwriting the platform with " + e + ".")), this.platformName = t, this.platform = e; + }, n.prototype.registerFlag = function(t, e, r) { + if (this.flagRegistry[t] = {evaluationFn: e, setHook: r}, this.urlFlags[t] != null) { + var i = this.urlFlags[t]; + console.warn("Setting feature override from URL " + t + ": " + i + "."), this.set(t, i); + } + }, n.prototype.getAsync = function(t) { + return pe(this, void 0, void 0, function() { + var e, r; + return fe(this, function(i) { + switch (i.label) { + case 0: + return t in this.flags ? [2, this.flags[t]] : (e = this.flags, r = t, [4, this.evaluateFlag(t)]); + case 1: + return e[r] = i.sent(), [2, this.flags[t]]; + } + }); + }); + }, n.prototype.get = function(t) { + if (t in this.flags) + return this.flags[t]; + var e = this.evaluateFlag(t); + if (pc(e)) + throw new Error("Flag " + t + " cannot be synchronously evaluated. Please use getAsync() instead."); + return this.flags[t] = e, this.flags[t]; + }, n.prototype.getNumber = function(t) { + return this.get(t); + }, n.prototype.getBool = function(t) { + return this.get(t); + }, n.prototype.getFlags = function() { + return this.flags; + }, Object.defineProperty(n.prototype, "features", {get: function() { + return this.flags; + }, enumerable: true, configurable: true}), n.prototype.set = function(t, e) { + if (this.flagRegistry[t] == null) + throw new Error("Cannot set flag " + t + " as it has not been registered."); + this.flags[t] = e, this.flagRegistry[t].setHook != null && this.flagRegistry[t].setHook(e); + }, n.prototype.evaluateFlag = function(t) { + if (this.flagRegistry[t] == null) + throw new Error("Cannot evaluate flag '" + t + "': no evaluation function found."); + return this.flagRegistry[t].evaluationFn(); + }, n.prototype.setFlags = function(t) { + this.flags = Object.assign({}, t); + }, n.prototype.reset = function() { + this.flags = {}, this.urlFlags = {}, this.populateURLFlags(); + }, n.prototype.populateURLFlags = function() { + var t = this; + if (typeof this.global == "undefined" || typeof this.global.location == "undefined" || typeof this.global.location.search == "undefined") + return; + var e = gL(this.global.location.search); + if (af in e) { + var r = e[af].split(","); + r.forEach(function(i) { + var a = i.split(":"), s = a[0], o = a[1]; + t.urlFlags[s] = yL(s, o); + }); + } + }, n; + }(); + function gL(n) { + var t = {}; + return n.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g, function(e) { + for (var r = [], i = 1; i < arguments.length; i++) + r[i - 1] = arguments[i]; + return vL(t, r[0], r[1]), r.join("="); + }), t; + } + function vL(n, t, e) { + n[decodeURIComponent(t)] = decodeURIComponent(e || ""); + } + function yL(n, t) { + if (t = t.toLowerCase(), t === "true" || t === "false") + return t === "true"; + if ("" + +t === t) + return +t; + throw new Error("Could not parse value flag value " + t + " for flag " + n + "."); + } + function qe() { + return A.ENV; + } + A.ENV = null; + function wL(n) { + A.ENV = n; + } + var fc; + function of() { + if (fc == null) { + var n = void 0; + if (typeof window != "undefined") + n = window; + else if (typeof global != "undefined") + n = global; + else if (typeof process != "undefined") + n = process; + else if (typeof self != "undefined") + n = self; + else + throw new Error("Could not find a global object"); + fc = n; + } + return fc; + } + function bL() { + var n = of(); + return n._tfGlobals == null && (n._tfGlobals = new Map()), n._tfGlobals; + } + function cf(n, t) { + var e = bL(); + if (e.has(n)) + return e.get(n); + var r = t(); + return e.set(n, r), e.get(n); + } + var mc = "Abs", gc = "Acos", yc = "Acosh", Ss = "Add", vc = "AddN", lf = "All", uf = "Any", wc = "ArgMax", bc = "ArgMin", xc = "Asin", Lc = "Asinh", Sc = "Atan", Ic = "Atanh", Ac = "Atan2", Tc = "AvgPool", hf = "AvgPoolBackprop", Nc = "AvgPool3D", df = "AvgPool3DBackprop", _c = "BatchMatMul", Cc = "BatchToSpaceND", Rc = "BroadcastTo", Is = "Cast", Oc = "Ceil", Ec = "ClipByValue", pf = "Complex", Dc = "Concat", kc = "Conv2D", ff = "Conv2DBackpropFilter", Fc = "Conv2DBackpropInput", Wc = "Conv3D", mf = "Conv3DBackpropFilterV2", gf = "Conv3DBackpropInputV2", Uc = "Cos", Bc = "Cosh", zc = "Cumsum", yf = "CropAndResize", vf = "DepthToSpace", Pc = "DepthwiseConv2dNative", wf = "DepthwiseConv2dNativeBackpropFilter", bf = "DepthwiseConv2dNativeBackpropInput", xf = "Diag", Mc = "Dilation2D", Lf = "Dilation2DBackpropInput", Sf = "Dilation2DBackpropFilter", Hc = "Div", Vc = "Elu", If = "EluGrad", Gc = "Erf", Af = "Equal", qc = "Exp", Yc = "Expm1", Tf = "FFT", Nf = "Fill", _f = "FlipLeftRight", Kc = "Floor", jc = "FloorDiv", $c = "FusedBatchNorm", Xc = "GatherV2", Cf = "GatherNd", Rf = "Greater", Jc = "GreaterEqual", Zc = "Identity", Of = "IFFT", Ef = "Imag", Qc = "IsFinite", el = "IsInf", tl = "IsNan", Df = "Less", kf = "LessEqual", Ff = "LinSpace", nl = "Log", rl = "Log1p", Wf = "LogicalAnd", Uf = "LogicalNot", Bf = "LogicalOr", il = "LogSoftmax", al = "LRN", zf = "LRNBackprop", sl = "Max", ol = "Maximum", cl = "MaxPool", Pf = "MaxPoolBackprop", ll = "MaxPool3D", Mf = "MaxPool3DBackprop", Hf = "MaxPoolWithArgmax", Vf = "Mean", ul = "Min", hl = "Minimum", dl = "MirrorPad", pl = "Mod", fl = "Multiply", ml = "Negate", Gf = "NotEqual", qf = "NonMaxSuppressionV3", Yf = "NonMaxSuppressionV4", Kf = "NonMaxSuppressionV5", gl = "OnesLike", yl = "OneHot", vl = "PadV2", xL = "Pool", wl = "Pow", bl = "Prelu", jf = "Prod", $f = "Range", Xf = "Real", xl = "Reciprocal", Ll = "Relu", Sl = "Reshape", Il = "ResizeNearestNeighbor", Jf = "ResizeNearestNeighborGrad", Al = "ResizeBilinear", Zf = "ResizeBilinearGrad", Tl = "Relu6", Nl = "Reverse", _l = "Round", Cl = "Rsqrt", Qf = "ScatterNd", Rl = "SelectV2", Ol = "Selu", El = "Slice", Dl = "Sin", kl = "Sinh", Fl = "Sign", Wl = "Sigmoid", Ul = "Softplus", Bl = "Sqrt", zl = "Sum", Pl = "SpaceToBatchND", Ml = "SplitV", Hl = "Softmax", Vl = "SquaredDifference", em = "Square", Gl = "Sub", tm = "SparseToDense", nm = "StridedSlice", ql = "Tan", Yl = "Tanh", Kl = "Tile", rm = "TopK", jl = "Transpose", im = "Unique", $l = "Unpack", Xl = "UnsortedSegmentSum", Jl = "ZerosLike", Zl = "Step", Ql = "FromPixels", am = "RotateWithOffset", eu = "_FusedMatMul", tu = "FusedConv2D", nu = "FusedDepthwiseConv2D"; + var Ii = cf("kernelRegistry", function() { + return new Map(); + }), va = cf("gradRegistry", function() { + return new Map(); + }); + function iu(n, t) { + var e = ru(n, t); + return Ii.get(e); + } + function au(n) { + return va.get(n); + } + function As(n) { + for (var t = Ii.entries(), e = []; ; ) { + var r = t.next(), i = r.done, a = r.value; + if (i) + break; + var s = a[0], o = a[1], c = s.split("_")[0]; + c === n && e.push(o); + } + return e; + } + function sm(n) { + var t = n.kernelName, e = n.backendName, r = ru(t, e); + Ii.has(r) && console.warn("The kernel '" + t + "' for backend " + ("'" + e + "' is already registered")), Ii.set(r, n); + } + function om(n) { + var t = n.kernelName; + va.has(t) && (qe().getBool("DEBUG") && console.warn("Overriding the gradient for '" + t + "'")), va.set(t, n); + } + function LL(n, t) { + var e = ru(n, t); + if (!Ii.has(e)) + throw new Error("The kernel '" + n + "' for backend " + ("'" + t + "' is not registered")); + Ii.delete(e); + } + function SL(n) { + if (!va.has(n)) + throw new Error("The gradient '" + n + "' for backend is not registered"); + va.delete(n); + } + function IL(n, t) { + var e = As(n); + e.forEach(function(r) { + var i = Object.assign({}, r, {backendName: t}); + sm(i); + }); + } + function ru(n, t) { + return t + "_" + n; + } + function AL(n, t) { + return t === "string" ? su(n) : Ts([n], t); + } + function TL(n, t) { + return n instanceof Float32Array && t === "float32" || n instanceof Int32Array && t === "int32" || n instanceof Uint8Array && t === "bool"; + } + function Ts(n, t) { + if (t === "string") + throw new Error("Cannot convert a string[] to a TypedArray"); + if (Array.isArray(n) && (n = zr(n)), qe().getBool("DEBUG") && Xp(n, t), TL(n, t)) + return n; + if (t == null || t === "float32" || t === "complex64") + return new Float32Array(n); + if (t === "int32") + return new Int32Array(n); + if (t === "bool") { + for (var e = new Uint8Array(n.length), r = 0; r < e.length; ++r) + Math.round(n[r]) !== 0 && (e[r] = 1); + return e; + } else + throw new Error("Unknown data type " + t); + } + function ou() { + return qe().platform.now(); + } + function NL(n, t) { + return qe().platform.fetch(n, t); + } + function su(n, t) { + return t === void 0 && (t = "utf-8"), t = t || "utf-8", qe().platform.encode(n, t); + } + function cu(n, t) { + return t === void 0 && (t = "utf-8"), t = t || "utf-8", qe().platform.decode(n, t); + } + var _L = {__proto__: null, createScalarValue: AL, toTypedArray: Ts, now: ou, fetch: NL, encodeString: su, decodeString: cu, shuffle: Yp, clamp: ga, nearestLargerEven: iL, sum: aL, randUniform: sL, distSquared: oL, assert: E, assertShapesMatch: Pe, assertNonNull: Br, flatten: zr, sizeFromShape: dt, isScalarShape: cL, arraysEqual: pn, isInt: ot, tanh: lL, sizeToSquarishShape: uL, createShuffledIndices: hL, rightPad: ya, repeatedTry: dL, inferFromImplicitShape: Kp, parseAxisParam: rt, squeezeShape: jp, getTypedArrayFromDType: bs, getArrayFromDType: $p, checkConversionForErrors: Xp, isValidDtype: Jp, hasEncodingLoss: Zp, isTypedArray: Ft, bytesPerElement: Qp, bytesFromStringArray: ef, isString: lr, isBoolean: tf, isNumber: nf, inferDtype: xs, isFunction: ur, nearestDivisor: Ls, computeStrides: xi, toNestedArray: Li, makeOnesTypedArray: hc, makeZerosTypedArray: Si, makeZerosNestedTypedArray: pL, assertNonNegativeIntegerDimensions: dc, locToIndex: fL, indexToLoc: mL, isPromise: pc}; + var OL = function() { + function n(t, e) { + this.backendTimer = t, this.logger = e, e == null && (this.logger = new RL()); + } + return n.prototype.profileKernel = function(t, e, r) { + for (var i, a = function() { + i = r(); + }, s = this.backendTimer.time(a), o = function(u) { + var h = i[u]; + h.data().then(function(d) { + CL(d, h.dtype, t); + }); + }, c = 0; c < i.length; c++) + o(c); + var l = {kernelName: t, outputs: i, inputs: e, timeMs: s.then(function(u) { + return u.kernelMs; + }), extraInfo: s.then(function(u) { + return u.getExtraProfileInfo != null ? u.getExtraProfileInfo() : ""; + })}; + return l; + }, n.prototype.logKernelProfile = function(t) { + var e = this, r = t.kernelName, i = t.outputs, a = t.timeMs, s = t.inputs, o = t.extraInfo; + i.forEach(function(c) { + Promise.all([c.data(), a, o]).then(function(l) { + e.logger.logKernelProfile(r, c, l[0], l[1], s, l[2]); + }); + }); + }, n; + }(); + function CL(n, t, e) { + if (t !== "float32") + return false; + for (var r = 0; r < n.length; r++) { + var i = n[r]; + if (isNaN(i) || !isFinite(i)) + return console.warn("Found " + i + " in the result of '" + e + "'"), true; + } + return false; + } + var RL = function() { + function n() { + } + return n.prototype.logKernelProfile = function(t, e, r, i, a, s) { + var o = typeof i == "number" ? ya(i + "ms", 9) : i.error, c = ya(t, 25), l = e.rank, u = e.size, h = ya(e.shape.toString(), 14), d = ""; + for (var p in a) { + var f = a[p]; + if (f != null) { + var m = f.shape || e.shape, g = m.length; + d += p + ": " + g + "D " + (g > 0 ? m : "") + " "; + } + } + console.log("%c" + c + " %c" + o + " %c" + l + "D " + h + " %c" + u + " %c" + d + " %c" + s, "font-weight:bold", "color:red", "color:blue", "color: orange", "color: green", "color: steelblue"); + }, n; + }(); + function EL(n, t, e) { + for (var r = {}, i = {}, a = 0; a < t.length; a++) + r[t[a].id] = true; + for (var a = 0; a < n.length; a++) { + var s = n[a], o = s.inputs; + for (var c in o) { + for (var l = o[c], u = false, h = 0; h < t.length; h++) + if (r[l.id]) { + s.outputs.forEach(function(b) { + return r[b.id] = true; + }), u = true, i[s.id] = true; + break; + } + if (u) + break; + } + } + var d = {}; + d[e.id] = true; + for (var p = {}, a = n.length - 1; a >= 0; a--) + for (var s = n[a], o = s.inputs, h = 0; h < s.outputs.length; h++) + if (d[s.outputs[h].id]) { + for (var c in o) + d[o[c].id] = true, p[s.id] = true; + break; + } + for (var f = [], a = 0; a < n.length; a++) { + var s = n[a]; + if (i[s.id] && p[s.id]) { + var m = {}; + for (var c in s.inputs) { + var g = s.inputs[c]; + r[g.id] && (m[c] = g); + } + var y = Object.assign({}, s); + y.inputs = m, y.outputs = s.outputs, f.push(y); + } + } + return f; + } + function DL(n, t, e, r) { + for (var i = function(s) { + var o = t[s], c = []; + if (o.outputs.forEach(function(d) { + var p = n[d.id]; + p != null ? c.push(p) : c.push(null); + }), o.gradient == null) + throw new Error("Cannot compute gradient: gradient function not found " + ("for " + o.kernelName + ".")); + var l = o.gradient(c), u = function(d) { + if (!(d in l)) + throw new Error("Cannot backprop through input " + d + ". " + ("Available gradients found: " + Object.keys(l) + ".")); + var p = e(function() { + return l[d](); + }); + if (p.dtype !== "float32") + throw new Error("Error in gradient for op " + o.kernelName + ". The gradient of input " + (d + " must have 'float32' dtype, but has '" + p.dtype + "'")); + var f = o.inputs[d]; + if (!pn(p.shape, f.shape)) + throw new Error("Error in gradient for op " + o.kernelName + ". The gradient of input " + ("'" + d + "' has shape '" + p.shape + "', which does not match ") + ("the shape of the input '" + f.shape + "'")); + if (n[f.id] == null) + n[f.id] = p; + else { + var m = n[f.id]; + n[f.id] = r(m, p), m.dispose(); + } + }; + for (var h in o.inputs) + u(h); + }, a = t.length - 1; a >= 0; a--) + i(a); + } + var cm = 20, wa = 3, lu = 7; + function FL(n, t, e, r) { + var i = xi(t), a = kL(n, t, e, i), s = t.length, o = Ns(n, t, e, i, a), c = ["Tensor"]; + return r && (c.push(" dtype: " + e), c.push(" rank: " + s), c.push(" shape: [" + t + "]"), c.push(" values:")), c.push(o.map(function(l) { + return " " + l; + }).join(` +`)), c.join(` +`); + } + function kL(n, t, e, r) { + var i = dt(t), a = r[r.length - 1], s = new Array(a).fill(0), o = t.length, c = e === "complex64" ? xa(n) : n; + if (o > 1) + for (var l = 0; l < i / a; l++) + for (var u = l * a, h = 0; h < a; h++) + s[h] = Math.max(s[h], ba(c[u + h], 0, e).length); + return s; + } + function ba(n, t, e) { + var r; + return Array.isArray(n) ? r = parseFloat(n[0].toFixed(lu)) + " + " + (parseFloat(n[1].toFixed(lu)) + "j") : lr(n) ? r = "'" + n + "'" : e === "bool" ? r = lm(n) : r = parseFloat(n.toFixed(lu)).toString(), ya(r, t); + } + function lm(n) { + return n === 0 ? "false" : "true"; + } + function Ns(n, t, e, r, i, a) { + a === void 0 && (a = true); + var s = e === "complex64" ? 2 : 1, o = t[0], c = t.length; + if (c === 0) { + if (e === "complex64") { + var l = xa(n); + return [ba(l[0], 0, e)]; + } + return e === "bool" ? [lm(n[0])] : [n[0].toString()]; + } + if (c === 1) { + if (o > cm) { + var u = wa * s, h = Array.from(n.slice(0, u)), d = Array.from(n.slice((o - wa) * s, o * s)); + return e === "complex64" && (h = xa(h), d = xa(d)), ["[" + h.map(function(I, C) { + return ba(I, i[C], e); + }).join(", ") + ", ..., " + d.map(function(I, C) { + return ba(I, i[o - wa + C], e); + }).join(", ") + "]"]; + } + var p = e === "complex64" ? xa(n) : Array.from(n); + return ["[" + p.map(function(I, C) { + return ba(I, i[C], e); + }).join(", ") + "]"]; + } + var f = t.slice(1), m = r.slice(1), g = r[0] * s, y = []; + if (o > cm) { + for (var w = 0; w < wa; w++) { + var b = w * g, x = b + g; + y.push.apply(y, Ns(n.slice(b, x), f, e, m, i, false)); + } + y.push("..."); + for (var w = o - wa; w < o; w++) { + var b = w * g, x = b + g; + y.push.apply(y, Ns(n.slice(b, x), f, e, m, i, w === o - 1)); + } + } else + for (var w = 0; w < o; w++) { + var b = w * g, x = b + g; + y.push.apply(y, Ns(n.slice(b, x), f, e, m, i, w === o - 1)); + } + var L = c === 2 ? "," : ""; + y[0] = "[" + y[0] + L; + for (var w = 1; w < y.length - 1; w++) + y[w] = " " + y[w] + L; + for (var N = `, +`, w = 2; w < c; w++) + N += ` +`; + return y[y.length - 1] = " " + y[y.length - 1] + "]" + (a ? "" : N), y; + } + function xa(n) { + for (var t = [], e = 0; e < n.length; e += 2) + t.push([n[e], n[e + 1]]); + return t; + } + var _s = function() { + function n(t, e, r) { + var i = this; + if (this.dtype = e, this.shape = t.slice(), this.size = dt(t), r != null) { + var a = r.length; + E(a === this.size, function() { + return "Length of values '" + a + "' does not match the size " + ("inferred by the shape '" + i.size + "'."); + }); + } + if (e === "complex64") + throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag)."); + this.values = r || $p(e, this.size), this.strides = xi(t); + } + return n.prototype.set = function(t) { + for (var e = this, r = [], i = 1; i < arguments.length; i++) + r[i - 1] = arguments[i]; + r.length === 0 && (r = [0]), E(r.length === this.rank, function() { + return "The number of provided coordinates (" + r.length + ") must " + ("match the rank (" + e.rank + ")"); + }); + var a = this.locToIndex(r); + this.values[a] = t; + }, n.prototype.get = function() { + for (var t = [], e = 0; e < arguments.length; e++) + t[e] = arguments[e]; + t.length === 0 && (t = [0]); + for (var r = 0, i = 0, a = t; i < a.length; i++) { + var s = a[i]; + if (s < 0 || s >= this.shape[r]) { + var o = "Requested out of range element at " + t + ". " + (" Buffer shape=" + this.shape); + throw new Error(o); + } + r++; + } + for (var c = t[t.length - 1], l = 0; l < t.length - 1; ++l) + c += this.strides[l] * t[l]; + return this.values[c]; + }, n.prototype.locToIndex = function(t) { + if (this.rank === 0) + return 0; + if (this.rank === 1) + return t[0]; + for (var e = t[t.length - 1], r = 0; r < t.length - 1; ++r) + e += this.strides[r] * t[r]; + return e; + }, n.prototype.indexToLoc = function(t) { + if (this.rank === 0) + return []; + if (this.rank === 1) + return [t]; + for (var e = new Array(this.shape.length), r = 0; r < e.length - 1; ++r) + e[r] = Math.floor(t / this.strides[r]), t -= e[r] * this.strides[r]; + return e[e.length - 1] = t, e; + }, Object.defineProperty(n.prototype, "rank", {get: function() { + return this.shape.length; + }, enumerable: true, configurable: true}), n.prototype.toTensor = function() { + return _n().makeTensor(this.values, this.shape, this.dtype); + }, n; + }(), _n = null, Ai = null; + function WL(n) { + _n = n; + } + function UL(n) { + Ai = n; + } + var K = function() { + function n(t, e, r, i) { + this.kept = false, this.isDisposedInternal = false, this.shape = t.slice(), this.dtype = e || "float32", this.size = dt(t), this.strides = xi(t), this.dataId = r, this.id = i, this.rankType = this.rank < 5 ? this.rank.toString() : "higher"; + } + return Object.defineProperty(n.prototype, "rank", {get: function() { + return this.shape.length; + }, enumerable: true, configurable: true}), n.prototype.buffer = function() { + return pe(this, void 0, void 0, function() { + var t; + return fe(this, function(e) { + switch (e.label) { + case 0: + return [4, this.data()]; + case 1: + return t = e.sent(), [2, Ai.buffer(this.shape, this.dtype, t)]; + } + }); + }); + }, n.prototype.bufferSync = function() { + return Ai.buffer(this.shape, this.dtype, this.dataSync()); + }, n.prototype.array = function() { + return pe(this, void 0, void 0, function() { + var t; + return fe(this, function(e) { + switch (e.label) { + case 0: + return [4, this.data()]; + case 1: + return t = e.sent(), [2, Li(this.shape, t)]; + } + }); + }); + }, n.prototype.arraySync = function() { + return Li(this.shape, this.dataSync()); + }, n.prototype.data = function() { + return pe(this, void 0, void 0, function() { + var t, e; + return fe(this, function(r) { + switch (r.label) { + case 0: + return this.throwIfDisposed(), t = _n().read(this.dataId), this.dtype === "string" ? [4, t] : [3, 2]; + case 1: + e = r.sent(); + try { + return [2, e.map(function(i) { + return cu(i); + })]; + } catch (i) { + throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes()."); + } + r.label = 2; + case 2: + return [2, t]; + } + }); + }); + }, n.prototype.dataSync = function() { + this.throwIfDisposed(); + var t = _n().readSync(this.dataId); + if (this.dtype === "string") + try { + return t.map(function(e) { + return cu(e); + }); + } catch (e) { + throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes()."); + } + return t; + }, n.prototype.bytes = function() { + return pe(this, void 0, void 0, function() { + var t; + return fe(this, function(e) { + switch (e.label) { + case 0: + return this.throwIfDisposed(), [4, _n().read(this.dataId)]; + case 1: + return t = e.sent(), this.dtype === "string" ? [2, t] : [2, new Uint8Array(t.buffer)]; + } + }); + }); + }, n.prototype.dispose = function() { + if (this.isDisposed) + return; + _n().disposeTensor(this), this.isDisposedInternal = true; + }, Object.defineProperty(n.prototype, "isDisposed", {get: function() { + return this.isDisposedInternal; + }, enumerable: true, configurable: true}), n.prototype.throwIfDisposed = function() { + if (this.isDisposed) + throw new Error("Tensor is disposed."); + }, n.prototype.print = function(t) { + return t === void 0 && (t = false), Ai.print(this, t); + }, n.prototype.clone = function() { + return this.throwIfDisposed(), Ai.clone(this); + }, n.prototype.toString = function(t) { + t === void 0 && (t = false); + var e = this.dataSync(); + return FL(e, this.shape, this.dtype, t); + }, n.prototype.cast = function(t) { + return this.throwIfDisposed(), Ai.cast(this, t); + }, n.prototype.variable = function(t, e, r) { + return t === void 0 && (t = true), this.throwIfDisposed(), _n().makeVariable(this, t, e, r); + }, n; + }(); + Object.defineProperty(K, Symbol.hasInstance, {value: function(n) { + return !!n && n.data != null && n.dataSync != null && n.throwIfDisposed != null; + }}); + var La = function(n) { + Yn(t, n); + function t(e, r, i, a) { + var s = n.call(this, e.shape, e.dtype, e.dataId, a) || this; + return s.trainable = r, s.name = i, s; + } + return t.prototype.assign = function(e) { + if (e.dtype !== this.dtype) + throw new Error("dtype of the new value (" + e.dtype + ") and " + ("previous value (" + this.dtype + ") must match")); + if (!pn(e.shape, this.shape)) + throw new Error("shape of the new value (" + e.shape + ") and " + ("previous value (" + this.shape + ") must match")); + _n().disposeTensor(this), this.dataId = e.dataId, _n().incRef(this, null); + }, t.prototype.dispose = function() { + _n().disposeVariable(this), this.isDisposedInternal = true; + }, t; + }(K); + Object.defineProperty(La, Symbol.hasInstance, {value: function(n) { + return n instanceof K && n.assign != null && n.assign instanceof Function; + }}); + (function(n) { + n.R0 = "R0", n.R1 = "R1", n.R2 = "R2", n.R3 = "R3", n.R4 = "R4", n.R5 = "R5", n.R6 = "R6"; + })(A.Rank || (A.Rank = {})); + var uu; + (function(n) { + n.float32 = "float32", n.int32 = "int32", n.bool = "int32", n.complex64 = "complex64"; + })(uu || (uu = {})); + var hu; + (function(n) { + n.float32 = "float32", n.int32 = "int32", n.bool = "bool", n.complex64 = "complex64"; + })(hu || (hu = {})); + var du; + (function(n) { + n.float32 = "float32", n.int32 = "float32", n.bool = "float32", n.complex64 = "complex64"; + })(du || (du = {})); + var pu; + (function(n) { + n.float32 = "complex64", n.int32 = "complex64", n.bool = "complex64", n.complex64 = "complex64"; + })(pu || (pu = {})); + var BL = {float32: du, int32: uu, bool: hu, complex64: pu}; + function Cs(n, t) { + if (n === "string" || t === "string") { + if (n === "string" && t === "string") + return "string"; + throw new Error("Can not upcast " + n + " with " + t); + } + return BL[n][t]; + } + function zL(n) { + return Cs(n, "int32"); + } + function ct(n, t) { + if (n.dtype === t.dtype) + return [n, t]; + var e = Cs(n.dtype, t.dtype); + return [n.cast(e), t.cast(e)]; + } + function um(n, t) { + E(n.dtype === t.dtype, function() { + return "The dtypes of the first(" + n.dtype + ") and" + (" second(" + t.dtype + ") input must match"); + }); + } + function PL(n, t) { + return t.some(function(e) { + return e.id === n.id; + }); + } + function fu(n) { + var t = [], e = new Set(); + return hm(n, t, e), t; + } + function hm(n, t, e) { + if (n == null) + return; + if (n instanceof K) { + t.push(n); + return; + } + if (!ML(n)) + return; + var r = n; + for (var i in r) { + var a = r[i]; + e.has(a) || (e.add(a), hm(a, t, e)); + } + } + function ML(n) { + return Array.isArray(n) || typeof n == "object"; + } + var HL = {__proto__: null, makeTypesMatch: ct, assertTypesMatch: um, isTensorInList: PL, getTensorsInContainer: fu}; + var dm = function() { + function n() { + this.registeredVariables = {}, this.nextTapeNodeId = 0, this.numBytes = 0, this.numTensors = 0, this.numStringTensors = 0, this.numDataBuffers = 0, this.gradientDepth = 0, this.kernelDepth = 0, this.scopeStack = [], this.numDataMovesStack = [], this.nextScopeId = 0, this.tensorInfo = new WeakMap(), this.profiling = false, this.activeProfile = {newBytes: 0, newTensors: 0, peakBytes: 0, kernels: [], result: null}; + } + return n.prototype.dispose = function() { + for (var t in this.registeredVariables) + this.registeredVariables[t].dispose(); + }, n; + }(), qL = function() { + function n(t) { + this.ENV = t, this.registry = {}, this.registryFactory = {}, this.pendingBackendInitId = 0, this.state = new dm(); + } + return n.prototype.ready = function() { + return pe(this, void 0, void 0, function() { + var t, e, r, i; + return fe(this, function(a) { + switch (a.label) { + case 0: + if (this.pendingBackendInit != null) + return [2, this.pendingBackendInit.then(function() { + })]; + if (this.backendInstance != null) + return [2]; + t = this.getSortedBackends(), e = 0, a.label = 1; + case 1: + return e < t.length ? (r = t[e], [4, this.initializeBackend(r).success]) : [3, 5]; + case 2: + return i = a.sent(), i ? [4, this.setBackend(r)] : [3, 4]; + case 3: + return a.sent(), [2]; + case 4: + return e++, [3, 1]; + case 5: + throw new Error("Could not initialize any backends, all backend initializations failed."); + } + }); + }); + }, Object.defineProperty(n.prototype, "backend", {get: function() { + if (this.pendingBackendInit != null) + throw new Error("Backend '" + this.backendName + "' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods"); + if (this.backendInstance == null) { + var t = this.initializeBackendsAndReturnBest(), e = t.name, r = t.asyncInit; + if (r) + throw new Error("The highest priority backend '" + e + "' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods"); + this.setBackend(e); + } + return this.backendInstance; + }, enumerable: true, configurable: true}), n.prototype.backendNames = function() { + return Object.keys(this.registryFactory); + }, n.prototype.findBackend = function(t) { + if (!(t in this.registry)) + if (t in this.registryFactory) { + var e = this.initializeBackend(t).asyncInit; + if (e) + return null; + } else + return null; + return this.registry[t]; + }, n.prototype.findBackendFactory = function(t) { + return t in this.registryFactory ? this.registryFactory[t].factory : null; + }, n.prototype.registerBackend = function(t, e, r) { + return r === void 0 && (r = 1), t in this.registryFactory ? (console.warn(t + " backend was already registered. Reusing existing backend factory."), false) : (this.registryFactory[t] = {factory: e, priority: r}, true); + }, n.prototype.setBackend = function(t) { + return pe(this, void 0, void 0, function() { + var e, r, i, a, s; + return fe(this, function(o) { + switch (o.label) { + case 0: + if (this.registryFactory[t] == null) + throw new Error("Backend name '" + t + "' not found in registry"); + return this.backendName = t, this.registry[t] == null ? (this.backendInstance = null, e = this.initializeBackend(t), r = e.success, i = e.asyncInit, i ? [4, r] : [3, 2]) : [3, 4]; + case 1: + return s = o.sent(), [3, 3]; + case 2: + s = r, o.label = 3; + case 3: + if (a = s, !a) + return [2, false]; + o.label = 4; + case 4: + return this.backendInstance = this.registry[t], this.setupRegisteredKernels(), this.profiler = new OL(this.backendInstance), [2, true]; + } + }); + }); + }, n.prototype.setupRegisteredKernels = function() { + var t = this, e = As(this.backendName); + e.forEach(function(r) { + r.setupFunc != null && r.setupFunc(t.backendInstance); + }); + }, n.prototype.disposeRegisteredKernels = function(t) { + var e = this, r = As(t); + r.forEach(function(i) { + i.disposeFunc != null && i.disposeFunc(e.registry[t]); + }); + }, n.prototype.initializeBackend = function(t) { + var e = this, r = this.registryFactory[t]; + if (r == null) + throw new Error("Cannot initialize backend " + t + ", no registration found."); + try { + var i = r.factory(); + if (i && !(i instanceof qp) && typeof i.then == "function") { + var a = ++this.pendingBackendInitId, s = i.then(function(o) { + return a < e.pendingBackendInitId ? false : (e.registry[t] = o, e.pendingBackendInit = null, true); + }).catch(function(o) { + return a < e.pendingBackendInitId || (e.pendingBackendInit = null, console.warn("Initialization of backend " + t + " failed"), console.warn(o.stack || o.message)), false; + }); + return this.pendingBackendInit = s, {success: s, asyncInit: true}; + } else + return this.registry[t] = i, {success: true, asyncInit: false}; + } catch (o) { + return console.warn("Initialization of backend " + t + " failed"), console.warn(o.stack || o.message), {success: false, asyncInit: false}; + } + }, n.prototype.removeBackend = function(t) { + if (!(t in this.registryFactory)) + throw new Error(t + " backend not found in registry"); + this.backendName === t && this.pendingBackendInit != null && this.pendingBackendInitId++, t in this.registry && (this.disposeRegisteredKernels(t), this.registry[t].dispose(), delete this.registry[t]), delete this.registryFactory[t], this.backendName === t && (this.pendingBackendInit = null, this.backendName = null, this.backendInstance = null); + }, n.prototype.getSortedBackends = function() { + var t = this; + if (Object.keys(this.registryFactory).length === 0) + throw new Error("No backend found in registry."); + return Object.keys(this.registryFactory).sort(function(e, r) { + return t.registryFactory[r].priority - t.registryFactory[e].priority; + }); + }, n.prototype.initializeBackendsAndReturnBest = function() { + for (var t = this.getSortedBackends(), e = 0; e < t.length; e++) { + var r = t[e], i = this.initializeBackend(r), a = i.success, s = i.asyncInit; + if (s || a) + return {name: r, asyncInit: s}; + } + throw new Error("Could not initialize any backends, all backend initializations failed."); + }, n.prototype.moveData = function(t, e) { + var r = this.state.tensorInfo.get(e), i = r.backend, a = this.readSync(e); + i.disposeData(e), r.backend = t, t.move(e, a, r.shape, r.dtype), this.shouldCheckForMemLeaks() && this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1]++; + }, n.prototype.tidy = function(t, e) { + var r = this, i = null; + if (e == null) { + if (typeof t != "function") + throw new Error("Please provide a function to tidy()"); + e = t; + } else { + if (typeof t != "string" && !(t instanceof String)) + throw new Error("When calling with two arguments, the first argument to tidy() must be a string"); + if (typeof e != "function") + throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function"); + i = t; + } + var a; + return this.scopedRun(function() { + return r.startScope(i); + }, function() { + return r.endScope(a); + }, function() { + return a = e(), a instanceof Promise && console.error("Cannot return a Promise inside of tidy."), a; + }); + }, n.prototype.scopedRun = function(t, e, r) { + t(); + try { + var i = r(); + return e(), i; + } catch (a) { + throw e(), a; + } + }, n.prototype.nextTensorId = function() { + return n.nextTensorId++; + }, n.prototype.nextVariableId = function() { + return n.nextVariableId++; + }, n.prototype.clone = function(t) { + var e = this.makeTensorFromDataId(t.dataId, t.shape, t.dtype), r = {x: t}, i = function(s) { + return {x: function() { + var o = "float32", c = {x: s}, l = {dtype: o}; + return z.runKernelFunc(function(u) { + return u.cast(s, o); + }, c, null, Is, l); + }}; + }, a = []; + return this.addTapeNode(this.state.activeScope.name, r, [e], i, a, {}), e; + }, n.prototype.runKernel = function(t, e, r, i, a) { + var s = null, o = null; + return this.runKernelFunc(s, e, o, t, r, i, a); + }, n.prototype.shouldCheckForMemLeaks = function() { + return this.ENV.getBool("IS_TEST"); + }, n.prototype.checkKernelForMemLeak = function(t, e, r) { + var i = this.backend.numDataIds(), a = 0; + r.forEach(function(c) { + a += c.dtype === "complex64" ? 3 : 1; + }); + var s = this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1], o = i - e - a - s; + if (o > 0) + throw new Error("Backend '" + this.backendName + "' has an internal memory leak " + ("(" + o + " data ids) after running '" + t + "'")); + }, n.prototype.runKernelFunc = function(t, e, r, i, a, s, o) { + var c = this, l, u = [], h = this.isTapeOn(); + i == null && (i = this.state.activeScope != null ? this.state.activeScope.name : ""); + var d = this.state.numBytes, p = this.state.numTensors; + this.shouldCheckForMemLeaks() && this.state.numDataMovesStack.push(0); + var f, m = iu(i, this.backendName), g; + if (m != null) + f = function() { + var b = c.backend.numDataIds(); + g = m.kernelFunc({inputs: e, attrs: a, backend: c.backend}); + var x = Array.isArray(g) ? g : [g]; + c.shouldCheckForMemLeaks() && c.checkKernelForMemLeak(i, b, x); + var L = x.map(function(C) { + var O = C.dataId, D = C.shape, F = C.dtype; + return c.makeTensorFromDataId(O, D, F); + }); + if (h) { + var N = c.getTensorsForGradient(i, e, L); + if (N == null) { + o == null && (o = []); + var I = L.filter(function(C, O) { + return o[O]; + }); + N = (s || []).slice().concat(I); + } + u = c.saveTensorsForBackwardMode(N); + } + return L; + }; + else { + var y = function(b) { + if (!h) + return; + u = b.map(function(x) { + return c.keep(c.clone(x)); + }); + }; + f = function() { + var b = c.backend.numDataIds(); + g = c.tidy(function() { + return t(c.backend, y); + }); + var x = Array.isArray(g) ? g : [g]; + return c.shouldCheckForMemLeaks() && c.checkKernelForMemLeak(i, b, x), x; + }; + } + var w; + return this.scopedRun(function() { + return c.state.kernelDepth++; + }, function() { + return c.state.kernelDepth--; + }, function() { + !c.ENV.getBool("DEBUG") && !c.state.profiling ? l = f() : (w = c.profiler.profileKernel(i, e, function() { + return f(); + }), c.ENV.getBool("DEBUG") && c.profiler.logKernelProfile(w), l = w.outputs); + }), h && this.addTapeNode(i, e, l, r, u, a), this.state.profiling && this.state.activeProfile.kernels.push({name: i, bytesAdded: this.state.numBytes - d, totalBytesSnapshot: this.state.numBytes, tensorsAdded: this.state.numTensors - p, totalTensorsSnapshot: this.state.numTensors, inputShapes: Object.keys(e).map(function(b) { + return e[b] != null ? e[b].shape : null; + }), outputShapes: l.map(function(b) { + return b.shape; + }), kernelTimeMs: w.timeMs, extraInfo: w.extraInfo}), Array.isArray(g) ? l : l[0]; + }, n.prototype.saveTensorsForBackwardMode = function(t) { + var e = this, r = t.map(function(i) { + return e.keep(e.clone(i)); + }); + return r; + }, n.prototype.getTensorsForGradient = function(t, e, r) { + var i = au(t); + if (i != null) { + var a = i.inputsToSave || [], s = i.outputsToSave || [], o = void 0; + i.saveAllInputs ? (E(Array.isArray(e), function() { + return "saveAllInputs is true, expected inputs to be an array."; + }), o = Object.keys(e).map(function(l) { + return e[l]; + })) : o = a.map(function(l) { + return e[l]; + }); + var c = r.filter(function(l, u) { + return s[u]; + }); + return o.concat(c); + } + return null; + }, n.prototype.makeTensor = function(t, e, r, i) { + if (t == null) + throw new Error("Values passed to engine.makeTensor() are null"); + r = r || "float32", i = i || this.backend; + var a = t; + r === "string" && lr(t[0]) && (a = t.map(function(u) { + return su(u); + })); + var s = i.write(a, e, r), o = new K(e, r, s, this.nextTensorId()); + if (this.incRef(o, i), r === "string") { + var c = this.state.tensorInfo.get(s), l = ef(a); + this.state.numBytes += l - c.bytes, c.bytes = l; + } + return o; + }, n.prototype.makeTensorFromDataId = function(t, e, r, i) { + r = r || "float32"; + var a = new K(e, r, t, this.nextTensorId()); + return this.incRef(a, i), a; + }, n.prototype.makeVariable = function(t, e, r, i) { + e === void 0 && (e = true), r = r || this.nextVariableId().toString(), i != null && i !== t.dtype && (t = t.cast(i)); + var a = new La(t, e, r, this.nextTensorId()); + if (this.state.registeredVariables[a.name] != null) + throw new Error("Variable with name " + a.name + " was already registered"); + return this.state.registeredVariables[a.name] = a, this.incRef(a, this.backend), a; + }, n.prototype.incRef = function(t, e) { + var r = this.state.tensorInfo.has(t.dataId) ? this.state.tensorInfo.get(t.dataId).refCount : 0; + if (this.state.numTensors++, t.dtype === "string" && this.state.numStringTensors++, r === 0) { + this.state.numDataBuffers++; + var i = 0; + t.dtype !== "complex64" && t.dtype !== "string" && (i = t.size * Qp(t.dtype)), this.state.tensorInfo.set(t.dataId, {backend: e || this.backend, dtype: t.dtype, shape: t.shape, bytes: i, refCount: 0}), this.state.numBytes += i; + } + this.state.tensorInfo.get(t.dataId).refCount++, t instanceof La || this.track(t); + }, n.prototype.disposeTensor = function(t) { + if (!this.state.tensorInfo.has(t.dataId)) + return; + this.state.numTensors--, t.dtype === "string" && this.state.numStringTensors--; + var e = this.state.tensorInfo.get(t.dataId), r = e.refCount; + r <= 1 ? (t.dtype !== "complex64" && (this.state.numBytes -= e.bytes), this.state.numDataBuffers--, e.backend.disposeData(t.dataId), this.state.tensorInfo.delete(t.dataId)) : this.state.tensorInfo.get(t.dataId).refCount--; + }, n.prototype.disposeVariables = function() { + for (var t in this.state.registeredVariables) { + var e = this.state.registeredVariables[t]; + this.disposeVariable(e); + } + }, n.prototype.disposeVariable = function(t) { + this.disposeTensor(t), this.state.registeredVariables[t.name] != null && delete this.state.registeredVariables[t.name]; + }, n.prototype.memory = function() { + var t = this.backend.memory(); + return t.numTensors = this.state.numTensors, t.numDataBuffers = this.state.numDataBuffers, t.numBytes = this.state.numBytes, this.state.numStringTensors > 0 && (t.unreliable = true, t.reasons == null && (t.reasons = []), t.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")), t; + }, n.prototype.profile = function(t) { + return pe(this, void 0, void 0, function() { + var e, r, i, a, s, o, c, l; + return fe(this, function(u) { + switch (u.label) { + case 0: + return this.state.profiling = true, e = this.state.numBytes, r = this.state.numTensors, this.state.activeProfile.kernels = [], i = this.state.activeProfile, [4, t()]; + case 1: + i.result = u.sent(), this.state.profiling = false, this.state.activeProfile.peakBytes = Math.max.apply(Math, this.state.activeProfile.kernels.map(function(h) { + return h.totalBytesSnapshot; + })), this.state.activeProfile.newBytes = this.state.numBytes - e, this.state.activeProfile.newTensors = this.state.numTensors - r, a = 0, s = this.state.activeProfile.kernels, u.label = 2; + case 2: + return a < s.length ? (o = s[a], c = o, [4, o.kernelTimeMs]) : [3, 6]; + case 3: + return c.kernelTimeMs = u.sent(), l = o, [4, o.extraInfo]; + case 4: + l.extraInfo = u.sent(), u.label = 5; + case 5: + return a++, [3, 2]; + case 6: + return [2, this.state.activeProfile]; + } + }); + }); + }, n.prototype.isTapeOn = function() { + return this.state.gradientDepth > 0 && this.state.kernelDepth === 0; + }, n.prototype.addTapeNode = function(t, e, r, i, a, s) { + var o = this, c = {id: this.state.nextTapeNodeId++, kernelName: t, inputs: e, outputs: r, saved: a}, l = au(t); + l != null && (i = l.gradFunc), i != null && (c.gradient = function(u) { + return u = u.map(function(h, d) { + if (h == null) { + var p = r[d], f = Si(p.size, p.dtype); + return o.makeTensor(f, p.shape, p.dtype); + } + return h; + }), i(u.length > 1 ? u : u[0], a, s); + }), this.state.activeTape.push(c); + }, n.prototype.keep = function(t) { + return t.kept = true, t; + }, n.prototype.startTape = function() { + this.state.gradientDepth === 0 && (this.state.activeTape = []), this.state.gradientDepth++; + }, n.prototype.endTape = function() { + this.state.gradientDepth--; + }, n.prototype.startScope = function(t) { + var e = {track: [], name: "unnamed scope", id: this.state.nextScopeId++}; + t && (e.name = t), this.state.scopeStack.push(e), this.state.activeScope = e; + }, n.prototype.endScope = function(t) { + for (var e = this, r = fu(t), i = new Set(r.map(function(c) { + return c.id; + })), a = 0; a < this.state.activeScope.track.length; a++) { + var s = this.state.activeScope.track[a]; + !s.kept && !i.has(s.id) && s.dispose(); + } + var o = this.state.scopeStack.pop(); + this.state.activeScope = this.state.scopeStack.length === 0 ? null : this.state.scopeStack[this.state.scopeStack.length - 1], r.forEach(function(c) { + !c.kept && c.scopeId === o.id && e.track(c); + }); + }, n.prototype.gradients = function(t, e, r, i) { + var a = this; + if (i === void 0 && (i = false), E(e.length > 0, function() { + return "gradients() received an empty list of xs."; + }), r != null && r.dtype !== "float32") + throw new Error("dy must have 'float32' dtype, but has '" + r.dtype + "'"); + var s = this.scopedRun(function() { + return a.startTape(); + }, function() { + return a.endTape(); + }, function() { + return a.tidy("forward", t); + }); + E(s instanceof K, function() { + return "The result y returned by f() must be a tensor."; + }); + var o = EL(this.state.activeTape, e, s); + if (!i && o.length === 0 && e.length > 0) + throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y."); + return this.tidy("backward", function() { + var c = {}; + c[s.id] = r ?? VL(s.shape), DL(c, o, function(u) { + return a.tidy(u); + }, GL); + var l = e.map(function(u) { + return c[u.id]; + }); + return a.state.gradientDepth === 0 && (a.state.activeTape.forEach(function(u) { + for (var h = 0, d = u.saved; h < d.length; h++) { + var p = d[h]; + p.dispose(); + } + }), a.state.activeTape = null), {value: s, grads: l}; + }); + }, n.prototype.customGrad = function(t) { + var e = this; + return E(ur(t), function() { + return "The f passed in customGrad(f) must be a function."; + }), function() { + for (var r = [], i = 0; i < arguments.length; i++) + r[i] = arguments[i]; + E(r.every(function(o) { + return o instanceof K; + }), function() { + return "The args passed in customGrad(f)(x1, x2,...) must all be tensors"; + }); + var a, s = {}; + return r.forEach(function(o, c) { + s[c] = o; + }), e.runKernelFunc(function(o, c) { + return a = t.apply(void 0, r.concat([c])), E(a.value instanceof K, function() { + return "The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"; + }), E(ur(a.gradFunc), function() { + return "The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."; + }), a.value; + }, s, function(o, c) { + var l = a.gradFunc(o, c), u = Array.isArray(l) ? l : [l]; + E(u.length === r.length, function() { + return "The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."; + }), E(u.every(function(d) { + return d instanceof K; + }), function() { + return "The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors."; + }); + var h = {}; + return u.forEach(function(d, p) { + h[p] = function() { + return d; + }; + }), h; + }); + }; + }, n.prototype.readSync = function(t) { + var e = this.state.tensorInfo.get(t); + return e.backend.readSync(t); + }, n.prototype.read = function(t) { + var e = this.state.tensorInfo.get(t); + return e.backend.read(t); + }, n.prototype.time = function(t) { + return pe(this, void 0, void 0, function() { + var e, r; + return fe(this, function(i) { + switch (i.label) { + case 0: + return e = ou(), [4, this.backend.time(t)]; + case 1: + return r = i.sent(), r.wallMs = ou() - e, [2, r]; + } + }); + }); + }, n.prototype.track = function(t) { + return this.state.activeScope != null && (t.scopeId = this.state.activeScope.id, this.state.activeScope.track.push(t)), t; + }, Object.defineProperty(n.prototype, "registeredVariables", {get: function() { + return this.state.registeredVariables; + }, enumerable: true, configurable: true}), n.prototype.reset = function() { + this.pendingBackendInitId++, this.state.dispose(), this.ENV.reset(), this.state = new dm(); + for (var t in this.registry) + this.disposeRegisteredKernels(t), this.registry[t].dispose(), delete this.registry[t]; + this.backendName = null, this.backendInstance = null, this.pendingBackendInit = null; + }, n.nextTensorId = 0, n.nextVariableId = 0, n; + }(); + function VL(n) { + var t = hc(dt(n), "float32"); + return z.makeTensor(t, n, "float32"); + } + function pm() { + var n = of(); + if (n._tfengine == null) { + var t = new sf(n); + n._tfengine = new qL(t); + } + return wL(n._tfengine.ENV), WL(function() { + return n._tfengine; + }), n._tfengine; + } + var z = pm(); + function GL(n, t) { + var e = {a: n, b: t}; + return z.runKernelFunc(function(r, i) { + var a = r.add(n, t); + return i([n, t]), a; + }, e, null, Ss); + } + function YL() { + return typeof navigator != "undefined" && navigator != null; + } + function KL() { + if (YL()) { + var n = navigator.userAgent || navigator.vendor || window.opera; + return /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(n) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(n.substr(0, 4)); + } + return false; + } + function fm() { + return typeof window != "undefined" && window.document != null || typeof WorkerGlobalScope != "undefined"; + } + var jL = {__proto__: null, isMobile: KL, isBrowser: fm}; + var Kn = qe(); + Kn.registerFlag("DEBUG", function() { + return false; + }, function(n) { + n && console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance."); + }); + Kn.registerFlag("IS_BROWSER", function() { + return fm(); + }); + Kn.registerFlag("IS_NODE", function() { + return typeof process != "undefined" && typeof process.versions != "undefined" && typeof process.versions.node != "undefined"; + }); + Kn.registerFlag("IS_CHROME", function() { + return typeof navigator != "undefined" && navigator != null && navigator.userAgent != null && /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor); + }); + Kn.registerFlag("PROD", function() { + return false; + }); + Kn.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY", function() { + return Kn.getBool("DEBUG"); + }); + Kn.registerFlag("DEPRECATION_WARNINGS_ENABLED", function() { + return true; + }); + Kn.registerFlag("IS_TEST", function() { + return false; + }); + function Cn(n, t) { + var e = n; + if (Ft(n)) + return t === "string" ? [] : [n.length]; + if (!Array.isArray(n)) + return []; + for (var r = []; Array.isArray(e) || Ft(e) && t !== "string"; ) + r.push(e.length), e = e[0]; + return Array.isArray(n) && qe().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY") && mm(n, r, []), r; + } + function mm(n, t, e) { + if (e = e || [], !Array.isArray(n) && !Ft(n)) { + E(t.length === 0, function() { + return "Element arr[" + e.join("][") + "] is a primitive, " + ("but should be an array/TypedArray of " + t[0] + " elements"); + }); + return; + } + E(t.length > 0, function() { + return "Element arr[" + e.join("][") + "] should be a primitive, " + ("but is an array of " + n.length + " elements"); + }), E(n.length === t[0], function() { + return "Element arr[" + e.join("][") + "] should have " + t[0] + " " + ("elements, but has " + n.length + " elements"); + }); + for (var r = t.slice(1), i = 0; i < n.length; ++i) + mm(n[i], r, e.concat(i)); + } + function gm(n, t, e, r) { + if (n == null) + return; + if (n !== "numeric" && n !== t || n === "numeric" && t === "string") + throw new Error("Argument '" + e + "' passed to '" + r + "' must " + ("be " + n + " tensor, but got " + t + " tensor")); + } + function R(n, t, e, r) { + if (r === void 0 && (r = "numeric"), n instanceof K) + return gm(r, n.dtype, t, e), n; + var i = xs(n); + if (i !== "string" && ["bool", "int32", "float32"].indexOf(r) >= 0 && (i = r), gm(r, i, t, e), n == null || !Ft(n) && !Array.isArray(n) && typeof n != "number" && typeof n != "boolean" && typeof n != "string") { + var a = n == null ? "null" : n.constructor.name; + throw new Error("Argument '" + t + "' passed to '" + e + "' must be a " + ("Tensor or TensorLike, but got '" + a + "'")); + } + var s = Cn(n, i); + !Ft(n) && !Array.isArray(n) && (n = [n]); + var o = true, c = i !== "string" ? Ts(n, i) : zr(n, [], o); + return z.makeTensor(c, s, i); + } + function Sa(n, t, e, r) { + if (r === void 0 && (r = "numeric"), !Array.isArray(n)) + throw new Error("Argument " + t + " passed to " + e + " must be a `Tensor[]` or `TensorLike[]`"); + var i = n; + return i.map(function(a, s) { + return R(a, t + "[" + s + "]", e); + }, r); + } + var ym = "__op"; + function U(n) { + var t = Object.keys(n); + if (t.length !== 1) + throw new Error("Please provide an object with a single key (operation name) mapping to a function. Got an object with " + (t.length + " keys.")); + var e = t[0], r = n[e]; + e.endsWith("_") && (e = e.substring(0, e.length - 1)), e = e + ym; + var i = function() { + for (var a = [], s = 0; s < arguments.length; s++) + a[s] = arguments[s]; + z.startScope(e); + try { + var o = r.apply(void 0, a); + return pc(o) && console.error("Cannot return a Promise inside of tidy."), z.endScope(o), o; + } catch (c) { + throw z.endScope(null), c; + } + }; + return Object.defineProperty(i, "name", {value: e, configurable: true}), i; + } + function $L(n, t) { + var e = R(n, "real", "complex"), r = R(t, "imag", "complex"); + Pe(e.shape, r.shape, "real and imag shapes, " + e.shape + " and " + r.shape + ", must match in call to tf.complex()."); + var i = function(s) { + return s.complex(e, r); + }, a = {real: e, imag: r}; + return z.runKernelFunc(i, a, null, pf); + } + var hr = U({complex_: $L}); + function dr(n, t, e, r) { + if (r == null && (r = xs(n)), r === "complex64") + throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag)."); + if (!Ft(n) && !Array.isArray(n) && typeof n != "number" && typeof n != "boolean" && typeof n != "string") + throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray"); + if (t != null) { + dc(t); + var i = dt(t), a = dt(e); + E(i === a, function() { + return "Based on the provided shape, [" + t + "], the tensor should have " + (i + " values but has " + a); + }); + for (var s = 0; s < e.length; ++s) { + var o = e[s], c = s === e.length - 1 ? o !== dt(t.slice(s)) : true; + E(e[s] === t[s] || !c, function() { + return "Error creating a new Tensor. Inferred shape " + ("(" + e + ") does not match the provided ") + ("shape (" + t + "). "); + }); + } + } + return !Ft(n) && !Array.isArray(n) && (n = [n]), t = t || e, n = r !== "string" ? Ts(n, r) : zr(n, [], true), z.makeTensor(n, t, r); + } + function pr(n, t, e) { + var r = Cn(n, e); + return dr(n, t, r, e); + } + var mu = {float32: 4, float16: 2, int32: 4, uint16: 2, uint8: 1, bool: 1, complex64: 8}; + var Rs = 4; + function JL(n, t) { + return pe(this, void 0, void 0, function() { + var e, r, i, a, s, o, c = this; + return fe(this, function(l) { + switch (l.label) { + case 0: + for (e = [], r = [], i = Array.isArray(n) ? n.map(function(u) { + return u.name; + }) : Object.keys(n), a = function(u) { + var h = i[u], d = Array.isArray(n) ? n[u].tensor : n[h]; + if (d.dtype !== "float32" && d.dtype !== "int32" && d.dtype !== "bool" && d.dtype !== "string" && d.dtype !== "complex64") + throw new Error("Unsupported dtype in weight '" + h + "': " + d.dtype); + var p = {name: h, shape: d.shape, dtype: d.dtype}; + if (d.dtype === "string") { + var f = new Promise(function(m) { + return pe(c, void 0, void 0, function() { + var g, y, w, b, x, L, N; + return fe(this, function(I) { + switch (I.label) { + case 0: + return [4, d.bytes()]; + case 1: + for (g = I.sent(), y = g.reduce(function(C, O) { + return C + O.length; + }, 0) + Rs * g.length, w = new Uint8Array(y), b = 0, x = 0; x < g.length; x++) + L = g[x], N = new Uint8Array(new Uint32Array([L.length]).buffer), w.set(N, b), b += Rs, w.set(L, b), b += L.length; + return m(w), [2]; + } + }); + }); + }); + r.push(f); + } else + r.push(d.data()); + t != null && (p.group = t), e.push(p); + }, s = 0; s < i.length; ++s) + a(s); + return [4, Promise.all(r)]; + case 1: + return o = l.sent(), [2, {data: XL(o), specs: e}]; + } + }); + }); + } + function vm(n, t) { + for (var e = {}, r, i = 0, a = 0, s = t; a < s.length; a++) { + var o = s[a], c = o.name, l = o.dtype, u = o.shape, h = dt(u), d = void 0; + if ("quantization" in o) { + var p = o.quantization; + if (p.dtype === "uint8" || p.dtype === "uint16") { + if (!("min" in p && "scale" in p)) + throw new Error("Weight " + o.name + " with quantization " + p.dtype + " doesn't have corresponding metadata min and scale."); + } else if (p.dtype === "float16") { + if (l !== "float32") + throw new Error("Weight " + o.name + " is quantized with " + p.dtype + " " + ("which only supports weights of type float32 not " + l + ".")); + } else + throw new Error("Weight " + o.name + " has unknown " + ("quantization dtype " + p.dtype + ". ") + "Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'."); + var f = mu[p.dtype], m = n.slice(i, i + h * f), g = p.dtype === "uint8" ? new Uint8Array(m) : new Uint16Array(m); + if (l === "float32") + if (p.dtype === "uint8" || p.dtype === "uint16") { + d = new Float32Array(g.length); + for (var y = 0; y < g.length; y++) { + var w = g[y]; + d[y] = w * p.scale + p.min; + } + } else if (p.dtype === "float16") + r === void 0 && (r = ZL()), d = r(g); + else + throw new Error("Unsupported quantization type " + p.dtype + " for weight type float32."); + else if (l === "int32") { + if (p.dtype !== "uint8" && p.dtype !== "uint16") + throw new Error("Unsupported quantization type " + p.dtype + " for weight type int32."); + d = new Int32Array(g.length); + for (var y = 0; y < g.length; y++) { + var w = g[y]; + d[y] = Math.round(w * p.scale + p.min); + } + } else + throw new Error("Unsupported dtype in weight '" + c + "': " + l); + i += h * f; + } else if (l === "string") { + var b = dt(o.shape); + d = []; + for (var y = 0; y < b; y++) { + var x = new Uint32Array(n.slice(i, i + Rs))[0]; + i += Rs; + var L = new Uint8Array(n.slice(i, i + x)); + d.push(L), i += x; + } + } else { + var N = mu[l], m = n.slice(i, i + h * N); + if (l === "float32") + d = new Float32Array(m); + else if (l === "int32") + d = new Int32Array(m); + else if (l === "bool") + d = new Uint8Array(m); + else if (l === "complex64") { + d = new Float32Array(m); + for (var I = new Float32Array(d.length / 2), C = new Float32Array(d.length / 2), y = 0; y < I.length; y++) + I[y] = d[y * 2], C[y] = d[y * 2 + 1]; + var O = pr(I, u, "float32"), D = pr(C, u, "float32"); + e[c] = hr(O, D), O.dispose(), D.dispose(); + } else + throw new Error("Unsupported dtype in weight '" + c + "': " + l); + i += h * N; + } + l !== "complex64" && (e[c] = pr(d, u, l)); + } + return e; + } + function XL(n) { + if (n === null) + throw new Error("Invalid input value: " + JSON.stringify(n)); + var t = 0, e = []; + n.forEach(function(a) { + if (t += a.byteLength, e.push(a.byteLength === a.buffer.byteLength ? a : new a.constructor(a)), !(a instanceof Float32Array || a instanceof Int32Array || a instanceof Uint8Array)) + throw new Error("Unsupported TypedArray subtype: " + a.constructor.name); + }); + var r = new Uint8Array(t), i = 0; + return e.forEach(function(a) { + r.set(new Uint8Array(a.buffer), i), i += a.byteLength; + }), r.buffer; + } + var gu = typeof Buffer != "undefined" && (typeof Blob == "undefined" || typeof atob == "undefined" || typeof btoa == "undefined"); + function wm(n) { + return gu ? Buffer.byteLength(n) : new Blob([n]).size; + } + function QL(n) { + if (gu) + return Buffer.from(n).toString("base64"); + for (var t = new Uint8Array(n), e = "", r = 0, i = t.length; r < i; r++) + e += String.fromCharCode(t[r]); + return btoa(e); + } + function eS(n) { + if (gu) { + var t = Buffer.from(n, "base64"); + return t.buffer.slice(t.byteOffset, t.byteOffset + t.byteLength); + } + for (var e = atob(n), r = new Uint8Array(e.length), i = 0; i < e.length; ++i) + r.set([e.charCodeAt(i)], i); + return r.buffer; + } + function yu(n) { + if (n.length === 1) + return n[0]; + var t = 0; + n.forEach(function(i) { + t += i.byteLength; + }); + var e = new Uint8Array(t), r = 0; + return n.forEach(function(i) { + e.set(new Uint8Array(i), r), r += i.byteLength; + }), e.buffer; + } + function bm(n) { + var t = "/"; + for (n = n.trim(); n.endsWith(t); ) + n = n.slice(0, n.length - 1); + var e = n.split(t); + return e[e.length - 1]; + } + function Ia(n) { + if (n.modelTopology instanceof ArrayBuffer) + throw new Error("Expected JSON model topology, received ArrayBuffer."); + return {dateSaved: new Date(), modelTopologyType: "JSON", modelTopologyBytes: n.modelTopology == null ? 0 : wm(JSON.stringify(n.modelTopology)), weightSpecsBytes: n.weightSpecs == null ? 0 : wm(JSON.stringify(n.weightSpecs)), weightDataBytes: n.weightData == null ? 0 : n.weightData.byteLength}; + } + function tS() { + var n = function(r) { + for (var i = r << 13, a = 0; (i & 8388608) === 0; ) + a -= 8388608, i <<= 1; + return i &= ~8388608, a += 947912704, i | a; + }, t = new Uint32Array(2048); + t[0] = 0; + for (var e = 1; e < 1024; e++) + t[e] = n(e); + for (var e = 1024; e < 2048; e++) + t[e] = 939524096 + (e - 1024 << 13); + return t; + } + function nS() { + var n = new Uint32Array(64); + n[0] = 0, n[31] = 1199570944, n[32] = 2147483648, n[63] = 3347054592; + for (var t = 1; t < 31; t++) + n[t] = t << 23; + for (var t = 33; t < 63; t++) + n[t] = 2147483648 + (t - 32 << 23); + return n; + } + function rS() { + for (var n = new Uint32Array(64), t = 0; t < 64; t++) + n[t] = 1024; + return n[0] = n[32] = 0, n; + } + function ZL() { + var n = tS(), t = nS(), e = rS(); + return function(r) { + for (var i = new ArrayBuffer(4 * r.length), a = new Uint32Array(i), s = 0; s < r.length; s++) { + var o = r[s], c = n[e[o >> 10] + (o & 1023)] + t[o >> 10]; + a[s] = c; + } + return new Float32Array(i); + }; + } + var rn = function() { + function n() { + this.saveRouters = [], this.loadRouters = []; + } + return n.getInstance = function() { + return n.instance == null && (n.instance = new n()), n.instance; + }, n.registerSaveRouter = function(t) { + n.getInstance().saveRouters.push(t); + }, n.registerLoadRouter = function(t) { + n.getInstance().loadRouters.push(t); + }, n.getSaveHandlers = function(t) { + return n.getHandlers(t, "save"); + }, n.getLoadHandlers = function(t, e) { + return n.getHandlers(t, "load", e); + }, n.getHandlers = function(t, e, r) { + var i = [], a = e === "load" ? n.getInstance().loadRouters : n.getInstance().saveRouters; + return a.forEach(function(s) { + var o = s(t, r); + o !== null && i.push(o); + }), i; + }, n; + }(), iS = function(n) { + return rn.registerSaveRouter(n); + }, aS = function(n) { + return rn.registerLoadRouter(n); + }, sS = function(n) { + return rn.getSaveHandlers(n); + }, oS = function(n, t) { + return rn.getLoadHandlers(n, t); + }; + var vu = "tensorflowjs", wu = 1, Pr = "models_store", fr = "model_info_store"; + function xm() { + if (!qe().getBool("IS_BROWSER")) + throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser."); + var n = typeof window == "undefined" ? self : window, t = n.indexedDB || n.mozIndexedDB || n.webkitIndexedDB || n.msIndexedDB || n.shimIndexedDB; + if (t == null) + throw new Error("The current browser does not appear to support IndexedDB."); + return t; + } + function bu(n) { + var t = n.result; + t.createObjectStore(Pr, {keyPath: "modelPath"}), t.createObjectStore(fr, {keyPath: "modelPath"}); + } + var Ti = function() { + function n(t) { + if (this.indexedDB = xm(), t == null || !t) + throw new Error("For IndexedDB, modelPath must not be null, undefined or empty."); + this.modelPath = t; + } + return n.prototype.save = function(t) { + return pe(this, void 0, void 0, function() { + return fe(this, function(e) { + if (t.modelTopology instanceof ArrayBuffer) + throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet."); + return [2, this.databaseAction(this.modelPath, t)]; + }); + }); + }, n.prototype.load = function() { + return pe(this, void 0, void 0, function() { + return fe(this, function(t) { + return [2, this.databaseAction(this.modelPath)]; + }); + }); + }, n.prototype.databaseAction = function(t, e) { + var r = this; + return new Promise(function(i, a) { + var s = r.indexedDB.open(vu, wu); + s.onupgradeneeded = function() { + return bu(s); + }, s.onsuccess = function() { + var o = s.result; + if (e == null) { + var c = o.transaction(Pr, "readonly"), l = c.objectStore(Pr), u = l.get(r.modelPath); + u.onsuccess = function() { + if (u.result == null) + return o.close(), a(new Error("Cannot find model with path '" + r.modelPath + "' in IndexedDB.")); + i(u.result.modelArtifacts); + }, u.onerror = function(g) { + return o.close(), a(u.error); + }, c.oncomplete = function() { + return o.close(); + }; + } else { + var h = Ia(e), d = o.transaction(fr, "readwrite"), p = d.objectStore(fr), f = p.put({modelPath: r.modelPath, modelArtifactsInfo: h}), m; + f.onsuccess = function() { + m = o.transaction(Pr, "readwrite"); + var g = m.objectStore(Pr), y = g.put({modelPath: r.modelPath, modelArtifacts: e, modelArtifactsInfo: h}); + y.onsuccess = function() { + return i({modelArtifactsInfo: h}); + }, y.onerror = function(w) { + p = d.objectStore(fr); + var b = p.delete(r.modelPath); + b.onsuccess = function() { + return o.close(), a(y.error); + }, b.onerror = function(x) { + return o.close(), a(y.error); + }; + }; + }, f.onerror = function(g) { + return o.close(), a(f.error); + }, d.oncomplete = function() { + m == null ? o.close() : m.oncomplete = function() { + return o.close(); + }; + }; + } + }, s.onerror = function(o) { + return a(s.error); + }; + }); + }, n.URL_SCHEME = "indexeddb://", n; + }(), Lm = function(n) { + return qe().getBool("IS_BROWSER") && (!Array.isArray(n) && n.startsWith(Ti.URL_SCHEME)) ? cS(n.slice(Ti.URL_SCHEME.length)) : null; + }; + rn.registerSaveRouter(Lm); + rn.registerLoadRouter(Lm); + function cS(n) { + return new Ti(n); + } + function lS(n) { + return n.startsWith(Ti.URL_SCHEME) ? n.slice(Ti.URL_SCHEME.length) : n; + } + var uS = function() { + function n() { + this.indexedDB = xm(); + } + return n.prototype.listModels = function() { + return pe(this, void 0, void 0, function() { + var t = this; + return fe(this, function(e) { + return [2, new Promise(function(r, i) { + var a = t.indexedDB.open(vu, wu); + a.onupgradeneeded = function() { + return bu(a); + }, a.onsuccess = function() { + var s = a.result, o = s.transaction(fr, "readonly"), c = o.objectStore(fr), l = c.getAll(); + l.onsuccess = function() { + for (var u = {}, h = 0, d = l.result; h < d.length; h++) { + var p = d[h]; + u[p.modelPath] = p.modelArtifactsInfo; + } + r(u); + }, l.onerror = function(u) { + return s.close(), i(l.error); + }, o.oncomplete = function() { + return s.close(); + }; + }, a.onerror = function(s) { + return i(a.error); + }; + })]; + }); + }); + }, n.prototype.removeModel = function(t) { + return pe(this, void 0, void 0, function() { + var e = this; + return fe(this, function(r) { + return t = lS(t), [2, new Promise(function(i, a) { + var s = e.indexedDB.open(vu, wu); + s.onupgradeneeded = function() { + return bu(s); + }, s.onsuccess = function() { + var o = s.result, c = o.transaction(fr, "readwrite"), l = c.objectStore(fr), u = l.get(t), h; + u.onsuccess = function() { + if (u.result == null) + return o.close(), a(new Error("Cannot find model with path '" + t + "' in IndexedDB.")); + var d = l.delete(t), p = function() { + h = o.transaction(Pr, "readwrite"); + var f = h.objectStore(Pr), m = f.delete(t); + m.onsuccess = function() { + return i(u.result.modelArtifactsInfo); + }, m.onerror = function(g) { + return a(u.error); + }; + }; + d.onsuccess = p, d.onerror = function(f) { + return p(), o.close(), a(u.error); + }; + }, u.onerror = function(d) { + return o.close(), a(u.error); + }, c.oncomplete = function() { + h == null ? o.close() : h.oncomplete = function() { + return o.close(); + }; + }; + }, s.onerror = function(o) { + return a(s.error); + }; + })]; + }); + }); + }, n; + }(); + var jn = "/", Ni = "tensorflowjs_models", Sm = "info", hS = "model_topology", dS = "weight_specs", pS = "weight_data", fS = "model_metadata"; + function Im(n) { + return {info: [Ni, n, Sm].join(jn), topology: [Ni, n, hS].join(jn), weightSpecs: [Ni, n, dS].join(jn), weightData: [Ni, n, pS].join(jn), modelMetadata: [Ni, n, fS].join(jn)}; + } + function mS(n) { + var t = n.split(jn); + if (t.length < 3) + throw new Error("Invalid key format: " + n); + return t.slice(1, t.length - 1).join(jn); + } + function gS(n) { + return n.startsWith(_i.URL_SCHEME) ? n.slice(_i.URL_SCHEME.length) : n; + } + var _i = function() { + function n(t) { + if (!qe().getBool("IS_BROWSER") || typeof window == "undefined" || typeof window.localStorage == "undefined") + throw new Error("The current environment does not support local storage."); + if (this.LS = window.localStorage, t == null || !t) + throw new Error("For local storage, modelPath must not be null, undefined or empty."); + this.modelPath = t, this.keys = Im(this.modelPath); + } + return n.prototype.save = function(t) { + return pe(this, void 0, void 0, function() { + var e, r, i; + return fe(this, function(a) { + if (t.modelTopology instanceof ArrayBuffer) + throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet."); + e = JSON.stringify(t.modelTopology), r = JSON.stringify(t.weightSpecs), i = Ia(t); + try { + return this.LS.setItem(this.keys.info, JSON.stringify(i)), this.LS.setItem(this.keys.topology, e), this.LS.setItem(this.keys.weightSpecs, r), this.LS.setItem(this.keys.weightData, QL(t.weightData)), this.LS.setItem(this.keys.modelMetadata, JSON.stringify({format: t.format, generatedBy: t.generatedBy, convertedBy: t.convertedBy, userDefinedMetadata: t.userDefinedMetadata})), [2, {modelArtifactsInfo: i}]; + } catch (s) { + throw this.LS.removeItem(this.keys.info), this.LS.removeItem(this.keys.topology), this.LS.removeItem(this.keys.weightSpecs), this.LS.removeItem(this.keys.weightData), this.LS.removeItem(this.keys.modelMetadata), new Error("Failed to save model '" + this.modelPath + "' to local storage: size quota being exceeded is a possible cause of this failure: " + ("modelTopologyBytes=" + i.modelTopologyBytes + ", ") + ("weightSpecsBytes=" + i.weightSpecsBytes + ", ") + ("weightDataBytes=" + i.weightDataBytes + ".")); + } + return [2]; + }); + }); + }, n.prototype.load = function() { + return pe(this, void 0, void 0, function() { + var t, e, r, i, a, s, o; + return fe(this, function(c) { + if (t = JSON.parse(this.LS.getItem(this.keys.info)), t == null) + throw new Error("In local storage, there is no model with name '" + this.modelPath + "'"); + if (t.modelTopologyType !== "JSON") + throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet."); + if (e = {}, r = JSON.parse(this.LS.getItem(this.keys.topology)), r == null) + throw new Error("In local storage, the topology of model '" + this.modelPath + "' is missing."); + if (e.modelTopology = r, i = JSON.parse(this.LS.getItem(this.keys.weightSpecs)), i == null) + throw new Error("In local storage, the weight specs of model '" + this.modelPath + "' are missing."); + if (e.weightSpecs = i, a = this.LS.getItem(this.keys.modelMetadata), a != null && (s = JSON.parse(a), e.format = s.format, e.generatedBy = s.generatedBy, e.convertedBy = s.convertedBy, e.userDefinedMetadata = s.userDefinedMetadata), o = this.LS.getItem(this.keys.weightData), o == null) + throw new Error("In local storage, the binary weight values of model " + ("'" + this.modelPath + "' are missing.")); + return e.weightData = eS(o), [2, e]; + }); + }); + }, n.URL_SCHEME = "localstorage://", n; + }(), Am = function(n) { + return qe().getBool("IS_BROWSER") && (!Array.isArray(n) && n.startsWith(_i.URL_SCHEME)) ? yS(n.slice(_i.URL_SCHEME.length)) : null; + }; + rn.registerSaveRouter(Am); + rn.registerLoadRouter(Am); + function yS(n) { + return new _i(n); + } + var vS = function() { + function n() { + E(qe().getBool("IS_BROWSER"), function() { + return "Current environment is not a web browser"; + }), E(typeof window == "undefined" || typeof window.localStorage != "undefined", function() { + return "Current browser does not appear to support localStorage"; + }), this.LS = window.localStorage; + } + return n.prototype.listModels = function() { + return pe(this, void 0, void 0, function() { + var t, e, r, i, a, s; + return fe(this, function(o) { + for (t = {}, e = Ni + jn, r = jn + Sm, i = 0; i < this.LS.length; ++i) + a = this.LS.key(i), a.startsWith(e) && a.endsWith(r) && (s = mS(a), t[s] = JSON.parse(this.LS.getItem(a))); + return [2, t]; + }); + }); + }, n.prototype.removeModel = function(t) { + return pe(this, void 0, void 0, function() { + var e, r; + return fe(this, function(i) { + if (t = gS(t), e = Im(t), this.LS.getItem(e.info) == null) + throw new Error("Cannot find model at path '" + t + "'"); + return r = JSON.parse(this.LS.getItem(e.info)), this.LS.removeItem(e.info), this.LS.removeItem(e.topology), this.LS.removeItem(e.weightSpecs), this.LS.removeItem(e.weightData), [2, r]; + }); + }); + }, n; + }(); + var Ci = "://", mr = function() { + function n() { + this.managers = {}; + } + return n.getInstance = function() { + return n.instance == null && (n.instance = new n()), n.instance; + }, n.registerManager = function(t, e) { + E(t != null, function() { + return "scheme must not be undefined or null."; + }), t.endsWith(Ci) && (t = t.slice(0, t.indexOf(Ci))), E(t.length > 0, function() { + return "scheme must not be an empty string."; + }); + var r = n.getInstance(); + E(r.managers[t] == null, function() { + return "A model store manager is already registered for scheme '" + t + "'."; + }), r.managers[t] = e; + }, n.getManager = function(t) { + var e = this.getInstance().managers[t]; + if (e == null) + throw new Error("Cannot find model manager for scheme '" + t + "'"); + return e; + }, n.getSchemes = function() { + return Object.keys(this.getInstance().managers); + }, n; + }(); + function Os(n) { + if (n.indexOf(Ci) === -1) + throw new Error("The url string provided does not contain a scheme. Supported schemes are: " + ("" + mr.getSchemes().join(","))); + return {scheme: n.split(Ci)[0], path: n.split(Ci)[1]}; + } + function Tm(n, t, e) { + return e === void 0 && (e = false), pe(this, void 0, void 0, function() { + var r, i, a, s, o, c, l, u, h; + return fe(this, function(d) { + switch (d.label) { + case 0: + return E(n !== t, function() { + return "Old path and new path are the same: '" + n + "'"; + }), r = rn.getLoadHandlers(n), E(r.length > 0, function() { + return "Copying failed because no load handler is found for source URL " + n + "."; + }), E(r.length < 2, function() { + return "Copying failed because more than one (" + r.length + ") " + ("load handlers for source URL " + n + "."); + }), i = r[0], a = rn.getSaveHandlers(t), E(a.length > 0, function() { + return "Copying failed because no save handler is found for destination " + ("URL " + t + "."); + }), E(a.length < 2, function() { + return "Copying failed because more than one (" + r.length + ") " + ("save handlers for destination URL " + t + "."); + }), s = a[0], o = Os(n).scheme, c = Os(n).path, l = o === Os(n).scheme, [4, i.load()]; + case 1: + return u = d.sent(), e && l ? [4, mr.getManager(o).removeModel(c)] : [3, 3]; + case 2: + d.sent(), d.label = 3; + case 3: + return [4, s.save(u)]; + case 4: + return h = d.sent(), e && !l ? [4, mr.getManager(o).removeModel(c)] : [3, 6]; + case 5: + d.sent(), d.label = 6; + case 6: + return [2, h.modelArtifactsInfo]; + } + }); + }); + } + function wS() { + return pe(this, void 0, void 0, function() { + var n, t, e, r, i, a, s, o; + return fe(this, function(c) { + switch (c.label) { + case 0: + n = mr.getSchemes(), t = {}, e = 0, r = n, c.label = 1; + case 1: + return e < r.length ? (i = r[e], [4, mr.getManager(i).listModels()]) : [3, 4]; + case 2: + a = c.sent(); + for (s in a) + o = i + Ci + s, t[o] = a[s]; + c.label = 3; + case 3: + return e++, [3, 1]; + case 4: + return [2, t]; + } + }); + }); + } + function bS(n) { + return pe(this, void 0, void 0, function() { + var t, e; + return fe(this, function(r) { + return t = Os(n), e = mr.getManager(t.scheme), [2, e.removeModel(t.path)]; + }); + }); + } + function xS(n, t) { + return pe(this, void 0, void 0, function() { + var e; + return fe(this, function(r) { + return e = false, [2, Tm(n, t, e)]; + }); + }); + } + function LS(n, t) { + return pe(this, void 0, void 0, function() { + var e; + return fe(this, function(r) { + return e = true, [2, Tm(n, t, e)]; + }); + }); + } + var SS = function() { + function n() { + } + return n.prototype.fetch = function(t, e) { + return fetch(t, e); + }, n.prototype.now = function() { + return performance.now(); + }, n.prototype.encode = function(t, e) { + if (e !== "utf-8" && e !== "utf8") + throw new Error("Browser's encoder only supports utf-8, but got " + e); + return this.textEncoder == null && (this.textEncoder = new TextEncoder()), this.textEncoder.encode(t); + }, n.prototype.decode = function(t, e) { + return new TextDecoder(e).decode(t); + }, n; + }(); + if (qe().get("IS_BROWSER")) { + qe().setPlatform("browser", new SS()); + try { + mr.registerManager(_i.URL_SCHEME, new vS()); + } catch (n) { + } + try { + mr.registerManager(Ti.URL_SCHEME, new uS()); + } catch (n) { + } + } + var IS = {importFetch: function() { + return Vp(); + }}, xu, AS = function() { + function n() { + this.util = Gp(), this.textEncoder = new this.util.TextEncoder(); + } + return n.prototype.fetch = function(t, e) { + return qe().global.fetch != null ? qe().global.fetch(t, e) : (xu == null && (xu = IS.importFetch()), xu(t, e)); + }, n.prototype.now = function() { + var t = process.hrtime(); + return t[0] * 1e3 + t[1] / 1e6; + }, n.prototype.encode = function(t, e) { + if (e !== "utf-8" && e !== "utf8") + throw new Error("Node built-in encoder only supports utf-8, but got " + e); + return this.textEncoder.encode(t); + }, n.prototype.decode = function(t, e) { + return t.length === 0 ? "" : new this.util.TextDecoder(e).decode(t); + }, n; + }(); + qe().get("IS_NODE") && qe().setPlatform("node", new AS()); + function Rn(n, t, e) { + return t === void 0 && (t = "float32"), t = t || "float32", dc(n), new _s(n, t, e); + } + function TS(n, t) { + var e = R(n, "x", "cast"); + if (!Jp(t)) + throw new Error("Failed to cast to unknown dtype " + t); + if (t === "string" && e.dtype !== "string" || t !== "string" && e.dtype === "string") + throw new Error("Only strings can be casted to strings"); + var r = {x: e}, i = {dtype: t}; + return z.runKernelFunc(function(a) { + return a.cast(e, t); + }, r, null, Is, i); + } + var he = U({cast_: TS}); + function NS(n) { + var t = R(n, "x", "clone", null), e = function() { + return z.makeTensorFromDataId(t.dataId, t.shape, t.dtype); + }, r = {x: t}; + return z.runKernelFunc(e, r, null, Zc); + } + var Mr = U({clone_: NS}); + function Nm(n, t) { + t === void 0 && (t = false), console.log(n.toString(t)); + } + pm(); + var _S = {buffer: Rn, cast: he, clone: Mr, print: Nm}; + UL(_S); + var CS = "model", RS = ".json", OS = ".weights.bin"; + function _m(n) { + return new Promise(function(t) { + return setTimeout(t); + }).then(n); + } + var Lu = function() { + function n(t) { + if (!qe().getBool("IS_BROWSER")) + throw new Error("browserDownloads() cannot proceed because the current environment is not a browser."); + t.startsWith(n.URL_SCHEME) && (t = t.slice(n.URL_SCHEME.length)), (t == null || t.length === 0) && (t = CS), this.modelTopologyFileName = t + RS, this.weightDataFileName = t + OS; + } + return n.prototype.save = function(t) { + return pe(this, void 0, void 0, function() { + var e, r, i, a, s, o; + return fe(this, function(c) { + switch (c.label) { + case 0: + if (typeof document == "undefined") + throw new Error("Browser downloads are not supported in this environment since `document` is not present"); + if (e = window.URL.createObjectURL(new Blob([t.weightData], {type: "application/octet-stream"})), !(t.modelTopology instanceof ArrayBuffer)) + return [3, 1]; + throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet."); + case 1: + return r = [{paths: ["./" + this.weightDataFileName], weights: t.weightSpecs}], i = {modelTopology: t.modelTopology, format: t.format, generatedBy: t.generatedBy, convertedBy: t.convertedBy, weightsManifest: r}, a = window.URL.createObjectURL(new Blob([JSON.stringify(i)], {type: "application/json"})), s = this.jsonAnchor == null ? document.createElement("a") : this.jsonAnchor, s.download = this.modelTopologyFileName, s.href = a, [4, _m(function() { + return s.dispatchEvent(new MouseEvent("click")); + })]; + case 2: + return c.sent(), t.weightData != null ? (o = this.weightDataAnchor == null ? document.createElement("a") : this.weightDataAnchor, o.download = this.weightDataFileName, o.href = e, [4, _m(function() { + return o.dispatchEvent(new MouseEvent("click")); + })]) : [3, 4]; + case 3: + c.sent(), c.label = 4; + case 4: + return [2, {modelArtifactsInfo: Ia(t)}]; + } + }); + }); + }, n.URL_SCHEME = "downloads://", n; + }(), ES = function() { + function n(t) { + if (t == null || t.length < 1) + throw new Error("When calling browserFiles, at least 1 file is required, " + ("but received " + t)); + this.files = t; + } + return n.prototype.load = function() { + return pe(this, void 0, void 0, function() { + var t, e, r = this; + return fe(this, function(i) { + return t = this.files[0], e = this.files.slice(1), [2, new Promise(function(a, s) { + var o = new FileReader(); + o.onload = function(c) { + var l = JSON.parse(c.target.result), u = l.modelTopology; + if (u == null) { + s(new Error("modelTopology field is missing from file " + t.name)); + return; + } + e.length === 0 && a({modelTopology: u}); + var h = l.weightsManifest; + if (h == null) { + s(new Error("weightManifest field is missing from file " + t.name)); + return; + } + var d; + try { + d = r.checkManifestAndWeightFiles(h, e); + } catch (g) { + s(g); + return; + } + var p = [], f = [], m = []; + h.forEach(function(g) { + g.paths.forEach(function(y) { + f.push(y), m.push(null); + }), p.push.apply(p, g.weights); + }), h.forEach(function(g) { + g.paths.forEach(function(y) { + var w = new FileReader(); + w.onload = function(b) { + var x = b.target.result, L = f.indexOf(y); + m[L] = x, m.indexOf(null) === -1 && a({modelTopology: u, weightSpecs: p, weightData: yu(m), format: l.format, generatedBy: l.generatedBy, convertedBy: l.convertedBy, userDefinedMetadata: l.userDefinedMetadata}); + }, w.onerror = function(b) { + return s("Failed to weights data from file of path '" + y + "'."); + }, w.readAsArrayBuffer(d[y]); + }); + }); + }, o.onerror = function(c) { + return s("Failed to read model topology and weights manifest JSON " + ("from file '" + t.name + "'. BrowserFiles supports loading ") + "Keras-style tf.Model artifacts only."); + }, o.readAsText(t); + })]; + }); + }); + }, n.prototype.checkManifestAndWeightFiles = function(t, e) { + for (var r = [], i = e.map(function(l) { + return bm(l.name); + }), a = {}, s = 0, o = t; s < o.length; s++) { + var c = o[s]; + c.paths.forEach(function(l) { + var u = bm(l); + if (r.indexOf(u) !== -1) + throw new Error("Duplicate file basename found in weights manifest: " + ("'" + u + "'")); + if (r.push(u), i.indexOf(u) === -1) + throw new Error("Weight file with basename '" + u + "' is not provided."); + a[l] = e[i.indexOf(u)]; + }); + } + if (r.length !== e.length) + throw new Error("Mismatch in the number of files in weights manifest " + ("(" + r.length + ") and the number of weight files provided ") + ("(" + e.length + ").")); + return a; + }, n; + }(), kS = function(n) { + return qe().getBool("IS_BROWSER") && (!Array.isArray(n) && n.startsWith(Lu.URL_SCHEME)) ? DS(n.slice(Lu.URL_SCHEME.length)) : null; + }; + rn.registerSaveRouter(kS); + function DS(n) { + return n === void 0 && (n = "model"), new Lu(n); + } + function FS(n) { + return new ES(n); + } + function Cm(n, t, e, r) { + s(n), e = e ?? 0, r = r ?? 1, o(e, r); + var i = 0, a = function(c) { + return c.then(function(l) { + var u = e + ++i / n.length * (r - e); + return t(u), l; + }), c; + }; + function s(c) { + E(c != null && Array.isArray(c) && c.length > 0, function() { + return "promises must be a none empty array"; + }); + } + function o(c, l) { + E(c >= 0 && c <= 1, function() { + return "Progress fraction must be in range [0, 1], but " + ("got startFraction " + c); + }), E(l >= 0 && l <= 1, function() { + return "Progress fraction must be in range [0, 1], but " + ("got endFraction " + l); + }), E(l >= c, function() { + return "startFraction must be no more than endFraction, but " + ("got startFraction " + c + " and endFraction ") + ("" + l); + }); + } + return Promise.all(n.map(a)); + } + function Rm(n, t) { + return pe(this, void 0, void 0, function() { + var e, r, i, a, s, o, c, l, u, h, d; + return fe(this, function(p) { + switch (p.label) { + case 0: + return t == null && (t = {}), e = t.fetchFunc == null ? qe().platform.fetch : t.fetchFunc, r = n.map(function(f) { + return e(f, t.requestInit, {isBinary: true}); + }), i = 0, a = 0.5, t.onProgress == null ? [4, Promise.all(r)] : [3, 2]; + case 1: + return o = p.sent(), [3, 4]; + case 2: + return [4, Cm(r, t.onProgress, i, a)]; + case 3: + o = p.sent(), p.label = 4; + case 4: + return s = o, c = s.map(function(f) { + return f.arrayBuffer(); + }), l = 0.5, u = 1, t.onProgress == null ? [4, Promise.all(c)] : [3, 6]; + case 5: + return d = p.sent(), [3, 8]; + case 6: + return [4, Cm(c, t.onProgress, l, u)]; + case 7: + d = p.sent(), p.label = 8; + case 8: + return h = d, [2, h]; + } + }); + }); + } + function WS(n, t, e, r) { + return t === void 0 && (t = ""), pe(this, void 0, void 0, function() { + var i, a; + return fe(this, function(s) { + return i = function(o) { + return Rm(o, {requestInit: r}); + }, a = Om(i), [2, a(n, t, e)]; + }); + }); + } + function Om(n) { + var t = this; + return function(e, r, i) { + return r === void 0 && (r = ""), pe(t, void 0, void 0, function() { + var a, s, o, c, l, u, h, d, p, f; + return fe(this, function(m) { + switch (m.label) { + case 0: + if (a = e.map(function() { + return false; + }), s = {}, o = i != null ? i.map(function() { + return false; + }) : [], c = [], e.forEach(function(g, y) { + var w = 0; + g.weights.forEach(function(b) { + var x = "quantization" in b ? b.quantization.dtype : b.dtype, L = mu[x] * dt(b.shape), N = function() { + a[y] = true, s[y] == null && (s[y] = []), s[y].push({manifestEntry: b, groupOffset: w, sizeBytes: L}); + }; + i != null ? i.forEach(function(I, C) { + I === b.name && (N(), o[C] = true); + }) : N(), c.push(b.name), w += L; + }); + }), !o.every(function(g) { + return g; + })) + throw l = i.filter(function(g, y) { + return !o[y]; + }), new Error("Could not find weights in manifest with names: " + (l.join(", ") + `. +`) + "Manifest JSON has weights with names: " + (c.join(", ") + ".")); + return u = a.reduce(function(g, y, w) { + return y && g.push(w), g; + }, []), h = [], u.forEach(function(g) { + e[g].paths.forEach(function(y) { + var w = r + (r.endsWith("/") ? "" : "/") + y; + h.push(w); + }); + }), [4, n(h)]; + case 1: + return d = m.sent(), p = {}, f = 0, u.forEach(function(g) { + for (var y = e[g].paths.length, w = 0, b = 0; b < y; b++) + w += d[f + b].byteLength; + for (var x = new ArrayBuffer(w), L = new Uint8Array(x), N = 0, I = 0; I < y; I++) { + var C = new Uint8Array(d[f + I]); + L.set(C, N), N += C.byteLength; + } + var O = s[g]; + O.forEach(function(D) { + var F = x.slice(D.groupOffset, D.groupOffset + D.sizeBytes), k = vm(F, [D.manifestEntry]); + for (var B in k) + p[B] = k[B]; + }), f += y; + }), [2, p]; + } + }); + }); + }; + } + var US = "application/octet-stream", BS = "application/json", Em = function() { + function n(t, e) { + if (this.DEFAULT_METHOD = "POST", e == null && (e = {}), this.weightPathPrefix = e.weightPathPrefix, this.onProgress = e.onProgress, this.weightUrlConverter = e.weightUrlConverter, e.fetchFunc != null ? (E(typeof e.fetchFunc == "function", function() { + return "Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"; + }), this.fetch = e.fetchFunc) : this.fetch = qe().platform.fetch, E(t != null && t.length > 0, function() { + return "URL path for http must not be null, undefined or empty."; + }), Array.isArray(t) && E(t.length === 2, function() { + return "URL paths for http must have a length of 2, " + ("(actual length is " + t.length + ")."); + }), this.path = t, e.requestInit != null && e.requestInit.body != null) + throw new Error("requestInit is expected to have no pre-existing body, but has one."); + this.requestInit = e.requestInit || {}; + } + return n.prototype.save = function(t) { + return pe(this, void 0, void 0, function() { + var e, r, i, a; + return fe(this, function(s) { + switch (s.label) { + case 0: + if (t.modelTopology instanceof ArrayBuffer) + throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet."); + return e = Object.assign({method: this.DEFAULT_METHOD}, this.requestInit), e.body = new FormData(), r = [{paths: ["./model.weights.bin"], weights: t.weightSpecs}], i = {modelTopology: t.modelTopology, format: t.format, generatedBy: t.generatedBy, convertedBy: t.convertedBy, userDefinedMetadata: t.userDefinedMetadata, weightsManifest: r}, e.body.append("model.json", new Blob([JSON.stringify(i)], {type: BS}), "model.json"), t.weightData != null && e.body.append("model.weights.bin", new Blob([t.weightData], {type: US}), "model.weights.bin"), [4, this.fetch(this.path, e)]; + case 1: + if (a = s.sent(), a.ok) + return [2, {modelArtifactsInfo: Ia(t), responses: [a]}]; + throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status " + (a.status + ".")); + } + }); + }); + }, n.prototype.load = function() { + return pe(this, void 0, void 0, function() { + var t, e, r, i, a, s, o, c, l, u, h, d, p, f, m; + return fe(this, function(g) { + switch (g.label) { + case 0: + return [4, this.fetch(this.path, this.requestInit)]; + case 1: + if (t = g.sent(), !t.ok) + throw new Error("Request to " + this.path + " failed with status code " + (t.status + ". Please verify this URL points to ") + "the model JSON of the model to load."); + g.label = 2; + case 2: + return g.trys.push([2, 4, , 5]), [4, t.json()]; + case 3: + return e = g.sent(), [3, 5]; + case 4: + throw r = g.sent(), i = "Failed to parse model JSON of response from " + this.path + ".", this.path.endsWith(".pb") ? i += " Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository." : i += " Please make sure the server is serving valid JSON for this request.", new Error(i); + case 5: + if (a = e.modelTopology, s = e.weightsManifest, o = e.generatedBy, c = e.convertedBy, l = e.format, u = e.userDefinedMetadata, a == null && s == null) + throw new Error("The JSON from HTTP path " + this.path + " contains neither model topology or manifest for weights."); + return s != null ? [4, this.loadWeights(s)] : [3, 7]; + case 6: + p = g.sent(), h = p[0], d = p[1], g.label = 7; + case 7: + return f = {modelTopology: a, weightSpecs: h, weightData: d, userDefinedMetadata: u, generatedBy: o, convertedBy: c, format: l}, m = e.modelInitializer, m && (f.modelInitializer = m), [2, f]; + } + }); + }); + }, n.prototype.loadWeights = function(t) { + return pe(this, void 0, void 0, function() { + var e, r, i, a, s, o, c, l, u, h, d, p, f, m, g, y, w, b, x, L, N; + return fe(this, function(I) { + switch (I.label) { + case 0: + for (e = Array.isArray(this.path) ? this.path[1] : this.path, r = zS(e), i = r[0], a = r[1], s = this.weightPathPrefix || i, o = [], c = 0, l = t; c < l.length; c++) + u = l[c], o.push.apply(o, u.weights); + for (h = [], d = [], p = 0, f = t; p < f.length; p++) + for (m = f[p], g = 0, y = m.paths; g < y.length; g++) + w = y[g], this.weightUrlConverter != null ? d.push(this.weightUrlConverter(w)) : h.push(s + w + a); + return this.weightUrlConverter ? (x = (b = h.push).apply, L = [h], [4, Promise.all(d)]) : [3, 2]; + case 1: + x.apply(b, L.concat([I.sent()])), I.label = 2; + case 2: + return [4, Rm(h, {requestInit: this.requestInit, fetchFunc: this.fetch, onProgress: this.onProgress})]; + case 3: + return N = I.sent(), [2, [o, yu(N)]]; + } + }); + }); + }, n.URL_SCHEME_REGEX = /^https?:\/\//, n; + }(); + function zS(n) { + var t = n.lastIndexOf("/"), e = n.lastIndexOf("?"), r = n.substring(0, t), i = e > t ? n.substring(e) : ""; + return [r + "/", i]; + } + function Su(n) { + return n.match(Em.URL_SCHEME_REGEX) != null; + } + var Dm = function(n, t) { + if (typeof fetch == "undefined" && (t == null || t.fetchFunc == null)) + return null; + var e = true; + return Array.isArray(n) ? e = n.every(function(r) { + return Su(r); + }) : e = Su(n), e ? Iu(n, t) : null; + }; + rn.registerSaveRouter(Dm); + rn.registerLoadRouter(Dm); + function Iu(n, t) { + return new Em(n, t); + } + function PS(n, t) { + return Iu(n, t); + } + var Au = function() { + function n(t) { + this.modelArtifacts = t; + } + return n.prototype.load = function() { + return pe(this, void 0, void 0, function() { + return fe(this, function(t) { + return [2, this.modelArtifacts]; + }); + }); + }, n; + }(), MS = function() { + function n(t) { + this.saveHandler = t; + } + return n.prototype.save = function(t) { + return pe(this, void 0, void 0, function() { + return fe(this, function(e) { + return [2, this.saveHandler(t)]; + }); + }); + }, n; + }(); + function HS(n, t, e, r) { + if (arguments.length === 1) { + var i = n.modelTopology != null || n.weightSpecs != null; + return i ? new Au(n) : (console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."), new Au({modelTopology: n})); + } else + return console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."), new Au({modelTopology: n, weightSpecs: t, weightData: e, trainingConfig: r}); + } + function VS(n) { + return new MS(n); + } + var GS = {__proto__: null, browserFiles: FS, browserHTTPRequest: PS, concatenateArrayBuffers: yu, decodeWeights: vm, encodeWeights: JL, fromMemory: HS, getLoadHandlers: oS, getModelArtifactsInfoForJSON: Ia, getSaveHandlers: sS, http: Iu, isHTTPScheme: Su, loadWeights: WS, registerLoadRouter: aS, registerSaveRouter: iS, weightsLoaderFactory: Om, withSaveHandler: VS, copyModel: xS, listModels: wS, moveModel: LS, removeModel: bS}; + function qS(n, t) { + var e = R(n, "x", "reshape", null), r = {x: e}, i = {shape: t}, a = function(s, o) { + return t = Kp(t, e.size), E(e.size === dt(t), function() { + return "new shape and old shape must have the same number of elements."; + }), o([e]), s.reshape(e, t); + }; + return z.runKernelFunc(a, r, null, Sl, i); + } + var Y = U({reshape_: qS}); + function YS(n, t, e, r) { + var i; + e === void 0 && (e = false), r === void 0 && (r = false); + var a = R(n, "a", "matMul"), s = R(t, "b", "matMul"); + i = ct(a, s), a = i[0], s = i[1]; + var o = function(u, h) { + h([a, s]); + var d = e ? a.shape[a.rank - 2] : a.shape[a.rank - 1], p = r ? s.shape[s.rank - 1] : s.shape[s.rank - 2], f = e ? a.shape[a.rank - 1] : a.shape[a.rank - 2], m = r ? s.shape[s.rank - 2] : s.shape[s.rank - 1], g = a.shape.slice(0, -2), y = s.shape.slice(0, -2), w = dt(g), b = dt(y), x = w === b || w === 1 || b === 1; + E(a.rank >= 2 && s.rank >= 2 && x, function() { + return "Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input " + ("batch dimensions of (" + g + ") and (" + y + ")."); + }), E(d === p, function() { + return "Error in matMul: inner shapes (" + d + ") and (" + (p + ") of Tensors with shapes " + a.shape + " and ") + (s.shape + " and transposeA=" + e) + (" and transposeB=" + r + " must match."); + }); + var L = w > b ? g : y, N = L.concat([f, m]), I = e ? Y(a, [w, d, f]) : Y(a, [w, f, d]), C = r ? Y(s, [b, m, p]) : Y(s, [b, p, m]), O = u.batchMatMul(I, C, e, r); + return Y(O, N); + }, c = {a, b: s}, l = {transposeA: e, transposeB: r}; + return z.runKernelFunc(o, c, null, _c, l); + } + var Ue = U({matMul_: YS}); + function KS(n, t, e, r) { + if (e === void 0 && (e = 1), r === void 0 && (r = 0), t < 2) + throw new Error("Error in oneHot: depth must be >=2, but it is " + t); + var i = R(n, "indices", "oneHot", "int32"), a = i.shape.concat([t]), s = function(l, u) { + return u([i]), Y(l.oneHot(Y(i, [i.size]), t, e, r), a); + }, o = {indices: i}, c = {depth: t, onValue: e, offValue: r}; + return z.runKernelFunc(s, o, null, yl, c); + } + var Es = U({oneHot_: KS}); + function jS(n, t) { + var e = R(n, "x", "transpose"); + if (t == null && (t = e.shape.map(function(a, s) { + return s; + }).reverse()), E(e.rank === t.length, function() { + return "Error in transpose: rank of input " + e.rank + " " + ("must match length of perm " + t + "."); + }), t.forEach(function(a) { + E(a >= 0 && a < e.rank, function() { + return "All entries in 'perm' must be between 0 and " + (e.rank - 1) + (" but got " + t); + }); + }), e.rank <= 1) + return e.clone(); + var r = {x: e}, i = {perm: t}; + return z.runKernelFunc(function(a) { + return a.transpose(e, t); + }, r, null, jl, i); + } + var Tt = U({transpose_: jS}); + function $S(n, t, e) { + var r = R(n, "labels", "confusionMatrix"), i = R(t, "predictions", "confusionMatrix"); + E(e == null || e > 0 && Number.isInteger(e), function() { + return "If provided, numClasses must be a positive integer, " + ("but got " + e); + }), E(r.rank === 1, function() { + return "Expected the rank of labels to be 1, but got " + r.rank; + }), E(i.rank === 1, function() { + return "Expected the rank of predictions to be 1, " + ("but got " + i.rank); + }), E(r.shape[0] === i.shape[0], function() { + return "Mismatch in the number of examples: " + (r.shape[0] + " vs. " + i.shape[0] + ". ") + "Labels and predictions should have the same number of elements."; + }), E(e > 0 && Number.isInteger(e), function() { + return "numClasses is required to be a positive integer, but got " + ("" + e); + }); + var a = Es(he(r, "int32"), e), s = Es(he(i, "int32"), e), o = Tt(a), c = Ue(o, s); + return he(c, "int32"); + } + var XS = U({confusionMatrix_: $S}); + var JS = {__proto__: null, confusionMatrix: XS}; + function km(n, t, e) { + if (Br(n), t != null && t.length !== 3) + throw new Error("tensor3d() requires shape to have three numbers"); + var r = Cn(n, e); + if (r.length !== 3 && r.length !== 1) + throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray"); + if (r.length === 1 && t == null) + throw new Error("tensor3d() requires shape to be provided when `values` are a flat array"); + return dr(n, t, r, e); + } + var Ri; + function ZS(n, t) { + if (t === void 0 && (t = 3), t > 4) + throw new Error("Cannot construct Tensor with more than 4 channels from pixels."); + if (n == null) + throw new Error("pixels passed to tf.browser.fromPixels() can not be null"); + var e = false, r = false, i = false, a = false, s = false; + if (n.data instanceof Uint8Array) + e = true; + else if (typeof ImageData != "undefined" && n instanceof ImageData) + r = true; + else if (typeof HTMLVideoElement != "undefined" && n instanceof HTMLVideoElement) + i = true; + else if (typeof HTMLImageElement != "undefined" && n instanceof HTMLImageElement) + a = true; + else if (n.getContext != null) + s = true; + else + throw new Error("pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, " + ("but was " + n.constructor.name)); + if (i) { + var o = 2; + if (i && n.readyState < o) + throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the