=n.outHeight||Math.floor(I)!==I))for(var R=0;R=n.outWidth||Math.floor(M)!==M||(D+=x.get(w,T,I,M,k))}}}y.set(D*b,w,E,C,A,k)}return y.toTensor()},e.prototype.maxPool3d=function(t,e){return Ql(t,"maxPool3d"),this.pool3d(t,e,"max").toFloat()},e.prototype.maxPool3dPositions=function(t,e){for(var n=or(e.outShape,"int32"),r=e.strideDepth,i=e.strideHeight,o=e.strideWidth,a=e.dilationDepth,s=e.dilationHeight,u=e.dilationWidth,c=e.effectiveFilterDepth,l=e.effectiveFilterHeight,f=e.effectiveFilterWidth,h=e.padInfo.front,d=e.padInfo.top,p=e.padInfo.left,m=this.bufferSync(t),g=0;g=F&&(F=P,T=I*l*f+M*l+B)}n.set(T,g,y,k,O,v)}}}return n.toTensor()},e.prototype.maxPool3dBackprop=function(t,e,n,r){Ql([e,n],"maxPool3dBackprop");for(var i=this.maxPool3dPositions(e,r),o=r.strideDepth,a=r.strideHeight,s=r.strideWidth,u=r.dilationDepth,c=r.dilationHeight,l=r.dilationWidth,f=r.effectiveFilterDepth,h=r.effectiveFilterHeight,d=r.effectiveFilterWidth,p=f-1-r.padInfo.front,m=d-1-r.padInfo.left,g=h-1-r.padInfo.top,v=or(e.shape,"float32"),y=this.bufferSync(i),b=this.bufferSync(t),x=0;x=r.outDepth||Math.floor(F)!==F))for(var T=0;T=r.outHeight||Math.floor(N)!==N))for(var I=0;I=r.outWidth||Math.floor(R)!==R)){var M=f*h*d-1-y.get(x,F,N,R,w)===D*h*d+T*d+I?1:0;0!==M&&(S+=b.get(x,F,N,R,w)*M)}}}}v.set(S,x,k,E,C,w)}return v.toTensor()},e.prototype.cast=function(t,e){return So(t,e,this)},e.prototype.reshape=function(t,e){return Do(t,e)},e.prototype.avgPool=function(t,e){return Ql(t,"avgPool"),Ql(t,"maxPool"),Zl(this.readSync(t.dataId),t.shape,t.dtype,t.strides,e,"avg").toTensor().toFloat()},e.prototype.resizeBilinear=function(t,e,n,r){Ql(t,"resizeBilinear");for(var i=t.shape,o=i[0],a=i[1],s=i[2],u=i[3],c=this.readSync(t.dataId),l=new Float32Array(T([o,e,n,u])),f=[r&&e>1?a-1:a,r&&n>1?s-1:s],h=[r&&e>1?e-1:e,r&&n>1?n-1:n],d=0,p=f[0]/h[0],m=f[1]/h[1],g=0;g1?o-1:o,n&&l>1?a-1:a],d=[n&&c>1?c-1:c,n&&l>1?l-1:l],p=h[0]/d[0],m=h[1]/d[1],g=this.readSync(t.dataId),v=0,y=0;y1?a-1:a,r&&n>1?s-1:s],h=[r&&e>1?e-1:e,r&&n>1?n-1:n],d=f[0]/h[0],p=f[1]/h[1],m=0,g=0;g1?o-1:o,n&&l>1?a-1:a],p=[n&&c>1?c-1:c,n&&l>1?l-1:l],m=d[0]/p[0],g=d[1]/p[1],v=1/m,y=1/g,b=2*Math.ceil(v)+2,x=2*Math.ceil(y)+2,w=0;w=c)){var M=k+R*t.strides[1],j=R*m;if(E===Math.min(o-1,n?Math.round(j):Math.floor(j)))for(var B=0;B=l)){var L=M+P*t.strides[2],z=P*g;_===Math.min(a-1,n?Math.round(z):Math.floor(z))&&(N+=h[L+T])}}}}f[S+T]=N}return Wn(f,e.shape,e.dtype)},e.prototype.batchNormalization=function(t,e,n,r,i,o){Ql([t,e,n,i,o],"batchNorm");for(var a=this.readSync(t.dataId),s=this.readSync(e.dataId),u=this.readSync(n.dataId),c=i?this.readSync(i.dataId):new Float32Array([1]),l=o?this.readSync(o.dataId):new Float32Array([0]),f=new Float32Array(a.length),h=l.length,d=c.length,p=u.length,m=s.length,g=0,v=0,y=0,b=0,x=0;x=h&&(g=0),v>=m&&(v=0),y>=d&&(y=0),b>=p&&(b=0);return Wn(f,t.shape)},e.prototype.localResponseNormalization4D=function(t,e,n,r,i){Ql(t,"localResponseNormalization4D");var o=t.shape[3],a=o-1,s=this.readSync(t.dataId),u=t.size,c=new Float32Array(u);function l(t){for(var n=t%o,r=t-n+Math.max(0,n-e),i=t-n+Math.min(n+e,a),u=0;r<=i;r++){var c=s[r];u+=c*c}return u}for(var f=0;f=0&&o[a]1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+e});for(var r=t.shape[0],i=t.shape[1],o=t.shape[2],a=t.shape[3],s=i*e,u=o*e,c=a/(e*e),l=this.readSync(t.dataId),f=new Float32Array(r*s*u*c),h=0,d=0;d=s))for(var _=h>1?(C-k)*(u-1)/(h-1):0,S=d>1?(A-E)*(c-1)/(d-1):0,D=0;D1?k*(u-1)+D*_:.5*(k+C)*(u-1);if(F<0||F>u-1)for(var T=0;T1?E*(c-1)+T*S:.5*(E+A)*(c-1))<0||$>c-1)for(N=0;N1?E*(c-1)+T*S:.5*(E+A)*(c-1))<0||$>c-1)for(N=0;N=t.size/s)throw new Error("Invalid indices: "+d+" does not index into "+t.shape);for(var v=0;v=r/i)throw new Error("Invalid indices: "+m+" does not index into "+n);for(var b=0;b6)throw Error("Packed transpose for rank "+this.rank+" is not yet supported.");var i=sa(this.rank),o=Ko("rc",this.rank),a=new Array(this.rank);for(r=0;r6)throw Error("Transpose for rank "+e+" is not yet supported");for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(e),i=0;i0&&(e=e.sum(r)),e.reshape(n.shape)},b:function(){var e=t,n=zr(r.shape,i);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)}}}},{kernelName:"AddN",saveAllInputs:!0,gradFunc:function(t,e){var n={};return e.forEach(function(e,r){n[r]=function(){return t.clone()}}),n}},{kernelName:Tr,gradFunc:function(t,e,n){for(var r=n,i=r.inputShape,o=r.shape,a=Array.from(o),s=i.length-1;s>=0;s--)if(i[s]===o[s])a[s]=1;else if(1!==i[s])throw new Error("broadcastTo(): ["+i+"] cannot be broadcast to ["+o+"].");var u=[];for(s=0;s1&&u.push(s);return{x:function(){return t.sum(u,!0)}}}},{kernelName:Ar,inputsToSave:["a","b"],gradFunc:function(t,e){var n=e[0],r=e[1],i=Ur(n.shape,r.shape);return{a:function(){var e=Li(t,r.toFloat()),o=zr(n.shape,i);return o.length>0?Wc(e,o).reshape(n.shape):e},b:function(){var e=t.mul(n.toFloat()),o=zr(r.shape,i);o.length>0&&(e=Wc(e,o).reshape(r.shape));var a=Tu(r);return ai(Li(e,a.toFloat()))}}}},{kernelName:"FusedBatchNorm",inputsToSave:["x","mean","variance","scale"],gradFunc:function(t,e,n){var r=n.varianceEpsilon,i=e[0],o=e[1],a=e[2],s=e[3],u=zs(i),c=null==s?Pn(1):s,l=zr(o.shape,u.shape),f=[];if(1===o.rank){for(var h=0;h0,function(){return"scheme must not be an empty string."});var r=t.getInstance();_(null==r.managers[e],function(){return"A model store manager is already registered for scheme '"+e+"'."}),r.managers[e]=n},t.getManager=function(t){var e=this.getInstance().managers[t];if(null==e)throw new Error("Cannot find model manager for scheme '"+t+"'");return e},t.getSchemes=function(){return Object.keys(this.getInstance().managers)},t}();function Rf(t){if(-1===t.indexOf(Nf))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+If.getSchemes().join(","));return{scheme:t.split(Nf)[0],path:t.split(Nf)[1]}}function Mf(t,e,n){return void 0===n&&(n=!1),u(this,void 0,void 0,function(){var r,i,o,a,s,u,l,f,h;return c(this,function(c){switch(c.label){case 0:return _(t!==e,function(){return"Old path and new path are the same: '"+t+"'"}),_((r=Tf.getLoadHandlers(t)).length>0,function(){return"Copying failed because no load handler is found for source URL "+t+"."}),_(r.length<2,function(){return"Copying failed because more than one ("+r.length+") load handlers for source URL "+t+"."}),i=r[0],_((o=Tf.getSaveHandlers(e)).length>0,function(){return"Copying failed because no save handler is found for destination URL "+e+"."}),_(o.length<2,function(){return"Copying failed because more than one ("+r.length+") save handlers for destination URL "+e+"."}),a=o[0],s=Rf(t).scheme,u=Rf(t).path,l=s===Rf(t).scheme,[4,i.load()];case 1:return f=c.sent(),n&&l?[4,If.getManager(s).removeModel(u)]:[3,3];case 2:c.sent(),c.label=3;case 3:return[4,a.save(f)];case 4:return h=c.sent(),!n||l?[3,6]:[4,If.getManager(s).removeModel(u)];case 5:c.sent(),c.label=6;case 6:return[2,h.modelArtifactsInfo]}})})}var jf="models_store",Bf="model_info_store";function Pf(){if(!f().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var t=window||self,e=t.indexedDB||t.mozIndexedDB||t.webkitIndexedDB||t.msIndexedDB||t.shimIndexedDB;if(null==e)throw new Error("The current browser does not appear to support IndexedDB.");return e}function Lf(t){var e=t.result;e.createObjectStore(jf,{keyPath:"modelPath"}),e.createObjectStore(Bf,{keyPath:"modelPath"})}var zf=function(){function t(t){if(this.indexedDB=Pf(),null==t||!t)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=t}return t.prototype.save=function(t){return u(this,void 0,void 0,function(){return c(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)]})})},t.prototype.load=function(){return u(this,void 0,void 0,function(){return c(this,function(t){return[2,this.databaseAction(this.modelPath)]})})},t.prototype.databaseAction=function(t,e){var n=this;return new Promise(function(t,r){var i=n.indexedDB.open("tensorflowjs",1);i.onupgradeneeded=function(){return Lf(i)},i.onsuccess=function(){var o=i.result;if(null==e){var a=o.transaction(jf,"readonly"),s=a.objectStore(jf).get(n.modelPath);s.onsuccess=function(){if(null==s.result)return o.close(),r(new Error("Cannot find model with path '"+n.modelPath+"' in IndexedDB."));t(s.result.modelArtifacts)},s.onerror=function(t){return o.close(),r(s.error)},a.oncomplete=function(){return o.close()}}else{var u,c=Ff(e),l=o.transaction(Bf,"readwrite"),f=l.objectStore(Bf),h=f.put({modelPath:n.modelPath,modelArtifactsInfo:c});h.onsuccess=function(){var i=(u=o.transaction(jf,"readwrite")).objectStore(jf).put({modelPath:n.modelPath,modelArtifacts:e,modelArtifactsInfo:c});i.onsuccess=function(){return t({modelArtifactsInfo:c})},i.onerror=function(t){var e=(f=l.objectStore(Bf)).delete(n.modelPath);e.onsuccess=function(){return o.close(),r(i.error)},e.onerror=function(t){return o.close(),r(i.error)}}},h.onerror=function(t){return o.close(),r(h.error)},l.oncomplete=function(){null==u?o.close():u.oncomplete=function(){return o.close()}}}},i.onerror=function(t){return r(i.error)}})},t.URL_SCHEME="indexeddb://",t}(),Uf=function(t){return f().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(zf.URL_SCHEME)?(e=t.slice(zf.URL_SCHEME.length),new zf(e)):null;var e};Tf.registerSaveRouter(Uf),Tf.registerLoadRouter(Uf);var Wf=function(){function t(){this.indexedDB=Pf()}return t.prototype.listModels=function(){return u(this,void 0,void 0,function(){var t=this;return c(this,function(e){return[2,new Promise(function(e,n){var r=t.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=function(){return Lf(r)},r.onsuccess=function(){var t=r.result,i=t.transaction(Bf,"readonly"),o=i.objectStore(Bf).getAll();o.onsuccess=function(){for(var t={},n=0,r=o.result;n0,function(){return"promises must be a none empty array"})}(t),function(t,e){_(t>=0&&t<=1,function(){return"Progress fraction must be in range [0, 1], but got startFraction "+t}),_(e>=0&&e<=1,function(){return"Progress fraction must be in range [0, 1], but got endFraction "+e}),_(e>=t,function(){return"startFraction must be no more than endFraction, but got startFraction "+t+" and endFraction "+e})}(n=null==n?0:n,r=null==r?1:r);var i=0;return Promise.all(t.map(function(o){return o.then(function(o){var a=n+ ++i/t.length*(r-n);return e(a),o}),o}))}function uh(t,e){return u(this,void 0,void 0,function(){var n,r,i,o,a,s,u,l,h;return c(this,function(c){switch(c.label){case 0:return null==e&&(e={}),n=null==e.fetchFunc?f().platform.fetch:e.fetchFunc,r=t.map(function(t){return n(t,e.requestInit,{isBinary:!0})}),i=0,o=.5,null!=e.onProgress?[3,2]:[4,Promise.all(r)];case 1:return a=c.sent(),[3,4];case 2:return[4,sh(r,e.onProgress,i,o)];case 3:a=c.sent(),c.label=4;case 4:return s=a.map(function(t){return t.arrayBuffer()}),u=.5,l=1,null!=e.onProgress?[3,6]:[4,Promise.all(s)];case 5:return h=c.sent(),[3,8];case 6:return[4,sh(s,e.onProgress,u,l)];case 7:h=c.sent(),c.label=8;case 8:return[2,h]}})})}function ch(t){var e=this;return function(n,r,i){return void 0===r&&(r=""),u(e,void 0,void 0,function(){var e,o,a,s,u,l,f,h,d,p;return c(this,function(c){switch(c.label){case 0:if(e=n.map(function(){return!1}),o={},a=null!=i?i.map(function(){return!1}):[],s=[],n.forEach(function(t,n){var r=0;t.weights.forEach(function(t){var u="quantization"in t?t.quantization.dtype:t.dtype,c=Ef[u]*T(t.shape),l=function(){e[n]=!0,null==o[n]&&(o[n]=[]),o[n].push({manifestEntry:t,groupOffset:r,sizeBytes:c})};null!=i?i.forEach(function(e,n){e===t.name&&(l(),a[n]=!0)}):l(),s.push(t.name),r+=c})}),!a.every(function(t){return t}))throw u=i.filter(function(t,e){return!a[e]}),new Error("Could not find weights in manifest with names: "+u.join(", ")+". \nManifest JSON has weights with names: "+s.join(", ")+".");return l=e.reduce(function(t,e,n){return e&&t.push(n),t},[]),f=[],l.forEach(function(t){n[t].paths.forEach(function(t){var e=r+(r.endsWith("/")?"":"/")+t;f.push(e)})}),[4,t(f)];case 1:return h=c.sent(),d={},p=0,l.forEach(function(t){for(var e=n[t].paths.length,r=0,i=0;i0,function(){return"URL path for http must not be null, undefined or empty."}),Array.isArray(t)&&_(2===t.length,function(){return"URL paths for http must have a length of 2, (actual length is "+t.length+")."}),this.path=t,null!=e.requestInit&&null!=e.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=e.requestInit||{}}return t.prototype.save=function(t){return u(this,void 0,void 0,function(){var e,n,r,i;return c(this,function(o){switch(o.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)).body=new FormData,n=[{paths:["./model.weights.bin"],weights:t.weightSpecs}],r={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,userDefinedMetadata:t.userDefinedMetadata,weightsManifest:n},e.body.append("model.json",new Blob([JSON.stringify(r)],{type:"application/json"}),"model.json"),null!=t.weightData&&e.body.append("model.weights.bin",new Blob([t.weightData],{type:"application/octet-stream"}),"model.weights.bin"),[4,this.fetch(this.path,e)];case 1:if((i=o.sent()).ok)return[2,{modelArtifactsInfo:Ff(t),responses:[i]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+i.status+".")}})})},t.prototype.load=function(){return u(this,void 0,void 0,function(){var t,e,n,r,i,o,a,s,u,l,f,h;return c(this,function(c){switch(c.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(!(t=c.sent()).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.");c.label=2;case 2:return c.trys.push([2,4,,5]),[4,t.json()];case 3:return e=c.sent(),[3,5];case 4:throw c.sent(),n="Failed to parse model JSON of response from "+this.path+".",this.path.endsWith(".pb")?n+=" 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.":n+=" Please make sure the server is serving valid JSON for this request.",new Error(n);case 5:if(r=e.modelTopology,i=e.weightsManifest,o=e.generatedBy,a=e.convertedBy,s=e.format,u=e.userDefinedMetadata,null==r&&null==i)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return null==i?[3,7]:[4,this.loadWeights(i)];case 6:h=c.sent(),l=h[0],f=h[1],c.label=7;case 7:return[2,{modelTopology:r,weightSpecs:l,weightData:f,userDefinedMetadata:u,generatedBy:o,convertedBy:a,format:s}]}})})},t.prototype.loadWeights=function(t){return u(this,void 0,void 0,function(){var e,n,r,i,o,a,s,u,l,f,h;return c(this,function(c){switch(c.label){case 0:for(e=Array.isArray(this.path)?this.path[1]:this.path,n=function(t){var e=t.lastIndexOf("/"),n=t.lastIndexOf("?");return[t.substring(0,e)+"/",n>e?t.substring(n):""]}(e),r=n[0],i=n[1],o=this.weightPathPrefix||r,a=[],s=0,u=t;s0&&Number.isInteger(n),function(){return"If provided, numClasses must be a positive integer, but got "+n}),_(1===r.rank,function(){return"Expected the rank of labels to be 1, but got "+r.rank}),_(1===i.rank,function(){return"Expected the rank of predictions to be 1, but got "+i.rank}),_(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."}),_(n>0&&Number.isInteger(n),function(){return"numClasses is required to be a positive integer, but got "+n});var o=hu(r.asType("int32"),n),a=hu(i.asType("int32"),n);return o.transpose().matMul(a).asType("int32")}}),bh=Object.freeze({confusionMatrix:yh}),xh=Nn({fromPixels_:function(t,e){if(void 0===e&&(e=3),e>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(null==t)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var n=!1,r=!1,i=!1,o=!1,a=!1;if(t.data instanceof Uint8Array)n=!0;else if("undefined"!=typeof ImageData&&t instanceof ImageData)r=!0;else if("undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement)i=!0;else if("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement)o=!0;else{if(null==t.getContext)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);a=!0}if(i&&i&&t.readyState<2)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the