From 04a5f9873419ae14d2ee59e0c4d2891b98863b24 Mon Sep 17 00:00:00 2001 From: Vladimir Mandic Date: Sat, 7 Nov 2020 11:34:56 -0500 Subject: [PATCH] update build --- dist/demo-browser-index.js | 33020 ++++++++++++++++++++++++++++-- dist/demo-browser-index.js.map | 2 +- dist/demo-browser-index.json | 14 +- dist/human.esm-nobundle.js | 14 +- dist/human.esm-nobundle.js.map | 4 +- dist/human.esm-nobundle.json | 40 +- dist/human.esm.js | 2 +- dist/human.js | 4 +- dist/human.js.map | 4 +- dist/human.json | 40 +- dist/human.node-nobundle.js | 14 +- dist/human.node-nobundle.js.map | 4 +- dist/human.node.js | 4 +- dist/human.node.js.map | 4 +- dist/human.node.json | 40 +- 15 files changed, 31661 insertions(+), 1549 deletions(-) diff --git a/dist/demo-browser-index.js b/dist/demo-browser-index.js index 1d45043d..0c864baa 100644 --- a/dist/demo-browser-index.js +++ b/dist/demo-browser-index.js @@ -1,75 +1,24759 @@ -var ff=Object.defineProperty,tg=N=>ff(N,"__esModule",{value:!0}),Or=(N,i)=>()=>(i||(i={exports:{}},N(i.exports,i)),i.exports),Zh=(N,i)=>{tg(N);for(var we in i)ff(N,we,{get:i[we],enumerable:!0})},rg=Or(()=>{}),ng=Or(()=>{}),Bp=Or(()=>{}),ml=Or(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 we(t,e){i(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function M(t,e,n,a){return new(n||(n=Promise))(function(c,d){function y(C){try{_(a.next(C))}catch(F){d(F)}}function v(C){try{_(a.throw(C))}catch(F){d(F)}}function _(C){C.done?c(C.value):new n(function(F){F(C.value)}).then(y,v)}_((a=a.apply(t,e||[])).next())})}function V(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(F){return _([C,F])}}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 ye(t,e,n){return Math.max(t,Math.min(e,n))}function ee(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 rr(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 jt(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 Pr(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 ar(t,e){for(var n=0;n=0;--a)n[a]=n[a+1]*t[a+1];return n}function fn(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 Wn(t,e,n){if(e===0)return 0;if(e===1)return t[0];for(var a=t[t.length-1],c=0;c0?Le:"")+" "}}console.log("%c"+_+" %c"+v+" %c"+C+"D "+B+" %c"+F+" %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 se=20,te=3,_e=7;function ce(t,e,n,a){var c=za(e),d=fe(t,e,n,c),y=e.length,v=Ae(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 fe(t,e,n,a){var c=It(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;Cse){var F=te*y,B=Array.from(t.slice(0,F)),U=Array.from(t.slice((v-te)*y,v*y));return n==="complex64"&&(B=Oe(B),U=Oe(U)),["["+B.map(function(nr,yr){return ve(nr,c[yr],n)}).join(", ")+", ..., "+U.map(function(nr,yr){return ve(nr,c[v-te+yr],n)}).join(", ")+"]"]}var J=n==="complex64"?Oe(t):Array.from(t);return["["+J.map(function(nr,yr){return ve(nr,c[yr],n)}).join(", ")+"]"]}var me=e.slice(1),Le=a.slice(1),Me=a[0]*y,He=[];if(v>se){for(var lt=0;lt=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,F=[],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 me,Le=Ps(c,this.backendName),Me;if(Le!=null)me=function(){var Nt=_.backend.numDataIds();Me=Le.kernelFunc({inputs:n,attrs:d,backend:_.backend});var Ct=Array.isArray(Me)?Me:[Me];_.shouldCheckForMemLeaks()&&_.checkKernelForMemLeak(c,Nt,Ct);var Bt=Ct.map(function(yr){var Gr=yr.dataId,en=yr.shape,Zr=yr.dtype;return _.makeTensorFromDataId(Gr,en,Zr)});if(B){var ur=_.getTensorsForGradient(c,n,Bt);if(ur==null){v==null&&(v=[]);var nr=Bt.filter(function(yr,Gr){return v[Gr]});ur=(y||[]).slice().concat(nr)}F=_.saveTensorsForBackwardMode(ur)}return Bt};else{var He=function(Nt){if(!B)return;F=Nt.map(function(Ct){return _.keep(_.clone(Ct))})};me=function(){var Nt=_.backend.numDataIds();Me=_.tidy(function(){return e(_.backend,He)});var Ct=Array.isArray(Me)?Me:[Me];return _.shouldCheckForMemLeaks()&&_.checkKernelForMemLeak(c,Nt,Ct),Ct}}var lt;return this.scopedRun(function(){return _.state.kernelDepth++},function(){return _.state.kernelDepth--},function(){!_.ENV.getBool("DEBUG")&&!_.state.profiling?C=me():(lt=_.profiler.profileKernel(c,n,function(){return me()}),_.ENV.getBool("DEBUG")&&_.profiler.logKernelProfile(lt),C=lt.outputs)}),B&&this.addTapeNode(c,n,C,a,F,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(Nt){return n[Nt]!=null?n[Nt].shape:null}),outputShapes:C.map(function(Nt){return Nt.shape}),kernelTimeMs:lt.timeMs,extraInfo:lt.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=Bs(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,F){return y[F]});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"&&ta(e[0])&&(d=e.map(function(F){return Yi(F)}));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=ka(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 rt(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*ba(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 rt||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 M(this,void 0,void 0,function(){var n,a,c,d,y,v,_,C;return V(this,function(F){switch(F.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=F.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,F.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=Bs(e);C!=null&&(c=C.gradFunc),c!=null&&(_.gradient=function(F){return F=F.map(function(B,U){if(B==null){var J=a[U],me=fa(J.size,J.dtype);return v.makeTensor(me,J.shape,J.dtype)}return B}),c(F.length>1?F:F[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==null?lr(y.shape):a,H(_,v,function(F){return d.tidy(F)},br);var C=n.map(function(F){return _[F.id]});return d.state.gradientDepth===0&&(d.state.activeTape.forEach(function(F){for(var B=0,U=F.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),_n(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"?ki(t,c):Kt(t,[],v);return Ie.makeTensor(_,y,c)}function In(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 wn="__op";function Re(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+wn;var c=function(){for(var d=[],y=0;y>10]+(v&1023)]+e[v>>10];d[y]=_}return new Float32Array(c)}}var ui=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}(),ku=function(t){return ui.registerSaveRouter(t)},Su=function(t){return ui.registerLoadRouter(t)},lc=function(t){return ui.getSaveHandlers(t)},_s=function(t,e){return ui.getLoadHandlers(t,e)},Si="tensorflowjs",ws=1,bo="models_store",uo="model_info_store";function Iu(){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 su(t){var e=t.result;e.createObjectStore(bo,{keyPath:"modelPath"}),e.createObjectStore(uo,{keyPath:"modelPath"})}var bs=function(){function t(e){if(this.indexedDB=Iu(),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 M(this,void 0,void 0,function(){return V(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 M(this,void 0,void 0,function(){return V(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(Si,ws);y.onupgradeneeded=function(){return su(y)},y.onsuccess=function(){var v=y.result;if(n==null){var _=v.transaction(bo,"readonly"),C=_.objectStore(bo),F=C.get(a.modelPath);F.onsuccess=function(){if(F.result==null)return v.close(),d(new Error("Cannot find model with path '"+a.modelPath+"' in IndexedDB."));c(F.result.modelArtifacts)},F.onerror=function(Me){return v.close(),d(F.error)},_.oncomplete=function(){return v.close()}}else{var B=dn(n),U=v.transaction(uo,"readwrite"),J=U.objectStore(uo),me=J.put({modelPath:a.modelPath,modelArtifactsInfo:B}),Le;me.onsuccess=function(){Le=v.transaction(bo,"readwrite");var Me=Le.objectStore(bo),He=Me.put({modelPath:a.modelPath,modelArtifacts:n,modelArtifactsInfo:B});He.onsuccess=function(){return c({modelArtifactsInfo:B})},He.onerror=function(lt){J=U.objectStore(uo);var Nt=J.delete(a.modelPath);Nt.onsuccess=function(){return v.close(),d(He.error)},Nt.onerror=function(Ct){return v.close(),d(He.error)}}},me.onerror=function(Me){return v.close(),d(me.error)},U.oncomplete=function(){Le==null?v.close():Le.oncomplete=function(){return v.close()}}}},y.onerror=function(v){return d(y.error)}})},t.URL_SCHEME="indexeddb://",t}(),Nu=function(t){return Rr().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(bs.URL_SCHEME)?uu(t.slice(bs.URL_SCHEME.length)):null};ui.registerSaveRouter(Nu),ui.registerLoadRouter(Nu);function uu(t){return new bs(t)}function Cu(t){return t.startsWith(bs.URL_SCHEME)?t.slice(bs.URL_SCHEME.length):t}var hc=function(){function t(){this.indexedDB=Iu()}return t.prototype.listModels=function(){return M(this,void 0,void 0,function(){var e=this;return V(this,function(n){return[2,new Promise(function(a,c){var d=e.indexedDB.open(Si,ws);d.onupgradeneeded=function(){return su(d)},d.onsuccess=function(){var y=d.result,v=y.transaction(uo,"readonly"),_=v.objectStore(uo),C=_.getAll();C.onsuccess=function(){for(var F={},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: "+(""+lo.getSchemes().join(",")));return{scheme:t.split(Wo)[0],path:t.split(Wo)[1]}}function cu(t,e,n){return n===void 0&&(n=!1),M(this,void 0,void 0,function(){var a,c,d,y,v,_,C,F,B;return V(this,function(U){switch(U.label){case 0:return W(t!==e,function(){return"Old path and new path are the same: '"+t+"'"}),a=ui.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=ui.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 F=U.sent(),n&&C?[4,lo.getManager(v).removeModel(_)]:[3,3];case 2:U.sent(),U.label=3;case 3:return[4,y.save(F)];case 4:return B=U.sent(),n&&!C?[4,lo.getManager(v).removeModel(_)]:[3,6];case 5:U.sent(),U.label=6;case 6:return[2,B.modelArtifactsInfo]}})})}function os(){return M(this,void 0,void 0,function(){var t,e,n,a,c,d,y,v;return V(this,function(_){switch(_.label){case 0:t=lo.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 hu(t,e){return M(this,void 0,void 0,function(){var n,a,c,d,y,v,_,C,F,B,U;return V(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(me){return n(me,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(me){return me.arrayBuffer()}),C=.5,F=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,F)];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=""),M(this,void 0,void 0,function(){var c,d;return V(this,function(y){return c=function(v){return hu(v,{requestInit:a})},d=Ou(c),[2,d(t,e,n)]})})}function Ou(t){var e=this;return function(n,a,c){return a===void 0&&(a=""),M(e,void 0,void 0,function(){var d,y,v,_,C,F,B,U,J,me;return V(this,function(Le){switch(Le.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 lt=0;Me.weights.forEach(function(Nt){var Ct="quantization"in Nt?Nt.quantization.dtype:Nt.dtype,Bt=Ja[Ct]*It(Nt.shape),ur=function(){d[He]=!0,y[He]==null&&(y[He]=[]),y[He].push({manifestEntry:Nt,groupOffset:lt,sizeBytes:Bt})};c!=null?c.forEach(function(nr,yr){nr===Nt.name&&(ur(),v[yr]=!0)}):ur(),_.push(Nt.name),lt+=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 F=d.reduce(function(Me,He,lt){return He&&Me.push(lt),Me},[]),B=[],F.forEach(function(Me){n[Me].paths.forEach(function(He){var lt=a+(a.endsWith("/")?"":"/")+He;B.push(lt)})}),[4,t(B)];case 1:return U=Le.sent(),J={},me=0,F.forEach(function(Me){for(var He=n[Me].paths.length,lt=0,Nt=0;Nt0,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 M(this,void 0,void 0,function(){var n,a,c,d;return V(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:fo}),"model.json"),e.weightData!=null&&n.body.append("model.weights.bin",new Blob([e.weightData],{type:Hs}),"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 M(this,void 0,void 0,function(){var e,n,a,c,d,y,v,_,C,F,B,U,J,me,Le;return V(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,F=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 me={modelTopology:d,weightSpecs:B,weightData:U,userDefinedMetadata:F,generatedBy:v,convertedBy:_,format:C},Le=n.modelInitializer,Le&&(me.modelInitializer=Le),[2,me]}})})},t.prototype.loadWeights=function(e){return M(this,void 0,void 0,function(){var n,a,c,d,y,v,_,C,F,B,U,J,me,Le,Me,He,lt,Nt,Ct,Bt,ur;return V(this,function(nr){switch(nr.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(Mu.URL_SCHEME_REGEX)!=null}var Lu=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?pu(t,e):null};ui.registerSaveRouter(Lu),ui.registerLoadRouter(Lu);function pu(t,e){return new Mu(t,e)}function wl(t,e){return pu(t,e)}var du=function(){function t(e){this.modelArtifacts=e}return t.prototype.load=function(){return M(this,void 0,void 0,function(){return V(this,function(e){return[2,this.modelArtifacts]})})},t}(),fu=function(){function t(e){this.saveHandler=e}return t.prototype.save=function(e){return M(this,void 0,void 0,function(){return V(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 du(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 du({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 du({modelTopology:t,weightSpecs:e,weightData:n,trainingConfig:a})}function Cc(t){return new fu(t)}var Tc={__proto__:null,browserFiles:po,browserHTTPRequest:wl,concatenateArrayBuffers:as,decodeWeights:xa,encodeWeights:$a,fromMemory:Nc,getLoadHandlers:_s,getModelArtifactsInfoForJSON:dn,getSaveHandlers:lc,http:pu,isHTTPScheme:zu,loadWeights:Ic,registerLoadRouter:Su,registerSaveRouter:ku,weightsLoaderFactory:Ou,withSaveHandler:Cc,copyModel:gl,listModels:os,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=rr(e,n.size),W(n.size===It(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,Br,c)}var Ke=Re({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=Tt(d,y),d=c[0],y=c[1];var v=function(F,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],me=n?d.shape[d.rank-1]:d.shape[d.rank-2],Le=a?y.shape[y.rank-2]:y.shape[y.rank-1],Me=d.shape.slice(0,-2),He=y.shape.slice(0,-2),lt=It(Me),Nt=It(He),Ct=lt===Nt||lt===1||Nt===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=lt>Nt?Me:He,ur=Bt.concat([me,Le]),nr=n?Ke(d,[lt,U,me]):Ke(d,[lt,me,U]),yr=a?Ke(y,[Nt,Le,J]):Ke(y,[Nt,J,Le]),Gr=F.batchMatMul(nr,yr,n,a);return Ke(Gr,ur)},_={a:d,b:y},C={transposeA:n,transposeB:a};return Ie.runKernelFunc(v,_,null,ya,C)}var sn=Re({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,F){return F([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,Li,_)}var Is=Re({oneHot_:Ac});function Fc(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=Is(dr(a,"int32"),n),y=Is(dr(c,"int32"),n),v=$n(d),_=sn(v,y);return dr(_,"int32")}var Oc=Re({confusionMatrix_:Dc}),Mc={__proto__:null,confusionMatrix:Oc};function Gs(t,e,n){if(ut(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 Oa(t,e,a,n)}var ss;function zc(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 _=Ps(xo,Ie.backendName);if(_!=null){var C={pixels:t},F={numChannels:e};return Ie.runKernel(xo,C,F)}var B=c?[t.videoWidth,t.videoHeight]:[t.width,t.height],U=B[0],J=B[1],me;y?me=t.getContext("2d").getImageData(0,0,U,J).data:a||n?me=t.data:(d||c)&&(ss==null&&(ss=document.createElement("canvas").getContext("2d")),ss.canvas.width=U,ss.canvas.height=J,ss.drawImage(t,0,0,U,J),me=ss.getImageData(0,0,U,J).data);var Le;if(e===4)Le=new Int32Array(me);else{var Me=U*J;Le=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(_=lt.sent(),C=n.dtype==="float32"?255:1,F=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 "+me+"."))}else if(n.dtype==="int32"&&(me<0||me>255))throw new Error("Tensor values for a int32 Tensor must be in the "+("range [0 - 255] but encountered "+me+"."));v===1?(U[0]=me*C,U[1]=me*C,U[2]=me*C):U[J]=me*C}Le=B*4,F[Le+0]=Math.round(U[0]),F[Le+1]=Math.round(U[1]),F[Le+2]=Math.round(U[2]),F[Le+3]=Math.round(U[3])}return e!=null&&(e.width=y,e.height=d,Me=e.getContext("2d"),He=new ImageData(F,y,d),Me.putImageData(He,0,0)),n!==t&&n.dispose(),[2,F]}})})}var mu=Re({fromPixels_:zc}),Pc={__proto__:null,toPixels:Lc,fromPixels:mu};function Pu(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],me=n+1;F=jc(y,J,me,a,t),B=Wu(v,J,me,c,t),U=Uc(d,J,me,t)}else for(var Le=0;Le-1)d[v]=0;else{var _=Vc(e,n,v),C=a[_];t&1<<_&&(C=0),d[v]=C}return d}function Wu(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 F=0;F0?y=Number.MIN_SAFE_INTEGER:y=Number.MAX_SAFE_INTEGER);var _=a[c];return y<0&&(y+=_),y=ye(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=ye(0,y,_):y=ye(-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:yu,computeOutShape:Wc,stridesWithElidedDims:Uc,getNormalizedAxes:Gc,startIndicesWithElidedDims:jc,stopIndicesWithElidedDims:Wu,stridesForAxis:Uu,startForAxis:qc,stopForAxis:Kc,isSliceContinous:Sl,computeFlatOffset:Il,parseSliceParams:Vu},Yc=function(){function t(){}return t.prototype.getClassName=function(){return this.constructor.className},t.fromConfig=function(e,n){return new e(n)},t}(),cs=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."}),cs.register(t)}var Nl={__proto__:null,Serializable:Yc,SerializationMap:cs,registerClass:jo},Cl=.001,Hu=.1;function Tl(t,e,n){return n==null&&(n=vu()),Gu(t,e,function(a,c){return js(a,c,n)})}function vu(){return Ie.backend.floatPrecision()===32?Cl:Hu}function Gu(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(!mt(y,v))throw new Error("Arrays have different shapes. "+("Actual: ["+y+"]. Expected: ["+v+"]"))}var _=Tn(t)?t:Kt(t),C=Tn(e)?e:Kt(e);if(_.length!==C.length)throw new Error("Arrays have different lengths actual: "+_.length+" vs "+("expected: "+C.length+`. -`)+("Actual: "+_+`. -`)+("Expected: "+C+"."));for(var F=0;Fn)}function ju(t,e,n){for(var a=0;an)throw new Error("Value out of range:"+t[a]+" low: "+e+", high: "+n)}function Fl(t,e){expect(new Float32Array(t)).toEqual(new Float32Array(e))}var Dl={__proto__:null,TEST_EPSILON_FLOAT16:Hu,expectArraysClose:Tl,testEpsilon:vu,expectPromiseToFail:El,expectArraysEqual:Rl,expectNumbersClose:Al,expectValuesInRange:ju,expectArrayBuffersEqual:Fl},qu="2.7.0";function Ol(){Rr().set("PROD",!0)}function Ml(){Rr().set("DEBUG",!0)}function Ku(){Rr().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function Ea(t){Rr().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(t+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function zl(){Ie.disposeVariables()}function Ll(){return Ie}function Pl(){return Ie.memory()}function Zc(t){return Ie.profile(t)}function la(t,e){return Ie.tidy(t,e)}function Ua(t){var e=Ot(t);e.forEach(function(n){return n.dispose()})}function gu(t){return Ie.keep(t)}function Qc(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=Tt(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,ma)}var Cr=Re({add_:Xl});function Yl(t,e){var n,a=ie(t,"a","floorDiv"),c=ie(e,"b","floorDiv");n=Tt(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 Xu=Re({floorDiv_:Yl});function Zl(t,e){var n,a=ie(t,"a","div"),c=ie(e,"b","div");if(n=Tt(a,c),a=n[0],c=n[1],a.dtype==="int32"&&c.dtype==="int32")return Xu(a,c);var d=function(_,C){var F=_.realDivide(a,c);return C([a,c]),F},y={a,b:c},v={};return Ie.runKernelFunc(d,y,null,Vr,v)}var Wr=Re({div_:Zl});function Jc(t,e){var n,a=ie(t,"a","mul"),c=ie(e,"b","mul");n=Tt(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=Re({mul_:Jc});function Ql(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,jn)}var ci=Re({abs_:Ql});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,ni)}var $c=Re({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=Re({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(!mt(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=Re({addN_:eh});function Yu(t,e){for(var n=0;n=0&&e=1,function(){return"Pass at least one tensor to concat"});var n=In(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 _=jt(e,n[0].shape)[0],C=Ir(n.map(function(U){return U.shape}),_);if(It(C)===0)return An([],C);if(n=n.filter(function(U){return U.size>0}),n.length===1)return n[0];var F=n.map(function(U){return U.shape});hr(F,_);var B=y.concat(n,_);return v(n),B},c=n,d={axis:e};return Ie.runKernelFunc(a,c,null,Ue,d)}var kr=Re({concat_:zr});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,As)}var mn=Re({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=Vu(a,e,n),F=C[0],B=C[1];return Bc(a,F,B),_([a]),v.slice(a,F,B)},d={x:a},y={begin:e,size:n};return Ie.runKernelFunc(c,d,null,To,y)}var er=Re({slice_:Xr});function Dn(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,Os)}var Cn=Re({tanh_:Dn});function bn(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"),F=ie(c,"c","basicLSTMCell"),B=ie(d,"h","basicLSTMCell"),U=kr([C,B],1),J=sn(U,v),me=Cr(J,_),Le=me.shape[0],Me=me.shape[1]/4,He=[Le,Me],lt=er(me,[0,0],He),Nt=er(me,[0,Me],He),Ct=er(me,[0,Me*2],He),Bt=er(me,[0,Me*3],He),ur=Cr(bt(mn(lt),Cn(Nt)),bt(F,mn(Cr(y,Ct)))),nr=bt(Cn(ur),mn(Bt));return[ur,nr]}var un=Re({basicLSTMCell_:bn});function On(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,Oi,v)}var Hr=Re({batchToSpaceND_:On});function ha(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 Ni(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 F;a!=null&&(F=ie(a,"offset","batchNorm")),W(v.rank===_.rank,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."}),W(F==null||v.rank===F.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=ha(y),U=function(Me,He){return He([B,v,_,C]),Me.batchNorm(B,Wi(v),Wi(_),Wi(F),Wi(C),d)},J={x:B,scale:C,offset:F,mean:v,variance:_},me={varianceEpsilon:d},Le=Ie.runKernelFunc(U,J,null,K,me);return Ke(Le,y.shape)}function Wi(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 Kn=Re({batchNorm_:Ni});function eo(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 F;return a!=null&&(F=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+".")}),F!=null&&W(F.rank===2||F.rank===1,function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 "+("but got rank "+F.rank+".")}),Kn(y,v,_,F,C,d)}var Ui=Re({batchNorm2d_:eo});function qs(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 F;return a!=null&&(F=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+".")}),F!=null&&W(F.rank===3||F.rank===1,function(){return"Error in batchNorm3D: offset must be rank 3 or rank 1 "+("but got rank "+F.rank+".")}),Kn(y,v,_,F,C,d)}var Zu=Re({batchNorm3d_:qs});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 F;return a!=null&&(F=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+".")}),F!=null&&W(F.rank===4||F.rank===1,function(){return"Error in batchNorm4D: offset must be rank 4 or rank 1 "+("but got rank "+F.rank+".")}),Kn(y,v,_,F,C,d)}var kh=Re({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)},F={x:n},B={shape:e,inputShape:d};return Ie.runKernelFunc(C,F,null,pe,B)}var Qu=Re({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=Re({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,ne,d)}var oh=Re({clipByValue_:ih});function sh(t){return kr(t,0)}var Sh=Re({concat1d_:sh});function uh(t,e){return kr(t,e)}var ep=Re({concat2d_:uh});function ch(t,e){return kr(t,e)}var Ih=Re({concat3d_:ch});function tp(t,e){return kr(t,e)}var Vn=Re({concat4d_:tp});function Ns(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,F=!1;v.rank===3&&(F=!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(yt(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 lt=Ft(c),Nt=T(C.shape,_.shape,n,d,a,y,!1,lt),Ct=Me.conv2d(C,_,Nt);return He([C,_]),Ct},J={x:C,filter:_},me={strides:n,pad:a,dataFormat:c,dilations:d,dimRoundingMode:y},Le=Ie.runKernelFunc(U,J,null,kt,me);return F?Ke(Le,[Le.shape[1],Le.shape[2],Le.shape[3]]):Le}var gi=Re({conv2d_:Ns});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,F=!1;v.rank===2&&(F=!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(yt(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],me=[1,d],Le="NHWC",Me=gi(U,B,J,a,Le,me,y);return F?Ke(Me,[Me.shape[2],Me.shape[3]]):Ke(Me,[Me.shape[0],Me.shape[2],Me.shape[3]])}var Cs=Re({conv1d_:qo});function Nh(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 F=d==="NHWC"?v[3]:v[1],B=d==="NHWC"?_.shape[3]:_.shape[1];W(F===n.shape[2],function(){return"Error in conv2dDerInput: depth of input ("+F+") 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(yt(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 lt=1,Nt=Ft(d),Ct=T(v,n.shape,a,lt,c,y,!1,Nt),Bt=Me.conv2dDerInput(_,n,Ct);return He([_,n]),Bt},J={dy:_,filter:n},me={strides:a,pad:c,dataFormat:d,dimRoundingMode:y,inputShape:v},Le=Ie.runKernelFunc(U,J,null,ze,me);return C?Ke(Le,[Le.shape[1],Le.shape[2],Le.shape[3]]):Le}var Ci=Re({conv2DBackpropInput_:Nh});function rp(t,e,n,a,c,d){var y=ie(t,"x","conv2dTranspose"),v=ie(e,"filter","conv2dTranspose");return Ci(n,y,v,a,c,"NHWC",d)}var Ks=Re({conv2dTranspose_:rp});function np(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 F=function(me,Le){var Me=O(_.shape,v.shape,n,d,a),He=me.conv3d(_,v,Me);return Le([_,v]),He},B={x:_,filter:v},U={strides:n,pad:a,dataFormat:c,dilations:d},J=Ie.runKernelFunc(F,B,null,Ye,U);return C?Ke(J,[J.shape[1],J.shape[2],J.shape[3],J.shape[4]]):J}var ap=Re({conv3d_:np});function ip(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 F=function(me){var Le=1,Me=O(d,n.shape,a,Le,c);return me.conv3dDerInput(y,n,Me)},B={dy:y,filter:n},U={pad:c,strides:a,inputShape:d},J=Ie.runKernelFunc(F,B,null,St,U);return v?Ke(J,[J.shape[1],J.shape[2],J.shape[3],J.shape[4]]):J}var Ch=Re({conv3DBackpropInput_:ip});function kf(t,e,n,a,c){var d=ie(t,"x","conv3dTranspose"),y=ie(e,"filter","conv3dTranspose");return Ch(n,d,y,a,c)}var Sf=Re({conv3dTranspose_:kf});function If(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 Th=Re({cos_:If});function Nf(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,fr)}var op=Re({cosh_:Nf});function Cf(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 F=$i([e],c.rank),B=c;F!=null&&(B=$n(c,F));var U=p(1,c.rank)[0],J=_.cumsum(B,U,n,a);if(C([c]),F!=null){var me=f(F);J=$n(J,me)}return J},y={x:c},v={axis:e,exclusive:n,reverse:a};return Ie.runKernelFunc(d,y,null,or,v)}var sp=Re({cumsum_:Cf});function Tf(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(F){return F.depthToSpace(a,e,n)},_={x:a},C={blockSize:e,dataFormat:n};return Ie.runKernelFunc(v,_,null,va,C)}var Yp=Re({depthToSpace_:Tf});function Ef(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,F=!1;v.rank===3&&(F=!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(yt(a),function(){return"Error in depthwiseConv2d: pad must be an integer when using, "+("dimRoundingMode "+y+" but got pad "+a+".")});var B=function(Le,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),lt=Le.depthwiseConv2D(C,_,He);return Me([C,_]),lt},U={x:C,filter:_},J={strides:n,pad:a,dataFormat:c,dilations:d,dimRoundingMode:y},me=Ie.runKernelFunc(B,U,null,ia,J);return F?Ke(me,[me.shape[1],me.shape[2],me.shape[3]]):me}var lh=Re({depthwiseConv2d_:Ef});function Rf(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,rn)}var Af=Re({diag_:Rf});function Ff(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 F={x:_,filter:v},B={strides:n,pad:a,dilations:c},U=Ie.runKernel(hn,F,B);return C?Ke(U,[U.shape[1],U.shape[2],U.shape[3]]):U}var Zp=Re({dilation2d_:Ff});function Df(t,e){for(var n=t.length,a=[],c=0;c1&&y===1&&a.unshift(d)}return a}function ti(t,e){for(var n=[],a=0;a1)&&n.unshift(d)}return n}function pa(t,e){for(var n=[],a=Math.max(t.length,e.length),c=0;ce||a===t?n=!0:a=cn(t,a+1);return a}function Yf(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 F={};return e.forEach(function(B,U){C[U]!=null&&(F[B.name]=C[U])}),c!=null&&c.forEach(function(B){return F[B.name]=null}),{value:_,grads:F}}function Ts(t){return Ie.customGrad(t)}function Dh(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 y1(t){var e=ie(t,"x","neg"),n={x:e};return Ie.runKernelFunc(function(a){return a.neg(e)},n,null,Io)}var ri=Re({neg_:y1});function v1(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,Zo)}var pp=Re({softplus_:v1});function g1(t){var e=ie(t,"x","logSigmoid"),n=Ts(function(a){var c=ri(pp(ri(a))),d=function(y){var v=bt(y,mn(ri(a)));return v};return{value:c,gradFunc:d}});return n(e)}var cd=Re({logSigmoid_:g1});function x1(t,e,n){e===void 0&&(e=null),n===void 0&&(n=!1);var a=ie(t,"x","max"),c=function(v,_){var C=jt(e,a.shape),F=C,B=$i(F,a.rank),U=a;B!=null&&(U=$n(a,B),F=p(F.length,U.rank));var J=v.max(U,F);B!=null&&U.dispose();var me=J;if(n){var Le=li(me.shape,jt(e,a.shape));me=Ke(me,Le),J.dispose()}return _([a,me]),me},d={x:a},y={reductionIndices:e,keepDims:n};return Ie.runKernelFunc(c,d,null,$r,y)}var tc=Re({max_:x1});function _1(t,e){var n,a=ie(t,"a","sub"),c=ie(e,"b","sub");n=Tt(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,ds)}var Lr=Re({sub_:_1});function w1(t,e,n){e===void 0&&(e=null),n===void 0&&(n=!1);var a=ie(t,"x","sum");a.dtype==="bool"&&(a=dr(a,"int32"));var c=function(v,_){_([a]);var C=jt(e,a.shape),F=$i(C,a.rank),B=C,U=a;F!=null&&(U=$n(a,F),B=p(B.length,a.rank));var J=v.sum(U,B);if(n){var me=li(J.shape,C);J=Ke(J,me)}return J},d={x:a},y={axis:e,keepDims:n};return Ie.runKernelFunc(c,d,null,Qo,y)}var Yr=Re({sum_:w1});function b1(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=tc(t,e,!0),F=Lr(t,C),B=Lr(dr(F,"float32"),ec(Yr(hs(F),e,_)));return v([B]),B},c={logits:n},d={axis:e};return Ie.runKernelFunc(a,c,null,Na,d)}var ld=Re({logSoftmax_:b1});function k1(t,e,n){e===void 0&&(e=null),n===void 0&&(n=!1);var a=ie(t,"x","logSumExp"),c=jt(e,a.shape),d=tc(a,c,!0),y=Lr(a,d),v=hs(y),_=Yr(v,c),C=ec(_),F=Cr(Ke(d,C.shape),C);if(n){var B=li(F.shape,c);return Ke(F,B)}return F}var dp=Re({logSumExp_:k1});function S1(t,e){var n=ie(t,"a","logicalAnd","bool"),a=ie(e,"b","logicalAnd","bool");pa(n.shape,a.shape);var c={a:n,b:a};return Ie.runKernelFunc(function(d){return d.logicalAnd(n,a)},c,null,pn)}var rc=Re({logicalAnd_:S1});function I1(t){var e=ie(t,"x","logicalNot","bool"),n={x:e};return Ie.runKernelFunc(function(a){return a.logicalNot(e)},n,null,zn)}var Oh=Re({logicalNot_:I1});function N1(t,e){var n=ie(t,"a","logicalOr","bool"),a=ie(e,"b","logicalOr","bool");pa(n.shape,a.shape);var c={a:n,b:a};return Ie.runKernelFunc(function(d){return d.logicalOr(n,a)},c,null,Dr)}var fp=Re({logicalOr_:N1});function C1(t,e){var n=ie(t,"a","logicalXor","bool"),a=ie(e,"b","logicalXor","bool");return pa(n.shape,a.shape),rc(fp(t,e),Oh(rc(t,e)))}var hd=Re({logicalXor_:C1});function T1(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(yt(a),function(){return"Error in maxPool: pad must be an integer when using, "+("dimRoundingMode "+c+" but got pad "+a+".")});var C=function(J,me){var Le=h(v.shape,e,n,1,a,c),Me;return Le.filterWidth===1&&Le.filterHeight===1&&mt(Le.inShape,Le.outShape)?Me=v.clone():Me=J.maxPool(v,Le),me([v,Me]),Me},F={x:v},B={filterSize:e,strides:n,pad:a,dimRoundingMode:c},U=Ie.runKernelFunc(C,F,null,mi,B);return _?Ke(U,[U.shape[1],U.shape[2],U.shape[3]]):U}var mp=Re({maxPool_:T1});function E1(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]:Ea("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(yt(a),function(){return"Error in maxPool3d: pad must be an integer when using, "+("dimRoundingMode "+c+" but got pad "+a+".")});var F=function(me,Le){y==null&&(y=[1,1,1]);var Me=b(_.shape,e,n,y,a,c,d),He=me.maxPool3d(_,Me);return Le([_,He]),He},B={x:_},U={filterSize:e,strides:n,pad:a,dimRoundingMode:c,dataFormat:d,dilations:y},J=Ie.runKernelFunc(F,B,null,Xa,U);return C?Ke(J,[J.shape[1],J.shape[2],J.shape[3],J.shape[4]]):J}var R1=Re({maxPool3d_:E1});function A1(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 F1=Re({maxPoolWithArgmax_:A1});function Xs(t,e){if(e===void 0&&(e="float32"),e==="complex64"){var n=Xs(t,"float32"),a=Xs(t,"float32");return Ln(n,a)}var c=fa(It(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=Xs(t,"float32");return Ln(n,a)}var c=_i(It(t),e);return Ie.makeTensor(c,t,e)}function D1(t,e,n){e===void 0&&(e=null),n===void 0&&(n=!1);var a=ie(t,"x","mean"),c=jt(e,a.shape),d=rl(a.shape,c),y=d[1],v=It(y),_={x:a},C={axis:e,keepDims:n},F=function(){var U=Ur(v),J=U.dtype===a.dtype?a:dr(a,U.dtype),me=Wr(J,U);return Yr(me,e,n)},B=Ts(function(U){var J=Ie.runKernelFunc(F,_,null,Rn,C),me=function(Le){var Me=U.shape.slice();c.forEach(function(Nt){Me[Nt]=1});var He=Ke(Le,Me),lt=Wr(bt(He,sl(U.shape,"float32")),v);return lt};return{value:J,gradFunc:me}});return B(a)}var ph=Re({mean_:D1});function O1(t,e,n){e===void 0&&(e=null),n===void 0&&(n=!1);var a=ie(t,"x","min"),c=function(v,_){var C=jt(e,a.shape),F=C,B=$i(F,a.rank),U=a;B!=null&&(U=$n(a,B),F=p(F.length,a.rank));var J=v.min(U,F);B!=null&&U.dispose();var me=J;if(n){var Le=li(me.shape,C);me=Ke(J,Le),J.dispose()}return _([a,me]),me},d={x:a},y={axis:e,keepDims:n};return Ie.runKernelFunc(c,d,null,Ca,y)}var Mh=Re({min_:O1});function M1(t,e){var n,a=ie(t,"a","minimum"),c=ie(e,"b","minimum");n=Tt(a,c),a=n[0],c=n[1],a.dtype==="bool"&&(a=dr(a,"int32"),c=dr(c,"int32")),pa(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,Ki)}var zh=Re({minimum_:M1});function z1(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 G1=Re({multinomial_:H1});function j1(t,e){var n,a=ie(t,"a","notEqual"),c=ie(e,"b","notEqual");n=Tt(a,c),a=n[0],c=n[1],pa(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 Lh=Re({notEqual_:j1});function q1(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=Re({real_:q1});function K1(t){var e=ie(t,"x","onesLike"),n=function(c,d){if(e.dtype==="complex64"){var y=vp(dh(e)),v=gn(Ah(e));return Ln(y,v)}return c.onesLike(e)},a={x:e};return Ie.runKernelFunc(n,a,null,si)}var vp=Re({onesLike_:K1});function X1(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 sn(c,d)}var Y1=Re({outerProduct_:X1});function Z1(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,ao,d)}var nc=Re({pad_:Z1});function Q1(t,e,n){return n===void 0&&(n=0),W(e.length===2,function(){return"Invalid number of paddings. Must be length of 2."}),nc(t,[e],n)}var J1=Re({pad1d_:Q1});function $1(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."}),nc(t,e,n)}var em=Re({pad2d_:$1});function tm(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."}),nc(t,e,n)}var rm=Re({pad3d_:tm});function nm(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."}),nc(t,e,n)}var am=Re({pad4d_:nm});function im(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 Ph=Re({spaceToBatchND_:im});function om(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),F=[C.dilationHeight,C.dilationWidth],B;a==="same"?B=um([C.filterHeight,C.filterWidth],F):B=[[0,0],[0,0]];var U=F[0]===1&&F[1]===1,J=sm([C.inHeight,C.inWidth],F,B),me=J[0],Le=J[1],Me=U?a:"valid",He=U?v:Ph(v,F,me),lt=n==="avg"?function(){return Yt(He,e,d,Me)}:function(){return mp(He,e,d,Me)},Nt=lt(),Ct=U?Nt:Hr(Nt,F,Le);return _?Ke(Ct,[Ct.shape[1],Ct.shape[2],Ct.shape[3]]):Ct}function sm(t,e,n){var a=n.map(function(F){return F[0]}),c=n.map(function(F){return F[1]}),d=t.concat(a,c),y=e.map(function(F,B){return(F-d[B]%F)%F}),v=c.map(function(F,B){return F+y[B]}),_=e.map(function(F,B){return[a[B],v[B]]}),C=e.map(function(F,B){return[0,y[B]]});return[_,C]}function um(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 dd=Re({pool_:om});function cm(t,e){var n,a=ie(t,"base","pow"),c=ie(e,"exp","pow");n=Tt(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,Za)}var Ys=Re({pow_:cm});function lm(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,io)}var gp=Re({prelu_:lm});function hm(t,e,n){e===void 0&&(e=null),n===void 0&&(n=!1);var a=ie(t,"x","prod");a.dtype==="bool"&&(a=dr(a,"int32"));var c=function(v){var _=jt(e,a.shape),C=$i(_,a.rank),F=_,B=a;C!=null&&(B=$n(a,C),F=p(F.length,a.rank));var U=v.prod(B,F);if(n){var J=li(U.shape,_);U=Ke(U,J)}return U},d={x:a},y={axis:e,keepDims:n};return Ie.runKernelFunc(c,d,null,Yo,y)}var fd=Re({prod_:hm});function pm(t,e,n){var a=It(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)}),mm=ac(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 F=0;F>>0)/4294967296};return B.double=function(){do var U=C.next()>>>11,J=(C.next()>>>0)/4294967296,me=(U+J)/(1<<21);while(me===0);return me},B.int32=C.next,B.quick=B,F&&(typeof F=="object"&&d(F,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)}),ym=ac(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 F=0;F>>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),F=_&&_.state,B=function(){return(C.next()>>>0)/4294967296};return B.double=function(){do var U=C.next()>>>11,J=(C.next()>>>0)/4294967296,me=(U+J)/(1<<21);while(me===0);return me},B.int32=C.next,B.quick=B,F&&(typeof F=="object"&&d(F,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)}),vm=ac(function(t){(function(e,n,a){function c(v){var _=this;_.next=function(){var F=_.x,B=_.i,U,J;return U=F[B],U^=U>>>7,J=U^U<<24,U=F[B+1&7],J^=U^U>>>10,U=F[B+3&7],J^=U^U>>>3,U=F[B+4&7],J^=U^U<<7,U=F[B+7&7],U=U^U<<13,J^=U^U<<9,F[B]=J,_.i=B+1&7,J};function C(F,B){var U,J,me=[];if(B===(B|0))J=me[0]=B;else for(B=""+B,U=0;U0;--U)F.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),F=_&&_.state,B=function(){return(C.next()>>>0)/4294967296};return B.double=function(){do var U=C.next()>>>11,J=(C.next()>>>0)/4294967296,me=(U+J)/(1<<21);while(me===0);return me},B.int32=C.next,B.quick=B,F&&(F.x&&d(F,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)}),gm=ac(function(t){(function(e,n,a){function c(v){var _=this;_.next=function(){var F=_.w,B=_.X,U=_.i,J,me;return _.w=F=F+1640531527|0,me=B[U+34&127],J=B[U=U+1&127],me^=me<<13,J^=J<<17,me^=me>>>15,J^=J>>>12,me=B[U]=me^J,_.i=U,me+(F^F>>>16)|0};function C(F,B){var U,J,me,Le,Me,He=[],lt=128;for(B===(B|0)?(J=B,B=null):(B=B+"\0",J=0,lt=Math.max(lt,B.length)),me=0,Le=-32;Le>>15,J^=J<<4,J^=J>>>13,Le>=0&&(Me=Me+1640531527|0,U=He[Le&127]^=J+Me,me=U==0?me+1:0);for(me>=128&&(He[(B&&B.length||0)&127]=-1),me=127,Le=4*128;Le>0;--Le)J=He[me+34&127],U=He[me=me+1&127],J^=J<<13,U^=U<<17,J^=J>>>15,U^=U>>>12,He[me]=J^U;F.w=Me,F.X=He,F.i=me}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),F=_&&_.state,B=function(){return(C.next()>>>0)/4294967296};return B.double=function(){do var U=C.next()>>>11,J=(C.next()>>>0)/4294967296,me=(U+J)/(1<<21);while(me===0);return me},B.int32=C.next,B.quick=B,F&&(F.X&&d(F,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)}),xm=ac(function(t){(function(e,n,a){function c(v){var _=this,C="";_.next=function(){var B=_.b,U=_.c,J=_.d,me=_.a;return B=B<<25^B>>>7^U,U=U-J|0,J=J<<24^J>>>8^me,me=me-B|0,_.b=B=B<<20^B>>>12^U,_.c=U=U-J|0,_.d=J<<16^U>>>16^me,_.a=me-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 F=0;F>>0)/4294967296};return B.double=function(){do var U=C.next()>>>11,J=(C.next()>>>0)/4294967296,me=(U+J)/(1<<21);while(me===0);return me},B.int32=C.next,B.quick=B,F&&(typeof F=="object"&&d(F,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)}),ic=ac(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),F=C*2,B=c-1,U;function J(Ct,Bt,ur){var nr=[];Bt=Bt==!0?{entropy:!0}:Bt||{};var yr=He(Me(Bt.entropy?[Ct,Nt(e)]:Ct==null?lt():Ct,3),nr),Gr=new me(nr),en=function(){for(var Zr=Gr.g(d),Qr=_,Kr=0;Zr=F;)Zr/=2,Qr/=2,Kr>>>=1;return(Zr+Kr)/Qr};return en.int32=function(){return Gr.g(4)|0},en.quick=function(){return Gr.g(4)/4294967296},en.double=en,He(Nt(Gr.S),e),(Bt.pass||ur||function(Zr,Qr,Kr,Hn){return Hn&&(Hn.S&&Le(Hn,Gr),Zr.state=function(){return Le(Gr,{})}),Kr?(n[v]=Zr,Qr):Zr})(en,yr,"global"in Bt?Bt.global:this==n,Bt.state)}n["seed"+v]=J;function me(Ct){var Bt,ur=Ct.length,nr=this,yr=0,Gr=nr.i=nr.j=0,en=nr.S=[];for(ur||(Ct=[ur++]);yr=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}(),wm=function(){function t(e,n,a,c){this.alpha=e,this.beta=1/n,this.dtype=a;var d=c||Math.random();this.randu=xp(d.toString()),this.randn=new _p(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 Xs([0],a);var C=Math.abs(Math.ceil((e-t)/n)),F=fa(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 sy(t,e,n){n===void 0&&(n=0);var a=ie(t,"x","split"),c=function(v,_){var C=jt(n,a.shape)[0],F=bd(a,e,C);return v.split(a,F,C)},d={x:a},y={numOrSizeSplits:e,axis:n};return Ie.runKernelFunc(c,d,null,Jo,y)}var ll=Re({split_:sy});function uy(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,Xs(v)],t.shape.length-1),n=e}else c=t;var _=gn(c),C=Ke(Ln(c,_),[a,n]),F=Bh(C),B=Math.floor(n/2)+1,U=dh(F),J=Ah(F),me=ll(U,[B,n-B],U.shape.length-1),Le=ll(J,[B,n-B],J.shape.length-1),Me=c.shape.slice();return Me[c.shape.length-1]=B,Ke(Ln(me[0],Le[0]),Me)}var Wh=Re({rfft_:uy});function cy(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 to=Re({sqrt_:cy});function ly(t,e){var n,a=ie(t,"a","squaredDifference"),c=ie(e,"b","squaredDifference");n=Tt(a,c),a=n[0],c=n[1],pa(a.shape,c.shape);var d=function(_,C){var F=_.squaredDifference(a,c);return C([a,c]),F},y={a,b:c},v={};return Ie.runKernelFunc(d,y,null,Fs,v)}var Uh=Re({squaredDifference_:ly});function hy(t,e){var n=ie(t,"x","squeeze");return Ke(n,jr(n.shape,e).newShape)}var Vh=Re({squeeze_:hy});function py(t,e){e===void 0&&(e=0);var n=In(t,"tensors","stack");if(W(n.length>=1,function(){return"Pass at least one tensor to tf.stack"}),n.length===1)return ps(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){st(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 ps(v,e)});return kr(y,e)}var oc=Re({stack_:py});function dy(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,$o,c)}var hl=Re({step_:dy});function fy(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"),F=function(J){a==null&&(a=new Array(e.length));var me=yu(y);if(me.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 Le=C.rank-e.length,Me=yu(v),He=C.shape.slice();Me.forEach(function(Zr){e[Zr]=0,n[Zr]=1,He.splice(Zr,0,1)}),C=Ke(C,He);var lt=Gc(C.shape,me,Le,e,n,a,c,d,y),Nt=lt.begin,Ct=lt.end,Bt=lt.strides;e=Nt,n=Ct,a=Bt;var ur=yu(_);ur.forEach(function(Zr){n[Zr]=e[Zr]+1,a[Zr]=1});var nr=Wc(e,n,a),yr=nr.filter(function(Zr,Qr){return ur.indexOf(Qr)===-1}),Gr=a.every(function(Zr){return Zr===1});if(Gr)return Ke(er(C,e,nr),yr);var en=J.stridedSlice(C,e,n,a);return Ke(en,yr)},B={x:C},U={begin:e,end:n,strides:a,beginMask:c,endMask:d,ellipsisMask:y,newAxisMask:v,shrinkAxisMask:_};return Ie.runKernelFunc(F,B,null,Ds,U)}var kd=Re({stridedSlice_:fy});function my(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,fs)}var Sd=Re({tan_:my});function yh(t,e,n){if(ut(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 Oa(t,e,a,n)}function yy(t,e,n){if(ut(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 Oa(t,e,a,n)}function vy(t,e,n){if(ut(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 Oa(t,e,a,n)}function gy(t,e,n){if(ut(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,Oa(t,e,a,n)}function xy(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(F){return F.topk(a,e,n)},d,null,ru,y),_=v[0],C=v[1];return{values:_,indices:C}}var Id=Re({topk_:xy});function _y(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 _p(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(nu,a,c),y=d[0],v=d[1];return{values:y,indices:v}}var Nd=Re({unique_:by});function ky(t,e,n){var a=ie(t,"x","unsortedSegmentSum"),c=ie(e,"segmentIds","unsortedSegmentSum","int32");W(yt(n),function(){return"numSegments must be of dtype int"});var d={x:a,segmentIds:c},y={numSegments:n},v=function(_,C){var F=_.unsortedSegmentSum(a,c,n);return C([c]),F};return Ie.runKernelFunc(v,d,null,Fo,y)}var Cp=Re({unsortedSegmentSum_:ky});function Sy(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"}),st(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 Zy(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);Yy(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,tu,_)}var Qy=Re({sparseToDense_:Zy});function Jy(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,be)}var $y=Re({gatherND_:Jy});function e0(t,e){if(e==null)return t.shape.slice();if(mt(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=e0(c,n),y=1-e,v=Wr(Eh(Cr(md(d,0,1,"float32",a),y)),y);return bt(c,v)}var r0=Re({dropout_:t0});function jd(t){return Math.floor(Math.pow(2,Math.ceil(Math.log(t)/Math.log(2))))}function Tp(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)}),st(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],F=_[1],B=Pr("bool",C),U=0;U0&&(n=Yr(n,a)),Ke(n,t.shape)}function Kh(t,e,n){if(e==="linear")return t;if(e==="relu")return fh(t);if(e==="elu")return up(t);if(e==="relu6")return bp(t);if(e==="prelu")return gp(t,n);throw new Error("Unknown fused activation "+e+".")}var Xh=function(t,e){var n=t>0;return!n||e==="linear"};function o0(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,F=t.bias,B=t.activation,U=B===void 0?"linear":B,J=t.preluActivationWeights;if(U=U||"linear",Xh(Ie.state.gradientDepth,U)===!1){var me=gi(e,n,a,c,y,_,C);return F!=null&&(me=Cr(me,F)),Kh(me,U,J)}var Le=ie(e,"x","conv2d"),Me=ie(n,"filter","conv2d"),He=Le,lt=!1;Le.rank===3&&(lt=!0,He=Ke(Le,[1,Le.shape[0],Le.shape[1],Le.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(yt(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 Nt=T(He.shape,Me.shape,a,_,c,C),Ct;F!=null&&(Ct=ie(F,"bias","fused conv2d"),Ct=Tt(Ct,Le)[0],pa(Nt.outShape,Ct.shape));var Bt;J!=null&&(Bt=ie(J,"prelu weights","fused conv2d"));var ur=function(Qr,Kr){var Hn=Kr,yn=Hn[0],Mn=Hn[1],Js=Hn[2],xi=Hn[3],Va=jh(Qr,Js,U);W(ct(_),function(){return"Error in gradient of fused conv2D: dilation rates greater than 1 "+("are not yet supported in gradients. Got dilations '"+_+"'")});var ko=Ci(Mn.shape,Va,yn,a,c),So=Ep(Mn,Va,yn.shape,a,c),wu=[ko,So];if(xi!=null){var Pp=qh(xi,Va);wu.push(Pp)}return wu},nr=function(Qr){var Kr=Qr.fusedConv2d({input:He,filter:Me,convInfo:Nt,bias:Ct,activation:U,preluActivationWeights:Bt});return Kr},yr={x:He,filter:Me,bias:Ct,preluActivationWeights:Bt},Gr={strides:a,pad:c,dataFormat:y,dilations:_,dimRoundingMode:C,activation:U};if(F==null){var en=Ts(function(Qr,Kr,Hn){var yn=Ie.runKernelFunc(nr,yr,null,Ls,Gr);return Hn([Kr,Qr,yn]),lt&&(yn=Ke(yn,[yn.shape[1],yn.shape[2],yn.shape[3]])),{value:yn,gradFunc:ur}});return en(He,Me)}else{var Zr=Ts(function(Qr,Kr,Hn,yn){var Mn=Ie.runKernelFunc(nr,yr,null,Ls,Gr);return yn([Kr,Qr,Mn,Hn]),lt&&(Mn=Ke(Mn,[Mn.shape[1],Mn.shape[2],Mn.shape[3]])),{value:Mn,gradFunc:ur}});return Zr(He,Me,Ct)}}var s0=Re({fusedConv2d_:o0});function u0(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)},F={x:v,dy:_},B={strides:a,pad:c,dimRoundingMode:y,dilations:d,filterShape:n};return Ie.runKernelFunc(C,F,null,qa,B)}var qd=Re({depthwiseConv2dNativeBackpropFilter_:u0});function c0(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 me=T(t,n.shape,a,d,c,y,!0);return J.depthwiseConv2DDerInput(v,n,me)},F={dy:v,filter:n},B={strides:a,pad:c,dimRoundingMode:y,dilations:d,inputShape:t},U=Ie.runKernelFunc(C,F,null,bi,B);return _?Ke(U,[U.shape[1],U.shape[2],U.shape[3]]):U}var Kd=Re({depthwiseConv2dNativeBackpropInput_:c0});function l0(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,F=t.bias,B=t.activation,U=B===void 0?"linear":B,J=t.preluActivationWeights;if(Xh(Ie.state.gradientDepth,U)===!1){var me=lh(e,n,a,c,y,_,C);return F!=null&&(me=Cr(me,F)),Kh(me,U,J)}var Le=ie(e,"x","depthwiseConv2d"),Me=ie(n,"filter","depthwiseConv2d"),He=Le,lt=!1;Le.rank===3&&(lt=!0,He=Ke(Le,[1,Le.shape[0],Le.shape[1],Le.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(yt(c),function(){return"Error in fused depthwiseConv2d: pad must be an integer when "+("using dimRoundingMode "+C+" but got pad "+c+".")});var Nt=T(He.shape,Me.shape,a,_,c,C,!0),Ct;F!=null&&(Ct=ie(F,"bias","fused conv2d"),Ct=Tt(Ct,Le)[0],pa(Nt.outShape,Ct.shape));var Bt;J!=null&&(Bt=ie(J,"prelu weights","fused depthwiseConv2d"));var ur=function(Qr,Kr){W(ct(_),function(){return"Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations "+("'"+_+"'")});var Hn=Kr[0],yn=Kr[1],Mn=Kr[2],Js=Kr[3],xi=jh(Qr,Mn,U),Va=Kd(yn.shape,xi,Hn,a,c,_,C),ko=qd(yn,xi,Hn.shape,a,c,_,C);if(Js!=null){var So=qh(Ct,xi);return[Va,ko,So]}return[Va,ko]},nr=function(Qr){var Kr=Qr.fusedDepthwiseConv2D({input:He,filter:Me,convInfo:Nt,bias:Ct,activation:U,preluActivationWeights:Bt});return Kr},yr={x:He,filter:Me,bias:Ct,preluActivationWeights:Bt},Gr={strides:a,pad:c,dataFormat:y,dilations:_,dimRoundingMode:C,activation:U};if(F==null){var en=Ts(function(Qr,Kr,Hn){var yn=Ie.runKernelFunc(nr,yr,null,es,Gr);return Hn([Kr,Qr,yn]),lt&&(yn=Ke(yn,[yn.shape[1],yn.shape[2],yn.shape[3]])),{value:yn,gradFunc:ur}});return en(He,Me)}else{var Zr=Ts(function(Qr,Kr,Hn,yn){var Mn=Ie.runKernelFunc(nr,yr,null,es,Gr);return yn([Kr,Qr,Mn,Hn]),lt&&(Mn=Ke(Mn,[Mn.shape[1],Mn.shape[2],Mn.shape[3]])),{value:Mn,gradFunc:ur}});return Zr(He,Me,Ct)}}var h0=Re({fusedDepthwiseConv2d_:l0});function p0(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,F=C===void 0?"linear":C,B=t.preluActivationWeights;if(Xh(Ie.state.gradientDepth,F)===!1){var U=sn(n,a,d,v);return _!=null&&(U=Cr(U,_)),Kh(U,F,B)}var J=ie(n,"a","fused matMul"),me=ie(a,"b","fused matMul");e=Tt(J,me),J=e[0],me=e[1];var Le=d?J.shape[J.rank-2]:J.shape[J.rank-1],Me=v?me.shape[me.rank-1]:me.shape[me.rank-2],He=d?J.shape[J.rank-1]:J.shape[J.rank-2],lt=v?me.shape[me.rank-2]:me.shape[me.rank-1],Nt=J.shape.slice(0,-2),Ct=me.shape.slice(0,-2),Bt=It(Nt),ur=It(Ct);W(J.rank>=2&&me.rank>=2&&J.rank===me.rank,function(){return"Error in fused matMul: inputs must have the same rank of at least "+("2, got ranks "+J.rank+" and "+me.rank+".")}),W(mt(Nt,Ct),function(){return"Error in fused matMul: outer dimensions ("+Nt+") and ("+(Ct+") of Tensors with shapes "+J.shape+" and ")+(me.shape+" must match.")}),W(Le===Me,function(){return"Error in fused matMul: inner shapes ("+Le+") and ("+(Me+") of Tensors with shapes "+J.shape+" and ")+(me.shape+" and transposeA="+d)+(" and transposeB="+v+" must match.")});var nr=J.shape.slice(0,-2).concat([He,lt]),yr=d?Ke(J,[Bt,Le,He]):Ke(J,[Bt,He,Le]),Gr=v?Ke(me,[ur,lt,Me]):Ke(me,[ur,Me,lt]),en;_!=null&&(en=ie(_,"bias","fused matMul"),en=Tt(en,J)[0],pa(nr,en.shape));var Zr;B!=null&&(Zr=ie(B,"prelu weights","fused matMul"));var Qr=function(xi,Va){var ko=Va[0],So=Va[1],wu=Va[2],Pp=Va[3],$s=jh(Ke(xi,wu.shape),wu,F),dl,fl;if(!d&&!v?(dl=sn($s,So,!1,!0),fl=sn(ko,$s,!0,!1)):!d&&v?(dl=sn($s,So,!1,!1),fl=sn($s,ko,!0,!1)):d&&!v?(dl=sn(So,$s,!1,!0),fl=sn(ko,$s,!1,!1)):(dl=sn(So,$s,!0,!0),fl=sn($s,ko,!0,!0)),_!=null){var eg=qh(Pp,$s);return[dl,fl,eg]}else return[dl,fl]},Kr=function(xi){var Va=xi.fusedBatchMatMul({a:yr,b:Gr,transposeA:d,transposeB:v,bias:en,activation:F,preluActivationWeights:Zr});return Va},Hn={a:yr,b:Gr,bias:en,preluActivationWeights:Zr},yn={transposeA:d,transposeB:v,activation:F};if(_==null){var Mn=Ts(function(xi,Va,ko){var So=Ie.runKernelFunc(Kr,Hn,null,Do,yn);return ko([xi,Va,So]),{value:Ke(So,nr),gradFunc:Qr}});return Mn(yr,Gr)}else{var Js=Ts(function(xi,Va,ko,So){var wu=Ie.runKernelFunc(Kr,Hn,null,Do,yn);return So([xi,Va,wu,ko]),{value:Ke(wu,nr),gradFunc:Qr}});return Js(yr,Gr,en)}}var d0=Re({fusedMatMul_:p0}),f0={__proto__:null,conv2d:s0,depthwiseConv2d:h0,matMul:d0};function m0(t){return Tp(t,.54,.46)}var y0=Re({hammingWindow_:m0});function v0(t){return Tp(t,.5,.5)}var Xd=Re({hannWindow_:v0});function g0(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(er(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 F=function(me){return me.cropAndResize(y,v,_,a,c,d)},B={image:y,boxes:v,boxInd:_},U={method:c,extrapolationValue:d,cropSize:a},J=Ie.runKernelFunc(F,B,null,aa,U);return J}var b0=Re({cropAndResize_:w0});function k0(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 S0=Re({flipLeftRight_:k0});function I0(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(vs,d,y);return v}var N0=Re({rotateWithOffset_:I0});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 C0(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,Ya,_)}var T0=Re({nonMaxSuppression_:C0});function E0(t,e,n){var a=R0(t,e,n),c=a<0?-(a+1):a;t.splice(c,0,e)}function R0(t,e,n){return F0(t,e,n||A0)}function A0(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 Zd(t,e,n,a,c){return Rp(t,e,n,a,c,0).selectedIndices}function Qd(t,e,n,a,c,d){return Rp(t,e,n,a,c,0,!1,d,!0)}function Jd(t,e,n,a,c,d){return Rp(t,e,n,a,c,d,!0)}function Rp(t,e,n,a,c,d,y,v,_){y===void 0&&(y=!1),v===void 0&&(v=!1),_===void 0&&(_=!1);for(var C=[],F=0;Fc&&C.push({score:e[F],boxIndex:F,suppressBeginIndex:0});C.sort($d);for(var B=d>0?-.5/d:0,U=[],J=[];U.length0;){var me=C.pop(),Le=me.score,Me=me.boxIndex,He=me.suppressBeginIndex;if(Le=He;--Nt){var Ct=D0(t,Me,U[Nt]);if(Ct>=a){lt=!0;break}if(me.score=me.score*O0(a,B,Ct),me.score<=c)break}me.suppressBeginIndex=U.length,lt||(me.score===Le?(U.push(Me),J.push(me.score)):me.score>c&&E0(C,me,$d))}var Bt=U.length,ur=n-Bt;v&&ur>0&&(U.push.apply(U,new Array(ur).fill(0)),J.push.apply(J,new Array(ur).fill(0)));var nr={selectedIndices:cl(U,"int32")};return y&&(nr.selectedScores=cl(J,"float32")),_&&(nr.validOutputs=Ur(Bt,"int32")),nr}function D0(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]),F=Math.min(c[1],c[3]),B=Math.max(c[0],c[2]),U=Math.max(c[1],c[3]),J=(v-d)*(_-y),me=(B-C)*(U-F);if(J<=0||me<=0)return 0;var Le=Math.max(d,C),Me=Math.max(y,F),He=Math.min(v,B),lt=Math.min(_,U),Nt=Math.max(He-Le,0)*Math.max(lt-Me,0);return Nt/(J+me-Nt)}function O0(t,e,n){var a=Math.exp(e*n*n);return n<=t?a:0}function $d(t,e){return t.score-e.score||t.score===e.score&&e.boxIndex-t.boxIndex}function M0(t,e,n,a,c){return a===void 0&&(a=.5),c===void 0&&(c=Number.NEGATIVE_INFINITY),M(this,void 0,void 0,function(){var d,y,v,_,C,F,B;return V(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],F=_[1],B=Zd(C,F,n,a,c),d!==t&&d.dispose(),y!==e&&y.dispose(),[2,B]}})})}var z0=M0;function L0(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},F={maxOutputSize:n,iouThreshold:a,scoreThreshold:c,softNmsSigma:d},B=Ie.runKernel(Xi,C,F);return{selectedIndices:B[0],selectedScores:B[1]}}var P0=Re({nonMaxSuppressionWithScore_:L0});function B0(t,e,n,a,c,d){return a===void 0&&(a=.5),c===void 0&&(c=Number.NEGATIVE_INFINITY),d===void 0&&(d=0),M(this,void 0,void 0,function(){var y,v,_,C,F,B,U;return V(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(),F=C[0],B=C[1],U=Jd(F,B,n,a,c,d),y!==t&&y.dispose(),v!==e&&v.dispose(),[2,U]}})})}var W0=B0;function U0(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,F=_.iouThreshold,B=_.scoreThreshold,U={boxes:y,scores:v},J={maxOutputSize:C,iouThreshold:F,scoreThreshold:B,padToMaxOutputSize:d},me=Ie.runKernel(Ba,U,J);return{selectedIndices:me[0],validOutputs:me[1]}}var V0=Re({nonMaxSuppressionPadded_:U0});function H0(t,e,n,a,c,d){return a===void 0&&(a=.5),c===void 0&&(c=Number.NEGATIVE_INFINITY),d===void 0&&(d=!1),M(this,void 0,void 0,function(){var y,v,_,C,F,B,U,J,me,Le;return V(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,F=_.iouThreshold,B=_.scoreThreshold,[4,Promise.all([y.data(),v.data()])];case 1:return U=Me.sent(),J=U[0],me=U[1],Le=Qd(J,me,C,F,B,d),y!==t&&y.dispose(),v!==e&&v.dispose(),[2,Le]}})})}var G0=H0;function j0(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},F={alignCorners:n,size:e},B=Ie.runKernelFunc(_,C,null,Zn,F);return d?Ke(B,[B.shape[1],B.shape[2],B.shape[3]]):B}var ef=Re({resizeBilinear_:j0});function q0(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},F=function(U,J){return J([c]),U.resizeNearestNeighbor(c,y,v,n)},B=Ie.runKernelFunc(F,_,null,ca,C);return d?Ke(B,[B.shape[1],B.shape[2],B.shape[3]]):B}var tf=Re({resizeNearestNeighbor_:q0});function K0(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(wp(0,y,1,"int32"),[-1,1]),C=wp(0,v,1,"int32"),F=Lr(_,C),B=rc($u(F,Ur(+e,"int32")),Ju(F,Ur(-n,"int32"))),U=Xs([y,v],a.dtype);return Ke(oc(Hh(Ke(a,[-1,y,v])).map(function(J){return ls(B,J,U)})),c)}var X0=Re({bandPart_:K0});function Y0(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 rf(t,e);var n=t.shape.slice(0,t.shape.length-2).reduce(function(_,C){return _*C}),a=Hh(Ke(t,[n,t.shape[t.shape.length-2],t.shape[t.shape.length-1]]),0),c=[],d=[];a.forEach(function(_){var C=rf(_,e),F=C[0],B=C[1];c.push(F),d.push(B)});var y=Ke(oc(c,0),t.shape),v=Ke(oc(d,0),t.shape);return[y,v]}function rf(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=td(n),d=Ho(t),y=yh([[1]],[1,1]),v=Ho(y),_=n>=a?a:n,C=function(B){var U,J=d,me=v,Le=c;U=Ie.tidy(function(){var Me=er(d,[B,B],[n-B,1]),He=Gh(Me),lt=er(d,[B,B],[1,1]),Nt=ls(xu(lt,0),yh([[-1]]),yh([[1]])),Ct=Lr(lt,bt(Nt,He)),Bt=Wr(Me,Ct);Bt.shape[0]===1?v=Ho(y):v=kr([y,er(Bt,[1,0],[Bt.shape[0]-1,Bt.shape[1]])],0);var ur=ri(Wr(sn(Nt,Ct),He)),nr=er(d,[B,0],[n-B,a]),yr=bt(ur,v),Gr=$n(v);if(B===0)d=Lr(nr,sn(yr,sn(Gr,nr)));else{var en=Lr(nr,sn(yr,sn(Gr,nr)));d=kr([er(d,[0,0],[B,a]),en],0)}var Zr=$n(yr),Qr=er(c,[0,B],[n,c.shape[1]-B]);if(B===0)c=Lr(Qr,sn(sn(Qr,v),Zr));else{var Kr=Lr(Qr,sn(sn(Qr,v),Zr));c=kr([er(c,[0,0],[n,B]),Kr],1)}return[v,d,c]}),v=U[0],d=U[1],c=U[2],Ua([J,me,Le])},F=0;F<_;++F)C(F);return!e&&n>a&&(c=er(c,[0,0],[n,a]),d=er(d,[0,0],[a,a])),[c,d]})}var J0=Re({qr_:Q0});(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 $0(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=Wr(Yr(d),Yr(c));return y>1?Wr(v,Ur(y)):v}if(n===N.Reduction.SUM_BY_NONZERO_WEIGHTS){if(c==null)return Wr(Yr(d),Ur(a.size));var _=bt(c,sl(a.shape)),C=dr(Yr(Lh(_,Ur(0))),"float32");return Wr(Yr(d),C)}throw Error("Unknown reduction: "+n)}var Qs=Re({computeWeightedLoss_:$0});function e2(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")),st(c.shape,d.shape,"Error in absoluteDifference: ");var v=ci(Lr(c,d));return Qs(v,y,a)}var t2=Re({absoluteDifference_:e2});function r2(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")),st(d.shape,y.shape,"Error in cosineDistance: ");var _=Ur(1),C=Lr(_,Yr(bt(d,y),n,!0));return Qs(C,v,c)}var n2=Re({cosineDistance_:r2});function a2(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")),st(c.shape,d.shape,"Error in hingeLoss: ");var v=Ur(1);c=Lr(bt(Ur(2),c),v);var _=fh(Lr(v,bt(c,d)));return Qs(_,y,a)}var i2=Re({hingeLoss_:a2});function o2(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")),st(d.shape,y.shape,"Error in huberLoss: ");var _=Ur(a),C=ci(Lr(y,d)),F=zh(C,_),B=Lr(C,F),U=Cr(bt(Ur(.5),Xn(F)),bt(_,B));return Qs(U,v,c)}var s2=Re({huberLoss_:o2});function u2(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")),st(d.shape,y.shape,"Error in logLoss: ");var _=Ur(1),C=Ur(a),F=ri(bt(d,ec(Cr(y,C)))),B=bt(Lr(_,d),ec(Cr(Lr(_,y),C))),U=Lr(F,B);return Qs(U,v,c)}var c2=Re({logLoss_:u2});function l2(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")),st(c.shape,d.shape,"Error in meanSquaredError: ");var v=Uh(c,d);return Qs(v,y,a)}var h2=Re({meanSquaredError_:l2});function p2(t,e){var n=ie(t,"labels","sigmoidCrossEntropyWithLogits"),a=ie(e,"logits","sigmoidCrossEntropyWithLogits");st(n.shape,a.shape,"Error in sigmoidCrossEntropyWithLogits: ");var c=fh(a),d=bt(a,n),y=hp(hs(ri(ci(a))));return Cr(Lr(c,d),y)}function d2(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")),st(d.shape,y.shape,"Error in sigmoidCrossEntropy: "),a>0){var _=Ur(a),C=Ur(1),F=Ur(.5);d=Cr(bt(d,Lr(C,_)),bt(F,_))}var B=p2(d,y);return Qs(B,v,c)}var f2=Re({sigmoidCrossEntropy_:d2});function m2(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=Ts(function(c,d,y){var v=!0,_=dp(d,[n],v),C=Lr(dr(d,"float32"),_);y([c,C]);var F=ri(bt(C,c)),B=Yr(F,[n]),U=function(J,me){var Le=me[0],Me=me[1],He=li(J.shape,[n]);return[bt(Ke(J,He),Lr(dr(Le,"float32"),hs(Me))),bt(Ke(J,He),Lr(hs(Me),dr(Le,"float32")))]};return{value:B,gradFunc:U}});return a(t,e)}function y2(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")),st(d.shape,y.shape,"Error in softmaxCrossEntropy: "),a>0){var _=Ur(a),C=Ur(1),F=Ur(d.shape[1]);d=Cr(bt(d,Lr(C,_)),Wr(_,F))}var B=m2(d,y);return Qs(B,v,c)}var v2=Re({softmaxCrossEntropy_:y2}),g2={fft:Bh,ifft:mh,rfft:Wh,irfft:Np},x2={hammingWindow:y0,hannWindow:Xd,frame:Yd,stft:_0},_2={flipLeftRight:S0,resizeNearestNeighbor:tf,resizeBilinear:ef,rotateWithOffset:N0,cropAndResize:b0,nonMaxSuppression:T0,nonMaxSuppressionAsync:z0,nonMaxSuppressionWithScore:P0,nonMaxSuppressionWithScoreAsync:W0,nonMaxSuppressionPadded:V0,nonMaxSuppressionPaddedAsync:G0},w2={bandPart:X0,gramSchmidt:Z0,qr:J0},b2={absoluteDifference:t2,computeWeightedLoss:Qs,cosineDistance:n2,hingeLoss:i2,huberLoss:s2,logLoss:c2,meanSquaredError:h2,sigmoidCrossEntropy:f2,softmaxCrossEntropy:v2},_u=function(t){we(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 Ua(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 ud(n,a)},e.prototype.dispose=function(){this.iterations_!=null&&Ua(this.iterations_)},e.prototype.saveIterations=function(){return M(this,void 0,void 0,function(){return V(this,function(n){return this.iterations_==null&&(this.iterations_=0),[2,{name:"iter",tensor:Ur(this.iterations_,"int32")}]})})},e.prototype.getWeights=function(){return M(this,void 0,void 0,function(){return V(this,function(n){throw new Error("getWeights() is not implemented for this optimizer yet.")})})},e.prototype.setWeights=function(n){return M(this,void 0,void 0,function(){return V(this,function(a){throw new Error("setWeights() is not implemented for this optimizer class "+(""+this.getClassName()))})})},e.prototype.extractIterations=function(n){return M(this,void 0,void 0,function(){var a;return V(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(_u,Symbol.hasInstance,{value:function(t){return t.minimize!=null&&t.computeGradients!=null&&t.applyGradients!=null}});var Ap=function(t){we(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:la(function(){return gn(v).variable(_)})}),a.accumulatedUpdates[y]==null&&(a.accumulatedUpdates[y]={originalName:d+"/accum_var",variable:la(function(){return gn(v).variable(_)})});var C=Array.isArray(n)?n[y].tensor:n[d];if(C==null)return;var F=a.accumulatedGrads[y].variable,B=a.accumulatedUpdates[y].variable;la(function(){var U=Cr(bt(F,a.rho),bt(Xn(C),1-a.rho)),J=bt(Wr(to(Cr(B,a.epsilon)),to(Cr(F,a.epsilon))),C),me=Cr(bt(B,a.rho),bt(Xn(J),1-a.rho));F.assign(U),B.assign(me);var Le=Cr(bt(J,-a.learningRate),v);v.assign(Le)})}),this.incrementIterations()},e.prototype.dispose=function(){this.accumulatedUpdates!=null&&(Ua(this.accumulatedGrads.map(function(n){return n.variable})),Ua(this.accumulatedUpdates.map(function(n){return n.variable})))},e.prototype.getWeights=function(){return M(this,void 0,void 0,function(){var n;return V(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 M(this,void 0,void 0,function(){var a,c;return V(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}(_u);jo(Ap);var Fp=function(t){we(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:la(function(){return cp(v.shape,a.initialAccumulatorValue).variable(_)})}}var C=Array.isArray(n)?n[y].tensor:n[d];if(C==null)return;var F=a.accumulatedGrads[y].variable;la(function(){var B=Cr(F,Xn(C));F.assign(B);var U=Cr(bt(Wr(C,to(Cr(B,Ie.backend.epsilon()))),-a.learningRate),v);v.assign(U)})}),this.incrementIterations()},e.prototype.dispose=function(){this.accumulatedGrads!=null&&Ua(this.accumulatedGrads.map(function(n){return n.variable}))},e.prototype.getWeights=function(){return M(this,void 0,void 0,function(){return V(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 M(this,void 0,void 0,function(){var a;return V(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}(_u);jo(Fp);var Dp=function(t){we(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=[],la(function(){y.accBeta1=Ur(a).variable(),y.accBeta2=Ur(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);la(function(){var d=Lr(1,a.accBeta1),y=Lr(1,a.accBeta2);c.forEach(function(v,_){var C=Ie.registeredVariables[v],F=!1;a.accumulatedFirstMoment[_]==null&&(a.accumulatedFirstMoment[_]={originalName:v+"/m",variable:la(function(){return gn(C).variable(F)})}),a.accumulatedSecondMoment[_]==null&&(a.accumulatedSecondMoment[_]={originalName:v+"/v",variable:la(function(){return gn(C).variable(F)})});var B=Array.isArray(n)?n[_].tensor:n[v];if(B==null)return;var U=a.accumulatedFirstMoment[_].variable,J=a.accumulatedSecondMoment[_].variable,me=Cr(bt(U,a.beta1),bt(B,1-a.beta1)),Le=Cr(bt(J,a.beta2),bt(Xn(B),1-a.beta2)),Me=Wr(me,d),He=Wr(Le,y);U.assign(me),J.assign(Le);var lt=Cr(bt(Wr(Me,Cr(to(He),a.epsilon)),-a.learningRate),C);C.assign(lt)}),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&&Ua(this.accumulatedFirstMoment.map(function(n){return n.variable})),this.accumulatedSecondMoment!=null&&Ua(this.accumulatedSecondMoment.map(function(n){return n.variable}))},e.prototype.getWeights=function(){return M(this,void 0,void 0,function(){var n;return V(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 M(this,void 0,void 0,function(){var a,c,d=this;return V(this,function(y){switch(y.label){case 0:return[4,this.extractIterations(n)];case 1:return n=y.sent(),la(function(){d.accBeta1.assign(Ys(d.beta1,d.iterations_+1)),d.accBeta2.assign(Ys(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}(_u);jo(Dp);var Op=function(t){we(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=[],la(function(){v.iteration=Ur(0).variable(),v.accBeta1=Ur(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);la(function(){var d=Lr(1,a.accBeta1),y=Wr(-a.learningRate,Cr(bt(a.iteration,a.decay),1));c.forEach(function(v,_){var C=Ie.registeredVariables[v],F=!1;a.accumulatedFirstMoment[_]==null&&(a.accumulatedFirstMoment[_]={originalName:v+"/m",variable:gn(C).variable(F)}),a.accumulatedWeightedInfNorm[_]==null&&(a.accumulatedWeightedInfNorm[_]={originalName:v+"/v",variable:gn(C).variable(F)});var B=Array.isArray(n)?n[_].tensor:n[v];if(B==null)return;var U=a.accumulatedFirstMoment[_].variable,J=a.accumulatedWeightedInfNorm[_].variable,me=Cr(bt(U,a.beta1),bt(B,1-a.beta1)),Le=bt(J,a.beta2),Me=ci(B),He=ol(Le,Me);U.assign(me),J.assign(He);var lt=Cr(bt(Wr(y,d),Wr(me,Cr(He,a.epsilon))),C);C.assign(lt)}),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&&Ua(this.accumulatedFirstMoment.map(function(n){return n.variable})),this.accumulatedWeightedInfNorm!=null&&Ua(this.accumulatedWeightedInfNorm.map(function(n){return n.variable}))},e.prototype.getWeights=function(){return M(this,void 0,void 0,function(){return V(this,function(n){throw new Error("getWeights() is not implemented for Adamax yet.")})})},e.prototype.setWeights=function(n){return M(this,void 0,void 0,function(){return V(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}(_u);jo(Op);var Yh=function(t){we(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];la(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=gu(Ur(-n))},e.prototype.dispose=function(){this.c.dispose()},e.prototype.getWeights=function(){return M(this,void 0,void 0,function(){return V(this,function(n){switch(n.label){case 0:return[4,this.saveIterations()];case 1:return[2,[n.sent()]]}})})},e.prototype.setWeights=function(n){return M(this,void 0,void 0,function(){return V(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}(_u);jo(Yh);var Mp=function(t){we(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=Ur(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:la(function(){return gn(v).variable(_)})}}var C=a.accumulations[y].variable,F=Array.isArray(n)?n[y].tensor:n[d];if(F==null)return;la(function(){var B,U=Cr(bt(a.m,C),F);a.useNesterov?B=Cr(bt(a.c,Cr(F,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&&Ua(this.accumulations.map(function(n){return n.variable}))},e.prototype.setMomentum=function(n){this.momentum=n},e.prototype.getWeights=function(){return M(this,void 0,void 0,function(){return V(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 M(this,void 0,void 0,function(){var a;return V(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}(Yh);jo(Mp);var zp=function(t){we(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:la(function(){return gn(v).variable(_)})}),a.accumulatedMoments[y]==null&&(a.accumulatedMoments[y]={originalName:d+"/momentum",variable:la(function(){return gn(v).variable(_)})}),a.accumulatedMeanGrads[y]==null&&a.centered&&(a.accumulatedMeanGrads[y]={originalName:d+"/mg",variable:la(function(){return gn(v).variable(_)})});var C=Array.isArray(n)?n[y].tensor:n[d];if(C==null)return;var F=a.accumulatedMeanSquares[y].variable,B=a.accumulatedMoments[y].variable;la(function(){var U=Cr(bt(F,a.decay),bt(Xn(C),1-a.decay));if(a.centered){var J=a.accumulatedMeanGrads[y].variable,me=Cr(bt(J,a.decay),bt(C,1-a.decay)),Le=Wr(bt(C,a.learningRate),to(Lr(U,Cr(Xn(me),a.epsilon)))),Me=Cr(bt(B,a.momentum),Le);F.assign(U),J.assign(me),B.assign(Me);var He=Lr(v,Me);v.assign(He)}else{var lt=Cr(bt(F,a.decay),bt(Xn(C),1-a.decay)),Me=Cr(bt(B,a.momentum),Wr(bt(C,a.learningRate),to(Cr(lt,a.epsilon))));F.assign(lt),B.assign(Me);var He=Lr(v,Me);v.assign(He)}})}),this.incrementIterations()},e.prototype.dispose=function(){this.accumulatedMeanSquares!=null&&Ua(this.accumulatedMeanSquares.map(function(n){return n.variable})),this.accumulatedMeanGrads!=null&&this.centered&&Ua(this.accumulatedMeanGrads.map(function(n){return n.variable})),this.accumulatedMoments!=null&&Ua(this.accumulatedMoments.map(function(n){return n.variable}))},e.prototype.getWeights=function(){return M(this,void 0,void 0,function(){var n;return V(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 M(this,void 0,void 0,function(){var a,c;return V(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}(_u);jo(zp);var sc=function(){function t(){}return t.sgd=function(e){return new Yh(e)},t.momentum=function(e,n,a){return a===void 0&&(a=!1),new Mp(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 zp(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 Ap(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 Op(e,n,a,c,d)},t.adagrad=function(e,n){return n===void 0&&(n=.1),new Fp(e,n)},t}(),k2={sgd:sc.sgd,momentum:sc.momentum,adadelta:sc.adadelta,adagrad:sc.adagrad,rmsprop:sc.rmsprop,adamax:sc.adamax,adam:sc.adam},S2=function(){return typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:function(t){return t()}}();function I2(){return new Promise(function(t){return S2(function(){return t()})})}function N2(t,e,n){var a=n*(typeof t=="number"?t:t[0]),c=e*(typeof t=="number"?t:t[1]);return[a,c]}function C2(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 E2(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,_=ti(a.shape,c);return _.length>0&&(v=Yr(v,_)),Ke(v,a.shape)};return{a:d,b:y}}},ov={kernelName:di,saveAllInputs:!0,gradFunc:function(t,e){var n={};return e.forEach(function(a,c){n[c]=function(){return t.clone()}}),n}},sv={kernelName:ln,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return gn(n)}}}},uv={kernelName:ai,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return gn(n)}}}},cv={kernelName:gr,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return Wr(t,to(Lr(Ur(1),Xn(dr(n,"float32")))))}}}},lv={kernelName:Ai,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){var a=to(Cr(Ur(1),Xn(dr(n,"float32"))));return Wr(t,a)}}}},hv={kernelName:Qn,inputsToSave:["a","b"],gradFunc:function(t,e){var n=e[0],a=e[1],c=pa(n.shape,a.shape),d=function(){var v=Cr(Xn(n),Xn(a)),_=bt(t,Wr(a,v)),C=ti(n.shape,c);return C.length>0&&(_=Yr(_,C)),Ke(_,n.shape)},y=function(){var v=Cr(Xn(n),Xn(a)),_=ri(bt(t,Wr(n,v))),C=ti(a.shape,c);return C.length>0&&(_=Yr(_,C)),Ke(_,a.shape)};return{a:d,b:y}}},pv={kernelName:wi,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return Wr(t,Cr(Xn(dr(n,"float32")),1))}}}},dv={kernelName:no,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return Wr(t,Lr(Ur(1),Xn(dr(n,"float32"))))}}}};function fv(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,F=_,B=!1;_.rank===4&&(B=!0,C=Ke(v,[1,v.shape[0],v.shape[1],v.shape[2],v.shape[3]]),F=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(F.rank===5,function(){return"Error in avgPool3dBackprop: input must be rank 5 but got rank "+(F.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(yt(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(F.shape,n,a,c,d,y);return Me.avgPool3dBackprop(C,F,He)},J={dy:C,input:F},me={filterSize:n,strides:a,dilations:c,pad:d,dimRoundingMode:y},Le=Ie.runKernelFunc(U,J,null,Di,me);return B?Ke(Le,[Le.shape[1],Le.shape[2],Le.shape[3],Le.shape[4]]):Le}var mv=Re({avgPool3dBackprop_:fv}),yv={kernelName:qi,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,F=v==null?[1,1,1]:v;return{x:function(){return mv(t,a,d,y,F,_,C)}}}};function vv(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 F=function(me){var Le=h(v.shape,n,a,1,c);return me.avgPoolBackprop(_,v,Le)},B={dy:_,input:v},U={filterSize:n,strides:a,pad:c},J=Ie.runKernelFunc(F,B,null,Fi,U);return C?Ke(J,[J.shape[1],J.shape[2],J.shape[3]]):J}var gv=Re({avgPoolBackprop_:vv}),xv={kernelName:ji,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 gv(t,a,d,y,v)}}}},_v={kernelName:ya,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 sn(t,c,!1,!0)},b:function(){return sn(a,t,!0,!1)}}:!y&&v?{a:function(){return sn(t,c,!1,!1)},b:function(){return sn(t,a,!0,!1)}}:y&&!v?{a:function(){return sn(c,t,!1,!0)},b:function(){return sn(a,t,!1,!1)}}:{a:function(){return sn(c,t,!0,!0)},b:function(){return sn(t,a,!0,!0)}}}},wv={kernelName:Oi,gradFunc:function(t,e,n){var a=n,c=a.blockShape,d=a.crops;return{x:function(){return Ph(t,c,d)}}}},bv={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)}}}},kv={kernelName:Y,gradFunc:function(t){return{x:function(){return t.clone()}}}},Sv={kernelName:j,gradFunc:function(t){return{x:function(){return gn(t)}}}},Iv={kernelName:ne,inputsToSave:["x"],gradFunc:function(t,e,n){var a=e[0],c=n,d=c.clipValueMin,y=c.clipValueMax;return{x:function(){return ls(rc(Ju(a,d),$u(a,y)),t,gn(t))}}}},Nv={kernelName:Ue,saveAllInputs:!0,gradFunc:function(t,e,n){var a=e.map(function(_){return _.shape}),c=n.axis,d=jt(c,e[0].shape)[0],y=a.map(function(_){return _[d]}),v=ll(t,y,d);return v.map(function(_){return function(){return _}})}},Cv={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,F=y.dataFormat;return W(ct(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 Ci(c.shape,t,d,_,C,F)},filter:function(){return Ep(c,t,d.shape,_,C,F)}}}},Tv={kernelName:ze,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,F=y.dimRoundingMode;return{dy:function(){return gi(t,d,v,_,C,1,F)},filter:function(){return Ep(t,c,d.shape,v,_,C,F)}}}};function Ev(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(F){var B=1,U=O(d.shape,n,a,B,c);return F.conv3dDerFilter(d,y,U)},_={x:d,dy:y},C={strides:a,pad:c,filterShape:n};return Ie.runKernelFunc(v,_,null,Dt,C)}var Rv=Re({conv3DBackpropFilter_:Ev}),Av={kernelName:Ye,inputsToSave:["x","filter"],gradFunc:function(t,e,n){var a=n,c=a.dilations,d=a.strides,y=a.pad;W(ct(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 Ch(v.shape,t,_,d,y)},filter:function(){return Rv(v,t,_.shape,d,y)}}}},Fv={kernelName:Mt,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return bt(ri(Sp(dr(n,"float32"))),t)}}}},Dv={kernelName:fr,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return bt(Ip(dr(n,"float32")),t)}}}},Ov={kernelName:or,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 _=$i([d],a.rank),C=sp(t,d,y,!v);return _!=null&&(C=$n(C,_)),C}}}},Mv={kernelName:ia,inputsToSave:["x","filter"],gradFunc:function(t,e,n){var a=n,c=a.dilations,d=a.strides,y=a.pad,v=a.dimRoundingMode,_=c==null?[1,1]:c;W(ct(_),function(){return"Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations "+("'"+_+"'")});var C=e,F=C[0],B=C[1];return W(F.rank===4,function(){return"Error in gradient of depthwiseConv2dNative: input must be "+("rank 4, but got rank "+F.rank+".")}),W(B.rank===4,function(){return"Error in gradient of depthwiseConv2dNative: filter must be "+("rank 4, but got rank "+B.rank+".")}),W(F.shape[3]===B.shape[2],function(){return"Error in gradient of depthwiseConv2d: number of input "+("channels ("+F.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(yt(y),function(){return"Error in depthwiseConv2d: pad must be an integer when using, "+("dimRoundingMode "+v+" but got pad "+y+".")}),{x:function(){return Kd(F.shape,t,B,d,y,c,v)},filter:function(){return qd(F,t,B.shape,d,y,c,v)}}}},zv={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(oa,y,n)},filter:function(){return Ie.runKernel(Jr,v,n)}}}},Lv={kernelName:Vr,inputsToSave:["a","b"],gradFunc:function(t,e){var n=e[0],a=e[1],c=pa(n.shape,a.shape),d=function(){var v=Wr(t,dr(a,"float32")),_=ti(n.shape,c);return _.length>0?Ke(Yr(v,_),n.shape):v},y=function(){var v=bt(t,dr(n,"float32")),_=ti(a.shape,c);_.length>0&&(v=Ke(Yr(v,_),a.shape));var C=Xn(a);return ri(Wr(v,dr(C,"float32")))};return{a:d,b:y}}},Pv={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)}}}},Bv={kernelName:En,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0],a=bt(hs(ri(Xn(n))),2/Math.sqrt(Math.PI));return{x:function(){return bt(t,a)}}}},Wv={kernelName:sa,outputsToSave:[!0],gradFunc:function(t,e){var n=e[0];return{x:function(){return bt(t,n)}}}},Uv={kernelName:ga,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return bt(t,hs(n))}}}},Vv={kernelName:x,gradFunc:function(t){return{x:function(){return gn(t)}}}},Hv={kernelName:k,inputsToSave:["a","b"],gradFunc:function(t,e){var n=e[0],a=e[1],c=pa(n.shape,a.shape),d=function(){var v=Wr(t,dr(a,"float32")),_=ti(n.shape,c);return _.length>0?Ke(Yr(v,_),n.shape):v},y=function(){var v=bt(t,dr(n,"float32")),_=ti(a.shape,c);_.length>0&&(v=Ke(Yr(v,_),a.shape));var C=Xn(a);return ri(Wr(v,dr(C,"float32")))};return{a:d,b:y}}},Gv={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==null?Ur(1):v,C=ti(d.shape,c.shape),F=[];if(d.rank===1){for(var B=0;B0?Ke(Yr(t,v),n.shape):t},y=function(){var v=bt(t,ri(Eh(Wr(n,a)))),_=ti(a.shape,c);return _.length>0?Ke(Yr(v,_),a.shape):v};return{a:d,b:y}}},f5={kernelName:qr,inputsToSave:["a","b"],gradFunc:function(t,e){var n=e[0],a=e[1],c=pa(n.shape,a.shape),d=function(){var v=bt(t,dr(a,"float32")),_=ti(n.shape,c);return _.length>0?Ke(Yr(v,_),n.shape):v},y=function(){var v=bt(t,dr(n,"float32")),_=ti(a.shape,c);return _.length>0?Ke(Yr(v,_),a.shape):v};return{a:d,b:y}}},m5={kernelName:Io,gradFunc:function(t){return{x:function(){return ri(t)}}}},y5={kernelName:Li,inputsToSave:["indices"],gradFunc:function(t,e){var n=e[0];return{indices:function(){return Xs(n.shape,"float32")}}}},v5={kernelName:si,gradFunc:function(t){return{x:function(){return gn(t)}}}},lf={kernelName:ao,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 er(t,d,a.shape)}}}},g5={kernelName:Za,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:function(t,e){var n=e[0],a=e[1],c=e[2],d=n,y=a,v=pa(d.shape,y.shape),_=function(){var F=dr(y,"float32"),B=bt(t,bt(F,Ys(d,Lr(F,Ur(1))))),U=ti(d.shape,v);return U.length>0&&(B=Yr(B,U)),Ke(B,d.shape)},C=function(){var F=xu(d,0),B=ls(F,ec(d),gn(d)),U=bt(t,bt(c,B)),J=ti(y.shape,v);return J.length>0&&(U=Yr(U,J)),Ke(U,y.shape)};return{a:_,b:C}}},x5={kernelName:io,inputsToSave:["x","alpha"],gradFunc:function(t,e){var n=e[0],a=e[1],c=xu(n,0);return{x:function(){return ls(c,t,bt(t,a))},alpha:function(){var d=ls(c,gn(t),bt(t,n)),y=ti(a.shape,t.shape);return y.length>0&&(d=Yr(d,y)),Ke(d,a.shape)}}}},_5={kernelName:oo,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return Wr(t,ri(Xn(n)))}}}},w5={kernelName:Ta,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0],a=bt($u(n,6),hl(n));return{x:function(){return bt(t,dr(a,"float32"))}}}},b5={kernelName:ua,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return bt(t,dr(hl(n),"float32"))}}}},k5={kernelName:Br,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return Ke(t,n.shape)}}}},S5={kernelName:Zn,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,so,n)};return{images:y}}},I5={kernelName:ca,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,Qa,n)};return{images:y}}},N5={kernelName:vn,gradFunc:function(t,e,n){var a=n.dims,c=jt(a,t.shape);return{x:function(){return Zs(t,c)}}}},C5={kernelName:Pi,gradFunc:function(t){return{x:function(){return gn(t)}}}},T5={kernelName:yo,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return ri(Wr(t,bt(Ys(n,1.5),2)))}}}},E5={kernelName:Da,inputsToSave:["condition"],gradFunc:function(t,e){var n=e[0];return{condition:function(){return dr(gn(n),"float32")},t:function(){return bt(t,dr(n,t.dtype))},e:function(){return bt(t,dr(Oh(n),t.dtype))}}}},R5={kernelName:go,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){var a=xu(n,Ur(0)),c=Ur(nf),d=Ur(af),y=bt(t,d),v=bt(bt(t,c),hs(dr(n,"float32")));return ls(a,y,v)}}}},A5={kernelName:As,outputsToSave:[!0],gradFunc:function(t,e){var n=e[0];return{x:function(){return bt(t,bt(n,Lr(Ur(1),n)))}}}},F5={kernelName:Rs,gradFunc:function(t){return{x:function(){return gn(t)}}}},D5={kernelName:Es,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return bt(Th(dr(n,"float32")),t)}}}},O5={kernelName:Eo,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return bt(op(dr(n,"float32")),t)}}}},M5={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,_=Vu(a,d,y),C=_[0],F=_[1],B=[],U=0;U0&&(v=Yr(v,_)),Ke(v,n.shape)},y=function(){var v=t,_=ti(a.shape,c);return _.length>0&&(v=Yr(v,_)),Ke(ri(v),a.shape)};return{a:d,b:y}}},H5={kernelName:Qo,inputsToSave:["x"],gradFunc:function(t,e,n){var a=e[0],c=a.shape.slice(),d=n.axis,y=jt(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 _}}}},G5={kernelName:fs,inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return Wr(t,Xn(Th(n)))}}}},j5={kernelName:Os,outputsToSave:[!0],gradFunc:function(t,e){var n=e[0];return{x:function(){return bt(Lr(Ur(1),Xn(n)),t)}}}},q5={kernelName:Ms,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(),we=function(s,u){return we=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])},we(s,u)};function M(s,u){we(s,u);function r(){this.constructor=s}s.prototype=u===null?Object.create(u):(r.prototype=u.prototype,new r)}var V=function(){return V=Object.assign||function(s){for(var u,r=1,o=arguments.length;r0&&b[b.length-1])&&(Z[0]===6||Z[0]===2)){r=0;continue}if(Z[0]===3&&(!b||Z[1]>b[0]&&Z[1]u?1:0}function rr(s,u){return-1*Qt(s,u)}function jt(s){if(s==null)return s;for(var u=[],r=0,o=s;r=0),ut(o>=r),Array.isArray(s)&&s.length>=r&&s.length<=o&&s.every(function(h){return typeof h===u})}function ar(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 ar(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 "+(da(s)+".")})}function da(s){return s===null?"null":Array.isArray(s)?"["+s.map(function(u){return da(u)}).join(",")+"]":typeof s=="string"?'"'+s+'"':""+s}function Ha(s,u){var r=i.util.now(),o,h=function(){for(var b=[],T=0;T0){var r=s+"_"+u;return La.set(r,1),r}else return s}var jn=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function ni(s){return!!s.match(jn)}function pi(s){return s===parseInt(s.toString(),10)}function ma(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 xe("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,O=!1;return i.fused.matMul({a:s,b:u,transposeA:T,transposeB:O,bias:o?ne(s.rank,o,he()):null,activation:r})}else{var q=s.shape.slice(),Z=q.pop();s=s.reshape([-1,Z]);var le=u.shape.slice(),Ne=le.pop(),b=le.pop(),Be=le.concat([Ne]),je=Array.from({length:u.rank},function(dt,Ft){return Ft===0?u.rank-2:Ft<=u.rank-2?Ft-1:Ft});u=u.transpose(je).reshape([b,-1]);var qe=q.concat(Be),T=!1,O=!1;return i.fused.matMul({a:s,b:u,transposeA:T,transposeB:O,bias:o?ne(s.rank,o,he()):null,activation:r}).reshape(qe)}}function Y(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 ne(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 re(s,u,r){return i.tidy(function(){return r==null&&(r=he()),on(r),s.add(ne(s.rank,u,r))})}function Ue(s,u){if(u===void 0&&(u=1),u!==1)throw new xe("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 tt(s,u,r,o){return i.tidy(function(){return i.dropout(s,u,r,o)})}function ze(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 Dt=["fanIn","fanOut","fanAvg"],St=["normal","uniform","truncatedNormal"];function Mt(s){Pr(Dt,"FanMode",s)}function fr(s){Pr(St,"Distribution",s)}var or=function(s){M(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),aa=function(s){M(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}(or);i.serialization.registerClass(aa);var va=function(s){M(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}(or);i.serialization.registerClass(va);var ia=function(s){M(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}(or);i.serialization.registerClass(ia);var qa=function(s){M(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}(or);i.serialization.registerClass(qa);var bi=function(s){M(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 xe("randomNormal does not support dType "+o+".");return Oi(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}(or);i.serialization.registerClass(bi);var rn=function(s){M(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 xe("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}(or);i.serialization.registerClass(rn);var hn=function(s){M(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}(or);i.serialization.registerClass(hn);function oa(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=ma(s,2);r=s[1]*h,o=s[0]*h}else if(u==="channelsLast"){var h=ma(s,0,s.length-2);r=s[s.length-2]*h,o=s[s.length-1]*h}}else{var b=ma(s);r=Math.sqrt(b),o=Math.sqrt(b)}return[r,o]}var Jr=function(s){M(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,fr(o.distribution),o.seed=r.seed,o}return u.prototype.apply=function(r,o){var h=oa(r),b=h[0],T=h[1],O=this.scale;if(this.mode==="fanIn"?O/=Math.max(1,b):this.mode==="fanOut"?O/=Math.max(1,T):O/=Math.max(1,(b+T)/2),this.distribution==="normal"){var q=Math.sqrt(O);if(o=o||"float32",o!=="float32"&&o!=="int32")throw new xe(this.getClassName()+" does not support dType "+o+".");return i.truncatedNormal(r,0,q,o,this.seed)}else{var Z=Math.sqrt(3*O);return i.randomUniform(r,-Z,Z,o)}},u.prototype.getConfig=function(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}},u.className="VarianceScaling",u}(or);i.serialization.registerClass(Jr);var Vr=function(s){M(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){M(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){M(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 En=function(s){M(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(En);var qn=function(s){M(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(qn);var sa=function(s){M(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(sa);var ga=function(s){M(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 xe("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 xe("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=Oi(b,0,1,"float32"),O=i.linalg.gramSchmidt(T);return r[0]>r[1]&&(O=O.transpose()),i.mul(h.gain,O)})},u.prototype.getConfig=function(){return{gain:this.gain,seed:this.seed}},u.className="Orthogonal",u}(or);i.serialization.registerClass(ga);var Mi={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 Aa(s,u){return u===void 0&&(u={}),et(s,i.serialization.SerializationMap.getMap().classNameMap,u,"initializer")}function S(s){return ot(s)}function x(s){if(typeof s=="string"){var u=s in Mi?Mi[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 En;if(u==="LeCunNormal")return new qn;if(u==="LeCunUniform")return new sa;var r={};return r.className=u,r.config={},Aa(r)}else return s instanceof or?s:Aa(s)}function k(){return new aa}function K(){return new va}function Se(s){return new ia(s)}function be(s){return new qa(s)}function Je(s){return new bi(s)}function Pe(s){return new rn(s)}function gt(s){return new hn(s)}function ft(s){return new Jr(s)}function Lt(s){return new Vr(s)}function Wt(s){return new Jn(s)}function Gt(s){return new tn(s)}function Jt(s){return new En(s)}function wr(s){return new qn(s)}function Ar(s){return new sa(s)}function Zt(s){return new ga(s)}var xr={__proto__:null,zeros:k,ones:K,constant:Se,randomUniform:be,randomNormal:Je,truncatedNormal:Pe,identity:gt,varianceScaling:ft,glorotUniform:Lt,glorotNormal:Wt,heNormal:Gt,heUniform:Jt,leCunNormal:wr,leCunUniform:Ar,orthogonal:Zt},kn=0;function pn(){return kn++}var zn={};function Dr(s){return s===void 0&&(s=""),s in zn||(zn[s]=0),zn[s]+=1,s+zn[s].toString()}function Na(s){return Array.isArray(s)&&Array.isArray(s[0])}function Sn(s){return s.length===0?[]:Array.isArray(s[0])?s:[s]}function cr(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 Fa(s){for(var u=0,r=0,o=s;r1)throw new ye("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 ye("Layer "+this.name+" is not connected, no input to return.");return It(this.getNodeAtIndex(0,"input").inputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(u.prototype,"output",{get:function(){if(this.inboundNodes.length===0)throw new ye("Layer "+this.name+" has no inbound nodes.");if(this.inboundNodes.length>1)throw new ye("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use `getOutputAt(nodeIndex)` instead.');return It(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=Ze(r),this.inputSpec==null||this.inputSpec.length===0)return;var o=Ze(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(Be)===-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(hr[0])?ct=hr.map(function(kr,Sr){return new Ca(Ir,kr,h,Ze(r),o,h.name,Sr)}):ct=new Ca(Ir,hr,h,Ze(r),o,h.name),h.addInboundNode(r,ct,null,null,vr,hr,o),h._refCount++,h.activityRegularizer!=null)throw new xe("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return ct}})},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 ye("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(O=Z.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 Br(s,u,r,o,h,b,T,O,q){var Z=new No,le=[new Yo].concat(ua.createCallbacks(u));s!=null&&le.push.apply(le,s),le.push(Z);var Ne=new io(le);return Ne.setParams({epochs:r,initialEpoch:o,samples:h,steps:b,batchSize:T,verbose:u,doValidation:O,metrics:q}),{callbackList:Ne,history:Z}}function ca(s,u,r){return u===void 0&&(u={}),r===void 0&&(r=!1),et(s,i.serialization.SerializationMap.getMap().classNameMap,u,"layer",r)}function Qa(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,z()),h=i.sqrt(i.maximum(r,o));return i.div(s,h)})}function Zn(s,u){return i.tidy(function(){return i.mean(j(i.sub(u,s)),-1)})}function so(s,u){return i.tidy(function(){return i.mean(i.abs(i.sub(u,s)),-1)})}function Ta(s,u){return i.tidy(function(){var r=i.sub(s,u),o=i.clipByValue(i.abs(s),z(),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,z(),Number.MAX_VALUE),o=i.log(i.add(1,r)),h=i.clipByValue(s,z(),Number.MAX_VALUE),b=i.log(i.add(1,h));return i.mean(j(i.sub(o,b)),-1)})}function Pi(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 Da(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,z(),1-z()),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(wi(s)).toInt();u=i.clipByValue(u,z(),1-z());var h=u.shape,b=i.oneHot(o,h[h.length-1]).reshape(h);return go(b,u,r)})}function Es(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,z(),1-z()),r=i.log(i.div(r,i.sub(1,r))),i.mean(Es(s,r),-1)})}function Rs(s,u){return i.tidy(function(){var r=i.clipByValue(s,z(),1),o=i.clipByValue(u,z(),1);return i.sum(i.mul(s,i.log(i.div(r,o))),-1)})}function As(s,u){return i.tidy(function(){var r=i.log(i.add(z(),u));return i.mean(i.sub(u,i.mul(s,r)),-1)})}function Zo(s,u){return i.tidy(function(){var r=Qa(s,-1),o=Qa(u,-1),h=i.mul(r,o);return i.neg(i.sum(h,-1))})}var Ro={meanSquaredError:Zn,meanAbsoluteError:so,meanAbsolutePercentageError:Ta,meanSquaredLogarithmicError:vn,squaredHinge:Pi,hinge:yo,categoricalHinge:vo,logcosh:Da,categoricalCrossentropy:go,sparseCategoricalCrossentropy:To,binaryCrossentropy:Eo,kullbackLeiblerDivergence:Rs,poisson:As,cosineProximity:Zo};function Qo(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=ai(i.greater(u,r),s.dtype);return i.mean(i.equal(s,o),-1)})}function Jo(s,u){return i.tidy(function(){return ai(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 eu(s,u){return i.tidy(function(){return i.logicalAnd(s.equal(0),u.equal(1)).sum().cast("float32")})}function ds(s,u){return i.tidy(function(){var r=vi(s,u),o=eu(s,u),h=r.add(o);return i.where(i.greater(h,0),r.div(h),0).cast("float32")})}function tu(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 Ds(s,u){return Eo(s,u)}function fs(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 Os=Zn,Ms=Zn,ru=so,ms=so,nu=Ta,ys=Ta,Fo=go,zs=Zo,$o=To,xo={binaryAccuracy:Ao,categoricalAccuracy:Jo,precision:ds,categoricalCrossentropy:Fo,sparseCategoricalCrossentropy:$o,mse:Os,MSE:Ms,mae:ru,MAE:ms,mape:nu,MAPE:ys,cosine:zs};function vs(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 Do(s){if(ut(s!==null,"Unknown LossOrMetricFn "+s),typeof s=="string")return s;for(var u=void 0,r=0,o=Object.keys(Ro);res&&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 <= "+(es+"."))}}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||O.length===1&&O[0].inboundLayers.length>1){u=!1;break}o.push.apply(o,O)}if(u)for(var q=0,Z=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 au(s,u,r){var o;try{o=JSON.stringify(s.outputShape)}catch(O){o="multiple"}var h=s.name,b=s.getClassName(),T=[h+" ("+b+")",o,s.countParams().toString()];ts(T,u,r)}function bu(s,u,r,o){var h;try{h=JSON.stringify(s.outputShape)}catch(ct){h="multiple"}for(var b=[],T=0,O=s.inboundNodes;T0&&r.indexOf(q)===-1)continue;for(var Z=0;Zo.maxNumTensors&&(o.maxNumTensors=Ft),Ft0,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,O=s;T0;){var le=q[q.length-1];if(r.has(le.name)){q.pop();continue}var Ne=Z[Z.length-1]===q.length-1;if(le.inputs.length===0||Ne)q.pop(),o.push(le),r.add(le.name),Ne&&Z.pop();else{Z.push(q.length-1);for(var Be=0,je=le.inputs;Be1 nodes"),ut(le===0,"input layer has >1 tensors"),o.inputLayers.push(q),o.inputLayersNodeIndices.push(Z),o.inputLayersTensorIndices.push(le)}o.inputNames=[],o.outputNames=[],o.feedInputShapes=[],o.feedInputNames=[],o.feedOutputNames=[];for(var je=0;je=0;)gi.splice(gi.indexOf(Ci),1);Yt.push(Ci)},vr=[],hr=[],Ir=0,zr=o.outputs;IrCs?1:0});for(var qs=0,Zu=Ui;qs0)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(ct.length+" of "+b+" weights are not set: "+(""+ct))}zi(Be)},u.prototype.updatedConfig=function(){var r=this.getConfig(),o={};return o.className=this.getClassName(),o.config=r,o.kerasVersion="tfjs-layers "+xs,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=Ze(r);for(var b=new ki,T=0;T1)for(var le=0,Ne=Z;le0){for(var vt=[],pt=0;pt0&&un.apply(It(Hr),ha)}function le(un){var On=un.name,Hr=ca(un,o.customObjects!=null?o.customObjects:{});Hr.setFastWeightInitDuringBuild(b),T[On]=Hr;var ha=un.inboundNodes;ha.forEach(function(Ni){if(!(Ni instanceof Array))throw new w("Corrupted configuration, expected array for nodeData: "+Ni);q(Hr,Ni)})}for(var Ne=o.name,Be=o.layers,je=0,qe=Be;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 H(s,u){return A(s,u,"classWeight")}function se(s,u,r,o){return de(this,void 0,void 0,function(){var h,b,T,O,q;return X(this,function(Z){switch(Z.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.")}),O=(T=Array).from,[4,h.data()]):[3,2];case 1:return b=O.apply(T,[Z.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 te(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=fe("input",s.inputNames,r),T=fe("output",s.outputNames,o),O=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(Be){i.util.assert(b[Be].shape[0]===O,function(){return"Batch size mismatch: input "+(s.inputNames[Be]+" has "+b[Be].shape[0]+"; ")+("expected "+O+" based on input "+s.inputNames[0]+".")})},Z=0;Z0&&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)}):(O=ve(r.validationData),b=O.xs,T=O.ys)),q=s.makeTrainFunction(),Z=s.getDedupedMetricsNames(),le=void 0,h?le=Z.slice().concat(Z.map(function(ha){return"val_"+ha})):le=Z.slice(),Ne=oo(r.callbacks,r.yieldEvery),Be=r.verbose==null?1:r.verbose,je=Br(Ne,Be,r.epochs,null,null,Ae(u,r),null,h,le),qe=je.callbackList,vt=je.history,qe.setModel(s),s.history=vt,[4,qe.onTrainBegin()];case 2:return Hr.sent(),s.stopTraining_=!1,pt=r.initialEpoch==null?0:r.initialEpoch,[4,u.iterator()];case 3:ct=Hr.sent(),Hr.label=4;case 4:return pt=r.batchesPerEpoch:Yt.done)?h?(un=void 0,Oe(r.validationData)?(On=Ze,[4,s.evaluateDataset(r.validationData,{batches:r.validationBatches})]):[3,17]):[3,19]:[3,20];case 16:return un=On.apply(void 0,[Hr.sent()]),[3,18];case 17:un=Ze(s.evaluate(b,T,{batchSize:r.validationBatchSize==null?_e:r.validationBatchSize,verbose:0})),Hr.label=18;case 18:for(Sr=0;Sr0)throw new xe("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))}),De(u)?(O=u,[3,3]):[3,1];case 1:return[4,u.iterator()];case 2:O=qe.sent(),qe.label=3;case 3:T=O,q=0,Z=0,le=function(){var vt;return X(this,function(pt){switch(pt.label){case 0:return[4,T.next()];case 1:return vt=pt.sent(),b=i.tidy(function(){if(vt.value){var ct=ce(s,vt.value),dt=ct.xs,Ft=ct.ys,sr=dt.concat(Ft),Yt=i.tidy(function(){return h(sr)});if(i.dispose(sr),Z===0)for(var $t=0;$t0&&i.dispose(Sr)},$t=0;$t0&&Number.isInteger(s),function(){return"batchSize is required to be a positive integer, but got "+s})}function at(s,u,r){return s==null?[null]:Array.isArray(s)?s.map(function(o){return Qn(o,u,r-u)}):Qn(s,u,r-u)}function it(s,u){return i.tidy(function(){return s==null?null:Array.isArray(s)?s.map(function(r){return it(r,u)}):Y(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 rt(s,u,r,o,h,b,T,O,q,Z,le,Ne,Be,je,qe){return de(this,void 0,void 0,function(){var vt,pt,ct,dt,Ft,sr,Yt,$t,vr;return X(this,function(hr){switch(hr.label){case 0:if(h==null&&(h=32),b==null&&(b=1),le==null&&(le=!0),Be==null&&(Be=0),vt=!1,q!=null&&Z!=null&&(vt=!0),qe!=null&&(vt=!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&&(ct=ln(0,pt)),T==null&&(T=1),dt=Br(O,T,b,Be,pt,je,h,vt,Ne),Ft=dt.callbackList,sr=dt.history,Ft.setModel(s),s.history=sr,[4,Ft.onTrainBegin()];case 1:hr.sent(),s.stopTraining_=!1,Yt=function(Ir){var zr,kr,Sr,mn,Xr,er;return X(this,function(Dn){switch(Dn.label){case 0:return[4,Ft.onEpochBegin(Ir)];case 1:if(Dn.sent(),zr={},!(je!=null))return[3,2];throw new xe("stepsPerEpoch mode is not implemented yet.");case 2:if(le==="batch")throw new xe("batch shuffling is not implemneted yet");le&&i.util.shuffle(ct),kr=i.tensor1d(ct),Sr=$(pt,h),mn=function(Cn){var bn;return X(this,function(un){switch(un.label){case 0:return bn={},[4,Ft.onBatchBegin(Cn,bn)];case 1:return un.sent(),i.tidy(function(){var On=Sr[Cn][0],Hr=Sr[Cn][1],ha=Qn(kr,On,Hr-On);bn.batch=Cn,bn.size=Hr-On;for(var Ni=it(r,ha),Wi=u(Ni),Kn=0;Kn0))return[3,4];if(qe=!0,o.validationData.length===2)T=o.validationData[0],O=o.validationData[1];else throw o.validationData.length===3?new xe("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,O,null,null,pt,Ne)];case 3:return ct=kr.sent(),q=ct[0],Z=ct[1],vt=q.concat(Z),[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)),Ft=h[0].shape[0],q=at(h,dt,Ft),h=at(h,0,dt),Z=at(b,dt,Ft),b=at(b,0,dt),vt=q.concat(Z)):o.validationSteps!=null&&(qe=!0),kr.label=5;case 5:return sr=h.concat(b).concat(le),s.checkTrainableWeightsConsistency(),Yt=s.makeTrainFunction(),$t=s.getDedupedMetricsNames(),vr=void 0,hr=void 0,qe?(s.makeTestFunction(),vr=s.testFunction,hr=$t.slice().concat($t.map(function(Sr){return"val_"+Sr}))):(vr=null,vt=[],hr=$t.slice()),Ir=oo(o.callbacks,o.yieldEvery),[4,rt(s,Yt,sr,$t,Ne,o.epochs,o.verbose,Ir,vr,vt,o.shuffle,hr,o.initialEpoch,null,null)];case 6:return zr=kr.sent(),[2,zr];case 7:return s.isTraining=!1,_t(h,u),_t(b,r),_t(q,T),_t(Z,O),le!=null&&i.dispose(le),[7];case 8:return[2]}})})}function ht(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 O;if(Pt(s)){s=s,O=[];for(var q=0,Z=u;q1)throw new w("The model "+h+" expects "+u.length+" Tensor(s), "+("but only received one Tensor. Found: Tensor with shape "+s.shape));O=[s]}if(O=ht(O),r!=null)for(var Ne=0;Ne=0&&qe!==vt)throw new w("Error when checking "+h+": expected "+u[Ne]+" "+("to have shape ["+r[Ne]+"], but got array with shape ")+("["+Be.shape+"]."))}}return O}function Tt(s,u,r){var o=jt(s.map(function(b){return b.shape[0]}));o.sort();var h=jt(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 Xt(s,u,r){for(var o=[Zn,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,ct]),o.metricsNames.push(o.outputNames[ct]+"_loss"))}});var vt=Ot(r.metrics,this.outputNames),pt=function(ct,dt,Ft){o.outputNames.length>1&&(dt=o.outputNames[ct]+"_"+dt),o.metricsNames.push(dt),o.metricsTensors.push([Ft,ct])};na("metric",function(){for(var ct=function(Ft){if(qe.indexOf(Ft)!==-1)return"continue";var sr=vt[Ft],Yt=function($t){for(var vr="",hr,Ir,zr,kr=function(er){if(typeof er=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(er)!==-1){var Dn=o.internalOutputShapes[Ft];Dn[Dn.length-1]===1||o.lossFunctions[Ft]===Eo?["accuracy","acc"].indexOf(er)!==-1?Ir=Ao:["crossentropy","ce"].indexOf(er)!==-1&&(Ir=Ds):o.lossFunctions[Ft]===To?["accuracy","acc"].indexOf(er)!==-1?Ir=fs:["crossentropy","ce"].indexOf(er)!==-1&&(Ir=$o):["accuracy","acc"].indexOf(er)!==-1?Ir=Jo:["crossentropy","ce"].indexOf(er)!==-1&&(Ir=Fo);var Cn=void 0;["accuracy","acc"].indexOf(er)!==-1?Cn="acc":["crossentropy","ce"].indexOf(er)!==-1&&(Cn="ce"),zr=Ir,hr=vr+Cn}else{var bn=vs(er);zr=bn,hr=vr+Do(er)}var un;na(hr,function(){un=zr}),pt(Ft,hr,un)},Sr=0,mn=$t;Sr0){var Be=[];throw o.forEach(function(je,qe){je==null&&Be.push(r[qe])}),new w("Cannot find SymbolicTensors for output name(s): "+(""+JSON.stringify(Be)))}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 xe("Verbose predictLoop() is not implemented yet.");for(var O=$(T,o),q=b.outputs.map(function(Ne){return[]}),Z=function(Ne){var Be=i.tidy(function(){var je=O[Ne][0],qe=O[Ne][1],vt=at(r,je,qe),pt=[];if(Array.isArray(vt))for(var ct=0;ct0&&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,O){return T===void 0&&(T=!0),de(this,void 0,void 0,function(){var q,Z,le,Ne,Be,je,qe,vt;return X(this,function(pt){switch(pt.label){case 0:if(q=this.standardizeUserDataXY(r,o,T,O),Z=q[0],le=q[1],h!=null)throw new Error("sample weight is not supported yet.");if(Ne=null,!(b!=null))return[3,4];Be=H(b,this.outputNames),Ne=[],je=0,pt.label=1;case 1:return je0)throw new xe("Verbose mode is not implemented yet.");if(T!=null)throw new xe("steps mode in testLoop() is not implemented yet");for(var le=$(q,h),Ne=i.tensor1d(ln(0,q)),Be=0;Be1){var O=Kt(r.slice(0,h),b);T+="_"+O}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),O=o.slice(r.inputs.length+r.outputs.length,r.inputs.length+r.outputs.length*2),q=[],Z=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=Ft.sent(),T=!1,O=null,q=this.toJSON(O,T),Z={modelTopology:q,format:Rt,generatedBy:"TensorFlow.js tfjs-layers v"+xs,convertedBy:null},le=o==null?!1:o.includeOptimizer,le&&this.optimizer!=null?(Z.trainingConfig=this.getTrainingConfig(),Ne="optimizer",pt=(vt=i.io).encodeWeights,[4,this.optimizer.getWeights()]):[3,4];case 2:return[4,pt.apply(vt,[Ft.sent(),Ne])];case 3:Be=Ft.sent(),je=Be.data,qe=Be.specs,(dt=b.specs).push.apply(dt,qe),b.data=i.io.concatenateArrayBuffers([b.data,je]),Ft.label=4;case 4:return this.userDefinedMetadata!=null&&(ct=!0,_o(this.userDefinedMetadata,this.name,ct),Z.userDefinedMetadata=this.userDefinedMetadata),Z.weightData=b.data,Z.weightSpecs=b.specs,[2,r.save(Z)]}})})},u.prototype.setUserDefinedMetadata=function(r){_o(r,this.name),this.userDefinedMetadata=r},u.prototype.getUserDefinedMetadata=function(){return this.userDefinedMetadata},u.className="Model",u}(D);i.serialization.registerClass(wt);var Et=function(s){M(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 de(this,void 0,void 0,function(){var r,o,h,b,T,O,q,Z;return X(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=ca(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={},O=0,q=h.weights;O1)throw new w("Found more than one ("+r.length+") load handlers for "+("URL '"+s+"'"));s=r[0]}return[2,lr(s,void 0,u)]})})}function lr(s,u,r){return de(this,void 0,void 0,function(){var o,h,b,T,O,q,Z,le,Ne;return X(this,function(Be){switch(Be.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=Be.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,O=ca(Oo(h),u,T),q=o.trainingConfig,q!=null&&O.loadTrainingConfig(q),o.userDefinedMetadata!=null&&O.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 Z=ir(o.weightData,o.weightSpecs),le=Z.modelWeights,Ne=Z.optimizerWeights,O.loadWeights(le,b),O.optimizer!=null&&Ne.length>0?[4,O.optimizer.setWeights(Ne)]:[3,3];case 2:Be.sent(),Be.label=3;case 3:i.dispose(le),i.dispose(Ne.map(function(je){return je.tensor})),Be.label=4;case 4:return[2,O]}})})}function ir(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){M(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:Dr("sequential_"),r.layers!=null)for(var h=0,b=r.layers;h 0 "+("but got "+JSON.stringify(r.filters)))},u}(Nu),Cu=function(s){M(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}(uu);i.serialization.registerClass(Cu);var hc=function(s){M(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}(uu);i.serialization.registerClass(hc);var co=function(s){M(u,s);function u(r){var o=s.call(this,r)||this;if(o.inputSpec=[new Rn({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 Rn({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=cr(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,O=T[0],q,Z;h.dataFormat==="channelsFirst"?(q=2,Z=3):(q=1,Z=2);var le=T[q],Ne=T[Z],Be=h.kernelSize[0],je=h.kernelSize[1],qe=h.strides[0],vt=h.strides[1],pt=ws(le,qe,Be,h.padding),ct=ws(Ne,vt,je,h.padding),dt=[O,pt,ct,h.filters];h.dataFormat!=="channelsLast"&&(b=i.transpose(b,[0,2,3,1]));var Ft=i.conv2dTranspose(b,h.kernel.read(),dt,h.strides,h.padding);return h.dataFormat!=="channelsLast"&&(Ft=i.transpose(Ft,[0,3,1,2])),h.bias!=null&&(Ft=re(Ft,h.bias.read(),h.dataFormat)),h.activation!=null&&(Ft=h.activation.apply(Ft)),Ft})},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 O=this.kernelSize[0],q=this.kernelSize[1],Z=this.strides[0],le=this.strides[1];return o[h]=this.filters,o[b]=ws(o[b],Z,O,this.padding),o[T]=ws(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}(Cu);i.serialization.registerClass(co);var ks=function(s){M(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=fn(o.depthwiseConstraint),h.pointwiseInitializer=x(o.depthwiseInitializer||h.DEFAULT_POINTWISE_INITIALIZER),h.pointwiseRegularizer=Fn(o.pointwiseRegularizer),h.pointwiseConstraint=fn(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,O){return o===void 0&&(o=!1),T===void 0&&(T=!1),O===void 0&&(O=!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 Z=[1,0].concat(ln(2,q));if(u=i.transpose(u,Z),b!=null)throw new xe("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,Z)),o&&(u=i.reverse(u,0),h!=null&&(h=i.reverse(h,0)));var le=[],Ne,Be=r,je=u.shape[0],qe=i.unstack(u),vt;h!=null&&(vt=i.unstack(h));for(var pt=function(sr){var Yt=qe[sr],$t=i.tidy(function(){return s(Yt,Be)});if(h==null)Ne=$t[0],Be=$t[1];else{var vr=i.tidy(function(){var hr=vt[sr],Ir=i.onesLike(hr).sub(hr),zr=$t[0].mul(hr).add(Be[0].mul(Ir)),kr=Be.map(function(Sr,mn){return $t[1][mn].mul(hr).add(Sr.mul(Ir))});return{output:zr,newStates:kr}});Ne=vr.output,Be=vr.newStates}O&&le.push(Ne)},ct=0;ct1?ya(h,[1,b]):h}):o.cell.stateSize>1?[ya(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}),V({},h,r,o)},u.fromConfig=function(r,o,h){h===void 0&&(h={});var b=o.cell,T=ca(b,h);return new r(Object.assign(o,{cell:T}))},u.className="RNN",u}(qr);i.serialization.registerClass(Ii);var is=function(s){M(u,s);function u(){return s!==null&&s.apply(this,arguments)||this}return u}(qr),Ss=function(s){M(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,ar(o.units,"units"),o.activation=_a(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=fn(r.kernelConstraint),o.recurrentConstraint=fn(r.recurrentConstraint),o.biasConstraint=fn(r.biasConstraint),o.dropout=fi([1,ja([0,r.dropout==null?0:r.dropout])]),o.recurrentDropout=fi([1,ja([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],O=2;O1)throw new w("Can not merge tensors with different batch sizes. "+("Got tensors with shapes: "+JSON.stringify(r)+"."));for(var O=r[0]==null?null:r[0].slice(1),q=1;q1){var sr=ln(1,Ne).concat([0]);b.push(i.transpose(le,sr)),je=!0}else b.push(le)}var Yt=h.mergeFunction(b),$t=Yt.rank;if(je){if($t==null){var vr=Yt.shape,hr=vr.length,ct=vr[hr-1],dt=[ct].concat(vr.slice(0,vr.length-1));Yt=i.transpose(Yt.reshape([-1,ct]),[1,0]).reshape(dt)}else if($t>1){var sr=[$t-1].concat(ln(0,$t-1));Yt=i.transpose(Yt,sr)}}return Yt}}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 qi(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,O=o.slice(1);T3||u.shape.length>3)throw new xe("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 xe("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 O=[],q=0;qo){T=h-o;for(var O=[],q=0;q0){var Be=void 0;o>h?Be=o+h-3:Be=o-1;for(var je=[],q=Be;q3||h.length>3)throw new xe("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,O){return po(T,r[O].shape.length)}):b=[po(this.axes,o.shape.length),po(this.axes,h.shape.length)],this.normalize&&(o=Qa(o,b[0]),h=Qa(h,b[1])),Sc(o,h,b)},u.prototype.interpretAxes=function(r,o){var h;return Array.isArray(this.axes)?h=this.axes:h=[po(this.axes,r.length),po(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 xe("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(hu);var Ic=function(s){M(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=cr(r),T=function(){return Oi(b.shape,0,h.stddev).add(b)},O=Ye(T,function(){return b},o.training||!1);return O})},u.className="GaussianNoise",u}(qr);i.serialization.registerClass(Ic);var Ou=function(s){M(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=cr(r);if(h.rate>0&&h.rate<1){var T=function(){var O=Math.sqrt(h.rate/(1-h.rate));return b.mul(Oi(b.shape,1,O))};return Ye(T,function(){return b},o.training||!1)}return b})},u.className="GaussianDropout",u}(qr);i.serialization.registerClass(Ou);var Hs=function(s){M(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||cr(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 O=cr(r),q=1.6732632423543772,Z=1.0507009873554805,le=-q*Z,Ne=i.greaterEqual(i.randomUniform(b),h.rate);Ne=ai(Ne,"float32");var Be=Math.pow((1-h.rate)*(1+h.rate*Math.pow(le,2)),-.5),je=-Be*le*h.rate,qe=O.mul(Ne).add(Ne.add(-1).mul(le));return qe.mul(Be).add(je)};return Ye(T,function(){return cr(r)},o.training||!1)}return r})},u.className="AlphaDropout",u}(qr);i.serialization.registerClass(Hs);function fo(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 xe("batchNormalization is not implemented for array of rank "+s.rank+" yet");return T}function Mu(s,u,r,o,h){return h===void 0&&(h=.001),i.tidy(function(){var b=i.moments(s,o),T=b.mean,O=b.variance,q=fo(s,T,O,r,u,h);return[q,T,O]})}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,O=b.variance,q=[],Z=0,le=ln(0,s.rank);Z=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 Rn({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=cr(r),O=T.shape,q=O.length,Z=ln(0,q),le=h.axis>=0?h.axis:h.axis+q;Z.splice(le,1);var Ne=st(1,q);Ne[le]=O[le];var Be=Z.slice();Be.sort();var je=!i.util.arraysEqual(Be,ln(0,q).slice(0,q-1)),qe=function(){if(je){var Yt=h.movingMean.read().reshape(Ne),$t=h.movingVariance.read().reshape(Ne),vr=h.center?h.beta.read().reshape(Ne):null,hr=h.scale?h.gamma.read().reshape(Ne):null;return fo(T,Yt,$t,vr,hr,h.epsilon)}else return fo(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 vt=zu(T,h.gamma.read(),h.beta.read(),Z,h.epsilon),pt=vt[0],ct=vt[1],dt=vt[2],Ft=function(Yt,$t,vr){i.tidy(function(){var hr=1-vr,Ir=Yt.read(),zr=Ir.sub($t).mul(hr);Yt.write(Ir.sub(zr))})},sr=function(){Ft(h.movingMean,ct,h.momentum),Ft(h.movingVariance,dt,h.momentum)};return sr(),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:cn(this.betaConstraint),gammaConstraint:cn(this.gammaConstraint)},o=s.prototype.getConfig.call(this);return Object.assign(r,o),r},u.className="BatchNormalization",u}(qr);i.serialization.registerClass(Lu);var pu=function(s){M(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: "+O)}if(this.axis.length!==jt(this.axis).length)throw new Error("Found duplicate axes in: "+this.axis);var q=this.axis.map(function(le){return r[le]}),Z=!0;this.scale?this.gamma=this.addWeight("gamma",q,"float32",this.gammaInitializer,this.gammaRegularizer,Z):this.gamma=null,this.center?this.beta=this.addWeight("beta",q,"float32",this.betaInitializer,this.betaRegularizer,Z):this.beta=null,this.built=!0},u.prototype.call=function(r,o){var h=this,b=cr(r),T=b.shape,O=T.length;return i.tidy(function(){for(var q=!0,Z=i.moments(b,h.axis,q),le=Z.mean,Ne=Z.variance,Be=st(1,O),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(cr(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(du);function fu(s,u,r,o,h,b){return i.tidy(function(){on(h),Ia(b),xn(o),r==null&&(r=[1,1]),o==null&&(o="valid"),h==null&&(h=he()),b==null&&(b="max"),s=bo(s,h);var T,O=o==="same"?"same":"valid";return b==="max"?T=i.maxPool(s,u,r,O):T=i.avgPool(s,u,r,O),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),Ia(b),xn(o),r==null&&(r=[1,1,1]),o==null&&(o="valid"),h==null&&(h=he()),b==null&&(b="max"),s=uo(s,h);var T,O=o==="same"?"same":"valid";return b==="max"?T=i.maxPool3d(s,u,r,O):T=i.avgPool3d(s,u,r,O),h==="channelsFirst"&&(T=i.transpose(T,[0,4,1,2,3])),T})}var Cc=function(s){M(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(ar(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 ar(o.strides,"strides"),o.padding=r.padding==null?"valid":r.padding,xn(o.padding),o.inputSpec=[new Rn({ndim:3})],o}return u.prototype.computeOutputShape=function(r){r=$r(r);var o=Si(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(cr(r),2);var b=h.poolingFunction(cr(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){M(u,s);function u(r){return s.call(this,r)||this}return u.prototype.poolingFunction=function(r,o,h,b,T){return on(T),xn(b),fu(r,o,h,b,T,"max")},u.className="MaxPooling1D",u}(Cc);i.serialization.registerClass(Tc);var Ec=function(s){M(u,s);function u(r){return s.call(this,r)||this}return u.prototype.poolingFunction=function(r,o,h,b,T){return on(T),xn(b),fu(r,o,h,b,T,"avg")},u.className="AveragePooling1D",u}(Cc);i.serialization.registerClass(Ec);var Ke=function(s){M(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 ar(o.poolSize,"poolSize"),ar(o.strides,"strides"),o.padding=r.padding==null?"valid":r.padding,o.dataFormat=r.dataFormat==null?"channelsLast":r.dataFormat,on(o.dataFormat),xn(o.padding),o.inputSpec=[new Rn({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=Si(o,this.poolSize[0],this.padding,this.strides[0]),h=Si(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(cr(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){M(u,s);function u(r){return s.call(this,r)||this}return u.prototype.poolingFunction=function(r,o,h,b,T){return on(T),xn(b),fu(r,o,h,b,T,"max")},u.className="MaxPooling2D",u}(Ke);i.serialization.registerClass(Rc);var sn=function(s){M(u,s);function u(r){return s.call(this,r)||this}return u.prototype.poolingFunction=function(r,o,h,b,T){return on(T),xn(b),fu(r,o,h,b,T,"avg")},u.className="AveragePooling2D",u}(Ke);i.serialization.registerClass(sn);var Ac=function(s){M(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 ar(o.poolSize,"poolSize"),ar(o.strides,"strides"),o.padding=r.padding==null?"valid":r.padding,o.dataFormat=r.dataFormat==null?"channelsLast":r.dataFormat,on(o.dataFormat),xn(o.padding),o.inputSpec=[new Rn({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=Si(o,this.poolSize[0],this.padding,this.strides[0]),h=Si(h,this.poolSize[1],this.padding,this.strides[1]),b=Si(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(cr(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),Is=function(s){M(u,s);function u(r){return s.call(this,r)||this}return u.prototype.poolingFunction=function(r,o,h,b,T){return on(T),xn(b),Nc(r,o,h,b,T,"max")},u.className="MaxPooling3D",u}(Ac);i.serialization.registerClass(Is);var Fc=function(s){M(u,s);function u(r){return s.call(this,r)||this}return u.prototype.poolingFunction=function(r,o,h,b,T){return on(T),xn(b),Nc(r,o,h,b,T,"avg")},u.className="AveragePooling3D",u}(Ac);i.serialization.registerClass(Fc);var $n=function(s){M(u,s);function u(r){var o=s.call(this,r)||this;return o.inputSpec=[new Rn({ndim:3})],o}return u.prototype.computeOutputShape=function(r){return[r[0],r[2]]},u.prototype.call=function(r,o){throw new xe},u}(qr),Dc=function(s){M(u,s);function u(r){return s.call(this,r||{})||this}return u.prototype.call=function(r,o){return i.tidy(function(){var h=cr(r);return i.mean(h,1)})},u.className="GlobalAveragePooling1D",u}($n);i.serialization.registerClass(Dc);var Oc=function(s){M(u,s);function u(r){return s.call(this,r||{})||this}return u.prototype.call=function(r,o){return i.tidy(function(){var h=cr(r);return i.max(h,1)})},u.className="GlobalMaxPooling1D",u}($n);i.serialization.registerClass(Oc);var Mc=function(s){M(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 Rn({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 xe},u.prototype.getConfig=function(){var r={dataFormat:this.dataFormat},o=s.prototype.getConfig.call(this);return Object.assign(r,o),r},u}(qr),Gs=function(s){M(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=cr(r);return h.dataFormat==="channelsLast"?i.mean(b,[1,2]):i.mean(b,[2,3])})},u.className="GlobalAveragePooling2D",u}(Mc);i.serialization.registerClass(Gs);var ss=function(s){M(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=cr(r);return h.dataFormat==="channelsLast"?i.max(b,[1,2]):i.max(b,[2,3])})},u.className="GlobalMaxPooling2D",u}(Mc);i.serialization.registerClass(ss);var zc=function(s){M(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=ca(b,h);delete o.layer;var O={layer:T};return Object.assign(O,o),new r(O)},u}(qr),Lc=function(s){M(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=cr(r);var b=function(q,Z){var le=cr(h.layer.call(q,o));return[le,[]]},T=yc(b,r,[],!1,null,null,!1,!0),O=T[1];return O})},u.className="TimeDistributed",u}(zc);i.serialization.registerClass(Lc);function mu(s){Pr(hi,"BidirectionalMergeMode",s)}var Pc="concat",Pu=function(s){M(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=ca(b),h.goBackwards=!(h.goBackwards===!0);var T={};if(T.className=r.layer.getClassName(),T.config=h,o.backwardLayer=ca(T),o.forwardLayer.name="forward_"+o.forwardLayer.name,o.backwardLayer.name="backward_"+o.backwardLayer.name,o.mergeMode=r.mergeMode===void 0?Pc:r.mergeMode,mu(o.mergeMode),r.weights)throw new xe("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()):It(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 O=[],q=[];if(h!=null){var Z=h.length;if(Z%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,O.push.apply(O,h);var le=h.map(function(Ft){return new Rn({shape:Ft.shape})});this.forwardLayer.stateSpec=le.slice(0,Z/2),this.backwardLayer.stateSpec=le.slice(Z/2),q.push.apply(q,le)}if(b!=null)throw new xe("Support for constants in Bidirectional layers is not implemented yet.");for(var Ne=O[0]instanceof Ca,Be=0,je=O;Beu}var Ee=function(s){M(u,s);function u(r){var o=s.call(this)||this;if(r==null&&(r={}),r.restoreBestWeights)throw new xe("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=Fe:o.monitorFunc=Ce,o.monitorFunc===Ce&&(o.minDelta*=-1),o}return u.prototype.onTrainBegin=function(r){return de(this,void 0,void 0,function(){return X(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 de(this,void 0,void 0,function(){var h;return X(this,function(b){switch(b.label){case 0:return[4,si(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 de(this,void 0,void 0,function(){return X(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}(ke);function Ge(s){return new Ee(s)}var Qe={earlyStopping:Ge};N.Callback=ke,N.CallbackList=io,N.CustomCallback=Co,N.EarlyStopping=Ee,N.History=No,N.InputSpec=Rn,N.LayerVariable=Ka,N.LayersModel=wt,N.RNN=Ii,N.Sequential=Ie,N.SymbolicTensor=Ca,N.callbacks=Qe,N.constraints=Yn,N.initializers=xr,N.input=pr,N.layers=$c,N.loadLayersModel=Tr,N.metrics=I,N.model=br,N.models=R,N.registerCallbackConstructor=Fr,N.regularizers=Q,N.sequential=Nr,N.version_layers=xs}),ig=Or(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});var i=ml(),we=Object.assign||function(S){for(var x,k=1,K=arguments.length;k0&&be[be.length-1])&&(ft[0]===6||ft[0]===2)){k=0;continue}if(ft[0]===3&&(!be||ft[1]>be[0]&&ft[1]0)&&!(Se=K.next()).done;)be.push(Se.value)}catch(Pe){Je={error:Pe}}finally{try{Se&&!Se.done&&(k=K.return)&&k.call(K)}finally{if(Je)throw Je.error}}return be}function de(){for(var S=[],x=0;x0?Object.keys(Wt).forEach(function(Zt){var xr=oe(W(Zt),1),kn=xr[0],pn=gt[kn];pn&&(pn.signatureKey=Wt[Zt],ft.push(pn))}):ft=be;var wr={};x.library!=null&&x.library.function!=null&&(wr=x.library.function.reduce(function(Zt,xr){return Zt[xr.signature.name]=K.mapFunction(xr),Zt},{}));var Ar={nodes:gt,inputs:ft,outputs:Lt,weights:Je,placeholders:be,signature:k,functions:wr};return Pe.length>0&&(Ar.initNodes=Pe),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=ye(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,be){return Se[be.name]={type:be.type,inputIndexStart:be.start,inputIndexEnd:be.end},Se},{})),k.attrs!=null&&(K.attrParams=k.attrs.reduce(function(Se,be){var Je=be.type,Pe=void 0;switch(be.type){case"string":Pe=on(x.attr,be.tfName,be.defaultValue),Pe===void 0&&!!be.tfDeprecatedName&&(Pe=on(x.attr,be.tfDeprecatedName,be.defaultValue));break;case"string[]":Pe=ni(x.attr,be.tfName,be.defaultValue),Pe===void 0&&!!be.tfDeprecatedName&&(Pe=ni(x.attr,be.tfDeprecatedName,be.defaultValue));break;case"number":Pe=Ia(x.attr,be.tfName,be.defaultValue||0),Pe===void 0&&!!be.tfDeprecatedName&&(Pe=Ia(x.attr,be.tfDeprecatedName,be.defaultValue));break;case"number[]":Pe=jn(x.attr,be.tfName,be.defaultValue),Pe===void 0&&!!be.tfDeprecatedName&&(Pe=jn(x.attr,be.tfDeprecatedName,be.defaultValue));break;case"bool":Pe=xn(x.attr,be.tfName,be.defaultValue),Pe===void 0&&!!be.tfDeprecatedName&&(Pe=xn(x.attr,be.tfDeprecatedName,be.defaultValue));break;case"bool[]":Pe=ma(x.attr,be.tfName,be.defaultValue),Pe===void 0&&!!be.tfDeprecatedName&&(Pe=ma(x.attr,be.tfDeprecatedName,be.defaultValue));break;case"shape":Pe=Ri(x.attr,be.tfName,be.defaultValue),Pe===void 0&&!!be.tfDeprecatedName&&(Pe=Ri(x.attr,be.tfDeprecatedName,be.defaultValue));break;case"shape[]":Pe=pi(x.attr,be.tfName,be.defaultValue),Pe===void 0&&!!be.tfDeprecatedName&&(Pe=pi(x.attr,be.tfDeprecatedName,be.defaultValue));break;case"dtype":Pe=na(x.attr,be.tfName,be.defaultValue),Pe===void 0&&!!be.tfDeprecatedName&&(Pe=na(x.attr,be.tfDeprecatedName,be.defaultValue));break;case"dtype[]":Pe=Ei(x.attr,be.tfName,be.defaultValue),Pe===void 0&&!!be.tfDeprecatedName&&(Pe=Ei(x.attr,be.tfDeprecatedName,be.defaultValue));break;case"func":Pe=Pa(x.attr,be.tfName,be.defaultValue),Pe===void 0&&!!be.tfDeprecatedName&&(Pe=Pa(x.attr,be.tfDeprecatedName,be.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error("Unsupported param type: "+be.type+" for op: "+x.op)}return Se[be.name]={value:Pe,type:Je},Se},{})),K},S.prototype.mapFunction=function(x){var k=this,K=x.nodeDef,Se=[],be=[],Je={};K!=null&&(Je=K.reduce(function(Gt,Jt){return Gt[Jt.name]=k.mapNode(Jt),Jt.op==="Const"&&be.push(Gt[Jt.name]),Gt},{}));var Pe=[],gt=[];x.signature.inputArg.forEach(function(Gt){var Jt=oe(W(Gt.name),1),wr=Jt[0],Ar={name:wr,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:Rr(Gt.type),type:"dtype"}},children:[]};Ar.signatureKey=Gt.name,Pe.push(Ar),Je[wr]=Ar});var ft=Object.keys(Je);ft.forEach(function(Gt){var Jt=Je[Gt];Jt.inputNames.forEach(function(wr){var Ar=oe(W(wr),1),Zt=Ar[0];Jt.inputs.push(Je[Zt]),Je[Zt].children.push(Jt)})});var Lt=x.ret;x.signature.outputArg.forEach(function(Gt){var Jt=oe(W(Lt[Gt.name]),2),wr=Jt[0],Ar=Jt[1],Zt=Je[wr];Zt!=null&&(Zt.defaultOutput=Ar,gt.push(Zt))});var Wt=this.mapArgsToSignature(x);return{nodes:Je,inputs:Pe,outputs:gt,weights:be,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 hi(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 La(S,x){var k=Array.isArray(S)?String.fromCharCode.apply(null,S):hi(S);return x?k:k.toLowerCase()}function on(S,x,k,K){K===void 0&&(K=!1);var Se=S[x];return Se!=null?La(Se.s,K):k}function xn(S,x,k){var K=S[x];return K?K.b:k}function Ia(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=X[S]);switch(S){case X.DT_FLOAT:return"float32";case X.DT_INT32:case X.DT_INT64:case X.DT_INT8:case X.DT_UINT8:return"int32";case X.DT_BOOL:return"bool";case X.DT_DOUBLE:return"float32";case X.DT_STRING:return"string";default:return null}}function Pa(S,x,k){var K=S[x];return K&&K.func?K.func.name:k}function na(S,x,k){var K=S[x];return K&&K.type?Rr(K.type):k}function Ei(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 Gi(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 Ri(S,x,k){var K=S[x];return K&&K.shape?Gi(K.shape):k}function jn(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 ni(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(be){return La(be,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 Gi(Se)}):k}function ma(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(be){return Se.getInput(be)}),x.rawAttrs!=null&&(this.attrs=Object.keys(x.rawAttrs).reduce(function(be,Je){return be[Je]=Se.getAttr(Je),be},{}))}return S.prototype.getInput=function(x){return xe(x,this.tensorMap,this.context)},S.prototype.getAttr=function(x,k){var K=this.node.rawAttrs[x];if(K.tensor!=null)return xe(x,this.tensorMap,this.context);if(K.i!=null||K.f!=null)return Ia(this.node.rawAttrs,x,k);if(K.s!=null)return on(this.node.rawAttrs,x,k);if(K.b!=null)return xn(this.node.rawAttrs,x,k);if(K.shape!=null)return Ri(this.node.rawAttrs,x,k);if(K.type!=null)return na(this.node.rawAttrs,x,k);if(K.list!=null){if(K.list.i!=null||K.list.f!=null)return jn(this.node.rawAttrs,x,k);if(K.list.s!=null)return ni(this.node.rawAttrs,x,k);if(K.list.shape!=null)return pi(this.node.rawAttrs,x,k);if(K.list.b!=null)return ma(this.node.rawAttrs,x,k);if(K.list.type!=null)return Ei(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")}},ja=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(xe(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(ai(S,x),function(){return k+(" Shapes "+S+" and "+x+" must match")})}function ai(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,be){return K.write(Se,k[be])})},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,be=x.map(function(Lt){return Se+=Lt,Se});if(Se!==k.shape[0])throw new Error(`Expected sum of lengths to be equal to +// dist/human.esm.js +var af = Object.defineProperty; +var hL = (n) => af(n, "__esModule", {value: true}); +var we = (n, t) => () => (t || (t = {exports: {}}, n(t.exports, t)), t.exports); +var Is = (n, t) => { + hL(n); + for (var e in t) + af(n, e, {get: t[e], enumerable: true}); +}; +var sf = we(() => { +}); +var of = we(() => { +}); +var As = we(() => { +}); +var Qr = we((A) => { + "use strict"; + Object.defineProperty(A, "__esModule", {value: true}); + var gc = function(n, t) { + return gc = 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]); + }, gc(n, t); + }; + function qn(n, t) { + gc(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 dL = 1e-7, pL = 1e-4, fL = 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; + }(), cf = 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 ? dL : pL; + }, 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 lf(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 mL(n) { + return n % 2 === 0 ? n : n + 1; + } + function gL(n) { + for (var t = 0, e = 0; e < n.length; e++) + t += n[e]; + return t; + } + function yL(n, t) { + var e = Math.random(); + return t * e + (1 - e) * n; + } + function vL(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 Ur(n) { + E(n != null, function() { + return "The input to the tensor constructor must be a non-null value."; + }); + } + function Br(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) + Br(n[r], t, e); + else + t.push(n); + return t; + } + function pt(n) { + if (n.length === 0) + return 1; + for (var t = n[0], e = 1; e < n.length; e++) + t *= n[e]; + return t; + } + function wL(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 bL(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 xL(n) { + var t = Math.ceil(Math.sqrt(n)); + return [t, Math.ceil(n / t)]; + } + function LL(n) { + for (var t = new Uint32Array(n), e = 0; e < n; ++e) + t[e] = e; + return lf(t), t; + } + function ya(n, t) { + return t <= n.length ? n : n + " ".repeat(t - n.length); + } + function SL(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 uf(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 hf(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 Ts(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 df(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 pf(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 ff(n) { + return n === "bool" || n === "complex64" || n === "float32" || n === "int32" || n === "string"; + } + function mf(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 gf(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 yf(n) { + if (n == null) + return 0; + var t = 0; + return n.forEach(function(e) { + return t += e.length; + }), t; + } + function or(n) { + return typeof n == "string" || n instanceof String; + } + function vf(n) { + return typeof n == "boolean"; + } + function wf(n) { + return typeof n == "number"; + } + function Ns(n) { + return Array.isArray(n) ? Ns(n[0]) : n instanceof Float32Array ? "float32" : n instanceof Int32Array || n instanceof Uint8Array ? "int32" : wf(n) ? "float32" : or(n) ? "string" : vf(n) ? "bool" : "float32"; + } + function cr(n) { + return !!(n && n.constructor && n.call && n.apply); + } + function _s(n, t) { + for (var e = t; e < n; ++e) + if (n % e === 0) + return e; + return n; + } + function bi(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 bf(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] = bf(n + a * o, s, e); + return r; + } + function xi(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 bf(0, n, t); + } + function yc(n, t) { + for (var e = Li(n, t), r = 0; r < e.length; r++) + e[r] = 1; + return e; + } + function Li(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 IL(n, t) { + var e = n.reduce(function(r, i) { + return r * i; + }, 1); + if (t == null || t === "float32") + return xi(n, new Float32Array(e)); + if (t === "int32") + return xi(n, new Int32Array(e)); + if (t === "bool") + return xi(n, new Uint8Array(e)); + throw new Error("Unknown data type " + t); + } + function vc(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 AL(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 TL(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 wc(n) { + return n && n.then && typeof n.then == "function"; + } + var xf = "tfjsflags", Lf = 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 (wc(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 = NL(this.global.location.search); + if (xf in e) { + var r = e[xf].split(","); + r.forEach(function(i) { + var a = i.split(":"), s = a[0], o = a[1]; + t.urlFlags[s] = _L(s, o); + }); + } + }, n; + }(); + function NL(n) { + var t = {}; + return n.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g, function(e) { + for (var r = [], i = 1; i < arguments.length; i++) + r[i - 1] = arguments[i]; + return CL(t, r[0], r[1]), r.join("="); + }), t; + } + function CL(n, t, e) { + n[decodeURIComponent(t)] = decodeURIComponent(e || ""); + } + function _L(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 Ge() { + return A.ENV; + } + A.ENV = null; + function RL(n) { + A.ENV = n; + } + var bc; + function Sf() { + if (bc == 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"); + bc = n; + } + return bc; + } + function OL() { + var n = Sf(); + return n._tfGlobals == null && (n._tfGlobals = new Map()), n._tfGlobals; + } + function If(n, t) { + var e = OL(); + if (e.has(n)) + return e.get(n); + var r = t(); + return e.set(n, r), e.get(n); + } + var xc = "Abs", Lc = "Acos", Sc = "Acosh", Cs = "Add", Ic = "AddN", Af = "All", Tf = "Any", Ac = "ArgMax", Tc = "ArgMin", Nc = "Asin", _c = "Asinh", Cc = "Atan", Rc = "Atanh", Oc = "Atan2", Ec = "AvgPool", Nf = "AvgPoolBackprop", Dc = "AvgPool3D", _f = "AvgPool3DBackprop", kc = "BatchMatMul", Fc = "BatchToSpaceND", Wc = "BroadcastTo", Rs = "Cast", Uc = "Ceil", Bc = "ClipByValue", Cf = "Complex", zc = "Concat", Pc = "Conv2D", Rf = "Conv2DBackpropFilter", Mc = "Conv2DBackpropInput", Hc = "Conv3D", Of = "Conv3DBackpropFilterV2", Ef = "Conv3DBackpropInputV2", Vc = "Cos", Gc = "Cosh", qc = "Cumsum", Df = "CropAndResize", kf = "DepthToSpace", Yc = "DepthwiseConv2dNative", Ff = "DepthwiseConv2dNativeBackpropFilter", Wf = "DepthwiseConv2dNativeBackpropInput", Uf = "Diag", Kc = "Dilation2D", Bf = "Dilation2DBackpropInput", zf = "Dilation2DBackpropFilter", jc = "Div", $c = "Elu", Pf = "EluGrad", Xc = "Erf", Mf = "Equal", Jc = "Exp", Zc = "Expm1", Hf = "FFT", Vf = "Fill", Gf = "FlipLeftRight", Qc = "Floor", el = "FloorDiv", tl = "FusedBatchNorm", nl = "GatherV2", qf = "GatherNd", Yf = "Greater", rl = "GreaterEqual", il = "Identity", Kf = "IFFT", jf = "Imag", al = "IsFinite", sl = "IsInf", ol = "IsNan", $f = "Less", Xf = "LessEqual", Jf = "LinSpace", cl = "Log", ll = "Log1p", Zf = "LogicalAnd", Qf = "LogicalNot", em = "LogicalOr", ul = "LogSoftmax", hl = "LRN", tm = "LRNBackprop", dl = "Max", pl = "Maximum", fl = "MaxPool", nm = "MaxPoolBackprop", ml = "MaxPool3D", rm = "MaxPool3DBackprop", im = "MaxPoolWithArgmax", am = "Mean", gl = "Min", yl = "Minimum", vl = "MirrorPad", wl = "Mod", bl = "Multiply", xl = "Negate", sm = "NotEqual", om = "NonMaxSuppressionV3", cm = "NonMaxSuppressionV4", lm = "NonMaxSuppressionV5", Ll = "OnesLike", Sl = "OneHot", Il = "PadV2", EL = "Pool", Al = "Pow", Tl = "Prelu", um = "Prod", hm = "Range", dm = "Real", Nl = "Reciprocal", _l = "Relu", Cl = "Reshape", Rl = "ResizeNearestNeighbor", pm = "ResizeNearestNeighborGrad", Ol = "ResizeBilinear", fm = "ResizeBilinearGrad", El = "Relu6", Dl = "Reverse", kl = "Round", Fl = "Rsqrt", mm = "ScatterNd", Wl = "SelectV2", Ul = "Selu", Bl = "Slice", zl = "Sin", Pl = "Sinh", Ml = "Sign", Hl = "Sigmoid", Vl = "Softplus", Gl = "Sqrt", ql = "Sum", Yl = "SpaceToBatchND", Kl = "SplitV", jl = "Softmax", $l = "SquaredDifference", gm = "Square", Xl = "Sub", ym = "SparseToDense", vm = "StridedSlice", Jl = "Tan", Zl = "Tanh", Ql = "Tile", wm = "TopK", eu = "Transpose", bm = "Unique", tu = "Unpack", nu = "UnsortedSegmentSum", ru = "ZerosLike", iu = "Step", au = "FromPixels", xm = "RotateWithOffset", su = "_FusedMatMul", ou = "FusedConv2D", cu = "FusedDepthwiseConv2D"; + var Si = If("kernelRegistry", function() { + return new Map(); + }), va = If("gradRegistry", function() { + return new Map(); + }); + function uu(n, t) { + var e = lu(n, t); + return Si.get(e); + } + function hu(n) { + return va.get(n); + } + function Os(n) { + for (var t = Si.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 Lm(n) { + var t = n.kernelName, e = n.backendName, r = lu(t, e); + Si.has(r) && console.warn("The kernel '" + t + "' for backend " + ("'" + e + "' is already registered")), Si.set(r, n); + } + function Sm(n) { + var t = n.kernelName; + va.has(t) && (Ge().getBool("DEBUG") && console.warn("Overriding the gradient for '" + t + "'")), va.set(t, n); + } + function DL(n, t) { + var e = lu(n, t); + if (!Si.has(e)) + throw new Error("The kernel '" + n + "' for backend " + ("'" + t + "' is not registered")); + Si.delete(e); + } + function kL(n) { + if (!va.has(n)) + throw new Error("The gradient '" + n + "' for backend is not registered"); + va.delete(n); + } + function FL(n, t) { + var e = Os(n); + e.forEach(function(r) { + var i = Object.assign({}, r, {backendName: t}); + Lm(i); + }); + } + function lu(n, t) { + return t + "_" + n; + } + function WL(n, t) { + return t === "string" ? du(n) : Es([n], t); + } + function UL(n, t) { + return n instanceof Float32Array && t === "float32" || n instanceof Int32Array && t === "int32" || n instanceof Uint8Array && t === "bool"; + } + function Es(n, t) { + if (t === "string") + throw new Error("Cannot convert a string[] to a TypedArray"); + if (Array.isArray(n) && (n = Br(n)), Ge().getBool("DEBUG") && pf(n, t), UL(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 pu() { + return Ge().platform.now(); + } + function BL(n, t) { + return Ge().platform.fetch(n, t); + } + function du(n, t) { + return t === void 0 && (t = "utf-8"), t = t || "utf-8", Ge().platform.encode(n, t); + } + function fu(n, t) { + return t === void 0 && (t = "utf-8"), t = t || "utf-8", Ge().platform.decode(n, t); + } + var zL = {__proto__: null, createScalarValue: WL, toTypedArray: Es, now: pu, fetch: BL, encodeString: du, decodeString: fu, shuffle: lf, clamp: ga, nearestLargerEven: mL, sum: gL, randUniform: yL, distSquared: vL, assert: E, assertShapesMatch: Pe, assertNonNull: Ur, flatten: Br, sizeFromShape: pt, isScalarShape: wL, arraysEqual: pn, isInt: ot, tanh: bL, sizeToSquarishShape: xL, createShuffledIndices: LL, rightPad: ya, repeatedTry: SL, inferFromImplicitShape: uf, parseAxisParam: rt, squeezeShape: hf, getTypedArrayFromDType: Ts, getArrayFromDType: df, checkConversionForErrors: pf, isValidDtype: ff, hasEncodingLoss: mf, isTypedArray: Ft, bytesPerElement: gf, bytesFromStringArray: yf, isString: or, isBoolean: vf, isNumber: wf, inferDtype: Ns, isFunction: cr, nearestDivisor: _s, computeStrides: bi, toNestedArray: xi, makeOnesTypedArray: yc, makeZerosTypedArray: Li, makeZerosNestedTypedArray: IL, assertNonNegativeIntegerDimensions: vc, locToIndex: AL, indexToLoc: TL, isPromise: wc}; + var HL = function() { + function n(t, e) { + this.backendTimer = t, this.logger = e, e == null && (this.logger = new ML()); + } + 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) { + PL(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 PL(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 ML = 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 VL(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 GL(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 Im = 20, wa = 3, mu = 7; + function YL(n, t, e, r) { + var i = bi(t), a = qL(n, t, e, i), s = t.length, o = Ds(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 qL(n, t, e, r) { + var i = pt(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(mu)) + " + " + (parseFloat(n[1].toFixed(mu)) + "j") : or(n) ? r = "'" + n + "'" : e === "bool" ? r = Am(n) : r = parseFloat(n.toFixed(mu)).toString(), ya(r, t); + } + function Am(n) { + return n === 0 ? "false" : "true"; + } + function Ds(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" ? [Am(n[0])] : [n[0].toString()]; + } + if (c === 1) { + if (o > Im) { + 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 > Im) { + for (var w = 0; w < wa; w++) { + var b = w * g, L = b + g; + y.push.apply(y, Ds(n.slice(b, L), f, e, m, i, false)); + } + y.push("..."); + for (var w = o - wa; w < o; w++) { + var b = w * g, L = b + g; + y.push.apply(y, Ds(n.slice(b, L), f, e, m, i, w === o - 1)); + } + } else + for (var w = 0; w < o; w++) { + var b = w * g, L = b + g; + y.push.apply(y, Ds(n.slice(b, L), f, e, m, i, w === o - 1)); + } + var x = c === 2 ? "," : ""; + y[0] = "[" + y[0] + x; + for (var w = 1; w < y.length - 1; w++) + y[w] = " " + y[w] + x; + 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 ks = function() { + function n(t, e, r) { + var i = this; + if (this.dtype = e, this.shape = t.slice(), this.size = pt(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 || df(e, this.size), this.strides = bi(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 Cn().makeTensor(this.values, this.shape, this.dtype); + }, n; + }(), Cn = null, Ii = null; + function KL(n) { + Cn = n; + } + function jL(n) { + Ii = 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 = pt(t), this.strides = bi(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, Ii.buffer(this.shape, this.dtype, t)]; + } + }); + }); + }, n.prototype.bufferSync = function() { + return Ii.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, xi(this.shape, t)]; + } + }); + }); + }, n.prototype.arraySync = function() { + return xi(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 = Cn().read(this.dataId), this.dtype === "string" ? [4, t] : [3, 2]; + case 1: + e = r.sent(); + try { + return [2, e.map(function(i) { + return fu(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 = Cn().readSync(this.dataId); + if (this.dtype === "string") + try { + return t.map(function(e) { + return fu(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, Cn().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; + Cn().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), Ii.print(this, t); + }, n.prototype.clone = function() { + return this.throwIfDisposed(), Ii.clone(this); + }, n.prototype.toString = function(t) { + t === void 0 && (t = false); + var e = this.dataSync(); + return YL(e, this.shape, this.dtype, t); + }, n.prototype.cast = function(t) { + return this.throwIfDisposed(), Ii.cast(this, t); + }, n.prototype.variable = function(t, e, r) { + return t === void 0 && (t = true), this.throwIfDisposed(), Cn().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) { + qn(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")); + Cn().disposeTensor(this), this.dataId = e.dataId, Cn().incRef(this, null); + }, t.prototype.dispose = function() { + Cn().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 gu; + (function(n) { + n.float32 = "float32", n.int32 = "int32", n.bool = "int32", n.complex64 = "complex64"; + })(gu || (gu = {})); + var yu; + (function(n) { + n.float32 = "float32", n.int32 = "int32", n.bool = "bool", n.complex64 = "complex64"; + })(yu || (yu = {})); + var vu; + (function(n) { + n.float32 = "float32", n.int32 = "float32", n.bool = "float32", n.complex64 = "complex64"; + })(vu || (vu = {})); + var wu; + (function(n) { + n.float32 = "complex64", n.int32 = "complex64", n.bool = "complex64", n.complex64 = "complex64"; + })(wu || (wu = {})); + var $L = {float32: vu, int32: gu, bool: yu, complex64: wu}; + function Fs(n, t) { + if (n === "string" || t === "string") { + if (n === "string" && t === "string") + return "string"; + throw new Error("Can not upcast " + n + " with " + t); + } + return $L[n][t]; + } + function XL(n) { + return Fs(n, "int32"); + } + function ct(n, t) { + if (n.dtype === t.dtype) + return [n, t]; + var e = Fs(n.dtype, t.dtype); + return [n.cast(e), t.cast(e)]; + } + function Tm(n, t) { + E(n.dtype === t.dtype, function() { + return "The dtypes of the first(" + n.dtype + ") and" + (" second(" + t.dtype + ") input must match"); + }); + } + function JL(n, t) { + return t.some(function(e) { + return e.id === n.id; + }); + } + function bu(n) { + var t = [], e = new Set(); + return Nm(n, t, e), t; + } + function Nm(n, t, e) { + if (n == null) + return; + if (n instanceof K) { + t.push(n); + return; + } + if (!ZL(n)) + return; + var r = n; + for (var i in r) { + var a = r[i]; + e.has(a) || (e.add(a), Nm(a, t, e)); + } + } + function ZL(n) { + return Array.isArray(n) || typeof n == "object"; + } + var QL = {__proto__: null, makeTypesMatch: ct, assertTypesMatch: Tm, isTensorInList: JL, getTensorsInContainer: bu}; + var _m = 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; + }(), nS = function() { + function n(t) { + this.ENV = t, this.registry = {}, this.registryFactory = {}, this.pendingBackendInitId = 0, this.state = new _m(); + } + 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 HL(this.backendInstance), [2, true]; + } + }); + }); + }, n.prototype.setupRegisteredKernels = function() { + var t = this, e = Os(this.backendName); + e.forEach(function(r) { + r.setupFunc != null && r.setupFunc(t.backendInstance); + }); + }, n.prototype.disposeRegisteredKernels = function(t) { + var e = this, r = Os(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 cf) && 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, Rs, 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 = uu(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 L = Array.isArray(g) ? g : [g]; + c.shouldCheckForMemLeaks() && c.checkKernelForMemLeak(i, b, L); + var x = L.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, x); + if (N == null) { + o == null && (o = []); + var I = x.filter(function(C, O) { + return o[O]; + }); + N = (s || []).slice().concat(I); + } + u = c.saveTensorsForBackwardMode(N); + } + return x; + }; + else { + var y = function(b) { + if (!h) + return; + u = b.map(function(L) { + return c.keep(c.clone(L)); + }); + }; + f = function() { + var b = c.backend.numDataIds(); + g = c.tidy(function() { + return t(c.backend, y); + }); + var L = Array.isArray(g) ? g : [g]; + return c.shouldCheckForMemLeaks() && c.checkKernelForMemLeak(i, b, L), L; + }; + } + 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 = hu(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" && or(t[0]) && (a = t.map(function(u) { + return du(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 = yf(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 * gf(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 = hu(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 = Li(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 = bu(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 = VL(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 == null ? eS(s.shape) : r, GL(c, o, function(u) { + return a.tidy(u); + }, tS); + 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(cr(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(cr(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 = pu(), [4, this.backend.time(t)]; + case 1: + return r = i.sent(), r.wallMs = pu() - 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 _m(); + 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 eS(n) { + var t = yc(pt(n), "float32"); + return z.makeTensor(t, n, "float32"); + } + function Cm() { + var n = Sf(); + if (n._tfengine == null) { + var t = new Lf(n); + n._tfengine = new nS(t); + } + return RL(n._tfengine.ENV), KL(function() { + return n._tfengine; + }), n._tfengine; + } + var z = Cm(); + function tS(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, Cs); + } + function rS() { + return typeof navigator != "undefined" && navigator != null; + } + function iS() { + if (rS()) { + 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 Rm() { + return typeof window != "undefined" && window.document != null || typeof WorkerGlobalScope != "undefined"; + } + var aS = {__proto__: null, isMobile: iS, isBrowser: Rm}; + var Yn = Ge(); + Yn.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."); + }); + Yn.registerFlag("IS_BROWSER", function() { + return Rm(); + }); + Yn.registerFlag("IS_NODE", function() { + return typeof process != "undefined" && typeof process.versions != "undefined" && typeof process.versions.node != "undefined"; + }); + Yn.registerFlag("IS_CHROME", function() { + return typeof navigator != "undefined" && navigator != null && navigator.userAgent != null && /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor); + }); + Yn.registerFlag("PROD", function() { + return false; + }); + Yn.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY", function() { + return Yn.getBool("DEBUG"); + }); + Yn.registerFlag("DEPRECATION_WARNINGS_ENABLED", function() { + return true; + }); + Yn.registerFlag("IS_TEST", function() { + return false; + }); + function Rn(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) && Ge().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY") && Om(n, r, []), r; + } + function Om(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) + Om(n[i], r, e.concat(i)); + } + function Em(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 Em(r, n.dtype, t, e), n; + var i = Ns(n); + if (i !== "string" && ["bool", "int32", "float32"].indexOf(r) >= 0 && (i = r), Em(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 = Rn(n, i); + !Ft(n) && !Array.isArray(n) && (n = [n]); + var o = true, c = i !== "string" ? Es(n, i) : Br(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 Dm = "__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 + Dm; + 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 wc(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 sS(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, Cf); + } + var lr = U({complex_: sS}); + function ur(n, t, e, r) { + if (r == null && (r = Ns(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) { + vc(t); + var i = pt(t), a = pt(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 !== pt(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" ? Es(n, r) : Br(n, [], true), z.makeTensor(n, t, r); + } + function hr(n, t, e) { + var r = Rn(n, e); + return ur(n, t, r, e); + } + var xu = {float32: 4, float16: 2, int32: 4, uint16: 2, uint8: 1, bool: 1, complex64: 8}; + var Ws = 4; + function cS(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, L, x, 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) + Ws * g.length, w = new Uint8Array(y), b = 0, L = 0; L < g.length; L++) + x = g[L], N = new Uint8Array(new Uint32Array([x.length]).buffer), w.set(N, b), b += Ws, w.set(x, b), b += x.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: oS(o), specs: e}]; + } + }); + }); + } + function km(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 = pt(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 = xu[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 = lS()), 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 = pt(o.shape); + d = []; + for (var y = 0; y < b; y++) { + var L = new Uint32Array(n.slice(i, i + Ws))[0]; + i += Ws; + var x = new Uint8Array(n.slice(i, i + L)); + d.push(x), i += L; + } + } else { + var N = xu[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 = hr(I, u, "float32"), D = hr(C, u, "float32"); + e[c] = lr(O, D), O.dispose(), D.dispose(); + } else + throw new Error("Unsupported dtype in weight '" + c + "': " + l); + i += h * N; + } + l !== "complex64" && (e[c] = hr(d, u, l)); + } + return e; + } + function oS(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 Lu = typeof Buffer != "undefined" && (typeof Blob == "undefined" || typeof atob == "undefined" || typeof btoa == "undefined"); + function Fm(n) { + return Lu ? Buffer.byteLength(n) : new Blob([n]).size; + } + function uS(n) { + if (Lu) + 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 hS(n) { + if (Lu) { + 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 Su(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 Wm(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 : Fm(JSON.stringify(n.modelTopology)), weightSpecsBytes: n.weightSpecs == null ? 0 : Fm(JSON.stringify(n.weightSpecs)), weightDataBytes: n.weightData == null ? 0 : n.weightData.byteLength}; + } + function dS() { + 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 pS() { + 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 fS() { + for (var n = new Uint32Array(64), t = 0; t < 64; t++) + n[t] = 1024; + return n[0] = n[32] = 0, n; + } + function lS() { + var n = dS(), t = pS(), e = fS(); + 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; + }(), mS = function(n) { + return rn.registerSaveRouter(n); + }, gS = function(n) { + return rn.registerLoadRouter(n); + }, yS = function(n) { + return rn.getSaveHandlers(n); + }, vS = function(n, t) { + return rn.getLoadHandlers(n, t); + }; + var Iu = "tensorflowjs", Au = 1, zr = "models_store", dr = "model_info_store"; + function Um() { + if (!Ge().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 Tu(n) { + var t = n.result; + t.createObjectStore(zr, {keyPath: "modelPath"}), t.createObjectStore(dr, {keyPath: "modelPath"}); + } + var Ai = function() { + function n(t) { + if (this.indexedDB = Um(), 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(Iu, Au); + s.onupgradeneeded = function() { + return Tu(s); + }, s.onsuccess = function() { + var o = s.result; + if (e == null) { + var c = o.transaction(zr, "readonly"), l = c.objectStore(zr), 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(dr, "readwrite"), p = d.objectStore(dr), f = p.put({modelPath: r.modelPath, modelArtifactsInfo: h}), m; + f.onsuccess = function() { + m = o.transaction(zr, "readwrite"); + var g = m.objectStore(zr), y = g.put({modelPath: r.modelPath, modelArtifacts: e, modelArtifactsInfo: h}); + y.onsuccess = function() { + return i({modelArtifactsInfo: h}); + }, y.onerror = function(w) { + p = d.objectStore(dr); + var b = p.delete(r.modelPath); + b.onsuccess = function() { + return o.close(), a(y.error); + }, b.onerror = function(L) { + 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; + }(), Bm = function(n) { + return Ge().getBool("IS_BROWSER") && (!Array.isArray(n) && n.startsWith(Ai.URL_SCHEME)) ? wS(n.slice(Ai.URL_SCHEME.length)) : null; + }; + rn.registerSaveRouter(Bm); + rn.registerLoadRouter(Bm); + function wS(n) { + return new Ai(n); + } + function bS(n) { + return n.startsWith(Ai.URL_SCHEME) ? n.slice(Ai.URL_SCHEME.length) : n; + } + var xS = function() { + function n() { + this.indexedDB = Um(); + } + 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(Iu, Au); + a.onupgradeneeded = function() { + return Tu(a); + }, a.onsuccess = function() { + var s = a.result, o = s.transaction(dr, "readonly"), c = o.objectStore(dr), 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 = bS(t), [2, new Promise(function(i, a) { + var s = e.indexedDB.open(Iu, Au); + s.onupgradeneeded = function() { + return Tu(s); + }, s.onsuccess = function() { + var o = s.result, c = o.transaction(dr, "readwrite"), l = c.objectStore(dr), 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(zr, "readwrite"); + var f = h.objectStore(zr), 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 Kn = "/", Ti = "tensorflowjs_models", zm = "info", LS = "model_topology", SS = "weight_specs", IS = "weight_data", AS = "model_metadata"; + function Pm(n) { + return {info: [Ti, n, zm].join(Kn), topology: [Ti, n, LS].join(Kn), weightSpecs: [Ti, n, SS].join(Kn), weightData: [Ti, n, IS].join(Kn), modelMetadata: [Ti, n, AS].join(Kn)}; + } + function TS(n) { + var t = n.split(Kn); + if (t.length < 3) + throw new Error("Invalid key format: " + n); + return t.slice(1, t.length - 1).join(Kn); + } + function NS(n) { + return n.startsWith(Ni.URL_SCHEME) ? n.slice(Ni.URL_SCHEME.length) : n; + } + var Ni = function() { + function n(t) { + if (!Ge().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 = Pm(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, uS(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 = hS(o), [2, e]; + }); + }); + }, n.URL_SCHEME = "localstorage://", n; + }(), Mm = function(n) { + return Ge().getBool("IS_BROWSER") && (!Array.isArray(n) && n.startsWith(Ni.URL_SCHEME)) ? _S(n.slice(Ni.URL_SCHEME.length)) : null; + }; + rn.registerSaveRouter(Mm); + rn.registerLoadRouter(Mm); + function _S(n) { + return new Ni(n); + } + var CS = function() { + function n() { + E(Ge().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 = Ti + Kn, r = Kn + zm, i = 0; i < this.LS.length; ++i) + a = this.LS.key(i), a.startsWith(e) && a.endsWith(r) && (s = TS(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 = NS(t), e = Pm(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 _i = "://", pr = 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(_i) && (t = t.slice(0, t.indexOf(_i))), 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 Us(n) { + if (n.indexOf(_i) === -1) + throw new Error("The url string provided does not contain a scheme. Supported schemes are: " + ("" + pr.getSchemes().join(","))); + return {scheme: n.split(_i)[0], path: n.split(_i)[1]}; + } + function Hm(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 = Us(n).scheme, c = Us(n).path, l = o === Us(n).scheme, [4, i.load()]; + case 1: + return u = d.sent(), e && l ? [4, pr.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, pr.getManager(o).removeModel(c)] : [3, 6]; + case 5: + d.sent(), d.label = 6; + case 6: + return [2, h.modelArtifactsInfo]; + } + }); + }); + } + function RS() { + 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 = pr.getSchemes(), t = {}, e = 0, r = n, c.label = 1; + case 1: + return e < r.length ? (i = r[e], [4, pr.getManager(i).listModels()]) : [3, 4]; + case 2: + a = c.sent(); + for (s in a) + o = i + _i + s, t[o] = a[s]; + c.label = 3; + case 3: + return e++, [3, 1]; + case 4: + return [2, t]; + } + }); + }); + } + function OS(n) { + return pe(this, void 0, void 0, function() { + var t, e; + return fe(this, function(r) { + return t = Us(n), e = pr.getManager(t.scheme), [2, e.removeModel(t.path)]; + }); + }); + } + function ES(n, t) { + return pe(this, void 0, void 0, function() { + var e; + return fe(this, function(r) { + return e = false, [2, Hm(n, t, e)]; + }); + }); + } + function DS(n, t) { + return pe(this, void 0, void 0, function() { + var e; + return fe(this, function(r) { + return e = true, [2, Hm(n, t, e)]; + }); + }); + } + var kS = 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 (Ge().get("IS_BROWSER")) { + Ge().setPlatform("browser", new kS()); + try { + pr.registerManager(Ni.URL_SCHEME, new CS()); + } catch (n) { + } + try { + pr.registerManager(Ai.URL_SCHEME, new xS()); + } catch (n) { + } + } + var FS = {importFetch: function() { + return sf(); + }}, Nu, WS = function() { + function n() { + this.util = of(), this.textEncoder = new this.util.TextEncoder(); + } + return n.prototype.fetch = function(t, e) { + return Ge().global.fetch != null ? Ge().global.fetch(t, e) : (Nu == null && (Nu = FS.importFetch()), Nu(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; + }(); + Ge().get("IS_NODE") && Ge().setPlatform("node", new WS()); + function On(n, t, e) { + return t === void 0 && (t = "float32"), t = t || "float32", vc(n), new ks(n, t, e); + } + function US(n, t) { + var e = R(n, "x", "cast"); + if (!ff(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, Rs, i); + } + var he = U({cast_: US}); + function BS(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, il); + } + var Pr = U({clone_: BS}); + function Vm(n, t) { + t === void 0 && (t = false), console.log(n.toString(t)); + } + Cm(); + var zS = {buffer: On, cast: he, clone: Pr, print: Vm}; + jL(zS); + var PS = "model", MS = ".json", HS = ".weights.bin"; + function Gm(n) { + return new Promise(function(t) { + return setTimeout(t); + }).then(n); + } + var _u = function() { + function n(t) { + if (!Ge().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 = PS), this.modelTopologyFileName = t + MS, this.weightDataFileName = t + HS; + } + 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, Gm(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, Gm(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; + }(), VS = 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 L = b.target.result, x = f.indexOf(y); + m[x] = L, m.indexOf(null) === -1 && a({modelTopology: u, weightSpecs: p, weightData: Su(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 Wm(l.name); + }), a = {}, s = 0, o = t; s < o.length; s++) { + var c = o[s]; + c.paths.forEach(function(l) { + var u = Wm(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; + }(), qS = function(n) { + return Ge().getBool("IS_BROWSER") && (!Array.isArray(n) && n.startsWith(_u.URL_SCHEME)) ? GS(n.slice(_u.URL_SCHEME.length)) : null; + }; + rn.registerSaveRouter(qS); + function GS(n) { + return n === void 0 && (n = "model"), new _u(n); + } + function YS(n) { + return new VS(n); + } + function qm(n, t, e, r) { + s(n), e = e == null ? 0 : e, r = r == null ? 1 : r, 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 Ym(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 ? Ge().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, qm(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, qm(c, t.onProgress, l, u)]; + case 7: + d = p.sent(), p.label = 8; + case 8: + return h = d, [2, h]; + } + }); + }); + } + function KS(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 Ym(o, {requestInit: r}); + }, a = Km(i), [2, a(n, t, e)]; + }); + }); + } + function Km(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 L = "quantization" in b ? b.quantization.dtype : b.dtype, x = xu[L] * pt(b.shape), N = function() { + a[y] = true, s[y] == null && (s[y] = []), s[y].push({manifestEntry: b, groupOffset: w, sizeBytes: x}); + }; + i != null ? i.forEach(function(I, C) { + I === b.name && (N(), o[C] = true); + }) : N(), c.push(b.name), w += x; + }); + }), !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 L = new ArrayBuffer(w), x = new Uint8Array(L), N = 0, I = 0; I < y; I++) { + var C = new Uint8Array(d[f + I]); + x.set(C, N), N += C.byteLength; + } + var O = s[g]; + O.forEach(function(D) { + var F = L.slice(D.groupOffset, D.groupOffset + D.sizeBytes), k = km(F, [D.manifestEntry]); + for (var B in k) + p[B] = k[B]; + }), f += y; + }), [2, p]; + } + }); + }); + }; + } + var jS = "application/octet-stream", $S = "application/json", jm = 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 = Ge().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: $S}), "model.json"), t.weightData != null && e.body.append("model.weights.bin", new Blob([t.weightData], {type: jS}), "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, L, x, N; + return fe(this, function(I) { + switch (I.label) { + case 0: + for (e = Array.isArray(this.path) ? this.path[1] : this.path, r = XS(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 ? (L = (b = h.push).apply, x = [h], [4, Promise.all(d)]) : [3, 2]; + case 1: + L.apply(b, x.concat([I.sent()])), I.label = 2; + case 2: + return [4, Ym(h, {requestInit: this.requestInit, fetchFunc: this.fetch, onProgress: this.onProgress})]; + case 3: + return N = I.sent(), [2, [o, Su(N)]]; + } + }); + }); + }, n.URL_SCHEME_REGEX = /^https?:\/\//, n; + }(); + function XS(n) { + var t = n.lastIndexOf("/"), e = n.lastIndexOf("?"), r = n.substring(0, t), i = e > t ? n.substring(e) : ""; + return [r + "/", i]; + } + function Cu(n) { + return n.match(jm.URL_SCHEME_REGEX) != null; + } + var $m = 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 Cu(r); + }) : e = Cu(n), e ? Ru(n, t) : null; + }; + rn.registerSaveRouter($m); + rn.registerLoadRouter($m); + function Ru(n, t) { + return new jm(n, t); + } + function JS(n, t) { + return Ru(n, t); + } + var Ou = 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; + }(), ZS = 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 QS(n, t, e, r) { + if (arguments.length === 1) { + var i = n.modelTopology != null || n.weightSpecs != null; + return i ? new Ou(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 Ou({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 Ou({modelTopology: n, weightSpecs: t, weightData: e, trainingConfig: r}); + } + function eI(n) { + return new ZS(n); + } + var tI = {__proto__: null, browserFiles: YS, browserHTTPRequest: JS, concatenateArrayBuffers: Su, decodeWeights: km, encodeWeights: cS, fromMemory: QS, getLoadHandlers: vS, getModelArtifactsInfoForJSON: Ia, getSaveHandlers: yS, http: Ru, isHTTPScheme: Cu, loadWeights: KS, registerLoadRouter: gS, registerSaveRouter: mS, weightsLoaderFactory: Km, withSaveHandler: eI, copyModel: ES, listModels: RS, moveModel: DS, removeModel: OS}; + function nI(n, t) { + var e = R(n, "x", "reshape", null), r = {x: e}, i = {shape: t}, a = function(s, o) { + return t = uf(t, e.size), E(e.size === pt(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, Cl, i); + } + var Y = U({reshape_: nI}); + function rI(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 = pt(g), b = pt(y), L = w === b || w === 1 || b === 1; + E(a.rank >= 2 && s.rank >= 2 && L, 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 x = w > b ? g : y, N = x.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, kc, l); + } + var Ue = U({matMul_: rI}); + function iI(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, Sl, c); + } + var Bs = U({oneHot_: iI}); + function aI(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, eu, i); + } + var Tt = U({transpose_: aI}); + function sI(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 = Bs(he(r, "int32"), e), s = Bs(he(i, "int32"), e), o = Tt(a), c = Ue(o, s); + return he(c, "int32"); + } + var oI = U({confusionMatrix_: sI}); + var cI = {__proto__: null, confusionMatrix: oI}; + function Xm(n, t, e) { + if (Ur(n), t != null && t.length !== 3) + throw new Error("tensor3d() requires shape to have three numbers"); + var r = Rn(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 ur(n, t, r, e); + } + var Ci; + function lI(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