var __create=Object.create;var __defProp=Object.defineProperty;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __getOwnPropNames=Object.getOwnPropertyNames;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __markAsModule=target=>__defProp(target,"__esModule",{value:true});var __commonJS=(callback,module2)=>()=>{if(!module2){module2={exports:{}};callback(module2.exports,module2)}return module2.exports};var __export=(target,all)=>{__markAsModule(target);for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __exportStar=(target,module2,desc)=>{__markAsModule(target);if(typeof module2==="object"||typeof module2==="function"){for(let key of __getOwnPropNames(module2))if(!__hasOwnProp.call(target,key)&&key!=="default")__defProp(target,key,{get:()=>module2[key],enumerable:!(desc=__getOwnPropDesc(module2,key))||desc.enumerable})}return target};var __toModule=module2=>{if(module2&&module2.__esModule)return module2;return __exportStar(__defProp(__create(__getProtoOf(module2)),"default",{value:module2,enumerable:true}),module2)};var require_lib=__commonJS(exports2=>{__export(exports2,{FetchError:()=>FetchError,Headers:()=>Headers,Request:()=>Request,Response:()=>Response,default:()=>lib_default});const stream=__toModule(require("stream"));const http2=__toModule(require("http"));const url=__toModule(require("url"));const https2=__toModule(require("https"));const zlib2=__toModule(require("zlib"));const Readable=stream.default.Readable;const BUFFER=Symbol("buffer");const TYPE=Symbol("type");class Blob2{constructor(){this[TYPE]="";const blobParts=arguments[0];const options=arguments[1];const buffers=[];let size=0;if(blobParts){const a=blobParts;const length=Number(a.length);for(let i=0;i1&&arguments[1]!==void 0?arguments[1]:{},_ref$size=_ref.size;let size=_ref$size===void 0?0:_ref$size;var _ref$timeout=_ref.timeout;let timeout=_ref$timeout===void 0?0:_ref$timeout;if(body2==null){body2=null}else if(isURLSearchParams(body2)){body2=Buffer.from(body2.toString())}else if(isBlob(body2));else if(Buffer.isBuffer(body2));else if(Object.prototype.toString.call(body2)==="[object ArrayBuffer]"){body2=Buffer.from(body2)}else if(ArrayBuffer.isView(body2)){body2=Buffer.from(body2.buffer,body2.byteOffset,body2.byteLength)}else if(body2 instanceof stream.default);else{body2=Buffer.from(String(body2))}this[INTERNALS]={body:body2,disturbed:false,error:null};this.size=size;this.timeout=timeout;if(body2 instanceof stream.default){body2.on("error",function(err){const error=err.name==="AbortError"?err:new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`,"system",err);_this[INTERNALS].error=error})}}Body.prototype={get body(){return this[INTERNALS].body},get bodyUsed(){return this[INTERNALS].disturbed},arrayBuffer(){return consumeBody.call(this).then(function(buf){return buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.byteLength)})},blob(){let ct=this.headers&&this.headers.get("content-type")||"";return consumeBody.call(this).then(function(buf){return Object.assign(new Blob2([],{type:ct.toLowerCase()}),{[BUFFER]:buf})})},json(){var _this2=this;return consumeBody.call(this).then(function(buffer2){try{return JSON.parse(buffer2.toString())}catch(err){return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`,"invalid-json"))}})},text(){return consumeBody.call(this).then(function(buffer2){return buffer2.toString()})},buffer(){return consumeBody.call(this)},textConverted(){var _this3=this;return consumeBody.call(this).then(function(buffer2){return convertBody(buffer2,_this3.headers)})}};Object.defineProperties(Body.prototype,{body:{enumerable:true},bodyUsed:{enumerable:true},arrayBuffer:{enumerable:true},blob:{enumerable:true},json:{enumerable:true},text:{enumerable:true}});Body.mixIn=function(proto){for(const name of Object.getOwnPropertyNames(Body.prototype)){if(!(name in proto)){const desc=Object.getOwnPropertyDescriptor(Body.prototype,name);Object.defineProperty(proto,name,desc)}}};function consumeBody(){var _this4=this;if(this[INTERNALS].disturbed){return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`))}this[INTERNALS].disturbed=true;if(this[INTERNALS].error){return Body.Promise.reject(this[INTERNALS].error)}let body2=this.body;if(body2===null){return Body.Promise.resolve(Buffer.alloc(0))}if(isBlob(body2)){body2=body2.stream()}if(Buffer.isBuffer(body2)){return Body.Promise.resolve(body2)}if(!(body2 instanceof stream.default)){return Body.Promise.resolve(Buffer.alloc(0))}let accum=[];let accumBytes=0;let abort=false;return new Body.Promise(function(resolve,reject){let resTimeout;if(_this4.timeout){resTimeout=setTimeout(function(){abort=true;reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`,"body-timeout"))},_this4.timeout)}body2.on("error",function(err){if(err.name==="AbortError"){abort=true;reject(err)}else{reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`,"system",err))}});body2.on("data",function(chunk){if(abort||chunk===null){return}if(_this4.size&&accumBytes+chunk.length>_this4.size){abort=true;reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`,"max-size"));return}accumBytes+=chunk.length;accum.push(chunk)});body2.on("end",function(){if(abort){return}clearTimeout(resTimeout);try{resolve(Buffer.concat(accum,accumBytes))}catch(err){reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`,"system",err))}})})}function convertBody(buffer2,headers){if(typeof convert!=="function"){throw new Error("The package `encoding` must be installed to use the textConverted() function")}const ct=headers.get("content-type");let charset="utf-8";let res,str;if(ct){res=/charset=([^;]*)/i.exec(ct)}str=buffer2.slice(0,1024).toString();if(!res&&str){res=/0&&arguments[0]!==void 0?arguments[0]:void 0;this[MAP]=Object.create(null);if(init2 instanceof Headers){const rawHeaders=init2.raw();const headerNames=Object.keys(rawHeaders);for(const headerName of headerNames){for(const value of rawHeaders[headerName]){this.append(headerName,value)}}return}if(init2==null);else if(typeof init2==="object"){const method=init2[Symbol.iterator];if(method!=null){if(typeof method!=="function"){throw new TypeError("Header pairs must be iterable")}const pairs=[];for(const pair of init2){if(typeof pair!=="object"||typeof pair[Symbol.iterator]!=="function"){throw new TypeError("Each header pair must be iterable")}pairs.push(Array.from(pair))}for(const pair of pairs){if(pair.length!==2){throw new TypeError("Each header pair must be a name/value tuple")}this.append(pair[0],pair[1])}}else{for(const key of Object.keys(init2)){const value=init2[key];this.append(key,value)}}}else{throw new TypeError("Provided initializer must be an object")}}get(name){name=`${name}`;validateName(name);const key=find(this[MAP],name);if(key===void 0){return null}return this[MAP][key].join(", ")}forEach(callback){let thisArg=arguments.length>1&&arguments[1]!==void 0?arguments[1]:void 0;let pairs=getHeaders(this);let i=0;while(i1&&arguments[1]!==void 0?arguments[1]:"key+value";const keys=Object.keys(headers[MAP]).sort();return keys.map(kind==="key"?function(k){return k.toLowerCase()}:kind==="value"?function(k){return headers[MAP][k].join(", ")}:function(k){return[k.toLowerCase(),headers[MAP][k].join(", ")]})}const INTERNAL=Symbol("internal");function createHeadersIterator(target,kind){const iterator=Object.create(HeadersIteratorPrototype);iterator[INTERNAL]={target,kind,index:0};return iterator}const HeadersIteratorPrototype=Object.setPrototypeOf({next(){if(!this||Object.getPrototypeOf(this)!==HeadersIteratorPrototype){throw new TypeError("Value of `this` is not a HeadersIterator")}var _INTERNAL=this[INTERNAL];const target=_INTERNAL.target,kind=_INTERNAL.kind,index=_INTERNAL.index;const values=getHeaders(target,kind);const len=values.length;if(index>=len){return{value:void 0,done:true}}this[INTERNAL].index=index+1;return{value:values[index],done:false}}},Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));Object.defineProperty(HeadersIteratorPrototype,Symbol.toStringTag,{value:"HeadersIterator",writable:false,enumerable:false,configurable:true});function exportNodeCompatibleHeaders(headers){const obj=Object.assign({__proto__:null},headers[MAP]);const hostHeaderKey=find(headers[MAP],"Host");if(hostHeaderKey!==void 0){obj[hostHeaderKey]=obj[hostHeaderKey][0]}return obj}function createHeadersLenient(obj){const headers=new Headers;for(const name of Object.keys(obj)){if(invalidTokenRegex.test(name)){continue}if(Array.isArray(obj[name])){for(const val of obj[name]){if(invalidHeaderCharRegex.test(val)){continue}if(headers[MAP][name]===void 0){headers[MAP][name]=[val]}else{headers[MAP][name].push(val)}}}else if(!invalidHeaderCharRegex.test(obj[name])){headers[MAP][name]=[obj[name]]}}return headers}const INTERNALS$1=Symbol("Response internals");const STATUS_CODES=http2.default.STATUS_CODES;class Response{constructor(){let body2=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null;let opts=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};Body.call(this,body2,opts);const status=opts.status||200;const headers=new Headers(opts.headers);if(body2!=null&&!headers.has("Content-Type")){const contentType=extractContentType(body2);if(contentType){headers.append("Content-Type",contentType)}}this[INTERNALS$1]={url:opts.url,status,statusText:opts.statusText||STATUS_CODES[status],headers,counter:opts.counter}}get url(){return this[INTERNALS$1].url||""}get status(){return this[INTERNALS$1].status}get ok(){return this[INTERNALS$1].status>=200&&this[INTERNALS$1].status<300}get redirected(){return this[INTERNALS$1].counter>0}get statusText(){return this[INTERNALS$1].statusText}get headers(){return this[INTERNALS$1].headers}clone(){return new Response(clone(this),{url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected})}}Body.mixIn(Response.prototype);Object.defineProperties(Response.prototype,{url:{enumerable:true},status:{enumerable:true},ok:{enumerable:true},redirected:{enumerable:true},statusText:{enumerable:true},headers:{enumerable:true},clone:{enumerable:true}});Object.defineProperty(Response.prototype,Symbol.toStringTag,{value:"Response",writable:false,enumerable:false,configurable:true});const INTERNALS$2=Symbol("Request internals");const parse_url=url.default.parse;const format_url=url.default.format;const streamDestructionSupported="destroy"in stream.default.Readable.prototype;function isRequest(input){return typeof input==="object"&&typeof input[INTERNALS$2]==="object"}function isAbortSignal(signal){const proto=signal&&typeof signal==="object"&&Object.getPrototypeOf(signal);return!!(proto&&proto.constructor.name==="AbortSignal")}class Request{constructor(input){let init2=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};let parsedURL;if(!isRequest(input)){if(input&&input.href){parsedURL=parse_url(input.href)}else{parsedURL=parse_url(`${input}`)}input={}}else{parsedURL=parse_url(input.url)}let method=init2.method||input.method||"GET";method=method.toUpperCase();if((init2.body!=null||isRequest(input)&&input.body!==null)&&(method==="GET"||method==="HEAD")){throw new TypeError("Request with GET/HEAD method cannot have body")}let inputBody=init2.body!=null?init2.body:isRequest(input)&&input.body!==null?clone(input):null;Body.call(this,inputBody,{timeout:init2.timeout||input.timeout||0,size:init2.size||input.size||0});const headers=new Headers(init2.headers||input.headers||{});if(inputBody!=null&&!headers.has("Content-Type")){const contentType=extractContentType(inputBody);if(contentType){headers.append("Content-Type",contentType)}}let signal=isRequest(input)?input.signal:null;if("signal"in init2)signal=init2.signal;if(signal!=null&&!isAbortSignal(signal)){throw new TypeError("Expected signal to be an instanceof AbortSignal")}this[INTERNALS$2]={method,redirect:init2.redirect||input.redirect||"follow",headers,parsedURL,signal};this.follow=init2.follow!==void 0?init2.follow:input.follow!==void 0?input.follow:20;this.compress=init2.compress!==void 0?init2.compress:input.compress!==void 0?input.compress:true;this.counter=init2.counter||input.counter||0;this.agent=init2.agent||input.agent}get method(){return this[INTERNALS$2].method}get url(){return format_url(this[INTERNALS$2].parsedURL)}get headers(){return this[INTERNALS$2].headers}get redirect(){return this[INTERNALS$2].redirect}get signal(){return this[INTERNALS$2].signal}clone(){return new Request(this)}}Body.mixIn(Request.prototype);Object.defineProperty(Request.prototype,Symbol.toStringTag,{value:"Request",writable:false,enumerable:false,configurable:true});Object.defineProperties(Request.prototype,{method:{enumerable:true},url:{enumerable:true},headers:{enumerable:true},redirect:{enumerable:true},clone:{enumerable:true},signal:{enumerable:true}});function getNodeRequestOptions(request){const parsedURL=request[INTERNALS$2].parsedURL;const headers=new Headers(request[INTERNALS$2].headers);if(!headers.has("Accept")){headers.set("Accept","*/*")}if(!parsedURL.protocol||!parsedURL.hostname){throw new TypeError("Only absolute URLs are supported")}if(!/^https?:$/.test(parsedURL.protocol)){throw new TypeError("Only HTTP(S) protocols are supported")}if(request.signal&&request.body instanceof stream.default.Readable&&!streamDestructionSupported){throw new Error("Cancellation of streamed requests with AbortSignal is not supported in node < 8")}let contentLengthValue=null;if(request.body==null&&/^(POST|PUT)$/i.test(request.method)){contentLengthValue="0"}if(request.body!=null){const totalBytes=getTotalBytes(request);if(typeof totalBytes==="number"){contentLengthValue=String(totalBytes)}}if(contentLengthValue){headers.set("Content-Length",contentLengthValue)}if(!headers.has("User-Agent")){headers.set("User-Agent","node-fetch/1.0 (+https://github.com/bitinn/node-fetch)")}if(request.compress&&!headers.has("Accept-Encoding")){headers.set("Accept-Encoding","gzip,deflate")}let agent=request.agent;if(typeof agent==="function"){agent=agent(parsedURL)}if(!headers.has("Connection")&&!agent){headers.set("Connection","close")}return Object.assign({},parsedURL,{method:request.method,headers:exportNodeCompatibleHeaders(headers),agent})}function AbortError(message){Error.call(this,message);this.type="aborted";this.message=message;Error.captureStackTrace(this,this.constructor)}AbortError.prototype=Object.create(Error.prototype);AbortError.prototype.constructor=AbortError;AbortError.prototype.name="AbortError";const PassThrough$1=stream.default.PassThrough;const resolve_url=url.default.resolve;function fetch2(url2,opts){if(!fetch2.Promise){throw new Error("native promise missing, set fetch.Promise to your favorite alternative")}Body.Promise=fetch2.Promise;return new fetch2.Promise(function(resolve,reject){const request=new Request(url2,opts);const options=getNodeRequestOptions(request);const send=(options.protocol==="https:"?https2.default:http2.default).request;const signal=request.signal;let response=null;const abort=function abort2(){let error=new AbortError("The user aborted a request.");reject(error);if(request.body&&request.body instanceof stream.default.Readable){request.body.destroy(error)}if(!response||!response.body)return;response.body.emit("error",error)};if(signal&&signal.aborted){abort();return}const abortAndFinalize=function abortAndFinalize2(){abort();finalize()};const req=send(options);let reqTimeout;if(signal){signal.addEventListener("abort",abortAndFinalize)}function finalize(){req.abort();if(signal)signal.removeEventListener("abort",abortAndFinalize);clearTimeout(reqTimeout)}if(request.timeout){req.once("socket",function(socket){reqTimeout=setTimeout(function(){reject(new FetchError(`network timeout at: ${request.url}`,"request-timeout"));finalize()},request.timeout)})}req.on("error",function(err){reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`,"system",err));finalize()});req.on("response",function(res){clearTimeout(reqTimeout);const headers=createHeadersLenient(res.headers);if(fetch2.isRedirect(res.statusCode)){const location=headers.get("Location");const locationURL=location===null?null:resolve_url(request.url,location);switch(request.redirect){case"error":reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`,"no-redirect"));finalize();return;case"manual":if(locationURL!==null){try{headers.set("Location",locationURL)}catch(err){reject(err)}}break;case"follow":if(locationURL===null){break}if(request.counter>=request.follow){reject(new FetchError(`maximum redirect reached at: ${request.url}`,"max-redirect"));finalize();return}const requestOpts={headers:new Headers(request.headers),follow:request.follow,counter:request.counter+1,agent:request.agent,compress:request.compress,method:request.method,body:request.body,signal:request.signal,timeout:request.timeout,size:request.size};if(res.statusCode!==303&&request.body&&getTotalBytes(request)===null){reject(new FetchError("Cannot follow redirect with body being a readable stream","unsupported-redirect"));finalize();return}if(res.statusCode===303||(res.statusCode===301||res.statusCode===302)&&request.method==="POST"){requestOpts.method="GET";requestOpts.body=void 0;requestOpts.headers.delete("content-length")}resolve(fetch2(new Request(locationURL,requestOpts)));finalize();return}}res.once("end",function(){if(signal)signal.removeEventListener("abort",abortAndFinalize)});let body2=res.pipe(new PassThrough$1);const response_options={url:request.url,status:res.statusCode,statusText:res.statusMessage,headers,size:request.size,timeout:request.timeout,counter:request.counter};const codings=headers.get("Content-Encoding");if(!request.compress||request.method==="HEAD"||codings===null||res.statusCode===204||res.statusCode===304){response=new Response(body2,response_options);resolve(response);return}const zlibOptions={flush:zlib2.default.Z_SYNC_FLUSH,finishFlush:zlib2.default.Z_SYNC_FLUSH};if(codings=="gzip"||codings=="x-gzip"){body2=body2.pipe(zlib2.default.createGunzip(zlibOptions));response=new Response(body2,response_options);resolve(response);return}if(codings=="deflate"||codings=="x-deflate"){const raw=res.pipe(new PassThrough$1);raw.once("data",function(chunk){if((chunk[0]&15)===8){body2=body2.pipe(zlib2.default.createInflate())}else{body2=body2.pipe(zlib2.default.createInflateRaw())}response=new Response(body2,response_options);resolve(response)});return}if(codings=="br"&&typeof zlib2.default.createBrotliDecompress==="function"){body2=body2.pipe(zlib2.default.createBrotliDecompress());response=new Response(body2,response_options);resolve(response);return}response=new Response(body2,response_options);resolve(response)});writeToStream(req,request)})}fetch2.isRedirect=function(code){return code===301||code===302||code===303||code===307||code===308};fetch2.Promise=global.Promise;var lib_default=fetch2});var require_tf_core_node=__commonJS(exports2=>{"use strict";Object.defineProperty(exports2,"__esModule",{value:true});var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d2,b2){d2.__proto__=b2}||function(d2,b2){for(var p in b2)if(b2.hasOwnProperty(p))d2[p]=b2[p]};return extendStatics(d,b)};function __extends(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}function __awaiter(thisArg,_arguments,P,generator){return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step2(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step2(generator["throw"](value))}catch(e){reject(e)}}function step2(result){result.done?resolve(result.value):new P(function(resolve2){resolve2(result.value)}).then(fulfilled,rejected)}step2((generator=generator.apply(thisArg,_arguments||[])).next())})}function __generator(thisArg,body2){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step2([n,v])}}function step2(op2){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op2[0]&2?y["return"]:op2[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op2[1])).done)return t;if(y=0,t)op2=[op2[0]&2,t.value];switch(op2[0]){case 0:case 1:t=op2;break;case 4:_.label++;return{value:op2[1],done:false};case 5:_.label++;y=op2[1];op2=[0];continue;case 7:op2=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op2[0]===6||op2[0]===2)){_=0;continue}if(op2[0]===3&&(!t||op2[1]>t[0]&&op2[1]0){index=Math.random()*counter|0;counter--;temp=array[counter];array[counter]=array[index];array[index]=temp}}function clamp(min3,x,max3){return Math.max(min3,Math.min(x,max3))}function nearestLargerEven(val){return val%2===0?val:val+1}function sum2(arr){var sum3=0;for(var i=0;i=maxCounter){reject();return}setTimeout(tryFn,nextBackoff)};tryFn()})}function inferFromImplicitShape(shape,size){var shapeProd=1;var implicitIdx=-1;for(var i=0;i=0){shapeProd*=shape[i]}else if(shape[i]===-1){if(implicitIdx!==-1){throw Error("Shapes can only have 1 implicit size. "+("Found -1 at dim "+implicitIdx+" and dim "+i))}implicitIdx=i}else if(shape[i]<0){throw Error("Shapes can not be < 0. Found "+shape[i]+" at dim "+i)}}if(implicitIdx===-1){if(size>0&&size!==shapeProd){throw Error("Size("+size+") must match the product of shape "+shape)}return shape}if(shapeProd===0){throw Error("Cannot infer the missing size in ["+shape+"] when there are 0 elements")}if(size%shapeProd!==0){throw Error("The implicit shape can't be a fractional number. "+("Got "+size+" / "+shapeProd))}var newShape=shape.slice();newShape[implicitIdx]=size/shapeProd;return newShape}function parseAxisParam(axis,shape){var rank=shape.length;axis=axis==null?shape.map(function(s,i){return i}):[].concat(axis);assert(axis.every(function(ax){return ax>=-rank&&axi)&&shape[i]===1){newShape.push(shape[i]);keptDims.push(i)}if(axes[j]<=i){j++}}if(shape[i]!==1){newShape.push(shape[i]);keptDims.push(i)}}return{newShape,keptDims}}function getTypedArrayFromDType(dtype,size){var values=null;if(dtype==null||dtype==="float32"){values=new Float32Array(size)}else if(dtype==="int32"){values=new Int32Array(size)}else if(dtype==="bool"){values=new Uint8Array(size)}else{throw new Error("Unknown data type "+dtype)}return values}function getArrayFromDType(dtype,size){var values=null;if(dtype==null||dtype==="float32"){values=new Float32Array(size)}else if(dtype==="int32"){values=new Int32Array(size)}else if(dtype==="bool"){values=new Uint8Array(size)}else if(dtype==="string"){values=new Array(size)}else{throw new Error("Unknown data type "+dtype)}return values}function checkConversionForErrors(vals,dtype){for(var i=0;i=0;--i){strides[i]=strides[i+1]*shape[i+1]}return strides}function createNestedArray(offset,shape,a){var ret=new Array;if(shape.length===1){var d=shape[0];for(var i=0;i=0,function(){return"Tensor must have a shape comprised of positive integers but got "+("shape ["+shape+"].")})})}function locToIndex(locs,rank,strides){if(rank===0){return 0}else if(rank===1){return locs[0]}var index=locs[locs.length-1];for(var i=0;i0?inputShape:"")+" "}}console.log("%c"+paddedName+" %c"+time2+" %c"+rank+"D "+shape+" %c"+size+" %c"+inputShapesDescription+" %c"+extraInfo,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")};return Logger2}();function getFilteredNodesXToY(tape,xs,y){var tensorsFromX={};var nodesFromX={};for(var i=0;i=0;i--){var node=tape[i];var nodeInputs=node.inputs;for(var j=0;j=0;i--){_loop_1(i)}}var FORMAT_LIMIT_NUM_VALS=20;var FORMAT_NUM_FIRST_LAST_VALS=3;var FORMAT_NUM_SIG_DIGITS=7;function tensorToString(vals,shape,dtype,verbose){var strides=computeStrides(shape);var padPerCol=computeMaxSizePerColumn(vals,shape,dtype,strides);var rank=shape.length;var valsLines=subTensorToString(vals,shape,dtype,strides,padPerCol);var lines=["Tensor"];if(verbose){lines.push(" dtype: "+dtype);lines.push(" rank: "+rank);lines.push(" shape: ["+shape+"]");lines.push(" values:")}lines.push(valsLines.map(function(l){return" "+l}).join("\n"));return lines.join("\n")}function computeMaxSizePerColumn(vals,shape,dtype,strides){var n=sizeFromShape(shape);var numCols=strides[strides.length-1];var padPerCol=new Array(numCols).fill(0);var rank=shape.length;var valuesOrTuples=dtype==="complex64"?createComplexTuples(vals):vals;if(rank>1){for(var row=0;rowFORMAT_LIMIT_NUM_VALS){var firstValsSize=FORMAT_NUM_FIRST_LAST_VALS*storagePerElement;var firstVals=Array.from(vals.slice(0,firstValsSize));var lastVals=Array.from(vals.slice((size-FORMAT_NUM_FIRST_LAST_VALS)*storagePerElement,size*storagePerElement));if(dtype==="complex64"){firstVals=createComplexTuples(firstVals);lastVals=createComplexTuples(lastVals)}return["["+firstVals.map(function(x,i2){return valToString(x,padPerCol[i2],dtype)}).join(", ")+", ..., "+lastVals.map(function(x,i2){return valToString(x,padPerCol[size-FORMAT_NUM_FIRST_LAST_VALS+i2],dtype)}).join(", ")+"]"]}var displayVals=dtype==="complex64"?createComplexTuples(vals):Array.from(vals);return["["+displayVals.map(function(x,i2){return valToString(x,padPerCol[i2],dtype)}).join(", ")+"]"]}var subshape=shape.slice(1);var substrides=strides.slice(1);var stride=strides[0]*storagePerElement;var lines=[];if(size>FORMAT_LIMIT_NUM_VALS){for(var i=0;i=this.shape[i]){var msg="Requested out of range element at "+locs+". "+(" Buffer shape="+this.shape);throw new Error(msg)}i++}var index=locs[locs.length-1];for(var i_1=0;i_10){throw new Error("Backend '"+this.backendName+"' has an internal memory leak "+("("+dataIdsLeaked+" data ids) after running '"+kernelName+"'"))}};Engine2.prototype.runKernelFunc=function(forwardFunc,inputs,backwardsFunc,kernelName,attrs,inputsToSave,outputsToSave){var _this=this;var outputs;var saved=[];var isTapeOn=this.isTapeOn();if(kernelName==null){kernelName=this.state.activeScope!=null?this.state.activeScope.name:""}var startingBytecount=this.state.numBytes;var startingNumTensors=this.state.numTensors;if(this.shouldCheckForMemLeaks()){this.state.numDataMovesStack.push(0)}var kernelFunc3;var kernel=getKernel(kernelName,this.backendName);var out;if(kernel!=null){kernelFunc3=function(){var numDataIdsBefore=_this.backend.numDataIds();out=kernel.kernelFunc({inputs,attrs,backend:_this.backend});var outInfos=Array.isArray(out)?out:[out];if(_this.shouldCheckForMemLeaks()){_this.checkKernelForMemLeak(kernelName,numDataIdsBefore,outInfos)}var outTensors=outInfos.map(function(_a){var dataId=_a.dataId,shape=_a.shape,dtype=_a.dtype;return _this.makeTensorFromDataId(dataId,shape,dtype)});if(isTapeOn){var tensorsToSave=_this.getTensorsForGradient(kernelName,inputs,outTensors);if(tensorsToSave==null){if(outputsToSave==null){outputsToSave=[]}var outsToSave=outTensors.filter(function(_,i){return outputsToSave[i]});tensorsToSave=(inputsToSave||[]).slice().concat(outsToSave)}saved=_this.saveTensorsForBackwardMode(tensorsToSave)}return outTensors}}else{var saveFunc_1=function(tensors){if(!isTapeOn){return}saved=tensors.map(function(tensor2){return _this.keep(_this.clone(tensor2))})};kernelFunc3=function(){var numDataIdsBefore=_this.backend.numDataIds();out=_this.tidy(function(){return forwardFunc(_this.backend,saveFunc_1)});var outs=Array.isArray(out)?out:[out];if(_this.shouldCheckForMemLeaks()){_this.checkKernelForMemLeak(kernelName,numDataIdsBefore,outs)}return outs}}var kernelProfile;this.scopedRun(function(){return _this.state.kernelDepth++},function(){return _this.state.kernelDepth--},function(){if(!_this.ENV.getBool("DEBUG")&&!_this.state.profiling){outputs=kernelFunc3()}else{kernelProfile=_this.profiler.profileKernel(kernelName,inputs,function(){return kernelFunc3()});if(_this.ENV.getBool("DEBUG")){_this.profiler.logKernelProfile(kernelProfile)}outputs=kernelProfile.outputs}});if(isTapeOn){this.addTapeNode(kernelName,inputs,outputs,backwardsFunc,saved,attrs)}if(this.state.profiling){this.state.activeProfile.kernels.push({name:kernelName,bytesAdded:this.state.numBytes-startingBytecount,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-startingNumTensors,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(inputs).map(function(key){return inputs[key]!=null?inputs[key].shape:null}),outputShapes:outputs.map(function(item){return item.shape}),kernelTimeMs:kernelProfile.timeMs,extraInfo:kernelProfile.extraInfo})}return Array.isArray(out)?outputs:outputs[0]};Engine2.prototype.saveTensorsForBackwardMode=function(tensors){var _this=this;var saved=tensors.map(function(tensor2){return _this.keep(_this.clone(tensor2))});return saved};Engine2.prototype.getTensorsForGradient=function(kernelName,inputs,outputs){var gradConfig=getGradient(kernelName);if(gradConfig!=null){var inputsToSave=gradConfig.inputsToSave||[];var outputsToSave_1=gradConfig.outputsToSave||[];var inputTensorsToSave=void 0;if(gradConfig.saveAllInputs){assert(Array.isArray(inputs),function(){return"saveAllInputs is true, expected inputs to be an array."});inputTensorsToSave=Object.keys(inputs).map(function(key){return inputs[key]})}else{inputTensorsToSave=inputsToSave.map(function(inputName){return inputs[inputName]})}var outputTensorsToSave=outputs.filter(function(_,i){return outputsToSave_1[i]});return inputTensorsToSave.concat(outputTensorsToSave)}return null};Engine2.prototype.makeTensor=function(values,shape,dtype,backend2){if(values==null){throw new Error("Values passed to engine.makeTensor() are null")}dtype=dtype||"float32";backend2=backend2||this.backend;var backendVals=values;if(dtype==="string"&&isString(values[0])){backendVals=values.map(function(d){return encodeString(d)})}var dataId=backend2.write(backendVals,shape,dtype);var t=new Tensor(shape,dtype,dataId,this.nextTensorId());this.incRef(t,backend2);if(dtype==="string"){var info=this.state.tensorInfo.get(dataId);var newBytes=bytesFromStringArray(backendVals);this.state.numBytes+=newBytes-info.bytes;info.bytes=newBytes}return t};Engine2.prototype.makeTensorFromDataId=function(dataId,shape,dtype,backend2){dtype=dtype||"float32";var t=new Tensor(shape,dtype,dataId,this.nextTensorId());this.incRef(t,backend2);return t};Engine2.prototype.makeVariable=function(initialValue,trainable,name,dtype){if(trainable===void 0){trainable=true}name=name||this.nextVariableId().toString();if(dtype!=null&&dtype!==initialValue.dtype){initialValue=initialValue.cast(dtype)}var v=new Variable(initialValue,trainable,name,this.nextTensorId());if(this.state.registeredVariables[v.name]!=null){throw new Error("Variable with name "+v.name+" was already registered")}this.state.registeredVariables[v.name]=v;this.incRef(v,this.backend);return v};Engine2.prototype.incRef=function(a,backend2){var refCount=this.state.tensorInfo.has(a.dataId)?this.state.tensorInfo.get(a.dataId).refCount:0;this.state.numTensors++;if(a.dtype==="string"){this.state.numStringTensors++}if(refCount===0){this.state.numDataBuffers++;var bytes=0;if(a.dtype!=="complex64"&&a.dtype!=="string"){bytes=a.size*bytesPerElement(a.dtype)}this.state.tensorInfo.set(a.dataId,{backend:backend2||this.backend,dtype:a.dtype,shape:a.shape,bytes,refCount:0});this.state.numBytes+=bytes}this.state.tensorInfo.get(a.dataId).refCount++;if(!(a instanceof Variable)){this.track(a)}};Engine2.prototype.disposeTensor=function(a){if(!this.state.tensorInfo.has(a.dataId)){return}this.state.numTensors--;if(a.dtype==="string"){this.state.numStringTensors--}var info=this.state.tensorInfo.get(a.dataId);var refCount=info.refCount;if(refCount<=1){if(a.dtype!=="complex64"){this.state.numBytes-=info.bytes}this.state.numDataBuffers--;info.backend.disposeData(a.dataId);this.state.tensorInfo.delete(a.dataId)}else{this.state.tensorInfo.get(a.dataId).refCount--}};Engine2.prototype.disposeVariables=function(){for(var varName in this.state.registeredVariables){var v=this.state.registeredVariables[varName];this.disposeVariable(v)}};Engine2.prototype.disposeVariable=function(v){this.disposeTensor(v);if(this.state.registeredVariables[v.name]!=null){delete this.state.registeredVariables[v.name]}};Engine2.prototype.memory=function(){var info=this.backend.memory();info.numTensors=this.state.numTensors;info.numDataBuffers=this.state.numDataBuffers;info.numBytes=this.state.numBytes;if(this.state.numStringTensors>0){info.unreliable=true;if(info.reasons==null){info.reasons=[]}info.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")}return info};Engine2.prototype.profile=function(query){return __awaiter(this,void 0,void 0,function(){var startBytes,startNumTensors,_a,_i2,_b,kernel,_c,_d;return __generator(this,function(_e){switch(_e.label){case 0:this.state.profiling=true;startBytes=this.state.numBytes;startNumTensors=this.state.numTensors;this.state.activeProfile.kernels=[];_a=this.state.activeProfile;return[4,query()];case 1:_a.result=_e.sent();this.state.profiling=false;this.state.activeProfile.peakBytes=Math.max.apply(Math,this.state.activeProfile.kernels.map(function(d){return d.totalBytesSnapshot}));this.state.activeProfile.newBytes=this.state.numBytes-startBytes;this.state.activeProfile.newTensors=this.state.numTensors-startNumTensors;_i2=0,_b=this.state.activeProfile.kernels;_e.label=2;case 2:if(!(_i2<_b.length))return[3,6];kernel=_b[_i2];_c=kernel;return[4,kernel.kernelTimeMs];case 3:_c.kernelTimeMs=_e.sent();_d=kernel;return[4,kernel.extraInfo];case 4:_d.extraInfo=_e.sent();_e.label=5;case 5:_i2++;return[3,2];case 6:return[2,this.state.activeProfile]}})})};Engine2.prototype.isTapeOn=function(){return this.state.gradientDepth>0&&this.state.kernelDepth===0};Engine2.prototype.addTapeNode=function(kernelName,inputs,outputs,gradientsFunc,saved,attrs){var _this=this;var tapeNode={id:this.state.nextTapeNodeId++,kernelName,inputs,outputs,saved};var gradConfig=getGradient(kernelName);if(gradConfig!=null){gradientsFunc=gradConfig.gradFunc}if(gradientsFunc!=null){tapeNode.gradient=function(dys){dys=dys.map(function(dy,i){if(dy==null){var output=outputs[i];var vals=makeZerosTypedArray(output.size,output.dtype);return _this.makeTensor(vals,output.shape,output.dtype)}return dy});return gradientsFunc(dys.length>1?dys:dys[0],saved,attrs)}}this.state.activeTape.push(tapeNode)};Engine2.prototype.keep=function(result){result.kept=true;return result};Engine2.prototype.startTape=function(){if(this.state.gradientDepth===0){this.state.activeTape=[]}this.state.gradientDepth++};Engine2.prototype.endTape=function(){this.state.gradientDepth--};Engine2.prototype.startScope=function(name){var scopeInfo={track:[],name:"unnamed scope",id:this.state.nextScopeId++};if(name){scopeInfo.name=name}this.state.scopeStack.push(scopeInfo);this.state.activeScope=scopeInfo};Engine2.prototype.endScope=function(result){var _this=this;var tensorsToTrackInParent=getTensorsInContainer(result);var tensorsToTrackInParentSet=new Set(tensorsToTrackInParent.map(function(t){return t.id}));for(var i=0;i0,function(){return"gradients() received an empty list of xs."});if(dy!=null&&dy.dtype!=="float32"){throw new Error("dy must have 'float32' dtype, but has '"+dy.dtype+"'")}var y=this.scopedRun(function(){return _this.startTape()},function(){return _this.endTape()},function(){return _this.tidy("forward",f)});assert(y instanceof Tensor,function(){return"The result y returned by f() must be a tensor."});var filteredTape=getFilteredNodesXToY(this.state.activeTape,xs,y);if(!allowNoGradients&&filteredTape.length===0&&xs.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 accumulatedGradientMap={};accumulatedGradientMap[y.id]=dy==null?ones(y.shape):dy;backpropagateGradients(accumulatedGradientMap,filteredTape,function(f2){return _this.tidy(f2)},add);var grads2=xs.map(function(x){return accumulatedGradientMap[x.id]});if(_this.state.gradientDepth===0){_this.state.activeTape.forEach(function(node){for(var _i2=0,_a=node.saved;_i2<_a.length;_i2++){var tensor2=_a[_i2];tensor2.dispose()}});_this.state.activeTape=null}return{value:y,grads:grads2}})};Engine2.prototype.customGrad=function(f){var _this=this;assert(isFunction(f),function(){return"The f passed in customGrad(f) must be a function."});return function(){var inputs=[];for(var _i2=0;_i20,function(){return"Element arr["+indices.join("][")+"] should be a primitive, "+("but is an array of "+val.length+" elements")});assert(val.length===shape[0],function(){return"Element arr["+indices.join("][")+"] should have "+shape[0]+" "+("elements, but has "+val.length+" elements")});var subShape=shape.slice(1);for(var i=0;i=0){inferredDtype=parseAsDtype}assertDtype(parseAsDtype,inferredDtype,argName,functionName);if(x==null||!isTypedArray(x)&&!Array.isArray(x)&&typeof x!=="number"&&typeof x!=="boolean"&&typeof x!=="string"){var type=x==null?"null":x.constructor.name;throw new Error("Argument '"+argName+"' passed to '"+functionName+"' must be a "+("Tensor or TensorLike, but got '"+type+"'"))}var inferredShape=inferShape(x,inferredDtype);if(!isTypedArray(x)&&!Array.isArray(x)){x=[x]}var skipTypedArray=true;var values=inferredDtype!=="string"?toTypedArray(x,inferredDtype):flatten(x,[],skipTypedArray);return ENGINE.makeTensor(values,inferredShape,inferredDtype)}function convertToTensorArray(arg,argName,functionName,parseAsDtype){if(parseAsDtype===void 0){parseAsDtype="numeric"}if(!Array.isArray(arg)){throw new Error("Argument "+argName+" passed to "+functionName+" must be a `Tensor[]` or `TensorLike[]`")}var tensors=arg;return tensors.map(function(t,i){return convertToTensor(t,argName+"["+i+"]",functionName)},parseAsDtype)}var OP_SCOPE_SUFFIX="__op";function op(f){var keys=Object.keys(f);if(keys.length!==1){throw new Error("Please provide an object with a single key (operation name) mapping to a function. Got an object with "+(keys.length+" keys."))}var opName=keys[0];var fn=f[opName];if(opName.endsWith("_")){opName=opName.substring(0,opName.length-1)}opName=opName+OP_SCOPE_SUFFIX;var f2=function(){var args=[];for(var _i2=0;_i2>10]+(float16Bits&1023)]+exponentTable[float16Bits>>10];bufferUint32View[index]=float32Bits}return new Float32Array(buffer3)}}var IORouterRegistry=function(){function IORouterRegistry2(){this.saveRouters=[];this.loadRouters=[]}IORouterRegistry2.getInstance=function(){if(IORouterRegistry2.instance==null){IORouterRegistry2.instance=new IORouterRegistry2}return IORouterRegistry2.instance};IORouterRegistry2.registerSaveRouter=function(saveRouter){IORouterRegistry2.getInstance().saveRouters.push(saveRouter)};IORouterRegistry2.registerLoadRouter=function(loadRouter){IORouterRegistry2.getInstance().loadRouters.push(loadRouter)};IORouterRegistry2.getSaveHandlers=function(url){return IORouterRegistry2.getHandlers(url,"save")};IORouterRegistry2.getLoadHandlers=function(url,loadOptions){return IORouterRegistry2.getHandlers(url,"load",loadOptions)};IORouterRegistry2.getHandlers=function(url,handlerType,loadOptions){var validHandlers=[];var routers=handlerType==="load"?IORouterRegistry2.getInstance().loadRouters:IORouterRegistry2.getInstance().saveRouters;routers.forEach(function(router){var handler=router(url,loadOptions);if(handler!==null){validHandlers.push(handler)}});return validHandlers};return IORouterRegistry2}();var registerSaveRouter=function(loudRouter){return IORouterRegistry.registerSaveRouter(loudRouter)};var registerLoadRouter=function(loudRouter){return IORouterRegistry.registerLoadRouter(loudRouter)};var getSaveHandlers=function(url){return IORouterRegistry.getSaveHandlers(url)};var getLoadHandlers=function(url,loadOptions){return IORouterRegistry.getLoadHandlers(url,loadOptions)};var DATABASE_NAME="tensorflowjs";var DATABASE_VERSION=1;var MODEL_STORE_NAME="models_store";var INFO_STORE_NAME="model_info_store";function getIndexedDBFactory(){if(!env3().getBool("IS_BROWSER")){throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.")}var theWindow=typeof window==="undefined"?self:window;var factory=theWindow.indexedDB||theWindow.mozIndexedDB||theWindow.webkitIndexedDB||theWindow.msIndexedDB||theWindow.shimIndexedDB;if(factory==null){throw new Error("The current browser does not appear to support IndexedDB.")}return factory}function setUpDatabase(openRequest){var db=openRequest.result;db.createObjectStore(MODEL_STORE_NAME,{keyPath:"modelPath"});db.createObjectStore(INFO_STORE_NAME,{keyPath:"modelPath"})}var BrowserIndexedDB=function(){function BrowserIndexedDB2(modelPath){this.indexedDB=getIndexedDBFactory();if(modelPath==null||!modelPath){throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.")}this.modelPath=modelPath}BrowserIndexedDB2.prototype.save=function(modelArtifacts){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){if(modelArtifacts.modelTopology instanceof ArrayBuffer){throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.")}return[2,this.databaseAction(this.modelPath,modelArtifacts)]})})};BrowserIndexedDB2.prototype.load=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){return[2,this.databaseAction(this.modelPath)]})})};BrowserIndexedDB2.prototype.databaseAction=function(modelPath,modelArtifacts){var _this=this;return new Promise(function(resolve,reject){var openRequest=_this.indexedDB.open(DATABASE_NAME,DATABASE_VERSION);openRequest.onupgradeneeded=function(){return setUpDatabase(openRequest)};openRequest.onsuccess=function(){var db=openRequest.result;if(modelArtifacts==null){var modelTx=db.transaction(MODEL_STORE_NAME,"readonly");var modelStore=modelTx.objectStore(MODEL_STORE_NAME);var getRequest_1=modelStore.get(_this.modelPath);getRequest_1.onsuccess=function(){if(getRequest_1.result==null){db.close();return reject(new Error("Cannot find model with path '"+_this.modelPath+"' in IndexedDB."))}else{resolve(getRequest_1.result.modelArtifacts)}};getRequest_1.onerror=function(error){db.close();return reject(getRequest_1.error)};modelTx.oncomplete=function(){return db.close()}}else{var modelArtifactsInfo_1=getModelArtifactsInfoForJSON(modelArtifacts);var infoTx_1=db.transaction(INFO_STORE_NAME,"readwrite");var infoStore_1=infoTx_1.objectStore(INFO_STORE_NAME);var putInfoRequest_1=infoStore_1.put({modelPath:_this.modelPath,modelArtifactsInfo:modelArtifactsInfo_1});var modelTx_1;putInfoRequest_1.onsuccess=function(){modelTx_1=db.transaction(MODEL_STORE_NAME,"readwrite");var modelStore2=modelTx_1.objectStore(MODEL_STORE_NAME);var putModelRequest=modelStore2.put({modelPath:_this.modelPath,modelArtifacts,modelArtifactsInfo:modelArtifactsInfo_1});putModelRequest.onsuccess=function(){return resolve({modelArtifactsInfo:modelArtifactsInfo_1})};putModelRequest.onerror=function(error){infoStore_1=infoTx_1.objectStore(INFO_STORE_NAME);var deleteInfoRequest=infoStore_1.delete(_this.modelPath);deleteInfoRequest.onsuccess=function(){db.close();return reject(putModelRequest.error)};deleteInfoRequest.onerror=function(error2){db.close();return reject(putModelRequest.error)}}};putInfoRequest_1.onerror=function(error){db.close();return reject(putInfoRequest_1.error)};infoTx_1.oncomplete=function(){if(modelTx_1==null){db.close()}else{modelTx_1.oncomplete=function(){return db.close()}}}}};openRequest.onerror=function(error){return reject(openRequest.error)}})};BrowserIndexedDB2.URL_SCHEME="indexeddb://";return BrowserIndexedDB2}();var indexedDBRouter=function(url){if(!env3().getBool("IS_BROWSER")){return null}else{if(!Array.isArray(url)&&url.startsWith(BrowserIndexedDB.URL_SCHEME)){return browserIndexedDB(url.slice(BrowserIndexedDB.URL_SCHEME.length))}else{return null}}};IORouterRegistry.registerSaveRouter(indexedDBRouter);IORouterRegistry.registerLoadRouter(indexedDBRouter);function browserIndexedDB(modelPath){return new BrowserIndexedDB(modelPath)}function maybeStripScheme(key){return key.startsWith(BrowserIndexedDB.URL_SCHEME)?key.slice(BrowserIndexedDB.URL_SCHEME.length):key}var BrowserIndexedDBManager=function(){function BrowserIndexedDBManager2(){this.indexedDB=getIndexedDBFactory()}BrowserIndexedDBManager2.prototype.listModels=function(){return __awaiter(this,void 0,void 0,function(){var _this=this;return __generator(this,function(_a){return[2,new Promise(function(resolve,reject){var openRequest=_this.indexedDB.open(DATABASE_NAME,DATABASE_VERSION);openRequest.onupgradeneeded=function(){return setUpDatabase(openRequest)};openRequest.onsuccess=function(){var db=openRequest.result;var tx=db.transaction(INFO_STORE_NAME,"readonly");var store=tx.objectStore(INFO_STORE_NAME);var getAllInfoRequest=store.getAll();getAllInfoRequest.onsuccess=function(){var out={};for(var _i2=0,_a2=getAllInfoRequest.result;_i2<_a2.length;_i2++){var item=_a2[_i2];out[item.modelPath]=item.modelArtifactsInfo}resolve(out)};getAllInfoRequest.onerror=function(error){db.close();return reject(getAllInfoRequest.error)};tx.oncomplete=function(){return db.close()}};openRequest.onerror=function(error){return reject(openRequest.error)}})]})})};BrowserIndexedDBManager2.prototype.removeModel=function(path){return __awaiter(this,void 0,void 0,function(){var _this=this;return __generator(this,function(_a){path=maybeStripScheme(path);return[2,new Promise(function(resolve,reject){var openRequest=_this.indexedDB.open(DATABASE_NAME,DATABASE_VERSION);openRequest.onupgradeneeded=function(){return setUpDatabase(openRequest)};openRequest.onsuccess=function(){var db=openRequest.result;var infoTx=db.transaction(INFO_STORE_NAME,"readwrite");var infoStore=infoTx.objectStore(INFO_STORE_NAME);var getInfoRequest=infoStore.get(path);var modelTx;getInfoRequest.onsuccess=function(){if(getInfoRequest.result==null){db.close();return reject(new Error("Cannot find model with path '"+path+"' in IndexedDB."))}else{var deleteInfoRequest=infoStore.delete(path);var deleteModelData_1=function(){modelTx=db.transaction(MODEL_STORE_NAME,"readwrite");var modelStore=modelTx.objectStore(MODEL_STORE_NAME);var deleteModelRequest=modelStore.delete(path);deleteModelRequest.onsuccess=function(){return resolve(getInfoRequest.result.modelArtifactsInfo)};deleteModelRequest.onerror=function(error){return reject(getInfoRequest.error)}};deleteInfoRequest.onsuccess=deleteModelData_1;deleteInfoRequest.onerror=function(error){deleteModelData_1();db.close();return reject(getInfoRequest.error)}}};getInfoRequest.onerror=function(error){db.close();return reject(getInfoRequest.error)};infoTx.oncomplete=function(){if(modelTx==null){db.close()}else{modelTx.oncomplete=function(){return db.close()}}}};openRequest.onerror=function(error){return reject(openRequest.error)}})]})})};return BrowserIndexedDBManager2}();var PATH_SEPARATOR="/";var PATH_PREFIX="tensorflowjs_models";var INFO_SUFFIX="info";var MODEL_TOPOLOGY_SUFFIX="model_topology";var WEIGHT_SPECS_SUFFIX="weight_specs";var WEIGHT_DATA_SUFFIX="weight_data";var MODEL_METADATA_SUFFIX="model_metadata";function getModelKeys(path){return{info:[PATH_PREFIX,path,INFO_SUFFIX].join(PATH_SEPARATOR),topology:[PATH_PREFIX,path,MODEL_TOPOLOGY_SUFFIX].join(PATH_SEPARATOR),weightSpecs:[PATH_PREFIX,path,WEIGHT_SPECS_SUFFIX].join(PATH_SEPARATOR),weightData:[PATH_PREFIX,path,WEIGHT_DATA_SUFFIX].join(PATH_SEPARATOR),modelMetadata:[PATH_PREFIX,path,MODEL_METADATA_SUFFIX].join(PATH_SEPARATOR)}}function getModelPathFromKey(key){var items=key.split(PATH_SEPARATOR);if(items.length<3){throw new Error("Invalid key format: "+key)}return items.slice(1,items.length-1).join(PATH_SEPARATOR)}function maybeStripScheme$1(key){return key.startsWith(BrowserLocalStorage.URL_SCHEME)?key.slice(BrowserLocalStorage.URL_SCHEME.length):key}var BrowserLocalStorage=function(){function BrowserLocalStorage2(modelPath){if(!env3().getBool("IS_BROWSER")||typeof window==="undefined"||typeof window.localStorage==="undefined"){throw new Error("The current environment does not support local storage.")}this.LS=window.localStorage;if(modelPath==null||!modelPath){throw new Error("For local storage, modelPath must not be null, undefined or empty.")}this.modelPath=modelPath;this.keys=getModelKeys(this.modelPath)}BrowserLocalStorage2.prototype.save=function(modelArtifacts){return __awaiter(this,void 0,void 0,function(){var topology,weightSpecs,modelArtifactsInfo;return __generator(this,function(_a){if(modelArtifacts.modelTopology instanceof ArrayBuffer){throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.")}else{topology=JSON.stringify(modelArtifacts.modelTopology);weightSpecs=JSON.stringify(modelArtifacts.weightSpecs);modelArtifactsInfo=getModelArtifactsInfoForJSON(modelArtifacts);try{this.LS.setItem(this.keys.info,JSON.stringify(modelArtifactsInfo));this.LS.setItem(this.keys.topology,topology);this.LS.setItem(this.keys.weightSpecs,weightSpecs);this.LS.setItem(this.keys.weightData,arrayBufferToBase64String(modelArtifacts.weightData));this.LS.setItem(this.keys.modelMetadata,JSON.stringify({format:modelArtifacts.format,generatedBy:modelArtifacts.generatedBy,convertedBy:modelArtifacts.convertedBy,userDefinedMetadata:modelArtifacts.userDefinedMetadata}));return[2,{modelArtifactsInfo}]}catch(err){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);throw new Error("Failed to save model '"+this.modelPath+"' to local storage: size quota being exceeded is a possible cause of this failure: "+("modelTopologyBytes="+modelArtifactsInfo.modelTopologyBytes+", ")+("weightSpecsBytes="+modelArtifactsInfo.weightSpecsBytes+", ")+("weightDataBytes="+modelArtifactsInfo.weightDataBytes+"."))}}return[2]})})};BrowserLocalStorage2.prototype.load=function(){return __awaiter(this,void 0,void 0,function(){var info,out,topology,weightSpecs,metadataString,metadata,weightDataBase64;return __generator(this,function(_a){info=JSON.parse(this.LS.getItem(this.keys.info));if(info==null){throw new Error("In local storage, there is no model with name '"+this.modelPath+"'")}if(info.modelTopologyType!=="JSON"){throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.")}out={};topology=JSON.parse(this.LS.getItem(this.keys.topology));if(topology==null){throw new Error("In local storage, the topology of model '"+this.modelPath+"' is missing.")}out.modelTopology=topology;weightSpecs=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(weightSpecs==null){throw new Error("In local storage, the weight specs of model '"+this.modelPath+"' are missing.")}out.weightSpecs=weightSpecs;metadataString=this.LS.getItem(this.keys.modelMetadata);if(metadataString!=null){metadata=JSON.parse(metadataString);out.format=metadata["format"];out.generatedBy=metadata["generatedBy"];out.convertedBy=metadata["convertedBy"];out.userDefinedMetadata=metadata["userDefinedMetadata"]}weightDataBase64=this.LS.getItem(this.keys.weightData);if(weightDataBase64==null){throw new Error("In local storage, the binary weight values of model "+("'"+this.modelPath+"' are missing."))}out.weightData=base64StringToArrayBuffer(weightDataBase64);return[2,out]})})};BrowserLocalStorage2.URL_SCHEME="localstorage://";return BrowserLocalStorage2}();var localStorageRouter=function(url){if(!env3().getBool("IS_BROWSER")){return null}else{if(!Array.isArray(url)&&url.startsWith(BrowserLocalStorage.URL_SCHEME)){return browserLocalStorage(url.slice(BrowserLocalStorage.URL_SCHEME.length))}else{return null}}};IORouterRegistry.registerSaveRouter(localStorageRouter);IORouterRegistry.registerLoadRouter(localStorageRouter);function browserLocalStorage(modelPath){return new BrowserLocalStorage(modelPath)}var BrowserLocalStorageManager=function(){function BrowserLocalStorageManager2(){assert(env3().getBool("IS_BROWSER"),function(){return"Current environment is not a web browser"});assert(typeof window==="undefined"||typeof window.localStorage!=="undefined",function(){return"Current browser does not appear to support localStorage"});this.LS=window.localStorage}BrowserLocalStorageManager2.prototype.listModels=function(){return __awaiter(this,void 0,void 0,function(){var out,prefix,suffix,i,key,modelPath;return __generator(this,function(_a){out={};prefix=PATH_PREFIX+PATH_SEPARATOR;suffix=PATH_SEPARATOR+INFO_SUFFIX;for(i=0;i0,function(){return"scheme must not be an empty string."});var registry=ModelStoreManagerRegistry2.getInstance();assert(registry.managers[scheme]==null,function(){return"A model store manager is already registered for scheme '"+scheme+"'."});registry.managers[scheme]=manager};ModelStoreManagerRegistry2.getManager=function(scheme){var manager=this.getInstance().managers[scheme];if(manager==null){throw new Error("Cannot find model manager for scheme '"+scheme+"'")}return manager};ModelStoreManagerRegistry2.getSchemes=function(){return Object.keys(this.getInstance().managers)};return ModelStoreManagerRegistry2}();function parseURL(url){if(url.indexOf(URL_SCHEME_SUFFIX)===-1){throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+(""+ModelStoreManagerRegistry.getSchemes().join(",")))}return{scheme:url.split(URL_SCHEME_SUFFIX)[0],path:url.split(URL_SCHEME_SUFFIX)[1]}}function cloneModelInternal(sourceURL,destURL,deleteSource){if(deleteSource===void 0){deleteSource=false}return __awaiter(this,void 0,void 0,function(){var loadHandlers,loadHandler,saveHandlers,saveHandler,sourceScheme,sourcePath,sameMedium,modelArtifacts,saveResult;return __generator(this,function(_a){switch(_a.label){case 0:assert(sourceURL!==destURL,function(){return"Old path and new path are the same: '"+sourceURL+"'"});loadHandlers=IORouterRegistry.getLoadHandlers(sourceURL);assert(loadHandlers.length>0,function(){return"Copying failed because no load handler is found for source URL "+sourceURL+"."});assert(loadHandlers.length<2,function(){return"Copying failed because more than one ("+loadHandlers.length+") "+("load handlers for source URL "+sourceURL+".")});loadHandler=loadHandlers[0];saveHandlers=IORouterRegistry.getSaveHandlers(destURL);assert(saveHandlers.length>0,function(){return"Copying failed because no save handler is found for destination "+("URL "+destURL+".")});assert(saveHandlers.length<2,function(){return"Copying failed because more than one ("+loadHandlers.length+") "+("save handlers for destination URL "+destURL+".")});saveHandler=saveHandlers[0];sourceScheme=parseURL(sourceURL).scheme;sourcePath=parseURL(sourceURL).path;sameMedium=sourceScheme===parseURL(sourceURL).scheme;return[4,loadHandler.load()];case 1:modelArtifacts=_a.sent();if(!(deleteSource&&sameMedium))return[3,3];return[4,ModelStoreManagerRegistry.getManager(sourceScheme).removeModel(sourcePath)];case 2:_a.sent();_a.label=3;case 3:return[4,saveHandler.save(modelArtifacts)];case 4:saveResult=_a.sent();if(!(deleteSource&&!sameMedium))return[3,6];return[4,ModelStoreManagerRegistry.getManager(sourceScheme).removeModel(sourcePath)];case 5:_a.sent();_a.label=6;case 6:return[2,saveResult.modelArtifactsInfo]}})})}function listModels(){return __awaiter(this,void 0,void 0,function(){var schemes,out,_i2,schemes_1,scheme,schemeOut,path,url;return __generator(this,function(_a){switch(_a.label){case 0:schemes=ModelStoreManagerRegistry.getSchemes();out={};_i2=0,schemes_1=schemes;_a.label=1;case 1:if(!(_i20,function(){return"promises must be a none empty array"})}function checkFraction(startFraction2,endFraction2){assert(startFraction2>=0&&startFraction2<=1,function(){return"Progress fraction must be in range [0, 1], but "+("got startFraction "+startFraction2)});assert(endFraction2>=0&&endFraction2<=1,function(){return"Progress fraction must be in range [0, 1], but "+("got endFraction "+endFraction2)});assert(endFraction2>=startFraction2,function(){return"startFraction must be no more than endFraction, but "+("got startFraction "+startFraction2+" and endFraction ")+(""+endFraction2)})}return Promise.all(promises.map(registerMonitor))}function loadWeightsAsArrayBuffer(fetchURLs,loadOptions){return __awaiter(this,void 0,void 0,function(){var fetchFunc,requests,fetchStartFraction,fetchEndFraction,responses,_a,bufferPromises,bufferStartFraction,bufferEndFraction,buffers,_b;return __generator(this,function(_c){switch(_c.label){case 0:if(loadOptions==null){loadOptions={}}fetchFunc=loadOptions.fetchFunc==null?env3().platform.fetch:loadOptions.fetchFunc;requests=fetchURLs.map(function(fetchURL){return fetchFunc(fetchURL,loadOptions.requestInit,{isBinary:true})});fetchStartFraction=0;fetchEndFraction=.5;if(!(loadOptions.onProgress==null))return[3,2];return[4,Promise.all(requests)];case 1:_a=_c.sent();return[3,4];case 2:return[4,monitorPromisesProgress(requests,loadOptions.onProgress,fetchStartFraction,fetchEndFraction)];case 3:_a=_c.sent();_c.label=4;case 4:responses=_a;bufferPromises=responses.map(function(response){return response.arrayBuffer()});bufferStartFraction=.5;bufferEndFraction=1;if(!(loadOptions.onProgress==null))return[3,6];return[4,Promise.all(bufferPromises)];case 5:_b=_c.sent();return[3,8];case 6:return[4,monitorPromisesProgress(bufferPromises,loadOptions.onProgress,bufferStartFraction,bufferEndFraction)];case 7:_b=_c.sent();_c.label=8;case 8:buffers=_b;return[2,buffers]}})})}function loadWeights(manifest,filePathPrefix,weightNames,requestInit){if(filePathPrefix===void 0){filePathPrefix=""}return __awaiter(this,void 0,void 0,function(){var fetchWeights,loadWeights2;return __generator(this,function(_a){fetchWeights=function(fetchUrls){return loadWeightsAsArrayBuffer(fetchUrls,{requestInit})};loadWeights2=weightsLoaderFactory(fetchWeights);return[2,loadWeights2(manifest,filePathPrefix,weightNames)]})})}function weightsLoaderFactory(fetchWeightsFunction){var _this=this;return function(manifest,filePathPrefix,weightNames){if(filePathPrefix===void 0){filePathPrefix=""}return __awaiter(_this,void 0,void 0,function(){var groupIndicesToFetchMap,groupWeightsToFetch,weightsFound,allManifestWeightNames,weightsNotFound,groupIndicesToFetch,fetchUrls,buffers,weightsTensorMap,bufferIndexOffset;return __generator(this,function(_a){switch(_a.label){case 0:groupIndicesToFetchMap=manifest.map(function(){return false});groupWeightsToFetch={};weightsFound=weightNames!=null?weightNames.map(function(){return false}):[];allManifestWeightNames=[];manifest.forEach(function(manifestGroupConfig,groupIndex){var groupOffset=0;manifestGroupConfig.weights.forEach(function(weightsEntry){var rawDtype="quantization"in weightsEntry?weightsEntry.quantization.dtype:weightsEntry.dtype;var weightsBytes=DTYPE_VALUE_SIZE_MAP[rawDtype]*sizeFromShape(weightsEntry.shape);var enqueueWeightsForFetchingFn=function(){groupIndicesToFetchMap[groupIndex]=true;if(groupWeightsToFetch[groupIndex]==null){groupWeightsToFetch[groupIndex]=[]}groupWeightsToFetch[groupIndex].push({manifestEntry:weightsEntry,groupOffset,sizeBytes:weightsBytes})};if(weightNames!=null){weightNames.forEach(function(weightName,weightIndex){if(weightName===weightsEntry.name){enqueueWeightsForFetchingFn();weightsFound[weightIndex]=true}})}else{enqueueWeightsForFetchingFn()}allManifestWeightNames.push(weightsEntry.name);groupOffset+=weightsBytes})});if(!weightsFound.every(function(found){return found})){weightsNotFound=weightNames.filter(function(_,i){return!weightsFound[i]});throw new Error("Could not find weights in manifest with names: "+(weightsNotFound.join(", ")+". \n")+"Manifest JSON has weights with names: "+(allManifestWeightNames.join(", ")+"."))}groupIndicesToFetch=groupIndicesToFetchMap.reduce(function(accumulator,shouldFetch,i){if(shouldFetch){accumulator.push(i)}return accumulator},[]);fetchUrls=[];groupIndicesToFetch.forEach(function(i){manifest[i].paths.forEach(function(filepath){var fetchUrl=filePathPrefix+(!filePathPrefix.endsWith("/")?"/":"")+filepath;fetchUrls.push(fetchUrl)})});return[4,fetchWeightsFunction(fetchUrls)];case 1:buffers=_a.sent();weightsTensorMap={};bufferIndexOffset=0;groupIndicesToFetch.forEach(function(i){var numBuffers=manifest[i].paths.length;var groupBytes=0;for(var i_1=0;i_10,function(){return"URL path for http must not be null, undefined or empty."});if(Array.isArray(path)){assert(path.length===2,function(){return"URL paths for http must have a length of 2, "+("(actual length is "+path.length+").")})}this.path=path;if(loadOptions.requestInit!=null&&loadOptions.requestInit.body!=null){throw new Error("requestInit is expected to have no pre-existing body, but has one.")}this.requestInit=loadOptions.requestInit||{}}HTTPRequest2.prototype.save=function(modelArtifacts){return __awaiter(this,void 0,void 0,function(){var init2,weightsManifest,modelTopologyAndWeightManifest,response;return __generator(this,function(_a){switch(_a.label){case 0:if(modelArtifacts.modelTopology instanceof ArrayBuffer){throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.")}init2=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);init2.body=new FormData;weightsManifest=[{paths:["./model.weights.bin"],weights:modelArtifacts.weightSpecs}];modelTopologyAndWeightManifest={modelTopology:modelArtifacts.modelTopology,format:modelArtifacts.format,generatedBy:modelArtifacts.generatedBy,convertedBy:modelArtifacts.convertedBy,userDefinedMetadata:modelArtifacts.userDefinedMetadata,weightsManifest};init2.body.append("model.json",new Blob([JSON.stringify(modelTopologyAndWeightManifest)],{type:JSON_TYPE}),"model.json");if(modelArtifacts.weightData!=null){init2.body.append("model.weights.bin",new Blob([modelArtifacts.weightData],{type:OCTET_STREAM_MIME_TYPE}),"model.weights.bin")}return[4,this.fetch(this.path,init2)];case 1:response=_a.sent();if(response.ok){return[2,{modelArtifactsInfo:getModelArtifactsInfoForJSON(modelArtifacts),responses:[response]}]}else{throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+(response.status+"."))}}})})};HTTPRequest2.prototype.load=function(){return __awaiter(this,void 0,void 0,function(){var modelConfigRequest,modelConfig,e_1,message,modelTopology,weightsManifest,generatedBy,convertedBy,format,userDefinedMetadata,weightSpecs,weightData,results,artifacts,initializer;return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:modelConfigRequest=_a.sent();if(!modelConfigRequest.ok){throw new Error("Request to "+this.path+" failed with status code "+(modelConfigRequest.status+". Please verify this URL points to ")+"the model JSON of the model to load.")}_a.label=2;case 2:_a.trys.push([2,4,,5]);return[4,modelConfigRequest.json()];case 3:modelConfig=_a.sent();return[3,5];case 4:e_1=_a.sent();message="Failed to parse model JSON of response from "+this.path+".";if(this.path.endsWith(".pb")){message+=" 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."}else{message+=" Please make sure the server is serving valid JSON for this request."}throw new Error(message);case 5:modelTopology=modelConfig.modelTopology;weightsManifest=modelConfig.weightsManifest;generatedBy=modelConfig.generatedBy;convertedBy=modelConfig.convertedBy;format=modelConfig.format;userDefinedMetadata=modelConfig.userDefinedMetadata;if(modelTopology==null&&weightsManifest==null){throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.")}if(!(weightsManifest!=null))return[3,7];return[4,this.loadWeights(weightsManifest)];case 6:results=_a.sent();weightSpecs=results[0],weightData=results[1];_a.label=7;case 7:artifacts={modelTopology,weightSpecs,weightData,userDefinedMetadata,generatedBy,convertedBy,format};initializer=modelConfig.modelInitializer;if(initializer){artifacts.modelInitializer=initializer}return[2,artifacts]}})})};HTTPRequest2.prototype.loadWeights=function(weightsManifest){return __awaiter(this,void 0,void 0,function(){var weightPath,_a,prefix,suffix,pathPrefix,weightSpecs,_i2,weightsManifest_1,entry,fetchURLs,urlPromises,_b,weightsManifest_2,weightsGroup,_c,_d,path,_e,_f,_g,buffers;return __generator(this,function(_h){switch(_h.label){case 0:weightPath=Array.isArray(this.path)?this.path[1]:this.path;_a=parseUrl(weightPath),prefix=_a[0],suffix=_a[1];pathPrefix=this.weightPathPrefix||prefix;weightSpecs=[];for(_i2=0,weightsManifest_1=weightsManifest;_i2lastSlash?url.substring(lastSearchParam):"";return[prefix+"/",suffix]}function isHTTPScheme(url){return url.match(HTTPRequest.URL_SCHEME_REGEX)!=null}var httpRouter=function(url,loadOptions){if(typeof fetch==="undefined"&&(loadOptions==null||loadOptions.fetchFunc==null)){return null}else{var isHTTP=true;if(Array.isArray(url)){isHTTP=url.every(function(urlItem){return isHTTPScheme(urlItem)})}else{isHTTP=isHTTPScheme(url)}if(isHTTP){return http(url,loadOptions)}}return null};IORouterRegistry.registerSaveRouter(httpRouter);IORouterRegistry.registerLoadRouter(httpRouter);function http(path,loadOptions){return new HTTPRequest(path,loadOptions)}function browserHTTPRequest(path,loadOptions){return http(path,loadOptions)}var PassthroughLoader=function(){function PassthroughLoader2(modelArtifacts){this.modelArtifacts=modelArtifacts}PassthroughLoader2.prototype.load=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){return[2,this.modelArtifacts]})})};return PassthroughLoader2}();var PassthroughSaver=function(){function PassthroughSaver2(saveHandler){this.saveHandler=saveHandler}PassthroughSaver2.prototype.save=function(modelArtifacts){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){return[2,this.saveHandler(modelArtifacts)]})})};return PassthroughSaver2}();function fromMemory(modelArtifacts,weightSpecs,weightData,trainingConfig){if(arguments.length===1){var isModelArtifacts=modelArtifacts.modelTopology!=null||modelArtifacts.weightSpecs!=null;if(isModelArtifacts){return new PassthroughLoader(modelArtifacts)}else{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.");return new PassthroughLoader({modelTopology:modelArtifacts})}}else{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.");return new PassthroughLoader({modelTopology:modelArtifacts,weightSpecs,weightData,trainingConfig})}}function withSaveHandler(saveHandler){return new PassthroughSaver(saveHandler)}var io={__proto__:null,browserFiles,browserHTTPRequest,concatenateArrayBuffers,decodeWeights,encodeWeights,fromMemory,getLoadHandlers,getModelArtifactsInfoForJSON,getSaveHandlers,http,isHTTPScheme,loadWeights,registerLoadRouter,registerSaveRouter,weightsLoaderFactory,withSaveHandler,copyModel,listModels,moveModel,removeModel};function reshape_(x,shape){var $x=convertToTensor(x,"x","reshape",null);var inputs={x:$x};var attrs={shape};var forward=function(backend2,save){shape=inferFromImplicitShape(shape,$x.size);assert($x.size===sizeFromShape(shape),function(){return"new shape and old shape must have the same number of elements."});save([$x]);return backend2.reshape($x,shape)};return ENGINE.runKernelFunc(forward,inputs,null,Reshape6,attrs)}var reshape2=op({reshape_});function matMul_(a,b,transposeA,transposeB){var _a;if(transposeA===void 0){transposeA=false}if(transposeB===void 0){transposeB=false}var $a=convertToTensor(a,"a","matMul");var $b=convertToTensor(b,"b","matMul");_a=makeTypesMatch($a,$b),$a=_a[0],$b=_a[1];var forward=function(backend2,save){save([$a,$b]);var innerShapeA=transposeA?$a.shape[$a.rank-2]:$a.shape[$a.rank-1];var innerShapeB=transposeB?$b.shape[$b.rank-1]:$b.shape[$b.rank-2];var outerShapeA=transposeA?$a.shape[$a.rank-1]:$a.shape[$a.rank-2];var outerShapeB=transposeB?$b.shape[$b.rank-2]:$b.shape[$b.rank-1];var outerDimsA=$a.shape.slice(0,-2);var outerDimsB=$b.shape.slice(0,-2);var batchDimA=sizeFromShape(outerDimsA);var batchDimB=sizeFromShape(outerDimsB);var batchDimsCompatible=batchDimA===batchDimB||batchDimA===1||batchDimB===1;assert($a.rank>=2&&$b.rank>=2&&batchDimsCompatible,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 ("+outerDimsA+") and ("+outerDimsB+").")});assert(innerShapeA===innerShapeB,function(){return"Error in matMul: inner shapes ("+innerShapeA+") and ("+(innerShapeB+") of Tensors with shapes "+$a.shape+" and ")+($b.shape+" and transposeA="+transposeA)+(" and transposeB="+transposeB+" must match.")});var outShapeOuterDims=batchDimA>batchDimB?outerDimsA:outerDimsB;var outShape=outShapeOuterDims.concat([outerShapeA,outerShapeB]);var a3D=transposeA?reshape2($a,[batchDimA,innerShapeA,outerShapeA]):reshape2($a,[batchDimA,outerShapeA,innerShapeA]);var b3D=transposeB?reshape2($b,[batchDimB,outerShapeB,innerShapeB]):reshape2($b,[batchDimB,innerShapeB,outerShapeB]);var res3d=backend2.batchMatMul(a3D,b3D,transposeA,transposeB);return reshape2(res3d,outShape)};var inputs={a:$a,b:$b};var attrs={transposeA,transposeB};return ENGINE.runKernelFunc(forward,inputs,null,BatchMatMul3,attrs)}var matMul=op({matMul_});function oneHot_(indices,depth,onValue,offValue){if(onValue===void 0){onValue=1}if(offValue===void 0){offValue=0}if(depth<2){throw new Error("Error in oneHot: depth must be >=2, but it is "+depth)}var $indices=convertToTensor(indices,"indices","oneHot","int32");var outShape=$indices.shape.concat([depth]);var forward=function(backend2,save){save([$indices]);return reshape2(backend2.oneHot(reshape2($indices,[$indices.size]),depth,onValue,offValue),outShape)};var inputs={indices:$indices};var attrs={depth,onValue,offValue};return ENGINE.runKernelFunc(forward,inputs,null,OneHot3,attrs)}var oneHot2=op({oneHot_});function transpose_(x,perm){var $x=convertToTensor(x,"x","transpose");if(perm==null){perm=$x.shape.map(function(s,i){return i}).reverse()}assert($x.rank===perm.length,function(){return"Error in transpose: rank of input "+$x.rank+" "+("must match length of perm "+perm+".")});perm.forEach(function(axis){assert(axis>=0&&axis<$x.rank,function(){return"All entries in 'perm' must be between 0 and "+($x.rank-1)+(" but got "+perm)})});if($x.rank<=1){return $x.clone()}var inputs={x:$x};var attrs={perm};return ENGINE.runKernelFunc(function(backend2){return backend2.transpose($x,perm)},inputs,null,Transpose5,attrs)}var transpose2=op({transpose_});function confusionMatrix_(labels,predictions,numClasses){var $labels=convertToTensor(labels,"labels","confusionMatrix");var $predictions=convertToTensor(predictions,"predictions","confusionMatrix");assert(numClasses==null||numClasses>0&&Number.isInteger(numClasses),function(){return"If provided, numClasses must be a positive integer, "+("but got "+numClasses)});assert($labels.rank===1,function(){return"Expected the rank of labels to be 1, but got "+$labels.rank});assert($predictions.rank===1,function(){return"Expected the rank of predictions to be 1, "+("but got "+$predictions.rank)});assert($labels.shape[0]===$predictions.shape[0],function(){return"Mismatch in the number of examples: "+($labels.shape[0]+" vs. "+$predictions.shape[0]+". ")+"Labels and predictions should have the same number of elements."});assert(numClasses>0&&Number.isInteger(numClasses),function(){return"numClasses is required to be a positive integer, but got "+(""+numClasses)});var oneHotLabels=oneHot2(cast2($labels,"int32"),numClasses);var oneHotPredictions=oneHot2(cast2($predictions,"int32"),numClasses);var oneHotLabelsT=transpose2(oneHotLabels);var product=matMul(oneHotLabelsT,oneHotPredictions);return cast2(product,"int32")}var confusionMatrix=op({confusionMatrix_});var math={__proto__:null,confusionMatrix};function tensor3d(values,shape,dtype){assertNonNull(values);if(shape!=null&&shape.length!==3){throw new Error("tensor3d() requires shape to have three numbers")}var inferredShape=inferShape(values,dtype);if(inferredShape.length!==3&&inferredShape.length!==1){throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray")}if(inferredShape.length===1&&shape==null){throw new Error("tensor3d() requires shape to be provided when `values` are a flat array")}return makeTensor(values,shape,inferredShape,dtype)}var fromPixels2DContext;function fromPixels_(pixels,numChannels){if(numChannels===void 0){numChannels=3}if(numChannels>4){throw new Error("Cannot construct Tensor with more than 4 channels from pixels.")}if(pixels==null){throw new Error("pixels passed to tf.browser.fromPixels() can not be null")}var isPixelData=false;var isImageData=false;var isVideo=false;var isImage=false;var isCanvasLike=false;if(pixels.data instanceof Uint8Array){isPixelData=true}else if(typeof ImageData!=="undefined"&&pixels instanceof ImageData){isImageData=true}else if(typeof HTMLVideoElement!=="undefined"&&pixels instanceof HTMLVideoElement){isVideo=true}else if(typeof HTMLImageElement!=="undefined"&&pixels instanceof HTMLImageElement){isImage=true}else if(pixels.getContext!=null){isCanvasLike=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 "+pixels.constructor.name))}if(isVideo){var HAVE_CURRENT_DATA_READY_STATE=2;if(isVideo&&pixels.readyState element.")}}var kernel=getKernel(FromPixels,ENGINE.backendName);if(kernel!=null){var inputs={pixels};var attrs={numChannels};return ENGINE.runKernel(FromPixels,inputs,attrs)}var _a=isVideo?[pixels.videoWidth,pixels.videoHeight]:[pixels.width,pixels.height],width=_a[0],height=_a[1];var vals;if(isCanvasLike){vals=pixels.getContext("2d").getImageData(0,0,width,height).data}else if(isImageData||isPixelData){vals=pixels.data}else if(isImage||isVideo){if(fromPixels2DContext==null){fromPixels2DContext=document.createElement("canvas").getContext("2d")}fromPixels2DContext.canvas.width=width;fromPixels2DContext.canvas.height=height;fromPixels2DContext.drawImage(pixels,0,0,width,height);vals=fromPixels2DContext.getImageData(0,0,width,height).data}var values;if(numChannels===4){values=new Int32Array(vals)}else{var numPixels=width*height;values=new Int32Array(numPixels*numChannels);for(var i=0;i4||depth===2){throw new Error("toPixels only supports depth of size "+("1, 3 or 4 but got "+depth))}if($img.dtype!=="float32"&&$img.dtype!=="int32"){throw new Error("Unsupported type for toPixels: "+$img.dtype+". Please use float32 or int32 tensors.")}return[4,$img.data()];case 1:data2=_b.sent();multiplier=$img.dtype==="float32"?255:1;bytes=new Uint8ClampedArray(width*height*4);for(i=0;i1){throw new Error("Tensor values for a float32 Tensor must be in the "+("range [0 - 1] but encountered "+value+"."))}}else if($img.dtype==="int32"){if(value<0||value>255){throw new Error("Tensor values for a int32 Tensor must be in the "+("range [0 - 255] but encountered "+value+"."))}}if(depth===1){rgba[0]=value*multiplier;rgba[1]=value*multiplier;rgba[2]=value*multiplier}else{rgba[d]=value*multiplier}}j=i*4;bytes[j+0]=Math.round(rgba[0]);bytes[j+1]=Math.round(rgba[1]);bytes[j+2]=Math.round(rgba[2]);bytes[j+3]=Math.round(rgba[3])}if(canvas!=null){canvas.width=width;canvas.height=height;ctx=canvas.getContext("2d");imageData=new ImageData(bytes,width,height);ctx.putImageData(imageData,0,0)}if($img!==img){$img.dispose()}return[2,bytes]}})})}var fromPixels=op({fromPixels_});var browser={__proto__:null,toPixels,fromPixels};function prepareAndValidate(tensor2,indices){if(tensor2.rank<1){throw new Error("tf.gatherND() expects the input to be rank 1 or higher,"+(" but the rank was "+tensor2.rank+"."))}if(indices.rank<1){throw new Error("tf.gatherND() expects the indices to be rank 1 or higher,"+(" but the rank was "+indices.rank+"."))}if(indices.dtype!=="int32"){throw new Error("tf.gatherND() expects the indices to be int32 type,"+(" but the dtype was "+indices.dtype+"."))}if(indices.shape[indices.rank-1]>tensor2.rank){throw new Error("index innermost dimension length must be <= tensor rank; saw: "+(indices.shape[indices.rank-1]+" vs. "+tensor2.rank))}if(tensor2.size===0){throw new Error("Requested more than 0 entries, but input is empty."+(" Input shape: "+tensor2.shape+"."))}var indicesShape=indices.shape;var sliceRank=indicesShape[indicesShape.length-1];var nResult=1;for(var i=0;i1?indices.shape[indices.rank-1]:1;var batchDim=indices.rank>1?indices.rank-1:1;var shapeError="Must have updates.shape = indices.shape[:batchDim] + "+("shape[sliceDim:], got updates.shape: "+updates.shape)+(", indices.shape: "+indices.shape+", shape: "+shape)+(", sliceDim: "+sliceDim+", and batchDim: "+batchDim+".");if(updates.rank1?indices.shape[indicesRank-1]:1;var totalNd=shape.length;var sliceSize=1;for(var i=sliceRank;i0){if(mask&1){axes.push(axis)}mask/=2;axis++}return axes}function computeOutShape2(begin,end,strides){var size=[];for(var axis=0;axis0){var fullIndex=ellipsisAxes[0];var numElidedAxes=numInterpolatedAxes+1;normalizedBegin=startIndicesWithElidedDims(beginMask,fullIndex,numElidedAxes,begin,inputShape);normalizedEnd=stopIndicesWithElidedDims(endMask,fullIndex,numElidedAxes,end,inputShape);normalizedStrides=stridesWithElidedDims(strides,fullIndex,numElidedAxes,inputShape)}else{for(var axis=0;axis-1){newIndices[axis]=0}else{var originalAxis=unnormalizeAxis(ellipsisInsertionIndex,numElidedAxes,axis);var originalValue=originalBegin[originalAxis];if(beginMask&1<-1){newIndices[axis]=Number.MAX_SAFE_INTEGER}else{var originalAxis=unnormalizeAxis(ellipsisInsertionIndex,numElidedAxes,axis);var originalValue=originalEnd[originalAxis];if(endMask&1<0){start=Number.MIN_SAFE_INTEGER}else{start=Number.MAX_SAFE_INTEGER}}var axisSize=inputShape[axis];if(start<0){start+=axisSize}start=clamp(0,start,axisSize-1);return start}function stopForAxis(endMask,stopIndices,strides,inputShape,axis,ellipsisMask){var stop=stopIndices[axis];var stride=strides[axis]||1;if(endMask&1<0){stop=Number.MAX_SAFE_INTEGER}else{stop=Number.MIN_SAFE_INTEGER}}var axisSize=inputShape[axis];if(stop<0){stop+=axisSize}if(stride>0){stop=clamp(0,stop,axisSize)}else{stop=clamp(-1,stop,axisSize-1)}return stop}function isSliceContinous(shape,begin,size){var firstNonOneAxis=size.length;for(var i=0;i1){firstNonOneAxis=i;break}}for(var i=firstNonOneAxis+1;i0||size[i]!==shape[i]){return false}}return true}function computeFlatOffset(begin,strides){var flatOffset=begin.length>0?begin[begin.length-1]:1;for(var i=0;i=0){return d}else{assert(d===-1,function(){return"Negative size values should be exactly -1 but got "+(d+" for the slice() size at index "+i+".")});return x.shape[i]-begin_[i]}});return[begin_,size_]}var slice_util2={__proto__:null,assertParamsValid,maskToAxes,computeOutShape:computeOutShape2,stridesWithElidedDims,getNormalizedAxes,startIndicesWithElidedDims,stopIndicesWithElidedDims,stridesForAxis,startForAxis,stopForAxis,isSliceContinous,computeFlatOffset,parseSliceParams};var Serializable=function(){function Serializable2(){}Serializable2.prototype.getClassName=function(){return this.constructor.className};Serializable2.fromConfig=function(cls,config2){return new cls(config2)};return Serializable2}();var SerializationMap=function(){function SerializationMap2(){this.classNameMap={}}SerializationMap2.getMap=function(){if(SerializationMap2.instance==null){SerializationMap2.instance=new SerializationMap2}return SerializationMap2.instance};SerializationMap2.register=function(cls){SerializationMap2.getMap().classNameMap[cls.className]=[cls,cls.fromConfig]};return SerializationMap2}();function registerClass(cls){assert(cls.className!=null,function(){return"Class being registered does not have the static className property defined."});assert(typeof cls.className==="string",function(){return"className is required to be a string, but got type "+typeof cls.className});assert(cls.className.length>0,function(){return"Class being registered has an empty-string as its className, which is disallowed."});SerializationMap.register(cls)}var serialization={__proto__:null,Serializable,SerializationMap,registerClass};var TEST_EPSILON_FLOAT32=.001;var TEST_EPSILON_FLOAT16=.1;function expectArraysClose(actual,expected,epsilon){if(epsilon==null){epsilon=testEpsilon()}return expectArraysPredicate(actual,expected,function(a,b){return areClose(a,b,epsilon)})}function testEpsilon(){return ENGINE.backend.floatPrecision()===32?TEST_EPSILON_FLOAT32:TEST_EPSILON_FLOAT16}function expectArraysPredicate(actual,expected,predicate){var checkClassType=true;if(isTypedArray(actual)||isTypedArray(expected)){checkClassType=false}if(isTypedArray(actual)&&isTypedArray(expected)){checkClassType=true}if(checkClassType){var aType=actual.constructor.name;var bType=expected.constructor.name;if(aType!==bType){throw new Error("Arrays are of different type. Actual: "+aType+". "+("Expected: "+bType))}}if(Array.isArray(actual)&&Array.isArray(expected)){var actualShape=inferShape(actual);var expectedShape=inferShape(expected);if(!arraysEqual(actualShape,expectedShape)){throw new Error("Arrays have different shapes. "+("Actual: ["+actualShape+"]. Expected: ["+expectedShape+"]"))}}var actualFlat=isTypedArray(actual)?actual:flatten(actual);var expectedFlat=isTypedArray(expected)?expected:flatten(expected);if(actualFlat.length!==expectedFlat.length){throw new Error("Arrays have different lengths actual: "+actualFlat.length+" vs "+("expected: "+expectedFlat.length+".\n")+("Actual: "+actualFlat+".\n")+("Expected: "+expectedFlat+"."))}for(var i=0;iepsilon){return false}return true}function expectValuesInRange(actual,low,high){for(var i=0;ihigh){throw new Error("Value out of range:"+actual[i]+" low: "+low+", high: "+high)}}}function expectArrayBuffersEqual(actual,expected){expect(new Float32Array(actual)).toEqual(new Float32Array(expected))}var test_util={__proto__:null,TEST_EPSILON_FLOAT16,expectArraysClose,testEpsilon,expectPromiseToFail,expectArraysEqual,expectNumbersClose,expectValuesInRange,expectArrayBuffersEqual};var version5="2.7.0";function enableProdMode(){env3().set("PROD",true)}function enableDebugMode(){env3().set("DEBUG",true)}function disableDeprecationWarnings(){env3().set("DEPRECATION_WARNINGS_ENABLED",false);console.warn("TensorFlow.js deprecation warnings have been disabled.")}function deprecationWarn2(msg){if(env3().getBool("DEPRECATION_WARNINGS_ENABLED")){console.warn(msg+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}}function disposeVariables(){ENGINE.disposeVariables()}function engine2(){return ENGINE}function memory(){return ENGINE.memory()}function profile2(f){return ENGINE.profile(f)}function tidy(nameOrFn,fn){return ENGINE.tidy(nameOrFn,fn)}function dispose(container){var tensors=getTensorsInContainer(container);tensors.forEach(function(tensor2){return tensor2.dispose()})}function keep(result){return ENGINE.keep(result)}function time(f){return ENGINE.time(f)}function setBackend(backendName){return ENGINE.setBackend(backendName)}function ready(){return ENGINE.ready()}function getBackend(){return ENGINE.backendName}function removeBackend(name){ENGINE.removeBackend(name)}function findBackend(name){return ENGINE.findBackend(name)}function findBackendFactory(name){return ENGINE.findBackendFactory(name)}function registerBackend2(name,factory,priority){if(priority===void 0){priority=1}return ENGINE.registerBackend(name,factory,priority)}function backend(){return ENGINE.backend}function setPlatform(platformName,platform){env3().setPlatform(platformName,platform)}function add_(a,b){var _a;var $a=convertToTensor(a,"a","add");var $b=convertToTensor(b,"b","add");_a=makeTypesMatch($a,$b),$a=_a[0],$b=_a[1];var forward=function(backend2,save){var res=backend2.add($a,$b);save([$a,$b]);return res};var inputs={a:$a,b:$b};return ENGINE.runKernelFunc(forward,inputs,null,Add3)}var add$1=op({add_});function floorDiv_(a,b){var _a;var $a=convertToTensor(a,"a","floorDiv");var $b=convertToTensor(b,"b","floorDiv");_a=makeTypesMatch($a,$b),$a=_a[0],$b=_a[1];var forward=function(backend2,save){var res=backend2.floorDiv($a,$b);save([$a,$b]);return res};var inputs={a:$a,b:$b};return ENGINE.runKernelFunc(forward,inputs,null,FloorDiv3)}var floorDiv=op({floorDiv_});function div_(a,b){var _a;var $a=convertToTensor(a,"a","div");var $b=convertToTensor(b,"b","div");_a=makeTypesMatch($a,$b),$a=_a[0],$b=_a[1];if($a.dtype==="int32"&&$b.dtype==="int32"){return floorDiv($a,$b)}var forward=function(backend2,save){var res=backend2.realDivide($a,$b);save([$a,$b]);return res};var inputs={a:$a,b:$b};var attrs={};return ENGINE.runKernelFunc(forward,inputs,null,Div3,attrs)}var div=op({div_});function mul_(a,b){var _a;var $a=convertToTensor(a,"a","mul");var $b=convertToTensor(b,"b","mul");_a=makeTypesMatch($a,$b),$a=_a[0],$b=_a[1];var forward=function(backend2,save){var res=backend2.multiply($a,$b);save([$a,$b]);return res};var inputs={a:$a,b:$b};return ENGINE.runKernelFunc(forward,inputs,null,Multiply3)}var mul=op({mul_});function abs_(x){var $x=convertToTensor(x,"x","abs");var inputs={x:$x};return ENGINE.runKernelFunc(function(backend2,save){save([$x]);if($x.dtype==="complex64"){return backend2.complexAbs($x)}return backend2.abs($x)},inputs,null,Abs3)}var abs=op({abs_});function acos_(x){var $x=convertToTensor(x,"x","acos");var inputs={x:$x};return ENGINE.runKernelFunc(function(backend2,save){var res=backend2.acos($x);save([$x]);return res},inputs,null,Acos)}var acos=op({acos_});function acosh_(x){var $x=convertToTensor(x,"x","acosh");var inputs={x:$x};return ENGINE.runKernelFunc(function(backend2,save){var res=backend2.acosh($x);save([$x]);return res},inputs,null,Acosh)}var acosh=op({acosh_});function addN_(tensors){assert(Array.isArray(tensors),function(){return"The argument passed to tf.addN() must be a list of tensors"});assert(tensors.length>=1,function(){return"Must pass at least one tensor to tf.addN(), but got "+(""+tensors.length)});var $tensors=tensors.map(function(t,i){return convertToTensor(t,"tensors"+i,"addN")});var firstTensor=$tensors[0];$tensors.forEach(function(t){if(t.dtype!==firstTensor.dtype){throw new Error("All tensors passed to tf.addN() must have the same dtype")}});$tensors.forEach(function(t){if(!arraysEqual(t.shape,firstTensor.shape)){throw new Error("All tensors passed to tf.addN() must have the same shape")}});var forward=function(backend2,save){var res=backend2.addN($tensors);save($tensors);return res};var inputs=$tensors;return ENGINE.runKernelFunc(forward,inputs,null,AddN3)}var addN=op({addN_});function axesAreInnerMostDims(axes,rank){for(var i=0;i=0&&axis=1,function(){return"Pass at least one tensor to concat"});var $tensors=convertToTensorArray(tensors,"tensors","concat");if($tensors[0].dtype==="complex64"){$tensors.forEach(function(tensor2){if(tensor2.dtype!=="complex64"){throw new Error("Cannot concatenate complex64 tensors with a tensor\n with dtype "+tensor2.dtype+". ")}})}var forward=function(backend2,save){var $axis=parseAxisParam(axis,$tensors[0].shape)[0];var outShape=computeOutShape$1($tensors.map(function(t){return t.shape}),$axis);if(sizeFromShape(outShape)===0){return tensor([],outShape)}$tensors=$tensors.filter(function(t){return t.size>0});if($tensors.length===1){return $tensors[0]}var shapes=$tensors.map(function(t){return t.shape});assertParamsConsistent(shapes,$axis);var res=backend2.concat($tensors,$axis);save($tensors);return res};var inputs=$tensors;var attr={axis};return ENGINE.runKernelFunc(forward,inputs,null,Concat3,attr)}var concat2=op({concat_});function sigmoid_(x){var $x=convertToTensor(x,"x","sigmoid");var inputs={x:$x};return ENGINE.runKernelFunc(function(backend2,save){var res=backend2.sigmoid($x);save([res]);return res},inputs,null,Sigmoid3)}var sigmoid2=op({sigmoid_});function slice_(x,begin,size){var $x=convertToTensor(x,"x","slice");if($x.rank===0){throw new Error("Slicing scalar is not possible")}var forward=function(backend2,save){var _a=parseSliceParams($x,begin,size),begin_=_a[0],size_=_a[1];assertParamsValid($x,begin_,size_);save([$x]);return backend2.slice($x,begin_,size_)};var inputs={x:$x};var attrs={begin,size};return ENGINE.runKernelFunc(forward,inputs,null,Slice6,attrs)}var slice2=op({slice_});function tanh_(x){var $x=convertToTensor(x,"x","tanh");var inputs={x:$x};return ENGINE.runKernelFunc(function(backend2,save){var y=backend2.tanh($x);save([y]);return y},inputs,null,Tanh3)}var tanh$1=op({tanh_});function basicLSTMCell_(forgetBias,lstmKernel,lstmBias,data2,c,h){var $forgetBias=convertToTensor(forgetBias,"forgetBias","basicLSTMCell");var $lstmKernel=convertToTensor(lstmKernel,"lstmKernel","basicLSTMCell");var $lstmBias=convertToTensor(lstmBias,"lstmBias","basicLSTMCell");var $data=convertToTensor(data2,"data","basicLSTMCell");var $c=convertToTensor(c,"c","basicLSTMCell");var $h=convertToTensor(h,"h","basicLSTMCell");var combined=concat2([$data,$h],1);var weighted=matMul(combined,$lstmKernel);var res=add$1(weighted,$lstmBias);var batchSize=res.shape[0];var sliceCols=res.shape[1]/4;var sliceSize=[batchSize,sliceCols];var i=slice2(res,[0,0],sliceSize);var j=slice2(res,[0,sliceCols],sliceSize);var f=slice2(res,[0,sliceCols*2],sliceSize);var o=slice2(res,[0,sliceCols*3],sliceSize);var newC=add$1(mul(sigmoid2(i),tanh$1(j)),mul($c,sigmoid2(add$1($forgetBias,f))));var newH=mul(tanh$1(newC),sigmoid2(o));return[newC,newH]}var basicLSTMCell=op({basicLSTMCell_});function batchToSpaceND_(x,blockShape,crops){var $x=convertToTensor(x,"x","batchToSpaceND");var prod2=blockShape.reduce(function(a,b){return a*b});assert($x.rank>=1+blockShape.length,function(){return"input rank is "+$x.rank+" but should be > than blockShape.length "+blockShape.length});assert(crops.length===blockShape.length,function(){return"crops.length is "+crops.length+" but should be equal to blockShape.length "+blockShape.length});assert($x.shape[0]%prod2===0,function(){return"input tensor batch is "+$x.shape[0]+" but is not divisible by the product of "+("the elements of blockShape "+blockShape.join(" * ")+" === "+prod2)});var forward=function(backend2){return backend2.batchToSpaceND($x,blockShape,crops)};var inputs={x:$x};var attrs={blockShape,crops};return ENGINE.runKernelFunc(forward,inputs,null,BatchToSpaceND,attrs)}var batchToSpaceND=op({batchToSpaceND_});function xAs4D(x){var x4D;if(x.rank===0||x.rank===1){x4D=reshape2(x,[1,1,1,x.size])}else if(x.rank===2){x4D=reshape2(x,[1,1,x.shape[0],x.shape[1]])}else if(x.rank===3){x4D=reshape2(x,[1,x.shape[0],x.shape[1],x.shape[2]])}else{x4D=x}return x4D}function batchNorm_(x,mean2,variance,offset,scale,varianceEpsilon){if(varianceEpsilon==null){varianceEpsilon=.001}var $x=convertToTensor(x,"x","batchNorm");var $mean=convertToTensor(mean2,"mean","batchNorm");var $variance=convertToTensor(variance,"variance","batchNorm");var $scale;if(scale!=null){$scale=convertToTensor(scale,"scale","batchNorm")}var $offset;if(offset!=null){$offset=convertToTensor(offset,"offset","batchNorm")}assert($mean.rank===$variance.rank,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."});assert($offset==null||$mean.rank===$offset.rank,function(){return"Batch normalization gradient requires mean and offset to have equal ranks."});assert($scale==null||$mean.rank===$scale.rank,function(){return"Batch normalization gradient requires mean and scale to have equal ranks."});var x4D=xAs4D($x);var forward=function(backend2,save){save([x4D,$mean,$variance,$scale]);return backend2.batchNorm(x4D,as1DOr4D($mean),as1DOr4D($variance),as1DOr4D($offset),as1DOr4D($scale),varianceEpsilon)};var inputs={x:x4D,scale:$scale,offset:$offset,mean:$mean,variance:$variance};var attrs={varianceEpsilon};var res=ENGINE.runKernelFunc(forward,inputs,null,FusedBatchNorm3,attrs);return reshape2(res,$x.shape)}function as1DOr4D(x){if(x==null){return null}if(x.rank===0){return reshape2(x,[x.size])}else if(x.rank===1){return x}else if(x.rank===2){return reshape2(x,[1,1,x.shape[0],x.shape[1]])}else if(x.rank===3){return reshape2(x,[1,x.shape[0],x.shape[1],x.shape[2]])}return x}var batchNorm=op({batchNorm_});function batchNorm2d_(x,mean2,variance,offset,scale,varianceEpsilon){var $x=convertToTensor(x,"x","batchNorm");var $mean=convertToTensor(mean2,"mean","batchNorm");var $variance=convertToTensor(variance,"variance","batchNorm");var $scale;if(scale!=null){$scale=convertToTensor(scale,"scale","batchNorm")}var $offset;if(offset!=null){$offset=convertToTensor(offset,"offset","batchNorm")}assert($x.rank===2,function(){return"Error in batchNorm2D: x must be rank 2 but got rank "+($x.rank+".")});assert($mean.rank===2||$mean.rank===1,function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but "+("got rank "+$mean.rank+".")});assert($variance.rank===2||$variance.rank===1,function(){return"Error in batchNorm2D: variance must be rank 2 or rank 1 "+("but got rank "+$variance.rank+".")});if($scale!=null){assert($scale.rank===2||$scale.rank===1,function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 "+("but got rank "+$scale.rank+".")})}if($offset!=null){assert($offset.rank===2||$offset.rank===1,function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 "+("but got rank "+$offset.rank+".")})}return batchNorm($x,$mean,$variance,$offset,$scale,varianceEpsilon)}var batchNorm2d=op({batchNorm2d_});function batchNorm3d_(x,mean2,variance,offset,scale,varianceEpsilon){var $x=convertToTensor(x,"x","batchNorm");var $mean=convertToTensor(mean2,"mean","batchNorm");var $variance=convertToTensor(variance,"variance","batchNorm");var $scale;if(scale!=null){$scale=convertToTensor(scale,"scale","batchNorm")}var $offset;if(offset!=null){$offset=convertToTensor(offset,"offset","batchNorm")}assert($x.rank===3,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+($x.rank+".")});assert($mean.rank===3||$mean.rank===1,function(){return"Error in batchNorm3D: mean must be rank 3 or rank 1 but "+("got rank "+$mean.rank+".")});assert($variance.rank===3||$variance.rank===1,function(){return"Error in batchNorm3D: variance must be rank 3 or rank 1 "+("but got rank "+$variance.rank+".")});if($scale!=null){assert($scale.rank===3||$scale.rank===1,function(){return"Error in batchNorm3D: scale must be rank 3 or rank 1 "+("but got rank "+$scale.rank+".")})}if($offset!=null){assert($offset.rank===3||$offset.rank===1,function(){return"Error in batchNorm3D: offset must be rank 3 or rank 1 "+("but got rank "+$offset.rank+".")})}return batchNorm($x,$mean,$variance,$offset,$scale,varianceEpsilon)}var batchNorm3d=op({batchNorm3d_});function batchNorm4d_(x,mean2,variance,offset,scale,varianceEpsilon){var $x=convertToTensor(x,"x","batchNorm");var $mean=convertToTensor(mean2,"mean","batchNorm");var $variance=convertToTensor(variance,"variance","batchNorm");var $scale;if(scale!=null){$scale=convertToTensor(scale,"scale","batchNorm")}var $offset;if(offset!=null){$offset=convertToTensor(offset,"offset","batchNorm")}assert($x.rank===4,function(){return"Error in batchNorm4D: x must be rank 4 but got rank "+($x.rank+".")});assert($mean.rank===4||$mean.rank===1,function(){return"Error in batchNorm4D: mean must be rank 4 or rank 1 but "+("got rank "+$mean.rank+".")});assert($variance.rank===4||$variance.rank===1,function(){return"Error in batchNorm4D: variance must be rank 4 or rank 1 "+("but got rank "+$variance.rank+".")});if($scale!=null){assert($scale.rank===4||$scale.rank===1,function(){return"Error in batchNorm4D: scale must be rank 4 or rank 1 "+("but got rank "+$scale.rank+".")})}if($offset!=null){assert($offset.rank===4||$offset.rank===1,function(){return"Error in batchNorm4D: offset must be rank 4 or rank 1 "+("but got rank "+$offset.rank+".")})}return batchNorm($x,$mean,$variance,$offset,$scale,varianceEpsilon)}var batchNorm4d=op({batchNorm4d_});function broadcastTo_(x,shape){var input=convertToTensor(x,"broadcastTo","x");var xShape=input.shape;if(shape.some(function(d){return!(d>0)||d%1!==0})){throw new Error("broadcastTo(): Invalid broadcast shape ["+shape+"].")}if(shape.lengthinput.rank){var newShape=input.shape.slice();while(newShape.length=0;i--){if(inputShape[i]===shape[i]){reps[i]=1}else if(input.shape[i]!==1){throw new Error("broadcastTo(): ["+xShape+"] cannot be broadcast to ["+shape+"].")}}var axes=reps.map(function(n,i2){return n>1?i2:-1}).filter(function(i2){return i2>=0});if(axes.length===0){return clone(input)}var forward=function(backend2){return backend2.tile(input,reps)};var inputs={x:input};var attrs={shape,inputShape};return ENGINE.runKernelFunc(forward,inputs,null,BroadcastTo,attrs)}var broadcastTo=op({broadcastTo_});function ceil_(x){var $x=convertToTensor(x,"x","ceil");var inputs={x:$x};return ENGINE.runKernelFunc(function(backend2){return backend2.ceil($x)},inputs,null,Ceil)}var ceil=op({ceil_});function clipByValue_(x,clipValueMin,clipValueMax){var $x=convertToTensor(x,"x","clipByValue");assert(clipValueMin<=clipValueMax,function(){return"Error in clip: min ("+clipValueMin+") must be "+("less than or equal to max ("+clipValueMax+").")});var inputs={x:$x};var attrs={clipValueMin,clipValueMax};return ENGINE.runKernelFunc(function(backend2,save){var res=backend2.clip($x,clipValueMin,clipValueMax);save([$x]);return res},inputs,null,ClipByValue3,attrs)}var clipByValue=op({clipByValue_});function concat1d_(tensors){return concat2(tensors,0)}var concat1d=op({concat1d_});function concat2d_(tensors,axis){return concat2(tensors,axis)}var concat2d=op({concat2d_});function concat3d_(tensors,axis){return concat2(tensors,axis)}var concat3d=op({concat3d_});function concat4d_(tensors,axis){return concat2(tensors,axis)}var concat4d=op({concat4d_});function conv2d_(x,filter,strides,pad3,dataFormat,dilations,dimRoundingMode){if(dataFormat===void 0){dataFormat="NHWC"}if(dilations===void 0){dilations=[1,1]}var $x=convertToTensor(x,"x","conv2d");var $filter=convertToTensor(filter,"filter","conv2d");var x4D=$x;var reshapedTo4D=false;if($x.rank===3){reshapedTo4D=true;x4D=reshape2($x,[1,$x.shape[0],$x.shape[1],$x.shape[2]])}assert(x4D.rank===4,function(){return"Error in conv2d: input must be rank 4, but got rank "+x4D.rank+"."});assert($filter.rank===4,function(){return"Error in conv2d: filter must be rank 4, but got rank "+($filter.rank+".")});if(dimRoundingMode!=null){assert(isInt(pad3),function(){return"Error in conv2d: pad must be an integer when using, "+("dimRoundingMode "+dimRoundingMode+" but got pad "+pad3+".")})}var inDepth=dataFormat==="NHWC"?x4D.shape[3]:x4D.shape[1];assert(inDepth===$filter.shape[2],function(){return"Error in conv2d: depth of input ("+inDepth+") must match "+("input depth for filter "+$filter.shape[2]+".")});assert(eitherStridesOrDilationsAreOne(strides,dilations),function(){return"Error in conv2D: Either strides or dilations must be 1. "+("Got strides "+strides+" and dilations '"+dilations+"'")});var forward=function(backend2,save){var $dataFormat=convertConv2DDataFormat(dataFormat);var convInfo=computeConv2DInfo(x4D.shape,$filter.shape,strides,dilations,pad3,dimRoundingMode,false,$dataFormat);var res2=backend2.conv2d(x4D,$filter,convInfo);save([x4D,$filter]);return res2};var inputs={x:x4D,filter:$filter};var attrs={strides,pad:pad3,dataFormat,dilations,dimRoundingMode};var res=ENGINE.runKernelFunc(forward,inputs,null,Conv2D3,attrs);if(reshapedTo4D){return reshape2(res,[res.shape[1],res.shape[2],res.shape[3]])}return res}var conv2d2=op({conv2d_});function conv1d_(x,filter,stride,pad3,dataFormat,dilation,dimRoundingMode){if(dataFormat===void 0){dataFormat="NWC"}if(dilation===void 0){dilation=1}var $x=convertToTensor(x,"x","conv1d");var $filter=convertToTensor(filter,"filter","conv1d");var x3D=$x;var reshapedTo3D=false;if($x.rank===2){reshapedTo3D=true;x3D=reshape2($x,[1,$x.shape[0],$x.shape[1]])}assert(x3D.rank===3,function(){return"Error in conv1d: input must be rank 3, but got rank "+x3D.rank+"."});assert($filter.rank===3,function(){return"Error in conv1d: filter must be rank 3, but got rank "+($filter.rank+".")});if(dimRoundingMode!=null){assert(isInt(pad3),function(){return"Error in conv1d: pad must be an integer when using, "+("dimRoundingMode "+dimRoundingMode+" but got pad "+pad3+".")})}assert(x3D.shape[2]===$filter.shape[1],function(){return"Error in conv1d: depth of input ("+x3D.shape[2]+") must match "+("input depth for filter "+$filter.shape[1]+".")});assert(eitherStridesOrDilationsAreOne(stride,dilation),function(){return"Error in conv1D: Either stride or dilation must be 1. "+("Got stride "+stride+" and dilation '"+dilation+"'")});assert(dataFormat==="NWC",function(){return"Error in conv1d: got dataFormat of "+dataFormat+" but only NWC is currently supported."});var filter4D=reshape2($filter,[1,$filter.shape[0],$filter.shape[1],$filter.shape[2]]);var input4D=reshape2(x3D,[x3D.shape[0],1,x3D.shape[1],x3D.shape[2]]);var strides=[1,stride];var dilations=[1,dilation];var conv2dDataFormat="NHWC";var res=conv2d2(input4D,filter4D,strides,pad3,conv2dDataFormat,dilations,dimRoundingMode);if(reshapedTo3D){return reshape2(res,[res.shape[2],res.shape[3]])}return reshape2(res,[res.shape[0],res.shape[2],res.shape[3]])}var conv1d=op({conv1d_});function conv2DBackpropInput_(xShape,dy,filter,strides,pad3,dataFormat,dimRoundingMode){if(dataFormat===void 0){dataFormat="NHWC"}assert(xShape.length===dy.rank,function(){return"Length of inShape "+("("+xShape.length+") and rank of dy ("+dy.rank+") must match")});var xShape4D=xShape;var dy4D=dy;var reshapedTo4D=false;if(dy.rank===3){reshapedTo4D=true;dy4D=reshape2(dy,[1,dy.shape[0],dy.shape[1],dy.shape[2]]);xShape4D=[1,xShape[0],xShape[1],xShape[2]]}assert(xShape4D.length===4,function(){return"Error in conv2dDerInput: inShape must be length 4, but got length "+(xShape4D.length+".")});assert(dy4D.rank===4,function(){return"Error in conv2dDerInput: dy must be rank 4, but got "+("rank "+dy4D.rank)});assert(filter.rank===4,function(){return"Error in conv2dDerInput: filter must be rank 4, but got "+("rank "+filter.rank)});var inDepth=dataFormat==="NHWC"?xShape4D[3]:xShape4D[1];var outDepth=dataFormat==="NHWC"?dy4D.shape[3]:dy4D.shape[1];assert(inDepth===filter.shape[2],function(){return"Error in conv2dDerInput: depth of input ("+inDepth+") must "+("match input depth for filter "+filter.shape[2]+".")});assert(outDepth===filter.shape[3],function(){return"Error in conv2dDerInput: depth of output ("+outDepth+") must "+("match output depth for filter "+filter.shape[3]+".")});if(dimRoundingMode!=null){assert(isInt(pad3),function(){return"Error in conv2dDerInput: pad must be an integer when using, "+("dimRoundingMode "+dimRoundingMode+" but got pad "+pad3+".")})}var forward=function(backend2,save){var dilations=1;var $dataFormat=convertConv2DDataFormat(dataFormat);var convInfo=computeConv2DInfo(xShape4D,filter.shape,strides,dilations,pad3,dimRoundingMode,false,$dataFormat);var res2=backend2.conv2dDerInput(dy4D,filter,convInfo);save([dy4D,filter]);return res2};var inputs={dy:dy4D,filter};var attrs={strides,pad:pad3,dataFormat,dimRoundingMode,inputShape:xShape4D};var res=ENGINE.runKernelFunc(forward,inputs,null,Conv2DBackpropInput3,attrs);if(reshapedTo4D){return reshape2(res,[res.shape[1],res.shape[2],res.shape[3]])}return res}var conv2DBackpropInput2=op({conv2DBackpropInput_});function conv2dTranspose_(x,filter,outputShape,strides,pad3,dimRoundingMode){var $x=convertToTensor(x,"x","conv2dTranspose");var $filter=convertToTensor(filter,"filter","conv2dTranspose");return conv2DBackpropInput2(outputShape,$x,$filter,strides,pad3,"NHWC",dimRoundingMode)}var conv2dTranspose=op({conv2dTranspose_});function conv3d_(x,filter,strides,pad3,dataFormat,dilations){if(dataFormat===void 0){dataFormat="NDHWC"}if(dilations===void 0){dilations=[1,1,1]}var $x=convertToTensor(x,"x","conv3d");var $filter=convertToTensor(filter,"filter","conv3d");var x5D=$x;var reshapedTo5D=false;if($x.rank===4){reshapedTo5D=true;x5D=reshape2($x,[1,$x.shape[0],$x.shape[1],$x.shape[2],$x.shape[3]])}assert(x5D.rank===5,function(){return"Error in conv3d: input must be rank 5, but got rank "+x5D.rank+"."});assert($filter.rank===5,function(){return"Error in conv3d: filter must be rank 5, but got rank "+($filter.rank+".")});assert(x5D.shape[4]===$filter.shape[3],function(){return"Error in conv3d: depth of input ("+x5D.shape[4]+") must match "+("input depth for filter "+$filter.shape[3]+".")});assert(eitherStridesOrDilationsAreOne(strides,dilations),function(){return"Error in conv3D: Either strides or dilations must be 1. "+("Got strides "+strides+" and dilations '"+dilations+"'")});assert(dataFormat==="NDHWC",function(){return"Error in conv3d: got dataFormat of "+dataFormat+" but only NDHWC is currently supported."});var forward=function(backend2,save){var convInfo=computeConv3DInfo(x5D.shape,$filter.shape,strides,dilations,pad3);var res2=backend2.conv3d(x5D,$filter,convInfo);save([x5D,$filter]);return res2};var inputs={x:x5D,filter:$filter};var attrs={strides,pad:pad3,dataFormat,dilations};var res=ENGINE.runKernelFunc(forward,inputs,null,Conv3D,attrs);if(reshapedTo5D){return reshape2(res,[res.shape[1],res.shape[2],res.shape[3],res.shape[4]])}return res}var conv3d=op({conv3d_});function conv3DBackpropInput_(xShape,dy,filter,strides,pad3){assert(xShape.length===dy.rank,function(){return"Length of inShape "+("("+xShape.length+") and rank of dy ("+dy.rank+") must match")});var xShape5D=xShape;var dy5D=dy;var reshapedTo5D=false;if(dy.rank===4){reshapedTo5D=true;dy5D=reshape2(dy,[1,dy.shape[0],dy.shape[1],dy.shape[2],dy.shape[3]]);xShape5D=[1,xShape[0],xShape[1],xShape[2],xShape[3]]}var inDepth=xShape5D[4];var outDepth=dy5D.shape[4];assert(xShape5D.length===5,function(){return"Error in conv3dDerInput: inShape must be length 5, but got length "+(xShape5D.length+".")});assert(dy5D.rank===5,function(){return"Error in conv3dDerInput: dy must be rank 5, but got "+("rank "+dy5D.rank)});assert(filter.rank===5,function(){return"Error in conv3dDerInput: filter must be rank 5, but got "+("rank "+filter.rank)});assert(inDepth===filter.shape[3],function(){return"Error in conv3dDerInput: depth of input ("+inDepth+") must "+("match input depth for filter "+filter.shape[3]+".")});assert(outDepth===filter.shape[4],function(){return"Error in conv3dDerInput: depth of output ("+outDepth+") must "+("match output depth for filter "+filter.shape[4]+".")});var forward=function(backend2){var dilations=1;var convInfo=computeConv3DInfo(xShape5D,filter.shape,strides,dilations,pad3);return backend2.conv3dDerInput(dy5D,filter,convInfo)};var inputs={dy:dy5D,filter};var attrs={pad:pad3,strides,inputShape:xShape5D};var res=ENGINE.runKernelFunc(forward,inputs,null,Conv3DBackpropInputV2,attrs);if(reshapedTo5D){return reshape2(res,[res.shape[1],res.shape[2],res.shape[3],res.shape[4]])}return res}var conv3DBackpropInput=op({conv3DBackpropInput_});function conv3dTranspose_(x,filter,outputShape,strides,pad3){var $x=convertToTensor(x,"x","conv3dTranspose");var $filter=convertToTensor(filter,"filter","conv3dTranspose");return conv3DBackpropInput(outputShape,$x,$filter,strides,pad3)}var conv3dTranspose=op({conv3dTranspose_});function cos_(x){var $x=convertToTensor(x,"x","cos");var inputs={x:$x};return ENGINE.runKernelFunc(function(backend2,save){var res=backend2.cos($x);save([$x]);return res},inputs,null,Cos3)}var cos=op({cos_});function cosh_(x){var $x=convertToTensor(x,"x","cosh");var inputs={x:$x};return ENGINE.runKernelFunc(function(backend2,save){var res=backend2.cosh($x);save([$x]);return res},inputs,null,Cosh)}var cosh=op({cosh_});function cumsum_(x,axis,exclusive,reverse3){if(axis===void 0){axis=0}if(exclusive===void 0){exclusive=false}if(reverse3===void 0){reverse3=false}var $x=convertToTensor(x,"x","cumsum");var forward=function(backend2,save){var permutation=getAxesPermutation([axis],$x.rank);var permutedX=$x;if(permutation!=null){permutedX=transpose2($x,permutation)}var permutedAxis=getInnerMostAxes(1,$x.rank)[0];var value=backend2.cumsum(permutedX,permutedAxis,exclusive,reverse3);save([$x]);if(permutation!=null){var reversePermutation=getUndoAxesPermutation(permutation);value=transpose2(value,reversePermutation)}return value};var inputs={x:$x};var attrs={axis,exclusive,reverse:reverse3};return ENGINE.runKernelFunc(forward,inputs,null,Cumsum3,attrs)}var cumsum2=op({cumsum_});function depthToSpace_(x,blockSize,dataFormat){if(dataFormat===void 0){dataFormat="NHWC"}var $x=convertToTensor(x,"x","depthToSpace");var inputHeight=dataFormat==="NHWC"?$x.shape[1]:$x.shape[2];var inputWidth=dataFormat==="NHWC"?$x.shape[2]:$x.shape[3];var inputDepth=dataFormat==="NHWC"?$x.shape[3]:$x.shape[1];assert(inputHeight*blockSize>=0,function(){return"Negative dimension size caused by overflow when multiplying\n "+inputHeight+" and "+blockSize+" for depthToSpace with input shape\n "+$x.shape});assert(inputWidth*blockSize>=0,function(){return"Negative dimension size caused by overflow when multiplying\n "+inputWidth+" and "+blockSize+" for depthToSpace with input shape\n "+$x.shape});assert(inputDepth%(blockSize*blockSize)===0,function(){return"Dimension size must be evenly divisible by "+blockSize*blockSize+" but is "+inputDepth+" for depthToSpace with input shape "+$x.shape});var forward=function(backend2){return backend2.depthToSpace($x,blockSize,dataFormat)};var inputs={x:$x};var attrs={blockSize,dataFormat};return ENGINE.runKernelFunc(forward,inputs,null,DepthToSpace3,attrs)}var depthToSpace2=op({depthToSpace_});function depthwiseConv2d_(x,filter,strides,pad3,dataFormat,dilations,dimRoundingMode){if(dataFormat===void 0){dataFormat="NHWC"}if(dilations===void 0){dilations=[1,1]}var $x=convertToTensor(x,"x","depthwiseConv2d");var $filter=convertToTensor(filter,"filter","depthwiseConv2d");var x4D=$x;var reshapedTo4D=false;if($x.rank===3){reshapedTo4D=true;x4D=reshape2($x,[1,$x.shape[0],$x.shape[1],$x.shape[2]])}assert(x4D.rank===4,function(){return"Error in depthwiseConv2d: input must be rank 4, but got "+("rank "+x4D.rank+".")});assert($filter.rank===4,function(){return"Error in depthwiseConv2d: filter must be rank 4, but got rank "+($filter.rank+".")});assert(x4D.shape[3]===$filter.shape[2],function(){return"Error in depthwiseConv2d: number of input channels "+("("+x4D.shape[3]+") must match the inChannels dimension in ")+("filter "+$filter.shape[2]+".")});if(dimRoundingMode!=null){assert(isInt(pad3),function(){return"Error in depthwiseConv2d: pad must be an integer when using, "+("dimRoundingMode "+dimRoundingMode+" but got pad "+pad3+".")})}var forward=function(backend2,save){if(dilations==null){dilations=[1,1]}assert(eitherStridesOrDilationsAreOne(strides,dilations),function(){return"Error in depthwiseConv2d: Either strides or dilations must be "+("1. Got strides "+strides+" and dilations '"+dilations+"'")});var convInfo=computeConv2DInfo(x4D.shape,$filter.shape,strides,dilations,pad3,dimRoundingMode,true);var res2=backend2.depthwiseConv2D(x4D,$filter,convInfo);save([x4D,$filter]);return res2};var inputs={x:x4D,filter:$filter};var attrs={strides,pad:pad3,dataFormat,dilations,dimRoundingMode};var res=ENGINE.runKernelFunc(forward,inputs,null,DepthwiseConv2dNative3,attrs);if(reshapedTo4D){return reshape2(res,[res.shape[1],res.shape[2],res.shape[3]])}return res}var depthwiseConv2d2=op({depthwiseConv2d_});function diag_(x){var $x=convertToTensor(x,"x","diag");var forward=function(backend2){var flat=reshape2($x,[$x.size]);var result=backend2.diag(flat);var outShape=x.shape.concat(x.shape);return reshape2(result,outShape)};var inputs={x:$x};return ENGINE.runKernelFunc(forward,inputs,null,Diag)}var diag=op({diag_});function dilation2d_(x,filter,strides,pad3,dilations,dataFormat){if(dilations===void 0){dilations=[1,1]}if(dataFormat===void 0){dataFormat="NHWC"}var $x=convertToTensor(x,"x","dilation2d");var $filter=convertToTensor(filter,"filter","dilation2d");assert($x.rank===3||$x.rank===4,function(){return"Error in dilation2d: input must be rank 3 or 4, but got rank "+($x.rank+".")});assert($filter.rank===3,function(){return"Error in dilation2d: filter must be rank 3, but got rank "+($filter.rank+".")});assert(dataFormat==="NHWC",function(){return"Error in dilation2d: Only NHWC is currently supported, "+("but got dataFormat of "+dataFormat)});var x4D=$x;var reshapedTo4D=false;if($x.rank===3){x4D=reshape2($x,[1,$x.shape[0],$x.shape[1],$x.shape[2]]);reshapedTo4D=true}var inputs={x:x4D,filter:$filter};var attrs={strides,pad:pad3,dilations};var res=ENGINE.runKernel(Dilation2D,inputs,attrs);if(reshapedTo4D){return reshape2(res,[res.shape[1],res.shape[2],res.shape[3]])}return res}var dilation2d=op({dilation2d_});function getBroadcastDims(inShape,outShape){var inRank=inShape.length;var dims=[];for(var i=0;i1&&a===1){dims.unshift(dim)}}return dims}function getReductionAxes(inShape,outShape){var result=[];for(var i=0;i1){result.unshift(outAxis)}}return result}function assertAndGetBroadcastShape(shapeA,shapeB){var result=[];var l=Math.max(shapeA.length,shapeB.length);for(var i=0;inumSegments||res===inSize){done=true}else{res=nearestDivisor(inSize,res+1)}}return res}function computeOutShape$2(aShape,axis,numSegments){var outShape=[];var rank=aShape.length;for(var dim=0;dim0,function(){return"variableGrads() expects at least one of the input variables to "+("be trainable, but none of the "+originalVarCount+" variables is ")+"trainable."});var allowNoGradients=true;var _a=ENGINE.gradients(f,varList,null,allowNoGradients),value=_a.value,grads2=_a.grads;assert(grads2.some(function(g){return g!=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()."});assert(value.rank===0,function(){return"The f passed in variableGrads(f) must return a scalar, but it "+("returned a rank-"+value.rank+" tensor")});var namedGrads={};varList.forEach(function(v,i){if(grads2[i]!=null){namedGrads[v.name]=grads2[i]}});if(specifiedNonTrainable!=null){specifiedNonTrainable.forEach(function(v){return namedGrads[v.name]=null})}return{value,grads:namedGrads}}function customGrad(f){return ENGINE.customGrad(f)}function checkGrads(grads2){var numNullGradients=grads2.filter(function(g){return g==null}).length;if(numNullGradients>0){throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that\n the f you passed encloses all operations that lead from x to y.")}}function neg_(x){var $x=convertToTensor(x,"x","neg");var inputs={x:$x};return ENGINE.runKernelFunc(function(backend2){return backend2.neg($x)},inputs,null,Negate3)}var neg=op({neg_});function softplus_(x){var $x=convertToTensor(x,"x","softplus");var inputs={x:$x};return ENGINE.runKernelFunc(function(backend2,save){var res=backend2.softplus($x);save([$x]);return res},inputs,null,Softplus)}var softplus=op({softplus_});function logSigmoid_(x){var $x=convertToTensor(x,"x","logSigmoid");var customOp=customGrad(function(x2){var value=neg(softplus(neg(x2)));var gradFunc=function(dy){var derX=mul(dy,sigmoid2(neg(x2)));return derX};return{value,gradFunc}});return customOp($x)}var logSigmoid=op({logSigmoid_});function max_(x,axis,keepDims){if(axis===void 0){axis=null}if(keepDims===void 0){keepDims=false}var $x=convertToTensor(x,"x","max");var forward=function(backend2,save){var origAxes=parseAxisParam(axis,$x.shape);var axes=origAxes;var permutedAxes=getAxesPermutation(axes,$x.rank);var maxInput=$x;if(permutedAxes!=null){maxInput=transpose2($x,permutedAxes);axes=getInnerMostAxes(axes.length,maxInput.rank)}var y=backend2.max(maxInput,axes);if(permutedAxes!=null){maxInput.dispose()}var res=y;if(keepDims){var expandedShape=expandShapeToKeepDim(res.shape,parseAxisParam(axis,$x.shape));res=reshape2(res,expandedShape);y.dispose()}save([$x,res]);return res};var inputs={x:$x};var attrs={reductionIndices:axis,keepDims};return ENGINE.runKernelFunc(forward,inputs,null,Max3,attrs)}var max2=op({max_});function sub_(a,b){var _a;var $a=convertToTensor(a,"a","sub");var $b=convertToTensor(b,"b","sub");_a=makeTypesMatch($a,$b),$a=_a[0],$b=_a[1];var forward=function(backend2,save){var res=backend2.subtract($a,$b);save([$a,$b]);return res};var inputs={a:$a,b:$b};return ENGINE.runKernelFunc(forward,inputs,null,Sub3)}var sub=op({sub_});function sum_(x,axis,keepDims){if(axis===void 0){axis=null}if(keepDims===void 0){keepDims=false}var $x=convertToTensor(x,"x","sum");if($x.dtype==="bool"){$x=cast2($x,"int32")}var forward=function(backend2,save){save([$x]);var axes=parseAxisParam(axis,$x.shape);var permutation=getAxesPermutation(axes,$x.rank);var reductionAxes=axes;var permutedX=$x;if(permutation!=null){permutedX=transpose2($x,permutation);reductionAxes=getInnerMostAxes(reductionAxes.length,$x.rank)}var value=backend2.sum(permutedX,reductionAxes);if(keepDims){var newShape=expandShapeToKeepDim(value.shape,axes);value=reshape2(value,newShape)}return value};var inputs={x:$x};var attrs={axis,keepDims};return ENGINE.runKernelFunc(forward,inputs,null,Sum3,attrs)}var sum$1=op({sum_});function logSoftmax_(logits,axis){if(axis===void 0){axis=-1}var $logits=convertToTensor(logits,"logits","logSoftmax");if(axis===-1){axis=$logits.rank-1}if(axis!==$logits.rank-1){throw Error("Log Softmax along a non-last dimension is not yet supported. "+("Logits was rank "+$logits.rank+" and axis was "+axis))}var forward=function(backend2,save){var keepDims=true;var xMax=max2(logits,axis,true);var shifted=sub(logits,xMax);var value=sub(cast2(shifted,"float32"),log(sum$1(exp(shifted),axis,keepDims)));save([value]);return value};var inputs={logits:$logits};var attrs={axis};return ENGINE.runKernelFunc(forward,inputs,null,LogSoftmax,attrs)}var logSoftmax=op({logSoftmax_});function logSumExp_(x,axis,keepDims){if(axis===void 0){axis=null}if(keepDims===void 0){keepDims=false}var $x=convertToTensor(x,"x","logSumExp");var axes=parseAxisParam(axis,$x.shape);var xMax=max2($x,axes,true);var a=sub($x,xMax);var b=exp(a);var c=sum$1(b,axes);var d=log(c);var res=add$1(reshape2(xMax,d.shape),d);if(keepDims){var newShape=expandShapeToKeepDim(res.shape,axes);return reshape2(res,newShape)}return res}var logSumExp=op({logSumExp_});function logicalAnd_(a,b){var $a=convertToTensor(a,"a","logicalAnd","bool");var $b=convertToTensor(b,"b","logicalAnd","bool");assertAndGetBroadcastShape($a.shape,$b.shape);var inputs={a:$a,b:$b};return ENGINE.runKernelFunc(function(backend2){return backend2.logicalAnd($a,$b)},inputs,null,LogicalAnd3)}var logicalAnd=op({logicalAnd_});function logicalNot_(x){var $x=convertToTensor(x,"x","logicalNot","bool");var inputs={x:$x};return ENGINE.runKernelFunc(function(backend2){return backend2.logicalNot($x)},inputs,null,LogicalNot)}var logicalNot=op({logicalNot_});function logicalOr_(a,b){var $a=convertToTensor(a,"a","logicalOr","bool");var $b=convertToTensor(b,"b","logicalOr","bool");assertAndGetBroadcastShape($a.shape,$b.shape);var inputs={a:$a,b:$b};return ENGINE.runKernelFunc(function(backend2){return backend2.logicalOr($a,$b)},inputs,null,LogicalOr)}var logicalOr=op({logicalOr_});function logicalXor_(a,b){var $a=convertToTensor(a,"a","logicalXor","bool");var $b=convertToTensor(b,"b","logicalXor","bool");assertAndGetBroadcastShape($a.shape,$b.shape);return logicalAnd(logicalOr(a,b),logicalNot(logicalAnd(a,b)))}var logicalXor=op({logicalXor_});function maxPool_(x,filterSize,strides,pad3,dimRoundingMode){var $x=convertToTensor(x,"x","maxPool");var dilations=1;var x4D=$x;var reshapedTo4D=false;if($x.rank===3){reshapedTo4D=true;x4D=reshape2($x,[1,$x.shape[0],$x.shape[1],$x.shape[2]])}assert(x4D.rank===4,function(){return"Error in maxPool: input must be rank 4 but got rank "+x4D.rank+"."});assert(eitherStridesOrDilationsAreOne(strides,dilations),function(){return"Error in maxPool: Either strides or dilations must be 1. "+("Got strides "+strides+" and dilations '"+dilations+"'")});if(dimRoundingMode!=null){assert(isInt(pad3),function(){return"Error in maxPool: pad must be an integer when using, "+("dimRoundingMode "+dimRoundingMode+" but got pad "+pad3+".")})}var forward=function(backend2,save){var convInfo=computePool2DInfo(x4D.shape,filterSize,strides,1,pad3,dimRoundingMode);var y;if(convInfo.filterWidth===1&&convInfo.filterHeight===1&&arraysEqual(convInfo.inShape,convInfo.outShape)){y=x4D.clone()}else{y=backend2.maxPool(x4D,convInfo)}save([x4D,y]);return y};var inputs={x:x4D};var attrs={filterSize,strides,pad:pad3,dimRoundingMode};var res=ENGINE.runKernelFunc(forward,inputs,null,MaxPool3,attrs);if(reshapedTo4D){return reshape2(res,[res.shape[1],res.shape[2],res.shape[3]])}return res}var maxPool2=op({maxPool_});function maxPool3d_(x,filterSize,strides,pad3,dimRoundingMode,dataFormat,dilations){if(filterSize===void 0){filterSize=[1,1,1]}if(dataFormat===void 0){dataFormat="NDHWC"}if(dilations==null){dilations=[1,1,1]}else{deprecationWarn2("dilations is deprecated, this field will be gone in v3.0.0.")}var $x=convertToTensor(x,"x","maxPool3d");var x5D=$x;var reshapedTo5D=false;if($x.rank===4){reshapedTo5D=true;x5D=reshape2($x,[1,$x.shape[0],$x.shape[1],$x.shape[2],$x.shape[3]])}assert(x5D.rank===5,function(){return"Error in maxPool3d: x must be rank 5 but got rank "+x5D.rank+"."});assert(dataFormat==="NDHWC",function(){return"Error in maxPool3d: Only NDHWC is currently supported, "+("but got dataFormat of "+dataFormat)});assert(eitherStridesOrDilationsAreOne(strides,dilations),function(){return"Error in maxPool3d: Either strides or dilations must be 1. "+("Got strides "+strides+" and dilations '"+dilations+"'")});if(dimRoundingMode!=null){assert(isInt(pad3),function(){return"Error in maxPool3d: pad must be an integer when using, "+("dimRoundingMode "+dimRoundingMode+" but got pad "+pad3+".")})}var forward=function(backend2,save){if(dilations==null){dilations=[1,1,1]}var convInfo=computePool3DInfo(x5D.shape,filterSize,strides,dilations,pad3,dimRoundingMode,dataFormat);var y=backend2.maxPool3d(x5D,convInfo);save([x5D,y]);return y};var inputs={x:x5D};var attrs={filterSize,strides,pad:pad3,dimRoundingMode,dataFormat,dilations};var res=ENGINE.runKernelFunc(forward,inputs,null,MaxPool3D,attrs);if(reshapedTo5D){return reshape2(res,[res.shape[1],res.shape[2],res.shape[3],res.shape[4]])}return res}var maxPool3d=op({maxPool3d_});function maxPoolWithArgmax_(x,filterSize,strides,pad3,includeBatchInIndex){if(includeBatchInIndex===void 0){includeBatchInIndex=false}var $x=convertToTensor(x,"x","maxPoolWithArgmax");var inputs={x:$x};var attrs={filterSize,strides,pad:pad3,includeBatchInIndex};var result=ENGINE.runKernel(MaxPoolWithArgmax,inputs,attrs);return{result:result[0],indexes:result[1]}}var maxPoolWithArgmax=op({maxPoolWithArgmax_});function zeros(shape,dtype){if(dtype===void 0){dtype="float32"}if(dtype==="complex64"){var real2=zeros(shape,"float32");var imag2=zeros(shape,"float32");return complex(real2,imag2)}var values=makeZerosTypedArray(sizeFromShape(shape),dtype);return ENGINE.makeTensor(values,shape,dtype)}function ones$1(shape,dtype){if(dtype===void 0){dtype="float32"}if(dtype==="complex64"){var real2=ones$1(shape,"float32");var imag2=zeros(shape,"float32");return complex(real2,imag2)}var values=makeOnesTypedArray(sizeFromShape(shape),dtype);return ENGINE.makeTensor(values,shape,dtype)}function mean_(x,axis,keepDims){if(axis===void 0){axis=null}if(keepDims===void 0){keepDims=false}var $x=convertToTensor(x,"x","mean");var axes=parseAxisParam(axis,$x.shape);var shapes=computeOutAndReduceShapes($x.shape,axes);var reduceShape=shapes[1];var reduceSize=sizeFromShape(reduceShape);var inputs={x:$x};var attrs={axis,keepDims};var forward=function(){var reduceSizeScalar=scalar(reduceSize);var xReduce=reduceSizeScalar.dtype===$x.dtype?$x:cast2($x,reduceSizeScalar.dtype);var res=div(xReduce,reduceSizeScalar);return sum$1(res,axis,keepDims)};var customOp=customGrad(function(x2){var value=ENGINE.runKernelFunc(forward,inputs,null,Mean,attrs);var gradFunc=function(dy){var expandedDyShape=x2.shape.slice();axes.forEach(function(axis2){expandedDyShape[axis2]=1});var expandedDy=reshape2(dy,expandedDyShape);var derX=div(mul(expandedDy,ones$1(x2.shape,"float32")),reduceSize);return derX};return{value,gradFunc}});return customOp($x)}var mean=op({mean_});function min_(x,axis,keepDims){if(axis===void 0){axis=null}if(keepDims===void 0){keepDims=false}var $x=convertToTensor(x,"x","min");var forward=function(backend2,save){var origAxes=parseAxisParam(axis,$x.shape);var axes=origAxes;var permutedAxes=getAxesPermutation(axes,$x.rank);var minInput=$x;if(permutedAxes!=null){minInput=transpose2($x,permutedAxes);axes=getInnerMostAxes(axes.length,$x.rank)}var y=backend2.min(minInput,axes);if(permutedAxes!=null){minInput.dispose()}var res=y;if(keepDims){var expandedShape=expandShapeToKeepDim(res.shape,origAxes);res=reshape2(y,expandedShape);y.dispose()}save([$x,res]);return res};var inputs={x:$x};var attrs={axis,keepDims};return ENGINE.runKernelFunc(forward,inputs,null,Min3,attrs)}var min2=op({min_});function minimum_(a,b){var _a;var $a=convertToTensor(a,"a","minimum");var $b=convertToTensor(b,"b","minimum");_a=makeTypesMatch($a,$b),$a=_a[0],$b=_a[1];if($a.dtype==="bool"){$a=cast2($a,"int32");$b=cast2($b,"int32")}assertAndGetBroadcastShape($a.shape,$b.shape);var forward=function(backend2,save){var res=backend2.minimum($a,$b);save([$a,$b]);return res};var inputs={a:$a,b:$b};return ENGINE.runKernelFunc(forward,inputs,null,Minimum3)}var minimum=op({minimum_});function mirrorPad_(x,paddings,mode){assert(mode==="reflect"||mode==="symmetric",function(){return"Invalid mode. Mode must be either reflect or symmetric. "+("Got "+mode+".")});var $x=convertToTensor(x,"x","mirrorPad");if($x.rank===0){throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad")}assert(paddings.length===$x.rank,function(){return"Padding doesn't match input. Must be "+$x.rank+". "+("Got "+paddings.length+".")});var shapeOffset=mode==="reflect"?1:0;var _loop_1=function(i2){assert(paddings[i2].length===2,function(){return"Invalid number of paddings. Must be length of 2 each."});assert(paddings[i2][0]>=0&&paddings[i2][0]<=$x.shape[i2]-shapeOffset&&paddings[i2][1]>=0&&paddings[i2][1]<=$x.shape[i2]-shapeOffset,function(){return"Padding in dimension "+i2+" cannot be greater than or equal "+("to "+($x.shape[i2]-shapeOffset)+" or less than 0 for input of ")+("shape "+$x.shape)})};for(var i=0;i<$x.rank;i++){_loop_1(i)}var attrs={paddings,mode};var inputs={x:$x};return ENGINE.runKernel(MirrorPad,inputs,attrs)}var mirrorPad=op({mirrorPad_});function mod_(a,b){var _a;var $a=convertToTensor(a,"a","mod");var $b=convertToTensor(b,"b","mod");_a=makeTypesMatch($a,$b),$a=_a[0],$b=_a[1];var forward=function(backend2,save){var res=backend2.mod($a,$b);save([$a,$b]);return res};var inputs={a:$a,b:$b};return ENGINE.runKernelFunc(forward,inputs,null,Mod)}var mod=op({mod_});function square_(x){var $x=convertToTensor(x,"x","square");var attrs={};var inputsToSave=[$x];var outputsToSave=[];return ENGINE.runKernelFunc(function(backend2,save){save([$x]);return backend2.square($x)},{x:$x},null,"Square",attrs,inputsToSave,outputsToSave)}var square=op({square_});function moments_(x,axis,keepDims){if(axis===void 0){axis=null}if(keepDims===void 0){keepDims=false}x=convertToTensor(x,"x","moments");var axes=parseAxisParam(axis,x.shape);var xMean=mean(x,axes,keepDims);var keepDimsShape=xMean.shape;if(!keepDims){keepDimsShape=expandShapeToKeepDim(xMean.shape,axes)}var devSquared=square(sub(cast2(x,"float32"),reshape2(xMean,keepDimsShape)));var variance=mean(devSquared,axes,keepDims);return{mean:xMean,variance}}var moments=op({moments_});function multiRNNCell_(lstmCells,data2,c,h){var $data=convertToTensor(data2,"data","multiRNNCell");var $c=convertToTensorArray(c,"c","multiRNNCell");var $h=convertToTensorArray(h,"h","multiRNNCell");var input=$data;var newStates=[];for(var i=0;i2){throw new Error("Rank of probabilities must be 1 or 2, but is "+origRank)}seed=seed||Math.random();var logits2D=origRank===1?reshape2($logits,[1,-1]):$logits;var res=ENGINE.runKernelFunc(function(backend2){return backend2.multinomial(logits2D,normalized,numSamples,seed)},{logits2D});return origRank===1?reshape2(res,[res.size]):res}var multinomial=op({multinomial_});function notEqual_(a,b){var _a;var $a=convertToTensor(a,"a","notEqual");var $b=convertToTensor(b,"b","notEqual");_a=makeTypesMatch($a,$b),$a=_a[0],$b=_a[1];assertAndGetBroadcastShape($a.shape,$b.shape);var forward=function(backend2){return backend2.notEqual($a,$b)};var inputs={a:$a,b:$b};return ENGINE.runKernelFunc(forward,inputs,null,NotEqual3)}var notEqual=op({notEqual_});function real_(input){var $input=convertToTensor(input,"input","real");var forward=function(backend2){return backend2.real($input)};var inputs={input:$input};return ENGINE.runKernelFunc(forward,inputs,null,Real)}var real=op({real_});function onesLike_(x){var $x=convertToTensor(x,"x","onesLike");var forward=function(backend2,save){if($x.dtype==="complex64"){var r=onesLike2(real($x));var i=zerosLike2(imag($x));return complex(r,i)}return backend2.onesLike($x)};var inputs={x:$x};return ENGINE.runKernelFunc(forward,inputs,null,OnesLike3)}var onesLike2=op({onesLike_});function outerProduct_(v1,v2){var $v1=convertToTensor(v1,"v1","outerProduct");var $v2=convertToTensor(v2,"v2","outerProduct");assert($v1.rank===1&&$v2.rank===1,function(){return"Error in outerProduct: inputs must be rank 1, but got ranks "+($v1.rank+" and "+$v2.rank+".")});var v12D=reshape2($v1,[-1,1]);var v22D=reshape2($v2,[1,-1]);return matMul(v12D,v22D)}var outerProduct=op({outerProduct_});function pad_(x,paddings,constantValue){if(constantValue===void 0){constantValue=0}var $x=convertToTensor(x,"x","pad");if($x.rank===0){throw new Error("pad(scalar) is not defined. Pass non-scalar to pad")}var forward=function(backend2,save){save([$x]);return backend2.pad($x,paddings,constantValue)};var attrs={paddings,constantValue};var inputs={x:$x};return ENGINE.runKernelFunc(forward,inputs,null,PadV23,attrs)}var pad2=op({pad_});function pad1d_(x,paddings,constantValue){if(constantValue===void 0){constantValue=0}assert(paddings.length===2,function(){return"Invalid number of paddings. Must be length of 2."});return pad2(x,[paddings],constantValue)}var pad1d=op({pad1d_});function pad2d_(x,paddings,constantValue){if(constantValue===void 0){constantValue=0}assert(paddings.length===2&&paddings[0].length===2&&paddings[1].length===2,function(){return"Invalid number of paddings. Must be length of 2 each."});return pad2(x,paddings,constantValue)}var pad2d=op({pad2d_});function pad3d_(x,paddings,constantValue){if(constantValue===void 0){constantValue=0}assert(paddings.length===3&&paddings[0].length===2&&paddings[1].length===2&&paddings[2].length===2,function(){return"Invalid number of paddings. Must be length of 2 each."});return pad2(x,paddings,constantValue)}var pad3d=op({pad3d_});function pad4d_(x,paddings,constantValue){if(constantValue===void 0){constantValue=0}assert(paddings.length===4&&paddings[0].length===2&&paddings[1].length===2&&paddings[2].length===2&&paddings[3].length===2,function(){return"Invalid number of paddings. Must be length of 2 each."});return pad2(x,paddings,constantValue)}var pad4d=op({pad4d_});function spaceToBatchND_(x,blockShape,paddings){var $x=convertToTensor(x,"x","spaceToBatchND");assert($x.rank>=1+blockShape.length,function(){return"input rank "+$x.rank+" should be > than [blockShape] "+blockShape.length});assert(paddings.length===blockShape.length,function(){return"paddings.shape[0] "+paddings.length+" must be equal to [blockShape] "+blockShape.length});assert($x.shape.reduce(function(a,b,i){if(i>0&&i<=blockShape.length){return a&&(b+paddings[i-1][0]+paddings[i-1][1])%blockShape[i-1]===0}return a},true),function(){return"input spatial dimensions "+$x.shape.slice(1)+" with paddings "+paddings.toString()+" must be divisible by blockShapes "+blockShape.toString()});var forward=function(backend2){return backend2.spaceToBatchND($x,blockShape,paddings)};var inputs={x:$x};var attrs={blockShape,paddings};return ENGINE.runKernelFunc(forward,inputs,null,SpaceToBatchND,attrs)}var spaceToBatchND=op({spaceToBatchND_});function pool_(input,windowShape,poolingType,pad3,dilations,strides){if(dilations==null){dilations=[1,1]}if(strides==null){strides=1}if(pad3===0){pad3="valid"}var $x=convertToTensor(input,"x","maxPool");var x4D=$x;var reshapedTo4D=false;if($x.rank===3){reshapedTo4D=true;x4D=reshape2($x,[1,$x.shape[0],$x.shape[1],$x.shape[2]])}assert(eitherStridesOrDilationsAreOne(strides,dilations),function(){return"Error in pool: Either strides or dilations must be 1. "+("Got strides "+strides+" and dilations '"+dilations+"'")});var convInfo=computePool2DInfo(x4D.shape,windowShape,strides,dilations,pad3);var dilation=[convInfo.dilationHeight,convInfo.dilationWidth];var basePadding;if(pad3==="same"){basePadding=withSpaceToBatchBasePaddings([convInfo.filterHeight,convInfo.filterWidth],dilation)}else{basePadding=[[0,0],[0,0]]}var isDilationOne=dilation[0]===1&&dilation[1]===1;var _a=requiredSpaceToBatchPaddings([convInfo.inHeight,convInfo.inWidth],dilation,basePadding),adjustedPadding=_a[0],adjustedCrops=_a[1];var convertedPad=isDilationOne?pad3:"valid";var convertedX=isDilationOne?x4D:spaceToBatchND(x4D,dilation,adjustedPadding);var forwardOp=poolingType==="avg"?function(){return avgPool2(convertedX,windowShape,strides,convertedPad)}:function(){return maxPool2(convertedX,windowShape,strides,convertedPad)};var y=forwardOp();var res=isDilationOne?y:batchToSpaceND(y,dilation,adjustedCrops);if(reshapedTo4D){return reshape2(res,[res.shape[1],res.shape[2],res.shape[3]])}return res}function requiredSpaceToBatchPaddings(inputShape,blockShape,basePadding){var padStart=basePadding.map(function(b){return b[0]});var origPadEnd=basePadding.map(function(b){return b[1]});var fullInputShape=inputShape.concat(padStart,origPadEnd);var padEndExtra=blockShape.map(function(b,i){return(b-fullInputShape[i]%b)%b});var padEnd=origPadEnd.map(function(s,i){return s+padEndExtra[i]});var paddings=blockShape.map(function(_,i){return[padStart[i],padEnd[i]]});var crops=blockShape.map(function(_,i){return[0,padEndExtra[i]]});return[paddings,crops]}function withSpaceToBatchBasePaddings(filterShape,dilation){var dilatedFilterShape=filterShape.map(function(s,i){return s+(s-1)*(dilation[i]-1)});var padExtraShape=dilatedFilterShape.map(function(s){return s-1});var padExtraStart=padExtraShape.map(function(s){return Math.floor(s/2)});var padExtraEnd=padExtraShape.map(function(s,i){return s-padExtraStart[i]});return padExtraShape.map(function(_,i){return[padExtraStart[i],padExtraEnd[i]]})}var pool=op({pool_});function pow_(base,exp2){var _a;var $base=convertToTensor(base,"base","pow");var $exp=convertToTensor(exp2,"exp","pow");_a=makeTypesMatch($base,$exp),$base=_a[0],$exp=_a[1];var inputs={a:$base,b:$exp};var forward=function(backend2,save){var y=backend2.pow($base,$exp);save([$base,$exp,y]);return y};return ENGINE.runKernelFunc(forward,inputs,null,Pow3)}var pow=op({pow_});function prelu_(x,alpha){var $x=convertToTensor(x,"x","prelu");var $alpha=convertToTensor(alpha,"alpha","prelu");var forward=function(backend2,save){var res=backend2.prelu($x,$alpha);save([$x,$alpha]);return res};var inputs={x:$x,alpha:$alpha};return ENGINE.runKernelFunc(forward,inputs,null,Prelu3)}var prelu2=op({prelu_});function prod_(x,axis,keepDims){if(axis===void 0){axis=null}if(keepDims===void 0){keepDims=false}var $x=convertToTensor(x,"x","prod");if($x.dtype==="bool"){$x=cast2($x,"int32")}var forward=function(backend2){var axes=parseAxisParam(axis,$x.shape);var permutation=getAxesPermutation(axes,$x.rank);var reductionAxes=axes;var permutedX=$x;if(permutation!=null){permutedX=transpose2($x,permutation);reductionAxes=getInnerMostAxes(reductionAxes.length,$x.rank)}var value=backend2.prod(permutedX,reductionAxes);if(keepDims){var newShape=expandShapeToKeepDim(value.shape,axes);value=reshape2(value,newShape)}return value};var inputs={x:$x};var attrs={axis,keepDims};return ENGINE.runKernelFunc(forward,inputs,null,Prod,attrs)}var prod=op({prod_});function rand_(shape,randFunction,dtype){var size=sizeFromShape(shape);var values=null;if(dtype==null||dtype==="float32"){values=new Float32Array(size)}else if(dtype==="int32"){values=new Int32Array(size)}else if(dtype==="bool"){values=new Uint8Array(size)}else{throw new Error("Unknown data type "+dtype)}for(var i=0;i>>0;h-=n;h*=n;n=h>>>0;h-=n;n+=h*4294967296}return(n>>>0)*23283064365386963e-26};return mash}if(module4&&module4.exports){module4.exports=impl}else if(define2&&define2.amd){define2(function(){return impl})}else{this.alea=impl}})(commonjsGlobal,module3,false)});var xor128=createCommonjsModule(function(module3){(function(global2,module4,define2){function XorGen(seed){var me=this,strseed="";me.x=0;me.y=0;me.z=0;me.w=0;me.next=function(){var t=me.x^me.x<<11;me.x=me.y;me.y=me.z;me.z=me.w;return me.w^=me.w>>>19^t^t>>>8};if(seed===(seed|0)){me.x=seed}else{strseed+=seed}for(var k=0;k>>0)/4294967296};prng.double=function(){do{var top=xg.next()>>>11,bot=(xg.next()>>>0)/4294967296,result=(top+bot)/(1<<21)}while(result===0);return result};prng.int32=xg.next;prng.quick=prng;if(state){if(typeof state=="object")copy(state,xg);prng.state=function(){return copy(xg,{})}}return prng}if(module4&&module4.exports){module4.exports=impl}else if(define2&&define2.amd){define2(function(){return impl})}else{this.xor128=impl}})(commonjsGlobal,module3,false)});var xorwow=createCommonjsModule(function(module3){(function(global2,module4,define2){function XorGen(seed){var me=this,strseed="";me.next=function(){var t=me.x^me.x>>>2;me.x=me.y;me.y=me.z;me.z=me.w;me.w=me.v;return(me.d=me.d+362437|0)+(me.v=me.v^me.v<<4^(t^t<<1))|0};me.x=0;me.y=0;me.z=0;me.w=0;me.v=0;if(seed===(seed|0)){me.x=seed}else{strseed+=seed}for(var k=0;k>>4}me.next()}}function copy(f,t){t.x=f.x;t.y=f.y;t.z=f.z;t.w=f.w;t.v=f.v;t.d=f.d;return t}function impl(seed,opts){var xg=new XorGen(seed),state=opts&&opts.state,prng=function(){return(xg.next()>>>0)/4294967296};prng.double=function(){do{var top=xg.next()>>>11,bot=(xg.next()>>>0)/4294967296,result=(top+bot)/(1<<21)}while(result===0);return result};prng.int32=xg.next;prng.quick=prng;if(state){if(typeof state=="object")copy(state,xg);prng.state=function(){return copy(xg,{})}}return prng}if(module4&&module4.exports){module4.exports=impl}else if(define2&&define2.amd){define2(function(){return impl})}else{this.xorwow=impl}})(commonjsGlobal,module3,false)});var xorshift7=createCommonjsModule(function(module3){(function(global2,module4,define2){function XorGen(seed){var me=this;me.next=function(){var X=me.x,i=me.i,t,v;t=X[i];t^=t>>>7;v=t^t<<24;t=X[i+1&7];v^=t^t>>>10;t=X[i+3&7];v^=t^t>>>3;t=X[i+4&7];v^=t^t<<7;t=X[i+7&7];t=t^t<<13;v^=t^t<<9;X[i]=v;me.i=i+1&7;return v};function init2(me2,seed2){var j,w,X=[];if(seed2===(seed2|0)){w=X[0]=seed2}else{seed2=""+seed2;for(j=0;j0;--j){me2.next()}}init2(me,seed)}function copy(f,t){t.x=f.x.slice();t.i=f.i;return t}function impl(seed,opts){if(seed==null)seed=+new Date;var xg=new XorGen(seed),state=opts&&opts.state,prng=function(){return(xg.next()>>>0)/4294967296};prng.double=function(){do{var top=xg.next()>>>11,bot=(xg.next()>>>0)/4294967296,result=(top+bot)/(1<<21)}while(result===0);return result};prng.int32=xg.next;prng.quick=prng;if(state){if(state.x)copy(state,xg);prng.state=function(){return copy(xg,{})}}return prng}if(module4&&module4.exports){module4.exports=impl}else if(define2&&define2.amd){define2(function(){return impl})}else{this.xorshift7=impl}})(commonjsGlobal,module3,false)});var xor4096=createCommonjsModule(function(module3){(function(global2,module4,define2){function XorGen(seed){var me=this;me.next=function(){var w=me.w,X=me.X,i=me.i,t,v;me.w=w=w+1640531527|0;v=X[i+34&127];t=X[i=i+1&127];v^=v<<13;t^=t<<17;v^=v>>>15;t^=t>>>12;v=X[i]=v^t;me.i=i;return v+(w^w>>>16)|0};function init2(me2,seed2){var t,v,i,j,w,X=[],limit=128;if(seed2===(seed2|0)){v=seed2;seed2=null}else{seed2=seed2+"\0";v=0;limit=Math.max(limit,seed2.length)}for(i=0,j=-32;j>>15;v^=v<<4;v^=v>>>13;if(j>=0){w=w+1640531527|0;t=X[j&127]^=v+w;i=t==0?i+1:0}}if(i>=128){X[(seed2&&seed2.length||0)&127]=-1}i=127;for(j=4*128;j>0;--j){v=X[i+34&127];t=X[i=i+1&127];v^=v<<13;t^=t<<17;v^=v>>>15;t^=t>>>12;X[i]=v^t}me2.w=w;me2.X=X;me2.i=i}init2(me,seed)}function copy(f,t){t.i=f.i;t.w=f.w;t.X=f.X.slice();return t}function impl(seed,opts){if(seed==null)seed=+new Date;var xg=new XorGen(seed),state=opts&&opts.state,prng=function(){return(xg.next()>>>0)/4294967296};prng.double=function(){do{var top=xg.next()>>>11,bot=(xg.next()>>>0)/4294967296,result=(top+bot)/(1<<21)}while(result===0);return result};prng.int32=xg.next;prng.quick=prng;if(state){if(state.X)copy(state,xg);prng.state=function(){return copy(xg,{})}}return prng}if(module4&&module4.exports){module4.exports=impl}else if(define2&&define2.amd){define2(function(){return impl})}else{this.xor4096=impl}})(commonjsGlobal,module3,false)});var tychei=createCommonjsModule(function(module3){(function(global2,module4,define2){function XorGen(seed){var me=this,strseed="";me.next=function(){var b=me.b,c=me.c,d=me.d,a=me.a;b=b<<25^b>>>7^c;c=c-d|0;d=d<<24^d>>>8^a;a=a-b|0;me.b=b=b<<20^b>>>12^c;me.c=c=c-d|0;me.d=d<<16^c>>>16^a;return me.a=a-b|0};me.a=0;me.b=0;me.c=2654435769|0;me.d=1367130551;if(seed===Math.floor(seed)){me.a=seed/4294967296|0;me.b=seed|0}else{strseed+=seed}for(var k=0;k>>0)/4294967296};prng.double=function(){do{var top=xg.next()>>>11,bot=(xg.next()>>>0)/4294967296,result=(top+bot)/(1<<21)}while(result===0);return result};prng.int32=xg.next;prng.quick=prng;if(state){if(typeof state=="object")copy(state,xg);prng.state=function(){return copy(xg,{})}}return prng}if(module4&&module4.exports){module4.exports=impl}else if(define2&&define2.amd){define2(function(){return impl})}else{this.tychei=impl}})(commonjsGlobal,module3,false)});var seedrandom=createCommonjsModule(function(module3){(function(pool2,math2){var global2=this,width=256,chunks=6,digits=52,rngname="random",startdenom=math2.pow(width,chunks),significance=math2.pow(2,digits),overflow=significance*2,mask=width-1,nodecrypto;function seedrandom2(seed,options,callback){var key=[];options=options==true?{entropy:true}:options||{};var shortseed=mixkey(flatten2(options.entropy?[seed,tostring(pool2)]:seed==null?autoseed():seed,3),key);var arc4=new ARC4(key);var prng=function(){var n=arc4.g(chunks),d=startdenom,x=0;while(n=overflow){n/=2;d/=2;x>>>=1}return(n+x)/d};prng.int32=function(){return arc4.g(4)|0};prng.quick=function(){return arc4.g(4)/4294967296};prng.double=prng;mixkey(tostring(arc4.S),pool2);return(options.pass||callback||function(prng2,seed2,is_math_call,state){if(state){if(state.S){copy(state,arc4)}prng2.state=function(){return copy(arc4,{})}}if(is_math_call){math2[rngname]=prng2;return seed2}else return prng2})(prng,shortseed,"global"in options?options.global:this==math2,options.state)}math2["seed"+rngname]=seedrandom2;function ARC4(key){var t,keylen=key.length,me=this,i=0,j=me.i=me.j=0,s=me.S=[];if(!keylen){key=[keylen++]}while(i=1||s===0);var mul2=Math.sqrt(-2*Math.log(s)/s);resultX=this.mean+this.stdDev*v1*mul2;resultY=this.mean+this.stdDev*v2*mul2;if(!this.truncated||this.isValidTruncated(resultX)){isValid=true}}if(!this.truncated||this.isValidTruncated(resultY)){this.nextVal=this.convertValue(resultY)}return this.convertValue(resultX)};MPRandGauss2.prototype.convertValue=function(value){if(this.dtype==null||this.dtype==="float32"){return value}return Math.round(value)};MPRandGauss2.prototype.isValidTruncated=function(value){return value<=this.upper&&value>=this.lower};return MPRandGauss2}();var RandGamma=function(){function RandGamma2(alpha,beta,dtype,seed){this.alpha=alpha;this.beta=1/beta;this.dtype=dtype;var seedValue=seed?seed:Math.random();this.randu=seedrandom_1(seedValue.toString());this.randn=new MPRandGauss(0,1,dtype,false,this.randu());if(alpha<1){this.d=alpha+2/3}else{this.d=alpha-1/3}this.c=1/Math.sqrt(9*this.d)}RandGamma2.prototype.nextValue=function(){var x2,v0,v1,x,u,v;while(true){do{x=this.randn.nextValue();v=1+this.c*x}while(v<=0);v*=v*v;x2=x*x;v0=1-.331*x2*x2;v1=.5*x2+this.d*(1-v+Math.log(v));u=this.randu();if(u1;if(sameStartStop||increasingRangeNegativeStep||decreasingRangePositiveStep){return zeros([0],dtype)}var numElements=Math.abs(Math.ceil((stop-start)/step2));var values=makeZerosTypedArray(numElements,dtype);if(stop0?a+b:a});numOrSizeSplits[negIndex]=x.shape[axis]-total}assert(x.shape[axis]===numOrSizeSplits.reduce(function(a,b){return a+b}),function(){return"The sum of sizes must match the size of the axis dimension."});splitSizes=numOrSizeSplits}return splitSizes}function split_(x,numOrSizeSplits,axis){if(axis===void 0){axis=0}var $x=convertToTensor(x,"x","split");var forward=function(backend2,_){var $axis=parseAxisParam(axis,$x.shape)[0];var splitSizes=prepareSplitSize($x,numOrSizeSplits,$axis);return backend2.split($x,splitSizes,$axis)};var inputs={x:$x};var attr={numOrSizeSplits,axis};return ENGINE.runKernelFunc(forward,inputs,null,SplitV2,attr)}var split2=op({split_});function rfft_(input,fftLength){assert(input.dtype==="float32",function(){return"The dtype for rfft() must be real value but got "+input.dtype});var innerDimensionSize=input.shape[input.shape.length-1];var batch=input.size/innerDimensionSize;var adjustedInput;if(fftLength!=null&&fftLengthinnerDimensionSize){var zerosShape=input.shape.map(function(v){return v});zerosShape[input.shape.length-1]=fftLength-innerDimensionSize;adjustedInput=concat2([input,zeros(zerosShape)],input.shape.length-1);innerDimensionSize=fftLength}else{adjustedInput=input}var zerosInput=zerosLike2(adjustedInput);var complexInput=reshape2(complex(adjustedInput,zerosInput),[batch,innerDimensionSize]);var ret=fft(complexInput);var half=Math.floor(innerDimensionSize/2)+1;var realValues=real(ret);var imagValues=imag(ret);var realComplexConjugate=split2(realValues,[half,innerDimensionSize-half],realValues.shape.length-1);var imagComplexConjugate=split2(imagValues,[half,innerDimensionSize-half],imagValues.shape.length-1);var outputShape=adjustedInput.shape.slice();outputShape[adjustedInput.shape.length-1]=half;return reshape2(complex(realComplexConjugate[0],imagComplexConjugate[0]),outputShape)}var rfft=op({rfft_});function sqrt_(x){var $x=convertToTensor(x,"x","sqrt");var inputs={x:$x};return ENGINE.runKernelFunc(function(backend2,save){var res=backend2.sqrt($x);save([$x]);return res},inputs,null,Sqrt3)}var sqrt=op({sqrt_});function squaredDifference_(a,b){var _a;var $a=convertToTensor(a,"a","squaredDifference");var $b=convertToTensor(b,"b","squaredDifference");_a=makeTypesMatch($a,$b),$a=_a[0],$b=_a[1];assertAndGetBroadcastShape($a.shape,$b.shape);var forward=function(backend2,save){var res=backend2.squaredDifference($a,$b);save([$a,$b]);return res};var inputs={a:$a,b:$b};var attrs={};return ENGINE.runKernelFunc(forward,inputs,null,SquaredDifference3,attrs)}var squaredDifference=op({squaredDifference_});function squeeze_(x,axis){var $x=convertToTensor(x,"x","squeeze");return reshape2($x,squeezeShape($x.shape,axis).newShape)}var squeeze=op({squeeze_});function stack_(tensors,axis){if(axis===void 0){axis=0}var $tensors=convertToTensorArray(tensors,"tensors","stack");assert($tensors.length>=1,function(){return"Pass at least one tensor to tf.stack"});if($tensors.length===1){return expandDims($tensors[0],axis)}var rank=$tensors[0].rank;var shape=$tensors[0].shape;var dtype=$tensors[0].dtype;assert(axis<=rank,function(){return"Axis must be <= rank of the tensor"});$tensors.forEach(function(t){assertShapesMatch(shape,t.shape,"All tensors passed to stack must have matching shapes");assert(dtype===t.dtype,function(){return"All tensors passed to stack must have matching dtypes"})});var expandedTensors=$tensors.map(function(t){return expandDims(t,axis)});return concat2(expandedTensors,axis)}var stack=op({stack_});function step_(x,alpha){if(alpha===void 0){alpha=0}var $x=convertToTensor(x,"x","step");var inputs={x:$x};var attrs={alpha};return ENGINE.runKernelFunc(function(backend2){return backend2.step($x,alpha)},inputs,null,Step,attrs)}var step=op({step_});function stridedSlice_(x,begin,end,strides,beginMask,endMask,ellipsisMask,newAxisMask,shrinkAxisMask){if(beginMask===void 0){beginMask=0}if(endMask===void 0){endMask=0}if(ellipsisMask===void 0){ellipsisMask=0}if(newAxisMask===void 0){newAxisMask=0}if(shrinkAxisMask===void 0){shrinkAxisMask=0}var $x=convertToTensor(x,"x","stridedSlice");var forward=function(backend2){if(strides==null){strides=new Array(begin.length)}var ellipsisAxes=maskToAxes(ellipsisMask);if(ellipsisAxes.length>1){throw new Error("Multiple ellipses in slice is not allowed.")}if(ellipsisMask!==0&&newAxisMask!==0){throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.")}if(ellipsisMask!==0&&shrinkAxisMask!==0){throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.")}var numInterpolatedAxes=$x.rank-begin.length;var expandAxes=maskToAxes(newAxisMask);var newShape=$x.shape.slice();expandAxes.forEach(function(axis){begin[axis]=0;end[axis]=1;newShape.splice(axis,0,1)});$x=reshape2($x,newShape);var _a=getNormalizedAxes($x.shape,ellipsisAxes,numInterpolatedAxes,begin,end,strides,beginMask,endMask,ellipsisMask),normalizedBegin=_a.begin,normalizedEnd=_a.end,normalizedStrides=_a.strides;begin=normalizedBegin;end=normalizedEnd;strides=normalizedStrides;var shrinkAxes=maskToAxes(shrinkAxisMask);shrinkAxes.forEach(function(axis){end[axis]=begin[axis]+1;strides[axis]=1});var size=computeOutShape2(begin,end,strides);var outShape=size.filter(function(_,axis){return shrinkAxes.indexOf(axis)===-1});var nonStrided=strides.every(function(v){return v===1});if(nonStrided){return reshape2(slice2($x,begin,size),outShape)}var res=backend2.stridedSlice($x,begin,end,strides);return reshape2(res,outShape)};var inputs={x:$x};var attrs={begin,end,strides,beginMask,endMask,ellipsisMask,newAxisMask,shrinkAxisMask};return ENGINE.runKernelFunc(forward,inputs,null,StridedSlice3,attrs)}var stridedSlice2=op({stridedSlice_});function tan_(x){var $x=convertToTensor(x,"x","tan");var inputs={x:$x};return ENGINE.runKernelFunc(function(backend2,save){var res=backend2.tan($x);save([$x]);return res},inputs,null,Tan)}var tan=op({tan_});function tensor2d(values,shape,dtype){assertNonNull(values);if(shape!=null&&shape.length!==2){throw new Error("tensor2d() requires shape to have two numbers")}var inferredShape=inferShape(values,dtype);if(inferredShape.length!==2&&inferredShape.length!==1){throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray")}if(inferredShape.length===1&&shape==null){throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray")}return makeTensor(values,shape,inferredShape,dtype)}function tensor4d(values,shape,dtype){assertNonNull(values);if(shape!=null&&shape.length!==4){throw new Error("tensor4d() requires shape to have four numbers")}var inferredShape=inferShape(values,dtype);if(inferredShape.length!==4&&inferredShape.length!==1){throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray")}if(inferredShape.length===1&&shape==null){throw new Error("tensor4d() requires shape to be provided when `values` are a flat array")}return makeTensor(values,shape,inferredShape,dtype)}function tensor5d(values,shape,dtype){assertNonNull(values);if(shape!=null&&shape.length!==5){throw new Error("tensor5d() requires shape to have five numbers")}var inferredShape=inferShape(values,dtype);if(inferredShape.length!==5&&inferredShape.length!==1){throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray")}if(inferredShape.length===1&&shape==null){throw new Error("tensor5d() requires shape to be provided when `values` are a flat array")}return makeTensor(values,shape,inferredShape,dtype)}function tensor6d(values,shape,dtype){assertNonNull(values);if(shape!=null&&shape.length!==6){throw new Error("tensor6d() requires shape to have six numbers")}var inferredShape=inferShape(values,dtype);if(inferredShape.length!==6&&inferredShape.length!==1){throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray")}if(inferredShape.length===1&&shape==null){throw new Error("tensor6d() requires shape to be provided when `values` are a flat array")}shape=shape||inferredShape;return makeTensor(values,shape,inferredShape,dtype)}function topk_(x,k,sorted){if(k===void 0){k=1}if(sorted===void 0){sorted=true}var $x=convertToTensor(x,"x","topk");if($x.rank===0){throw new Error("topk() expects the input to be of rank 1 or higher")}var lastDim=$x.shape[$x.shape.length-1];if(k>lastDim){throw new Error("'k' passed to topk() must be <= the last dimension ("+lastDim+") "+("but got "+k))}var inputs={x:$x};var attrs={k,sorted};var _a=ENGINE.runKernelFunc(function(b){return b.topk($x,k,sorted)},inputs,null,TopK,attrs),values=_a[0],indices=_a[1];return{values,indices}}var topk=op({topk_});function truncatedNormal_(shape,mean2,stdDev,dtype,seed){if(mean2===void 0){mean2=0}if(stdDev===void 0){stdDev=1}if(dtype!=null&&dtype==="bool"){throw new Error("Unsupported data type $ { dtype }")}var randGauss=new MPRandGauss(mean2,stdDev,dtype,true,seed);var res=buffer2(shape,dtype);for(var i=0;i0,function(){return"The input tensor must be at least 1D"});var inputs={x:$x};var attrs={axis};var _a=ENGINE.runKernel(Unique,inputs,attrs),values=_a[0],indices=_a[1];return{values,indices}}var unique=op({unique_});function unsortedSegmentSum_(x,segmentIds,numSegments){var $x=convertToTensor(x,"x","unsortedSegmentSum");var $segmentIds=convertToTensor(segmentIds,"segmentIds","unsortedSegmentSum","int32");assert(isInt(numSegments),function(){return"numSegments must be of dtype int"});var inputs={x:$x,segmentIds:$segmentIds};var attrs={numSegments};var forward=function(backend2,save){var res=backend2.unsortedSegmentSum($x,$segmentIds,numSegments);save([$segmentIds]);return res};return ENGINE.runKernelFunc(forward,inputs,null,UnsortedSegmentSum,attrs)}var unsortedSegmentSum=op({unsortedSegmentSum_});function unstack_(x,axis){if(axis===void 0){axis=0}var $x=convertToTensor(x,"x","unstack");assert(axis>=-$x.shape.length&&axis<$x.shape.length,function(){return"Axis = "+axis+" is not in [-"+$x.shape.length+", "+$x.shape.length+")"});if(axis<0){axis+=$x.shape.length}var inputs={value:$x};var attrs={axis};var forward=function(backend2){return backend2.unstack($x,axis)};return ENGINE.runKernelFunc(forward,inputs,null,Unpack3,attrs)}var unstack=op({unstack_});function variable(initialValue,trainable,name,dtype){if(trainable===void 0){trainable=true}return ENGINE.makeVariable(initialValue,trainable,name,dtype)}function whereImpl(condShape,condVals){var indices=[];for(var i=0;i0,function(){return"mask cannot be scalar"});assertShapesMatch(tensorShape.slice(axisFrom,axisFrom+maskDim),$mask.shape,"mask's shape must match the first K dimensions of tensor's shape,");leadingSize=1;for(i=axisFrom;i2){throw new Error("sparseIndices should be a scalar, vector, or matrix,"+(" but got shape "+sparseIndices.shape+"."))}var numElems=sparseIndices.rank>0?sparseIndices.shape[0]:1;var numDims=sparseIndices.rank>1?sparseIndices.shape[1]:1;if(outputShape.length!==numDims){throw new Error("outputShape has incorrect number of elements:,"+(" "+outputShape.length+", should be: "+numDims+"."))}var numValues=sparseValues.size;if(!(sparseValues.rank===0||sparseValues.rank===1&&numValues===numElems)){throw new Error("sparseValues has incorrect shape "+(sparseValues.shape+", should be [] or ["+numElems+"]"))}if(sparseValues.dtype!==defaultValues.dtype){throw new Error("sparseValues.dtype must match defaultValues.dtype")}}function sparseToDense_(sparseIndices,sparseValues,outputShape,defaultValue){if(defaultValue===void 0){defaultValue=0}var $sparseIndices=convertToTensor(sparseIndices,"sparseIndices","sparseToDense","int32");var $sparseValues=convertToTensor(sparseValues,"sparseValues","sparseToDense");var $defaultValue=convertToTensor(defaultValue,"defaultValue","sparseToDense",$sparseValues.dtype);validateInput$1($sparseIndices,$sparseValues,outputShape,$defaultValue);var inputs={sparseIndices:$sparseIndices,sparseValues:$sparseValues,defaultValue:$defaultValue};var attrs={outputShape};return ENGINE.runKernelFunc(function(backend2){return backend2.sparseToDense($sparseIndices,$sparseValues,outputShape,$defaultValue)},inputs,null,SparseToDense,attrs)}var sparseToDense=op({sparseToDense_});function gatherND_(x,indices){var $indices=convertToTensor(indices,"indices","gatherND","int32");var $x=convertToTensor(x,"x","gatherND");var forward=function(backend2){return backend2.gatherND($x,$indices)};var inputs={params:$x,indices:$indices};return ENGINE.runKernelFunc(forward,inputs,null,GatherNd3)}var gatherND=op({gatherND_});function getNoiseShape(x,noiseShape){if(noiseShape==null){return x.shape.slice()}if(arraysEqual(x.shape,noiseShape)){return noiseShape}if(x.shape.length===noiseShape.length){var newDimension=[];for(var i=0;i=0&&rate<1,function(){return"rate must be a float in the range [0, 1), but got "+rate+"."});if(rate===0){return x instanceof Tensor?$x.clone():$x}var $noiseShape=getNoiseShape($x,noiseShape);var keepProb=1-rate;var multiplier=div(floor(add$1(randomUniform($noiseShape,0,1,"float32",seed),keepProb)),keepProb);return mul($x,multiplier)}var dropout=op({dropout_});function enclosingPowerOfTwo(value){return Math.floor(Math.pow(2,Math.ceil(Math.log(value)/Math.log(2))))}function cosineWindow(windowLength,a,b){var even=1-windowLength%2;var newValues=new Float32Array(windowLength);for(var i=0;i1,function(){return"inTopK() expects the predictions to be of rank 2 or higher, "+("but got "+$predictions.rank)});assert($predictions.rank-1===$targets.rank,function(){return"predictions rank should be 1 larger than targets rank, but got predictions rank "+($predictions.rank+" and targets rank "+$targets.rank)});assertShapesMatch($predictions.shape.slice(0,$predictions.shape.length-1),$targets.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");lastDim=$predictions.shape[$predictions.shape.length-1];assert(k>0&&k<=lastDim,function(){return"'k' passed to inTopK() must be > 0 && <= the predictions last "+("dimension ("+lastDim+"), but got "+k)});return[4,$predictions.data()];case 1:predictionsVals=_b.sent();return[4,$targets.data()];case 2:targetsVals=_b.sent();_a=[predictionsVals.length/lastDim,lastDim],batch=_a[0],size=_a[1];precision=getTypedArrayFromDType("bool",batch);for(b=0;b0){res=sum$1(res,reduceAxes)}return reshape2(res,bias.shape)}function applyActivation(x,activation,preluActivationWeights){if(activation==="linear"){return x}else if(activation==="relu"){return relu(x)}else if(activation==="elu"){return elu(x)}else if(activation==="relu6"){return relu6(x)}else if(activation==="prelu"){return prelu2(x,preluActivationWeights)}throw new Error("Unknown fused activation "+activation+".")}var shouldFuse=function(gradientDepth,activation){var gradientMode=gradientDepth>0;return!gradientMode||activation==="linear"};function fusedConv2d_(_a){var x=_a.x,filter=_a.filter,strides=_a.strides,pad3=_a.pad,_b=_a.dataFormat,dataFormat=_b===void 0?"NHWC":_b,_c=_a.dilations,dilations=_c===void 0?[1,1]:_c,dimRoundingMode=_a.dimRoundingMode,bias=_a.bias,_d=_a.activation,activation=_d===void 0?"linear":_d,preluActivationWeights=_a.preluActivationWeights;activation=activation||"linear";if(shouldFuse(ENGINE.state.gradientDepth,activation)===false){var result=conv2d2(x,filter,strides,pad3,dataFormat,dilations,dimRoundingMode);if(bias!=null){result=add$1(result,bias)}return applyActivation(result,activation,preluActivationWeights)}var $x=convertToTensor(x,"x","conv2d");var $filter=convertToTensor(filter,"filter","conv2d");var x4D=$x;var reshapedTo4D=false;if($x.rank===3){reshapedTo4D=true;x4D=reshape2($x,[1,$x.shape[0],$x.shape[1],$x.shape[2]])}assert(x4D.rank===4,function(){return"Error in fused conv2d: input must be rank 4, but got rank "+(x4D.rank+".")});assert($filter.rank===4,function(){return"Error in fused conv2d: filter must be rank 4, but got rank "+($filter.rank+".")});if(dimRoundingMode!=null){assert(isInt(pad3),function(){return"Error in fused conv2d: pad must be an integer when using, "+("dimRoundingMode "+dimRoundingMode+" but got pad "+pad3+".")})}assert(x4D.shape[3]===$filter.shape[2],function(){return"Error in conv2d: depth of input ("+x4D.shape[3]+") must match "+("input depth for filter "+$filter.shape[2]+".")});assert(eitherStridesOrDilationsAreOne(strides,dilations),function(){return"Error in conv2D: Either strides or dilations must be 1. "+("Got strides "+strides+" and dilations '"+dilations+"'")});assert(dataFormat==="NHWC",function(){return"Error in conv2d: got dataFormat of "+dataFormat+" but only NHWC is currently supported."});var convInfo=computeConv2DInfo(x4D.shape,$filter.shape,strides,dilations,pad3,dimRoundingMode);var $bias;if(bias!=null){$bias=convertToTensor(bias,"bias","fused conv2d");$bias=makeTypesMatch($bias,$x)[0];assertAndGetBroadcastShape(convInfo.outShape,$bias.shape)}var $preluActivationWeights;if(preluActivationWeights!=null){$preluActivationWeights=convertToTensor(preluActivationWeights,"prelu weights","fused conv2d")}var grad2=function(dy,saved){var _a2=saved,$filter2=_a2[0],x4D2=_a2[1],y=_a2[2],$bias2=_a2[3];var dyActivation=getFusedDyActivation(dy,y,activation);assert(tupleValuesAreOne(dilations),function(){return"Error in gradient of fused conv2D: dilation rates greater than 1 "+("are not yet supported in gradients. Got dilations '"+dilations+"'")});var xDer=conv2DBackpropInput2(x4D2.shape,dyActivation,$filter2,strides,pad3);var filterDer=conv2DBackpropFilter(x4D2,dyActivation,$filter2.shape,strides,pad3);var der=[xDer,filterDer];if($bias2!=null){var biasDer=getFusedBiasGradient($bias2,dyActivation);der.push(biasDer)}return der};var forward=function(backend2){var res=backend2.fusedConv2d({input:x4D,filter:$filter,convInfo,bias:$bias,activation,preluActivationWeights:$preluActivationWeights});return res};var inputs={x:x4D,filter:$filter,bias:$bias,preluActivationWeights:$preluActivationWeights};var attrs={strides,pad:pad3,dataFormat,dilations,dimRoundingMode,activation};if(bias==null){var customOp=customGrad(function(x4D2,filter2,save){var res=ENGINE.runKernelFunc(forward,inputs,null,FusedConv2D3,attrs);save([filter2,x4D2,res]);if(reshapedTo4D){res=reshape2(res,[res.shape[1],res.shape[2],res.shape[3]])}return{value:res,gradFunc:grad2}});return customOp(x4D,$filter)}else{var customOpWithBias=customGrad(function(x4D2,filter2,bias2,save){var res=ENGINE.runKernelFunc(forward,inputs,null,FusedConv2D3,attrs);save([filter2,x4D2,res,bias2]);if(reshapedTo4D){res=reshape2(res,[res.shape[1],res.shape[2],res.shape[3]])}return{value:res,gradFunc:grad2}});return customOpWithBias(x4D,$filter,$bias)}}var conv2d$1=op({fusedConv2d_});function depthwiseConv2dNativeBackpropFilter_(x,dy,filterShape,strides,pad3,dilations,dimRoundingMode){if(dilations===void 0){dilations=[1,1]}var x4D=x;if(x.rank===3){x4D=reshape2(x,[1,x.shape[0],x.shape[1],x.shape[2]])}var dy4D=dy;if(dy4D.rank===3){dy4D=reshape2(dy,[1,dy.shape[0],dy.shape[1],dy.shape[2]])}var forward=function(backend2){var convInfo=computeConv2DInfo(x.shape,filterShape,strides,dilations,pad3,dimRoundingMode,true);return backend2.depthwiseConv2DDerFilter(x4D,dy4D,convInfo)};var inputs={x:x4D,dy:dy4D};var attrs={strides,pad:pad3,dimRoundingMode,dilations,filterShape};return ENGINE.runKernelFunc(forward,inputs,null,DepthwiseConv2dNativeBackpropFilter,attrs)}var depthwiseConv2dNativeBackpropFilter=op({depthwiseConv2dNativeBackpropFilter_});function depthwiseConv2dNativeBackpropInput_(xShape,dy,filter,strides,pad3,dilations,dimRoundingMode){if(dilations===void 0){dilations=[1,1]}var dy4D=dy;var reshapedTo4D=false;if(dy.rank===3){reshapedTo4D=true;dy4D=reshape2(dy,[1,dy.shape[0],dy.shape[1],dy.shape[2]])}var forward=function(backend2){var convInfo=computeConv2DInfo(xShape,filter.shape,strides,dilations,pad3,dimRoundingMode,true);return backend2.depthwiseConv2DDerInput(dy4D,filter,convInfo)};var inputs={dy:dy4D,filter};var attrs={strides,pad:pad3,dimRoundingMode,dilations,inputShape:xShape};var res=ENGINE.runKernelFunc(forward,inputs,null,DepthwiseConv2dNativeBackpropInput,attrs);if(reshapedTo4D){return reshape2(res,[res.shape[1],res.shape[2],res.shape[3]])}return res}var depthwiseConv2dNativeBackpropInput=op({depthwiseConv2dNativeBackpropInput_});function fusedDepthwiseConv2d_(_a){var x=_a.x,filter=_a.filter,strides=_a.strides,pad3=_a.pad,_b=_a.dataFormat,dataFormat=_b===void 0?"NHWC":_b,_c=_a.dilations,dilations=_c===void 0?[1,1]:_c,dimRoundingMode=_a.dimRoundingMode,bias=_a.bias,_d=_a.activation,activation=_d===void 0?"linear":_d,preluActivationWeights=_a.preluActivationWeights;if(shouldFuse(ENGINE.state.gradientDepth,activation)===false){var result=depthwiseConv2d2(x,filter,strides,pad3,dataFormat,dilations,dimRoundingMode);if(bias!=null){result=add$1(result,bias)}return applyActivation(result,activation,preluActivationWeights)}var $x=convertToTensor(x,"x","depthwiseConv2d");var $filter=convertToTensor(filter,"filter","depthwiseConv2d");var x4D=$x;var reshapedTo4D=false;if($x.rank===3){reshapedTo4D=true;x4D=reshape2($x,[1,$x.shape[0],$x.shape[1],$x.shape[2]])}assert(x4D.rank===4,function(){return"Error in fused depthwiseConv2d: input must be rank 4, but got "+("rank "+x4D.rank+".")});assert($filter.rank===4,function(){return"Error in fused depthwiseConv2d: filter must be rank 4, "+("but got rank "+$filter.rank+".")});assert(x4D.shape[3]===$filter.shape[2],function(){return"Error in fused depthwiseConv2d: number of input channels "+("("+x4D.shape[3]+") must match the inChannels dimension in ")+("filter "+$filter.shape[2]+".")});if(dilations==null){dilations=[1,1]}assert(eitherStridesOrDilationsAreOne(strides,dilations),function(){return"Error in fused depthwiseConv2d: Either strides or dilations must "+("be 1. Got strides "+strides+" and dilations '"+dilations+"'")});if(dimRoundingMode!=null){assert(isInt(pad3),function(){return"Error in fused depthwiseConv2d: pad must be an integer when "+("using dimRoundingMode "+dimRoundingMode+" but got pad "+pad3+".")})}var convInfo=computeConv2DInfo(x4D.shape,$filter.shape,strides,dilations,pad3,dimRoundingMode,true);var $bias;if(bias!=null){$bias=convertToTensor(bias,"bias","fused conv2d");$bias=makeTypesMatch($bias,$x)[0];assertAndGetBroadcastShape(convInfo.outShape,$bias.shape)}var $preluActivationWeights;if(preluActivationWeights!=null){$preluActivationWeights=convertToTensor(preluActivationWeights,"prelu weights","fused depthwiseConv2d")}var grad2=function(dy,saved){assert(tupleValuesAreOne(dilations),function(){return"Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations "+("'"+dilations+"'")});var $filter2=saved[0],x4D2=saved[1],y=saved[2],bias2=saved[3];var dyActivation=getFusedDyActivation(dy,y,activation);var xDer=depthwiseConv2dNativeBackpropInput(x4D2.shape,dyActivation,$filter2,strides,pad3,dilations,dimRoundingMode);var filterDer=depthwiseConv2dNativeBackpropFilter(x4D2,dyActivation,$filter2.shape,strides,pad3,dilations,dimRoundingMode);if(bias2!=null){var biasDer=getFusedBiasGradient($bias,dyActivation);return[xDer,filterDer,biasDer]}return[xDer,filterDer]};var forward=function(backend2){var res=backend2.fusedDepthwiseConv2D({input:x4D,filter:$filter,convInfo,bias:$bias,activation,preluActivationWeights:$preluActivationWeights});return res};var inputs={x:x4D,filter:$filter,bias:$bias,preluActivationWeights:$preluActivationWeights};var attrs={strides,pad:pad3,dataFormat,dilations,dimRoundingMode,activation};if(bias==null){var customOp=customGrad(function(x4D2,filter2,save){var res=ENGINE.runKernelFunc(forward,inputs,null,FusedDepthwiseConv2D3,attrs);save([filter2,x4D2,res]);if(reshapedTo4D){res=reshape2(res,[res.shape[1],res.shape[2],res.shape[3]])}return{value:res,gradFunc:grad2}});return customOp(x4D,$filter)}else{var customOpWithBias=customGrad(function(x4D2,filter2,bias2,save){var res=ENGINE.runKernelFunc(forward,inputs,null,FusedDepthwiseConv2D3,attrs);save([filter2,x4D2,res,bias2]);if(reshapedTo4D){res=reshape2(res,[res.shape[1],res.shape[2],res.shape[3]])}return{value:res,gradFunc:grad2}});return customOpWithBias(x4D,$filter,$bias)}}var depthwiseConv2d$1=op({fusedDepthwiseConv2d_});function fusedMatMul_(_a){var _b;var a=_a.a,b=_a.b,_c=_a.transposeA,transposeA=_c===void 0?false:_c,_d=_a.transposeB,transposeB=_d===void 0?false:_d,bias=_a.bias,_e=_a.activation,activation=_e===void 0?"linear":_e,preluActivationWeights=_a.preluActivationWeights;if(shouldFuse(ENGINE.state.gradientDepth,activation)===false){var result=matMul(a,b,transposeA,transposeB);if(bias!=null){result=add$1(result,bias)}return applyActivation(result,activation,preluActivationWeights)}var $a=convertToTensor(a,"a","fused matMul");var $b=convertToTensor(b,"b","fused matMul");_b=makeTypesMatch($a,$b),$a=_b[0],$b=_b[1];var innerShapeA=transposeA?$a.shape[$a.rank-2]:$a.shape[$a.rank-1];var innerShapeB=transposeB?$b.shape[$b.rank-1]:$b.shape[$b.rank-2];var outerShapeA=transposeA?$a.shape[$a.rank-1]:$a.shape[$a.rank-2];var outerShapeB=transposeB?$b.shape[$b.rank-2]:$b.shape[$b.rank-1];var outerDimsA=$a.shape.slice(0,-2);var outerDimsB=$b.shape.slice(0,-2);var batchDimA=sizeFromShape(outerDimsA);var batchDimB=sizeFromShape(outerDimsB);assert($a.rank>=2&&$b.rank>=2&&$a.rank===$b.rank,function(){return"Error in fused matMul: inputs must have the same rank of at least "+("2, got ranks "+$a.rank+" and "+$b.rank+".")});assert(arraysEqual(outerDimsA,outerDimsB),function(){return"Error in fused matMul: outer dimensions ("+outerDimsA+") and ("+(outerDimsB+") of Tensors with shapes "+$a.shape+" and ")+($b.shape+" must match.")});assert(innerShapeA===innerShapeB,function(){return"Error in fused matMul: inner shapes ("+innerShapeA+") and ("+(innerShapeB+") of Tensors with shapes "+$a.shape+" and ")+($b.shape+" and transposeA="+transposeA)+(" and transposeB="+transposeB+" must match.")});var outShape=$a.shape.slice(0,-2).concat([outerShapeA,outerShapeB]);var a3D=transposeA?reshape2($a,[batchDimA,innerShapeA,outerShapeA]):reshape2($a,[batchDimA,outerShapeA,innerShapeA]);var b3D=transposeB?reshape2($b,[batchDimB,outerShapeB,innerShapeB]):reshape2($b,[batchDimB,innerShapeB,outerShapeB]);var $bias;if(bias!=null){$bias=convertToTensor(bias,"bias","fused matMul");$bias=makeTypesMatch($bias,$a)[0];assertAndGetBroadcastShape(outShape,$bias.shape)}var $preluActivationWeights;if(preluActivationWeights!=null){$preluActivationWeights=convertToTensor(preluActivationWeights,"prelu weights","fused matMul")}var grad2=function(dy,saved){var a3D2=saved[0],b3D2=saved[1],y=saved[2],$bias2=saved[3];var dyActivation=getFusedDyActivation(reshape2(dy,y.shape),y,activation);var aDer;var bDer;if(!transposeA&&!transposeB){aDer=matMul(dyActivation,b3D2,false,true);bDer=matMul(a3D2,dyActivation,true,false)}else if(!transposeA&&transposeB){aDer=matMul(dyActivation,b3D2,false,false);bDer=matMul(dyActivation,a3D2,true,false)}else if(transposeA&&!transposeB){aDer=matMul(b3D2,dyActivation,false,true);bDer=matMul(a3D2,dyActivation,false,false)}else{aDer=matMul(b3D2,dyActivation,true,true);bDer=matMul(dyActivation,a3D2,true,true)}if(bias!=null){var biasDer=getFusedBiasGradient($bias2,dyActivation);return[aDer,bDer,biasDer]}else{return[aDer,bDer]}};var forward=function(backend2){var y=backend2.fusedBatchMatMul({a:a3D,b:b3D,transposeA,transposeB,bias:$bias,activation,preluActivationWeights:$preluActivationWeights});return y};var inputs={a:a3D,b:b3D,bias:$bias,preluActivationWeights:$preluActivationWeights};var attrs={transposeA,transposeB,activation};if(bias==null){var customOp=customGrad(function(a3D2,b3D2,save){var res=ENGINE.runKernelFunc(forward,inputs,null,_FusedMatMul2,attrs);save([a3D2,b3D2,res]);return{value:reshape2(res,outShape),gradFunc:grad2}});return customOp(a3D,b3D)}else{var customOpWithBias=customGrad(function(a3D2,b3D2,$bias2,save){var res=ENGINE.runKernelFunc(forward,inputs,null,_FusedMatMul2,attrs);save([a3D2,b3D2,res,$bias2]);return{value:reshape2(res,outShape),gradFunc:grad2}});return customOpWithBias(a3D,b3D,$bias)}}var matMul$1=op({fusedMatMul_});var fused_ops={__proto__:null,conv2d:conv2d$1,depthwiseConv2d:depthwiseConv2d$1,matMul:matMul$1};function hammingWindow_(windowLength){return cosineWindow(windowLength,.54,.46)}var hammingWindow=op({hammingWindow_});function hannWindow_(windowLength){return cosineWindow(windowLength,.5,.5)}var hannWindow=op({hannWindow_});function frame_(signal2,frameLength,frameStep,padEnd,padValue){if(padEnd===void 0){padEnd=false}if(padValue===void 0){padValue=0}var start=0;var output=[];while(start+frameLength<=signal2.size){output.push(slice2(signal2,start,frameLength));start+=frameStep}if(padEnd){while(start=1&&cropSize[1]>=1,function(){return"cropSize must be atleast [1,1], but was "+cropSize});assert(method==="bilinear"||method==="nearest",function(){return"method must be bilinear or nearest, but was "+method});var forward=function(backend2){return backend2.cropAndResize($image,$boxes,$boxInd,cropSize,method,extrapolationValue)};var inputs={image:$image,boxes:$boxes,boxInd:$boxInd};var attrs={method,extrapolationValue,cropSize};var res=ENGINE.runKernelFunc(forward,inputs,null,CropAndResize3,attrs);return res}var cropAndResize2=op({cropAndResize_});function flipLeftRight_(image3){var $image=convertToTensor(image3,"image","flipLeftRight","float32");assert($image.rank===4,function(){return"Error in flipLeftRight: image must be rank 4,"+("but got rank "+$image.rank+".")});var inputs={image:$image};var res=ENGINE.runKernel(FlipLeftRight3,inputs,{});return res}var flipLeftRight2=op({flipLeftRight_});function rotateWithOffset_(image3,radians,fillValue,center){if(fillValue===void 0){fillValue=0}if(center===void 0){center=.5}var $image=convertToTensor(image3,"image","rotateWithOffset","float32");assert($image.rank===4,function(){return"Error in rotateWithOffset: image must be rank 4,"+("but got rank "+$image.rank+".")});var inputs={image:$image};var attrs={radians,fillValue,center};var res=ENGINE.runKernel(RotateWithOffset3,inputs,attrs);return res}var rotateWithOffset2=op({rotateWithOffset_});function nonMaxSuppSanityCheck(boxes,scores,maxOutputSize,iouThreshold,scoreThreshold,softNmsSigma){if(iouThreshold==null){iouThreshold=.5}if(scoreThreshold==null){scoreThreshold=Number.NEGATIVE_INFINITY}if(softNmsSigma==null){softNmsSigma=0}var numBoxes=boxes.shape[0];maxOutputSize=Math.min(maxOutputSize,numBoxes);assert(0<=iouThreshold&&iouThreshold<=1,function(){return"iouThreshold must be in [0, 1], but was '"+iouThreshold+"'"});assert(boxes.rank===2,function(){return"boxes must be a 2D tensor, but was of rank '"+boxes.rank+"'"});assert(boxes.shape[1]===4,function(){return"boxes must have 4 columns, but 2nd dimension was "+boxes.shape[1]});assert(scores.rank===1,function(){return"scores must be a 1D tensor"});assert(scores.shape[0]===numBoxes,function(){return"scores has incompatible shape with boxes. Expected "+numBoxes+", "+("but was "+scores.shape[0])});assert(0<=softNmsSigma&&softNmsSigma<=1,function(){return"softNmsSigma must be in [0, 1], but was '"+softNmsSigma+"'"});return{maxOutputSize,iouThreshold,scoreThreshold,softNmsSigma}}function nonMaxSuppression_(boxes,scores,maxOutputSize,iouThreshold,scoreThreshold){if(iouThreshold===void 0){iouThreshold=.5}if(scoreThreshold===void 0){scoreThreshold=Number.NEGATIVE_INFINITY}var $boxes=convertToTensor(boxes,"boxes","nonMaxSuppression");var $scores=convertToTensor(scores,"scores","nonMaxSuppression");var inputs=nonMaxSuppSanityCheck($boxes,$scores,maxOutputSize,iouThreshold,scoreThreshold);maxOutputSize=inputs.maxOutputSize;iouThreshold=inputs.iouThreshold;scoreThreshold=inputs.scoreThreshold;var attrs={maxOutputSize,iouThreshold,scoreThreshold};return ENGINE.runKernelFunc(function(b){return b.nonMaxSuppression($boxes,$scores,maxOutputSize,iouThreshold,scoreThreshold)},{boxes:$boxes,scores:$scores},null,NonMaxSuppressionV33,attrs)}var nonMaxSuppression=op({nonMaxSuppression_});function binaryInsert(arr,element,comparator){var index=binarySearch(arr,element,comparator);var insertionPoint=index<0?-(index+1):index;arr.splice(insertionPoint,0,element)}function binarySearch(arr,target,comparator){return binarySearch_(arr,target,comparator||defaultComparator)}function defaultComparator(a,b){return a>b?1:a>>1);var compareResult=comparator(target,arr[middle]);if(compareResult>0){left=middle+1}else{right=middle;found=!compareResult}}return found?left:-left-1}function nonMaxSuppressionV3Impl(boxes,scores,maxOutputSize,iouThreshold,scoreThreshold){return nonMaxSuppressionImpl_(boxes,scores,maxOutputSize,iouThreshold,scoreThreshold,0).selectedIndices}function nonMaxSuppressionV4Impl(boxes,scores,maxOutputSize,iouThreshold,scoreThreshold,padToMaxOutputSize){return nonMaxSuppressionImpl_(boxes,scores,maxOutputSize,iouThreshold,scoreThreshold,0,false,padToMaxOutputSize,true)}function nonMaxSuppressionV5Impl(boxes,scores,maxOutputSize,iouThreshold,scoreThreshold,softNmsSigma){return nonMaxSuppressionImpl_(boxes,scores,maxOutputSize,iouThreshold,scoreThreshold,softNmsSigma,true)}function nonMaxSuppressionImpl_(boxes,scores,maxOutputSize,iouThreshold,scoreThreshold,softNmsSigma,returnScoresTensor,padToMaxOutputSize,returnValidOutputs){if(returnScoresTensor===void 0){returnScoresTensor=false}if(padToMaxOutputSize===void 0){padToMaxOutputSize=false}if(returnValidOutputs===void 0){returnValidOutputs=false}var candidates=[];for(var i=0;iscoreThreshold){candidates.push({score:scores[i],boxIndex:i,suppressBeginIndex:0})}}candidates.sort(ascendingComparator);var scale=softNmsSigma>0?-.5/softNmsSigma:0;var selectedIndices=[];var selectedScores=[];while(selectedIndices.length0){var candidate=candidates.pop();var originalScore=candidate.score,boxIndex=candidate.boxIndex,suppressBeginIndex=candidate.suppressBeginIndex;if(originalScore=suppressBeginIndex;--j){var iou=intersectionOverUnion(boxes,boxIndex,selectedIndices[j]);if(iou>=iouThreshold){ignoreCandidate=true;break}candidate.score=candidate.score*suppressWeight(iouThreshold,scale,iou);if(candidate.score<=scoreThreshold){break}}candidate.suppressBeginIndex=selectedIndices.length;if(!ignoreCandidate){if(candidate.score===originalScore){selectedIndices.push(boxIndex);selectedScores.push(candidate.score)}else if(candidate.score>scoreThreshold){binaryInsert(candidates,candidate,ascendingComparator)}}}var validOutputs=selectedIndices.length;var elemsToPad=maxOutputSize-validOutputs;if(padToMaxOutputSize&&elemsToPad>0){selectedIndices.push.apply(selectedIndices,new Array(elemsToPad).fill(0));selectedScores.push.apply(selectedScores,new Array(elemsToPad).fill(0))}var result={selectedIndices:tensor1d(selectedIndices,"int32")};if(returnScoresTensor){result["selectedScores"]=tensor1d(selectedScores,"float32")}if(returnValidOutputs){result["validOutputs"]=scalar(validOutputs,"int32")}return result}function intersectionOverUnion(boxes,i,j){var iCoord=boxes.subarray(i*4,i*4+4);var jCoord=boxes.subarray(j*4,j*4+4);var yminI=Math.min(iCoord[0],iCoord[2]);var xminI=Math.min(iCoord[1],iCoord[3]);var ymaxI=Math.max(iCoord[0],iCoord[2]);var xmaxI=Math.max(iCoord[1],iCoord[3]);var yminJ=Math.min(jCoord[0],jCoord[2]);var xminJ=Math.min(jCoord[1],jCoord[3]);var ymaxJ=Math.max(jCoord[0],jCoord[2]);var xmaxJ=Math.max(jCoord[1],jCoord[3]);var areaI=(ymaxI-yminI)*(xmaxI-xminI);var areaJ=(ymaxJ-yminJ)*(xmaxJ-xminJ);if(areaI<=0||areaJ<=0){return 0}var intersectionYmin=Math.max(yminI,yminJ);var intersectionXmin=Math.max(xminI,xminJ);var intersectionYmax=Math.min(ymaxI,ymaxJ);var intersectionXmax=Math.min(xmaxI,xmaxJ);var intersectionArea=Math.max(intersectionYmax-intersectionYmin,0)*Math.max(intersectionXmax-intersectionXmin,0);return intersectionArea/(areaI+areaJ-intersectionArea)}function suppressWeight(iouThreshold,scale,iou){var weight=Math.exp(scale*iou*iou);return iou<=iouThreshold?weight:0}function ascendingComparator(c1,c2){return c1.score-c2.score||c1.score===c2.score&&c2.boxIndex-c1.boxIndex}function nonMaxSuppressionAsync_(boxes,scores,maxOutputSize,iouThreshold,scoreThreshold){if(iouThreshold===void 0){iouThreshold=.5}if(scoreThreshold===void 0){scoreThreshold=Number.NEGATIVE_INFINITY}return __awaiter(this,void 0,void 0,function(){var $boxes,$scores,inputs,boxesAndScores,boxesVals,scoresVals,res;return __generator(this,function(_a){switch(_a.label){case 0:$boxes=convertToTensor(boxes,"boxes","nonMaxSuppressionAsync");$scores=convertToTensor(scores,"scores","nonMaxSuppressionAsync");inputs=nonMaxSuppSanityCheck($boxes,$scores,maxOutputSize,iouThreshold,scoreThreshold);maxOutputSize=inputs.maxOutputSize;iouThreshold=inputs.iouThreshold;scoreThreshold=inputs.scoreThreshold;return[4,Promise.all([$boxes.data(),$scores.data()])];case 1:boxesAndScores=_a.sent();boxesVals=boxesAndScores[0];scoresVals=boxesAndScores[1];res=nonMaxSuppressionV3Impl(boxesVals,scoresVals,maxOutputSize,iouThreshold,scoreThreshold);if($boxes!==boxes){$boxes.dispose()}if($scores!==scores){$scores.dispose()}return[2,res]}})})}var nonMaxSuppressionAsync=nonMaxSuppressionAsync_;function nonMaxSuppressionWithScore_(boxes,scores,maxOutputSize,iouThreshold,scoreThreshold,softNmsSigma){if(iouThreshold===void 0){iouThreshold=.5}if(scoreThreshold===void 0){scoreThreshold=Number.NEGATIVE_INFINITY}if(softNmsSigma===void 0){softNmsSigma=0}var $boxes=convertToTensor(boxes,"boxes","nonMaxSuppression");var $scores=convertToTensor(scores,"scores","nonMaxSuppression");var params=nonMaxSuppSanityCheck($boxes,$scores,maxOutputSize,iouThreshold,scoreThreshold,softNmsSigma);maxOutputSize=params.maxOutputSize;iouThreshold=params.iouThreshold;scoreThreshold=params.scoreThreshold;softNmsSigma=params.softNmsSigma;var inputs={boxes:$boxes,scores:$scores};var attrs={maxOutputSize,iouThreshold,scoreThreshold,softNmsSigma};var result=ENGINE.runKernel(NonMaxSuppressionV53,inputs,attrs);return{selectedIndices:result[0],selectedScores:result[1]}}var nonMaxSuppressionWithScore=op({nonMaxSuppressionWithScore_});function nonMaxSuppressionWithScoreAsync_(boxes,scores,maxOutputSize,iouThreshold,scoreThreshold,softNmsSigma){if(iouThreshold===void 0){iouThreshold=.5}if(scoreThreshold===void 0){scoreThreshold=Number.NEGATIVE_INFINITY}if(softNmsSigma===void 0){softNmsSigma=0}return __awaiter(this,void 0,void 0,function(){var $boxes,$scores,params,boxesAndScores,boxesVals,scoresVals,res;return __generator(this,function(_a){switch(_a.label){case 0:$boxes=convertToTensor(boxes,"boxes","nonMaxSuppressionAsync");$scores=convertToTensor(scores,"scores","nonMaxSuppressionAsync");params=nonMaxSuppSanityCheck($boxes,$scores,maxOutputSize,iouThreshold,scoreThreshold,softNmsSigma);maxOutputSize=params.maxOutputSize;iouThreshold=params.iouThreshold;scoreThreshold=params.scoreThreshold;softNmsSigma=params.softNmsSigma;return[4,Promise.all([$boxes.data(),$scores.data()])];case 1:boxesAndScores=_a.sent();boxesVals=boxesAndScores[0];scoresVals=boxesAndScores[1];res=nonMaxSuppressionV5Impl(boxesVals,scoresVals,maxOutputSize,iouThreshold,scoreThreshold,softNmsSigma);if($boxes!==boxes){$boxes.dispose()}if($scores!==scores){$scores.dispose()}return[2,res]}})})}var nonMaxSuppressionWithScoreAsync=nonMaxSuppressionWithScoreAsync_;function nonMaxSuppressionPadded_(boxes,scores,maxOutputSize,iouThreshold,scoreThreshold,padToMaxOutputSize){if(iouThreshold===void 0){iouThreshold=.5}if(scoreThreshold===void 0){scoreThreshold=Number.NEGATIVE_INFINITY}if(padToMaxOutputSize===void 0){padToMaxOutputSize=false}var $boxes=convertToTensor(boxes,"boxes","nonMaxSuppression");var $scores=convertToTensor(scores,"scores","nonMaxSuppression");var params=nonMaxSuppSanityCheck($boxes,$scores,maxOutputSize,iouThreshold,scoreThreshold,null);var $maxOutputSize=params.maxOutputSize;var $iouThreshold=params.iouThreshold;var $scoreThreshold=params.scoreThreshold;var inputs={boxes:$boxes,scores:$scores};var attrs={maxOutputSize:$maxOutputSize,iouThreshold:$iouThreshold,scoreThreshold:$scoreThreshold,padToMaxOutputSize};var result=ENGINE.runKernel(NonMaxSuppressionV43,inputs,attrs);return{selectedIndices:result[0],validOutputs:result[1]}}var nonMaxSuppressionPadded=op({nonMaxSuppressionPadded_});function nonMaxSuppressionPaddedAsync_(boxes,scores,maxOutputSize,iouThreshold,scoreThreshold,padToMaxOutputSize){if(iouThreshold===void 0){iouThreshold=.5}if(scoreThreshold===void 0){scoreThreshold=Number.NEGATIVE_INFINITY}if(padToMaxOutputSize===void 0){padToMaxOutputSize=false}return __awaiter(this,void 0,void 0,function(){var $boxes,$scores,params,$maxOutputSize,$iouThreshold,$scoreThreshold,_a,boxesVals,scoresVals,res;return __generator(this,function(_b){switch(_b.label){case 0:$boxes=convertToTensor(boxes,"boxes","nonMaxSuppressionAsync");$scores=convertToTensor(scores,"scores","nonMaxSuppressionAsync");params=nonMaxSuppSanityCheck($boxes,$scores,maxOutputSize,iouThreshold,scoreThreshold,null);$maxOutputSize=params.maxOutputSize;$iouThreshold=params.iouThreshold;$scoreThreshold=params.scoreThreshold;return[4,Promise.all([$boxes.data(),$scores.data()])];case 1:_a=_b.sent(),boxesVals=_a[0],scoresVals=_a[1];res=nonMaxSuppressionV4Impl(boxesVals,scoresVals,$maxOutputSize,$iouThreshold,$scoreThreshold,padToMaxOutputSize);if($boxes!==boxes){$boxes.dispose()}if($scores!==scores){$scores.dispose()}return[2,res]}})})}var nonMaxSuppressionPaddedAsync=nonMaxSuppressionPaddedAsync_;function resizeBilinear_(images,size,alignCorners){if(alignCorners===void 0){alignCorners=false}var $images=convertToTensor(images,"images","resizeBilinear");assert($images.rank===3||$images.rank===4,function(){return"Error in resizeBilinear: x must be rank 3 or 4, but got "+("rank "+$images.rank+".")});assert(size.length===2,function(){return"Error in resizeBilinear: new shape must 2D, but got shape "+(size+".")});var batchImages=$images;var reshapedTo4D=false;if($images.rank===3){reshapedTo4D=true;batchImages=reshape2($images,[1,$images.shape[0],$images.shape[1],$images.shape[2]])}var newHeight=size[0],newWidth=size[1];var forward=function(backend2,save){save([batchImages]);return backend2.resizeBilinear(batchImages,newHeight,newWidth,alignCorners)};var inputs={images:batchImages};var attrs={alignCorners,size};var res=ENGINE.runKernelFunc(forward,inputs,null,ResizeBilinear3,attrs);if(reshapedTo4D){return reshape2(res,[res.shape[1],res.shape[2],res.shape[3]])}return res}var resizeBilinear2=op({resizeBilinear_});function resizeNearestNeighbor_(images,size,alignCorners){if(alignCorners===void 0){alignCorners=false}var $images=convertToTensor(images,"images","resizeNearestNeighbor");assert($images.rank===3||$images.rank===4,function(){return"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got "+("rank "+$images.rank+".")});assert(size.length===2,function(){return"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+(size+".")});assert($images.dtype==="float32"||$images.dtype==="int32",function(){return"`images` must have `int32` or `float32` as dtype"});var batchImages=$images;var reshapedTo4D=false;if($images.rank===3){reshapedTo4D=true;batchImages=reshape2($images,[1,$images.shape[0],$images.shape[1],$images.shape[2]])}var newHeight=size[0],newWidth=size[1];var inputs={images:batchImages};var attrs={alignCorners,size};var forward=function(backend2,save){save([batchImages]);return backend2.resizeNearestNeighbor(batchImages,newHeight,newWidth,alignCorners)};var res=ENGINE.runKernelFunc(forward,inputs,null,ResizeNearestNeighbor,attrs);if(reshapedTo4D){return reshape2(res,[res.shape[1],res.shape[2],res.shape[3]])}return res}var resizeNearestNeighbor=op({resizeNearestNeighbor_});function bandPart_(a,numLower,numUpper){assert(numLower%1===0,function(){return"bandPart(): numLower must be an integer, got "+numLower+"."});assert(numUpper%1===0,function(){return"bandPart(): numUpper must be an integer, got "+numUpper+"."});var $a=convertToTensor(a,"a","bandPart");assert($a.rank>=2,function(){return"bandPart(): Rank must be at least 2, got "+$a.rank+"."});var shape=$a.shape;var _a=$a.shape.slice(-2),M=_a[0],N=_a[1];if(!(numLower<=M)){throw new Error("bandPart(): numLower ("+numLower+")"+(" must not be greater than the number of rows ("+M+")."))}if(!(numUpper<=N)){throw new Error("bandPart(): numUpper ("+numUpper+")"+(" must not be greater than the number of columns ("+N+")."))}if(numLower<0){numLower=M}if(numUpper<0){numUpper=N}var i=reshape2(range(0,M,1,"int32"),[-1,1]);var j=range(0,N,1,"int32");var ij=sub(i,j);var inBand=logicalAnd(lessEqual(ij,scalar(+numLower,"int32")),greaterEqual(ij,scalar(-numUpper,"int32")));var zero=zeros([M,N],$a.dtype);return reshape2(stack(unstack(reshape2($a,[-1,M,N])).map(function(mat){return where(inBand,mat,zero)})),shape)}var bandPart=op({bandPart_});function gramSchmidt_(xs){var inputIsTensor2D;if(Array.isArray(xs)){inputIsTensor2D=false;assert(xs!=null&&xs.length>0,function(){return"Gram-Schmidt process: input must not be null, undefined, or empty"});var dim_1=xs[0].shape[0];var _loop_1=function(i2){assert(xs[i2].shape[0]===dim_1,function(){return"Gram-Schmidt: Non-unique lengths found in the input vectors: "+("("+xs[i2].shape[0]+" vs. "+dim_1+")")})};for(var i=1;i0){for(var j=0;j=2,function(){return"qr() requires input tensor to have a rank >= 2, but got rank "+x.rank});if(x.rank===2){return qr2d(x,fullMatrices)}else{var outerDimsProd=x.shape.slice(0,x.shape.length-2).reduce(function(value,prev){return value*prev});var x2ds=unstack(reshape2(x,[outerDimsProd,x.shape[x.shape.length-2],x.shape[x.shape.length-1]]),0);var q2ds_1=[];var r2ds_1=[];x2ds.forEach(function(x2d){var _a=qr2d(x2d,fullMatrices),q2d=_a[0],r2d=_a[1];q2ds_1.push(q2d);r2ds_1.push(r2d)});var q=reshape2(stack(q2ds_1,0),x.shape);var r=reshape2(stack(r2ds_1,0),x.shape);return[q,r]}}function qr2d(x,fullMatrices){if(fullMatrices===void 0){fullMatrices=false}return ENGINE.tidy(function(){assert(x.shape.length===2,function(){return"qr2d() requires a 2D Tensor, but got a "+x.shape.length+"D Tensor."});var m=x.shape[0];var n=x.shape[1];var q=eye(m);var r=clone(x);var one2D=tensor2d([[1]],[1,1]);var w=clone(one2D);var iters=m>=n?n:m;var _loop_1=function(j2){var _a;var rTemp=r;var wTemp=w;var qTemp=q;_a=ENGINE.tidy(function(){var rjEnd1=slice2(r,[j2,j2],[m-j2,1]);var normX=norm(rjEnd1);var rjj=slice2(r,[j2,j2],[1,1]);var s=where(greater(rjj,0),tensor2d([[-1]]),tensor2d([[1]]));var u1=sub(rjj,mul(s,normX));var wPre=div(rjEnd1,u1);if(wPre.shape[0]===1){w=clone(one2D)}else{w=concat2([one2D,slice2(wPre,[1,0],[wPre.shape[0]-1,wPre.shape[1]])],0)}var tau=neg(div(matMul(s,u1),normX));var rjEndAll=slice2(r,[j2,0],[m-j2,n]);var tauTimesW=mul(tau,w);var wT=transpose2(w);if(j2===0){r=sub(rjEndAll,matMul(tauTimesW,matMul(wT,rjEndAll)))}else{var rTimesTau=sub(rjEndAll,matMul(tauTimesW,matMul(wT,rjEndAll)));r=concat2([slice2(r,[0,0],[j2,n]),rTimesTau],0)}var tawTimesWT=transpose2(tauTimesW);var qAllJEnd=slice2(q,[0,j2],[m,q.shape[1]-j2]);if(j2===0){q=sub(qAllJEnd,matMul(matMul(qAllJEnd,w),tawTimesWT))}else{var qTimesTau=sub(qAllJEnd,matMul(matMul(qAllJEnd,w),tawTimesWT));q=concat2([slice2(q,[0,0],[m,j2]),qTimesTau],1)}return[w,r,q]}),w=_a[0],r=_a[1],q=_a[2];dispose([rTemp,wTemp,qTemp])};for(var j=0;jn){q=slice2(q,[0,0],[m,n]);r=slice2(r,[0,0],[n,n])}return[q,r]})}var qr=op({qr_});(function(Reduction){Reduction[Reduction["NONE"]=0]="NONE";Reduction[Reduction["MEAN"]=1]="MEAN";Reduction[Reduction["SUM"]=2]="SUM";Reduction[Reduction["SUM_BY_NONZERO_WEIGHTS"]=3]="SUM_BY_NONZERO_WEIGHTS"})(exports2.Reduction||(exports2.Reduction={}));function computeWeightedLoss_(losses2,weights,reduction){if(reduction===void 0){reduction=exports2.Reduction.SUM_BY_NONZERO_WEIGHTS}var $losses=convertToTensor(losses2,"losses","computeWeightedLoss");var $weights=null;if(weights!=null){$weights=convertToTensor(weights,"weights","computeWeightedLoss")}var weightedLoss=$weights==null?$losses:mul($losses,$weights);if(reduction===exports2.Reduction.NONE){return weightedLoss}if(reduction===exports2.Reduction.SUM){return sum$1(weightedLoss)}if(reduction===exports2.Reduction.MEAN){if($weights==null){return mean(weightedLoss)}else{var broadcastFactor=$losses.size/$weights.size;var result=div(sum$1(weightedLoss),sum$1($weights));return broadcastFactor>1?div(result,scalar(broadcastFactor)):result}}if(reduction===exports2.Reduction.SUM_BY_NONZERO_WEIGHTS){if($weights==null){return div(sum$1(weightedLoss),scalar($losses.size))}else{var broadcastedWeights=mul($weights,ones$1($losses.shape));var numNonZeros=cast2(sum$1(notEqual(broadcastedWeights,scalar(0))),"float32");return div(sum$1(weightedLoss),numNonZeros)}}throw Error("Unknown reduction: "+reduction)}var computeWeightedLoss=op({computeWeightedLoss_});function absoluteDifference_(labels,predictions,weights,reduction){if(reduction===void 0){reduction=exports2.Reduction.SUM_BY_NONZERO_WEIGHTS}var $labels=convertToTensor(labels,"labels","absoluteDifference");var $predictions=convertToTensor(predictions,"predictions","absoluteDifference");var $weights=null;if(weights!=null){$weights=convertToTensor(weights,"weights","absoluteDifference")}assertShapesMatch($labels.shape,$predictions.shape,"Error in absoluteDifference: ");var losses2=abs(sub($labels,$predictions));return computeWeightedLoss(losses2,$weights,reduction)}var absoluteDifference=op({absoluteDifference_});function cosineDistance_(labels,predictions,axis,weights,reduction){if(reduction===void 0){reduction=exports2.Reduction.SUM_BY_NONZERO_WEIGHTS}var $labels=convertToTensor(labels,"labels","cosineDistance");var $predictions=convertToTensor(predictions,"predictions","cosineDistance");var $weights=null;if(weights!=null){$weights=convertToTensor(weights,"weights","cosineDistance")}assertShapesMatch($labels.shape,$predictions.shape,"Error in cosineDistance: ");var one=scalar(1);var losses2=sub(one,sum$1(mul($labels,$predictions),axis,true));return computeWeightedLoss(losses2,$weights,reduction)}var cosineDistance=op({cosineDistance_});function hingeLoss_(labels,predictions,weights,reduction){if(reduction===void 0){reduction=exports2.Reduction.SUM_BY_NONZERO_WEIGHTS}var $labels=convertToTensor(labels,"labels","hingeLoss");var $predictions=convertToTensor(predictions,"predictions","hingeLoss");var $weights=null;if(weights!=null){$weights=convertToTensor(weights,"weights","hingeLoss")}assertShapesMatch($labels.shape,$predictions.shape,"Error in hingeLoss: ");var one=scalar(1);$labels=sub(mul(scalar(2),$labels),one);var losses2=relu(sub(one,mul($labels,$predictions)));return computeWeightedLoss(losses2,$weights,reduction)}var hingeLoss=op({hingeLoss_});function huberLoss_(labels,predictions,weights,delta,reduction){if(delta===void 0){delta=1}if(reduction===void 0){reduction=exports2.Reduction.SUM_BY_NONZERO_WEIGHTS}var $labels=convertToTensor(labels,"labels","huberLoss");var $predictions=convertToTensor(predictions,"predictions","huberLoss");var $weights=null;if(weights!=null){$weights=convertToTensor(weights,"weights","huberLoss")}assertShapesMatch($labels.shape,$predictions.shape,"Error in huberLoss: ");var deltaScalar=scalar(delta);var error=abs(sub($predictions,$labels));var quadratic=minimum(error,deltaScalar);var linear=sub(error,quadratic);var losses2=add$1(mul(scalar(.5),square(quadratic)),mul(deltaScalar,linear));return computeWeightedLoss(losses2,$weights,reduction)}var huberLoss=op({huberLoss_});function logLoss_(labels,predictions,weights,epsilon,reduction){if(epsilon===void 0){epsilon=1e-7}if(reduction===void 0){reduction=exports2.Reduction.SUM_BY_NONZERO_WEIGHTS}var $labels=convertToTensor(labels,"labels","logLoss");var $predictions=convertToTensor(predictions,"predictions","logLoss");var $weights=null;if(weights!=null){$weights=convertToTensor(weights,"weights","logLoss")}assertShapesMatch($labels.shape,$predictions.shape,"Error in logLoss: ");var one=scalar(1);var epsilonScalar=scalar(epsilon);var l1=neg(mul($labels,log(add$1($predictions,epsilonScalar))));var l2=mul(sub(one,$labels),log(add$1(sub(one,$predictions),epsilonScalar)));var losses2=sub(l1,l2);return computeWeightedLoss(losses2,$weights,reduction)}var logLoss=op({logLoss_});function meanSquaredError_(labels,predictions,weights,reduction){if(reduction===void 0){reduction=exports2.Reduction.SUM_BY_NONZERO_WEIGHTS}var $labels=convertToTensor(labels,"labels","meanSquaredError");var $predictions=convertToTensor(predictions,"predictions","meanSquaredError");var $weights=null;if(weights!=null){$weights=convertToTensor(weights,"weights","meanSquaredError")}assertShapesMatch($labels.shape,$predictions.shape,"Error in meanSquaredError: ");var losses2=squaredDifference($labels,$predictions);return computeWeightedLoss(losses2,$weights,reduction)}var meanSquaredError=op({meanSquaredError_});function sigmoidCrossEntropyWithLogits_(labels,logits){var $labels=convertToTensor(labels,"labels","sigmoidCrossEntropyWithLogits");var $logits=convertToTensor(logits,"logits","sigmoidCrossEntropyWithLogits");assertShapesMatch($labels.shape,$logits.shape,"Error in sigmoidCrossEntropyWithLogits: ");var maxOutput=relu($logits);var outputXTarget=mul($logits,$labels);var sigmoidOutput=log1p(exp(neg(abs($logits))));return add$1(sub(maxOutput,outputXTarget),sigmoidOutput)}function sigmoidCrossEntropy_(multiClassLabels,logits,weights,labelSmoothing,reduction){if(labelSmoothing===void 0){labelSmoothing=0}if(reduction===void 0){reduction=exports2.Reduction.SUM_BY_NONZERO_WEIGHTS}var $multiClassLabels=convertToTensor(multiClassLabels,"multiClassLabels","sigmoidCrossEntropy");var $logits=convertToTensor(logits,"logits","sigmoidCrossEntropy");var $weights=null;if(weights!=null){$weights=convertToTensor(weights,"weights","sigmoidCrossEntropy")}assertShapesMatch($multiClassLabels.shape,$logits.shape,"Error in sigmoidCrossEntropy: ");if(labelSmoothing>0){var labelSmoothingScalar=scalar(labelSmoothing);var one=scalar(1);var half=scalar(.5);$multiClassLabels=add$1(mul($multiClassLabels,sub(one,labelSmoothingScalar)),mul(half,labelSmoothingScalar))}var losses2=sigmoidCrossEntropyWithLogits_($multiClassLabels,$logits);return computeWeightedLoss(losses2,$weights,reduction)}var sigmoidCrossEntropy=op({sigmoidCrossEntropy_});function softmaxCrossEntropyWithLogits_(labels,logits,dim){if(dim===void 0){dim=-1}if(dim===-1){dim=logits.rank-1}if(dim!==logits.rank-1){throw Error("Softmax cross entropy along a non-last dimension is not yet "+("supported. Labels / logits was rank "+logits.rank+" ")+("and dim was "+dim))}var customOp=customGrad(function(labels2,logits2,save){var keepDims=true;var lse=logSumExp(logits2,[dim],keepDims);var logResult=sub(cast2(logits2,"float32"),lse);save([labels2,logResult]);var costVector=neg(mul(logResult,labels2));var value=sum$1(costVector,[dim]);var gradFunc=function(dy,saved){var labels3=saved[0],logResult2=saved[1];var dyShape=expandShapeToKeepDim(dy.shape,[dim]);return[mul(reshape2(dy,dyShape),sub(cast2(labels3,"float32"),exp(logResult2))),mul(reshape2(dy,dyShape),sub(exp(logResult2),cast2(labels3,"float32")))]};return{value,gradFunc}});return customOp(labels,logits)}function softmaxCrossEntropy_(onehotLabels,logits,weights,labelSmoothing,reduction){if(labelSmoothing===void 0){labelSmoothing=0}if(reduction===void 0){reduction=exports2.Reduction.SUM_BY_NONZERO_WEIGHTS}var $onehotLabels=convertToTensor(onehotLabels,"onehotLabels","softmaxCrossEntropy");var $logits=convertToTensor(logits,"logits","softmaxCrossEntropy");var $weights=null;if(weights!=null){$weights=convertToTensor(weights,"weights","softmaxCrossEntropy")}assertShapesMatch($onehotLabels.shape,$logits.shape,"Error in softmaxCrossEntropy: ");if(labelSmoothing>0){var labelSmoothingScalar=scalar(labelSmoothing);var one=scalar(1);var numClasses=scalar($onehotLabels.shape[1]);$onehotLabels=add$1(mul($onehotLabels,sub(one,labelSmoothingScalar)),div(labelSmoothingScalar,numClasses))}var losses2=softmaxCrossEntropyWithLogits_($onehotLabels,$logits);return computeWeightedLoss(losses2,$weights,reduction)}var softmaxCrossEntropy=op({softmaxCrossEntropy_});var spectral={fft,ifft,rfft,irfft};var signal={hammingWindow,hannWindow,frame,stft};var image2={flipLeftRight:flipLeftRight2,resizeNearestNeighbor,resizeBilinear:resizeBilinear2,rotateWithOffset:rotateWithOffset2,cropAndResize:cropAndResize2,nonMaxSuppression,nonMaxSuppressionAsync,nonMaxSuppressionWithScore,nonMaxSuppressionWithScoreAsync,nonMaxSuppressionPadded,nonMaxSuppressionPaddedAsync};var linalg={bandPart,gramSchmidt,qr};var losses={absoluteDifference,computeWeightedLoss,cosineDistance,hingeLoss,huberLoss,logLoss,meanSquaredError,sigmoidCrossEntropy,softmaxCrossEntropy};var Optimizer=function(_super){__extends(Optimizer2,_super);function Optimizer2(){return _super!==null&&_super.apply(this,arguments)||this}Optimizer2.prototype.minimize=function(f,returnCost,varList){if(returnCost===void 0){returnCost=false}var _a=this.computeGradients(f,varList),value=_a.value,grads2=_a.grads;if(varList!=null){var gradArray=varList.map(function(v){return{name:v.name,tensor:grads2[v.name]}});this.applyGradients(gradArray)}else{this.applyGradients(grads2)}dispose(grads2);if(returnCost){return value}else{value.dispose();return null}};Object.defineProperty(Optimizer2.prototype,"iterations",{get:function(){if(this.iterations_==null){this.iterations_=0}return this.iterations_},enumerable:true,configurable:true});Optimizer2.prototype.incrementIterations=function(){this.iterations_=this.iterations+1};Optimizer2.prototype.computeGradients=function(f,varList){return variableGrads(f,varList)};Optimizer2.prototype.dispose=function(){if(this.iterations_!=null){dispose(this.iterations_)}};Optimizer2.prototype.saveIterations=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){if(this.iterations_==null){this.iterations_=0}return[2,{name:"iter",tensor:scalar(this.iterations_,"int32")}]})})};Optimizer2.prototype.getWeights=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){throw new Error("getWeights() is not implemented for this optimizer yet.")})})};Optimizer2.prototype.setWeights=function(weightValues){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){throw new Error("setWeights() is not implemented for this optimizer class "+(""+this.getClassName()))})})};Optimizer2.prototype.extractIterations=function(weightValues){return __awaiter(this,void 0,void 0,function(){var _a;return __generator(this,function(_b){switch(_b.label){case 0:_a=this;return[4,weightValues[0].tensor.data()];case 1:_a.iterations_=_b.sent()[0];return[2,weightValues.slice(1)]}})})};return Optimizer2}(Serializable);Object.defineProperty(Optimizer,Symbol.hasInstance,{value:function(instance){return instance.minimize!=null&&instance.computeGradients!=null&&instance.applyGradients!=null}});var AdadeltaOptimizer=function(_super){__extends(AdadeltaOptimizer2,_super);function AdadeltaOptimizer2(learningRate,rho,epsilon){if(epsilon===void 0){epsilon=null}var _this=_super.call(this)||this;_this.learningRate=learningRate;_this.rho=rho;_this.epsilon=epsilon;_this.accumulatedGrads=[];_this.accumulatedUpdates=[];if(epsilon==null){_this.epsilon=ENGINE.backend.epsilon()}return _this}AdadeltaOptimizer2.prototype.applyGradients=function(variableGradients){var _this=this;var variableNames=Array.isArray(variableGradients)?variableGradients.map(function(item){return item.name}):Object.keys(variableGradients);variableNames.forEach(function(name,i){var value=ENGINE.registeredVariables[name];var trainable=false;if(_this.accumulatedGrads[i]==null){_this.accumulatedGrads[i]={originalName:name+"/accum_grad",variable:tidy(function(){return zerosLike2(value).variable(trainable)})}}if(_this.accumulatedUpdates[i]==null){_this.accumulatedUpdates[i]={originalName:name+"/accum_var",variable:tidy(function(){return zerosLike2(value).variable(trainable)})}}var gradient=Array.isArray(variableGradients)?variableGradients[i].tensor:variableGradients[name];if(gradient==null){return}var accumulatedGrad=_this.accumulatedGrads[i].variable;var accumulatedUpdate=_this.accumulatedUpdates[i].variable;tidy(function(){var newAccumulatedGrad=add$1(mul(accumulatedGrad,_this.rho),mul(square(gradient),1-_this.rho));var updates=mul(div(sqrt(add$1(accumulatedUpdate,_this.epsilon)),sqrt(add$1(accumulatedGrad,_this.epsilon))),gradient);var newAccumulatedUpdate=add$1(mul(accumulatedUpdate,_this.rho),mul(square(updates),1-_this.rho));accumulatedGrad.assign(newAccumulatedGrad);accumulatedUpdate.assign(newAccumulatedUpdate);var newValue=add$1(mul(updates,-_this.learningRate),value);value.assign(newValue)})});this.incrementIterations()};AdadeltaOptimizer2.prototype.dispose=function(){if(this.accumulatedUpdates!=null){dispose(this.accumulatedGrads.map(function(v){return v.variable}));dispose(this.accumulatedUpdates.map(function(v){return v.variable}))}};AdadeltaOptimizer2.prototype.getWeights=function(){return __awaiter(this,void 0,void 0,function(){var variables;return __generator(this,function(_a){switch(_a.label){case 0:variables=this.accumulatedGrads.concat(this.accumulatedUpdates);return[4,this.saveIterations()];case 1:return[2,[_a.sent()].concat(variables.map(function(v){return{name:v.originalName,tensor:v.variable}}))]}})})};AdadeltaOptimizer2.prototype.setWeights=function(weightValues){return __awaiter(this,void 0,void 0,function(){var variableCount,trainable;return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.extractIterations(weightValues)];case 1:weightValues=_a.sent();variableCount=weightValues.length/2;trainable=false;this.accumulatedGrads=weightValues.slice(0,variableCount).map(function(v){return{originalName:v.name,variable:v.tensor.variable(trainable)}});this.accumulatedUpdates=weightValues.slice(variableCount,variableCount*2).map(function(v){return{originalName:v.name,variable:v.tensor.variable(trainable)}});return[2]}})})};AdadeltaOptimizer2.prototype.getConfig=function(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}};AdadeltaOptimizer2.fromConfig=function(cls,config2){return new cls(config2["learningRate"],config2["rho"],config2["epsilon"])};AdadeltaOptimizer2.className="Adadelta";return AdadeltaOptimizer2}(Optimizer);registerClass(AdadeltaOptimizer);var AdagradOptimizer=function(_super){__extends(AdagradOptimizer2,_super);function AdagradOptimizer2(learningRate,initialAccumulatorValue){if(initialAccumulatorValue===void 0){initialAccumulatorValue=.1}var _this=_super.call(this)||this;_this.learningRate=learningRate;_this.initialAccumulatorValue=initialAccumulatorValue;_this.accumulatedGrads=[];return _this}AdagradOptimizer2.prototype.applyGradients=function(variableGradients){var _this=this;var variableNames=Array.isArray(variableGradients)?variableGradients.map(function(item){return item.name}):Object.keys(variableGradients);variableNames.forEach(function(name,i){var value=ENGINE.registeredVariables[name];if(_this.accumulatedGrads[i]==null){var trainable_1=false;_this.accumulatedGrads[i]={originalName:name+"/accumulator",variable:tidy(function(){return fill2(value.shape,_this.initialAccumulatorValue).variable(trainable_1)})}}var gradient=Array.isArray(variableGradients)?variableGradients[i].tensor:variableGradients[name];if(gradient==null){return}var accumulatedGrad=_this.accumulatedGrads[i].variable;tidy(function(){var newAccumulatedGrad=add$1(accumulatedGrad,square(gradient));accumulatedGrad.assign(newAccumulatedGrad);var newValue=add$1(mul(div(gradient,sqrt(add$1(newAccumulatedGrad,ENGINE.backend.epsilon()))),-_this.learningRate),value);value.assign(newValue)})});this.incrementIterations()};AdagradOptimizer2.prototype.dispose=function(){if(this.accumulatedGrads!=null){dispose(this.accumulatedGrads.map(function(v){return v.variable}))}};AdagradOptimizer2.prototype.getWeights=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.saveIterations()];case 1:return[2,[_a.sent()].concat(this.accumulatedGrads.map(function(v){return{name:v.originalName,tensor:v.variable}}))]}})})};AdagradOptimizer2.prototype.setWeights=function(weightValues){return __awaiter(this,void 0,void 0,function(){var trainable;return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.extractIterations(weightValues)];case 1:weightValues=_a.sent();trainable=false;this.accumulatedGrads=weightValues.map(function(v){return{originalName:v.name,variable:v.tensor.variable(trainable)}});return[2]}})})};AdagradOptimizer2.prototype.getConfig=function(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}};AdagradOptimizer2.fromConfig=function(cls,config2){return new cls(config2["learningRate"],config2["initialAccumulatorValue"])};AdagradOptimizer2.className="Adagrad";return AdagradOptimizer2}(Optimizer);registerClass(AdagradOptimizer);var AdamOptimizer=function(_super){__extends(AdamOptimizer2,_super);function AdamOptimizer2(learningRate,beta1,beta2,epsilon){if(epsilon===void 0){epsilon=null}var _this=_super.call(this)||this;_this.learningRate=learningRate;_this.beta1=beta1;_this.beta2=beta2;_this.epsilon=epsilon;_this.accumulatedFirstMoment=[];_this.accumulatedSecondMoment=[];tidy(function(){_this.accBeta1=scalar(beta1).variable();_this.accBeta2=scalar(beta2).variable()});if(epsilon==null){_this.epsilon=ENGINE.backend.epsilon()}return _this}AdamOptimizer2.prototype.applyGradients=function(variableGradients){var _this=this;var varNames=Array.isArray(variableGradients)?variableGradients.map(function(v){return v.name}):Object.keys(variableGradients);tidy(function(){var oneMinusAccBeta1=sub(1,_this.accBeta1);var oneMinusAccBeta2=sub(1,_this.accBeta2);varNames.forEach(function(name,i){var value=ENGINE.registeredVariables[name];var trainable=false;if(_this.accumulatedFirstMoment[i]==null){_this.accumulatedFirstMoment[i]={originalName:name+"/m",variable:tidy(function(){return zerosLike2(value).variable(trainable)})}}if(_this.accumulatedSecondMoment[i]==null){_this.accumulatedSecondMoment[i]={originalName:name+"/v",variable:tidy(function(){return zerosLike2(value).variable(trainable)})}}var gradient=Array.isArray(variableGradients)?variableGradients[i].tensor:variableGradients[name];if(gradient==null){return}var firstMoment=_this.accumulatedFirstMoment[i].variable;var secondMoment=_this.accumulatedSecondMoment[i].variable;var newFirstMoment=add$1(mul(firstMoment,_this.beta1),mul(gradient,1-_this.beta1));var newSecondMoment=add$1(mul(secondMoment,_this.beta2),mul(square(gradient),1-_this.beta2));var biasCorrectedFirstMoment=div(newFirstMoment,oneMinusAccBeta1);var biasCorrectedSecondMoment=div(newSecondMoment,oneMinusAccBeta2);firstMoment.assign(newFirstMoment);secondMoment.assign(newSecondMoment);var newValue=add$1(mul(div(biasCorrectedFirstMoment,add$1(sqrt(biasCorrectedSecondMoment),_this.epsilon)),-_this.learningRate),value);value.assign(newValue)});_this.accBeta1.assign(mul(_this.accBeta1,_this.beta1));_this.accBeta2.assign(mul(_this.accBeta2,_this.beta2))});this.incrementIterations()};AdamOptimizer2.prototype.dispose=function(){this.accBeta1.dispose();this.accBeta2.dispose();if(this.accumulatedFirstMoment!=null){dispose(this.accumulatedFirstMoment.map(function(v){return v.variable}))}if(this.accumulatedSecondMoment!=null){dispose(this.accumulatedSecondMoment.map(function(v){return v.variable}))}};AdamOptimizer2.prototype.getWeights=function(){return __awaiter(this,void 0,void 0,function(){var variables;return __generator(this,function(_a){switch(_a.label){case 0:variables=this.accumulatedFirstMoment.concat(this.accumulatedSecondMoment);return[4,this.saveIterations()];case 1:return[2,[_a.sent()].concat(variables.map(function(v){return{name:v.originalName,tensor:v.variable}}))]}})})};AdamOptimizer2.prototype.setWeights=function(weightValues){return __awaiter(this,void 0,void 0,function(){var variableCount,trainable;var _this=this;return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.extractIterations(weightValues)];case 1:weightValues=_a.sent();tidy(function(){_this.accBeta1.assign(pow(_this.beta1,_this.iterations_+1));_this.accBeta2.assign(pow(_this.beta2,_this.iterations_+1))});variableCount=weightValues.length/2;trainable=false;this.accumulatedFirstMoment=weightValues.slice(0,variableCount).map(function(v){return{originalName:v.name,variable:v.tensor.variable(trainable)}});this.accumulatedSecondMoment=weightValues.slice(variableCount,variableCount*2).map(function(v){return{originalName:v.name,variable:v.tensor.variable(trainable)}});return[2]}})})};AdamOptimizer2.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}};AdamOptimizer2.fromConfig=function(cls,config2){return new cls(config2["learningRate"],config2["beta1"],config2["beta2"],config2["epsilon"])};AdamOptimizer2.className="Adam";return AdamOptimizer2}(Optimizer);registerClass(AdamOptimizer);var AdamaxOptimizer=function(_super){__extends(AdamaxOptimizer2,_super);function AdamaxOptimizer2(learningRate,beta1,beta2,epsilon,decay){if(epsilon===void 0){epsilon=null}if(decay===void 0){decay=0}var _this=_super.call(this)||this;_this.learningRate=learningRate;_this.beta1=beta1;_this.beta2=beta2;_this.epsilon=epsilon;_this.decay=decay;_this.accumulatedFirstMoment=[];_this.accumulatedWeightedInfNorm=[];tidy(function(){_this.iteration=scalar(0).variable();_this.accBeta1=scalar(beta1).variable()});if(epsilon==null){_this.epsilon=ENGINE.backend.epsilon()}return _this}AdamaxOptimizer2.prototype.applyGradients=function(variableGradients){var _this=this;var variableNames=Array.isArray(variableGradients)?variableGradients.map(function(item){return item.name}):Object.keys(variableGradients);tidy(function(){var oneMinusAccBeta1=sub(1,_this.accBeta1);var lr=div(-_this.learningRate,add$1(mul(_this.iteration,_this.decay),1));variableNames.forEach(function(name,i){var value=ENGINE.registeredVariables[name];var trainable=false;if(_this.accumulatedFirstMoment[i]==null){_this.accumulatedFirstMoment[i]={originalName:name+"/m",variable:zerosLike2(value).variable(trainable)}}if(_this.accumulatedWeightedInfNorm[i]==null){_this.accumulatedWeightedInfNorm[i]={originalName:name+"/v",variable:zerosLike2(value).variable(trainable)}}var gradient=Array.isArray(variableGradients)?variableGradients[i].tensor:variableGradients[name];if(gradient==null){return}var firstMoment=_this.accumulatedFirstMoment[i].variable;var weightedInfNorm=_this.accumulatedWeightedInfNorm[i].variable;var newFirstMoment=add$1(mul(firstMoment,_this.beta1),mul(gradient,1-_this.beta1));var ut0=mul(weightedInfNorm,_this.beta2);var ut1=abs(gradient);var newWeightedInfNorm=maximum(ut0,ut1);firstMoment.assign(newFirstMoment);weightedInfNorm.assign(newWeightedInfNorm);var newValue=add$1(mul(div(lr,oneMinusAccBeta1),div(newFirstMoment,add$1(newWeightedInfNorm,_this.epsilon))),value);value.assign(newValue)});_this.iteration.assign(add$1(_this.iteration,1));_this.accBeta1.assign(mul(_this.accBeta1,_this.beta1))});this.incrementIterations()};AdamaxOptimizer2.prototype.dispose=function(){this.accBeta1.dispose();this.iteration.dispose();if(this.accumulatedFirstMoment!=null){dispose(this.accumulatedFirstMoment.map(function(v){return v.variable}))}if(this.accumulatedWeightedInfNorm!=null){dispose(this.accumulatedWeightedInfNorm.map(function(v){return v.variable}))}};AdamaxOptimizer2.prototype.getWeights=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){throw new Error("getWeights() is not implemented for Adamax yet.")})})};AdamaxOptimizer2.prototype.setWeights=function(weightValues){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){throw new Error("setWeights() is not implemented for Adamax yet.")})})};AdamaxOptimizer2.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}};AdamaxOptimizer2.fromConfig=function(cls,config2){return new cls(config2["learningRate"],config2["beta1"],config2["beta2"],config2["epsilon"],config2["decay"])};AdamaxOptimizer2.className="Adamax";return AdamaxOptimizer2}(Optimizer);registerClass(AdamaxOptimizer);var SGDOptimizer=function(_super){__extends(SGDOptimizer2,_super);function SGDOptimizer2(learningRate){var _this=_super.call(this)||this;_this.learningRate=learningRate;_this.setLearningRate(learningRate);return _this}SGDOptimizer2.prototype.applyGradients=function(variableGradients){var _this=this;var varNames=Array.isArray(variableGradients)?variableGradients.map(function(v){return v.name}):Object.keys(variableGradients);varNames.forEach(function(name,i){var gradient=Array.isArray(variableGradients)?variableGradients[i].tensor:variableGradients[name];if(gradient==null){return}var value=ENGINE.registeredVariables[name];tidy(function(){var newValue=add$1(mul(_this.c,gradient),value);value.assign(newValue)})});this.incrementIterations()};SGDOptimizer2.prototype.setLearningRate=function(learningRate){this.learningRate=learningRate;if(this.c!=null){this.c.dispose()}this.c=keep(scalar(-learningRate))};SGDOptimizer2.prototype.dispose=function(){this.c.dispose()};SGDOptimizer2.prototype.getWeights=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.saveIterations()];case 1:return[2,[_a.sent()]]}})})};SGDOptimizer2.prototype.setWeights=function(weightValues){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.extractIterations(weightValues)];case 1:weightValues=_a.sent();if(weightValues.length!==0){throw new Error("SGD optimizer does not have settable weights.")}return[2]}})})};SGDOptimizer2.prototype.getConfig=function(){return{learningRate:this.learningRate}};SGDOptimizer2.fromConfig=function(cls,config2){return new cls(config2["learningRate"])};SGDOptimizer2.className="SGD";return SGDOptimizer2}(Optimizer);registerClass(SGDOptimizer);var MomentumOptimizer=function(_super){__extends(MomentumOptimizer2,_super);function MomentumOptimizer2(learningRate,momentum,useNesterov){if(useNesterov===void 0){useNesterov=false}var _this=_super.call(this,learningRate)||this;_this.learningRate=learningRate;_this.momentum=momentum;_this.useNesterov=useNesterov;_this.accumulations=[];_this.m=scalar(_this.momentum);return _this}MomentumOptimizer2.prototype.applyGradients=function(variableGradients){var _this=this;var variableNames=Array.isArray(variableGradients)?variableGradients.map(function(item){return item.name}):Object.keys(variableGradients);variableNames.forEach(function(name,i){var value=ENGINE.registeredVariables[name];if(_this.accumulations[i]==null){var trainable_1=false;_this.accumulations[i]={originalName:name+"/momentum",variable:tidy(function(){return zerosLike2(value).variable(trainable_1)})}}var accumulation=_this.accumulations[i].variable;var gradient=Array.isArray(variableGradients)?variableGradients[i].tensor:variableGradients[name];if(gradient==null){return}tidy(function(){var newValue;var newAccumulation=add$1(mul(_this.m,accumulation),gradient);if(_this.useNesterov){newValue=add$1(mul(_this.c,add$1(gradient,mul(newAccumulation,_this.m))),value)}else{newValue=add$1(mul(_this.c,newAccumulation),value)}accumulation.assign(newAccumulation);value.assign(newValue)})});this.incrementIterations()};MomentumOptimizer2.prototype.dispose=function(){this.m.dispose();if(this.accumulations!=null){dispose(this.accumulations.map(function(v){return v.variable}))}};MomentumOptimizer2.prototype.setMomentum=function(momentum){this.momentum=momentum};MomentumOptimizer2.prototype.getWeights=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.saveIterations()];case 1:return[2,[_a.sent()].concat(this.accumulations.map(function(v){return{name:v.originalName,tensor:v.variable}}))]}})})};MomentumOptimizer2.prototype.setWeights=function(weightValues){return __awaiter(this,void 0,void 0,function(){var trainable;return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.extractIterations(weightValues)];case 1:weightValues=_a.sent();trainable=false;this.accumulations=weightValues.map(function(v){return{originalName:v.name,variable:v.tensor.variable(trainable)}});return[2]}})})};MomentumOptimizer2.prototype.getConfig=function(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}};MomentumOptimizer2.fromConfig=function(cls,config2){return new cls(config2["learningRate"],config2["momentum"],config2["useNesterov"])};MomentumOptimizer2.className="Momentum";return MomentumOptimizer2}(SGDOptimizer);registerClass(MomentumOptimizer);var RMSPropOptimizer=function(_super){__extends(RMSPropOptimizer2,_super);function RMSPropOptimizer2(learningRate,decay,momentum,epsilon,centered){if(decay===void 0){decay=.9}if(momentum===void 0){momentum=0}if(epsilon===void 0){epsilon=null}if(centered===void 0){centered=false}var _this=_super.call(this)||this;_this.learningRate=learningRate;_this.decay=decay;_this.momentum=momentum;_this.epsilon=epsilon;_this.accumulatedMeanSquares=[];_this.accumulatedMoments=[];_this.accumulatedMeanGrads=[];_this.centered=centered;if(epsilon==null){_this.epsilon=ENGINE.backend.epsilon()}if(learningRate==null){throw new Error("learningRate for RMSPropOptimizer must be defined.")}return _this}RMSPropOptimizer2.prototype.applyGradients=function(variableGradients){var _this=this;var variableNames=Array.isArray(variableGradients)?variableGradients.map(function(item){return item.name}):Object.keys(variableGradients);variableNames.forEach(function(name,i){var value=ENGINE.registeredVariables[name];var trainable=false;if(_this.accumulatedMeanSquares[i]==null){_this.accumulatedMeanSquares[i]={originalName:name+"/rms",variable:tidy(function(){return zerosLike2(value).variable(trainable)})}}if(_this.accumulatedMoments[i]==null){_this.accumulatedMoments[i]={originalName:name+"/momentum",variable:tidy(function(){return zerosLike2(value).variable(trainable)})}}if(_this.accumulatedMeanGrads[i]==null&&_this.centered){_this.accumulatedMeanGrads[i]={originalName:name+"/mg",variable:tidy(function(){return zerosLike2(value).variable(trainable)})}}var gradient=Array.isArray(variableGradients)?variableGradients[i].tensor:variableGradients[name];if(gradient==null){return}var accumulatedMeanSquare=_this.accumulatedMeanSquares[i].variable;var accumulatedMoments=_this.accumulatedMoments[i].variable;tidy(function(){var newAccumulatedMeanSquare=add$1(mul(accumulatedMeanSquare,_this.decay),mul(square(gradient),1-_this.decay));if(_this.centered){var accumulatedMeanGrad=_this.accumulatedMeanGrads[i].variable;var newAccumulatedMeanGrad=add$1(mul(accumulatedMeanGrad,_this.decay),mul(gradient,1-_this.decay));var gradContribution=div(mul(gradient,_this.learningRate),sqrt(sub(newAccumulatedMeanSquare,add$1(square(newAccumulatedMeanGrad),_this.epsilon))));var newAccumulatedMoments=add$1(mul(accumulatedMoments,_this.momentum),gradContribution);accumulatedMeanSquare.assign(newAccumulatedMeanSquare);accumulatedMeanGrad.assign(newAccumulatedMeanGrad);accumulatedMoments.assign(newAccumulatedMoments);var newValue=sub(value,newAccumulatedMoments);value.assign(newValue)}else{var newAccumulatedMeanSquare_1=add$1(mul(accumulatedMeanSquare,_this.decay),mul(square(gradient),1-_this.decay));var newAccumulatedMoments=add$1(mul(accumulatedMoments,_this.momentum),div(mul(gradient,_this.learningRate),sqrt(add$1(newAccumulatedMeanSquare_1,_this.epsilon))));accumulatedMeanSquare.assign(newAccumulatedMeanSquare_1);accumulatedMoments.assign(newAccumulatedMoments);var newValue=sub(value,newAccumulatedMoments);value.assign(newValue)}})});this.incrementIterations()};RMSPropOptimizer2.prototype.dispose=function(){if(this.accumulatedMeanSquares!=null){dispose(this.accumulatedMeanSquares.map(function(v){return v.variable}))}if(this.accumulatedMeanGrads!=null&&this.centered){dispose(this.accumulatedMeanGrads.map(function(v){return v.variable}))}if(this.accumulatedMoments!=null){dispose(this.accumulatedMoments.map(function(v){return v.variable}))}};RMSPropOptimizer2.prototype.getWeights=function(){return __awaiter(this,void 0,void 0,function(){var variables;return __generator(this,function(_a){switch(_a.label){case 0:variables=this.accumulatedMeanSquares.concat(this.accumulatedMoments);if(this.centered){variables.push.apply(variables,this.accumulatedMeanGrads)}return[4,this.saveIterations()];case 1:return[2,[_a.sent()].concat(variables.map(function(v){return{name:v.originalName,tensor:v.variable}}))]}})})};RMSPropOptimizer2.prototype.setWeights=function(weightValues){return __awaiter(this,void 0,void 0,function(){var variableCount,trainable;return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.extractIterations(weightValues)];case 1:weightValues=_a.sent();variableCount=this.centered?weightValues.length/3:weightValues.length/2;trainable=false;this.accumulatedMeanSquares=weightValues.slice(0,variableCount).map(function(v){return{originalName:v.name,variable:v.tensor.variable(trainable)}});this.accumulatedMoments=weightValues.slice(variableCount,variableCount*2).map(function(v){return{originalName:v.name,variable:v.tensor.variable(trainable)}});if(this.centered){this.accumulatedMeanGrads=weightValues.slice(variableCount*2,variableCount*3).map(function(v){return{originalName:v.name,variable:v.tensor.variable(trainable)}})}return[2]}})})};RMSPropOptimizer2.prototype.getConfig=function(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}};RMSPropOptimizer2.fromConfig=function(cls,config2){return new cls(config2["learningRate"],config2["decay"],config2["momentum"],config2["epsilon"],config2["centered"])};RMSPropOptimizer2.className="RMSProp";return RMSPropOptimizer2}(Optimizer);registerClass(RMSPropOptimizer);var OptimizerConstructors=function(){function OptimizerConstructors2(){}OptimizerConstructors2.sgd=function(learningRate){return new SGDOptimizer(learningRate)};OptimizerConstructors2.momentum=function(learningRate,momentum,useNesterov){if(useNesterov===void 0){useNesterov=false}return new MomentumOptimizer(learningRate,momentum,useNesterov)};OptimizerConstructors2.rmsprop=function(learningRate,decay,momentum,epsilon,centered){if(decay===void 0){decay=.9}if(momentum===void 0){momentum=0}if(epsilon===void 0){epsilon=null}if(centered===void 0){centered=false}return new RMSPropOptimizer(learningRate,decay,momentum,epsilon,centered)};OptimizerConstructors2.adam=function(learningRate,beta1,beta2,epsilon){if(learningRate===void 0){learningRate=.001}if(beta1===void 0){beta1=.9}if(beta2===void 0){beta2=.999}if(epsilon===void 0){epsilon=null}return new AdamOptimizer(learningRate,beta1,beta2,epsilon)};OptimizerConstructors2.adadelta=function(learningRate,rho,epsilon){if(learningRate===void 0){learningRate=.001}if(rho===void 0){rho=.95}if(epsilon===void 0){epsilon=null}return new AdadeltaOptimizer(learningRate,rho,epsilon)};OptimizerConstructors2.adamax=function(learningRate,beta1,beta2,epsilon,decay){if(learningRate===void 0){learningRate=.002}if(beta1===void 0){beta1=.9}if(beta2===void 0){beta2=.999}if(epsilon===void 0){epsilon=null}if(decay===void 0){decay=0}return new AdamaxOptimizer(learningRate,beta1,beta2,epsilon,decay)};OptimizerConstructors2.adagrad=function(learningRate,initialAccumulatorValue){if(initialAccumulatorValue===void 0){initialAccumulatorValue=.1}return new AdagradOptimizer(learningRate,initialAccumulatorValue)};return OptimizerConstructors2}();var train={sgd:OptimizerConstructors.sgd,momentum:OptimizerConstructors.momentum,adadelta:OptimizerConstructors.adadelta,adagrad:OptimizerConstructors.adagrad,rmsprop:OptimizerConstructors.rmsprop,adamax:OptimizerConstructors.adamax,adam:OptimizerConstructors.adam};var delayCallback=function(){if(typeof requestAnimationFrame!=="undefined"){return requestAnimationFrame}else if(typeof setImmediate!=="undefined"){return setImmediate}return function(f){return f()}}();function nextFrame(){return new Promise(function(resolve){return delayCallback(function(){return resolve()})})}function getImageCenter(center,imageHeight,imageWidth){var centerX=imageWidth*(typeof center==="number"?center:center[0]);var centerY=imageHeight*(typeof center==="number"?center:center[1]);return[centerX,centerY]}function getReshaped(inputShape,blockShape,prod2,batchToSpace){if(batchToSpace===void 0){batchToSpace=true}var reshaped=[];if(batchToSpace){reshaped=reshaped.concat(blockShape.slice(0));reshaped.push(inputShape[0]/prod2);reshaped=reshaped.concat(inputShape.slice(1))}else{reshaped=reshaped.concat(inputShape[0]);var spatialLength=blockShape.length;for(var i=0;i=blockShapeRank*2+1||i%2===1){permutedAfterBatch.push(i)}else{permutedBeforeBatch.push(i)}}permuted.push.apply(permuted,permutedBeforeBatch);permuted.push(0);permuted.push.apply(permuted,permutedAfterBatch)}return permuted}function getReshapedPermuted(inputShape,blockShape,prod2,batchToSpace){if(batchToSpace===void 0){batchToSpace=true}var reshapedPermuted=[];if(batchToSpace){reshapedPermuted.push(inputShape[0]/prod2)}else{reshapedPermuted.push(inputShape[0]*prod2)}for(var i=1;i0){res=sum$1(res,reduceAxes)}return reshape2(res,a.shape)};var derB=function(){var res=dy;var reduceAxes=getReductionAxes(b.shape,outShape);if(reduceAxes.length>0){res=sum$1(res,reduceAxes)}return reshape2(res,b.shape)};return{a:derA,b:derB}}};var addNGradConfig={kernelName:AddN3,saveAllInputs:true,gradFunc:function(dy,saved){var ders={};saved.forEach(function(_,i){ders[i]=function(){return dy.clone()}});return ders}};var argMaxGradConfig={kernelName:ArgMax3,inputsToSave:["x"],gradFunc:function(dy,saved){var x=saved[0];return{x:function(){return zerosLike2(x)}}}};var argMinGradConfig={kernelName:ArgMin,inputsToSave:["x"],gradFunc:function(dy,saved){var x=saved[0];return{x:function(){return zerosLike2(x)}}}};var asinGradConfig={kernelName:Asin,inputsToSave:["x"],gradFunc:function(dy,saved){var x=saved[0];return{x:function(){return div(dy,sqrt(sub(scalar(1),square(cast2(x,"float32")))))}}}};var asinhGradConfig={kernelName:Asinh,inputsToSave:["x"],gradFunc:function(dy,saved){var x=saved[0];return{x:function(){var a=sqrt(add$1(scalar(1),square(cast2(x,"float32"))));return div(dy,a)}}}};var atan2GradConfig={kernelName:Atan2,inputsToSave:["a","b"],gradFunc:function(dy,saved){var a=saved[0],b=saved[1];var outShape=assertAndGetBroadcastShape(a.shape,b.shape);var derA=function(){var d=add$1(square(a),square(b));var res=mul(dy,div(b,d));var reduceAxes=getReductionAxes(a.shape,outShape);if(reduceAxes.length>0){res=sum$1(res,reduceAxes)}return reshape2(res,a.shape)};var derB=function(){var d=add$1(square(a),square(b));var res=neg(mul(dy,div(a,d)));var reduceAxes=getReductionAxes(b.shape,outShape);if(reduceAxes.length>0){res=sum$1(res,reduceAxes)}return reshape2(res,b.shape)};return{a:derA,b:derB}}};var atanGradConfig={kernelName:Atan,inputsToSave:["x"],gradFunc:function(dy,saved){var x=saved[0];return{x:function(){return div(dy,add$1(square(cast2(x,"float32")),1))}}}};var atanhGradConfig={kernelName:Atanh,inputsToSave:["x"],gradFunc:function(dy,saved){var x=saved[0];return{x:function(){return div(dy,sub(scalar(1),square(cast2(x,"float32"))))}}}};function avgPool3dBackprop_(dy,input,filterSize,strides,dilations,pad3,dimRoundingMode){if(dilations===void 0){dilations=[1,1,1]}var $dy=convertToTensor(dy,"dy","avgPool3dBackprop");var $input=convertToTensor(input,"input","avgPool3dBackprop");var dy5D=$dy;var input5D=$input;var reshapedTo5D=false;if($input.rank===4){reshapedTo5D=true;dy5D=reshape2($dy,[1,$dy.shape[0],$dy.shape[1],$dy.shape[2],$dy.shape[3]]);input5D=reshape2($input,[1,$input.shape[0],$input.shape[1],$input.shape[2],$input.shape[3]])}assert(dy5D.rank===5,function(){return"Error in avgPool3dBackprop: dy must be rank 5 but got rank "+(dy5D.rank+".")});assert(input5D.rank===5,function(){return"Error in avgPool3dBackprop: input must be rank 5 but got rank "+(input5D.rank+".")});assert(eitherStridesOrDilationsAreOne(strides,dilations),function(){return"Error in avgPool3dBackprop: Either strides or dilations "+("must be 1. Got strides "+strides+" and dilations '"+dilations+"'")});if(dimRoundingMode!=null){assert(isInt(pad3),function(){return"Error in maxPool3dBackprop: pad must be an integer when "+("using, dimRoundingMode "+dimRoundingMode+" but got pad "+pad3+".")})}var forward=function(backend2){var convInfo=computePool3DInfo(input5D.shape,filterSize,strides,dilations,pad3,dimRoundingMode);return backend2.avgPool3dBackprop(dy5D,input5D,convInfo)};var inputs={dy:dy5D,input:input5D};var attrs={filterSize,strides,dilations,pad:pad3,dimRoundingMode};var res=ENGINE.runKernelFunc(forward,inputs,null,AvgPool3DBackprop,attrs);if(reshapedTo5D){return reshape2(res,[res.shape[1],res.shape[2],res.shape[3],res.shape[4]])}return res}var avgPool3dBackprop=op({avgPool3dBackprop_});var avgPool3DGradConfig={kernelName:AvgPool3D,inputsToSave:["x"],gradFunc:function(dy,saved,attrs){var x=saved[0];var _a=attrs,filterSize=_a.filterSize,strides=_a.strides,dilations=_a.dilations,pad3=_a.pad,dimRoundingMode=_a.dimRoundingMode;var $dilations=dilations==null?[1,1,1]:dilations;return{x:function(){return avgPool3dBackprop(dy,x,filterSize,strides,$dilations,pad3,dimRoundingMode)}}}};function avgPoolBackprop_(dy,input,filterSize,strides,pad3){var $dy=convertToTensor(dy,"dy","avgPoolBackprop");var $input=convertToTensor(input,"input","avgPoolBackprop");assert($input.rank===$dy.rank,function(){return"Rank of input ("+$input.rank+") does not match rank of dy ("+$dy.rank+")"});var input4D=$input;var dy4D=$dy;var reshapedTo4D=false;if($input.rank===3){reshapedTo4D=true;input4D=reshape2($input,[1,$input.shape[0],$input.shape[1],$input.shape[2]]);dy4D=reshape2($dy,[1,$dy.shape[0],$dy.shape[1],$dy.shape[2]])}assert(dy4D.rank===4,function(){return"Error in avgPoolBackprop: dy must be rank 4 but got rank "+(dy4D.rank+".")});assert(input4D.rank===4,function(){return"Error in avgPoolBackprop: input must be rank 4 but got rank "+(input4D.rank+".")});var forward=function(backend2){var convInfo=computePool2DInfo(input4D.shape,filterSize,strides,1,pad3);return backend2.avgPoolBackprop(dy4D,input4D,convInfo)};var inputs={dy:dy4D,input:input4D};var attrs={filterSize,strides,pad:pad3};var res=ENGINE.runKernelFunc(forward,inputs,null,AvgPoolBackprop,attrs);if(reshapedTo4D){return reshape2(res,[res.shape[1],res.shape[2],res.shape[3]])}return res}var avgPoolBackprop=op({avgPoolBackprop_});var avgPoolGradConfig={kernelName:AvgPool3,inputsToSave:["x"],gradFunc:function(dy,saved,attrs){var x=saved[0];var _a=attrs,filterSize=_a.filterSize,strides=_a.strides,pad3=_a.pad;return{x:function(){return avgPoolBackprop(dy,x,filterSize,strides,pad3)}}}};var batchMatMulGradConfig={kernelName:BatchMatMul3,inputsToSave:["a","b"],gradFunc:function(dy,saved,attrs){var a=saved[0],b=saved[1];var _a=attrs,transposeA=_a.transposeA,transposeB=_a.transposeB;if(!transposeA&&!transposeB){return{a:function(){return matMul(dy,b,false,true)},b:function(){return matMul(a,dy,true,false)}}}else if(!transposeA&&transposeB){return{a:function(){return matMul(dy,b,false,false)},b:function(){return matMul(dy,a,true,false)}}}else if(transposeA&&!transposeB){return{a:function(){return matMul(b,dy,false,true)},b:function(){return matMul(a,dy,false,false)}}}else{return{a:function(){return matMul(b,dy,true,true)},b:function(){return matMul(dy,a,true,true)}}}}};var batchToSpaceNDGradConfig={kernelName:BatchToSpaceND,gradFunc:function(dy,saved,attrs){var _a=attrs,blockShape=_a.blockShape,crops=_a.crops;return{x:function(){return spaceToBatchND(dy,blockShape,crops)}}}};var broadcastToGradConfig={kernelName:BroadcastTo,gradFunc:function(dy,saved,attrs){var broadCastToAttrs=attrs;var inputShape=broadCastToAttrs.inputShape;var outputShape=broadCastToAttrs.shape;var reps=Array.from(outputShape);for(var i=inputShape.length-1;i>=0;i--){if(inputShape[i]===outputShape[i]){reps[i]=1}else if(inputShape[i]!==1){throw new Error("broadcastTo(): ["+inputShape+"] cannot be broadcast to ["+outputShape+"].")}}var axes=[];for(var i=0;i1){axes.push(i)}}return{x:function(){return sum$1(dy,axes,true)}}}};var castGradConfig={kernelName:Cast5,gradFunc:function(dy){return{x:function(){return dy.clone()}}}};var ceilGradConfig={kernelName:Ceil,gradFunc:function(dy){return{x:function(){return zerosLike2(dy)}}}};var clipByValueGradConfig={kernelName:ClipByValue3,inputsToSave:["x"],gradFunc:function(dy,saved,attrs){var x=saved[0];var _a=attrs,clipValueMin=_a.clipValueMin,clipValueMax=_a.clipValueMax;return{x:function(){return where(logicalAnd(greaterEqual(x,clipValueMin),lessEqual(x,clipValueMax)),dy,zerosLike2(dy))}}}};var concatGradConfig={kernelName:Concat3,saveAllInputs:true,gradFunc:function(dy,saved,attrs){var shapes=saved.map(function(t){return t.shape});var axis=attrs.axis;var $axis=parseAxisParam(axis,saved[0].shape)[0];var sizeSplits=shapes.map(function(s){return s[$axis]});var derTensors=split2(dy,sizeSplits,$axis);return derTensors.map(function(t){return function(){return t}})}};var conv2DGradConfig={kernelName:Conv2D3,inputsToSave:["x","filter"],gradFunc:function(dy,saved,attrs){var _a=saved,x4D=_a[0],$filter=_a[1];var _b=attrs,dilations=_b.dilations,strides=_b.strides,pad3=_b.pad,dataFormat=_b.dataFormat;assert(tupleValuesAreOne(dilations),function(){return"Error in gradient of conv2D: dilation rates greater than 1 "+("are not yet supported in gradients. Got dilations '"+dilations+"'")});return{x:function(){return conv2DBackpropInput2(x4D.shape,dy,$filter,strides,pad3,dataFormat)},filter:function(){return conv2DBackpropFilter(x4D,dy,$filter.shape,strides,pad3,dataFormat)}}}};var conv2DBackpropInputGradConfig={kernelName:Conv2DBackpropInput3,inputsToSave:["dy","filter"],gradFunc:function(ddx,saved,attrs){var _a=saved,dy=_a[0],filter=_a[1];var _b=attrs,strides=_b.strides,pad3=_b.pad,dataFormat=_b.dataFormat,dimRoundingMode=_b.dimRoundingMode;return{dy:function(){return conv2d2(ddx,filter,strides,pad3,dataFormat,1,dimRoundingMode)},filter:function(){return conv2DBackpropFilter(ddx,dy,filter.shape,strides,pad3,dataFormat,dimRoundingMode)}}}};function conv3DBackpropFilter_(x,dy,filterShape,strides,pad3){var x5D=x;if(x.rank===4){x5D=reshape2(x,[1,x.shape[0],x.shape[1],x.shape[2],x.shape[3]])}var dy5D=dy;if(dy5D.rank===4){dy5D=reshape2(dy,[1,dy.shape[0],dy.shape[1],dy.shape[2],dy.shape[3]])}assert(x5D.rank===5,function(){return"Error in conv3dDerFilter: input must be rank 5, but got shape "+(x5D.shape+".")});assert(dy5D.rank===5,function(){return"Error in conv3dDerFilter: dy must be rank 5, but got shape "+(dy5D.shape+".")});assert(filterShape.length===5,function(){return"Error in conv3dDerFilter: filterShape must be length 5, but got "+(filterShape+".")});assert(x5D.shape[4]===filterShape[3],function(){return"Error in conv3dDerFilter: depth of input "+x5D.shape[4]+") must "+("match input depth in filter ("+filterShape[3]+".")});assert(dy5D.shape[4]===filterShape[4],function(){return"Error in conv3dDerFilter: depth of dy ("+dy5D.shape[4]+") must "+("match output depth for filter ("+filterShape[4]+").")});var forward=function(backend2){var dilations=1;var convInfo=computeConv3DInfo(x5D.shape,filterShape,strides,dilations,pad3);return backend2.conv3dDerFilter(x5D,dy5D,convInfo)};var inputs={x:x5D,dy:dy5D};var attrs={strides,pad:pad3,filterShape};return ENGINE.runKernelFunc(forward,inputs,null,Conv3DBackpropFilterV2,attrs)}var conv3DBackpropFilter=op({conv3DBackpropFilter_});var conv3DGradConfig={kernelName:Conv3D,inputsToSave:["x","filter"],gradFunc:function(dy,saved,attrs){var _a=attrs,dilations=_a.dilations,strides=_a.strides,pad3=_a.pad;assert(tupleValuesAreOne(dilations),function(){return"Error in gradient of conv3D: dilation rates greater than 1 are "+("not yet supported in gradients. Got dilations '"+dilations+"'")});var x5D=saved[0],$filter=saved[1];return{x:function(){return conv3DBackpropInput(x5D.shape,dy,$filter,strides,pad3)},filter:function(){return conv3DBackpropFilter(x5D,dy,$filter.shape,strides,pad3)}}}};var cosGradConfig={kernelName:Cos3,inputsToSave:["x"],gradFunc:function(dy,saved){var x=saved[0];return{x:function(){return mul(neg(sin(cast2(x,"float32"))),dy)}}}};var coshGradConfig={kernelName:Cosh,inputsToSave:["x"],gradFunc:function(dy,saved){var x=saved[0];return{x:function(){return mul(sinh(cast2(x,"float32")),dy)}}}};var cumsumGradConfig={kernelName:Cumsum3,inputsToSave:["x"],gradFunc:function(dy,saved,attrs){var x=saved[0];var _a=attrs,axis=_a.axis,exclusive=_a.exclusive,reverse3=_a.reverse;return{x:function(){var permutation=getAxesPermutation([axis],x.rank);var out=cumsum2(dy,axis,exclusive,!reverse3);if(permutation!=null){out=transpose2(out,permutation)}return out}}}};var depthwiseConv2dNativeGradConfig={kernelName:DepthwiseConv2dNative3,inputsToSave:["x","filter"],gradFunc:function(dy,saved,attrs){var _a=attrs,dilations=_a.dilations,strides=_a.strides,pad3=_a.pad,dimRoundingMode=_a.dimRoundingMode;var $dilations=dilations==null?[1,1]:dilations;assert(tupleValuesAreOne($dilations),function(){return"Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations "+("'"+$dilations+"'")});var _b=saved,x=_b[0],filter=_b[1];assert(x.rank===4,function(){return"Error in gradient of depthwiseConv2dNative: input must be "+("rank 4, but got rank "+x.rank+".")});assert(filter.rank===4,function(){return"Error in gradient of depthwiseConv2dNative: filter must be "+("rank 4, but got rank "+filter.rank+".")});assert(x.shape[3]===filter.shape[2],function(){return"Error in gradient of depthwiseConv2d: number of input "+("channels ("+x.shape[3]+") must match the inChannels dimension ")+("in filter "+filter.shape[2]+".")});assert(eitherStridesOrDilationsAreOne(strides,$dilations),function(){return"Error in gradient of depthwiseConv2d: Either strides or "+("dilations must be 1. Got strides "+strides+" and dilations ")+("'"+$dilations+"'.")});if(dimRoundingMode!=null){assert(isInt(pad3),function(){return"Error in depthwiseConv2d: pad must be an integer when using, "+("dimRoundingMode "+dimRoundingMode+" but got pad "+pad3+".")})}return{x:function(){return depthwiseConv2dNativeBackpropInput(x.shape,dy,filter,strides,pad3,dilations,dimRoundingMode)},filter:function(){return depthwiseConv2dNativeBackpropFilter(x,dy,filter.shape,strides,pad3,dilations,dimRoundingMode)}}}};var dilation2dGradConfig={kernelName:Dilation2D,inputsToSave:["x","filter"],gradFunc:function(dy,saved,attrs){var _a=saved,x=_a[0],filter=_a[1];var inputInputs={x,filter,dy};var filterInputs={x,filter,dy};return{x:function(){return ENGINE.runKernel(Dilation2DBackpropInput,inputInputs,attrs)},filter:function(){return ENGINE.runKernel(Dilation2DBackpropFilter,filterInputs,attrs)}}}};var divGradConfig={kernelName:Div3,inputsToSave:["a","b"],gradFunc:function(dy,saved){var a=saved[0],b=saved[1];var outShape=assertAndGetBroadcastShape(a.shape,b.shape);var derA=function(){var res=div(dy,cast2(b,"float32"));var reduceAxes=getReductionAxes(a.shape,outShape);if(reduceAxes.length>0){return reshape2(sum$1(res,reduceAxes),a.shape)}return res};var derB=function(){var res=mul(dy,cast2(a,"float32"));var reduceAxes=getReductionAxes(b.shape,outShape);if(reduceAxes.length>0){res=reshape2(sum$1(res,reduceAxes),b.shape)}var tmp=square(b);return neg(div(res,cast2(tmp,"float32")))};return{a:derA,b:derB}}};var eluGradConfig={kernelName:Elu,outputsToSave:[true],gradFunc:function(dy,saved){var y=saved[0];var backPropKernelFunc=function(backend2){return backend2.eluDer(dy,y)};var inputs={dy,y};return{x:function(){return ENGINE.runKernelFunc(backPropKernelFunc,inputs,null,EluGrad)}}}};var erfGradConfig={kernelName:Erf,inputsToSave:["x"],gradFunc:function(dy,saved){var x=saved[0];var a=mul(exp(neg(square(x))),2/Math.sqrt(Math.PI));return{x:function(){return mul(dy,a)}}}};var expGradConfig={kernelName:Exp3,outputsToSave:[true],gradFunc:function(dy,saved){var y=saved[0];return{x:function(){return mul(dy,y)}}}};var expm1GradConfig={kernelName:Expm1,inputsToSave:["x"],gradFunc:function(dy,saved){var x=saved[0];return{x:function(){return mul(dy,exp(x))}}}};var floorGradConfig={kernelName:Floor,gradFunc:function(dy){return{x:function(){return zerosLike2(dy)}}}};var floorDivGradConfig={kernelName:FloorDiv3,inputsToSave:["a","b"],gradFunc:function(dy,saved){var a=saved[0],b=saved[1];var outShape=assertAndGetBroadcastShape(a.shape,b.shape);var derA=function(){var res=div(dy,cast2(b,"float32"));var reduceAxes=getReductionAxes(a.shape,outShape);if(reduceAxes.length>0){return reshape2(sum$1(res,reduceAxes),a.shape)}return res};var derB=function(){var res=mul(dy,cast2(a,"float32"));var reduceAxes=getReductionAxes(b.shape,outShape);if(reduceAxes.length>0){res=reshape2(sum$1(res,reduceAxes),b.shape)}var tmp=square(b);return neg(div(res,cast2(tmp,"float32")))};return{a:derA,b:derB}}};var fusedBatchNormGradConfig={kernelName:FusedBatchNorm3,inputsToSave:["x","mean","variance","scale"],gradFunc:function(dy,saved,attrs){var varianceEpsilon=attrs.varianceEpsilon;var x=saved[0],mean2=saved[1],variance=saved[2],scale=saved[3];var scaleValue=scale==null?scalar(1):scale;var reductionAxes=getReductionAxes(mean2.shape,x.shape);var tileShape=[];if(mean2.rank===1){for(var i=0;i0){return reshape2(sum$1(dy,reduceAxes),a.shape)}return dy};var derB=function(){var res=mul(dy,neg(floor(div(a,b))));var reduceAxes=getReductionAxes(b.shape,outShape);if(reduceAxes.length>0){return reshape2(sum$1(res,reduceAxes),b.shape)}return res};return{a:derA,b:derB}}};var multiplyGradConfig={kernelName:Multiply3,inputsToSave:["a","b"],gradFunc:function(dy,saved){var a=saved[0],b=saved[1];var outShape=assertAndGetBroadcastShape(a.shape,b.shape);var derA=function(){var res=mul(dy,cast2(b,"float32"));var reduceAxes=getReductionAxes(a.shape,outShape);if(reduceAxes.length>0){return reshape2(sum$1(res,reduceAxes),a.shape)}return res};var derB=function(){var res=mul(dy,cast2(a,"float32"));var reduceAxes=getReductionAxes(b.shape,outShape);if(reduceAxes.length>0){return reshape2(sum$1(res,reduceAxes),b.shape)}return res};return{a:derA,b:derB}}};var negateGradConfig={kernelName:Negate3,gradFunc:function(dy){return{x:function(){return neg(dy)}}}};var oneHotGradConfig={kernelName:OneHot3,inputsToSave:["indices"],gradFunc:function(dy,saved){var indices=saved[0];return{indices:function(){return zeros(indices.shape,"float32")}}}};var onesLikeGradConfig={kernelName:OnesLike3,gradFunc:function(dy){return{x:function(){return zerosLike2(dy)}}}};var padV2GradConfig={kernelName:PadV23,inputsToSave:["x"],gradFunc:function(dy,saved,attrs){var x=saved[0];var paddings=attrs.paddings;var begin=paddings.map(function(p){return p[0]});return{x:function(){return slice2(dy,begin,x.shape)}}}};var powGradConfig={kernelName:Pow3,inputsToSave:["a","b"],outputsToSave:[true],gradFunc:function(dy,saved){var a=saved[0],b=saved[1],y=saved[2];var base=a;var exp2=b;var outShape=assertAndGetBroadcastShape(base.shape,exp2.shape);var derBase=function(){var expFloat=cast2(exp2,"float32");var res=mul(dy,mul(expFloat,pow(base,sub(expFloat,scalar(1)))));var reduceAxes=getReductionAxes(base.shape,outShape);if(reduceAxes.length>0){res=sum$1(res,reduceAxes)}return reshape2(res,base.shape)};var derExp=function(){var condition=greater(base,0);var logBase=where(condition,log(base),zerosLike2(base));var res=mul(dy,mul(y,logBase));var reduceAxes=getReductionAxes(exp2.shape,outShape);if(reduceAxes.length>0){res=sum$1(res,reduceAxes)}return reshape2(res,exp2.shape)};return{a:derBase,b:derExp}}};var preluGradConfig={kernelName:Prelu3,inputsToSave:["x","alpha"],gradFunc:function(dy,saved){var x=saved[0],alpha=saved[1];var mask=greater(x,0);return{x:function(){return where(mask,dy,mul(dy,alpha))},alpha:function(){var res=where(mask,zerosLike2(dy),mul(dy,x));var reduceAxes=getReductionAxes(alpha.shape,dy.shape);if(reduceAxes.length>0){res=sum$1(res,reduceAxes)}return reshape2(res,alpha.shape)}}}};var reciprocalGradConfig={kernelName:Reciprocal,inputsToSave:["x"],gradFunc:function(dy,saved){var x=saved[0];return{x:function(){return div(dy,neg(square(x)))}}}};var relu6GradConfig={kernelName:Relu63,inputsToSave:["x"],gradFunc:function(dy,saved){var x=saved[0];var mask=mul(lessEqual(x,6),step(x));return{x:function(){return mul(dy,cast2(mask,"float32"))}}}};var reluGradConfig={kernelName:Relu3,inputsToSave:["x"],gradFunc:function(dy,saved){var x=saved[0];return{x:function(){return mul(dy,cast2(step(x),"float32"))}}}};var reshapeGradConfig={kernelName:Reshape6,inputsToSave:["x"],gradFunc:function(dy,saved){var x=saved[0];return{x:function(){return reshape2(dy,x.shape)}}}};var resizeBilinearGradConfig={kernelName:ResizeBilinear3,inputsToSave:["images"],gradFunc:function(dy,saved,attrs){var images=saved[0];var backPropKernelFunc=function(backend2){var alignCorners=attrs.alignCorners;return backend2.resizeBilinearBackprop(dy,images,alignCorners)};var inputs={images};var imagesDer=function(){return ENGINE.runKernelFunc(backPropKernelFunc,inputs,null,ResizeBilinearGrad,attrs)};return{images:imagesDer}}};var resizeNearestNeighborGradConfig={kernelName:ResizeNearestNeighbor,inputsToSave:["images"],gradFunc:function(dy,saved,attrs){var images=saved[0];var backPropKernelFunc=function(backend2){var alignCorners=attrs.alignCorners;return backend2.resizeNearestNeighborBackprop(dy,images,alignCorners)};var inputs={images};var imagesDer=function(){return ENGINE.runKernelFunc(backPropKernelFunc,inputs,null,ResizeNearestNeighborGrad,attrs)};return{images:imagesDer}}};var reverseGradConfig={kernelName:Reverse3,gradFunc:function(dy,saved,attrs){var dims=attrs.dims;var axes=parseAxisParam(dims,dy.shape);return{x:function(){return reverse2(dy,axes)}}}};var roundGradConfig={kernelName:Round,gradFunc:function(dy){return{x:function(){return zerosLike2(dy)}}}};var rsqrtGradConfig={kernelName:Rsqrt3,inputsToSave:["x"],gradFunc:function(dy,saved){var x=saved[0];return{x:function(){return neg(div(dy,mul(pow(x,1.5),2)))}}}};var selectV2PoolGradConfig={kernelName:SelectV23,inputsToSave:["condition"],gradFunc:function(dy,saved){var condition=saved[0];return{condition:function(){return cast2(zerosLike2(condition),"float32")},t:function(){return mul(dy,cast2(condition,dy.dtype))},e:function(){return mul(dy,cast2(logicalNot(condition),dy.dtype))}}}};var seluGradConfig={kernelName:Selu,inputsToSave:["x"],gradFunc:function(dy,saved){var x=saved[0];return{x:function(){var mask=greater(x,scalar(0));var scaleAlpha=scalar(SELU_SCALEALPHA);var scale=scalar(SELU_SCALE);var greaterThanZeroDer=mul(dy,scale);var lessEqualZeroDer=mul(mul(dy,scaleAlpha),exp(cast2(x,"float32")));return where(mask,greaterThanZeroDer,lessEqualZeroDer)}}}};var sigmoidGradConfig={kernelName:Sigmoid3,outputsToSave:[true],gradFunc:function(dy,saved){var y=saved[0];return{x:function(){return mul(dy,mul(y,sub(scalar(1),y)))}}}};var signGradConfig={kernelName:Sign,gradFunc:function(dy){return{x:function(){return zerosLike2(dy)}}}};var sinGradConfig={kernelName:Sin3,inputsToSave:["x"],gradFunc:function(dy,saved){var x=saved[0];return{x:function(){return mul(cos(cast2(x,"float32")),dy)}}}};var sinhGradConfig={kernelName:Sinh,inputsToSave:["x"],gradFunc:function(dy,saved){var x=saved[0];return{x:function(){return mul(cosh(cast2(x,"float32")),dy)}}}};var sliceGradConfig={kernelName:Slice6,inputsToSave:["x"],gradFunc:function(dy,saved,attrs){var x=saved[0];var _a=attrs,begin=_a.begin,size=_a.size;var inputShape=x.shape;var _b=parseSliceParams(x,begin,size),begin_=_b[0],size_=_b[1];var paddings=[];for(var i=0;i0){res=sum$1(res,reduceAxes)}return reshape2(res,a.shape)};var derB=function(){var res=dy;var reduceAxes=getReductionAxes(b.shape,outShape);if(reduceAxes.length>0){res=sum$1(res,reduceAxes)}return reshape2(neg(res),b.shape)};return{a:derA,b:derB}}};var sumGradConfig={kernelName:Sum3,inputsToSave:["x"],gradFunc:function(dy,saved,attrs){var x=saved[0];var expandedDyShape=x.shape.slice();var axis=attrs.axis;var axes=parseAxisParam(axis,x.shape);axes.forEach(function(axis2){expandedDyShape[axis2]=1});var expandedDy=reshape2(dy,expandedDyShape);var derX=mul(expandedDy,ones$1(x.shape,"float32"));return{x:function(){return derX}}}};var tanGradConfig={kernelName:Tan,inputsToSave:["x"],gradFunc:function(dy,saved){var x=saved[0];return{x:function(){return div(dy,square(cos(x)))}}}};var tanhGradConfig={kernelName:Tanh3,outputsToSave:[true],gradFunc:function(dy,saved){var y=saved[0];return{x:function(){return mul(sub(scalar(1),square(y)),dy)}}}};var tileGradConfig={kernelName:Tile3,inputsToSave:["x"],gradFunc:function(dy,saved,attrs){var x=saved[0];var reps=attrs.reps;var derX=function(){var xGrad=zerosLike2(x);if(x.rank===1){for(var i=0;i{"use strict";Object.defineProperty(exports2,"__esModule",{value:true});var tfc=require_tf_core_node();var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d2,b2){d2.__proto__=b2}||function(d2,b2){for(var p in b2)if(b2.hasOwnProperty(p))d2[p]=b2[p]};return extendStatics(d,b)};function __extends(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}var __assign=function(){__assign=Object.assign||function __assign2(t){for(var s,i=1,n=arguments.length;i0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]b?1:0}function reverseNumberCompare(a,b){return-1*numberCompare(a,b)}function unique(xs){if(xs==null){return xs}var out=[];for(var _i=0,xs_1=xs;_i=0);assert(maxLength>=minLength);return Array.isArray(x)&&x.length>=minLength&&x.length<=maxLength&&x.every(function(e){return typeof e===expectedType})}function assertPositiveInteger(value,name){if(Array.isArray(value)){tfc.util.assert(value.length>0,function(){return name+" is unexpectedly an empty array."});value.forEach(function(v,i){return assertPositiveInteger(v,"element "+(i+1)+" of "+name)})}else{tfc.util.assert(Number.isInteger(value)&&value>0,function(){return"Expected "+name+" to be a positive integer, but got "+(formatAsFriendlyString(value)+".")})}}function formatAsFriendlyString(value){if(value===null){return"null"}else if(Array.isArray(value)){return"["+value.map(function(v){return formatAsFriendlyString(v)}).join(",")+"]"}else if(typeof value==="string"){return'"'+value+'"'}else{return""+value}}function debounce(f,waitMs){var lastTime=tfc.util.now();var lastResult;var f2=function(){var args=[];for(var _i=0;_i0){var result=scopedName+"_"+index;nameMap.set(result,1);return result}else{return scopedName}}var tensorNameRegex=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function isValidTensorName(name){return!!name.match(tensorNameRegex)}function isInteger(x){return x===parseInt(x.toString(),10)}function arrayProd(array,begin,end){if(begin==null){begin=0}if(end==null){end=array.length}var prod=1;for(var i=begin;i= 2"+(" but got x shape = "+a.shape+" and y shape = "+b.shape))}if(b.rank>=3){var xLastDim=a.shape.slice(-1)[0];var ySecondLastDim=b.shape.slice(-2)[0];if(xLastDim!==ySecondLastDim){throw new NotImplementedError("If rank y >= 3, then the second last dim"+(" of y must equal the last dim of x but got x shape = "+a.shape+" and ")+(" y shape = "+b.shape))}}if(a.rank===2&&b.rank===2){var transposeA=false;var transposeB=false;return tfc.fused.matMul({a,b,transposeA,transposeB,bias:bias?reshapeBias(a.rank,bias,imageDataFormat()):null,activation:activation2})}else{var aFirstDims=a.shape.slice();var aLastDim=aFirstDims.pop();a=a.reshape([-1,aLastDim]);var bShape=b.shape.slice();var bLastDim=bShape.pop();var ySecondLastDim=bShape.pop();var yOtherDims=bShape.concat([bLastDim]);var perm=Array.from({length:b.rank},function(_,i){if(i===0){return b.rank-2}else if(i<=b.rank-2){return i-1}return i});b=b.transpose(perm).reshape([ySecondLastDim,-1]);var outputShape=aFirstDims.concat(yOtherDims);var transposeA=false;var transposeB=false;return tfc.fused.matMul({a,b,transposeA,transposeB,bias:bias?reshapeBias(a.rank,bias,imageDataFormat()):null,activation:activation2}).reshape(outputShape)}}function gather(reference,indices,axis){return tfc.tidy(function(){if(Array.isArray(indices)){indices=tfc.tensor1d(indices,"int32")}else{indices=indices.toInt()}return tfc.gather(reference,indices,axis)})}function square(x){return tfc.mul(x,x)}function reshapeBias(xRank,bias,dataFormat){var biasShape=bias.shape;if(bias.rank!==1&&bias.rank!==xRank){throw new ValueError("Unexpected bias dimensions: "+bias.rank+("; expected it to be 1 or "+xRank))}if(xRank===5){if(dataFormat==="channelsFirst"){if(biasShape.length===1){return bias.reshape([1,biasShape[0],1,1,1])}else{return bias.reshape([1,biasShape[3],biasShape[0],biasShape[1],biasShape[2]])}}else if(dataFormat==="channelsLast"){if(biasShape.length===1){return bias.reshape([1,1,1,1,biasShape[0]])}else{return bias.reshape([1].concat(biasShape))}}}else if(xRank===4){if(dataFormat==="channelsFirst"){if(biasShape.length===1){return bias.reshape([1,biasShape[0],1,1])}else{return bias.reshape([1,biasShape[2],biasShape[0],biasShape[1]])}}else if(dataFormat==="channelsLast"){if(biasShape.length===1){return bias.reshape([1,1,1,biasShape[0]])}else{return bias.reshape([1].concat(biasShape))}}}else if(xRank===3){if(dataFormat==="channelsFirst"){if(biasShape.length===1){return bias.reshape([1,biasShape[0],1])}else{return bias.reshape([1,biasShape[1],biasShape[0]])}}else if(dataFormat==="channelsLast"){if(biasShape.length===1){return bias.reshape([1,1,biasShape[0]])}else{return bias.reshape([1].concat(biasShape))}}}else if(xRank<3){return bias}throw new ValueError("Unsupported input rank by biasAdd: "+bias.rank)}function biasAdd(x,bias,dataFormat){return tfc.tidy(function(){if(dataFormat==null){dataFormat=imageDataFormat()}checkDataFormat(dataFormat);return x.add(reshapeBias(x.rank,bias,dataFormat))})}function elu(x,alpha){if(alpha===void 0){alpha=1}if(alpha!==1){throw new NotImplementedError("Support for alpha values other than 1 ("+alpha+") is not implemented yet.")}return tfc.elu(x)}function softsign(x){return tfc.tidy(function(){return tfc.div(x,tfc.abs(x).add(1))})}function dropout(x,level,noiseShape,seed){return tfc.tidy(function(){return tfc.dropout(x,level,noiseShape,seed)})}function hardSigmoid(x){return tfc.tidy(function(){var y=tfc.add(.5,tfc.mul(.2,x));return tfc.clipByValue(y,0,1)})}function inTrainPhase(x,alt,training){if(training===void 0){training=false}return training?x():alt()}var VALID_FAN_MODE_VALUES=["fanIn","fanOut","fanAvg"];var VALID_DISTRIBUTION_VALUES=["normal","uniform","truncatedNormal"];function checkFanMode(value){checkStringTypeUnionValue(VALID_FAN_MODE_VALUES,"FanMode",value)}function checkDistribution(value){checkStringTypeUnionValue(VALID_DISTRIBUTION_VALUES,"Distribution",value)}var Initializer=function(_super){__extends(Initializer2,_super);function Initializer2(){return _super!==null&&_super.apply(this,arguments)||this}Initializer2.prototype.fromConfigUsesCustomObjects=function(){return false};Initializer2.prototype.getConfig=function(){return{}};return Initializer2}(tfc.serialization.Serializable);var Zeros=function(_super){__extends(Zeros2,_super);function Zeros2(){return _super!==null&&_super.apply(this,arguments)||this}Zeros2.prototype.apply=function(shape,dtype){return tfc.zeros(shape,dtype)};Zeros2.className="Zeros";return Zeros2}(Initializer);tfc.serialization.registerClass(Zeros);var Ones=function(_super){__extends(Ones2,_super);function Ones2(){return _super!==null&&_super.apply(this,arguments)||this}Ones2.prototype.apply=function(shape,dtype){return tfc.ones(shape,dtype)};Ones2.className="Ones";return Ones2}(Initializer);tfc.serialization.registerClass(Ones);var Constant=function(_super){__extends(Constant2,_super);function Constant2(args){var _this=_super.call(this)||this;if(typeof args!=="object"){throw new ValueError("Expected argument of type ConstantConfig but got "+args)}if(args.value===void 0){throw new ValueError("config must have value set but got "+args)}_this.value=args.value;return _this}Constant2.prototype.apply=function(shape,dtype){var _this=this;return tfc.tidy(function(){return tfc.mul(tfc.scalar(_this.value),tfc.ones(shape,dtype))})};Constant2.prototype.getConfig=function(){return{value:this.value}};Constant2.className="Constant";return Constant2}(Initializer);tfc.serialization.registerClass(Constant);var RandomUniform=function(_super){__extends(RandomUniform2,_super);function RandomUniform2(args){var _this=_super.call(this)||this;_this.DEFAULT_MINVAL=-.05;_this.DEFAULT_MAXVAL=.05;_this.minval=args.minval||_this.DEFAULT_MINVAL;_this.maxval=args.maxval||_this.DEFAULT_MAXVAL;_this.seed=args.seed;return _this}RandomUniform2.prototype.apply=function(shape,dtype){return tfc.randomUniform(shape,this.minval,this.maxval,dtype)};RandomUniform2.prototype.getConfig=function(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}};RandomUniform2.className="RandomUniform";return RandomUniform2}(Initializer);tfc.serialization.registerClass(RandomUniform);var RandomNormal=function(_super){__extends(RandomNormal2,_super);function RandomNormal2(args){var _this=_super.call(this)||this;_this.DEFAULT_MEAN=0;_this.DEFAULT_STDDEV=.05;_this.mean=args.mean||_this.DEFAULT_MEAN;_this.stddev=args.stddev||_this.DEFAULT_STDDEV;_this.seed=args.seed;return _this}RandomNormal2.prototype.apply=function(shape,dtype){dtype=dtype||"float32";if(dtype!=="float32"&&dtype!=="int32"){throw new NotImplementedError("randomNormal does not support dType "+dtype+".")}return randomNormal(shape,this.mean,this.stddev,dtype,this.seed)};RandomNormal2.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}};RandomNormal2.className="RandomNormal";return RandomNormal2}(Initializer);tfc.serialization.registerClass(RandomNormal);var TruncatedNormal=function(_super){__extends(TruncatedNormal2,_super);function TruncatedNormal2(args){var _this=_super.call(this)||this;_this.DEFAULT_MEAN=0;_this.DEFAULT_STDDEV=.05;_this.mean=args.mean||_this.DEFAULT_MEAN;_this.stddev=args.stddev||_this.DEFAULT_STDDEV;_this.seed=args.seed;return _this}TruncatedNormal2.prototype.apply=function(shape,dtype){dtype=dtype||"float32";if(dtype!=="float32"&&dtype!=="int32"){throw new NotImplementedError("truncatedNormal does not support dType "+dtype+".")}return tfc.truncatedNormal(shape,this.mean,this.stddev,dtype,this.seed)};TruncatedNormal2.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}};TruncatedNormal2.className="TruncatedNormal";return TruncatedNormal2}(Initializer);tfc.serialization.registerClass(TruncatedNormal);var Identity5=function(_super){__extends(Identity6,_super);function Identity6(args){var _this=_super.call(this)||this;_this.gain=args.gain!=null?args.gain:1;return _this}Identity6.prototype.apply=function(shape,dtype){var _this=this;return tfc.tidy(function(){if(shape.length!==2||shape[0]!==shape[1]){throw new ValueError("Identity matrix initializer can only be used for 2D square matrices.")}else{return tfc.mul(_this.gain,tfc.eye(shape[0]))}})};Identity6.prototype.getConfig=function(){return{gain:this.gain}};Identity6.className="Identity";return Identity6}(Initializer);tfc.serialization.registerClass(Identity5);function computeFans(shape,dataFormat){if(dataFormat===void 0){dataFormat="channelsLast"}var fanIn;var fanOut;checkDataFormat(dataFormat);if(shape.length===2){fanIn=shape[0];fanOut=shape[1]}else if([3,4,5].indexOf(shape.length)!==-1){if(dataFormat==="channelsFirst"){var receptiveFieldSize=arrayProd(shape,2);fanIn=shape[1]*receptiveFieldSize;fanOut=shape[0]*receptiveFieldSize}else if(dataFormat==="channelsLast"){var receptiveFieldSize=arrayProd(shape,0,shape.length-2);fanIn=shape[shape.length-2]*receptiveFieldSize;fanOut=shape[shape.length-1]*receptiveFieldSize}}else{var shapeProd=arrayProd(shape);fanIn=Math.sqrt(shapeProd);fanOut=Math.sqrt(shapeProd)}return[fanIn,fanOut]}var VarianceScaling=function(_super){__extends(VarianceScaling2,_super);function VarianceScaling2(args){var _this=_super.call(this)||this;if(args.scale<0){throw new ValueError("scale must be a positive float. Got: "+args.scale)}_this.scale=args.scale==null?1:args.scale;_this.mode=args.mode==null?"fanIn":args.mode;checkFanMode(_this.mode);_this.distribution=args.distribution==null?"normal":args.distribution;checkDistribution(_this.distribution);_this.seed=args.seed;return _this}VarianceScaling2.prototype.apply=function(shape,dtype){var fans=computeFans(shape);var fanIn=fans[0];var fanOut=fans[1];var scale=this.scale;if(this.mode==="fanIn"){scale/=Math.max(1,fanIn)}else if(this.mode==="fanOut"){scale/=Math.max(1,fanOut)}else{scale/=Math.max(1,(fanIn+fanOut)/2)}if(this.distribution==="normal"){var stddev=Math.sqrt(scale);dtype=dtype||"float32";if(dtype!=="float32"&&dtype!=="int32"){throw new NotImplementedError(this.getClassName()+" does not support dType "+dtype+".")}return tfc.truncatedNormal(shape,0,stddev,dtype,this.seed)}else{var limit=Math.sqrt(3*scale);return tfc.randomUniform(shape,-limit,limit,dtype)}};VarianceScaling2.prototype.getConfig=function(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}};VarianceScaling2.className="VarianceScaling";return VarianceScaling2}(Initializer);tfc.serialization.registerClass(VarianceScaling);var GlorotUniform=function(_super){__extends(GlorotUniform2,_super);function GlorotUniform2(args){return _super.call(this,{scale:1,mode:"fanAvg",distribution:"uniform",seed:args==null?null:args.seed})||this}GlorotUniform2.prototype.getClassName=function(){return VarianceScaling.className};GlorotUniform2.className="GlorotUniform";return GlorotUniform2}(VarianceScaling);tfc.serialization.registerClass(GlorotUniform);var GlorotNormal=function(_super){__extends(GlorotNormal2,_super);function GlorotNormal2(args){return _super.call(this,{scale:1,mode:"fanAvg",distribution:"normal",seed:args==null?null:args.seed})||this}GlorotNormal2.prototype.getClassName=function(){return VarianceScaling.className};GlorotNormal2.className="GlorotNormal";return GlorotNormal2}(VarianceScaling);tfc.serialization.registerClass(GlorotNormal);var HeNormal=function(_super){__extends(HeNormal2,_super);function HeNormal2(args){return _super.call(this,{scale:2,mode:"fanIn",distribution:"normal",seed:args==null?null:args.seed})||this}HeNormal2.prototype.getClassName=function(){return VarianceScaling.className};HeNormal2.className="HeNormal";return HeNormal2}(VarianceScaling);tfc.serialization.registerClass(HeNormal);var HeUniform=function(_super){__extends(HeUniform2,_super);function HeUniform2(args){return _super.call(this,{scale:2,mode:"fanIn",distribution:"uniform",seed:args==null?null:args.seed})||this}HeUniform2.prototype.getClassName=function(){return VarianceScaling.className};HeUniform2.className="HeUniform";return HeUniform2}(VarianceScaling);tfc.serialization.registerClass(HeUniform);var LeCunNormal=function(_super){__extends(LeCunNormal2,_super);function LeCunNormal2(args){return _super.call(this,{scale:1,mode:"fanIn",distribution:"normal",seed:args==null?null:args.seed})||this}LeCunNormal2.prototype.getClassName=function(){return VarianceScaling.className};LeCunNormal2.className="LeCunNormal";return LeCunNormal2}(VarianceScaling);tfc.serialization.registerClass(LeCunNormal);var LeCunUniform=function(_super){__extends(LeCunUniform2,_super);function LeCunUniform2(args){return _super.call(this,{scale:1,mode:"fanIn",distribution:"uniform",seed:args==null?null:args.seed})||this}LeCunUniform2.prototype.getClassName=function(){return VarianceScaling.className};LeCunUniform2.className="LeCunNormal";return LeCunUniform2}(VarianceScaling);tfc.serialization.registerClass(LeCunUniform);var Orthogonal=function(_super){__extends(Orthogonal2,_super);function Orthogonal2(args){var _this=_super.call(this)||this;_this.DEFAULT_GAIN=1;_this.gain=args.gain==null?_this.DEFAULT_GAIN:args.gain;_this.seed=args.seed;if(_this.seed!=null){throw new NotImplementedError("Random seed is not implemented for Orthogonal Initializer yet.")}return _this}Orthogonal2.prototype.apply=function(shape,dtype){var _this=this;return tfc.tidy(function(){if(shape.length<2){throw new NotImplementedError("Shape must be at least 2D.")}if(shape[0]*shape[1]>2e3){console.warn("Orthogonal initializer is being called on a matrix with more "+("than 2000 ("+shape[0]*shape[1]+") elements: ")+"Slowness may result.")}var normalizedShape=shape[0]>shape[1]?[shape[1],shape[0]]:shape;var a=randomNormal(normalizedShape,0,1,"float32");var q=tfc.linalg.gramSchmidt(a);if(shape[0]>shape[1]){q=q.transpose()}return tfc.mul(_this.gain,q)})};Orthogonal2.prototype.getConfig=function(){return{gain:this.gain,seed:this.seed}};Orthogonal2.className="Orthogonal";return Orthogonal2}(Initializer);tfc.serialization.registerClass(Orthogonal);var INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP={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 deserializeInitializer(config2,customObjects){if(customObjects===void 0){customObjects={}}return deserializeKerasObject(config2,tfc.serialization.SerializationMap.getMap().classNameMap,customObjects,"initializer")}function serializeInitializer(initializer){return serializeKerasObject(initializer)}function getInitializer(identifier){if(typeof identifier==="string"){var className=identifier in INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP?INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP[identifier]:identifier;if(className==="GlorotNormal"){return new GlorotNormal}else if(className==="GlorotUniform"){return new GlorotUniform}else if(className==="HeNormal"){return new HeNormal}else if(className==="HeUniform"){return new HeUniform}else if(className==="LeCunNormal"){return new LeCunNormal}else if(className==="LeCunUniform"){return new LeCunUniform}else{var config2={};config2["className"]=className;config2["config"]={};return deserializeInitializer(config2)}}else if(identifier instanceof Initializer){return identifier}else{return deserializeInitializer(identifier)}}function zeros(){return new Zeros}function ones(){return new Ones}function constant(args){return new Constant(args)}function randomUniform(args){return new RandomUniform(args)}function randomNormal$1(args){return new RandomNormal(args)}function truncatedNormal(args){return new TruncatedNormal(args)}function identity2(args){return new Identity5(args)}function varianceScaling(config2){return new VarianceScaling(config2)}function glorotUniform(args){return new GlorotUniform(args)}function glorotNormal(args){return new GlorotNormal(args)}function heNormal(args){return new HeNormal(args)}function heUniform(args){return new HeUniform(args)}function leCunNormal(args){return new LeCunNormal(args)}function leCunUniform(args){return new LeCunUniform(args)}function orthogonal(args){return new Orthogonal(args)}var exports_initializers={__proto__:null,zeros,ones,constant,randomUniform,randomNormal:randomNormal$1,truncatedNormal,identity:identity2,varianceScaling,glorotUniform,glorotNormal,heNormal,heUniform,leCunNormal,leCunUniform,orthogonal};var _nextUniqueTensorId=0;function getNextUniqueTensorId(){return _nextUniqueTensorId++}var _uidPrefixes={};function getUid(prefix){if(prefix===void 0){prefix=""}if(!(prefix in _uidPrefixes)){_uidPrefixes[prefix]=0}_uidPrefixes[prefix]+=1;return prefix+_uidPrefixes[prefix].toString()}function isArrayOfShapes(x){return Array.isArray(x)&&Array.isArray(x[0])}function normalizeShapeList(x){if(x.length===0){return[]}if(!Array.isArray(x[0])){return[x]}return x}function getExactlyOneTensor(xs){var x;if(Array.isArray(xs)){if(xs.length!==1){throw new ValueError("Expected Tensor length to be 1; got "+xs.length)}x=xs[0]}else{x=xs}return x}function getExactlyOneShape(shapes){if(Array.isArray(shapes)&&Array.isArray(shapes[0])){if(shapes.length===1){shapes=shapes;return shapes[0]}else{throw new ValueError("Expected exactly 1 Shape; got "+shapes.length)}}else{return shapes}}function countParamsInWeights(weights){var count2=0;for(var _i=0,weights_1=weights;_i1){throw new AttributeError("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use `getInputAt(nodeIndex)` instead.')}else if(this.inboundNodes.length===0){throw new AttributeError("Layer "+this.name+" is not connected, no input to return.")}return singletonOrArray(this.getNodeAtIndex(0,"input").inputTensors)},enumerable:true,configurable:true});Object.defineProperty(Layer2.prototype,"output",{get:function(){if(this.inboundNodes.length===0){throw new AttributeError("Layer "+this.name+" has no inbound nodes.")}if(this.inboundNodes.length>1){throw new AttributeError("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use `getOutputAt(nodeIndex)` instead.')}return singletonOrArray(this.getNodeAtIndex(0,"output").outputTensors)},enumerable:true,configurable:true});Object.defineProperty(Layer2.prototype,"losses",{get:function(){return this._losses},enumerable:true,configurable:true});Layer2.prototype.calculateLosses=function(){return this.losses.map(function(lossFn){return lossFn()})};Object.defineProperty(Layer2.prototype,"updates",{get:function(){return this._updates},enumerable:true,configurable:true});Object.defineProperty(Layer2.prototype,"built",{get:function(){return this._built},set:function(built){this._built=built},enumerable:true,configurable:true});Object.defineProperty(Layer2.prototype,"trainable",{get:function(){return this.trainable_},set:function(trainable){this._trainableWeights.forEach(function(w){return w.trainable=trainable});this.trainable_=trainable},enumerable:true,configurable:true});Object.defineProperty(Layer2.prototype,"trainableWeights",{get:function(){if(this.trainable_){return this._trainableWeights.filter(function(w){return w.trainable})}else{return[]}},set:function(weights){this._trainableWeights=weights},enumerable:true,configurable:true});Object.defineProperty(Layer2.prototype,"nonTrainableWeights",{get:function(){if(this.trainable){return this._trainableWeights.filter(function(w){return!w.trainable}).concat(this._nonTrainableWeights)}else{return this._trainableWeights.concat(this._nonTrainableWeights)}},set:function(weights){this._nonTrainableWeights=weights},enumerable:true,configurable:true});Object.defineProperty(Layer2.prototype,"weights",{get:function(){return this.trainableWeights.concat(this.nonTrainableWeights)},enumerable:true,configurable:true});Object.defineProperty(Layer2.prototype,"stateful",{get:function(){return this._stateful},enumerable:true,configurable:true});Layer2.prototype.resetStates=function(){if(!this.stateful){throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")}};Layer2.prototype.assertInputCompatibility=function(inputs){inputs=toList(inputs);if(this.inputSpec==null||this.inputSpec.length===0){return}var inputSpec=toList(this.inputSpec);if(inputs.length!==inputSpec.length){throw new ValueError("Layer "+this.name+" expects "+inputSpec.length+" inputs, "+("but it received "+inputs.length+" input tensors. ")+("Input received: "+inputs))}for(var inputIndex=0;inputIndex=0?xShape[axis]:xShape[xShape.length+axis];if(value!=null&&[value,null].indexOf(xShapeAtAxis)===-1){throw new ValueError("Input "+inputIndex+" is incompatible with layer "+(this.name+": expected axis "+axis+" of input shape to ")+("have value "+value+" but got shape "+xShape+"."))}}}if(spec.shape!=null){for(var i=0;i0&&Array.isArray(outputShape[0])){output=outputShape.map(function(shape,index){return new SymbolicTensor(outputDType_1,shape,_this,toList(inputs),kwargs,_this.name,index)})}else{output=new SymbolicTensor(outputDType_1,outputShape,_this,toList(inputs),kwargs,_this.name)}_this.addInboundNode(inputs,output,null,null,inputShape,outputShape,kwargs);_this._refCount++;if(_this.activityRegularizer!=null){throw new NotImplementedError("Layer invocation in the presence of activity regularizer(s) is not supported yet.")}return output}})};Layer2.prototype.warnOnIncompatibleInputShape=function(inputShape){if(this.batchInputShape==null){return}else if(inputShape.length!==this.batchInputShape.length){console.warn("The rank of the input tensor provided (shape: "+(JSON.stringify(inputShape)+") does not match that of the ")+("batchInputShape ("+JSON.stringify(this.batchInputShape)+") ")+("of the layer "+this.name))}else{var dimMismatch_1=false;this.batchInputShape.forEach(function(dimension,i){if(dimension!=null&&inputShape[i]!=null&&inputShape[i]!==dimension){dimMismatch_1=true}});if(dimMismatch_1){console.warn("The shape of the input tensor "+("("+JSON.stringify(inputShape)+") does not ")+("match the expectation of layer "+this.name+": ")+(""+JSON.stringify(this.batchInputShape)))}}};Object.defineProperty(Layer2.prototype,"outputShape",{get:function(){if(this.inboundNodes==null||this.inboundNodes.length===0){throw new AttributeError("The layer "+this.name+" has never been called and thus has no defined output shape.")}var allOutputShapes=[];for(var _i=0,_a=this.inboundNodes;_i<_a.length;_i++){var node=_a[_i];var shapeString=JSON.stringify(node.outputShapes);if(allOutputShapes.indexOf(shapeString)===-1){allOutputShapes.push(shapeString)}}if(allOutputShapes.length===1){var outputShapes=this.inboundNodes[0].outputShapes;if(Array.isArray(outputShapes)&&Array.isArray(outputShapes[0])&&outputShapes.length===1){return outputShapes[0]}else{return outputShapes}}else{throw new AttributeError("The layer "+this.name+' has multiple inbound nodes with different output shapes. Hence the notion of "output shape" is ill-defined for the layer.')}},enumerable:true,configurable:true});Layer2.prototype.countParams=function(){if(!this.built){throw new RuntimeError("You tried to call countParams() on "+this.name+", but the layer is not built yet. Build it first by calling build(batchInputShape).")}return countParamsInWeights(this.weights)};Layer2.prototype.build=function(inputShape){this.built=true};Layer2.prototype.getWeights=function(trainableOnly){if(trainableOnly===void 0){trainableOnly=false}return batchGetValue(trainableOnly?this.trainableWeights:this.weights)};Layer2.prototype.setWeights=function(weights){var _this=this;tfc.tidy(function(){var params=_this.weights;if(params.length!==weights.length){throw new ValueError('You called setWeights(weights) on layer "'+_this.name+'" '+("with a weight list of length "+weights.length+", ")+("but the layer was expecting "+params.length+" weights. ")+("Provided weights: "+weights+"..."))}if(params.length===0){return}var weightValueTuples=[];var paramValues=batchGetValue(params);for(var i=0;i0){layer=tensor.sourceLayer;nodeIndex=tensor.nodeIndex}if(layer.inboundNodes.length===0){return[tensor]}else{var node=layer.inboundNodes[nodeIndex];if(node.inboundLayers.length===0){return node.inputTensors}else{var sourceTensors=[];for(var i=0;i0))return[3,2];return[4,Promise.all(promises)];case 1:values=_a.sent();for(i=0;i=0&&Number.isInteger(verbosityLevel),function(){return"Verbosity level is expected to be an integer >= 0, "+("but got "+verbosityLevel)});CallbackConstructorRegistry2.checkForDuplicate(callbackConstructor);if(CallbackConstructorRegistry2.constructors[verbosityLevel]==null){CallbackConstructorRegistry2.constructors[verbosityLevel]=[]}CallbackConstructorRegistry2.constructors[verbosityLevel].push(callbackConstructor)};CallbackConstructorRegistry2.checkForDuplicate=function(callbackConstructor){for(var levelName in CallbackConstructorRegistry2.constructors){var constructors=CallbackConstructorRegistry2.constructors[+levelName];constructors.forEach(function(ctor){if(ctor===callbackConstructor){throw new ValueError("Duplicate callback constructor.")}})}};CallbackConstructorRegistry2.clear=function(){CallbackConstructorRegistry2.constructors={}};CallbackConstructorRegistry2.createCallbacks=function(verbosityLevel){var constructors=[];for(var levelName in CallbackConstructorRegistry2.constructors){var level=+levelName;if(verbosityLevel>=level){constructors.push.apply(constructors,CallbackConstructorRegistry2.constructors[level])}}return constructors.map(function(ctor){return new ctor})};CallbackConstructorRegistry2.constructors={};return CallbackConstructorRegistry2}();function configureCallbacks(callbacks2,verbose,epochs,initialEpoch,numTrainSamples,stepsPerEpoch,batchSize,doValidation,callbackMetrics){var history=new History;var actualCallbacks=[new BaseLogger].concat(CallbackConstructorRegistry.createCallbacks(verbose));if(callbacks2!=null){actualCallbacks.push.apply(actualCallbacks,callbacks2)}actualCallbacks.push(history);var callbackList=new CallbackList(actualCallbacks);callbackList.setParams({epochs,initialEpoch,samples:numTrainSamples,steps:stepsPerEpoch,batchSize,verbose,doValidation,metrics:callbackMetrics});return{callbackList,history}}function deserialize(config2,customObjects,fastWeightInit){if(customObjects===void 0){customObjects={}}if(fastWeightInit===void 0){fastWeightInit=false}return deserializeKerasObject(config2,tfc.serialization.SerializationMap.getMap().classNameMap,customObjects,"layer",fastWeightInit)}function l2Normalize(x,axis){return tfc.tidy(function(){if(x.dtype!=="float32"){x=x.asType("float32")}var squareSum=tfc.sum(square(x),axis,true);var epsilonTensor=tfc.fill(squareSum.shape,epsilon());var norm=tfc.sqrt(tfc.maximum(squareSum,epsilonTensor));return tfc.div(x,norm)})}function meanSquaredError(yTrue,yPred){return tfc.tidy(function(){return tfc.mean(square(tfc.sub(yPred,yTrue)),-1)})}function meanAbsoluteError(yTrue,yPred){return tfc.tidy(function(){return tfc.mean(tfc.abs(tfc.sub(yPred,yTrue)),-1)})}function meanAbsolutePercentageError(yTrue,yPred){return tfc.tidy(function(){var diff=tfc.sub(yTrue,yPred);var clippedTrue=tfc.clipByValue(tfc.abs(yTrue),epsilon(),Number.MAX_VALUE);var absResult=tfc.abs(tfc.div(diff,clippedTrue));return tfc.mul(100,tfc.mean(absResult,-1))})}function meanSquaredLogarithmicError(yTrue,yPred){return tfc.tidy(function(){var clippedPred=tfc.clipByValue(yPred,epsilon(),Number.MAX_VALUE);var firstLog=tfc.log(tfc.add(1,clippedPred));var clippedTrue=tfc.clipByValue(yTrue,epsilon(),Number.MAX_VALUE);var secondLog=tfc.log(tfc.add(1,clippedTrue));return tfc.mean(square(tfc.sub(firstLog,secondLog)),-1)})}function squaredHinge(yTrue,yPred){return tfc.tidy(function(){var maxResult=tfc.maximum(0,tfc.sub(1,tfc.mul(yTrue,yPred)));return tfc.mean(square(maxResult),-1)})}function hinge(yTrue,yPred){return tfc.tidy(function(){var maxResult=tfc.maximum(0,tfc.sub(1,tfc.mul(yTrue,yPred)));return tfc.mean(maxResult,-1)})}function categoricalHinge(yTrue,yPred){return tfc.tidy(function(){var pos=tfc.sum(tfc.mul(yTrue,yPred),-1);var neg=tfc.max(tfc.mul(tfc.sub(1,yTrue),yPred),-1);return tfc.maximum(0,tfc.add(1,tfc.sub(neg,pos)))})}function logcosh(yTrue,yPred){return tfc.tidy(function(){var log2=Math.log(2);var predictionDiff=tfc.sub(yPred,yTrue);var logcoshResult=tfc.sub(tfc.add(predictionDiff,tfc.softplus(tfc.mul(-2,predictionDiff))),log2);return tfc.mean(logcoshResult,-1)})}function categoricalCrossentropy(target,output,fromLogits){if(fromLogits===void 0){fromLogits=false}return tfc.tidy(function(){if(fromLogits){output=tfc.softmax(output)}else{var outputSum=tfc.sum(output,output.shape.length-1,true);output=tfc.div(output,outputSum)}output=tfc.clipByValue(output,epsilon(),1-epsilon());return tfc.neg(tfc.sum(tfc.mul(target.toFloat(),tfc.log(output)),output.shape.length-1))})}function sparseCategoricalCrossentropy(target,output,fromLogits){if(fromLogits===void 0){fromLogits=false}return tfc.tidy(function(){var flatTarget=tfc.floor(flatten(target)).toInt();output=tfc.clipByValue(output,epsilon(),1-epsilon());var outputShape=output.shape;var oneHotTarget=tfc.oneHot(flatTarget,outputShape[outputShape.length-1]).reshape(outputShape);return categoricalCrossentropy(oneHotTarget,output,fromLogits)})}function sigmoidCrossEntropyWithLogits(labels,logits){if(!tfc.util.arraysEqual(labels.shape,logits.shape)){throw new ValueError("logits and labels must have the same shape, but got shapes "+(JSON.stringify(labels.shape)+" and "+JSON.stringify(logits.shape)))}return tfc.tidy(function(){var reluLogits=logits.relu();var negAbsLogits=logits.abs().neg();return reluLogits.sub(logits.mul(labels)).add(negAbsLogits.exp().log1p())})}function binaryCrossentropy(yTrue,yPred){return tfc.tidy(function(){var y;y=tfc.clipByValue(yPred,epsilon(),1-epsilon());y=tfc.log(tfc.div(y,tfc.sub(1,y)));return tfc.mean(sigmoidCrossEntropyWithLogits(yTrue,y),-1)})}function kullbackLeiblerDivergence(yTrue,yPred){return tfc.tidy(function(){var clippedTrue=tfc.clipByValue(yTrue,epsilon(),1);var clippedPred=tfc.clipByValue(yPred,epsilon(),1);return tfc.sum(tfc.mul(yTrue,tfc.log(tfc.div(clippedTrue,clippedPred))),-1)})}function poisson(yTrue,yPred){return tfc.tidy(function(){var logPred=tfc.log(tfc.add(epsilon(),yPred));return tfc.mean(tfc.sub(yPred,tfc.mul(yTrue,logPred)),-1)})}function cosineProximity(yTrue,yPred){return tfc.tidy(function(){var trueNormalized=l2Normalize(yTrue,-1);var predNormalized=l2Normalize(yPred,-1);var trueXPred=tfc.mul(trueNormalized,predNormalized);return tfc.neg(tfc.sum(trueXPred,-1))})}var lossesMap={meanSquaredError,meanAbsoluteError,meanAbsolutePercentageError,meanSquaredLogarithmicError,squaredHinge,hinge,categoricalHinge,logcosh,categoricalCrossentropy,sparseCategoricalCrossentropy,binaryCrossentropy,kullbackLeiblerDivergence,poisson,cosineProximity};function get(identifierOrFn){if(typeof identifierOrFn==="string"){if(identifierOrFn in lossesMap){return lossesMap[identifierOrFn]}var errMsg="Unknown loss "+identifierOrFn;if(identifierOrFn.toLowerCase().includes("softmaxcrossentropy")){errMsg="Unknown loss "+identifierOrFn+'. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy'}throw new ValueError(errMsg)}else{return identifierOrFn}}function binaryAccuracy(yTrue,yPred){return tfc.tidy(function(){var threshold=tfc.mul(.5,tfc.onesLike(yPred));var yPredThresholded=cast2(tfc.greater(yPred,threshold),yTrue.dtype);return tfc.mean(tfc.equal(yTrue,yPredThresholded),-1)})}function categoricalAccuracy(yTrue,yPred){return tfc.tidy(function(){return cast2(tfc.equal(tfc.argMax(yTrue,-1),tfc.argMax(yPred,-1)),"float32")})}function truePositives(yTrue,yPred){return tfc.tidy(function(){return tfc.logicalAnd(yTrue.equal(1),yPred.equal(1)).sum().cast("float32")})}function falseNegatives(yTrue,yPred){return tfc.tidy(function(){return tfc.logicalAnd(yTrue.equal(1),yPred.equal(0)).sum().cast("float32")})}function falsePositives(yTrue,yPred){return tfc.tidy(function(){return tfc.logicalAnd(yTrue.equal(0),yPred.equal(1)).sum().cast("float32")})}function precision(yTrue,yPred){return tfc.tidy(function(){var tp=truePositives(yTrue,yPred);var fp=falsePositives(yTrue,yPred);var denominator=tp.add(fp);return tfc.where(tfc.greater(denominator,0),tp.div(denominator),0).cast("float32")})}function recall(yTrue,yPred){return tfc.tidy(function(){var tp=truePositives(yTrue,yPred);var fn=falseNegatives(yTrue,yPred);var denominator=tp.add(fn);return tfc.where(tfc.greater(denominator,0),tp.div(denominator),0).cast("float32")})}function binaryCrossentropy$1(yTrue,yPred){return binaryCrossentropy(yTrue,yPred)}function sparseCategoricalAccuracy(yTrue,yPred){if(yTrue.rank===yPred.rank){yTrue=yTrue.squeeze([yTrue.rank-1])}yPred=yPred.argMax(-1);if(yPred.dtype!==yTrue.dtype){yPred=yPred.asType(yTrue.dtype)}return tfc.equal(yTrue,yPred).asType("float32")}var mse=meanSquaredError;var MSE=meanSquaredError;var mae=meanAbsoluteError;var MAE=meanAbsoluteError;var mape=meanAbsolutePercentageError;var MAPE=meanAbsolutePercentageError;var categoricalCrossentropy$1=categoricalCrossentropy;var cosine=cosineProximity;var sparseCategoricalCrossentropy$1=sparseCategoricalCrossentropy;var metricsMap={binaryAccuracy,categoricalAccuracy,precision,categoricalCrossentropy:categoricalCrossentropy$1,sparseCategoricalCrossentropy:sparseCategoricalCrossentropy$1,mse,MSE,mae,MAE,mape,MAPE,cosine};function get$1(identifier){if(typeof identifier==="string"&&identifier in metricsMap){return metricsMap[identifier]}else if(typeof identifier!=="string"&&identifier!=null){return identifier}else{throw new ValueError("Unknown metric "+identifier)}}function getLossOrMetricName(fn){assert(fn!==null,"Unknown LossOrMetricFn "+fn);if(typeof fn==="string"){return fn}else{var fnName=void 0;for(var _i=0,_a=Object.keys(lossesMap);_i<_a.length;_i++){var key=_a[_i];if(lossesMap[key]===fn){fnName=key;break}}if(fnName!==void 0){return fnName}for(var _b=0,_c=Object.keys(metricsMap);_b<_c.length;_b++){var key=_c[_b];if(metricsMap[key]===fn){fnName=key;break}}if(fnName!==void 0){return fnName}return fn.name}}function getOptimizer(identifier){var optimizerMap={Adagrad:function(){return tfc.train.adagrad(.01)},Adadelta:function(){return tfc.train.adadelta(1,.95,epsilon())},Adam:function(){return tfc.train.adam(.001,.9,.999,epsilon())},Adamax:function(){return tfc.train.adamax(.002,.9,.999,epsilon(),0)},RMSProp:function(){return tfc.train.rmsprop(.001,.9,0,epsilon())},SGD:function(){return tfc.train.sgd(.01)}};optimizerMap["adagrad"]=optimizerMap["Adagrad"];optimizerMap["adadelta"]=optimizerMap["Adadelta"];optimizerMap["adam"]=optimizerMap["Adam"];optimizerMap["adamax"]=optimizerMap["Adamax"];optimizerMap["rmsprop"]=optimizerMap["RMSProp"];optimizerMap["sgd"]=optimizerMap["SGD"];if(identifier in optimizerMap){return optimizerMap[identifier]()}throw new ValueError("Unknown Optimizer "+identifier)}var MAX_USER_DEFINED_METADATA_SERIALIZED_LENGTH=1*1024*1024;function checkUserDefinedMetadata(userDefinedMetadata,modelName,checkSize){if(checkSize===void 0){checkSize=false}if(userDefinedMetadata==null||typeof userDefinedMetadata!=="object"||Object.getPrototypeOf(userDefinedMetadata)!==Object.prototype||!plainObjectCheck(userDefinedMetadata)){throw new Error("User-defined metadata is expected to be a JSON object, but is not.")}if(checkSize){var out=JSON.stringify(userDefinedMetadata);if(out.length>MAX_USER_DEFINED_METADATA_SERIALIZED_LENGTH){console.warn('User-defined metadata of model "'+modelName+'" is too large in '+("size (length="+out.length+" when serialized). It is not ")+"recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= "+(MAX_USER_DEFINED_METADATA_SERIALIZED_LENGTH+"."))}}}function plainObjectCheck(x){if(x===null){return true}else if(typeof x==="object"){if(Object.getPrototypeOf(x)===Object.prototype){var keys=Object.keys(x);for(var _i=0,keys_1=keys;_i1||depthNodes.length===1&&depthNodes[0].inboundLayers.length>1){sequentialLike=false;break}nodes.push.apply(nodes,depthNodes)}if(sequentialLike){for(var _a=0,_b=model2.layers;_a<_b.length;_a++){var layer=_b[_a];var flag=false;for(var _c=0,_d=layer.inboundNodes;_c<_d.length;_c++){var node=_d[_c];if(nodes.indexOf(node)!==-1){if(flag){sequentialLike=false;break}else{flag=true}}}if(!sequentialLike){break}}}return sequentialLike}function printRow(fields,positions,printFn){if(printFn===void 0){printFn=console.log}var line="";for(var i=0;i0){line=line.slice(0,line.length-1)+" "}line+=fields[i];line=line.slice(0,positions[i]);line+=" ".repeat(positions[i]-line.length)}printFn(line)}function printLayerSummary(layer,positions,printFn){var outputShape;try{outputShape=JSON.stringify(layer.outputShape)}catch(err){outputShape="multiple"}var name=layer.name;var className=layer.getClassName();var fields=[name+" ("+className+")",outputShape,layer.countParams().toString()];printRow(fields,positions,printFn)}function printLayerSummaryWithConnections(layer,positions,relevantNodes,printFn){var outputShape;try{outputShape=JSON.stringify(layer.outputShape)}catch(err){outputShape="multiple"}var connections=[];for(var _i=0,_a=layer.inboundNodes;_i<_a.length;_i++){var node=_a[_i];if(relevantNodes!=null&&relevantNodes.length>0&&relevantNodes.indexOf(node)===-1){continue}for(var i=0;iprobe.maxNumTensors){probe.maxNumTensors=numTensors}if(numTensors0,function(){return"Expected at least one fetch, got none"});var finalSorted=[];var finalRecipientMap={};if(fetches.length===1){var out=getTopologicalSortAndRecipientCountsForOneFetch(fetches[0],feedDict);finalSorted=out.sorted;finalRecipientMap=out.recipientMap}else{var visited=new Set;for(var _i=0,fetches_1=fetches;_i0){var top_1=stack[stack.length-1];if(visited.has(top_1.name)){stack.pop();continue}var topIsMarked=marks[marks.length-1]===stack.length-1;if(top_1.inputs.length===0||topIsMarked){stack.pop();sorted.push(top_1);visited.add(top_1.name);if(topIsMarked){marks.pop()}}else{marks.push(stack.length-1);for(var _b=0,_c=top_1.inputs;_b<_c.length;_b++){var input2=_c[_b];if(recipientMap[input2.name]==null){recipientMap[input2.name]=new Set}recipientMap[input2.name].add(top_1.name);if(visited.has(input2.name)){continue}stack.push(input2)}}}return{sorted,recipientMap}}function getNodeOutputs(fetch2){var layerOutputs;if(fetch2.sourceLayer.inboundNodes.length===1){layerOutputs=fetch2.sourceLayer.output}else{var nodeIndex=null;for(var i=0;i1 nodes");assert(tensorIndex===0,"input layer has >1 tensors");_this.inputLayers.push(layer);_this.inputLayersNodeIndices.push(nodeIndex);_this.inputLayersTensorIndices.push(tensorIndex)}_this.inputNames=[];_this.outputNames=[];_this.feedInputShapes=[];_this.feedInputNames=[];_this.feedOutputNames=[];for(var i=0;i<_this.inputLayers.length;i++){var layer=_this.inputLayers[i];if(!(layer instanceof InputLayer)){throw new TypeError("Input layers to a LayersModel must be InputLayer objects. "+("Received inputs: "+args.inputs+". ")+("Input "+i+" (0-based) originates ")+("from layer type "+layer.getClassName()+"."))}_this.inputNames.push(layer.name);_this.feedInputShapes.push(layer.batchInputShape);_this.feedInputNames.push(layer.name)}for(var _d=0,_e=_this.outputLayers;_d<_e.length;_d++){var layer=_e[_d];_this.outputNames.push(layer.name)}_this.internalInputShapes=_this.inputs.map(function(x2){return x2.shape});_this.internalOutputShapes=_this.outputs.map(function(x2){return x2.shape});var nodesDepths={};var nodeIDToNode={};var layersDepths={};var layerIDToLayer={};var layerIndices={};var nodesInDecreasingDepth=[];var buildMapOfGraph=function(tensor,finishedNodes2,nodesInProgress2,layer2,nodeIndex2,tensorIndex2){if(layer2==null||nodeIndex2==null||tensorIndex2==null){layer2=tensor.sourceLayer;nodeIndex2=tensor.nodeIndex;tensorIndex2=tensor.tensorIndex}var node2=layer2.inboundNodes[nodeIndex2];if(nodesInProgress2.indexOf(node2)!==-1){throw new RuntimeError("The tensor "+tensor.name+' at layer "'+layer2.name+'" is part of a cycle.')}if(finishedNodes2.indexOf(node2)!==-1){return}_this.containerNodes.add(Container2.nodeKey(layer2,nodeIndex2));if(!(layer2.id in layerIndices)){layerIndices[layer2.id]=Object.keys(layerIndices).length}if(nodesInProgress2.indexOf(node2)===-1){nodesInProgress2.push(node2)}var numInboundLayers=node2.inboundLayers.length;for(var i2=0;i2=0){nodesInProgress2.splice(nodesInProgress2.indexOf(node2),1)}nodesInDecreasingDepth.push(node2)};var finishedNodes=[];var nodesInProgress=[];for(var _f=0,_g=_this.outputs;_f<_g.length;_f++){var x=_g[_f];buildMapOfGraph(x,finishedNodes,nodesInProgress)}var reversedNodesInDecreasingDepth=nodesInDecreasingDepth.slice().reverse();for(var _h=0,reversedNodesInDecreasingDepth_1=reversedNodesInDecreasingDepth;_hbIndex){return 1}return 0});for(var _k=0,layersForDepth_1=layersForDepth;_k0){throw new ValueError("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[]}var weights=[];for(var _i=0,_a=this.layers;_i<_a.length;_i++){var layer=_a[_i];weights=weights.concat(layer.trainableWeights)}return weights},enumerable:true,configurable:true});Object.defineProperty(Container2.prototype,"nonTrainableWeights",{get:function(){var weights=[];for(var _i=0,_a=this.layers;_i<_a.length;_i++){var layer=_a[_i];weights.push.apply(weights,layer.nonTrainableWeights)}if(!this.trainable){var trainableWeights=[];for(var _b=0,_c=this.layers;_b<_c.length;_b++){var layer=_c[_b];trainableWeights.push.apply(trainableWeights,layer.trainableWeights)}return trainableWeights.concat(weights)}return weights},enumerable:true,configurable:true});Object.defineProperty(Container2.prototype,"weights",{get:function(){return this.trainableWeights.concat(this.nonTrainableWeights)},enumerable:true,configurable:true});Container2.prototype.loadWeights=function(weights,strict){if(strict===void 0){strict=true}var nameToWeight={};var totalWeightsCount=0;for(var _i=0,_a=this.layers;_i<_a.length;_i++){var layer=_a[_i];for(var _b=0,_c=layer.weights;_b<_c.length;_b++){var weight=_c[_b];if(nameToWeight[weight.originalName]!=null){throw new ValueError("Duplicate weight name: "+weight.originalName)}nameToWeight[weight.originalName]=weight;totalWeightsCount++}}var weightValueTuples=[];for(var name_2 in weights){var validatedName=name_2;if(nameToWeight[name_2]==null){var tokens=name_2.split("/");var shortenNameArray=tokens.slice(0,-2).concat([tokens[tokens.length-1]]);validatedName=shortenNameArray.join("/")}if(nameToWeight[validatedName]!=null){weightValueTuples.push([nameToWeight[validatedName],weights[name_2]])}else if(strict){throw new ValueError("Provided weight data has no target variable: "+name_2)}delete nameToWeight[validatedName]}if(strict){var unsetNames=[];for(var name_3 in nameToWeight){unsetNames.push(name_3)}if(unsetNames.length>0){throw new ValueError(unsetNames.length+" of "+totalWeightsCount+" weights are not set: "+(""+unsetNames))}}batchSetValue(weightValueTuples)};Container2.prototype.updatedConfig=function(){var theConfig=this.getConfig();var modelConfig={};modelConfig["className"]=this.getClassName();modelConfig["config"]=theConfig;modelConfig["kerasVersion"]="tfjs-layers "+version5;modelConfig["backend"]="TensorFlow.js";return modelConfig};Container2.prototype.toJSON=function(unused,returnString){if(returnString===void 0){returnString=true}var modelConfig=convertTsToPythonic(this.updatedConfig());return returnString?JSON.stringify(modelConfig):modelConfig};Container2.prototype.call=function(inputs,kwargs){var _this=this;return tfc.tidy(function(){inputs=toList(inputs);var feedDict=new FeedDict;for(var i=0;i<_this.inputs.length;++i){feedDict.add(_this.inputs[i],inputs[i])}return execute(_this.outputs,feedDict,kwargs)})};Container2.prototype.computeMask=function(inputs,mask){var _this=this;return tfc.tidy(function(){inputs=toList(inputs);var masks;if(mask==null){masks=pyListRepeat(null,inputs.length)}else{masks=toList(mask)}return _this.runInternalGraph(inputs,masks)[1]})};Container2.prototype.computeOutputShape=function(inputShape){var inputShapes=normalizeShapeList(inputShape);if(inputShapes.length!==this.inputLayers.length){throw new ValueError("Invalid inputShape argument "+inputShape+": "+("model has "+this.inputLayers.length+" tensor inputs."))}var layersToOutputShapes={};for(var i=0;i1){for(var _i=0,depthKeys_3=depthKeys;_i0){var nodeData=[];for(var i=0;i0){layer2.apply(singletonOrArray(inputTensors2),kwargs)}}function processLayer(layerData2){var layerName2=layerData2["name"];var layer2=deserialize(layerData2,config2["customObjects"]!=null?config2["customObjects"]:{});layer2.setFastWeightInitDuringBuild(fastWeightInit);createdLayers[layerName2]=layer2;var inboundNodesData=layerData2["inboundNodes"];inboundNodesData.forEach(function(nodeData2){if(!(nodeData2 instanceof Array)){throw new ValueError("Corrupted configuration, expected array for nodeData: "+nodeData2)}addUnprocessedNode(layer2,nodeData2)})}var name=config2["name"];var layersFromConfig=config2["layers"];for(var _i=0,layersFromConfig_1=layersFromConfig;_i0&&typeof xWeight[Object.keys(xWeight)[0]]==="object"){var output_1=[];outputNames.forEach(function(outputName){if(outputName in xWeight){output_1.push(xWeight[outputName])}else{output_1.push(null)}});return output_1}else{throw new Error("The model has multiple ("+numOutputs+") outputs, "+("so "+weightType+" must be either an array with ")+(numOutputs+" elements or an object with "+outputNames+" keys. ")+("Provided "+weightType+" not understood: "+JSON.stringify(xWeight)))}}function standardizeClassWeights(classWeight,outputNames){return standardizeSampleOrClassWeights(classWeight,outputNames,"classWeight")}function standardizeWeights(y,sampleWeight,classWeight,sampleWeightMode){return __awaiter(this,void 0,void 0,function(){var yClasses,yClassIndices,_a,_b,classSampleWeight_1;return __generator(this,function(_c){switch(_c.label){case 0:if(sampleWeight!=null||sampleWeightMode!=null){throw new Error("Support sampleWeight is not implemented yet")}if(!(classWeight!=null))return[3,2];yClasses=tfc.tidy(function(){if(y.shape.length===1){return y.clone()}else if(y.shape.length===2){if(y.shape[1]>1){var axis=1;return y.argMax(axis)}else if(y.shape[1]===1){return y.reshape([y.shape[0]])}else{throw new Error("Encountered unexpected last-dimension size ("+y.shape[1]+") during handling of class weights. The size is expected to be >= 1.")}}else{throw new Error("Unexpected rank of target (y) tensor ("+y.rank+") during handling of class weights. The rank is expected to be 1 or 2.")}});_b=(_a=Array).from;return[4,yClasses.data()];case 1:yClassIndices=_b.apply(_a,[_c.sent()]);tfc.dispose(yClasses);classSampleWeight_1=[];yClassIndices.forEach(function(classIndex){if(classWeight[classIndex]==null){throw new Error("classWeight must contain all classes in the training data. "+("The class "+classIndex+" exists in the data but not in ")+"classWeight")}else{classSampleWeight_1.push(classWeight[classIndex])}});return[2,tfc.tensor1d(classSampleWeight_1,"float32")];case 2:return[2,null]}})})}function computeWeightedLoss(losses,sampleWeights){return tfc.mul(losses,sampleWeights)}var DEFAULT_VALIDATION_BATCH_SIZE=32;function standardizeDataIteratorOutput(model2,iteratorOut){var xs;var ys;var iteratorOutObj=iteratorOut;xs=iteratorOutObj["xs"];ys=iteratorOutObj["ys"];tfc.util.assert(xs!=null&&ys!=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 "+(""+iteratorOut)});var flattenedXs=flattenTensorOrArrayOrMap("input",model2.inputNames,xs);var flattenedYs=flattenTensorOrArrayOrMap("output",model2.outputNames,ys);var batchSize=flattenedXs[0].shape[0];tfc.util.assert(flattenedXs.length===model2.inputs.length,function(){return"LayersModel has "+model2.inputs.length+" inputs, but the dataset "+("provides "+flattenedXs.length+" inputs. (Expected input keys: ")+(JSON.stringify(model2.inputNames)+")")});tfc.util.assert(flattenedYs.length===model2.outputs.length,function(){return"LayersModel has "+model2.outputs.length+" outputs, but the dataset "+("provides "+flattenedYs.length+" outputs. (Expected output keys: ")+(JSON.stringify(model2.outputNames)+")")});var _loop_1=function(xIndex2){tfc.util.assert(flattenedXs[xIndex2].shape[0]===batchSize,function(){return"Batch size mismatch: input "+(model2.inputNames[xIndex2]+" has "+flattenedXs[xIndex2].shape[0]+"; ")+("expected "+batchSize+" based on input "+model2.inputNames[0]+".")})};for(var xIndex=0;xIndex0&&Number.isInteger(args.epochs),function(){return"For fitDataset(), config.epochs is expected to be a positive "+("integer, but got "+args.epochs)});tfc.util.assert(!hasBatchesPerEpoch||args.batchesPerEpoch>0&&Number.isInteger(args.batchesPerEpoch),function(){return"For fitDataset(), config.batchesPerEpoch is expected to be a "+("positive integer if specified, but got "+args.batchesPerEpoch)});tfc.util.assert(args["validationSplit"]==null,function(){return"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."});if(model2.isTraining){throw new Error("Cannot start training because another fit() call is ongoing.")}model2.isTraining=true;_f.label=1;case 1:_f.trys.push([1,,26,27]);doValidation=args.validationData!=null;valXs=void 0;valYs=void 0;if(doValidation){if(isDatasetObject(args.validationData)){tfc.util.assert(args.validationBatches==null||args.validationBatches>0&&Number.isInteger(args.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 "+args.validationBatches)})}else{validationData=standardizeTensorValidationData(args.validationData);valXs=validationData.xs;valYs=validationData.ys}}trainFunction=model2.makeTrainFunction();outLabels=model2.getDedupedMetricsNames();callbackMetrics=void 0;if(doValidation){callbackMetrics=outLabels.slice().concat(outLabels.map(function(n){return"val_"+n}))}else{callbackMetrics=outLabels.slice()}callbacks2=standardizeCallbacks(args.callbacks,args.yieldEvery);verbose=args.verbose==null?1:args.verbose;_a=configureCallbacks(callbacks2,verbose,args.epochs,null,null,getStepsPerEpoch(dataset,args),null,doValidation,callbackMetrics),callbackList=_a.callbackList,history_1=_a.history;callbackList.setModel(model2);model2.history=history_1;return[4,callbackList.onTrainBegin()];case 2:_f.sent();model2.stopTraining_=false;epoch=args.initialEpoch==null?0:args.initialEpoch;return[4,dataset.iterator()];case 3:dataIterator=_f.sent();_f.label=4;case 4:if(!(epoch=args.batchesPerEpoch:iteratorOut.done))return[3,20];if(!doValidation)return[3,19];valOuts=void 0;if(!isDatasetObject(args.validationData))return[3,17];_e=toList;return[4,model2.evaluateDataset(args.validationData,{batches:args.validationBatches})];case 16:valOuts=_e.apply(void 0,[_f.sent()]);return[3,18];case 17:valOuts=toList(model2.evaluate(valXs,valYs,{batchSize:args.validationBatchSize==null?DEFAULT_VALIDATION_BATCH_SIZE:args.validationBatchSize,verbose:0}));_f.label=18;case 18:for(i=0;i0){throw new NotImplementedError("Verbose mode is not implemented yet.")}tfc.util.assert(!hasBatches||args.batches>0&&Number.isInteger(args.batches),function(){return"Test loop expects `batches` to be a positive integer, but "+("received "+JSON.stringify(args.batches))});if(!isLazyIteratorObject(dataset))return[3,1];_a=dataset;return[3,3];case 1:return[4,dataset.iterator()];case 2:_a=_b.sent();_b.label=3;case 3:dataIterator=_a;numExamples=0;batch=0;_loop_3=function(){var iteratorOut;return __generator(this,function(_a2){switch(_a2.label){case 0:return[4,dataIterator.next()];case 1:iteratorOut=_a2.sent();outs=tfc.tidy(function(){if(iteratorOut.value){var _a3=standardizeDataIteratorOutput(model2,iteratorOut.value),xs=_a3.xs,ys=_a3.ys;var xsAndYs_1=xs.concat(ys);var batchOuts=tfc.tidy(function(){return f(xsAndYs_1)});tfc.dispose(xsAndYs_1);if(batch===0){for(var i2=0;i20){tfc.dispose(oldScalar2)}};for(var i2=0;i20&&Number.isInteger(batchSize),function(){return"batchSize is required to be a positive integer, but got "+batchSize})}function sliceArrays(arrays,start,stop){if(arrays==null){return[null]}else if(Array.isArray(arrays)){return arrays.map(function(array){return sliceAlongFirstAxis(array,start,stop-start)})}else{return sliceAlongFirstAxis(arrays,start,stop-start)}}function sliceArraysByIndices(arrays,indices){return tfc.tidy(function(){if(arrays==null){return null}else if(Array.isArray(arrays)){return arrays.map(function(array){return sliceArraysByIndices(array,indices)})}else{return gather(arrays,indices.dtype==="int32"?indices:indices.toInt())}})}function makeBatches(size,batchSize){var output=[];var batchStart=0;var batchEnd=null;while(batchStart=size){batchEnd=size}output.push([batchStart,batchEnd]);batchStart=batchEnd}return output}function fitLoop(model2,f,ins,outLabels,batchSize,epochs,verbose,callbacks2,valF,valIns,shuffle,callbackMetrics,initialEpoch,stepsPerEpoch,validationSteps){return __awaiter(this,void 0,void 0,function(){var doValidation,numTrainSamples,indexArray,_a,callbackList,history,_loop_1,epoch,state_1;return __generator(this,function(_b){switch(_b.label){case 0:if(batchSize==null){batchSize=32}if(epochs==null){epochs=1}if(shuffle==null){shuffle=true}if(initialEpoch==null){initialEpoch=0}doValidation=false;if(valF!=null&&valIns!=null){doValidation=true}if(validationSteps!=null){doValidation=true;if(stepsPerEpoch==null){throw new ValueError("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.")}}numTrainSamples=model2.checkNumSamples(ins,batchSize,stepsPerEpoch,"steps_per_epoch");if(numTrainSamples!=null){indexArray=range(0,numTrainSamples)}if(verbose==null){verbose=1}_a=configureCallbacks(callbacks2,verbose,epochs,initialEpoch,numTrainSamples,stepsPerEpoch,batchSize,doValidation,callbackMetrics),callbackList=_a.callbackList,history=_a.history;callbackList.setModel(model2);model2.history=history;return[4,callbackList.onTrainBegin()];case 1:_b.sent();model2.stopTraining_=false;_loop_1=function(epoch2){var epochLogs,epochIndexArray1D_1,batches_1,_loop_2,batchIndex,state_2;return __generator(this,function(_a2){switch(_a2.label){case 0:return[4,callbackList.onEpochBegin(epoch2)];case 1:_a2.sent();epochLogs={};if(!(stepsPerEpoch!=null))return[3,2];throw new NotImplementedError("stepsPerEpoch mode is not implemented yet.");case 2:if(shuffle==="batch"){throw new NotImplementedError("batch shuffling is not implemneted yet")}else if(shuffle){tfc.util.shuffle(indexArray)}epochIndexArray1D_1=tfc.tensor1d(indexArray);batches_1=makeBatches(numTrainSamples,batchSize);_loop_2=function(batchIndex2){var batchLogs;return __generator(this,function(_a3){switch(_a3.label){case 0:batchLogs={};return[4,callbackList.onBatchBegin(batchIndex2,batchLogs)];case 1:_a3.sent();tfc.tidy(function(){var batchStart=batches_1[batchIndex2][0];var batchEnd=batches_1[batchIndex2][1];var batchIds=sliceAlongFirstAxis(epochIndexArray1D_1,batchStart,batchEnd-batchStart);batchLogs["batch"]=batchIndex2;batchLogs["size"]=batchEnd-batchStart;var insBatch=sliceArraysByIndices(ins,batchIds);var outs=f(insBatch);for(var i=0;i0))return[3,4];doValidation=true;if(args.validationData.length===2){inputValX=args.validationData[0];inputValY=args.validationData[1]}else if(args.validationData.length===3){throw new NotImplementedError("validationData including sample weights is not supported yet.")}else{throw new ValueError("When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; "+(args.validationData+" is invalid."))}checkBatchAxis_1=true;return[4,model2.standardizeUserData(inputValX,inputValY,null,null,checkBatchAxis_1,batchSize)];case 3:valStandardized=_a.sent();valX=valStandardized[0];valY=valStandardized[1];valIns=valX.concat(valY);return[3,5];case 4:if(args.validationSplit!=null&&args.validationSplit>0&&args.validationSplit<1){doValidation=true;splitAt=Math.floor(inputs[0].shape[0]*(1-args.validationSplit));originalBatchSize=inputs[0].shape[0];valX=sliceArrays(inputs,splitAt,originalBatchSize);inputs=sliceArrays(inputs,0,splitAt);valY=sliceArrays(targets,splitAt,originalBatchSize);targets=sliceArrays(targets,0,splitAt);valIns=valX.concat(valY)}else if(args.validationSteps!=null){doValidation=true}_a.label=5;case 5:ins=inputs.concat(targets).concat(sampleWeights);model2.checkTrainableWeightsConsistency();trainFunction=model2.makeTrainFunction();outLabels=model2.getDedupedMetricsNames();valFunction=void 0;callbackMetrics=void 0;if(doValidation){model2.makeTestFunction();valFunction=model2.testFunction;callbackMetrics=outLabels.slice().concat(outLabels.map(function(n){return"val_"+n}))}else{valFunction=null;valIns=[];callbackMetrics=outLabels.slice()}callbacks2=standardizeCallbacks(args.callbacks,args.yieldEvery);return[4,fitLoop(model2,trainFunction,ins,outLabels,batchSize,args.epochs,args.verbose,callbacks2,valFunction,valIns,args.shuffle,callbackMetrics,args.initialEpoch,null,null)];case 6:out=_a.sent();return[2,out];case 7:model2.isTraining=false;disposeNewTensors(inputs,x);disposeNewTensors(targets,y);disposeNewTensors(valX,inputValX);disposeNewTensors(valY,inputValY);if(sampleWeights!=null){tfc.dispose(sampleWeights)}return[7];case 8:return[2]}})})}function ensureTensorsRank2OrHigher(tensors){var outs=[];if(tensors instanceof tfc.Tensor){tensors=[tensors]}for(var i=0;i0){gotUnexpectedData=true}else if(isDataDict(data2)){for(var key in data2){if(data2.hasOwnProperty(key)){gotUnexpectedData=true;break}}}else{gotUnexpectedData=true}if(gotUnexpectedData){throw new ValueError("Error when checking model "+exceptionPrefix+" expected no data, "+("but got "+data2))}}return[]}if(data2==null){return names.map(function(name){return null})}var arrays;if(isDataDict(data2)){data2=data2;arrays=[];for(var _i=0,names_1=names;_i1){throw new ValueError("The model "+exceptionPrefix+" expects "+names.length+" Tensor(s), "+("but only received one Tensor. Found: Tensor with shape "+data2.shape))}arrays=[data2]}arrays=ensureTensorsRank2OrHigher(arrays);if(shapes!=null){for(var i=0;i=0&&dim!==refDim){throw new ValueError("Error when checking "+exceptionPrefix+": expected "+names[i]+" "+("to have shape ["+shapes[i]+"], but got array with shape ")+("["+array.shape+"]."))}}}}return arrays}function checkArrayLengths(inputs,targets,weights){var setX=unique(inputs.map(function(input2){return input2.shape[0]}));setX.sort();var setY=unique(targets.map(function(target){return target.shape[0]}));setY.sort();if(setX.length>1){throw new ValueError("All input Tensors (x) should have the same number of samples. Got array shapes: "+(""+JSON.stringify(inputs.map(function(input2){return input2.shape}))))}if(setY.length>1){throw new ValueError("All target Tensors (y) should have the same number of samples. Got array shapes: "+(""+JSON.stringify(targets.map(function(target){return target.shape}))))}if(setX.length>0&&setY.length>0&&!tfc.util.arraysEqual(setX,setY)){throw new ValueError("Input Tensors should have the same number of samples as target "+("Tensors. Found "+setX[0]+" input sample(s) and "+setY[0]+" target ")+"sample(s).")}}function checkLossAndTargetCompatibility(targets,lossFns,outputShapes){var keyLosses=[meanSquaredError,binaryCrossentropy,categoricalCrossentropy];for(var i=0;i1){throw new ValueError("The model expects "+names.length+" "+exceptionPrefix+" Tensors, but only received one Tensor. Found: array with shape "+(JSON.stringify(data2.shape)+"."))}arrays=[data2]}if(shapes!=null){for(var i=0;i1){_this.metricsTensors.push([weightedLoss,i2]);_this.metricsNames.push(_this.outputNames[i2]+"_loss")}}});var nestedMetrics=collectMetrics(args.metrics,this.outputNames);var appendMetric=function(outputIndex,metricName,metricTensor){if(_this.outputNames.length>1){metricName=_this.outputNames[outputIndex]+"_"+metricName}_this.metricsNames.push(metricName);_this.metricsTensors.push([metricTensor,outputIndex])};nameScope("metric",function(){var _loop_1=function(i3){if(skipTargetIndices.indexOf(i3)!==-1){return"continue"}var outputMetrics=nestedMetrics[i3];var handleMetrics=function(metrics){var metricNamePrefix="";var metricName;var accFn;var weightedMetricFn;var _loop_2=function(metric2){if(typeof metric2==="string"&&["accuracy","acc","crossentropy","ce"].indexOf(metric2)!==-1){var outputShape=_this.internalOutputShapes[i3];if(outputShape[outputShape.length-1]===1||_this.lossFunctions[i3]===binaryCrossentropy){if(["accuracy","acc"].indexOf(metric2)!==-1){accFn=binaryAccuracy}else if(["crossentropy","ce"].indexOf(metric2)!==-1){accFn=binaryCrossentropy$1}}else if(_this.lossFunctions[i3]===sparseCategoricalCrossentropy){if(["accuracy","acc"].indexOf(metric2)!==-1){accFn=sparseCategoricalAccuracy}else if(["crossentropy","ce"].indexOf(metric2)!==-1){accFn=sparseCategoricalCrossentropy$1}}else{if(["accuracy","acc"].indexOf(metric2)!==-1){accFn=categoricalAccuracy}else if(["crossentropy","ce"].indexOf(metric2)!==-1){accFn=categoricalCrossentropy$1}}var suffix=void 0;if(["accuracy","acc"].indexOf(metric2)!==-1){suffix="acc"}else if(["crossentropy","ce"].indexOf(metric2)!==-1){suffix="ce"}weightedMetricFn=accFn;metricName=metricNamePrefix+suffix}else{var metricFn=get$1(metric2);weightedMetricFn=metricFn;metricName=metricNamePrefix+getLossOrMetricName(metric2)}var metricResult;nameScope(metricName,function(){metricResult=weightedMetricFn});appendMetric(i3,metricName,metricResult)};for(var _i2=0,metrics_1=metrics;_i20){var remainingNames_1=[];outputSymbolicTensors.forEach(function(tensor,i2){if(tensor==null){remainingNames_1.push(symbolicTensorNames[i2])}});throw new ValueError("Cannot find SymbolicTensors for output name(s): "+(""+JSON.stringify(remainingNames_1)))}return outputSymbolicTensors};LayersModel2.prototype.predictLoop=function(ins,batchSize,verbose){var _this=this;if(batchSize===void 0){batchSize=32}if(verbose===void 0){verbose=false}return tfc.tidy(function(){var numSamples=_this.checkNumSamples(ins);if(verbose){throw new NotImplementedError("Verbose predictLoop() is not implemented yet.")}var batches=makeBatches(numSamples,batchSize);var outsBatches=_this.outputs.map(function(output){return[]});var _loop_3=function(batchIndex2){var batchOuts=tfc.tidy(function(){var batchStart=batches[batchIndex2][0];var batchEnd=batches[batchIndex2][1];var insBatch=sliceArrays(ins,batchStart,batchEnd);var feeds=[];if(Array.isArray(insBatch)){for(var i=0;i0){if(x[0].shape[0]%batchSize!==0){throw new ValueError("In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size "+(batchSize+". Found: "+x[0].shape[0]+" sample(s)."))}}return[x,y]};LayersModel2.prototype.standardizeUserData=function(x,y,sampleWeight,classWeight,checkBatchAxis,batchSize){if(checkBatchAxis===void 0){checkBatchAxis=true}return __awaiter(this,void 0,void 0,function(){var _a,standardXs,standardYs,standardSampleWeights,classWeights,i,_b,_c;return __generator(this,function(_d){switch(_d.label){case 0:_a=this.standardizeUserDataXY(x,y,checkBatchAxis,batchSize),standardXs=_a[0],standardYs=_a[1];if(sampleWeight!=null){throw new Error("sample weight is not supported yet.")}standardSampleWeights=null;if(!(classWeight!=null))return[3,4];classWeights=standardizeClassWeights(classWeight,this.outputNames);standardSampleWeights=[];i=0;_d.label=1;case 1:if(!(i0){throw new NotImplementedError("Verbose mode is not implemented yet.")}if(steps!=null){throw new NotImplementedError("steps mode in testLoop() is not implemented yet")}else{var batches=makeBatches(numSamples,batchSize);var indexArray=tfc.tensor1d(range(0,numSamples));for(var batchIndex=0;batchIndex1){var dupIndex=count(outLabels.slice(0,i),label);newLabel+="_"+dupIndex}dedupedOutLabels.push(newLabel)}return dedupedOutLabels};LayersModel2.prototype.makeTrainFunction=function(){var _this=this;return function(data2){var lossValues=[];var inputs=data2.slice(0,_this.inputs.length);var targets=data2.slice(_this.inputs.length,_this.inputs.length+_this.outputs.length);var sampleWeights=data2.slice(_this.inputs.length+_this.outputs.length,_this.inputs.length+_this.outputs.length*2);var metricsValues=[];var totalLossFunction=function(){var feeds=[];for(var i=0;i<_this.inputs.length;++i){feeds.push({key:_this.inputs[i],value:inputs[i]})}var feedDict=new FeedDict(feeds);var outputs=execute(_this.outputs,feedDict,{training:true});var totalLoss;for(var i=0;i<_this.lossFunctions.length;++i){var lossFunction=_this.lossFunctions[i];var loss=lossFunction(targets[i],outputs[i]);if(sampleWeights[i]!=null){loss=computeWeightedLoss(loss,sampleWeights[i])}var meanLoss=tfc.mean(loss);lossValues.push(meanLoss);if(i===0){totalLoss=loss}else{totalLoss=tfc.add(totalLoss,loss)}}for(var i=0;i<_this.metricsTensors.length;++i){var weightedMetric=void 0;if(_this.outputs.length>1&&i<_this.outputs.length){weightedMetric=lossValues[i]}else{var metric=_this.metricsTensors[i][0];var outputIndex=_this.metricsTensors[i][1];weightedMetric=tfc.mean(metric(targets[outputIndex],outputs[outputIndex]))}tfc.keep(weightedMetric);metricsValues.push(weightedMetric)}totalLoss=tfc.mean(totalLoss);_this.calculateLosses().forEach(function(regularizerLoss){totalLoss=tfc.add(totalLoss,regularizerLoss)});return totalLoss};var variables=_this.collectedTrainableWeights.map(function(param){return param.read()});var returnCost=true;var totalLossValue=_this.optimizer_.minimize(totalLossFunction,returnCost,variables);return[totalLossValue].concat(metricsValues)}};LayersModel2.prototype.makeTestFunction=function(){var _this=this;this.testFunction=function(data2){return tfc.tidy(function(){var valOutputs=[];var totalLoss;var inputs=data2.slice(0,_this.inputs.length);var targets=data2.slice(_this.inputs.length,_this.inputs.length+_this.outputs.length);var feeds=[];for(var i=0;i<_this.inputs.length;++i){feeds.push({key:_this.inputs[i],value:inputs[i]})}var feedDict=new FeedDict(feeds);var outputs=execute(_this.outputs,feedDict);for(var i=0;i<_this.lossFunctions.length;++i){var lossFunction=_this.lossFunctions[i];var loss=tfc.mean(lossFunction(targets[i],outputs[i]));if(i===0){totalLoss=loss}else{totalLoss=tfc.add(totalLoss,loss)}valOutputs.push(totalLoss)}for(var i=0;i<_this.metricsTensors.length;++i){var metric=_this.metricsTensors[i][0];var outputIndex=_this.metricsTensors[i][1];var meanMetric=tfc.mean(metric(targets[outputIndex],outputs[outputIndex]));valOutputs.push(meanMetric)}return valOutputs})}};LayersModel2.prototype.fit=function(x,y,args){if(args===void 0){args={}}return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){return[2,fitTensors(this,x,y,args)]})})};LayersModel2.prototype.fitDataset=function(dataset,args){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){return[2,fitDataset(this,dataset,args)]})})};LayersModel2.prototype.trainOnBatch=function(x,y){return __awaiter(this,void 0,void 0,function(){var standardizeOut,inputs,targets,trainFunction,losses,lossValues,_i,losses_1,loss,v;return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.standardizeUserData(x,y)];case 1:standardizeOut=_a.sent();inputs=standardizeOut[0];targets=standardizeOut[1];trainFunction=this.makeTrainFunction();losses=trainFunction(inputs.concat(targets));lossValues=[];_i=0,losses_1=losses;_a.label=2;case 2:if(!(_i1){throw new ValueError("Found more than one ("+handlers.length+") save handlers for "+("URL '"+handlerOrURL+"'"))}handlerOrURL=handlers[0]}if(handlerOrURL.save==null){throw new ValueError("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.")}return[4,tfc.io.encodeWeights(this.getNamedWeights(config2))];case 1:weightDataAndSpecs=_e.sent();returnString=false;unusedArg=null;modelConfig=this.toJSON(unusedArg,returnString);modelArtifacts={modelTopology:modelConfig,format:LAYERS_MODEL_FORMAT_NAME,generatedBy:"TensorFlow.js tfjs-layers v"+version5,convertedBy:null};includeOptimizer=config2==null?false:config2.includeOptimizer;if(!(includeOptimizer&&this.optimizer!=null))return[3,4];modelArtifacts.trainingConfig=this.getTrainingConfig();weightType="optimizer";_c=(_b=tfc.io).encodeWeights;return[4,this.optimizer.getWeights()];case 2:return[4,_c.apply(_b,[_e.sent(),weightType])];case 3:_a=_e.sent(),optimizerWeightData=_a.data,optimizerWeightSpecs=_a.specs;(_d=weightDataAndSpecs.specs).push.apply(_d,optimizerWeightSpecs);weightDataAndSpecs.data=tfc.io.concatenateArrayBuffers([weightDataAndSpecs.data,optimizerWeightData]);_e.label=4;case 4:if(this.userDefinedMetadata!=null){checkSize=true;checkUserDefinedMetadata(this.userDefinedMetadata,this.name,checkSize);modelArtifacts.userDefinedMetadata=this.userDefinedMetadata}modelArtifacts.weightData=weightDataAndSpecs.data;modelArtifacts.weightSpecs=weightDataAndSpecs.specs;return[2,handlerOrURL.save(modelArtifacts)]}})})};LayersModel2.prototype.setUserDefinedMetadata=function(userDefinedMetadata){checkUserDefinedMetadata(userDefinedMetadata,this.name);this.userDefinedMetadata=userDefinedMetadata};LayersModel2.prototype.getUserDefinedMetadata=function(){return this.userDefinedMetadata};LayersModel2.className="Model";return LayersModel2}(Container);tfc.serialization.registerClass(LayersModel);var Functional=function(_super){__extends(Functional2,_super);function Functional2(){return _super!==null&&_super.apply(this,arguments)||this}Functional2.className="Functional";return Functional2}(LayersModel);tfc.serialization.registerClass(Functional);function modelFromJSON(modelAndWeightsConfig,customObjects){return __awaiter(this,void 0,void 0,function(){var modelTopology,tsConfig,model2,weightValues,uniqueWeightValues,_i,_a,weight;return __generator(this,function(_b){switch(_b.label){case 0:if(!("modelTopology"in modelAndWeightsConfig)){modelAndWeightsConfig={modelTopology:modelAndWeightsConfig}}modelAndWeightsConfig=modelAndWeightsConfig;modelTopology=modelAndWeightsConfig.modelTopology;if(modelTopology["model_config"]!=null){modelTopology=modelTopology["model_config"]}tsConfig=convertPythonicToTs(modelTopology);model2=deserialize(tsConfig,customObjects);if(!(modelAndWeightsConfig.weightsManifest!=null))return[3,2];return[4,tfc.io.loadWeights(modelAndWeightsConfig.weightsManifest,modelAndWeightsConfig.pathPrefix,model2.weights.map(function(weight2){return weight2.originalName}))];case 1:weightValues=_b.sent();uniqueWeightValues={};for(_i=0,_a=model2.weights;_i<_a.length;_i++){weight=_a[_i];uniqueWeightValues[weight.originalName]=weightValues[weight.originalName]}model2.loadWeights(uniqueWeightValues);tfc.dispose(weightValues);_b.label=2;case 2:return[2,model2]}})})}function loadLayersModelInternal(pathOrIOHandler,options){return __awaiter(this,void 0,void 0,function(){var handlers;return __generator(this,function(_a){if(options==null){options={}}if(typeof pathOrIOHandler==="string"){handlers=tfc.io.getLoadHandlers(pathOrIOHandler,options);if(handlers.length===0){handlers.push(tfc.io.browserHTTPRequest(pathOrIOHandler,options))}else if(handlers.length>1){throw new ValueError("Found more than one ("+handlers.length+") load handlers for "+("URL '"+pathOrIOHandler+"'"))}pathOrIOHandler=handlers[0]}return[2,loadLayersModelFromIOHandler(pathOrIOHandler,void 0,options)]})})}function loadLayersModelFromIOHandler(handler,customObjects,options){return __awaiter(this,void 0,void 0,function(){var artifacts,modelTopology,strict,fastWeightInit,model2,trainingConfig,_a,modelWeights,optimizerWeights;return __generator(this,function(_b){switch(_b.label){case 0:if(options==null){options={}}if(handler.load==null){throw new ValueError("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.")}return[4,handler.load()];case 1:artifacts=_b.sent();modelTopology=artifacts.modelTopology;if(modelTopology["model_config"]!=null){modelTopology=modelTopology["model_config"]}strict=options.strict==null?true:options.strict;fastWeightInit=artifacts.weightData!=null&&artifacts.weightSpecs!=null&&strict;model2=deserialize(convertPythonicToTs(modelTopology),customObjects,fastWeightInit);trainingConfig=artifacts.trainingConfig;if(trainingConfig!=null){model2.loadTrainingConfig(trainingConfig)}if(artifacts.userDefinedMetadata!=null){model2.setUserDefinedMetadata(artifacts.userDefinedMetadata)}if(!(artifacts.weightData!=null))return[3,4];if(artifacts.weightSpecs==null){throw new ValueError("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.")}_a=decodeModelAndOptimizerWeights(artifacts.weightData,artifacts.weightSpecs),modelWeights=_a.modelWeights,optimizerWeights=_a.optimizerWeights;model2.loadWeights(modelWeights,strict);if(!(model2.optimizer!=null&&optimizerWeights.length>0))return[3,3];return[4,model2.optimizer.setWeights(optimizerWeights)];case 2:_b.sent();_b.label=3;case 3:tfc.dispose(modelWeights);tfc.dispose(optimizerWeights.map(function(w){return w.tensor}));_b.label=4;case 4:return[2,model2]}})})}function decodeModelAndOptimizerWeights(buffer2,specs){var name2Tensor=tfc.io.decodeWeights(buffer2,specs);var modelWeights={};var optimizerWeights=[];specs.forEach(function(spec){if(spec.group==="optimizer"){optimizerWeights.push({name:spec.name,tensor:name2Tensor[spec.name]})}else{modelWeights[spec.name]=name2Tensor[spec.name]}});return{modelWeights,optimizerWeights}}var Sequential=function(_super){__extends(Sequential2,_super);function Sequential2(args){var _this=_super.call(this,{inputs:[],outputs:[]})||this;args=args||{};_this.trainable=true;_this.built=false;_this.name=args.name!=null?args.name:getUid("sequential_");if(args.layers!=null){for(var _i=0,_a=args.layers;_i<_a.length;_i++){var layer=_a[_i];_this.add(layer)}}return _this}Sequential2.prototype.checkShape=function(layer){var shape=layer.inboundNodes[0].outputTensors[0].shape;if(shape.some(function(x){return x<0})){throw new ValueError("Negative dimension size caused by adding layer "+(layer.name+" with input shape [")+(layer.inboundNodes[0].inputTensors[0].shape+"]"))}};Sequential2.prototype.add=function(layer){var isLayerModelInstance=layer instanceof Sequential2||layer instanceof LayersModel;var modelLayer;if(isLayerModelInstance){modelLayer=layer;if(modelLayer.outputs.length!==1){throw new ValueError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.")}if(modelLayer.inputs.length!==1){throw new ValueError("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}}if(this.outputs.length===0){if(layer.inboundNodes.length===0){if(layer.batchInputShape==null){throw new ValueError("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.")}var x=Input({batchShape:layer.batchInputShape,dtype:layer.dtype,name:layer.name+"_input"});layer.apply(x)}if(isLayerModelInstance){this.outputs=modelLayer.outputs;this.inputs=modelLayer.inputs}else{if(layer.inboundNodes.length!==1){throw new ValueError("A layer added to a Sequential model must not already be "+("connected somewhere else. LayersModel received layer "+layer.name+" ")+("which has "+layer.inboundNodes.length+" pre-existing inbound ")+"connections.")}if(layer.inboundNodes[0].outputTensors.length!==1){throw new ValueError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.")}this.checkShape(layer);this.outputs=[layer.inboundNodes[0].outputTensors[0]];this.inputs=getSourceInputs(this.outputs[0])}this.inboundNodes=[];new Node({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:pyListRepeat(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(function(x2){return x2.shape}),outputShapes:this.outputs[0].shape})}else{var outputTensor=layer.apply(this.outputs[0]);if(Array.isArray(outputTensor)){throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.")}this.checkShape(layer);this.outputs=[outputTensor];this.inboundNodes[0].outputTensors=this.outputs;this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(layer);this.built=false};Sequential2.prototype.pop=function(){if(this.layers.length===0){throw new TypeError("There are no layers in the model.")}this.layers.pop();if(this.layers.length===0){this.outputs=[];this.inboundNodes=[];this.outboundNodes=[]}else{var lastLayerIndex=this.layers.length-1;this.layers[lastLayerIndex].outboundNodes=[];this.outputs=[this.layers[lastLayerIndex].output];this.inboundNodes[0].outputTensors=this.outputs;this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}};Sequential2.prototype.call=function(inputs,kwargs){if(this.model==null){this.build()}return this.model.call(inputs,kwargs)};Sequential2.prototype.build=function(inputShape){getExactlyOneShape(inputShape);if(this.inputs.length===0||this.outputs.length===0){throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.")}this.model=new LayersModel({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"});this.model.trainable=this.trainable;this.supportsMasking=this.model.supportsMasking;this.inputLayers=this.model.inputLayers;this.inputLayersNodeIndices=this.model.inputLayersNodeIndices;this.inputLayersTensorIndices=this.model.inputLayersTensorIndices;this.outputLayers=this.model.outputLayers;this.outputLayersNodeIndices=this.model.outputLayersNodeIndices;this.outputLayersTensorIndices=this.model.outputLayersTensorIndices;this.nodesByDepth=this.model.nodesByDepth;this.containerNodes=this.model.containerNodes;this.outputNames=this.model.outputNames;this.inputNames=this.model.inputNames;this.built=true};Sequential2.prototype.countParams=function(){if(!this.built){this.build()}return _super.prototype.countParams.call(this)};Sequential2.prototype.summary=function(lineLength,positions,printFn){if(printFn===void 0){printFn=console.log}if(!this.built){this.build()}_super.prototype.summary.call(this,lineLength,positions,printFn)};Sequential2.prototype.setWeights=function(weights){if(this.model==null){this.build()}this.model.setWeights(weights)};Sequential2.prototype.evaluate=function(x,y,args){if(args===void 0){args={}}if(!this.built){throw new RuntimeError("The model needs to be compiled before being used.")}return this.model.evaluate(x,y,args)};Sequential2.prototype.evaluateDataset=function(dataset,args){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){if(!this.built){throw new RuntimeError("The model needs to be compiled before being used.")}return[2,this.model.evaluateDataset(dataset,args)]})})};Sequential2.prototype.predict=function(x,args){if(args===void 0){args={}}if(this.model==null){this.build()}return this.model.predict(x,args)};Sequential2.prototype.predictOnBatch=function(x){if(this.model==null){this.build()}return this.model.predictOnBatch(x)};Sequential2.prototype.compile=function(args){this.build();this.model.compile(args);this.optimizer_=this.model.optimizer;this.isOptimizerOwned=this.model.isOptimizerOwned;this.loss=this.model.loss;this.metrics=this.model.metrics;this.metricsTensors=this.model.metricsTensors;this.metricsNames=this.model.metricsNames};Object.defineProperty(Sequential2.prototype,"optimizer",{get:function(){return this.model==null?void 0:this.model.optimizer},set:function(optimizer){this.model.optimizer=optimizer},enumerable:true,configurable:true});Sequential2.prototype.fit=function(x,y,args){if(args===void 0){args={}}return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){if(!this.built){throw new RuntimeError("The model needs to be compiled before being used.")}return[2,this.model.fit(x,y,args)]})})};Sequential2.prototype.fitDataset=function(dataset,args){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){if(!this.built){throw new RuntimeError("The model needs to be compiled before being used.")}return[2,this.model.fitDataset(dataset,args)]})})};Sequential2.prototype.trainOnBatch=function(x,y){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){return[2,this.model.trainOnBatch(x,y)]})})};Sequential2.fromConfig=function(cls,config2,customObjects,fastWeightInit){if(fastWeightInit===void 0){fastWeightInit=false}var configArray;var extraModelConfig={};if(config2 instanceof Array){if(!(config2[0].className!=null)||config2[0]["className"]==="Merge"){throw new ValueError("Legacy serialization format not supported yet.")}configArray=config2}else{tfc.util.assert(config2["layers"]!=null,function(){return"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field."});configArray=config2["layers"];delete config2["layers"];extraModelConfig=config2}var model2=new cls(extraModelConfig);if(!(model2 instanceof Sequential2)){throw new NotImplementedError("Sequential.fromConfig called on non-Sequential input: "+model2)}for(var _i=0,configArray_1=configArray;_i 0 "+("but got "+JSON.stringify(args.filters)))}};return Conv2}(BaseConv);var Conv2D3=function(_super){__extends(Conv2D4,_super);function Conv2D4(args){var _this=_super.call(this,2,args)||this;Conv2D4.verifyArgs(args);return _this}Conv2D4.prototype.getConfig=function(){var config2=_super.prototype.getConfig.call(this);delete config2["rank"];return config2};Conv2D4.verifyArgs=function(args){if(typeof args.kernelSize!=="number"&&!checkArrayTypeAndLength(args.kernelSize,"number",1,2)){throw new ValueError("Conv2D expects config.kernelSize to be number or number[] with "+("length 1 or 2, but received "+JSON.stringify(args.kernelSize)+"."))}};Conv2D4.className="Conv2D";return Conv2D4}(Conv);tfc.serialization.registerClass(Conv2D3);var Conv3D=function(_super){__extends(Conv3D2,_super);function Conv3D2(args){var _this=_super.call(this,3,args)||this;Conv3D2.verifyArgs(args);return _this}Conv3D2.prototype.getConfig=function(){var config2=_super.prototype.getConfig.call(this);delete config2["rank"];return config2};Conv3D2.verifyArgs=function(args){if(typeof args.kernelSize!=="number"){if(!(Array.isArray(args.kernelSize)&&(args.kernelSize.length===1||args.kernelSize.length===3))){throw new ValueError("Conv3D expects config.kernelSize to be number or"+(" [number, number, number], but received "+JSON.stringify(args.kernelSize)+"."))}}};Conv3D2.className="Conv3D";return Conv3D2}(Conv);tfc.serialization.registerClass(Conv3D);var Conv2DTranspose=function(_super){__extends(Conv2DTranspose2,_super);function Conv2DTranspose2(args){var _this=_super.call(this,args)||this;_this.inputSpec=[new InputSpec({ndim:4})];if(_this.padding!=="same"&&_this.padding!=="valid"){throw new ValueError("Conv2DTranspose currently supports only padding modes 'same' "+("and 'valid', but received padding mode "+_this.padding))}return _this}Conv2DTranspose2.prototype.build=function(inputShape){var _a;inputShape=getExactlyOneShape(inputShape);if(inputShape.length!==4){throw new ValueError("Input should have rank 4; Received input shape: "+JSON.stringify(inputShape))}var channelAxis=this.dataFormat==="channelsFirst"?1:inputShape.length-1;if(inputShape[channelAxis]==null){throw new ValueError("The channel dimension of the inputs should be defined. Found `None`.")}var inputDim=inputShape[channelAxis];var kernelShape=this.kernelSize.concat([this.filters,inputDim]);this.kernel=this.addWeight("kernel",kernelShape,"float32",this.kernelInitializer,this.kernelRegularizer,true,this.kernelConstraint);if(this.useBias){this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,true,this.biasConstraint)}this.inputSpec=[new InputSpec({ndim:4,axes:(_a={},_a[channelAxis]=inputDim,_a)})];this.built=true};Conv2DTranspose2.prototype.call=function(inputs,kwargs){var _this=this;return tfc.tidy(function(){var input2=getExactlyOneTensor(inputs);if(input2.shape.length!==4){throw new ValueError("Conv2DTranspose.call() expects input tensor to be rank-4, but "+("received a tensor of rank-"+input2.shape.length))}var inputShape=input2.shape;var batchSize=inputShape[0];var hAxis;var wAxis;if(_this.dataFormat==="channelsFirst"){hAxis=2;wAxis=3}else{hAxis=1;wAxis=2}var height=inputShape[hAxis];var width=inputShape[wAxis];var kernelH=_this.kernelSize[0];var kernelW=_this.kernelSize[1];var strideH=_this.strides[0];var strideW=_this.strides[1];var outHeight=deconvLength(height,strideH,kernelH,_this.padding);var outWidth=deconvLength(width,strideW,kernelW,_this.padding);var outputShape=[batchSize,outHeight,outWidth,_this.filters];if(_this.dataFormat!=="channelsLast"){input2=tfc.transpose(input2,[0,2,3,1])}var outputs=tfc.conv2dTranspose(input2,_this.kernel.read(),outputShape,_this.strides,_this.padding);if(_this.dataFormat!=="channelsLast"){outputs=tfc.transpose(outputs,[0,3,1,2])}if(_this.bias!=null){outputs=biasAdd(outputs,_this.bias.read(),_this.dataFormat)}if(_this.activation!=null){outputs=_this.activation.apply(outputs)}return outputs})};Conv2DTranspose2.prototype.computeOutputShape=function(inputShape){inputShape=getExactlyOneShape(inputShape);var outputShape=inputShape.slice();var channelAxis;var heightAxis;var widthAxis;if(this.dataFormat==="channelsFirst"){channelAxis=1;heightAxis=2;widthAxis=3}else{channelAxis=3;heightAxis=1;widthAxis=2}var kernelH=this.kernelSize[0];var kernelW=this.kernelSize[1];var strideH=this.strides[0];var strideW=this.strides[1];outputShape[channelAxis]=this.filters;outputShape[heightAxis]=deconvLength(outputShape[heightAxis],strideH,kernelH,this.padding);outputShape[widthAxis]=deconvLength(outputShape[widthAxis],strideW,kernelW,this.padding);return outputShape};Conv2DTranspose2.prototype.getConfig=function(){var config2=_super.prototype.getConfig.call(this);delete config2["dilationRate"];return config2};Conv2DTranspose2.className="Conv2DTranspose";return Conv2DTranspose2}(Conv2D3);tfc.serialization.registerClass(Conv2DTranspose);var SeparableConv=function(_super){__extends(SeparableConv2,_super);function SeparableConv2(rank,config2){var _this=_super.call(this,rank,config2)||this;_this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform";_this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform";_this.depthwiseKernel=null;_this.pointwiseKernel=null;if(config2.filters==null){throw new ValueError("The `filters` configuration field is required by SeparableConv, but is unspecified.")}if(config2.kernelInitializer!=null||config2.kernelRegularizer!=null||config2.kernelConstraint!=null){throw new ValueError("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.")}if(config2.padding!=null&&config2.padding!=="same"&&config2.padding!=="valid"){throw new ValueError("SeparableConv"+_this.rank+"D supports only padding modes: "+("'same' and 'valid', but received "+JSON.stringify(config2.padding)))}_this.depthMultiplier=config2.depthMultiplier==null?1:config2.depthMultiplier;_this.depthwiseInitializer=getInitializer(config2.depthwiseInitializer||_this.DEFAULT_DEPTHWISE_INITIALIZER);_this.depthwiseRegularizer=getRegularizer(config2.depthwiseRegularizer);_this.depthwiseConstraint=getConstraint(config2.depthwiseConstraint);_this.pointwiseInitializer=getInitializer(config2.depthwiseInitializer||_this.DEFAULT_POINTWISE_INITIALIZER);_this.pointwiseRegularizer=getRegularizer(config2.pointwiseRegularizer);_this.pointwiseConstraint=getConstraint(config2.pointwiseConstraint);return _this}SeparableConv2.prototype.build=function(inputShape){var _a;inputShape=getExactlyOneShape(inputShape);if(inputShape.length1){initialState=inputs.slice(1,inputs.length)}inputs=inputs[0]}function toListOrNull(x){if(x==null||Array.isArray(x)){return x}else{return[x]}}initialState=toListOrNull(initialState);constants=toListOrNull(constants);return{inputs,initialState,constants}}function rnn(stepFunction,inputs,initialStates,goBackwards,mask,constants,unroll,needPerStepOutputs){if(goBackwards===void 0){goBackwards=false}if(unroll===void 0){unroll=false}if(needPerStepOutputs===void 0){needPerStepOutputs=false}return tfc.tidy(function(){var ndim=inputs.shape.length;if(ndim<3){throw new ValueError("Input should be at least 3D, but is "+ndim+"D.")}var axes=[1,0].concat(range(2,ndim));inputs=tfc.transpose(inputs,axes);if(constants!=null){throw new NotImplementedError("The rnn() functoin of the deeplearn.js backend does not support constants yet.")}if(unroll){console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend.")}if(mask!=null){mask=mask.asType("bool").asType("float32");if(mask.rank===ndim-1){mask=tfc.expandDims(mask,-1)}mask=tfc.transpose(mask,axes)}if(goBackwards){inputs=tfc.reverse(inputs,0);if(mask!=null){mask=tfc.reverse(mask,0)}}var perStepOutputs=[];var lastOutput;var states=initialStates;var timeSteps=inputs.shape[0];var perStepInputs=tfc.unstack(inputs);var perStepMasks;if(mask!=null){perStepMasks=tfc.unstack(mask)}var _loop_1=function(t2){var currentInput=perStepInputs[t2];var stepOutputs=tfc.tidy(function(){return stepFunction(currentInput,states)});if(mask==null){lastOutput=stepOutputs[0];states=stepOutputs[1]}else{var maskedOutputs=tfc.tidy(function(){var stepMask=perStepMasks[t2];var negStepMask=tfc.onesLike(stepMask).sub(stepMask);var output=stepOutputs[0].mul(stepMask).add(states[0].mul(negStepMask));var newStates=states.map(function(state,i){return stepOutputs[1][i].mul(stepMask).add(state.mul(negStepMask))});return{output,newStates}});lastOutput=maskedOutputs.output;states=maskedOutputs.newStates}if(needPerStepOutputs){perStepOutputs.push(lastOutput)}};for(var t=0;t1?tile2(initialState,[1,dim]):initialState})}else{return _this.cell.stateSize>1?[tile2(initialState,[1,_this.cell.stateSize])]:[initialState]}})};Object.defineProperty(RNN2.prototype,"trainableWeights",{get:function(){if(!this.trainable){return[]}return this.cell.trainableWeights},enumerable:true,configurable:true});Object.defineProperty(RNN2.prototype,"nonTrainableWeights",{get:function(){if(!this.trainable){return this.cell.weights}return this.cell.nonTrainableWeights},enumerable:true,configurable:true});RNN2.prototype.setFastWeightInitDuringBuild=function(value){_super.prototype.setFastWeightInitDuringBuild.call(this,value);if(this.cell!=null){this.cell.setFastWeightInitDuringBuild(value)}};RNN2.prototype.getConfig=function(){var baseConfig=_super.prototype.getConfig.call(this);var config2={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};if(this.numConstants!=null){config2["numConstants"]=this.numConstants}var cellConfig=this.cell.getConfig();if(this.getClassName()===RNN2.className){config2["cell"]={className:this.cell.getClassName(),config:cellConfig}}return __assign({},cellConfig,baseConfig,config2)};RNN2.fromConfig=function(cls,config2,customObjects){if(customObjects===void 0){customObjects={}}var cellConfig=config2["cell"];var cell=deserialize(cellConfig,customObjects);return new cls(Object.assign(config2,{cell}))};RNN2.className="RNN";return RNN2}(Layer);tfc.serialization.registerClass(RNN);var RNNCell=function(_super){__extends(RNNCell2,_super);function RNNCell2(){return _super!==null&&_super.apply(this,arguments)||this}return RNNCell2}(Layer);var SimpleRNNCell=function(_super){__extends(SimpleRNNCell2,_super);function SimpleRNNCell2(args){var _this=_super.call(this,args)||this;_this.DEFAULT_ACTIVATION="tanh";_this.DEFAULT_KERNEL_INITIALIZER="glorotNormal";_this.DEFAULT_RECURRENT_INITIALIZER="orthogonal";_this.DEFAULT_BIAS_INITIALIZER="zeros";_this.units=args.units;assertPositiveInteger(_this.units,"units");_this.activation=getActivation(args.activation==null?_this.DEFAULT_ACTIVATION:args.activation);_this.useBias=args.useBias==null?true:args.useBias;_this.kernelInitializer=getInitializer(args.kernelInitializer||_this.DEFAULT_KERNEL_INITIALIZER);_this.recurrentInitializer=getInitializer(args.recurrentInitializer||_this.DEFAULT_RECURRENT_INITIALIZER);_this.biasInitializer=getInitializer(args.biasInitializer||_this.DEFAULT_BIAS_INITIALIZER);_this.kernelRegularizer=getRegularizer(args.kernelRegularizer);_this.recurrentRegularizer=getRegularizer(args.recurrentRegularizer);_this.biasRegularizer=getRegularizer(args.biasRegularizer);_this.kernelConstraint=getConstraint(args.kernelConstraint);_this.recurrentConstraint=getConstraint(args.recurrentConstraint);_this.biasConstraint=getConstraint(args.biasConstraint);_this.dropout=min2([1,max2([0,args.dropout==null?0:args.dropout])]);_this.recurrentDropout=min2([1,max2([0,args.recurrentDropout==null?0:args.recurrentDropout])]);_this.stateSize=_this.units;_this.dropoutMask=null;_this.recurrentDropoutMask=null;return _this}SimpleRNNCell2.prototype.build=function(inputShape){inputShape=getExactlyOneShape(inputShape);this.kernel=this.addWeight("kernel",[inputShape[inputShape.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,true,this.kernelConstraint);this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,true,this.recurrentConstraint);if(this.useBias){this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,true,this.biasConstraint)}else{this.bias=null}this.built=true};SimpleRNNCell2.prototype.call=function(inputs,kwargs){var _this=this;return tfc.tidy(function(){inputs=inputs;if(inputs.length!==2){throw new ValueError("SimpleRNNCell expects 2 input Tensors, got "+inputs.length+".")}var prevOutput=inputs[1];inputs=inputs[0];var training=kwargs["training"]==null?false:kwargs["training"];if(0<_this.dropout&&_this.dropout<1&&_this.dropoutMask==null){_this.dropoutMask=generateDropoutMask({ones:function(){return tfc.onesLike(inputs)},rate:_this.dropout,training})}if(0<_this.recurrentDropout&&_this.recurrentDropout<1&&_this.recurrentDropoutMask==null){_this.recurrentDropoutMask=generateDropoutMask({ones:function(){return tfc.onesLike(prevOutput)},rate:_this.recurrentDropout,training})}var h;var dpMask=_this.dropoutMask;var recDpMask=_this.recurrentDropoutMask;if(dpMask!=null){h=dot2(tfc.mul(inputs,dpMask),_this.kernel.read())}else{h=dot2(inputs,_this.kernel.read())}if(_this.bias!=null){h=biasAdd(h,_this.bias.read())}if(recDpMask!=null){prevOutput=tfc.mul(prevOutput,recDpMask)}var output=tfc.add(h,dot2(prevOutput,_this.recurrentKernel.read()));if(_this.activation!=null){output=_this.activation.apply(output)}return[output,output]})};SimpleRNNCell2.prototype.getConfig=function(){var baseConfig=_super.prototype.getConfig.call(this);var config2={units:this.units,activation:serializeActivation(this.activation),useBias:this.useBias,kernelInitializer:serializeInitializer(this.kernelInitializer),recurrentInitializer:serializeInitializer(this.recurrentInitializer),biasInitializer:serializeInitializer(this.biasInitializer),kernelRegularizer:serializeRegularizer(this.kernelRegularizer),recurrentRegularizer:serializeRegularizer(this.recurrentRegularizer),biasRegularizer:serializeRegularizer(this.biasRegularizer),activityRegularizer:serializeRegularizer(this.activityRegularizer),kernelConstraint:serializeConstraint(this.kernelConstraint),recurrentConstraint:serializeConstraint(this.recurrentConstraint),biasConstraint:serializeConstraint(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return __assign({},baseConfig,config2)};SimpleRNNCell2.className="SimpleRNNCell";return SimpleRNNCell2}(RNNCell);tfc.serialization.registerClass(SimpleRNNCell);var SimpleRNN=function(_super){__extends(SimpleRNN2,_super);function SimpleRNN2(args){var _this=this;args.cell=new SimpleRNNCell(args);_this=_super.call(this,args)||this;return _this}SimpleRNN2.prototype.call=function(inputs,kwargs){var _this=this;return tfc.tidy(function(){if(_this.cell.dropoutMask!=null){tfc.dispose(_this.cell.dropoutMask);_this.cell.dropoutMask=null}if(_this.cell.recurrentDropoutMask!=null){tfc.dispose(_this.cell.recurrentDropoutMask);_this.cell.recurrentDropoutMask=null}var mask=kwargs==null?null:kwargs["mask"];var training=kwargs==null?null:kwargs["training"];var initialState=kwargs==null?null:kwargs["initialState"];return _super.prototype.call.call(_this,inputs,{mask,training,initialState})})};SimpleRNN2.fromConfig=function(cls,config2){return new cls(config2)};SimpleRNN2.className="SimpleRNN";return SimpleRNN2}(RNN);tfc.serialization.registerClass(SimpleRNN);var GRUCell=function(_super){__extends(GRUCell2,_super);function GRUCell2(args){var _this=_super.call(this,args)||this;_this.DEFAULT_ACTIVATION="tanh";_this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid";_this.DEFAULT_KERNEL_INITIALIZER="glorotNormal";_this.DEFAULT_RECURRENT_INITIALIZER="orthogonal";_this.DEFAULT_BIAS_INITIALIZER="zeros";if(args.resetAfter){throw new ValueError("GRUCell does not support reset_after parameter set to true.")}_this.units=args.units;assertPositiveInteger(_this.units,"units");_this.activation=getActivation(args.activation===void 0?_this.DEFAULT_ACTIVATION:args.activation);_this.recurrentActivation=getActivation(args.recurrentActivation===void 0?_this.DEFAULT_RECURRENT_ACTIVATION:args.recurrentActivation);_this.useBias=args.useBias==null?true:args.useBias;_this.kernelInitializer=getInitializer(args.kernelInitializer||_this.DEFAULT_KERNEL_INITIALIZER);_this.recurrentInitializer=getInitializer(args.recurrentInitializer||_this.DEFAULT_RECURRENT_INITIALIZER);_this.biasInitializer=getInitializer(args.biasInitializer||_this.DEFAULT_BIAS_INITIALIZER);_this.kernelRegularizer=getRegularizer(args.kernelRegularizer);_this.recurrentRegularizer=getRegularizer(args.recurrentRegularizer);_this.biasRegularizer=getRegularizer(args.biasRegularizer);_this.kernelConstraint=getConstraint(args.kernelConstraint);_this.recurrentConstraint=getConstraint(args.recurrentConstraint);_this.biasConstraint=getConstraint(args.biasConstraint);_this.dropout=min2([1,max2([0,args.dropout==null?0:args.dropout])]);_this.recurrentDropout=min2([1,max2([0,args.recurrentDropout==null?0:args.recurrentDropout])]);_this.implementation=args.implementation;_this.stateSize=_this.units;_this.dropoutMask=null;_this.recurrentDropoutMask=null;return _this}GRUCell2.prototype.build=function(inputShape){inputShape=getExactlyOneShape(inputShape);var inputDim=inputShape[inputShape.length-1];this.kernel=this.addWeight("kernel",[inputDim,this.units*3],null,this.kernelInitializer,this.kernelRegularizer,true,this.kernelConstraint);this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*3],null,this.recurrentInitializer,this.recurrentRegularizer,true,this.recurrentConstraint);if(this.useBias){this.bias=this.addWeight("bias",[this.units*3],null,this.biasInitializer,this.biasRegularizer,true,this.biasConstraint)}else{this.bias=null}this.built=true};GRUCell2.prototype.call=function(inputs,kwargs){var _this=this;return tfc.tidy(function(){inputs=inputs;if(inputs.length!==2){throw new ValueError("GRUCell expects 2 input Tensors (inputs, h, c), got "+(inputs.length+"."))}var training=kwargs["training"]==null?false:kwargs["training"];var hTMinus1=inputs[1];inputs=inputs[0];if(0<_this.dropout&&_this.dropout<1&&_this.dropoutMask==null){_this.dropoutMask=generateDropoutMask({ones:function(){return tfc.onesLike(inputs)},rate:_this.dropout,training,count:3})}if(0<_this.recurrentDropout&&_this.recurrentDropout<1&&_this.recurrentDropoutMask==null){_this.recurrentDropoutMask=generateDropoutMask({ones:function(){return tfc.onesLike(hTMinus1)},rate:_this.recurrentDropout,training,count:3})}var dpMask=_this.dropoutMask;var recDpMask=_this.recurrentDropoutMask;var z;var r;var hh;if(0<_this.dropout&&_this.dropout<1){inputs=tfc.mul(inputs,dpMask[0])}var matrixX=dot2(inputs,_this.kernel.read());if(_this.useBias){matrixX=biasAdd(matrixX,_this.bias.read())}if(0<_this.recurrentDropout&&_this.recurrentDropout<1){hTMinus1=tfc.mul(hTMinus1,recDpMask[0])}var recurrentKernelValue=_this.recurrentKernel.read();var _a=tfc.split(recurrentKernelValue,[2*_this.units,_this.units],recurrentKernelValue.rank-1),rk1=_a[0],rk2=_a[1];var matrixInner=dot2(hTMinus1,rk1);var _b=tfc.split(matrixX,3,matrixX.rank-1),xZ=_b[0],xR=_b[1],xH=_b[2];var _c=tfc.split(matrixInner,2,matrixInner.rank-1),recurrentZ=_c[0],recurrentR=_c[1];z=_this.recurrentActivation.apply(tfc.add(xZ,recurrentZ));r=_this.recurrentActivation.apply(tfc.add(xR,recurrentR));var recurrentH=dot2(tfc.mul(r,hTMinus1),rk2);hh=_this.activation.apply(tfc.add(xH,recurrentH));var h=tfc.add(tfc.mul(z,hTMinus1),tfc.mul(tfc.add(1,tfc.neg(z)),hh));return[h,h]})};GRUCell2.prototype.getConfig=function(){var baseConfig=_super.prototype.getConfig.call(this);var config2={units:this.units,activation:serializeActivation(this.activation),recurrentActivation:serializeActivation(this.recurrentActivation),useBias:this.useBias,kernelInitializer:serializeInitializer(this.kernelInitializer),recurrentInitializer:serializeInitializer(this.recurrentInitializer),biasInitializer:serializeInitializer(this.biasInitializer),kernelRegularizer:serializeRegularizer(this.kernelRegularizer),recurrentRegularizer:serializeRegularizer(this.recurrentRegularizer),biasRegularizer:serializeRegularizer(this.biasRegularizer),activityRegularizer:serializeRegularizer(this.activityRegularizer),kernelConstraint:serializeConstraint(this.kernelConstraint),recurrentConstraint:serializeConstraint(this.recurrentConstraint),biasConstraint:serializeConstraint(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:false};return __assign({},baseConfig,config2)};GRUCell2.className="GRUCell";return GRUCell2}(RNNCell);tfc.serialization.registerClass(GRUCell);var GRU=function(_super){__extends(GRU2,_super);function GRU2(args){var _this=this;if(args.implementation===0){console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call.")}args.cell=new GRUCell(args);_this=_super.call(this,args)||this;return _this}GRU2.prototype.call=function(inputs,kwargs){var _this=this;return tfc.tidy(function(){if(_this.cell.dropoutMask!=null){tfc.dispose(_this.cell.dropoutMask);_this.cell.dropoutMask=null}if(_this.cell.recurrentDropoutMask!=null){tfc.dispose(_this.cell.recurrentDropoutMask);_this.cell.recurrentDropoutMask=null}var mask=kwargs==null?null:kwargs["mask"];var training=kwargs==null?null:kwargs["training"];var initialState=kwargs==null?null:kwargs["initialState"];return _super.prototype.call.call(_this,inputs,{mask,training,initialState})})};GRU2.fromConfig=function(cls,config2){if(config2["implmentation"]===0){config2["implementation"]=1}return new cls(config2)};GRU2.className="GRU";return GRU2}(RNN);tfc.serialization.registerClass(GRU);var LSTMCell=function(_super){__extends(LSTMCell2,_super);function LSTMCell2(args){var _this=_super.call(this,args)||this;_this.DEFAULT_ACTIVATION="tanh";_this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid";_this.DEFAULT_KERNEL_INITIALIZER="glorotNormal";_this.DEFAULT_RECURRENT_INITIALIZER="orthogonal";_this.DEFAULT_BIAS_INITIALIZER="zeros";_this.units=args.units;assertPositiveInteger(_this.units,"units");_this.activation=getActivation(args.activation===void 0?_this.DEFAULT_ACTIVATION:args.activation);_this.recurrentActivation=getActivation(args.recurrentActivation===void 0?_this.DEFAULT_RECURRENT_ACTIVATION:args.recurrentActivation);_this.useBias=args.useBias==null?true:args.useBias;_this.kernelInitializer=getInitializer(args.kernelInitializer||_this.DEFAULT_KERNEL_INITIALIZER);_this.recurrentInitializer=getInitializer(args.recurrentInitializer||_this.DEFAULT_RECURRENT_INITIALIZER);_this.biasInitializer=getInitializer(args.biasInitializer||_this.DEFAULT_BIAS_INITIALIZER);_this.unitForgetBias=args.unitForgetBias;_this.kernelRegularizer=getRegularizer(args.kernelRegularizer);_this.recurrentRegularizer=getRegularizer(args.recurrentRegularizer);_this.biasRegularizer=getRegularizer(args.biasRegularizer);_this.kernelConstraint=getConstraint(args.kernelConstraint);_this.recurrentConstraint=getConstraint(args.recurrentConstraint);_this.biasConstraint=getConstraint(args.biasConstraint);_this.dropout=min2([1,max2([0,args.dropout==null?0:args.dropout])]);_this.recurrentDropout=min2([1,max2([0,args.recurrentDropout==null?0:args.recurrentDropout])]);_this.implementation=args.implementation;_this.stateSize=[_this.units,_this.units];_this.dropoutMask=null;_this.recurrentDropoutMask=null;return _this}LSTMCell2.prototype.build=function(inputShape){var _a;inputShape=getExactlyOneShape(inputShape);var inputDim=inputShape[inputShape.length-1];this.kernel=this.addWeight("kernel",[inputDim,this.units*4],null,this.kernelInitializer,this.kernelRegularizer,true,this.kernelConstraint);this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*4],null,this.recurrentInitializer,this.recurrentRegularizer,true,this.recurrentConstraint);var biasInitializer;if(this.useBias){if(this.unitForgetBias){var capturedBiasInit_1=this.biasInitializer;var capturedUnits_1=this.units;biasInitializer=new(_a=function(_super2){__extends(CustomInit,_super2);function CustomInit(){return _super2!==null&&_super2.apply(this,arguments)||this}CustomInit.prototype.apply=function(shape,dtype){var bI=capturedBiasInit_1.apply([capturedUnits_1]);var bF=new Ones().apply([capturedUnits_1]);var bCAndH=capturedBiasInit_1.apply([capturedUnits_1*2]);return concatAlongFirstAxis(concatAlongFirstAxis(bI,bF),bCAndH)};return CustomInit}(Initializer),_a.className="CustomInit",_a)}else{biasInitializer=this.biasInitializer}this.bias=this.addWeight("bias",[this.units*4],null,biasInitializer,this.biasRegularizer,true,this.biasConstraint)}else{this.bias=null}this.built=true};LSTMCell2.prototype.call=function(inputs,kwargs){var _this=this;return tfc.tidy(function(){var training=kwargs["training"]==null?false:kwargs["training"];inputs=inputs;if(inputs.length!==3){throw new ValueError("LSTMCell expects 3 input Tensors (inputs, h, c), got "+(inputs.length+"."))}var hTMinus1=inputs[1];var cTMinus1=inputs[2];inputs=inputs[0];if(0<_this.dropout&&_this.dropout<1&&_this.dropoutMask==null){_this.dropoutMask=generateDropoutMask({ones:function(){return tfc.onesLike(inputs)},rate:_this.dropout,training,count:4})}if(0<_this.recurrentDropout&&_this.recurrentDropout<1&&_this.recurrentDropoutMask==null){_this.recurrentDropoutMask=generateDropoutMask({ones:function(){return tfc.onesLike(hTMinus1)},rate:_this.recurrentDropout,training,count:4})}var dpMask=_this.dropoutMask;var recDpMask=_this.recurrentDropoutMask;var i;var f;var c;var o;if(0<_this.dropout&&_this.dropout<1){inputs=tfc.mul(inputs,dpMask[0])}var z=dot2(inputs,_this.kernel.read());if(0<_this.recurrentDropout&&_this.recurrentDropout<1){hTMinus1=tfc.mul(hTMinus1,recDpMask[0])}z=tfc.add(z,dot2(hTMinus1,_this.recurrentKernel.read()));if(_this.useBias){z=biasAdd(z,_this.bias.read())}var _a=tfc.split(z,4,z.rank-1),z0=_a[0],z1=_a[1],z2=_a[2],z3=_a[3];i=_this.recurrentActivation.apply(z0);f=_this.recurrentActivation.apply(z1);c=tfc.add(tfc.mul(f,cTMinus1),tfc.mul(i,_this.activation.apply(z2)));o=_this.recurrentActivation.apply(z3);var h=tfc.mul(o,_this.activation.apply(c));return[h,h,c]})};LSTMCell2.prototype.getConfig=function(){var baseConfig=_super.prototype.getConfig.call(this);var config2={units:this.units,activation:serializeActivation(this.activation),recurrentActivation:serializeActivation(this.recurrentActivation),useBias:this.useBias,kernelInitializer:serializeInitializer(this.kernelInitializer),recurrentInitializer:serializeInitializer(this.recurrentInitializer),biasInitializer:serializeInitializer(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:serializeRegularizer(this.kernelRegularizer),recurrentRegularizer:serializeRegularizer(this.recurrentRegularizer),biasRegularizer:serializeRegularizer(this.biasRegularizer),activityRegularizer:serializeRegularizer(this.activityRegularizer),kernelConstraint:serializeConstraint(this.kernelConstraint),recurrentConstraint:serializeConstraint(this.recurrentConstraint),biasConstraint:serializeConstraint(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return __assign({},baseConfig,config2)};LSTMCell2.className="LSTMCell";return LSTMCell2}(RNNCell);tfc.serialization.registerClass(LSTMCell);var LSTM=function(_super){__extends(LSTM2,_super);function LSTM2(args){var _this=this;if(args.implementation===0){console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call.")}args.cell=new LSTMCell(args);_this=_super.call(this,args)||this;return _this}LSTM2.prototype.call=function(inputs,kwargs){var _this=this;return tfc.tidy(function(){if(_this.cell.dropoutMask!=null){tfc.dispose(_this.cell.dropoutMask);_this.cell.dropoutMask=null}if(_this.cell.recurrentDropoutMask!=null){tfc.dispose(_this.cell.recurrentDropoutMask);_this.cell.recurrentDropoutMask=null}var mask=kwargs==null?null:kwargs["mask"];var training=kwargs==null?null:kwargs["training"];var initialState=kwargs==null?null:kwargs["initialState"];return _super.prototype.call.call(_this,inputs,{mask,training,initialState})})};LSTM2.fromConfig=function(cls,config2){if(config2["implmentation"]===0){config2["implementation"]=1}return new cls(config2)};LSTM2.className="LSTM";return LSTM2}(RNN);tfc.serialization.registerClass(LSTM);var StackedRNNCells=function(_super){__extends(StackedRNNCells2,_super);function StackedRNNCells2(args){var _this=_super.call(this,args)||this;_this.cells=args.cells;return _this}Object.defineProperty(StackedRNNCells2.prototype,"stateSize",{get:function(){var stateSize=[];for(var _i=0,_a=this.cells.slice().reverse();_i<_a.length;_i++){var cell=_a[_i];if(Array.isArray(cell.stateSize)){stateSize.push.apply(stateSize,cell.stateSize)}else{stateSize.push(cell.stateSize)}}return stateSize},enumerable:true,configurable:true});StackedRNNCells2.prototype.call=function(inputs,kwargs){var _this=this;return tfc.tidy(function(){inputs=inputs;var states=inputs.slice(1);var nestedStates=[];for(var _i=0,_a=_this.cells.slice().reverse();_i<_a.length;_i++){var cell=_a[_i];if(Array.isArray(cell.stateSize)){nestedStates.push(states.splice(0,cell.stateSize.length))}else{nestedStates.push(states.splice(0,1))}}nestedStates.reverse();var newNestedStates=[];var callInputs;for(var i=0;i<_this.cells.length;++i){var cell=_this.cells[i];states=nestedStates[i];if(i===0){callInputs=[inputs[0]].concat(states)}else{callInputs=[callInputs[0]].concat(states)}callInputs=cell.call(callInputs,kwargs);newNestedStates.push(callInputs.slice(1))}states=[];for(var _b=0,_c=newNestedStates.slice().reverse();_b<_c.length;_b++){var cellStates=_c[_b];states.push.apply(states,cellStates)}return[callInputs[0]].concat(states)})};StackedRNNCells2.prototype.build=function(inputShape){if(isArrayOfShapes(inputShape)){inputShape=inputShape[0]}inputShape=inputShape;var outputDim;this.cells.forEach(function(cell,i){nameScope("RNNCell_"+i,function(){cell.build(inputShape);if(Array.isArray(cell.stateSize)){outputDim=cell.stateSize[0]}else{outputDim=cell.stateSize}inputShape=[inputShape[0],outputDim]})});this.built=true};StackedRNNCells2.prototype.getConfig=function(){var baseConfig=_super.prototype.getConfig.call(this);var getCellConfig=function(cell){return{className:cell.getClassName(),config:cell.getConfig()}};var cellConfigs=this.cells.map(getCellConfig);var config2={cells:cellConfigs};return __assign({},baseConfig,config2)};StackedRNNCells2.fromConfig=function(cls,config2,customObjects){if(customObjects===void 0){customObjects={}}var cells=[];for(var _i=0,_a=config2["cells"];_i<_a.length;_i++){var cellConfig=_a[_i];cells.push(deserialize(cellConfig,customObjects))}return new cls({cells})};Object.defineProperty(StackedRNNCells2.prototype,"trainableWeights",{get:function(){if(!this.trainable){return[]}var weights=[];for(var _i=0,_a=this.cells;_i<_a.length;_i++){var cell=_a[_i];weights.push.apply(weights,cell.trainableWeights)}return weights},enumerable:true,configurable:true});Object.defineProperty(StackedRNNCells2.prototype,"nonTrainableWeights",{get:function(){var weights=[];for(var _i=0,_a=this.cells;_i<_a.length;_i++){var cell=_a[_i];weights.push.apply(weights,cell.nonTrainableWeights)}if(!this.trainable){var trainableWeights=[];for(var _b=0,_c=this.cells;_b<_c.length;_b++){var cell=_c[_b];trainableWeights.push.apply(trainableWeights,cell.trainableWeights)}return trainableWeights.concat(weights)}return weights},enumerable:true,configurable:true});StackedRNNCells2.prototype.getWeights=function(){var weights=[];for(var _i=0,_a=this.cells;_i<_a.length;_i++){var cell=_a[_i];weights.push.apply(weights,cell.weights)}return batchGetValue(weights)};StackedRNNCells2.prototype.setWeights=function(weights){var tuples=[];for(var _i=0,_a=this.cells;_i<_a.length;_i++){var cell=_a[_i];var numParams=cell.weights.length;var inputWeights=weights.splice(numParams);for(var i=0;i1){var permutation=[0];for(var i=2;i1){throw new ValueError("Can not merge tensors with different batch sizes. "+("Got tensors with shapes: "+JSON.stringify(inputShape)+"."))}var outputShape=inputShape[0]==null?null:inputShape[0].slice(1);for(var i=1;i1){var dims=range(1,xNDim).concat([0]);reshapedInputs.push(tfc.transpose(x,dims));transposed=true}else{reshapedInputs.push(x)}}var y=_this.mergeFunction(reshapedInputs);var yNDim=y.rank;if(transposed){if(yNDim==null){var yShape=y.shape;var yNDim_1=yShape.length;var batchSize=yShape[yNDim_1-1];var newShape=[batchSize].concat(yShape.slice(0,yShape.length-1));y=tfc.transpose(y.reshape([-1,batchSize]),[1,0]).reshape(newShape)}else if(yNDim>1){var dims=[yNDim-1].concat(range(0,yNDim-1));y=tfc.transpose(y,dims)}}return y}}else{return _this.mergeFunction(inputs)}})};Merge2.prototype.computeOutputShape=function(inputShape){inputShape=inputShape;var outputShape;if(inputShape[0]==null){outputShape=null}else{outputShape=inputShape[0].slice(1)}for(var i=1;i1){throw new ValueError("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(inputShape))}};Concatenate2.prototype.mergeFunction=function(inputs){var _this=this;return tfc.tidy(function(){return concatenate(inputs,_this.axis)})};Concatenate2.prototype.computeOutputShape=function(inputShape){if(!(Array.isArray(inputShape)&&Array.isArray(inputShape[0]))){throw new ValueError("A `Concatenate` layer should be called on a list of inputs.")}var inputShapes=inputShape;var outputShape=inputShapes[0].slice();var axis=this.axis<0?outputShape.length+this.axis:this.axis;for(var _i=0,_a=inputShapes.slice(1);_i<_a.length;_i++){var shape=_a[_i];if(outputShape[axis]==null||shape[axis]==null){outputShape[axis]=null;break}outputShape[axis]+=shape[axis]}return outputShape};Concatenate2.prototype.computeMask=function(inputs,mask){var _this=this;if(mask==null){return null}if(!Array.isArray(mask)){throw new ValueError("`mask` should be an array for Concatenate")}if(!Array.isArray(inputs)){throw new ValueError("`inputs` should be an array for Concatenate")}if(mask.length!==inputs.length){throw new ValueError("Mismatch in the length of mask ("+mask.length+") "+("and the legnth of inputs ("+inputs.length+")"))}return tfc.tidy(function(){var allNullMasks=true;mask.forEach(function(m){if(m!=null){allNullMasks=false;return}});if(allNullMasks){return null}var outputMasks=[];for(var i=0;i3||y.shape.length>3){throw new NotImplementedError("batchDot is not implemented for tensors of 4D or higher rank yet")}tfc.util.assert(x.shape.length>=2,function(){return"batchDot requires the rank of x to be >= 2, "+("but got "+x.shape.length)});tfc.util.assert(x.shape.length>=2,function(){return"batchDot requires the rank of y to be >= 2, "+("but got "+y.shape.length)});if(typeof axes==="number"){axes=[axes,axes]}if(x.dtype==="complex64"||y.dtype==="complex64"){throw new NotImplementedError("batchDot is not implemented for complex64-type Tensors yet.")}var xNDim=x.shape.length;var yNDim=y.shape.length;if(axes==null){axes=[xNDim-1,yNDim-2]}var axesArray=axes;return tfc.tidy(function(){var diff;if(xNDim>yNDim){diff=xNDim-yNDim;var diffShape=[];for(var i=0;ixNDim){diff=yNDim-xNDim;var diffShape=[];for(var i=0;i0){var idx=void 0;if(xNDim>yNDim){idx=xNDim+yNDim-3}else{idx=xNDim-1}var squeezeAxes=[];for(var i=idx;i3||shape2.length>3){throw new NotImplementedError("Dot layer does not support tensors of 4D or higher rank yet.")}var axes=this.interpretAxes(shape1,shape2);if(shape1[axes[0]]!==shape2[axes[1]]){throw new ValueError("Dimension incompatibility: "+(shape1[axes[0]]+" !== "+shape2[axes[1]]))}};Dot2.prototype.mergeFunction=function(inputs){if(inputs.length!==2){throw new ValueError("A `Dot` layer must be called on exactly 2 inputs, "+("but received "+inputs.length+" input(s)."))}var x1=inputs[0];var x2=inputs[1];var axes;if(!Array.isArray(this.axes)){axes=[interpretAxis(this.axes,x1.shape.length),interpretAxis(this.axes,x2.shape.length)]}else{axes=this.axes.map(function(axis,i){return interpretAxis(axis,inputs[i].shape.length)})}if(this.normalize){x1=l2Normalize(x1,axes[0]);x2=l2Normalize(x2,axes[1])}return batchDot(x1,x2,axes)};Dot2.prototype.interpretAxes=function(shape1,shape2){var axes;if(!Array.isArray(this.axes)){axes=[interpretAxis(this.axes,shape1.length),interpretAxis(this.axes,shape2.length)]}else{axes=this.axes}return axes};Dot2.prototype.computeOutputShape=function(inputShape){tfc.util.assert(Array.isArray(inputShape)&&inputShape.length===2&&Array.isArray(inputShape[0])&&Array.isArray(inputShape[1]),function(){return"A `Dot` layer should be called on a list of exactly 2 inputs."});var shape1=inputShape[0].slice();var shape2=inputShape[1].slice();if(shape1.length>3||shape2.length>3){throw new NotImplementedError("Dot layer does not support tensors of 4D or higher rank yet.")}var axes=this.interpretAxes(shape1,shape2);shape1.splice(axes[0],1);shape2.splice(axes[1],1);shape2.splice(0,1);var outputShape=shape1.concat(shape2);if(outputShape.length===1){outputShape.push(1)}return outputShape};Dot2.prototype.computeMask=function(inputs,mask){return null};Dot2.prototype.getConfig=function(){var config2={axes:this.axes,normalize:this.normalize};var baseConfig=_super.prototype.getConfig.call(this);Object.assign(config2,baseConfig);return config2};Dot2.className="Dot";return Dot2}(Merge);tfc.serialization.registerClass(Dot);var GaussianNoise=function(_super){__extends(GaussianNoise2,_super);function GaussianNoise2(args){var _this=_super.call(this,args)||this;_this.supportsMasking=true;_this.stddev=args.stddev;return _this}GaussianNoise2.prototype.computeOutputShape=function(inputShape){return inputShape};GaussianNoise2.prototype.getConfig=function(){var baseConfig=_super.prototype.getConfig.call(this);var config2={stddev:this.stddev};Object.assign(config2,baseConfig);return config2};GaussianNoise2.prototype.call=function(inputs,kwargs){var _this=this;return tfc.tidy(function(){_this.invokeCallHook(inputs,kwargs);var input2=getExactlyOneTensor(inputs);var noised=function(){return randomNormal(input2.shape,0,_this.stddev).add(input2)};var output=inTrainPhase(noised,function(){return input2},kwargs["training"]||false);return output})};GaussianNoise2.className="GaussianNoise";return GaussianNoise2}(Layer);tfc.serialization.registerClass(GaussianNoise);var GaussianDropout=function(_super){__extends(GaussianDropout2,_super);function GaussianDropout2(args){var _this=_super.call(this,args)||this;_this.supportsMasking=true;_this.rate=args.rate;return _this}GaussianDropout2.prototype.computeOutputShape=function(inputShape){return inputShape};GaussianDropout2.prototype.getConfig=function(){var baseConfig=_super.prototype.getConfig.call(this);var config2={rate:this.rate};Object.assign(config2,baseConfig);return config2};GaussianDropout2.prototype.call=function(inputs,kwargs){var _this=this;return tfc.tidy(function(){_this.invokeCallHook(inputs,kwargs);var input2=getExactlyOneTensor(inputs);if(_this.rate>0&&_this.rate<1){var noised=function(){var stddev=Math.sqrt(_this.rate/(1-_this.rate));return input2.mul(randomNormal(input2.shape,1,stddev))};return inTrainPhase(noised,function(){return input2},kwargs["training"]||false)}return input2})};GaussianDropout2.className="GaussianDropout";return GaussianDropout2}(Layer);tfc.serialization.registerClass(GaussianDropout);var AlphaDropout=function(_super){__extends(AlphaDropout2,_super);function AlphaDropout2(args){var _this=_super.call(this,args)||this;_this.supportsMasking=true;_this.rate=args.rate;_this.noiseShape=args.noiseShape;return _this}AlphaDropout2.prototype._getNoiseShape=function(inputs){return this.noiseShape||getExactlyOneTensor(inputs).shape};AlphaDropout2.prototype.computeOutputShape=function(inputShape){return inputShape};AlphaDropout2.prototype.getConfig=function(){var baseConfig=_super.prototype.getConfig.call(this);var config2={rate:this.rate};Object.assign(config2,baseConfig);return config2};AlphaDropout2.prototype.call=function(inputs,kwargs){var _this=this;return tfc.tidy(function(){if(_this.rate<1&&_this.rate>0){var noiseShape_1=_this._getNoiseShape(inputs);var droppedInputs=function(){var input2=getExactlyOneTensor(inputs);var alpha=1.6732632423543772;var scale=1.0507009873554805;var alphaP=-alpha*scale;var keptIdx=tfc.greaterEqual(tfc.randomUniform(noiseShape_1),_this.rate);keptIdx=cast2(keptIdx,"float32");var a=Math.pow((1-_this.rate)*(1+_this.rate*Math.pow(alphaP,2)),-.5);var b=-a*alphaP*_this.rate;var x=input2.mul(keptIdx).add(keptIdx.add(-1).mul(alphaP));return x.mul(a).add(b)};return inTrainPhase(droppedInputs,function(){return getExactlyOneTensor(inputs)},kwargs["training"]||false)}return inputs})};AlphaDropout2.className="AlphaDropout";return AlphaDropout2}(Layer);tfc.serialization.registerClass(AlphaDropout);function batchNormalization(x,mean,variance,beta,gamma,epsilon2){if(epsilon2===void 0){epsilon2=.001}var out;if(x.rank===2){out=tfc.batchNorm2d(x,mean,variance,beta,gamma,epsilon2)}else if(x.rank===3){out=tfc.batchNorm3d(x,mean,variance,beta,gamma,epsilon2)}else if(x.rank===4){out=tfc.batchNorm4d(x,mean,variance,beta,gamma,epsilon2)}else{throw new NotImplementedError("batchNormalization is not implemented for array of rank "+x.rank+" yet")}return out}function regularNormalizeBatchInTraining(x,gamma,beta,reductionAxes,epsilon2){if(epsilon2===void 0){epsilon2=.001}return tfc.tidy(function(){var meanAndVariance=tfc.moments(x,reductionAxes);var mean=meanAndVariance.mean;var variance=meanAndVariance.variance;var normed=batchNormalization(x,mean,variance,beta,gamma,epsilon2);return[normed,mean,variance]})}function broadcastNormalizeBatchInTraining(x,gamma,beta,reductionAxes,epsilon2){if(epsilon2===void 0){epsilon2=.001}return tfc.tidy(function(){var meanAndVariance=tfc.moments(x,reductionAxes);var mean=meanAndVariance.mean;var variance=meanAndVariance.variance;var targetShape=[];for(var _i=0,_a=range(0,x.rank);_i<_a.length;_i++){var axis=_a[_i];if(reductionAxes.indexOf(axis)!==-1){targetShape.push(1)}else{targetShape.push(x.shape[axis])}}var broadcastMean=mean.reshape(targetShape);var broadcastVariance=variance.reshape(targetShape);var broadcastGamma=gamma==null?null:gamma.reshape(targetShape);var broadcastBeta=beta==null?null:beta.reshape(targetShape);var normed=batchNormalization(x,broadcastMean,broadcastVariance,broadcastBeta,broadcastGamma,epsilon2);return[normed,mean,variance]})}function normalizeBatchInTraining(x,gamma,beta,reductionAxes,epsilon2){if(epsilon2===void 0){epsilon2=.001}if(tfc.util.arraysEqual(reductionAxes.slice().sort(),range(0,x.rank-1))){return regularNormalizeBatchInTraining(x,gamma,beta,reductionAxes,epsilon2)}else{return broadcastNormalizeBatchInTraining(x,gamma,beta,reductionAxes,epsilon2)}}var BatchNormalization=function(_super){__extends(BatchNormalization2,_super);function BatchNormalization2(args){var _this=this;if(args==null){args={}}_this=_super.call(this,args)||this;_this.supportsMasking=true;_this.axis=args.axis==null?-1:args.axis;_this.momentum=args.momentum==null?.99:args.momentum;_this.epsilon=args.epsilon==null?.001:args.epsilon;_this.center=args.center==null?true:args.center;_this.scale=args.scale==null?true:args.scale;_this.betaInitializer=getInitializer(args.betaInitializer||"zeros");_this.gammaInitializer=getInitializer(args.gammaInitializer||"ones");_this.movingMeanInitializer=getInitializer(args.movingMeanInitializer||"zeros");_this.movingVarianceInitializer=getInitializer(args.movingVarianceInitializer||"ones");_this.betaConstraint=getConstraint(args.betaConstraint);_this.gammaConstraint=getConstraint(args.gammaConstraint);_this.betaRegularizer=getRegularizer(args.betaRegularizer);_this.gammaRegularizer=getRegularizer(args.gammaRegularizer);return _this}BatchNormalization2.prototype.build=function(inputShape){var _a;inputShape=getExactlyOneShape(inputShape);var axis=this.axis>=0?this.axis:this.axis+inputShape.length;var dim=inputShape[axis];if(dim==null){throw new ValueError("Axis "+axis+" of input tensor should have a defined dimension but the layer received an input with shape "+(JSON.stringify(inputShape)+"."))}this.inputSpec=[new InputSpec({ndim:inputShape.length,axes:(_a={},_a[axis]=dim,_a)})];var shape=[dim];if(this.scale){this.gamma=this.addWeight("gamma",shape,null,this.gammaInitializer,this.gammaRegularizer,true,this.gammaConstraint)}if(this.center){this.beta=this.addWeight("beta",shape,null,this.betaInitializer,this.betaRegularizer,true,this.betaConstraint)}this.movingMean=this.addWeight("moving_mean",shape,null,this.movingMeanInitializer,null,false);this.movingVariance=this.addWeight("moving_variance",shape,null,this.movingVarianceInitializer,null,false);this.built=true};BatchNormalization2.prototype.call=function(inputs,kwargs){var _this=this;return tfc.tidy(function(){var training=kwargs["training"]==null?false:kwargs["training"];var input2=getExactlyOneTensor(inputs);var inputShape=input2.shape;var ndim=inputShape.length;var reductionAxes=range(0,ndim);var axis=_this.axis>=0?_this.axis:_this.axis+ndim;reductionAxes.splice(axis,1);var broadcastShape=pyListRepeat(1,ndim);broadcastShape[axis]=inputShape[axis];var sortedReductionAxes=reductionAxes.slice();sortedReductionAxes.sort();var needsBroadcasting=!tfc.util.arraysEqual(sortedReductionAxes,range(0,ndim).slice(0,ndim-1));var normalizeInference=function(){if(needsBroadcasting){var broadcastMovingMean=_this.movingMean.read().reshape(broadcastShape);var broadcastMovingVariance=_this.movingVariance.read().reshape(broadcastShape);var broadcastBeta=_this.center?_this.beta.read().reshape(broadcastShape):null;var broadcastGamma=_this.scale?_this.gamma.read().reshape(broadcastShape):null;return batchNormalization(input2,broadcastMovingMean,broadcastMovingVariance,broadcastBeta,broadcastGamma,_this.epsilon)}else{return batchNormalization(input2,_this.movingMean.read(),_this.movingVariance.read(),_this.beta==null?null:_this.beta.read(),_this.gamma==null?null:_this.gamma.read(),_this.epsilon)}};if(!training){return normalizeInference()}var _a=normalizeBatchInTraining(input2,_this.gamma.read(),_this.beta.read(),reductionAxes,_this.epsilon),normedTraining=_a[0],mean=_a[1],variance=_a[2];var doMovingAverage=function(variable,value,momentum){tfc.tidy(function(){var decay=1-momentum;var origValue=variable.read();var updateDelta=origValue.sub(value).mul(decay);variable.write(origValue.sub(updateDelta))})};var updateMovingMeanAndVariance=function(){doMovingAverage(_this.movingMean,mean,_this.momentum);doMovingAverage(_this.movingVariance,variance,_this.momentum)};updateMovingMeanAndVariance();return normedTraining})};BatchNormalization2.prototype.getConfig=function(){var config2={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:serializeInitializer(this.betaInitializer),gammaInitializer:serializeInitializer(this.gammaInitializer),movingMeanInitializer:serializeInitializer(this.movingMeanInitializer),movingVarianceInitializer:serializeInitializer(this.movingVarianceInitializer),betaRegularizer:serializeRegularizer(this.betaRegularizer),gammaRegularizer:serializeRegularizer(this.gammaRegularizer),betaConstraint:serializeConstraint(this.betaConstraint),gammaConstraint:serializeConstraint(this.gammaConstraint)};var baseConfig=_super.prototype.getConfig.call(this);Object.assign(config2,baseConfig);return config2};BatchNormalization2.className="BatchNormalization";return BatchNormalization2}(Layer);tfc.serialization.registerClass(BatchNormalization);var LayerNormalization=function(_super){__extends(LayerNormalization2,_super);function LayerNormalization2(args){var _this=this;if(args==null){args={}}_this=_super.call(this,args)||this;_this.axis=args.axis==null?-1:args.axis;if(typeof _this.axis==="number"){if(!Number.isInteger(_this.axis)){throw new Error("Expected axis to be an integer, but received "+_this.axis)}}else if(Array.isArray(_this.axis)){for(var _i=0,_a=_this.axis;_i<_a.length;_i++){var axis=_a[_i];if(!Number.isInteger(axis)){throw new Error("Expected axis to be an array of integers, "+("but received "+JSON.stringify(_this.axis)))}}}else{throw new Error("Expected axis to be an integer or an array of integers, "+("but received "+JSON.stringify(_this.axis)))}_this.epsilon=args.epsilon==null?.001:args.epsilon;_this.center=args.center==null?true:args.center;_this.scale=args.scale==null?true:args.scale;_this.betaInitializer=getInitializer(args.betaInitializer||"zeros");_this.gammaInitializer=getInitializer(args.gammaInitializer||"ones");_this.betaRegularizer=getRegularizer(args.betaRegularizer);_this.gammaRegularizer=getRegularizer(args.gammaRegularizer);_this.supportsMasking=true;return _this}LayerNormalization2.prototype.build=function(inputShape){inputShape=getExactlyOneShape(inputShape);var nDims=inputShape.length;if(typeof this.axis==="number"){this.axis=[this.axis]}for(var i=0;i=nDims){throw new Error("Invalid axis: "+axis)}}if(this.axis.length!==unique(this.axis).length){throw new Error("Found duplicate axes in: "+this.axis)}var paramShape=this.axis.map(function(axis2){return inputShape[axis2]});var trainable=true;if(this.scale){this.gamma=this.addWeight("gamma",paramShape,"float32",this.gammaInitializer,this.gammaRegularizer,trainable)}else{this.gamma=null}if(this.center){this.beta=this.addWeight("beta",paramShape,"float32",this.betaInitializer,this.betaRegularizer,trainable)}else{this.beta=null}this.built=true};LayerNormalization2.prototype.call=function(inputs,kwargs){var _this=this;var input2=getExactlyOneTensor(inputs);var inputShape=input2.shape;var nDims=inputShape.length;return tfc.tidy(function(){var keepDims=true;var _a=tfc.moments(input2,_this.axis,keepDims),mean=_a.mean,variance=_a.variance;var broadcastShape=pyListRepeat(1,nDims);for(var _i=0,_b=_this.axis;_i<_b.length;_i++){var dim=_b[_i];broadcastShape[dim]=inputShape[dim]}var broadcast=function(v){if(v!=null&&v.shape.length!==nDims&&_this.axis!==[nDims-1]){return v.reshape(broadcastShape)}else{return v}};var scale=broadcast(_this.gamma.read());var offset=broadcast(_this.beta.read());var momentsTiling=[];var scaleOffsetTiling=[];for(var i=0;i=0){rows=inputShape[2]+this.padding[0][0]+this.padding[0][1]}else{rows=null}if(inputShape[3]!=null&&inputShape[3]>=0){cols=inputShape[3]+this.padding[1][0]+this.padding[1][1]}else{cols=null}return[inputShape[0],inputShape[1],rows,cols]}else{if(inputShape[1]!=null&&inputShape[1]>=0){rows=inputShape[1]+this.padding[0][0]+this.padding[0][1]}else{rows=null}if(inputShape[2]!=null&&inputShape[2]>=0){cols=inputShape[2]+this.padding[1][0]+this.padding[1][1]}else{cols=null}return[inputShape[0],rows,cols,inputShape[3]]}};ZeroPadding2D2.prototype.call=function(inputs,kwargs){var _this=this;return tfc.tidy(function(){return spatial2dPadding(getExactlyOneTensor(inputs),_this.padding,_this.dataFormat)})};ZeroPadding2D2.prototype.getConfig=function(){var config2={padding:this.padding,dataFormat:this.dataFormat};var baseConfig=_super.prototype.getConfig.call(this);Object.assign(config2,baseConfig);return config2};ZeroPadding2D2.className="ZeroPadding2D";return ZeroPadding2D2}(Layer);tfc.serialization.registerClass(ZeroPadding2D);function pool2d(x,poolSize,strides,padding,dataFormat,poolMode){return tfc.tidy(function(){checkDataFormat(dataFormat);checkPoolMode(poolMode);checkPaddingMode(padding);if(strides==null){strides=[1,1]}if(padding==null){padding="valid"}if(dataFormat==null){dataFormat=imageDataFormat()}if(poolMode==null){poolMode="max"}x=preprocessConv2DInput(x,dataFormat);var y;var paddingString=padding==="same"?"same":"valid";if(poolMode==="max"){y=tfc.maxPool(x,poolSize,strides,paddingString)}else{y=tfc.avgPool(x,poolSize,strides,paddingString)}if(dataFormat==="channelsFirst"){y=tfc.transpose(y,[0,3,1,2])}return y})}function pool3d(x,poolSize,strides,padding,dataFormat,poolMode){return tfc.tidy(function(){checkDataFormat(dataFormat);checkPoolMode(poolMode);checkPaddingMode(padding);if(strides==null){strides=[1,1,1]}if(padding==null){padding="valid"}if(dataFormat==null){dataFormat=imageDataFormat()}if(poolMode==null){poolMode="max"}x=preprocessConv3DInput(x,dataFormat);var y;var paddingString=padding==="same"?"same":"valid";if(poolMode==="max"){y=tfc.maxPool3d(x,poolSize,strides,paddingString)}else{y=tfc.avgPool3d(x,poolSize,strides,paddingString)}if(dataFormat==="channelsFirst"){y=tfc.transpose(y,[0,4,1,2,3])}return y})}var Pooling1D=function(_super){__extends(Pooling1D2,_super);function Pooling1D2(args){var _this=this;if(args.poolSize==null){args.poolSize=2}_this=_super.call(this,args)||this;if(typeof args.poolSize==="number"){_this.poolSize=[args.poolSize]}else if(Array.isArray(args.poolSize)&&args.poolSize.length===1&&typeof args.poolSize[0]==="number"){_this.poolSize=args.poolSize}else{throw new ValueError("poolSize for 1D convolutional layer must be a number or an Array of a single number, but received "+(""+JSON.stringify(args.poolSize)))}assertPositiveInteger(_this.poolSize,"poolSize");if(args.strides==null){_this.strides=_this.poolSize}else{if(typeof args.strides==="number"){_this.strides=[args.strides]}else if(Array.isArray(args.strides)&&args.strides.length===1&&typeof args.strides[0]==="number"){_this.strides=args.strides}else{throw new ValueError("strides for 1D convolutional layer must be a number or an Array of a single number, but received "+(""+JSON.stringify(args.strides)))}}assertPositiveInteger(_this.strides,"strides");_this.padding=args.padding==null?"valid":args.padding;checkPaddingMode(_this.padding);_this.inputSpec=[new InputSpec({ndim:3})];return _this}Pooling1D2.prototype.computeOutputShape=function(inputShape){inputShape=getExactlyOneShape(inputShape);var length=convOutputLength(inputShape[1],this.poolSize[0],this.padding,this.strides[0]);return[inputShape[0],length,inputShape[2]]};Pooling1D2.prototype.call=function(inputs,kwargs){var _this=this;return tfc.tidy(function(){_this.invokeCallHook(inputs,kwargs);inputs=expandDims(getExactlyOneTensor(inputs),2);var output=_this.poolingFunction(getExactlyOneTensor(inputs),[_this.poolSize[0],1],[_this.strides[0],1],_this.padding,"channelsLast");return tfc.squeeze(output,[2])})};Pooling1D2.prototype.getConfig=function(){var config2={poolSize:this.poolSize,padding:this.padding,strides:this.strides};var baseConfig=_super.prototype.getConfig.call(this);Object.assign(config2,baseConfig);return config2};return Pooling1D2}(Layer);var MaxPooling1D=function(_super){__extends(MaxPooling1D2,_super);function MaxPooling1D2(args){return _super.call(this,args)||this}MaxPooling1D2.prototype.poolingFunction=function(inputs,poolSize,strides,padding,dataFormat){checkDataFormat(dataFormat);checkPaddingMode(padding);return pool2d(inputs,poolSize,strides,padding,dataFormat,"max")};MaxPooling1D2.className="MaxPooling1D";return MaxPooling1D2}(Pooling1D);tfc.serialization.registerClass(MaxPooling1D);var AveragePooling1D=function(_super){__extends(AveragePooling1D2,_super);function AveragePooling1D2(args){return _super.call(this,args)||this}AveragePooling1D2.prototype.poolingFunction=function(inputs,poolSize,strides,padding,dataFormat){checkDataFormat(dataFormat);checkPaddingMode(padding);return pool2d(inputs,poolSize,strides,padding,dataFormat,"avg")};AveragePooling1D2.className="AveragePooling1D";return AveragePooling1D2}(Pooling1D);tfc.serialization.registerClass(AveragePooling1D);var Pooling2D=function(_super){__extends(Pooling2D2,_super);function Pooling2D2(args){var _this=this;if(args.poolSize==null){args.poolSize=[2,2]}_this=_super.call(this,args)||this;_this.poolSize=Array.isArray(args.poolSize)?args.poolSize:[args.poolSize,args.poolSize];if(args.strides==null){_this.strides=_this.poolSize}else if(Array.isArray(args.strides)){if(args.strides.length!==2){throw new ValueError("If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length "+(args.strides.length+"."))}_this.strides=args.strides}else{_this.strides=[args.strides,args.strides]}assertPositiveInteger(_this.poolSize,"poolSize");assertPositiveInteger(_this.strides,"strides");_this.padding=args.padding==null?"valid":args.padding;_this.dataFormat=args.dataFormat==null?"channelsLast":args.dataFormat;checkDataFormat(_this.dataFormat);checkPaddingMode(_this.padding);_this.inputSpec=[new InputSpec({ndim:4})];return _this}Pooling2D2.prototype.computeOutputShape=function(inputShape){inputShape=getExactlyOneShape(inputShape);var rows=this.dataFormat==="channelsFirst"?inputShape[2]:inputShape[1];var cols=this.dataFormat==="channelsFirst"?inputShape[3]:inputShape[2];rows=convOutputLength(rows,this.poolSize[0],this.padding,this.strides[0]);cols=convOutputLength(cols,this.poolSize[1],this.padding,this.strides[1]);if(this.dataFormat==="channelsFirst"){return[inputShape[0],inputShape[1],rows,cols]}else{return[inputShape[0],rows,cols,inputShape[3]]}};Pooling2D2.prototype.call=function(inputs,kwargs){var _this=this;return tfc.tidy(function(){_this.invokeCallHook(inputs,kwargs);return _this.poolingFunction(getExactlyOneTensor(inputs),_this.poolSize,_this.strides,_this.padding,_this.dataFormat)})};Pooling2D2.prototype.getConfig=function(){var config2={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat};var baseConfig=_super.prototype.getConfig.call(this);Object.assign(config2,baseConfig);return config2};return Pooling2D2}(Layer);var MaxPooling2D=function(_super){__extends(MaxPooling2D2,_super);function MaxPooling2D2(args){return _super.call(this,args)||this}MaxPooling2D2.prototype.poolingFunction=function(inputs,poolSize,strides,padding,dataFormat){checkDataFormat(dataFormat);checkPaddingMode(padding);return pool2d(inputs,poolSize,strides,padding,dataFormat,"max")};MaxPooling2D2.className="MaxPooling2D";return MaxPooling2D2}(Pooling2D);tfc.serialization.registerClass(MaxPooling2D);var AveragePooling2D=function(_super){__extends(AveragePooling2D2,_super);function AveragePooling2D2(args){return _super.call(this,args)||this}AveragePooling2D2.prototype.poolingFunction=function(inputs,poolSize,strides,padding,dataFormat){checkDataFormat(dataFormat);checkPaddingMode(padding);return pool2d(inputs,poolSize,strides,padding,dataFormat,"avg")};AveragePooling2D2.className="AveragePooling2D";return AveragePooling2D2}(Pooling2D);tfc.serialization.registerClass(AveragePooling2D);var Pooling3D=function(_super){__extends(Pooling3D2,_super);function Pooling3D2(args){var _this=this;if(args.poolSize==null){args.poolSize=[2,2,2]}_this=_super.call(this,args)||this;_this.poolSize=Array.isArray(args.poolSize)?args.poolSize:[args.poolSize,args.poolSize,args.poolSize];if(args.strides==null){_this.strides=_this.poolSize}else if(Array.isArray(args.strides)){if(args.strides.length!==3){throw new ValueError("If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length "+(args.strides.length+"."))}_this.strides=args.strides}else{_this.strides=[args.strides,args.strides,args.strides]}assertPositiveInteger(_this.poolSize,"poolSize");assertPositiveInteger(_this.strides,"strides");_this.padding=args.padding==null?"valid":args.padding;_this.dataFormat=args.dataFormat==null?"channelsLast":args.dataFormat;checkDataFormat(_this.dataFormat);checkPaddingMode(_this.padding);_this.inputSpec=[new InputSpec({ndim:5})];return _this}Pooling3D2.prototype.computeOutputShape=function(inputShape){inputShape=getExactlyOneShape(inputShape);var depths=this.dataFormat==="channelsFirst"?inputShape[2]:inputShape[1];var rows=this.dataFormat==="channelsFirst"?inputShape[3]:inputShape[2];var cols=this.dataFormat==="channelsFirst"?inputShape[4]:inputShape[3];depths=convOutputLength(depths,this.poolSize[0],this.padding,this.strides[0]);rows=convOutputLength(rows,this.poolSize[1],this.padding,this.strides[1]);cols=convOutputLength(cols,this.poolSize[2],this.padding,this.strides[2]);if(this.dataFormat==="channelsFirst"){return[inputShape[0],inputShape[1],depths,rows,cols]}else{return[inputShape[0],depths,rows,cols,inputShape[4]]}};Pooling3D2.prototype.call=function(inputs,kwargs){var _this=this;return tfc.tidy(function(){_this.invokeCallHook(inputs,kwargs);return _this.poolingFunction(getExactlyOneTensor(inputs),_this.poolSize,_this.strides,_this.padding,_this.dataFormat)})};Pooling3D2.prototype.getConfig=function(){var config2={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat};var baseConfig=_super.prototype.getConfig.call(this);Object.assign(config2,baseConfig);return config2};return Pooling3D2}(Layer);var MaxPooling3D=function(_super){__extends(MaxPooling3D2,_super);function MaxPooling3D2(args){return _super.call(this,args)||this}MaxPooling3D2.prototype.poolingFunction=function(inputs,poolSize,strides,padding,dataFormat){checkDataFormat(dataFormat);checkPaddingMode(padding);return pool3d(inputs,poolSize,strides,padding,dataFormat,"max")};MaxPooling3D2.className="MaxPooling3D";return MaxPooling3D2}(Pooling3D);tfc.serialization.registerClass(MaxPooling3D);var AveragePooling3D=function(_super){__extends(AveragePooling3D2,_super);function AveragePooling3D2(args){return _super.call(this,args)||this}AveragePooling3D2.prototype.poolingFunction=function(inputs,poolSize,strides,padding,dataFormat){checkDataFormat(dataFormat);checkPaddingMode(padding);return pool3d(inputs,poolSize,strides,padding,dataFormat,"avg")};AveragePooling3D2.className="AveragePooling3D";return AveragePooling3D2}(Pooling3D);tfc.serialization.registerClass(AveragePooling3D);var GlobalPooling1D=function(_super){__extends(GlobalPooling1D2,_super);function GlobalPooling1D2(args){var _this=_super.call(this,args)||this;_this.inputSpec=[new InputSpec({ndim:3})];return _this}GlobalPooling1D2.prototype.computeOutputShape=function(inputShape){return[inputShape[0],inputShape[2]]};GlobalPooling1D2.prototype.call=function(inputs,kwargs){throw new NotImplementedError};return GlobalPooling1D2}(Layer);var GlobalAveragePooling1D=function(_super){__extends(GlobalAveragePooling1D2,_super);function GlobalAveragePooling1D2(args){return _super.call(this,args||{})||this}GlobalAveragePooling1D2.prototype.call=function(inputs,kwargs){return tfc.tidy(function(){var input2=getExactlyOneTensor(inputs);return tfc.mean(input2,1)})};GlobalAveragePooling1D2.className="GlobalAveragePooling1D";return GlobalAveragePooling1D2}(GlobalPooling1D);tfc.serialization.registerClass(GlobalAveragePooling1D);var GlobalMaxPooling1D=function(_super){__extends(GlobalMaxPooling1D2,_super);function GlobalMaxPooling1D2(args){return _super.call(this,args||{})||this}GlobalMaxPooling1D2.prototype.call=function(inputs,kwargs){return tfc.tidy(function(){var input2=getExactlyOneTensor(inputs);return tfc.max(input2,1)})};GlobalMaxPooling1D2.className="GlobalMaxPooling1D";return GlobalMaxPooling1D2}(GlobalPooling1D);tfc.serialization.registerClass(GlobalMaxPooling1D);var GlobalPooling2D=function(_super){__extends(GlobalPooling2D2,_super);function GlobalPooling2D2(args){var _this=_super.call(this,args)||this;_this.dataFormat=args.dataFormat==null?"channelsLast":args.dataFormat;checkDataFormat(_this.dataFormat);_this.inputSpec=[new InputSpec({ndim:4})];return _this}GlobalPooling2D2.prototype.computeOutputShape=function(inputShape){inputShape=inputShape;if(this.dataFormat==="channelsLast"){return[inputShape[0],inputShape[3]]}else{return[inputShape[0],inputShape[1]]}};GlobalPooling2D2.prototype.call=function(inputs,kwargs){throw new NotImplementedError};GlobalPooling2D2.prototype.getConfig=function(){var config2={dataFormat:this.dataFormat};var baseConfig=_super.prototype.getConfig.call(this);Object.assign(config2,baseConfig);return config2};return GlobalPooling2D2}(Layer);var GlobalAveragePooling2D=function(_super){__extends(GlobalAveragePooling2D2,_super);function GlobalAveragePooling2D2(){return _super!==null&&_super.apply(this,arguments)||this}GlobalAveragePooling2D2.prototype.call=function(inputs,kwargs){var _this=this;return tfc.tidy(function(){var input2=getExactlyOneTensor(inputs);if(_this.dataFormat==="channelsLast"){return tfc.mean(input2,[1,2])}else{return tfc.mean(input2,[2,3])}})};GlobalAveragePooling2D2.className="GlobalAveragePooling2D";return GlobalAveragePooling2D2}(GlobalPooling2D);tfc.serialization.registerClass(GlobalAveragePooling2D);var GlobalMaxPooling2D=function(_super){__extends(GlobalMaxPooling2D2,_super);function GlobalMaxPooling2D2(){return _super!==null&&_super.apply(this,arguments)||this}GlobalMaxPooling2D2.prototype.call=function(inputs,kwargs){var _this=this;return tfc.tidy(function(){var input2=getExactlyOneTensor(inputs);if(_this.dataFormat==="channelsLast"){return tfc.max(input2,[1,2])}else{return tfc.max(input2,[2,3])}})};GlobalMaxPooling2D2.className="GlobalMaxPooling2D";return GlobalMaxPooling2D2}(GlobalPooling2D);tfc.serialization.registerClass(GlobalMaxPooling2D);var Wrapper=function(_super){__extends(Wrapper2,_super);function Wrapper2(args){var _this=_super.call(this,args)||this;_this.layer=args.layer;return _this}Wrapper2.prototype.build=function(inputShape){this.built=true};Object.defineProperty(Wrapper2.prototype,"trainable",{get:function(){if(this.layer!=null){return this.layer.trainable}else{return false}},set:function(value){if(this.layer!=null){this.layer.trainable=value}},enumerable:true,configurable:true});Object.defineProperty(Wrapper2.prototype,"trainableWeights",{get:function(){return this.layer.trainableWeights},enumerable:true,configurable:true});Object.defineProperty(Wrapper2.prototype,"nonTrainableWeights",{get:function(){return this.layer.nonTrainableWeights},enumerable:true,configurable:true});Object.defineProperty(Wrapper2.prototype,"updates",{get:function(){return this.layer._updates},enumerable:true,configurable:true});Object.defineProperty(Wrapper2.prototype,"losses",{get:function(){return this.layer.losses},enumerable:true,configurable:true});Wrapper2.prototype.getWeights=function(){return this.layer.getWeights()};Wrapper2.prototype.setWeights=function(weights){this.layer.setWeights(weights)};Wrapper2.prototype.getConfig=function(){var config2={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}};var baseConfig=_super.prototype.getConfig.call(this);Object.assign(config2,baseConfig);return config2};Wrapper2.prototype.setFastWeightInitDuringBuild=function(value){_super.prototype.setFastWeightInitDuringBuild.call(this,value);if(this.layer!=null){this.layer.setFastWeightInitDuringBuild(value)}};Wrapper2.fromConfig=function(cls,config2,customObjects){if(customObjects===void 0){customObjects={}}var layerConfig=config2["layer"];var layer=deserialize(layerConfig,customObjects);delete config2["layer"];var newConfig={layer};Object.assign(newConfig,config2);return new cls(newConfig)};return Wrapper2}(Layer);var TimeDistributed=function(_super){__extends(TimeDistributed2,_super);function TimeDistributed2(args){var _this=_super.call(this,args)||this;_this.supportsMasking=true;return _this}TimeDistributed2.prototype.build=function(inputShape){inputShape=getExactlyOneShape(inputShape);if(inputShape.length<3){throw new ValueError("TimeDistributed layer expects an input shape >= 3D, but received "+("input shape "+JSON.stringify(inputShape)))}this.inputSpec=[{shape:inputShape}];var childInputShape=[inputShape[0]].concat(inputShape.slice(2));if(!this.layer.built){this.layer.build(childInputShape);this.layer.built=true}_super.prototype.build.call(this,inputShape)};TimeDistributed2.prototype.computeOutputShape=function(inputShape){inputShape=getExactlyOneShape(inputShape);var childInputShape=[inputShape[0]].concat(inputShape.slice(2));var childOutputShape=this.layer.computeOutputShape(childInputShape);var timesteps=inputShape[1];return[childOutputShape[0],timesteps].concat(childOutputShape.slice(1))};TimeDistributed2.prototype.call=function(inputs,kwargs){var _this=this;return tfc.tidy(function(){inputs=getExactlyOneTensor(inputs);var step=function(inputs2,states){var output=getExactlyOneTensor(_this.layer.call(inputs2,kwargs));return[output,[]]};var rnnOutputs=rnn(step,inputs,[],false,null,null,false,true);var y=rnnOutputs[1];return y})};TimeDistributed2.className="TimeDistributed";return TimeDistributed2}(Wrapper);tfc.serialization.registerClass(TimeDistributed);function checkBidirectionalMergeMode(value){checkStringTypeUnionValue(VALID_BIDIRECTIONAL_MERGE_MODES,"BidirectionalMergeMode",value)}var DEFAULT_BIDIRECTIONAL_MERGE_MODE="concat";var Bidirectional=function(_super){__extends(Bidirectional2,_super);function Bidirectional2(args){var _this=_super.call(this,args)||this;var layerConfig=args.layer.getConfig();var forwDict={};forwDict["className"]=args.layer.getClassName();forwDict["config"]=layerConfig;_this.forwardLayer=deserialize(forwDict);layerConfig["goBackwards"]=layerConfig["goBackwards"]===true?false:true;var backDict={};backDict["className"]=args.layer.getClassName();backDict["config"]=layerConfig;_this.backwardLayer=deserialize(backDict);_this.forwardLayer.name="forward_"+_this.forwardLayer.name;_this.backwardLayer.name="backward_"+_this.backwardLayer.name;_this.mergeMode=args.mergeMode===void 0?DEFAULT_BIDIRECTIONAL_MERGE_MODE:args.mergeMode;checkBidirectionalMergeMode(_this.mergeMode);if(args.weights){throw new NotImplementedError("weights support is not implemented for Bidirectional layer yet.")}_this._stateful=args.layer.stateful;_this.returnSequences=args.layer.returnSequences;_this.returnState=args.layer.returnState;_this.supportsMasking=true;_this._trainable=true;_this.inputSpec=args.layer.inputSpec;_this.numConstants=null;return _this}Object.defineProperty(Bidirectional2.prototype,"trainable",{get:function(){return this._trainable},set:function(value){this._trainable=value;if(this.forwardLayer!=null){this.forwardLayer.trainable=value}if(this.backwardLayer!=null){this.backwardLayer.trainable=value}},enumerable:true,configurable:true});Bidirectional2.prototype.getWeights=function(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())};Bidirectional2.prototype.setWeights=function(weights){var numWeights=weights.length;var numeightsOver2=Math.floor(numWeights/2);this.forwardLayer.setWeights(weights.slice(0,numeightsOver2));this.backwardLayer.setWeights(weights.slice(numeightsOver2))};Bidirectional2.prototype.computeOutputShape=function(inputShape){var layerShapes=this.forwardLayer.computeOutputShape(inputShape);if(!(Array.isArray(layerShapes)&&Array.isArray(layerShapes[0]))){layerShapes=[layerShapes]}layerShapes=layerShapes;var outputShape;var outputShapes;var stateShape;if(this.returnState){stateShape=layerShapes.slice(1);outputShape=layerShapes[0]}else{outputShape=layerShapes[0]}outputShape=outputShape;if(this.mergeMode==="concat"){outputShape[outputShape.length-1]*=2;outputShapes=[outputShape]}else if(this.mergeMode==null){outputShapes=[outputShape,outputShape.slice()]}else{outputShapes=[outputShape]}if(this.returnState){if(this.mergeMode==null){return outputShapes.concat(stateShape).concat(stateShape.slice())}return[outputShape].concat(stateShape).concat(stateShape.slice())}return singletonOrArray(outputShapes)};Bidirectional2.prototype.apply=function(inputs,kwargs){var initialState=kwargs==null?null:kwargs["initialState"];var constants=kwargs==null?null:kwargs["constants"];if(kwargs==null){kwargs={}}var standardized=standardizeArgs(inputs,initialState,constants,this.numConstants);inputs=standardized.inputs;initialState=standardized.initialState;constants=standardized.constants;if(Array.isArray(inputs)){initialState=inputs.slice(1);inputs=inputs[0]}if((initialState==null||initialState.length===0)&&constants==null){return _super.prototype.apply.call(this,inputs,kwargs)}var additionalInputs=[];var additionalSpecs=[];if(initialState!=null){var numStates=initialState.length;if(numStates%2>0){throw new ValueError("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.")}kwargs["initialState"]=initialState;additionalInputs.push.apply(additionalInputs,initialState);var stateSpecs=initialState.map(function(state){return new InputSpec({shape:state.shape})});this.forwardLayer.stateSpec=stateSpecs.slice(0,numStates/2);this.backwardLayer.stateSpec=stateSpecs.slice(numStates/2);additionalSpecs.push.apply(additionalSpecs,stateSpecs)}if(constants!=null){throw new NotImplementedError("Support for constants in Bidirectional layers is not implemented yet.")}var isSymbolicTensor=additionalInputs[0]instanceof SymbolicTensor;for(var _i=0,additionalInputs_1=additionalInputs;_iprevVal}var EarlyStopping=function(_super){__extends(EarlyStopping2,_super);function EarlyStopping2(args){var _this=_super.call(this)||this;if(args==null){args={}}if(args.restoreBestWeights){throw new NotImplementedError("restoreBestWeights = True is not implemented in EarlyStopping yet.")}_this.monitor=args.monitor||"val_loss";_this.minDelta=Math.abs(args.minDelta||0);_this.patience=args.patience||0;_this.verbose=args.verbose||0;_this.mode=args.mode||"auto";_this.baseline=args.baseline;if(["auto","min","max"].indexOf(_this.mode)===-1){console.warn("EarlyStopping mode '"+_this.mode+"' is invalid. Falling back to mode 'auto'.");_this.mode="auto"}if(_this.mode==="min"){_this.monitorFunc=less}else if(_this.mode==="max"){_this.monitorFunc=greater}else{if(_this.monitor.indexOf("acc")!==-1){_this.monitorFunc=greater}else{_this.monitorFunc=less}}if(_this.monitorFunc===less){_this.minDelta*=-1}return _this}EarlyStopping2.prototype.onTrainBegin=function(logs){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){this.wait=0;this.stoppedEpoch=0;if(this.baseline!=null){this.best=this.baseline}else{this.best=this.monitorFunc===less?Infinity:-Infinity}return[2]})})};EarlyStopping2.prototype.onEpochEnd=function(epoch,logs){return __awaiter(this,void 0,void 0,function(){var current;return __generator(this,function(_a){switch(_a.label){case 0:return[4,resolveScalarsInLogs(logs)];case 1:_a.sent();current=this.getMonitorValue(logs);if(current==null){return[2]}if(this.monitorFunc(current-this.minDelta,this.best)){this.best=current;this.wait=0}else{this.wait++;if(this.wait>=this.patience){this.stoppedEpoch=epoch;this.model.stopTraining=true}}return[2]}})})};EarlyStopping2.prototype.onTrainEnd=function(logs){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){if(this.stoppedEpoch>0&&this.verbose){console.log("Epoch "+this.stoppedEpoch+": early stopping.")}return[2]})})};EarlyStopping2.prototype.getMonitorValue=function(logs){if(logs==null){logs={}}var monitorValue=logs[this.monitor];if(monitorValue==null){console.warn("Metric for EarlyStopping "+this.monitor+" is not available. "+("Available metrics are: "+Object.keys(logs)))}return monitorValue};return EarlyStopping2}(Callback);function earlyStopping(args){return new EarlyStopping(args)}var callbacks={earlyStopping};exports2.Callback=Callback;exports2.CallbackList=CallbackList;exports2.CustomCallback=CustomCallback;exports2.EarlyStopping=EarlyStopping;exports2.History=History;exports2.InputSpec=InputSpec;exports2.LayerVariable=LayerVariable;exports2.LayersModel=LayersModel;exports2.RNN=RNN;exports2.Sequential=Sequential;exports2.SymbolicTensor=SymbolicTensor;exports2.callbacks=callbacks;exports2.constraints=exports_constraints;exports2.initializers=exports_initializers;exports2.input=input;exports2.layers=exports_layers;exports2.loadLayersModel=loadLayersModel;exports2.metrics=exports_metrics;exports2.model=model;exports2.models=exports_models;exports2.registerCallbackConstructor=registerCallbackConstructor;exports2.regularizers=exports_regularizers;exports2.sequential=sequential;exports2.version_layers=version5});var require_tf_converter_node=__commonJS(exports2=>{"use strict";Object.defineProperty(exports2,"__esModule",{value:true});var tfOps=require_tf_core_node();var __assign=Object.assign||function __assign2(t){for(var s,i=1,n=arguments.length;i0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar}function __spread(){for(var ar=[],i=0;i0){Object.keys(inputNodeNameToKey).forEach(function(name){var _a=__read(getNodeNameAndIndex(name),1),nodeName=_a[0];var node=nodes[nodeName];if(node){node.signatureKey=inputNodeNameToKey[name];inputs.push(node)}})}else{inputs=placeholders}var functions={};if(graph2.library!=null&&graph2.library.function!=null){functions=graph2.library.function.reduce(function(functions2,func){functions2[func.signature.name]=_this2.mapFunction(func);return functions2},{})}var result={nodes,inputs,outputs,weights,placeholders,signature,functions};if(initNodes.length>0){result.initNodes=initNodes}return result};OperationMapper2.prototype.mapSignatureEntries=function(entries){return Object.keys(entries||{}).reduce(function(prev,curr){prev[entries[curr].name]=curr;return prev},{})};OperationMapper2.prototype.mapNode=function(node){var mapper=getRegisteredOp(node.op)||this.opMappers[node.op]||{};if(node.attr==null){node.attr={}}var newNode={name:node.name,op:node.op,category:mapper.category,inputNames:(node.input||[]).map(function(input){return input.startsWith("^")?input.substr(1):input}),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:node.attr};if(mapper.inputs!=null){newNode.inputParams=mapper.inputs.reduce(function(map,param){map[param.name]={type:param.type,inputIndexStart:param.start,inputIndexEnd:param.end};return map},{})}if(mapper.attrs!=null){newNode.attrParams=mapper.attrs.reduce(function(map,param){var type=param.type;var value=void 0;switch(param.type){case"string":value=getStringParam(node.attr,param.tfName,param.defaultValue);if(value===void 0&&!!param.tfDeprecatedName){value=getStringParam(node.attr,param.tfDeprecatedName,param.defaultValue)}break;case"string[]":value=getStringArrayParam(node.attr,param.tfName,param.defaultValue);if(value===void 0&&!!param.tfDeprecatedName){value=getStringArrayParam(node.attr,param.tfDeprecatedName,param.defaultValue)}break;case"number":value=getNumberParam(node.attr,param.tfName,param.defaultValue||0);if(value===void 0&&!!param.tfDeprecatedName){value=getNumberParam(node.attr,param.tfDeprecatedName,param.defaultValue)}break;case"number[]":value=getNumericArrayParam(node.attr,param.tfName,param.defaultValue);if(value===void 0&&!!param.tfDeprecatedName){value=getNumericArrayParam(node.attr,param.tfDeprecatedName,param.defaultValue)}break;case"bool":value=getBoolParam(node.attr,param.tfName,param.defaultValue);if(value===void 0&&!!param.tfDeprecatedName){value=getBoolParam(node.attr,param.tfDeprecatedName,param.defaultValue)}break;case"bool[]":value=getBoolArrayParam(node.attr,param.tfName,param.defaultValue);if(value===void 0&&!!param.tfDeprecatedName){value=getBoolArrayParam(node.attr,param.tfDeprecatedName,param.defaultValue)}break;case"shape":value=getTensorShapeParam(node.attr,param.tfName,param.defaultValue);if(value===void 0&&!!param.tfDeprecatedName){value=getTensorShapeParam(node.attr,param.tfDeprecatedName,param.defaultValue)}break;case"shape[]":value=getTensorShapeArrayParam(node.attr,param.tfName,param.defaultValue);if(value===void 0&&!!param.tfDeprecatedName){value=getTensorShapeArrayParam(node.attr,param.tfDeprecatedName,param.defaultValue)}break;case"dtype":value=getDtypeParam(node.attr,param.tfName,param.defaultValue);if(value===void 0&&!!param.tfDeprecatedName){value=getDtypeParam(node.attr,param.tfDeprecatedName,param.defaultValue)}break;case"dtype[]":value=getDtypeArrayParam(node.attr,param.tfName,param.defaultValue);if(value===void 0&&!!param.tfDeprecatedName){value=getDtypeArrayParam(node.attr,param.tfDeprecatedName,param.defaultValue)}break;case"func":value=getFuncParam(node.attr,param.tfName,param.defaultValue);if(value===void 0&&!!param.tfDeprecatedName){value=getFuncParam(node.attr,param.tfDeprecatedName,param.defaultValue)}break;case"tensor":case"tensors":break;default:throw new Error("Unsupported param type: "+param.type+" for op: "+node.op)}map[param.name]={value,type};return map},{})}return newNode};OperationMapper2.prototype.mapFunction=function(functionDef){var _this2=this;var tfNodes=functionDef.nodeDef;var placeholders=[];var weights=[];var nodes={};if(tfNodes!=null){nodes=tfNodes.reduce(function(map,node){map[node.name]=_this2.mapNode(node);if(node.op==="Const"){weights.push(map[node.name])}return map},{})}var inputs=[];var outputs=[];functionDef.signature.inputArg.forEach(function(arg){var _a=__read(getNodeNameAndIndex(arg.name),1),nodeName=_a[0];var node={name:nodeName,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:parseDtypeParam(arg.type),type:"dtype"}},children:[]};node.signatureKey=arg.name;inputs.push(node);nodes[nodeName]=node});var allNodes=Object.keys(nodes);allNodes.forEach(function(key){var node=nodes[key];node.inputNames.forEach(function(name){var _a=__read(getNodeNameAndIndex(name),1),nodeName=_a[0];node.inputs.push(nodes[nodeName]);nodes[nodeName].children.push(node)})});var returnNodeMap=functionDef.ret;functionDef.signature.outputArg.forEach(function(output){var _a=__read(getNodeNameAndIndex(returnNodeMap[output.name]),2),nodeName=_a[0],index=_a[1];var node=nodes[nodeName];if(node!=null){node.defaultOutput=index;outputs.push(node)}});var signature=this.mapArgsToSignature(functionDef);return{nodes,inputs,outputs,weights,placeholders,signature}};OperationMapper2.prototype.mapArgsToSignature=function(functionDef){var _this2=this;return{methodName:functionDef.signature.name,inputs:functionDef.signature.inputArg.reduce(function(map,arg){map[arg.name]=_this2.mapArgToTensorInfo(arg);return map},{}),outputs:functionDef.signature.outputArg.reduce(function(map,arg){map[arg.name]=_this2.mapArgToTensorInfo(arg,functionDef.ret);return map},{})}};OperationMapper2.prototype.mapArgToTensorInfo=function(arg,nameMap){var name=arg.name;if(nameMap!=null){name=nameMap[name]}return{name,dtype:arg.type}};return OperationMapper2}();function decodeBase64(text){var global2=tfOps.env().global;if(typeof global2.atob!=="undefined"){return global2.atob(text)}else if(typeof Buffer!=="undefined"){return new Buffer(text,"base64").toString()}else{throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}}function parseStringParam(s,keepCase){var value=Array.isArray(s)?String.fromCharCode.apply(null,s):decodeBase64(s);return keepCase?value:value.toLowerCase()}function getStringParam(attrs,name,def,keepCase){if(keepCase===void 0){keepCase=false}var param=attrs[name];if(param!=null){return parseStringParam(param.s,keepCase)}return def}function getBoolParam(attrs,name,def){var param=attrs[name];return param?param.b:def}function getNumberParam(attrs,name,def){var param=attrs[name]||{};var value=param["i"]!=null?param["i"]:param["f"]!=null?param["f"]:def;return typeof value==="number"?value:parseInt(value,10)}function parseDtypeParam(value){if(typeof value==="string"){value=DataType[value]}switch(value){case DataType.DT_FLOAT:return"float32";case DataType.DT_INT32:case DataType.DT_INT64:case DataType.DT_INT8:case DataType.DT_UINT8:return"int32";case DataType.DT_BOOL:return"bool";case DataType.DT_DOUBLE:return"float32";case DataType.DT_STRING:return"string";default:return null}}function getFuncParam(attrs,name,def){var param=attrs[name];if(param&¶m.func){return param.func.name}return def}function getDtypeParam(attrs,name,def){var param=attrs[name];if(param&¶m.type){return parseDtypeParam(param.type)}return def}function getDtypeArrayParam(attrs,name,def){var param=attrs[name];if(param&¶m.list&¶m.list.type){return param.list.type.map(function(v){return parseDtypeParam(v)})}return def}function parseTensorShapeParam(shape){if(shape.unknownRank){return void 0}if(shape.dim!=null){return shape.dim.map(function(dim){return typeof dim.size==="number"?dim.size:parseInt(dim.size,10)})}return[]}function getTensorShapeParam(attrs,name,def){var param=attrs[name];if(param&¶m.shape){return parseTensorShapeParam(param.shape)}return def}function getNumericArrayParam(attrs,name,def){var param=attrs[name];if(param){return((param.list.f&¶m.list.f.length?param.list.f:param.list.i)||[]).map(function(v){return typeof v==="number"?v:parseInt(v,10)})}return def}function getStringArrayParam(attrs,name,def,keepCase){if(keepCase===void 0){keepCase=false}var param=attrs[name];if(param&¶m.list&¶m.list.s){return param.list.s.map(function(v){return parseStringParam(v,keepCase)})}return def}function getTensorShapeArrayParam(attrs,name,def){var param=attrs[name];if(param&¶m.list&¶m.list.shape){return param.list.shape.map(function(v){return parseTensorShapeParam(v)})}return def}function getBoolArrayParam(attrs,name,def){var param=attrs[name];if(param&¶m.list&¶m.list.b){return param.list.b}return def}var NodeValueImpl=function(){function NodeValueImpl2(node,tensorMap,context){var _this2=this;this.node=node;this.tensorMap=tensorMap;this.context=context;this.inputs=[];this.attrs={};this.inputs=node.inputNames.map(function(name){return _this2.getInput(name)});if(node.rawAttrs!=null){this.attrs=Object.keys(node.rawAttrs).reduce(function(attrs,key){attrs[key]=_this2.getAttr(key);return attrs},{})}}NodeValueImpl2.prototype.getInput=function(name){return getTensor(name,this.tensorMap,this.context)};NodeValueImpl2.prototype.getAttr=function(name,defaultValue){var value=this.node.rawAttrs[name];if(value.tensor!=null){return getTensor(name,this.tensorMap,this.context)}if(value.i!=null||value.f!=null){return getNumberParam(this.node.rawAttrs,name,defaultValue)}if(value.s!=null){return getStringParam(this.node.rawAttrs,name,defaultValue)}if(value.b!=null){return getBoolParam(this.node.rawAttrs,name,defaultValue)}if(value.shape!=null){return getTensorShapeParam(this.node.rawAttrs,name,defaultValue)}if(value.type!=null){return getDtypeParam(this.node.rawAttrs,name,defaultValue)}if(value.list!=null){if(value.list.i!=null||value.list.f!=null){return getNumericArrayParam(this.node.rawAttrs,name,defaultValue)}if(value.list.s!=null){return getStringArrayParam(this.node.rawAttrs,name,defaultValue)}if(value.list.shape!=null){return getTensorShapeArrayParam(this.node.rawAttrs,name,defaultValue)}if(value.list.b!=null){return getBoolArrayParam(this.node.rawAttrs,name,defaultValue)}if(value.list.type!=null){return getDtypeArrayParam(this.node.rawAttrs,name,defaultValue)}}return defaultValue};return NodeValueImpl2}();var executeOp=function(node,tensorMap,context){switch(node.op){case"BiasAdd":case"AddV2":case"Add":{return[tfOps.add(getParamValue("a",node,tensorMap,context),getParamValue("b",node,tensorMap,context))]}case"AddN":{return[tfOps.addN(getParamValue("tensors",node,tensorMap,context))]}case"FloorMod":case"Mod":return[tfOps.mod(getParamValue("a",node,tensorMap,context),getParamValue("b",node,tensorMap,context))];case"Mul":return[tfOps.mul(getParamValue("a",node,tensorMap,context),getParamValue("b",node,tensorMap,context))];case"RealDiv":case"Div":{return[tfOps.div(getParamValue("a",node,tensorMap,context),getParamValue("b",node,tensorMap,context))]}case"DivNoNan":{return[tfOps.divNoNan(getParamValue("a",node,tensorMap,context),getParamValue("b",node,tensorMap,context))]}case"FloorDiv":{return[tfOps.floorDiv(getParamValue("a",node,tensorMap,context),getParamValue("b",node,tensorMap,context))]}case"Sub":{return[tfOps.sub(getParamValue("a",node,tensorMap,context),getParamValue("b",node,tensorMap,context))]}case"Minimum":{return[tfOps.minimum(getParamValue("a",node,tensorMap,context),getParamValue("b",node,tensorMap,context))]}case"Maximum":{return[tfOps.maximum(getParamValue("a",node,tensorMap,context),getParamValue("b",node,tensorMap,context))]}case"Pow":{return[tfOps.pow(getParamValue("a",node,tensorMap,context),getParamValue("b",node,tensorMap,context))]}case"SquaredDifference":{return[tfOps.squaredDifference(getParamValue("a",node,tensorMap,context),getParamValue("b",node,tensorMap,context))]}default:throw TypeError("Node type "+node.op+" is not implemented")}};var executeOp$1=function(node,tensorMap,context){switch(node.op){case"Abs":case"ComplexAbs":return[tfOps.abs(getParamValue("x",node,tensorMap,context))];case"Acos":return[tfOps.acos(getParamValue("x",node,tensorMap,context))];case"Acosh":return[tfOps.acosh(getParamValue("x",node,tensorMap,context))];case"Asin":return[tfOps.asin(getParamValue("x",node,tensorMap,context))];case"Asinh":return[tfOps.asinh(getParamValue("x",node,tensorMap,context))];case"Atan":return[tfOps.atan(getParamValue("x",node,tensorMap,context))];case"Atan2":return[tfOps.atan2(getParamValue("x",node,tensorMap,context),getParamValue("y",node,tensorMap,context))];case"Atanh":return[tfOps.atanh(getParamValue("x",node,tensorMap,context))];case"Ceil":return[tfOps.ceil(getParamValue("x",node,tensorMap,context))];case"Complex":return[tfOps.complex(getParamValue("real",node,tensorMap,context),getParamValue("imag",node,tensorMap,context))];case"Cos":return[tfOps.cos(getParamValue("x",node,tensorMap,context))];case"Cosh":return[tfOps.cosh(getParamValue("x",node,tensorMap,context))];case"Elu":return[tfOps.elu(getParamValue("x",node,tensorMap,context))];case"Erf":return[tfOps.erf(getParamValue("x",node,tensorMap,context))];case"Exp":return[tfOps.exp(getParamValue("x",node,tensorMap,context))];case"Expm1":{return[tfOps.expm1(getParamValue("x",node,tensorMap,context))]}case"Floor":return[tfOps.floor(getParamValue("x",node,tensorMap,context))];case"Log":return[tfOps.log(getParamValue("x",node,tensorMap,context))];case"Log1p":{return[tfOps.log1p(getParamValue("x",node,tensorMap,context))]}case"Imag":return[tfOps.imag(getParamValue("x",node,tensorMap,context))];case"Neg":return[tfOps.neg(getParamValue("x",node,tensorMap,context))];case"Reciprocal":{return[tfOps.reciprocal(getParamValue("x",node,tensorMap,context))]}case"Real":return[tfOps.real(getParamValue("x",node,tensorMap,context))];case"Relu":return[tfOps.relu(getParamValue("x",node,tensorMap,context))];case"Round":{return[tfOps.round(getParamValue("x",node,tensorMap,context))]}case"Selu":return[tfOps.selu(getParamValue("x",node,tensorMap,context))];case"Sigmoid":return[tfOps.sigmoid(getParamValue("x",node,tensorMap,context))];case"Sin":return[tfOps.sin(getParamValue("x",node,tensorMap,context))];case"Sign":{return[tfOps.sign(getParamValue("x",node,tensorMap,context))]}case"Sinh":{return[tfOps.sinh(getParamValue("x",node,tensorMap,context))]}case"Softplus":{return[tfOps.softplus(getParamValue("x",node,tensorMap,context))]}case"Sqrt":{return[tfOps.sqrt(getParamValue("x",node,tensorMap,context))]}case"Square":{return[tfOps.square(getParamValue("x",node,tensorMap,context))]}case"Tanh":{return[tfOps.tanh(getParamValue("x",node,tensorMap,context))]}case"Tan":return[tfOps.tan(getParamValue("x",node,tensorMap,context))];case"Relu6":case"ClipByValue":return[tfOps.clipByValue(getParamValue("x",node,tensorMap,context),getParamValue("clipValueMin",node,tensorMap,context),getParamValue("clipValueMax",node,tensorMap,context))];case"Rsqrt":return[tfOps.rsqrt(getTensor(node.inputNames[0],tensorMap,context))];case"Prod":return[tfOps.prod(getParamValue("x",node,tensorMap,context),getParamValue("axes",node,tensorMap,context))];case"LeakyRelu":return[tfOps.leakyRelu(getParamValue("x",node,tensorMap,context),getParamValue("alpha",node,tensorMap,context))];case"Prelu":return[tfOps.prelu(getParamValue("x",node,tensorMap,context),getParamValue("alpha",node,tensorMap,context))];default:throw TypeError("Node type "+node.op+" is not implemented")}};function assertShapesMatchAllowUndefinedSize(shapeA,shapeB,errorMessagePrefix){if(errorMessagePrefix===void 0){errorMessagePrefix=""}tfOps.util.assert(shapesEqualAllowUndefinedSize(shapeA,shapeB),function(){return errorMessagePrefix+(" Shapes "+shapeA+" and "+shapeB+" must match")})}function shapesEqualAllowUndefinedSize(n1,n2){if(n1.length!==n2.length){return false}for(var i=0;i=this.size()){throw new Error("Tried to read from index "+index+", but array size is: "+this.size())}var tensorWithState=this.tensors[index];if(tensorWithState.cleared){throw new Error("TensorArray "+this.name+": Could not read index "+index+" twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).")}if(this.clearAfterRead){tensorWithState.cleared=true}tensorWithState.read=true;return tensorWithState.tensor};TensorArray2.prototype.readMany=function(indices){var _this2=this;return indices.map(function(index){return _this2.read(index)})};TensorArray2.prototype.write=function(index,tensor){if(this.closed_){throw new Error("TensorArray "+this.name+" has already been closed.")}if(index<0||!this.dynamicSize&&index>=this.maxSize){throw new Error("Tried to write to index "+index+", but array is not resizeable and size is: "+this.maxSize)}var t=this.tensors[index]||{};if(tensor.dtype!==this.dtype){throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+index+",\n because the value dtype is "+tensor.dtype+", but TensorArray dtype is "+this.dtype+".")}if(this.size()===0&&(this.elementShape==null||this.elementShape.length===0)){this.elementShape=tensor.shape}assertShapesMatchAllowUndefinedSize(this.elementShape,tensor.shape,"TensorArray "+this.name+": Could not write to TensorArray index "+index+".");if(t.read){throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+index+", because it has already been read.")}if(t.written){throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+index+", because it has already been written.")}t.tensor=tensor;tfOps.keep(tensor);t.written=true;this.tensors[index]=t};TensorArray2.prototype.writeMany=function(indices,tensors){var _this2=this;if(indices.length!==tensors.length){throw new Error("TensorArray "+this.name+": could not write multiple tensors,"+("because the index size: "+indices.length+" is not the same as tensors size: "+tensors.length+"."))}indices.forEach(function(i,index){return _this2.write(i,tensors[index])})};TensorArray2.prototype.gather=function(indices,dtype){if(!!dtype&&dtype!==this.dtype){throw new Error("TensorArray dtype is "+this.dtype+" but gather requested dtype "+dtype)}if(!indices){indices=[];for(var i=0;i=this.maxSize){throw new Error("Max index must be < array size ("+maxIndex+" vs. "+this.maxSize+")")}this.writeMany(indices,tfOps.unstack(tensor,0))};TensorArray2.prototype.split=function(length,tensor){var _this2=this;if(tensor.dtype!==this.dtype){throw new Error("TensorArray dtype is "+this.dtype+" but tensor has dtype "+tensor.dtype)}var totalLength=0;var cumulativeLengths=length.map(function(len){totalLength+=len;return totalLength});if(totalLength!==tensor.shape[0]){throw new Error("Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n "+totalLength+", and tensor's shape is: "+tensor.shape)}if(!this.dynamicSize&&length.length!==this.maxSize){throw new Error("TensorArray's size is not equal to the size of lengths ("+this.maxSize+" vs. "+length.length+"), and the TensorArray is not marked as dynamically resizeable")}var elementPerRow=totalLength===0?0:tensor.size/totalLength;var tensors=[];tfOps.tidy(function(){tensor=tfOps.reshape(tensor,[1,totalLength,elementPerRow]);for(var i2=0;i2this.maxNumElements){throw new Error("TensorListResize input size "+size+" is greater maxNumElement "+this.maxNumElements+".")}this.tensors.length=size};TensorList2.prototype.getItem=function(elementIndex,elementShape,elementDtype){if(elementDtype!==this.elementDtype){throw new Error("Invalid data types; op elements "+elementDtype+", but list elements "+this.elementDtype)}if(elementIndex<0||elementIndex>this.tensors.length){throw new Error("Trying to access element "+elementIndex+" in a list with "+this.tensors.length+" elements.")}if(this.tensors[elementIndex]==null){throw new Error("element at index "+elementIndex+" is null.")}assertShapesMatchAllowUndefinedSize(this.tensors[elementIndex].shape,elementShape,"TensorList shape mismatch: ");return this.tensors[elementIndex]};TensorList2.prototype.setItem=function(elementIndex,tensor){if(tensor.dtype!==this.elementDtype){throw new Error("Invalid data types; op elements "+tensor.dtype+", but list elements "+this.elementDtype)}if(elementIndex<0||this.maxNumElements!==-1&&elementIndex>=this.maxNumElements){throw new Error("Trying to set element "+elementIndex+" in a list with max "+this.maxNumElements+" elements.")}assertShapesMatchAllowUndefinedSize(this.elementShape,tensor.shape,"TensorList shape mismatch: ");tfOps.keep(tensor);this.tensors[elementIndex]=tensor};TensorList2.prototype.gather=function(indices,elementDtype,elementShape){var _this2=this;if(elementDtype!==this.elementDtype){throw new Error("Invalid data types; op elements "+elementDtype+", but list elements "+this.elementDtype)}assertShapesMatchAllowUndefinedSize(this.elementShape,elementShape,"TensorList shape mismatch: ");indices=indices.slice(0,this.size());if(indices.length===0){return tfOps.tensor([],[0].concat(this.elementShape))}return tfOps.tidy(function(){var tensors=indices.map(function(i){return tfOps.reshape(_this2.tensors[i],elementShape)});return tfOps.stack(tensors,0)})};TensorList2.prototype.concat=function(elementDtype,elementShape){var _this2=this;if(!!elementDtype&&elementDtype!==this.elementDtype){throw new Error("TensorList dtype is "+this.elementDtype+" but concat requested dtype "+elementDtype)}assertShapesMatchAllowUndefinedSize(this.elementShape,elementShape,"TensorList shape mismatch: ");if(this.size()===0){return tfOps.tensor([],[0].concat(this.elementShape))}return tfOps.tidy(function(){var tensors=_this2.tensors.map(function(t){return tfOps.reshape(t,elementShape)});return tfOps.concat(tensors,0)})};return TensorList2}();function fromTensor(tensor,elementShape,elementDtype){var dtype=tensor.dtype;if(tensor.shape.length<1){throw new Error("Tensor must be at least a vector, but saw shape: "+tensor.shape)}if(tensor.dtype!==elementDtype){throw new Error("Invalid data types; op elements "+tensor.dtype+", but list elements "+elementDtype)}var outputShape=tensor.shape.slice(1);assertShapesMatchAllowUndefinedSize(outputShape,elementShape,"TensorList shape mismatch: ");var tensorList=tfOps.unstack(tensor);return new TensorList(tensorList,elementShape,dtype)}function reserve(elementShape,elementDtype,numElements){return new TensorList([],elementShape,elementDtype,numElements)}function scatter(tensor,indices,elementShape,numElements){if(indices.length!==tensor.shape[0]){throw new Error("Expected len(indices) == tensor.shape[0], but saw: "+indices.length+" vs. "+tensor.shape[0])}var maxIndex=Math.max.apply(Math,__spread(indices));if(numElements!=null&&numElements!==-1&&maxIndex>=numElements){throw new Error("Max index must be < array size ("+maxIndex+" vs. "+numElements+")")}var list=new TensorList([],elementShape,tensor.dtype,numElements);var tensors=tfOps.unstack(tensor,0);indices.forEach(function(value,index){list.setItem(value,tensors[index])});return list}function split2(tensor,length,elementShape){var totalLength=0;var cumulativeLengths=length.map(function(len){totalLength+=len;return totalLength});if(totalLength!==tensor.shape[0]){throw new Error("Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n "+totalLength+", and tensor's shape is: "+tensor.shape)}var elementPerRow=totalLength===0?0:tensor.size/totalLength;var tensors=tfOps.tidy(function(){var tensors2=[];tensor=tfOps.reshape(tensor,[1,totalLength,elementPerRow]);for(var i2=0;i21){this.contexts=this.contexts.slice();this.contexts.splice(-1);this.currentContextIds.shift()}else{throw new Error("Cannot exit frame, the context is empty")}};ExecutionContext2.prototype.nextIteration=function(){if(this.contexts&&this.contexts.length>0){this.contexts=this.contexts.slice();this.lastId++;var context=Object.assign({},this.contexts[this.contexts.length-1]);context.iterationId+=1;context.id=this.lastId;this.contexts.splice(-1,1,context);this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))}else{throw new Error("Cannot increase frame iteration, the context is empty")}};ExecutionContext2.prototype.getWeight=function(name){return this.weightMap[name]};ExecutionContext2.prototype.addTensorArray=function(tensorArray){this.tensorArrayMap[tensorArray.id]=tensorArray};ExecutionContext2.prototype.getTensorArray=function(id){return this.tensorArrayMap[id]};ExecutionContext2.prototype.addTensorList=function(tensorList){this.tensorListMap[tensorList.id]=tensorList};ExecutionContext2.prototype.getTensorList=function(id){return this.tensorListMap[id]};ExecutionContext2.prototype.dispose=function(keepIds){for(var key in this.tensorArrayMap){this.tensorArrayMap[key].clearAndClose(keepIds)}for(var key in this.tensorListMap){this.tensorListMap[key].clearAndClose(keepIds)}};return ExecutionContext2}();function getExecutionSubgraph(inputs,outputs,weightMap,initNodes){var usedNodes=new Set;var missingInputs=[];var dynamicNode=null;var syncInputs=null;var seen=new Set;var inputNodeNames=Object.keys(inputs).map(function(name){return parseNodeName(name)[0]});var initNodeNames=[];if(initNodes!=null){initNodeNames=initNodes.map(function(node2){return parseNodeName(node2.name)[0]})}var frontier=__spread(outputs);while(frontier.length>0){var node=frontier.pop();if(isControlFlow(node)||isDynamicShape(node)||isHashTable(node)){if(dynamicNode==null){dynamicNode=node;syncInputs=dynamicNode.children.map(function(child){return child.name}).filter(function(name){return usedNodes.has(name)})}}usedNodes.add(node.name);if(weightMap[node.name]!=null){continue}if(inputNodeNames.indexOf(node.name)!==-1){continue}if(initNodeNames.indexOf(node.name)!==-1){continue}if(node.inputs.length===0){missingInputs.push(node.name);continue}node.inputs.forEach(function(input){if(seen.has(input.name)){return}seen.add(input.name);frontier.push(input)})}return{inputs,outputs,usedNodes,missingInputs,dynamicNode,syncInputs}}function getNodesInTopologicalOrder(graph2,weightMap,executionInfo){var usedNodes=executionInfo.usedNodes,inputs=executionInfo.inputs;var frontier=[];var inputNodes=Object.keys(inputs).map(function(name){return parseNodeName(name)[0]}).map(function(name){return graph2.nodes[name]});var initNodes=graph2.initNodes;inputNodes.forEach(function(input){if(usedNodes.has(input.name)){frontier.push(input)}});graph2.weights.forEach(function(weight){if(usedNodes.has(weight.name)){frontier.push(weight)}});if(initNodes!=null){initNodes.forEach(function(node2){if(usedNodes.has(node2.name)){frontier.push(node2)}})}var seen=new Set;var orderedNodes=[];while(frontier.length>0){var node=frontier.pop();seen.add(node.name);if(!weightMap[node.name]){orderedNodes.push(node)}node.children.forEach(function(child){if(!seen.has(child.name)&&usedNodes.has(child.name)&&child.inputs.every(function(input){return seen.has(input.name)})){frontier.push(child)}})}return orderedNodes}var CONTROL_FLOW_OPS=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"];var DYNAMIC_SHAPE_OPS=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"];var HASH_TABLE_OPS=["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2"];function isControlFlow(node){return CONTROL_FLOW_OPS.indexOf(node.op)>=0}function isDynamicShape(node){return DYNAMIC_SHAPE_OPS.indexOf(node.op)>=0}function isHashTable(node){return HASH_TABLE_OPS.indexOf(node.op)>=0}var GraphExecutor=function(){function GraphExecutor2(graph2,parent){var _this2=this;this.graph=graph2;this.parent=parent;this.compiledMap=new Map;this._weightMap={};this.SEPERATOR=",";this._functions={};this._functionExecutorMap={};this._outputs=graph2.outputs;this._inputs=graph2.inputs;this._initNodes=graph2.initNodes;this._signature=graph2.signature;this._functions=graph2.functions;if(graph2.functions!=null){Object.keys(graph2.functions).forEach(function(name){_this2._functionExecutorMap[name]=new GraphExecutor2(graph2.functions[name],_this2)})}}Object.defineProperty(GraphExecutor2.prototype,"weightIds",{get:function(){return this.parent?this.parent.weightIds:this._weightIds},enumerable:true,configurable:true});Object.defineProperty(GraphExecutor2.prototype,"functionExecutorMap",{get:function(){return this.parent?this.parent.functionExecutorMap:this._functionExecutorMap},enumerable:true,configurable:true});Object.defineProperty(GraphExecutor2.prototype,"weightMap",{get:function(){return this.parent?this.parent.weightMap:this._weightMap},set:function(weightMap){var weightIds=Object.keys(weightMap).map(function(key){return weightMap[key].map(function(tensor){return tensor.id})});this._weightIds=[].concat.apply([],__spread(weightIds));this._weightMap=weightMap},enumerable:true,configurable:true});Object.defineProperty(GraphExecutor2.prototype,"resourceManager",{set:function(resourceManager){this._resourceManager=resourceManager},enumerable:true,configurable:true});Object.defineProperty(GraphExecutor2.prototype,"inputs",{get:function(){return this._inputs.map(function(node){return{name:node.name,shape:node.attrParams["shape"]?node.attrParams["shape"].value:void 0,dtype:node.attrParams["dtype"]?node.attrParams["dtype"].value:void 0}})},enumerable:true,configurable:true});Object.defineProperty(GraphExecutor2.prototype,"outputs",{get:function(){return this._outputs.map(function(node){return{name:node.name,shape:node.attrParams["shape"]?node.attrParams["shape"].value:void 0,dtype:node.attrParams["dtype"]?node.attrParams["dtype"].value:void 0}})},enumerable:true,configurable:true});Object.defineProperty(GraphExecutor2.prototype,"inputNodes",{get:function(){return this._inputs.map(function(node){return node.signatureKey||node.name})},enumerable:true,configurable:true});Object.defineProperty(GraphExecutor2.prototype,"outputNodes",{get:function(){return this._outputs.map(function(node){var name=node.signatureKey||node.name;return node.defaultOutput?name+":"+node.defaultOutput:name})},enumerable:true,configurable:true});Object.defineProperty(GraphExecutor2.prototype,"functions",{get:function(){var _this2=this;return Object.keys(this._functions).reduce(function(map,key){map[key]=_this2._functions[key].signature;return map},{})},enumerable:true,configurable:true});GraphExecutor2.prototype.getCompilationKey=function(inputs,outputs){var sortedInputs=inputs.map(function(node){return node.name}).sort();var sortedOutputs=outputs.map(function(node){return node.name}).sort();return sortedInputs.join(this.SEPERATOR)+"--"+sortedOutputs.join(this.SEPERATOR)};GraphExecutor2.prototype.compile=function(inputs,outputs){var executionInfo=getExecutionSubgraph(inputs,outputs,this.weightMap,this._initNodes);var missingInputs=executionInfo.missingInputs,dynamicNode=executionInfo.dynamicNode,syncInputs=executionInfo.syncInputs;if(dynamicNode!=null){throw new Error("This execution contains the node '"+dynamicNode.name+"', which has "+("the dynamic op '"+dynamicNode.op+"'. Please use ")+"model.executeAsync() instead. Alternatively, to avoid the "+("dynamic ops, specify the inputs ["+syncInputs+"]"))}if(missingInputs.length>0){var outNames=outputs.map(function(n){return n.name});var inNames=Object.keys(inputs);throw new Error("Cannot compute the outputs ["+outNames+"] from the provided inputs "+("["+inNames+"]. Missing the following inputs: ["+missingInputs+"]"))}return getNodesInTopologicalOrder(this.graph,this.weightMap,executionInfo)};GraphExecutor2.prototype.execute=function(inputs,outputs){var _this2=this;inputs=this.mapInputs(inputs);var names=Object.keys(inputs).sort();this.checkInputs(inputs);this.checkInputShapeAndType(inputs);outputs=this.mapOutputs(outputs);this.checkOutputs(outputs);var inputNodes=names.map(function(name){return _this2.graph.nodes[parseNodeName(name)[0]]});var outputNodeNames=outputs.map(function(name){return parseNodeName(name)[0]});var outputNodes=outputNodeNames.map(function(name){return _this2.graph.nodes[name]});if(outputNodes.length===0){outputNodes=this._outputs}var compilationKey=this.getCompilationKey(inputNodes,outputNodes);var orderedNodes=this.compiledMap.get(compilationKey);if(orderedNodes==null){orderedNodes=this.compile(inputs,outputNodes);this.compiledMap.set(compilationKey,orderedNodes)}var tensorArrayMap={};var tensorListMap={};return tfOps.tidy(function(){var context=new ExecutionContext(_this2.weightMap,tensorArrayMap,tensorListMap,_this2.functionExecutorMap);var tensorsMap=__assign({},_this2.weightMap);Object.keys(inputs).forEach(function(name){var _a=__read(parseNodeName(name),2),nodeName=_a[0],index=_a[1];var tensors2=[];tensors2[index]=inputs[name];tensorsMap[nodeName]=tensors2});var tensorsToKeep=_this2.getFrozenTensorIds(tensorsMap);var intermediateTensorConsumerCount={};for(var i=0;i0))return[3,3];promises=this.processStack(inputNodes,stack,context,tensorsMap,added,tensorsToKeep,outputNodeNames,intermediateTensorConsumerCount,usedNodes);return[4,Promise.all(promises)];case 2:_b.sent();return[3,1];case 3:if(dynamicNode==null&&!isFunctionExecution){console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.")}missingOutputs=outputNodes.filter(function(node){return!isControlFlow(node)&&!getTensor(node.name,tensorsMap,context)}).map(function(node){return node.name});if(missingOutputs.length>0){alternativeMsg="";if(dynamicNode!=null){alternativeMsg="Alternatively, to avoid the dynamic ops, use model.execute() "+("and specify the inputs ["+syncInputs+"]")}throw new Error("Cannot compute the outputs ["+missingOutputs+"] from the provided "+("inputs ["+names+"]. Consider providing the following inputs: ")+("["+missingInputs+"]. "+alternativeMsg))}return[2,tensorsMap]}})})};GraphExecutor2.prototype.processStack=function(inputNodes,stack,context,tensorMap,added,tensorsToKeep,outputNames,intermediateTensorConsumerCount,usedNodes){var _this2=this;var promises=[];var _loop_1=function(){var _a,_b;var item=stack.pop();context.currentContext=item.contexts;var nodeName="";if(item.node.op==="Enter"&&getParamValue("isConstant",item.node,tensorMap,context)){_a=__read(getNodeNameAndIndex(item.node.name,context),1),nodeName=_a[0]}if(tensorMap[item.node.name]==null){var tensors=executeOp$h(item.node,tensorMap,context,this_1._resourceManager);if(!nodeName){_b=__read(getNodeNameAndIndex(item.node.name,context),1),nodeName=_b[0]}var currentContext_1=context.currentContext;if(tfOps.util.isPromise(tensors)){promises.push(tensors.then(function(t){tensorMap[nodeName]=t;context.currentContext=currentContext_1;_this2.checkTensorForDisposal(nodeName,item.node,tensorMap,context,tensorsToKeep,outputNames,intermediateTensorConsumerCount);_this2.processChildNodes(item.node,stack,context,tensorMap,added,usedNodes);return t}))}else{tensorMap[nodeName]=tensors;this_1.checkTensorForDisposal(nodeName,item.node,tensorMap,context,tensorsToKeep,outputNames,intermediateTensorConsumerCount);this_1.processChildNodes(item.node,stack,context,tensorMap,added,usedNodes)}}else{this_1.processChildNodes(item.node,stack,context,tensorMap,added,usedNodes)}};var this_1=this;while(stack.length>0){_loop_1()}return promises};GraphExecutor2.prototype.processChildNodes=function(node,stack,context,tensorMap,added,usedNodes){node.children.forEach(function(childNode){var _a=__read(getNodeNameAndIndex(childNode.name,context),1),nodeName=_a[0];if(added[nodeName]||!usedNodes.has(childNode.name)){return}if(childNode.op==="Merge"){if(childNode.inputNames.some(function(name){return!!getTensor(name,tensorMap,context)})){added[nodeName]=true;stack.push({contexts:context.currentContext,node:childNode})}}else if(childNode.inputNames.every(function(name){return!!getTensor(name,tensorMap,context)})){added[nodeName]=true;stack.push({contexts:context.currentContext,node:childNode})}})};GraphExecutor2.prototype.dispose=function(){var _this2=this;Object.keys(this.weightMap).forEach(function(key){return _this2.weightMap[key].forEach(function(tensor){return tensor.dispose()})})};GraphExecutor2.prototype.checkInputShapeAndType=function(inputs){var _this2=this;Object.keys(inputs).forEach(function(name){var input=inputs[name];var _a=__read(parseNodeName(name),1),nodeName=_a[0];var node=_this2.graph.nodes[nodeName];if(node.attrParams["shape"]&&node.attrParams["shape"].value){var shape_1=node.attrParams["shape"].value;var match=shape_1.length===input.shape.length&&input.shape.every(function(dim,index){return shape_1[index]===-1||shape_1[index]===dim});tfOps.util.assert(match,function(){return"The shape of dict['"+node.name+"'] provided in "+("model.execute(dict) must be ["+shape_1+"], but was ")+("["+input.shape+"]")})}if(node.attrParams["dtype"]&&node.attrParams["dtype"].value){tfOps.util.assert(input.dtype===node.attrParams["dtype"].value,function(){return"The dtype of dict['"+node.name+"'] provided in model.execute(dict) must be "+(node.attrParams["dtype"].value+", but was "+input.dtype)})}})};GraphExecutor2.prototype.mapInputs=function(inputs){var result={};for(var inputName in inputs){if(this._signature!=null&&this._signature.inputs!=null&&this._signature.inputs[inputName]!=null){var tensor=this._signature.inputs[inputName];result[tensor.name]=inputs[inputName]}else{result[inputName]=inputs[inputName]}}return result};GraphExecutor2.prototype.checkInputs=function(inputs){var _this2=this;var notInGraph=Object.keys(inputs).filter(function(name){var _a=__read(parseNodeName(name),1),nodeName=_a[0];return _this2.graph.nodes[nodeName]==null});if(notInGraph.length>0){throw new Error("The dict provided in model.execute(dict) has "+("keys: ["+notInGraph+"] that are not part of graph"))}};GraphExecutor2.prototype.mapOutputs=function(outputs){var _this2=this;return outputs.map(function(name){if(_this2._signature!=null&&_this2._signature.outputs!=null&&_this2._signature.outputs[name]!=null){var tensor=_this2._signature.outputs[name];return tensor.name}return name},{})};GraphExecutor2.prototype.checkOutputs=function(outputs){var _this2=this;outputs.forEach(function(name){var _a=__read(parseNodeName(name),1),normalizedName=_a[0];if(!_this2.graph.nodes[normalizedName]){throw new Error("The output '"+name+"' is not found in the graph")}})};return GraphExecutor2}();var ResourceManager=function(){function ResourceManager2(hashTableNameToHandle,hashTableMap){if(hashTableNameToHandle===void 0){hashTableNameToHandle={}}if(hashTableMap===void 0){hashTableMap={}}this.hashTableNameToHandle=hashTableNameToHandle;this.hashTableMap=hashTableMap}ResourceManager2.prototype.addHashTable=function(name,hashTable2){this.hashTableNameToHandle[name]=hashTable2.handle;this.hashTableMap[hashTable2.id]=hashTable2};ResourceManager2.prototype.getHashTableHandleByName=function(name){return this.hashTableNameToHandle[name]};ResourceManager2.prototype.getHashTableById=function(id){return this.hashTableMap[id]};ResourceManager2.prototype.dispose=function(){for(var key in this.hashTableMap){this.hashTableMap[key].clearAndClose();delete this.hashTableMap[key]}for(var name_1 in this.hashTableNameToHandle){this.hashTableNameToHandle[name_1].dispose();delete this.hashTableNameToHandle[name_1]}};return ResourceManager2}();var TFHUB_SEARCH_PARAM="?tfjs-format=file";var DEFAULT_MODEL_NAME="model.json";var GraphModel=function(){function GraphModel2(modelUrl,loadOptions){if(loadOptions===void 0){loadOptions={}}this.modelUrl=modelUrl;this.loadOptions=loadOptions;this.version="n/a";if(loadOptions==null){this.loadOptions={}}this.resourceManager=new ResourceManager}Object.defineProperty(GraphModel2.prototype,"modelVersion",{get:function(){return this.version},enumerable:true,configurable:true});Object.defineProperty(GraphModel2.prototype,"inputNodes",{get:function(){return this.executor.inputNodes},enumerable:true,configurable:true});Object.defineProperty(GraphModel2.prototype,"outputNodes",{get:function(){return this.executor.outputNodes},enumerable:true,configurable:true});Object.defineProperty(GraphModel2.prototype,"inputs",{get:function(){return this.executor.inputs},enumerable:true,configurable:true});Object.defineProperty(GraphModel2.prototype,"outputs",{get:function(){return this.executor.outputs},enumerable:true,configurable:true});Object.defineProperty(GraphModel2.prototype,"weights",{get:function(){return this.executor.weightMap},enumerable:true,configurable:true});GraphModel2.prototype.findIOHandler=function(){var path=this.modelUrl;if(path.load!=null){this.handler=path}else if(this.loadOptions.requestInit!=null){this.handler=tfOps.io.browserHTTPRequest(path,this.loadOptions)}else{var handlers=tfOps.io.getLoadHandlers(path,this.loadOptions);if(handlers.length===0){handlers.push(tfOps.io.browserHTTPRequest(path,this.loadOptions))}else if(handlers.length>1){throw new Error("Found more than one ("+handlers.length+") load handlers for "+("URL '"+[path]+"'"))}this.handler=handlers[0]}};GraphModel2.prototype.load=function(){return __awaiter(this,void 0,void 0,function(){var artifacts;return __generator(this,function(_a){switch(_a.label){case 0:this.findIOHandler();if(this.handler.load==null){throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.")}return[4,this.handler.load()];case 1:artifacts=_a.sent();return[2,this.loadSync(artifacts)]}})})};GraphModel2.prototype.loadSync=function(artifacts){this.artifacts=artifacts;var graph2=this.artifacts.modelTopology;var signature={};if(this.artifacts.userDefinedMetadata!=null){signature=this.artifacts.userDefinedMetadata.signature}this.version=graph2.versions.producer+"."+graph2.versions.minConsumer;var weightMap=tfOps.io.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);this.executor=new GraphExecutor(OperationMapper.Instance.transformGraph(graph2,signature));this.executor.weightMap=this.convertTensorMapToTensorsMap(weightMap);this.executor.resourceManager=this.resourceManager;if(artifacts.modelInitializer!=null){var initializer=OperationMapper.Instance.transformGraph(artifacts.modelInitializer);this.initializer=new GraphExecutor(initializer);this.initializer.weightMap=this.executor.weightMap;this.initializer.resourceManager=this.resourceManager;this.initializer.executeAsync({},[])}return true};GraphModel2.prototype.save=function(handlerOrURL,config2){return __awaiter(this,void 0,void 0,function(){var handlers;return __generator(this,function(_a){if(typeof handlerOrURL==="string"){handlers=tfOps.io.getSaveHandlers(handlerOrURL);if(handlers.length===0){throw new Error("Cannot find any save handlers for URL '"+handlerOrURL+"'")}else if(handlers.length>1){throw new Error("Found more than one ("+handlers.length+") save handlers for "+("URL '"+handlerOrURL+"'"))}handlerOrURL=handlers[0]}if(handlerOrURL.save==null){throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.")}return[2,handlerOrURL.save(this.artifacts)]})})};GraphModel2.prototype.predict=function(inputs,config2){return this.execute(inputs,this.outputNodes)};GraphModel2.prototype.normalizeInputs=function(inputs){if(!(inputs instanceof tfOps.Tensor)&&!Array.isArray(inputs)){return inputs}inputs=Array.isArray(inputs)?inputs:[inputs];if(inputs.length!==this.inputNodes.length){throw new Error("Input tensor count mismatch,"+("the graph model has "+this.inputNodes.length+" placeholders, ")+("while there are "+inputs.length+" input tensors."))}return this.inputNodes.reduce(function(map,inputName,i){map[inputName]=inputs[i];return map},{})};GraphModel2.prototype.normalizeOutputs=function(outputs){outputs=outputs||this.outputNodes;return!Array.isArray(outputs)?[outputs]:outputs};GraphModel2.prototype.execute=function(inputs,outputs){inputs=this.normalizeInputs(inputs);outputs=this.normalizeOutputs(outputs);var result=this.executor.execute(inputs,outputs);return result.length>1?result:result[0]};GraphModel2.prototype.executeAsync=function(inputs,outputs){return __awaiter(this,void 0,void 0,function(){var result;return __generator(this,function(_a){switch(_a.label){case 0:inputs=this.normalizeInputs(inputs);outputs=this.normalizeOutputs(outputs);return[4,this.executor.executeAsync(inputs,outputs)];case 1:result=_a.sent();return[2,result.length>1?result:result[0]]}})})};GraphModel2.prototype.convertTensorMapToTensorsMap=function(map){return Object.keys(map).reduce(function(newMap,key){newMap[key]=[map[key]];return newMap},{})};GraphModel2.prototype.dispose=function(){this.executor.dispose();if(this.initializer){this.initializer.dispose()}this.resourceManager.dispose()};return GraphModel2}();function loadGraphModel(modelUrl,options){if(options===void 0){options={}}return __awaiter(this,void 0,void 0,function(){var model;return __generator(this,function(_a){switch(_a.label){case 0:if(modelUrl==null){throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model")}if(options==null){options={}}if(options.fromTFHub){if(modelUrl.load==null){if(!modelUrl.endsWith("/")){modelUrl=modelUrl+"/"}modelUrl=""+modelUrl+DEFAULT_MODEL_NAME+TFHUB_SEARCH_PARAM}}model=new GraphModel(modelUrl,options);return[4,model.load()];case 1:_a.sent();return[2,model]}})})}var version5="2.7.0";exports2.GraphModel=GraphModel;exports2.deregisterOp=deregisterOp;exports2.loadGraphModel=loadGraphModel;exports2.registerOp=registerOp;exports2.version_converter=version5});var require_tf_data_node=__commonJS(exports2=>{"use strict";Object.defineProperty(exports2,"__esModule",{value:true});var tf4=require_tf_core_node();var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d2,b2){d2.__proto__=b2}||function(d2,b2){for(var p in b2)if(b2.hasOwnProperty(p))d2[p]=b2[p]};return extendStatics(d,b)};function __extends(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}function __awaiter(thisArg,_arguments,P,generator2){return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator2.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator2["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):new P(function(resolve2){resolve2(result.value)}).then(fulfilled,rejected)}step((generator2=generator2.apply(thisArg,_arguments||[])).next())})}function __generator(thisArg,body2){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]>>0;h-=n;h*=n;n=h>>>0;h-=n;n+=h*4294967296}return(n>>>0)*23283064365386963e-26};return mash}if(module4&&module4.exports){module4.exports=impl}else if(define2&&define2.amd){define2(function(){return impl})}else{this.alea=impl}})(commonjsGlobal,module3,false)});var xor128=createCommonjsModule(function(module3){(function(global2,module4,define2){function XorGen(seed){var me=this,strseed="";me.x=0;me.y=0;me.z=0;me.w=0;me.next=function(){var t=me.x^me.x<<11;me.x=me.y;me.y=me.z;me.z=me.w;return me.w^=me.w>>>19^t^t>>>8};if(seed===(seed|0)){me.x=seed}else{strseed+=seed}for(var k=0;k>>0)/4294967296};prng.double=function(){do{var top=xg.next()>>>11,bot=(xg.next()>>>0)/4294967296,result=(top+bot)/(1<<21)}while(result===0);return result};prng.int32=xg.next;prng.quick=prng;if(state){if(typeof state=="object")copy(state,xg);prng.state=function(){return copy(xg,{})}}return prng}if(module4&&module4.exports){module4.exports=impl}else if(define2&&define2.amd){define2(function(){return impl})}else{this.xor128=impl}})(commonjsGlobal,module3,false)});var xorwow=createCommonjsModule(function(module3){(function(global2,module4,define2){function XorGen(seed){var me=this,strseed="";me.next=function(){var t=me.x^me.x>>>2;me.x=me.y;me.y=me.z;me.z=me.w;me.w=me.v;return(me.d=me.d+362437|0)+(me.v=me.v^me.v<<4^(t^t<<1))|0};me.x=0;me.y=0;me.z=0;me.w=0;me.v=0;if(seed===(seed|0)){me.x=seed}else{strseed+=seed}for(var k=0;k>>4}me.next()}}function copy(f,t){t.x=f.x;t.y=f.y;t.z=f.z;t.w=f.w;t.v=f.v;t.d=f.d;return t}function impl(seed,opts){var xg=new XorGen(seed),state=opts&&opts.state,prng=function(){return(xg.next()>>>0)/4294967296};prng.double=function(){do{var top=xg.next()>>>11,bot=(xg.next()>>>0)/4294967296,result=(top+bot)/(1<<21)}while(result===0);return result};prng.int32=xg.next;prng.quick=prng;if(state){if(typeof state=="object")copy(state,xg);prng.state=function(){return copy(xg,{})}}return prng}if(module4&&module4.exports){module4.exports=impl}else if(define2&&define2.amd){define2(function(){return impl})}else{this.xorwow=impl}})(commonjsGlobal,module3,false)});var xorshift7=createCommonjsModule(function(module3){(function(global2,module4,define2){function XorGen(seed){var me=this;me.next=function(){var X=me.x,i=me.i,t,v;t=X[i];t^=t>>>7;v=t^t<<24;t=X[i+1&7];v^=t^t>>>10;t=X[i+3&7];v^=t^t>>>3;t=X[i+4&7];v^=t^t<<7;t=X[i+7&7];t=t^t<<13;v^=t^t<<9;X[i]=v;me.i=i+1&7;return v};function init2(me2,seed2){var j,w,X=[];if(seed2===(seed2|0)){w=X[0]=seed2}else{seed2=""+seed2;for(j=0;j0;--j){me2.next()}}init2(me,seed)}function copy(f,t){t.x=f.x.slice();t.i=f.i;return t}function impl(seed,opts){if(seed==null)seed=+new Date;var xg=new XorGen(seed),state=opts&&opts.state,prng=function(){return(xg.next()>>>0)/4294967296};prng.double=function(){do{var top=xg.next()>>>11,bot=(xg.next()>>>0)/4294967296,result=(top+bot)/(1<<21)}while(result===0);return result};prng.int32=xg.next;prng.quick=prng;if(state){if(state.x)copy(state,xg);prng.state=function(){return copy(xg,{})}}return prng}if(module4&&module4.exports){module4.exports=impl}else if(define2&&define2.amd){define2(function(){return impl})}else{this.xorshift7=impl}})(commonjsGlobal,module3,false)});var xor4096=createCommonjsModule(function(module3){(function(global2,module4,define2){function XorGen(seed){var me=this;me.next=function(){var w=me.w,X=me.X,i=me.i,t,v;me.w=w=w+1640531527|0;v=X[i+34&127];t=X[i=i+1&127];v^=v<<13;t^=t<<17;v^=v>>>15;t^=t>>>12;v=X[i]=v^t;me.i=i;return v+(w^w>>>16)|0};function init2(me2,seed2){var t,v,i,j,w,X=[],limit=128;if(seed2===(seed2|0)){v=seed2;seed2=null}else{seed2=seed2+"\0";v=0;limit=Math.max(limit,seed2.length)}for(i=0,j=-32;j>>15;v^=v<<4;v^=v>>>13;if(j>=0){w=w+1640531527|0;t=X[j&127]^=v+w;i=t==0?i+1:0}}if(i>=128){X[(seed2&&seed2.length||0)&127]=-1}i=127;for(j=4*128;j>0;--j){v=X[i+34&127];t=X[i=i+1&127];v^=v<<13;t^=t<<17;v^=v>>>15;t^=t>>>12;X[i]=v^t}me2.w=w;me2.X=X;me2.i=i}init2(me,seed)}function copy(f,t){t.i=f.i;t.w=f.w;t.X=f.X.slice();return t}function impl(seed,opts){if(seed==null)seed=+new Date;var xg=new XorGen(seed),state=opts&&opts.state,prng=function(){return(xg.next()>>>0)/4294967296};prng.double=function(){do{var top=xg.next()>>>11,bot=(xg.next()>>>0)/4294967296,result=(top+bot)/(1<<21)}while(result===0);return result};prng.int32=xg.next;prng.quick=prng;if(state){if(state.X)copy(state,xg);prng.state=function(){return copy(xg,{})}}return prng}if(module4&&module4.exports){module4.exports=impl}else if(define2&&define2.amd){define2(function(){return impl})}else{this.xor4096=impl}})(commonjsGlobal,module3,false)});var tychei=createCommonjsModule(function(module3){(function(global2,module4,define2){function XorGen(seed){var me=this,strseed="";me.next=function(){var b=me.b,c=me.c,d=me.d,a=me.a;b=b<<25^b>>>7^c;c=c-d|0;d=d<<24^d>>>8^a;a=a-b|0;me.b=b=b<<20^b>>>12^c;me.c=c=c-d|0;me.d=d<<16^c>>>16^a;return me.a=a-b|0};me.a=0;me.b=0;me.c=2654435769|0;me.d=1367130551;if(seed===Math.floor(seed)){me.a=seed/4294967296|0;me.b=seed|0}else{strseed+=seed}for(var k=0;k>>0)/4294967296};prng.double=function(){do{var top=xg.next()>>>11,bot=(xg.next()>>>0)/4294967296,result=(top+bot)/(1<<21)}while(result===0);return result};prng.int32=xg.next;prng.quick=prng;if(state){if(typeof state=="object")copy(state,xg);prng.state=function(){return copy(xg,{})}}return prng}if(module4&&module4.exports){module4.exports=impl}else if(define2&&define2.amd){define2(function(){return impl})}else{this.tychei=impl}})(commonjsGlobal,module3,false)});var seedrandom=createCommonjsModule(function(module3){(function(pool,math){var global2=this,width=256,chunks=6,digits=52,rngname="random",startdenom=math.pow(width,chunks),significance=math.pow(2,digits),overflow=significance*2,mask=width-1,nodecrypto;function seedrandom2(seed,options,callback){var key=[];options=options==true?{entropy:true}:options||{};var shortseed=mixkey(flatten(options.entropy?[seed,tostring(pool)]:seed==null?autoseed():seed,3),key);var arc4=new ARC4(key);var prng=function(){var n=arc4.g(chunks),d=startdenom,x=0;while(n=overflow){n/=2;d/=2;x>>>=1}return(n+x)/d};prng.int32=function(){return arc4.g(4)|0};prng.quick=function(){return arc4.g(4)/4294967296};prng.double=prng;mixkey(tostring(arc4.S),pool);return(options.pass||callback||function(prng2,seed2,is_math_call,state){if(state){if(state.S){copy(state,arc4)}prng2.state=function(){return copy(arc4,{})}}if(is_math_call){math[rngname]=prng2;return seed2}else return prng2})(prng,shortseed,"global"in options?options.global:this==math,options.state)}math["seed"+rngname]=seedrandom2;function ARC4(key){var t,keylen=key.length,me=this,i=0,j=me.i=me.j=0,s=me.S=[];if(!keylen){key=[keylen++]}while(i=this.items.length){return[2,{value:null,done:true}]}item=this.items[this.trav];this.trav++;return[2,{value:deepClone(item),done:false}]})})};return ArrayIterator2}(LazyIterator);var FunctionCallIterator=function(_super){__extends(FunctionCallIterator2,_super);function FunctionCallIterator2(nextFn){var _this=_super.call(this)||this;_this.nextFn=nextFn;return _this}FunctionCallIterator2.prototype.summary=function(){return"Function call"};FunctionCallIterator2.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){try{return[2,this.nextFn()]}catch(e){e.message="Error thrown while iterating through a dataset: "+e.message;throw e}return[2]})})};return FunctionCallIterator2}(LazyIterator);var SerialIterator=function(_super){__extends(SerialIterator2,_super);function SerialIterator2(upstream){var _this=_super.call(this)||this;_this.upstream=upstream;_this.lastRead=Promise.resolve({value:null,done:false});return _this}SerialIterator2.prototype.summary=function(){return this.upstream.summary()+" -> Serial"};SerialIterator2.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){var _this=this;return __generator(this,function(_a){this.lastRead=this.lastRead.then(function(){return _this.serialNext()});return[2,this.lastRead]})})};SerialIterator2.prototype.serialNext=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){return[2,this.upstream.next()]})})};return SerialIterator2}(LazyIterator);var SkipIterator=function(_super){__extends(SkipIterator2,_super);function SkipIterator2(upstream,maxCount){var _this=_super.call(this)||this;_this.upstream=upstream;_this.maxCount=maxCount;_this.count=0;_this.lastRead=Promise.resolve({value:null,done:false});return _this}SkipIterator2.prototype.summary=function(){return this.upstream.summary()+" -> Skip"};SkipIterator2.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){var _this=this;return __generator(this,function(_a){this.lastRead=this.lastRead.then(function(){return _this.serialNext()});return[2,this.lastRead]})})};SkipIterator2.prototype.serialNext=function(){return __awaiter(this,void 0,void 0,function(){var skipped;return __generator(this,function(_a){switch(_a.label){case 0:if(!(this.count++ Take"};TakeIterator2.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){if(this.count++>=this.maxCount){return[2,{value:null,done:true}]}return[2,this.upstream.next()]})})};return TakeIterator2}(LazyIterator);var RowMajorBatchIterator=function(_super){__extends(RowMajorBatchIterator2,_super);function RowMajorBatchIterator2(upstream,batchSize,enableSmallLastBatch){if(enableSmallLastBatch===void 0){enableSmallLastBatch=true}var _this=_super.call(this)||this;_this.upstream=upstream;_this.batchSize=batchSize;_this.enableSmallLastBatch=enableSmallLastBatch;_this.lastRead=Promise.resolve({value:null,done:false});return _this}RowMajorBatchIterator2.prototype.summary=function(){return this.upstream.summary()+" -> RowMajorBatch"};RowMajorBatchIterator2.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){var _this=this;return __generator(this,function(_a){this.lastRead=this.lastRead.then(function(){return _this.serialNext()});return[2,this.lastRead]})})};RowMajorBatchIterator2.prototype.serialNext=function(){return __awaiter(this,void 0,void 0,function(){var batch,item;return __generator(this,function(_a){switch(_a.label){case 0:batch=[];_a.label=1;case 1:if(!(batch.length0){return[2,{value:batch,done:false}]}return[2,{value:null,done:true}]}batch.push(item.value);return[3,1];case 3:return[2,{value:batch,done:false}]}})})};return RowMajorBatchIterator2}(LazyIterator);var FilterIterator=function(_super){__extends(FilterIterator2,_super);function FilterIterator2(upstream,predicate){var _this=_super.call(this)||this;_this.upstream=upstream;_this.predicate=predicate;_this.lastRead=Promise.resolve({value:null,done:false});return _this}FilterIterator2.prototype.summary=function(){return this.upstream.summary()+" -> Filter"};FilterIterator2.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){var _this=this;return __generator(this,function(_a){this.lastRead=this.lastRead.then(function(){return _this.serialNext()});return[2,this.lastRead]})})};FilterIterator2.prototype.serialNext=function(){return __awaiter(this,void 0,void 0,function(){var item;return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.upstream.next()];case 1:item=_a.sent();if(item.done||this.predicate(item.value)){return[2,item]}tf4.dispose(item.value);return[3,0];case 2:return[2]}})})};return FilterIterator2}(LazyIterator);var MapIterator=function(_super){__extends(MapIterator2,_super);function MapIterator2(upstream,transform){var _this=_super.call(this)||this;_this.upstream=upstream;_this.transform=transform;return _this}MapIterator2.prototype.summary=function(){return this.upstream.summary()+" -> Map"};MapIterator2.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){var item,inputTensors,mapped,outputTensors,_i,inputTensors_1,t;return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.upstream.next()];case 1:item=_a.sent();if(item.done){return[2,{value:null,done:true}]}inputTensors=tf4.tensor_util.getTensorsInContainer(item.value);mapped=this.transform(item.value);outputTensors=tf4.tensor_util.getTensorsInContainer(mapped);for(_i=0,inputTensors_1=inputTensors;_i handleErrors"};ErrorHandlingLazyIterator2.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){var _this=this;return __generator(this,function(_a){this.lastRead=this.lastRead.then(function(){return _this.serialNext()});return[2,this.lastRead]})})};ErrorHandlingLazyIterator2.prototype.serialNext=function(){return __awaiter(this,void 0,void 0,function(){var e_1;return __generator(this,function(_a){switch(_a.label){case 0:_a.label=1;case 1:_a.trys.push([1,3,,4]);return[4,this.upstream.next()];case 2:return[2,_a.sent()];case 3:e_1=_a.sent();if(!this.handler(e_1)){return[2,{value:null,done:true}]}return[3,4];case 4:return[3,0];case 5:return[2]}})})};return ErrorHandlingLazyIterator2}(LazyIterator);var AsyncMapIterator=function(_super){__extends(AsyncMapIterator2,_super);function AsyncMapIterator2(upstream,transform){var _this=_super.call(this)||this;_this.upstream=upstream;_this.transform=transform;return _this}AsyncMapIterator2.prototype.summary=function(){return this.upstream.summary()+" -> AsyncMap"};AsyncMapIterator2.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){var item,inputTensors,mapped,outputTensors,_i,inputTensors_2,t;return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.upstream.next()];case 1:item=_a.sent();if(item.done){return[2,{value:null,done:true}]}inputTensors=tf4.tensor_util.getTensorsInContainer(item.value);return[4,this.transform(item.value)];case 2:mapped=_a.sent();outputTensors=tf4.tensor_util.getTensorsInContainer(mapped);for(_i=0,inputTensors_2=inputTensors;_i Flatmap"};FlatmapIterator2.prototype.pump=function(){return __awaiter(this,void 0,void 0,function(){var item,inputTensors,mappedArray,outputTensors,_i,inputTensors_3,t;return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.upstream.next()];case 1:item=_a.sent();if(item.done){return[2,false]}inputTensors=tf4.tensor_util.getTensorsInContainer(item.value);mappedArray=this.transform(item.value);outputTensors=tf4.tensor_util.getTensorsInContainer(mappedArray);this.outputQueue.pushAll(mappedArray);for(_i=0,inputTensors_3=inputTensors;_i Chained"};ChainedIterator2.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){this.lastRead=this.readFromChain(this.lastRead);return[2,this.lastRead]})})};ChainedIterator2.prototype.readFromChain=function(lastRead){return __awaiter(this,void 0,void 0,function(){var iteratorResult,itemResult;return __generator(this,function(_a){switch(_a.label){case 0:return[4,lastRead];case 1:_a.sent();if(!(this.iterator==null))return[3,3];return[4,this.moreIterators.next()];case 2:iteratorResult=_a.sent();if(iteratorResult.done){return[2,{value:null,done:true}]}this.iterator=iteratorResult.value;if(this.baseErrorHandler!=null){this.iterator=this.iterator.handleErrors(this.baseErrorHandler)}_a.label=3;case 3:return[4,this.iterator.next()];case 4:itemResult=_a.sent();if(itemResult.done){this.iterator=null;return[2,this.readFromChain(lastRead)]}return[2,itemResult]}})})};return ChainedIterator2}(LazyIterator);var ZipMismatchMode;(function(ZipMismatchMode2){ZipMismatchMode2[ZipMismatchMode2["FAIL"]=0]="FAIL";ZipMismatchMode2[ZipMismatchMode2["SHORTEST"]=1]="SHORTEST";ZipMismatchMode2[ZipMismatchMode2["LONGEST"]=2]="LONGEST"})(ZipMismatchMode||(ZipMismatchMode={}));var ZipIterator=function(_super){__extends(ZipIterator2,_super);function ZipIterator2(iterators,mismatchMode){if(mismatchMode===void 0){mismatchMode=ZipMismatchMode.FAIL}var _this=_super.call(this)||this;_this.iterators=iterators;_this.mismatchMode=mismatchMode;_this.count=0;_this.currentPromise=null;return _this}ZipIterator2.prototype.summary=function(){var upstreamSummaries="TODO: fill in upstream of zip summaries";return"{"+upstreamSummaries+"} -> Zip"};ZipIterator2.prototype.nextState=function(afterState){return __awaiter(this,void 0,void 0,function(){function getNext(container){if(container instanceof LazyIterator){var result=container.next();return{value:result.then(function(x){numIterators++;if(x.done){iteratorsDone++}return x.value}),recurse:false}}else{return{value:null,recurse:true}}}var numIterators,iteratorsDone,mapped;return __generator(this,function(_a){switch(_a.label){case 0:return[4,afterState];case 1:_a.sent();numIterators=0;iteratorsDone=0;return[4,deepMapAndAwaitAll(this.iterators,getNext)];case 2:mapped=_a.sent();if(numIterators===iteratorsDone){return[2,{value:null,done:true}]}if(iteratorsDone>0){switch(this.mismatchMode){case ZipMismatchMode.FAIL:throw new Error("Zipped streams should have the same length. "+("Mismatched at element "+this.count+"."));case ZipMismatchMode.SHORTEST:return[2,{value:null,done:true}];case ZipMismatchMode.LONGEST:}}this.count++;return[2,{value:mapped,done:false}]}})})};ZipIterator2.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){this.currentPromise=this.nextState(this.currentPromise);return[2,this.currentPromise]})})};return ZipIterator2}(LazyIterator);var PrefetchIterator=function(_super){__extends(PrefetchIterator2,_super);function PrefetchIterator2(upstream,bufferSize){var _this=_super.call(this)||this;_this.upstream=upstream;_this.bufferSize=bufferSize;_this.buffer=new RingBuffer(bufferSize);return _this}PrefetchIterator2.prototype.summary=function(){return this.upstream.summary()+" -> Prefetch"};PrefetchIterator2.prototype.refill=function(){while(!this.buffer.isFull()){var v=this.upstream.next();this.buffer.push(v)}};PrefetchIterator2.prototype.next=function(){this.refill();return this.buffer.shift()};return PrefetchIterator2}(LazyIterator);var ShuffleIterator=function(_super){__extends(ShuffleIterator2,_super);function ShuffleIterator2(upstream,windowSize,seed){var _this=_super.call(this,upstream,windowSize)||this;_this.upstream=upstream;_this.windowSize=windowSize;_this.upstreamExhausted=false;_this.random=seedrandom_1(seed||tf4.util.now().toString());_this.lastRead=Promise.resolve({value:null,done:false});return _this}ShuffleIterator2.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){var _this=this;return __generator(this,function(_a){this.lastRead=this.lastRead.then(function(){return _this.serialNext()});return[2,this.lastRead]})})};ShuffleIterator2.prototype.randomInt=function(max2){return Math.floor(this.random()*max2)};ShuffleIterator2.prototype.chooseIndex=function(){return this.randomInt(this.buffer.length())};ShuffleIterator2.prototype.serialNext=function(){return __awaiter(this,void 0,void 0,function(){var chosenIndex,result;return __generator(this,function(_a){switch(_a.label){case 0:if(!this.upstreamExhausted){this.refill()}_a.label=1;case 1:if(!!this.buffer.isEmpty())return[3,3];chosenIndex=this.chooseIndex();return[4,this.buffer.shuffleExcise(chosenIndex)];case 2:result=_a.sent();if(result.done){this.upstreamExhausted=true}else{this.refill();return[2,result]}return[3,1];case 3:return[2,{value:null,done:true}]}})})};return ShuffleIterator2}(PrefetchIterator);var Dataset=function(){function Dataset2(){this.size=null}Dataset2.prototype.batch=function(batchSize,smallLastBatch){var _this=this;if(smallLastBatch===void 0){smallLastBatch=true}var base=this;tf4.util.assert(batchSize>0,function(){return"batchSize needs to be positive, but it is\n "+batchSize});var size;if(this.size===Infinity||this.size==null){size=this.size}else if(smallLastBatch){size=Math.ceil(this.size/batchSize)}else{size=Math.floor(this.size/batchSize)}return datasetFromIteratorFn(function(){return __awaiter(_this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,base.iterator()];case 1:return[2,_a.sent().columnMajorBatch(batchSize,smallLastBatch,deepBatchConcat)]}})})},size)};Dataset2.prototype.concatenate=function(dataset){var _this=this;var base=this;var size;if(this.size===Infinity||dataset.size===Infinity){size=Infinity}else if(this.size!=null&&dataset.size!=null){size=this.size+dataset.size}else{size=null}return datasetFromIteratorFn(function(){return __awaiter(_this,void 0,void 0,function(){var _a,_b;return __generator(this,function(_c){switch(_c.label){case 0:return[4,base.iterator()];case 1:_b=(_a=_c.sent()).concatenate;return[4,dataset.iterator()];case 2:return[2,_b.apply(_a,[_c.sent()])]}})})},size)};Dataset2.prototype.filter=function(predicate){var _this=this;var base=this;var size;if(this.size===Infinity){size=Infinity}else{size=null}return datasetFromIteratorFn(function(){return __awaiter(_this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,base.iterator()];case 1:return[2,_a.sent().filter(function(x){return tf4.tidy(function(){return predicate(x)})})]}})})},size)};Dataset2.prototype.forEachAsync=function(f){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.iterator()];case 1:return[2,_a.sent().forEachAsync(f)]}})})};Dataset2.prototype.map=function(transform){var _this=this;var base=this;return datasetFromIteratorFn(function(){return __awaiter(_this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,base.iterator()];case 1:return[2,_a.sent().map(function(x){return tf4.tidy(function(){return transform(x)})})]}})})},this.size)};Dataset2.prototype.mapAsync=function(transform){var _this=this;var base=this;return datasetFromIteratorFn(function(){return __awaiter(_this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,base.iterator()];case 1:return[2,_a.sent().mapAsync(transform)]}})})},this.size)};Dataset2.prototype.prefetch=function(bufferSize){var _this=this;if(bufferSize==null){throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.")}var base=this;return datasetFromIteratorFn(function(){return __awaiter(_this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,base.iterator()];case 1:return[2,_a.sent().prefetch(bufferSize)]}})})},this.size)};Dataset2.prototype.repeat=function(count){var _this=this;var base=this;var size;if(this.size!=null&&count>0){size=this.size*count}else if(count===0){size=0}else if(this.size!=null&&(count===void 0||count<0)){size=Infinity}else{size=null}return datasetFromIteratorFn(function(){return __awaiter(_this,void 0,void 0,function(){var iteratorIterator;var _this2=this;return __generator(this,function(_a){iteratorIterator=iteratorFromFunction(function(){return __awaiter(_this2,void 0,void 0,function(){var _a2;return __generator(this,function(_b){switch(_b.label){case 0:_a2={};return[4,base.iterator()];case 1:return[2,(_a2.value=_b.sent(),_a2.done=false,_a2)]}})})});return[2,iteratorFromConcatenated(iteratorIterator.take(count))]})})},size)};Dataset2.prototype.skip=function(count){var _this=this;var base=this;var size;if(this.size!=null&&count>=0&&this.size>=count){size=this.size-count}else if(this.size!=null&&(this.sizecount){size=count}else if(this.size!=null&&this.size<=count){size=this.size}else{size=null}return datasetFromIteratorFn(function(){return __awaiter(_this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,base.iterator()];case 1:return[2,_a.sent().take(count)]}})})},size)};Dataset2.prototype.toArray=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:if(this.size===Infinity){throw new Error("Can not convert infinite data stream to array.")}return[4,this.iterator()];case 1:return[2,_a.sent().toArray()]}})})};Dataset2.prototype.toArrayForTest=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:if(this.size===Infinity){throw new Error("Can not convert infinite data stream to array.")}return[4,this.iterator()];case 1:return[2,_a.sent().toArrayForTest()]}})})};Dataset2.MAX_BUFFER_SIZE=1e4;return Dataset2}();function datasetFromIteratorFn(iteratorFn,size){if(size===void 0){size=null}return new(function(_super){__extends(class_1,_super);function class_1(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.size=size;return _this}class_1.prototype.iterator=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){return[2,iteratorFn()]})})};return class_1}(Dataset))}function array(items){var _this=this;return datasetFromIteratorFn(function(){return __awaiter(_this,void 0,void 0,function(){return __generator(this,function(_a){return[2,iteratorFromItems(items)]})})},items.length)}function zip(datasets){var _this=this;if(!isIterable(datasets)){throw new Error("The argument to zip() must be an object or array.")}var size;if(Array.isArray(datasets)){for(var i=0;i1});tf4.util.assert(duplicateNames.length===0,function(){return"Duplicate column names found: "+duplicateNames.toString()});if(this.columnConfigs){for(_i=0,_a=Object.keys(this.columnConfigs);_i<_a.length;_i++){key=_a[_i];index=this.fullColumnNames.indexOf(key);if(index===-1){throw new Error('The key "'+key+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}}}this.columnNamesValidated=true;return[2]}})})};CSVDataset2.prototype.maybeReadHeaderLine=function(){return __awaiter(this,void 0,void 0,function(){var iter,firstElement,firstLine,headers;return __generator(this,function(_a){switch(_a.label){case 0:if(!this.hasHeader)return[3,3];return[4,this.base.iterator()];case 1:iter=_a.sent();return[4,iter.next()];case 2:firstElement=_a.sent();if(firstElement.done){throw new Error("No data was found for CSV parsing.")}firstLine=firstElement.value;headers=this.parseRow(firstLine,false);return[2,headers];case 3:return[2,null]}})})};CSVDataset2.prototype.iterator=function(){return __awaiter(this,void 0,void 0,function(){var lines;var _this=this;return __generator(this,function(_a){switch(_a.label){case 0:if(!!this.columnNamesValidated)return[3,2];return[4,this.setColumnNames()];case 1:_a.sent();_a.label=2;case 2:return[4,this.base.iterator()];case 3:lines=_a.sent();if(this.hasHeader){lines=lines.skip(1)}return[2,lines.map(function(x){return _this.makeDataElement(x)})]}})})};CSVDataset2.prototype.makeDataElement=function(line){var values=this.parseRow(line);var features={};var labels={};for(var i=0;i14||!Number.isInteger(fftSizeLog2)){throw new Error("Invalid fftSize: it must be a power of 2 between "+("2 to 4 and 2 to 14, but got "+_this.fftSize))}_this.numFrames=microphoneConfig.numFramesPerSpectrogram||43;_this.sampleRateHz=microphoneConfig.sampleRateHz;_this.columnTruncateLength=microphoneConfig.columnTruncateLength||_this.fftSize;_this.audioTrackConstraints=microphoneConfig.audioTrackConstraints;_this.smoothingTimeConstant=microphoneConfig.smoothingTimeConstant||0;_this.includeSpectrogram=microphoneConfig.includeSpectrogram===false?false:true;_this.includeWaveform=microphoneConfig.includeWaveform===true?true:false;if(!_this.includeSpectrogram&&!_this.includeWaveform){throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.")}return _this}MicrophoneIterator2.prototype.summary=function(){return"microphone"};MicrophoneIterator2.create=function(microphoneConfig){if(microphoneConfig===void 0){microphoneConfig={}}return __awaiter(this,void 0,void 0,function(){var microphoneIterator;return __generator(this,function(_a){switch(_a.label){case 0:if(tf4.env().get("IS_NODE")){throw new Error("microphone API is only supported in browser environment.")}microphoneIterator=new MicrophoneIterator2(microphoneConfig);return[4,microphoneIterator.start()];case 1:_a.sent();return[2,microphoneIterator]}})})};MicrophoneIterator2.prototype.start=function(){return __awaiter(this,void 0,void 0,function(){var _a,e_1,ctxConstructor,streamSource;return __generator(this,function(_b){switch(_b.label){case 0:_b.trys.push([0,2,,3]);_a=this;return[4,navigator.mediaDevices.getUserMedia({audio:this.audioTrackConstraints==null?true:this.audioTrackConstraints,video:false})];case 1:_a.stream=_b.sent();return[3,3];case 2:e_1=_b.sent();throw new Error("Error thrown while initializing video stream: "+e_1.message);case 3:if(!this.stream){throw new Error("Could not obtain audio from microphone.")}ctxConstructor=window.AudioContext||window.webkitAudioContext;this.audioContext=new ctxConstructor;if(!this.sampleRateHz){this.sampleRateHz=this.audioContext.sampleRate}else if(this.audioContext.sampleRate!==this.sampleRateHz){throw new Error("Mismatch in sampling rate: "+("Expected: "+this.sampleRateHz+"; ")+("Actual: "+this.audioContext.sampleRate))}streamSource=this.audioContext.createMediaStreamSource(this.stream);this.analyser=this.audioContext.createAnalyser();this.analyser.fftSize=this.fftSize*2;this.analyser.smoothingTimeConstant=this.smoothingTimeConstant;streamSource.connect(this.analyser);this.freqData=new Float32Array(this.fftSize);this.timeData=new Float32Array(this.fftSize);return[2]}})})};MicrophoneIterator2.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){var spectrogramTensor,waveformTensor,audioDataQueue,freqData,timeData;return __generator(this,function(_a){switch(_a.label){case 0:if(this.isClosed){return[2,{value:null,done:true}]}return[4,this.getAudioData()];case 1:audioDataQueue=_a.sent();if(this.includeSpectrogram){freqData=this.flattenQueue(audioDataQueue.freqDataQueue);spectrogramTensor=this.getTensorFromAudioDataArray(freqData,[this.numFrames,this.columnTruncateLength,1])}if(this.includeWaveform){timeData=this.flattenQueue(audioDataQueue.timeDataQueue);waveformTensor=this.getTensorFromAudioDataArray(timeData,[this.numFrames*this.fftSize,1])}return[2,{value:{spectrogram:spectrogramTensor,waveform:waveformTensor},done:false}]}})})};MicrophoneIterator2.prototype.capture=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.next()];case 1:return[2,_a.sent().value]}})})};MicrophoneIterator2.prototype.getAudioData=function(){return __awaiter(this,void 0,void 0,function(){var freqDataQueue,timeDataQueue,currentFrames;var _this=this;return __generator(this,function(_a){freqDataQueue=[];timeDataQueue=[];currentFrames=0;return[2,new Promise(function(resolve){var intervalID=setInterval(function(){if(_this.includeSpectrogram){_this.analyser.getFloatFrequencyData(_this.freqData);if(_this.freqData[0]===-Infinity){resolve({freqDataQueue,timeDataQueue})}freqDataQueue.push(_this.freqData.slice(0,_this.columnTruncateLength))}if(_this.includeWaveform){_this.analyser.getFloatTimeDomainData(_this.timeData);timeDataQueue.push(_this.timeData.slice())}if(++currentFrames===_this.numFrames){clearInterval(intervalID);resolve({freqDataQueue,timeDataQueue})}},_this.fftSize/_this.sampleRateHz*1e3)})]})})};MicrophoneIterator2.prototype.stop=function(){if(!this.isClosed){this.isClosed=true;this.analyser.disconnect();this.audioContext.close();if(this.stream!=null&&this.stream.getTracks().length>0){this.stream.getTracks()[0].stop()}}};MicrophoneIterator2.prototype.toArray=function(){throw new Error("Can not convert infinite audio stream to array.")};MicrophoneIterator2.prototype.getSampleRate=function(){return this.sampleRateHz};MicrophoneIterator2.prototype.flattenQueue=function(queue){var frameSize=queue[0].length;var freqData=new Float32Array(queue.length*frameSize);queue.forEach(function(data2,i){return freqData.set(data2,i*frameSize)});return freqData};MicrophoneIterator2.prototype.getTensorFromAudioDataArray=function(freqData,shape){var vals=new Float32Array(tf4.util.sizeFromShape(shape));vals.set(freqData,vals.length-freqData.length);return tf4.tensor(vals,shape)};return MicrophoneIterator2}(LazyIterator);var WebcamIterator=function(_super){__extends(WebcamIterator2,_super);function WebcamIterator2(webcamVideoElement,webcamConfig){var _this=_super.call(this)||this;_this.webcamVideoElement=webcamVideoElement;_this.webcamConfig=webcamConfig;_this.isClosed=true;_this.resize=false;if(_this.needToResize()){_this.resize=true;_this.cropSize=[_this.webcamConfig.resizeHeight,_this.webcamConfig.resizeWidth];_this.cropBoxInd=tf4.tensor1d([0],"int32");if(_this.webcamConfig.centerCrop){var widthCroppingRatio=_this.webcamConfig.resizeWidth*1/_this.webcamVideoElement.width;var heightCroppingRatio=_this.webcamConfig.resizeHeight*1/_this.webcamVideoElement.height;var widthCropStart=(1-widthCroppingRatio)/2;var heightCropStart=(1-heightCroppingRatio)/2;var widthCropEnd=widthCropStart+widthCroppingRatio;var heightCropEnd=heightCroppingRatio+heightCropStart;_this.cropBox=tf4.tensor2d([heightCropStart,widthCropStart,heightCropEnd,widthCropEnd],[1,4])}else{_this.cropBox=tf4.tensor2d([0,0,1,1],[1,4])}}return _this}WebcamIterator2.prototype.summary=function(){return"webcam"};WebcamIterator2.create=function(webcamVideoElement,webcamConfig){if(webcamConfig===void 0){webcamConfig={}}return __awaiter(this,void 0,void 0,function(){var webcamIterator;return __generator(this,function(_a){switch(_a.label){case 0:if(tf4.env().get("IS_NODE")){throw new Error("tf.data.webcam is only supported in browser environment.")}if(!webcamVideoElement){webcamVideoElement=document.createElement("video");if(!webcamConfig.resizeWidth||!webcamConfig.resizeHeight){throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.")}webcamVideoElement.width=webcamConfig.resizeWidth;webcamVideoElement.height=webcamConfig.resizeHeight}webcamIterator=new WebcamIterator2(webcamVideoElement,webcamConfig);return[4,webcamIterator.start()];case 1:_a.sent();return[2,webcamIterator]}})})};WebcamIterator2.prototype.start=function(){return __awaiter(this,void 0,void 0,function(){var _a,e_1;var _this=this;return __generator(this,function(_b){switch(_b.label){case 0:if(this.webcamConfig.facingMode){tf4.util.assert(this.webcamConfig.facingMode==="user"||this.webcamConfig.facingMode==="environment",function(){return"Invalid webcam facing mode: "+_this.webcamConfig.facingMode+". Please provide 'user' or 'environment'"})}_b.label=1;case 1:_b.trys.push([1,3,,4]);_a=this;return[4,navigator.mediaDevices.getUserMedia({video:{deviceId:this.webcamConfig.deviceId,facingMode:this.webcamConfig.facingMode?this.webcamConfig.facingMode:"user",width:this.webcamVideoElement.width,height:this.webcamVideoElement.height}})];case 2:_a.stream=_b.sent();return[3,4];case 3:e_1=_b.sent();e_1.message="Error thrown while initializing video stream: "+e_1.message;throw e_1;case 4:if(!this.stream){throw new Error("Could not obtain video from webcam.")}try{this.webcamVideoElement.srcObject=this.stream}catch(error){console.log(error);this.webcamVideoElement.src=window.URL.createObjectURL(this.stream)}this.webcamVideoElement.play();this.isClosed=false;return[2,new Promise(function(resolve){_this.webcamVideoElement.onloadedmetadata=function(){resolve()}})]}})})};WebcamIterator2.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){var img;return __generator(this,function(_a){if(this.isClosed){return[2,{value:null,done:true}]}try{img=tf4.browser.fromPixels(this.webcamVideoElement)}catch(e){throw new Error("Error thrown converting video to pixels: "+JSON.stringify(e))}if(this.resize){try{return[2,{value:this.cropAndResizeFrame(img),done:false}]}catch(e){throw new Error("Error thrown cropping the video: "+e.message)}finally{img.dispose()}}else{return[2,{value:img,done:false}]}return[2]})})};WebcamIterator2.prototype.needToResize=function(){if(this.webcamConfig.resizeWidth&&this.webcamConfig.resizeHeight&&(this.webcamVideoElement.width!==this.webcamConfig.resizeWidth||this.webcamVideoElement.height!==this.webcamConfig.resizeHeight)){return true}return false};WebcamIterator2.prototype.cropAndResizeFrame=function(img){var _this=this;return tf4.tidy(function(){var expandedImage=img.toFloat().expandDims(0);var resizedImage;resizedImage=tf4.image.cropAndResize(expandedImage,_this.cropBox,_this.cropBoxInd,_this.cropSize,"bilinear");var shape=resizedImage.shape;return resizedImage.reshape(shape.slice(1))})};WebcamIterator2.prototype.capture=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.next()];case 1:return[2,_a.sent().value]}})})};WebcamIterator2.prototype.stop=function(){var tracks=this.stream.getTracks();tracks.forEach(function(track){return track.stop()});try{this.webcamVideoElement.srcObject=null}catch(error){console.log(error);this.webcamVideoElement.src=null}this.isClosed=true};WebcamIterator2.prototype.toArray=function(){throw new Error("Can not convert infinite video stream to array.")};return WebcamIterator2}(LazyIterator);var DataSource=function(){function DataSource2(){}return DataSource2}();var StringIterator=function(_super){__extends(StringIterator2,_super);function StringIterator2(){return _super!==null&&_super.apply(this,arguments)||this}StringIterator2.prototype.split=function(separator){return new SplitIterator(this,separator)};return StringIterator2}(LazyIterator);var SplitIterator=function(_super){__extends(SplitIterator2,_super);function SplitIterator2(upstream,separator){var _this=_super.call(this)||this;_this.upstream=upstream;_this.impl=new SplitIteratorImpl(upstream,separator);return _this}SplitIterator2.prototype.summary=function(){return this.impl.summary()};SplitIterator2.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){return[2,this.impl.next()]})})};return SplitIterator2}(StringIterator);var SplitIteratorImpl=function(_super){__extends(SplitIteratorImpl2,_super);function SplitIteratorImpl2(upstream,separator){var _this=_super.call(this)||this;_this.upstream=upstream;_this.separator=separator;_this.carryover="";return _this}SplitIteratorImpl2.prototype.summary=function(){return this.upstream.summary()+" -> Split('"+this.separator+"')"};SplitIteratorImpl2.prototype.pump=function(){return __awaiter(this,void 0,void 0,function(){var chunkResult,lines,_i,_a,line;return __generator(this,function(_b){switch(_b.label){case 0:return[4,this.upstream.next()];case 1:chunkResult=_b.sent();if(chunkResult.done){if(this.carryover===""){return[2,false]}this.outputQueue.push(this.carryover);this.carryover="";return[2,true]}lines=chunkResult.value.split(this.separator);lines[0]=this.carryover+lines[0];for(_i=0,_a=lines.slice(0,-1);_i<_a.length;_i++){line=_a[_i];this.outputQueue.push(line)}this.carryover=lines[lines.length-1];return[2,true]}})})};return SplitIteratorImpl2}(OneToManyIterator);var ByteChunkIterator=function(_super){__extends(ByteChunkIterator2,_super);function ByteChunkIterator2(){return _super!==null&&_super.apply(this,arguments)||this}ByteChunkIterator2.prototype.decodeUTF8=function(){return new Utf8Iterator(this)};return ByteChunkIterator2}(LazyIterator);var Utf8Iterator=function(_super){__extends(Utf8Iterator2,_super);function Utf8Iterator2(upstream){var _this=_super.call(this)||this;_this.upstream=upstream;_this.impl=new Utf8IteratorImpl(upstream);return _this}Utf8Iterator2.prototype.summary=function(){return this.impl.summary()};Utf8Iterator2.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){return[2,this.impl.next()]})})};return Utf8Iterator2}(StringIterator);var Utf8IteratorImpl=function(_super){__extends(Utf8IteratorImpl2,_super);function Utf8IteratorImpl2(upstream){var _this=_super.call(this)||this;_this.upstream=upstream;if(tf4.env().get("IS_BROWSER")){_this.decoder=new TextDecoder("utf-8")}else{var StringDecoder=require("string_decoder").StringDecoder;_this.decoder=new StringDecoder("utf8")}return _this}Utf8IteratorImpl2.prototype.summary=function(){return this.upstream.summary()+" -> Utf8"};Utf8IteratorImpl2.prototype.pump=function(){return __awaiter(this,void 0,void 0,function(){var chunkResult,chunk,text;return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.upstream.next()];case 1:chunkResult=_a.sent();if(chunkResult.done){return[2,false]}else{chunk=chunkResult.value}if(tf4.env().get("IS_BROWSER")){text=this.decoder.decode(chunk,{stream:true})}else{text=this.decoder.write(Buffer.from(chunk.buffer))}this.outputQueue.push(text);return[2,true]}})})};return Utf8IteratorImpl2}(OneToManyIterator);var FileChunkIterator=function(_super){__extends(FileChunkIterator2,_super);function FileChunkIterator2(file,options){if(options===void 0){options={}}var _this=_super.call(this)||this;_this.file=file;_this.options=options;tf4.util.assert(file instanceof Uint8Array||(tf4.env().get("IS_BROWSER")?file instanceof File||file instanceof Blob:false),function(){return"FileChunkIterator only supports File, Blob and Uint8Array right now."});_this.offset=options.offset||0;_this.chunkSize=options.chunkSize||1024*1024;return _this}FileChunkIterator2.prototype.summary=function(){return"FileChunks "+this.file};FileChunkIterator2.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){var chunk,_a;var _this=this;return __generator(this,function(_b){switch(_b.label){case 0:if(this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size)){return[2,{value:null,done:true}]}chunk=new Promise(function(resolve,reject){var end=_this.offset+_this.chunkSize;if(_this.file instanceof Uint8Array){resolve(new Uint8Array(_this.file.slice(_this.offset,end)))}else{var fileReader_1=new FileReader;fileReader_1.onload=function(event){var data2=fileReader_1.result;if(data2 instanceof ArrayBuffer){data2=new Uint8Array(data2)}if(!(data2 instanceof Uint8Array)){return reject(new TypeError("FileReader returned unknown type."))}resolve(data2)};fileReader_1.onabort=function(event){return reject(new Error("Aborted"))};fileReader_1.onerror=function(event){return reject(new Error(event.type))};var slice2=_this.file.slice(_this.offset,end);fileReader_1.readAsArrayBuffer(slice2)}_this.offset=end});_a={};return[4,chunk];case 1:return[2,(_a.value=_b.sent(),_a.done=false,_a)]}})})};return FileChunkIterator2}(ByteChunkIterator);function urlChunkIterator(url,options){if(options===void 0){options={}}return __awaiter(this,void 0,void 0,function(){var urlString,requestInit,response,uint8Array,_a;return __generator(this,function(_b){switch(_b.label){case 0:if(typeof url==="string"){urlString=url}else{urlString=url.url;requestInit=getRequestInitFromRequest(url)}return[4,tf4.util.fetch(urlString,requestInit)];case 1:response=_b.sent();if(!response.ok)return[3,3];_a=Uint8Array.bind;return[4,response.arrayBuffer()];case 2:uint8Array=new(_a.apply(Uint8Array,[void 0,_b.sent()]));return[2,new FileChunkIterator(uint8Array,options)];case 3:throw new Error(response.statusText)}})})}var getRequestInitFromRequest=function(request){var init2={method:request.method,headers:request.headers,body:request.body,mode:request.mode,credentials:request.credentials,cache:request.cache,redirect:request.redirect,referrer:request.referrer,integrity:request.integrity};return init2};function isLocalPath(source){return typeof source==="string"&&source.substr(0,7)==="file://"}var FileDataSource=function(_super){__extends(FileDataSource2,_super);function FileDataSource2(input,options){if(options===void 0){options={}}var _this=_super.call(this)||this;_this.input=input;_this.options=options;return _this}FileDataSource2.prototype.iterator=function(){return __awaiter(this,void 0,void 0,function(){var fs;return __generator(this,function(_a){if(isLocalPath(this.input)&&tf4.env().get("IS_NODE")){fs=require("fs");this.input=fs.readFileSync(this.input.substr(7))}return[2,new FileChunkIterator(this.input,this.options)]})})};return FileDataSource2}(DataSource);var URLDataSource=function(_super){__extends(URLDataSource2,_super);function URLDataSource2(url,fileOptions){if(fileOptions===void 0){fileOptions={}}var _this=_super.call(this)||this;_this.url=url;_this.fileOptions=fileOptions;return _this}URLDataSource2.prototype.iterator=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){if(isLocalPath(this.url)){return[2,new FileDataSource(this.url,this.fileOptions).iterator()]}else{return[2,urlChunkIterator(this.url,this.fileOptions)]}})})};return URLDataSource2}(DataSource);function csv(source,csvConfig){if(csvConfig===void 0){csvConfig={}}return new CSVDataset(new URLDataSource(source),csvConfig)}function func(f){var _this=this;var iter=iteratorFromFunction(f);return datasetFromIteratorFn(function(){return __awaiter(_this,void 0,void 0,function(){return __generator(this,function(_a){return[2,iter]})})})}function generator(generator2){var _this=this;return datasetFromIteratorFn(function(){return __awaiter(_this,void 0,void 0,function(){var gen;return __generator(this,function(_a){switch(_a.label){case 0:return[4,generator2()];case 1:gen=_a.sent();return[2,iteratorFromFunction(function(){return gen.next()})]}})})})}function webcam(webcamVideoElement,webcamConfig){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){return[2,WebcamIterator.create(webcamVideoElement,webcamConfig)]})})}function microphone(microphoneConfig){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){return[2,MicrophoneIterator.create(microphoneConfig)]})})}var version5="2.7.0";exports2.CSVDataset=CSVDataset;exports2.Dataset=Dataset;exports2.FileDataSource=FileDataSource;exports2.TextLineDataset=TextLineDataset;exports2.URLDataSource=URLDataSource;exports2.array=array;exports2.csv=csv;exports2.func=func;exports2.generator=generator;exports2.microphone=microphone;exports2.version_data=version5;exports2.webcam=webcam;exports2.zip=zip});var require_alea=__commonJS((exports2,module2)=>{(function(global2,module3,define2){function Alea(seed){var me=this,mash=Mash();me.next=function(){var t=2091639*me.s0+me.c*23283064365386963e-26;me.s0=me.s1;me.s1=me.s2;return me.s2=t-(me.c=t|0)};me.c=1;me.s0=mash(" ");me.s1=mash(" ");me.s2=mash(" ");me.s0-=mash(seed);if(me.s0<0){me.s0+=1}me.s1-=mash(seed);if(me.s1<0){me.s1+=1}me.s2-=mash(seed);if(me.s2<0){me.s2+=1}mash=null}function copy(f,t){t.c=f.c;t.s0=f.s0;t.s1=f.s1;t.s2=f.s2;return t}function impl(seed,opts){var xg=new Alea(seed),state=opts&&opts.state,prng=xg.next;prng.int32=function(){return xg.next()*4294967296|0};prng.double=function(){return prng()+(prng()*2097152|0)*11102230246251565e-32};prng.quick=prng;if(state){if(typeof state=="object")copy(state,xg);prng.state=function(){return copy(xg,{})}}return prng}function Mash(){var n=4022871197;var mash=function(data2){data2=data2.toString();for(var i=0;i>>0;h-=n;h*=n;n=h>>>0;h-=n;n+=h*4294967296}return(n>>>0)*23283064365386963e-26};return mash}if(module3&&module3.exports){module3.exports=impl}else if(define2&&define2.amd){define2(function(){return impl})}else{this.alea=impl}})(exports2,typeof module2=="object"&&module2,typeof define=="function"&&define)});var require_xor128=__commonJS((exports2,module2)=>{(function(global2,module3,define2){function XorGen(seed){var me=this,strseed="";me.x=0;me.y=0;me.z=0;me.w=0;me.next=function(){var t=me.x^me.x<<11;me.x=me.y;me.y=me.z;me.z=me.w;return me.w^=me.w>>>19^t^t>>>8};if(seed===(seed|0)){me.x=seed}else{strseed+=seed}for(var k=0;k>>0)/4294967296};prng.double=function(){do{var top=xg.next()>>>11,bot=(xg.next()>>>0)/4294967296,result=(top+bot)/(1<<21)}while(result===0);return result};prng.int32=xg.next;prng.quick=prng;if(state){if(typeof state=="object")copy(state,xg);prng.state=function(){return copy(xg,{})}}return prng}if(module3&&module3.exports){module3.exports=impl}else if(define2&&define2.amd){define2(function(){return impl})}else{this.xor128=impl}})(exports2,typeof module2=="object"&&module2,typeof define=="function"&&define)});var require_xorwow=__commonJS((exports2,module2)=>{(function(global2,module3,define2){function XorGen(seed){var me=this,strseed="";me.next=function(){var t=me.x^me.x>>>2;me.x=me.y;me.y=me.z;me.z=me.w;me.w=me.v;return(me.d=me.d+362437|0)+(me.v=me.v^me.v<<4^(t^t<<1))|0};me.x=0;me.y=0;me.z=0;me.w=0;me.v=0;if(seed===(seed|0)){me.x=seed}else{strseed+=seed}for(var k=0;k>>4}me.next()}}function copy(f,t){t.x=f.x;t.y=f.y;t.z=f.z;t.w=f.w;t.v=f.v;t.d=f.d;return t}function impl(seed,opts){var xg=new XorGen(seed),state=opts&&opts.state,prng=function(){return(xg.next()>>>0)/4294967296};prng.double=function(){do{var top=xg.next()>>>11,bot=(xg.next()>>>0)/4294967296,result=(top+bot)/(1<<21)}while(result===0);return result};prng.int32=xg.next;prng.quick=prng;if(state){if(typeof state=="object")copy(state,xg);prng.state=function(){return copy(xg,{})}}return prng}if(module3&&module3.exports){module3.exports=impl}else if(define2&&define2.amd){define2(function(){return impl})}else{this.xorwow=impl}})(exports2,typeof module2=="object"&&module2,typeof define=="function"&&define)});var require_xorshift7=__commonJS((exports2,module2)=>{(function(global2,module3,define2){function XorGen(seed){var me=this;me.next=function(){var X=me.x,i=me.i,t,v,w;t=X[i];t^=t>>>7;v=t^t<<24;t=X[i+1&7];v^=t^t>>>10;t=X[i+3&7];v^=t^t>>>3;t=X[i+4&7];v^=t^t<<7;t=X[i+7&7];t=t^t<<13;v^=t^t<<9;X[i]=v;me.i=i+1&7;return v};function init2(me2,seed2){var j,w,X=[];if(seed2===(seed2|0)){w=X[0]=seed2}else{seed2=""+seed2;for(j=0;j0;--j){me2.next()}}init2(me,seed)}function copy(f,t){t.x=f.x.slice();t.i=f.i;return t}function impl(seed,opts){if(seed==null)seed=+new Date;var xg=new XorGen(seed),state=opts&&opts.state,prng=function(){return(xg.next()>>>0)/4294967296};prng.double=function(){do{var top=xg.next()>>>11,bot=(xg.next()>>>0)/4294967296,result=(top+bot)/(1<<21)}while(result===0);return result};prng.int32=xg.next;prng.quick=prng;if(state){if(state.x)copy(state,xg);prng.state=function(){return copy(xg,{})}}return prng}if(module3&&module3.exports){module3.exports=impl}else if(define2&&define2.amd){define2(function(){return impl})}else{this.xorshift7=impl}})(exports2,typeof module2=="object"&&module2,typeof define=="function"&&define)});var require_xor4096=__commonJS((exports2,module2)=>{(function(global2,module3,define2){function XorGen(seed){var me=this;me.next=function(){var w=me.w,X=me.X,i=me.i,t,v;me.w=w=w+1640531527|0;v=X[i+34&127];t=X[i=i+1&127];v^=v<<13;t^=t<<17;v^=v>>>15;t^=t>>>12;v=X[i]=v^t;me.i=i;return v+(w^w>>>16)|0};function init2(me2,seed2){var t,v,i,j,w,X=[],limit=128;if(seed2===(seed2|0)){v=seed2;seed2=null}else{seed2=seed2+"\0";v=0;limit=Math.max(limit,seed2.length)}for(i=0,j=-32;j>>15;v^=v<<4;v^=v>>>13;if(j>=0){w=w+1640531527|0;t=X[j&127]^=v+w;i=t==0?i+1:0}}if(i>=128){X[(seed2&&seed2.length||0)&127]=-1}i=127;for(j=4*128;j>0;--j){v=X[i+34&127];t=X[i=i+1&127];v^=v<<13;t^=t<<17;v^=v>>>15;t^=t>>>12;X[i]=v^t}me2.w=w;me2.X=X;me2.i=i}init2(me,seed)}function copy(f,t){t.i=f.i;t.w=f.w;t.X=f.X.slice();return t};function impl(seed,opts){if(seed==null)seed=+new Date;var xg=new XorGen(seed),state=opts&&opts.state,prng=function(){return(xg.next()>>>0)/4294967296};prng.double=function(){do{var top=xg.next()>>>11,bot=(xg.next()>>>0)/4294967296,result=(top+bot)/(1<<21)}while(result===0);return result};prng.int32=xg.next;prng.quick=prng;if(state){if(state.X)copy(state,xg);prng.state=function(){return copy(xg,{})}}return prng}if(module3&&module3.exports){module3.exports=impl}else if(define2&&define2.amd){define2(function(){return impl})}else{this.xor4096=impl}})(exports2,typeof module2=="object"&&module2,typeof define=="function"&&define)});var require_tychei=__commonJS((exports2,module2)=>{(function(global2,module3,define2){function XorGen(seed){var me=this,strseed="";me.next=function(){var b=me.b,c=me.c,d=me.d,a=me.a;b=b<<25^b>>>7^c;c=c-d|0;d=d<<24^d>>>8^a;a=a-b|0;me.b=b=b<<20^b>>>12^c;me.c=c=c-d|0;me.d=d<<16^c>>>16^a;return me.a=a-b|0};me.a=0;me.b=0;me.c=2654435769|0;me.d=1367130551;if(seed===Math.floor(seed)){me.a=seed/4294967296|0;me.b=seed|0}else{strseed+=seed}for(var k=0;k>>0)/4294967296};prng.double=function(){do{var top=xg.next()>>>11,bot=(xg.next()>>>0)/4294967296,result=(top+bot)/(1<<21)}while(result===0);return result};prng.int32=xg.next;prng.quick=prng;if(state){if(typeof state=="object")copy(state,xg);prng.state=function(){return copy(xg,{})}}return prng}if(module3&&module3.exports){module3.exports=impl}else if(define2&&define2.amd){define2(function(){return impl})}else{this.tychei=impl}})(exports2,typeof module2=="object"&&module2,typeof define=="function"&&define)});var require_seedrandom=__commonJS((exports2,module2)=>{(function(pool,math){var global2=this,width=256,chunks=6,digits=52,rngname="random",startdenom=math.pow(width,chunks),significance=math.pow(2,digits),overflow=significance*2,mask=width-1,nodecrypto;function seedrandom(seed,options,callback){var key=[];options=options==true?{entropy:true}:options||{};var shortseed=mixkey(flatten(options.entropy?[seed,tostring(pool)]:seed==null?autoseed():seed,3),key);var arc4=new ARC4(key);var prng=function(){var n=arc4.g(chunks),d=startdenom,x=0;while(n=overflow){n/=2;d/=2;x>>>=1}return(n+x)/d};prng.int32=function(){return arc4.g(4)|0};prng.quick=function(){return arc4.g(4)/4294967296};prng.double=prng;mixkey(tostring(arc4.S),pool);return(options.pass||callback||function(prng2,seed2,is_math_call,state){if(state){if(state.S){copy(state,arc4)}prng2.state=function(){return copy(arc4,{})}}if(is_math_call){math[rngname]=prng2;return seed2}else return prng2})(prng,shortseed,"global"in options?options.global:this==math,options.state)}math["seed"+rngname]=seedrandom;function ARC4(key){var t,keylen=key.length,me=this,i=0,j=me.i=me.j=0,s=me.S=[];if(!keylen){key=[keylen++]}while(i{var alea=require_alea();var xor128=require_xor128();var xorwow=require_xorwow();var xorshift7=require_xorshift7();var xor4096=require_xor4096();var tychei=require_tychei();var sr=require_seedrandom();sr.alea=alea;sr.xor128=xor128;sr.xorwow=xorwow;sr.xorshift7=xorshift7;sr.xor4096=xor4096;sr.tychei=tychei;module2.exports=sr});var require_tf_backend_cpu_node=__commonJS(exports2=>{"use strict";Object.defineProperty(exports2,"__esModule",{value:true});var tf4=require_tf_core_node();var seedrandom=require_seedrandom2();var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d2,b2){d2.__proto__=b2}||function(d2,b2){for(var p2 in b2)if(b2.hasOwnProperty(p2))d2[p2]=b2[p2]};return extendStatics(d,b)};function __extends(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}function __awaiter(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step2(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step2(generator["throw"](value))}catch(e){reject(e)}}function step2(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step2((generator=generator.apply(thisArg,_arguments||[])).next())})}function __generator(thisArg,body2){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step2([n,v])}}function step2(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]0&&tf4.util.isString(values[0])){var encodedValues=values.map(function(d){return tf4.util.encodeString(d)});outId=this.write(encodedValues,shape,dtype)}else{outId=this.write(values,shape,dtype)}return{dataId:outId,shape,dtype}};MathBackendCPU2.prototype.incRef=function(dataId){var tensorData=this.data.get(dataId);tensorData.refCount++};MathBackendCPU2.prototype.decRef=function(dataId){if(this.data.has(dataId)){var tensorData=this.data.get(dataId);tensorData.refCount--}};MathBackendCPU2.prototype.move=function(dataId,values,shape,dtype){this.data.set(dataId,{values,dtype,refCount:1})};MathBackendCPU2.prototype.numDataIds=function(){return this.data.numDataIds()};MathBackendCPU2.prototype.read=function(dataId){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){return[2,this.readSync(dataId)]})})};MathBackendCPU2.prototype.readSync=function(dataId){var _a=this.data.get(dataId),dtype=_a.dtype,complexTensorInfos=_a.complexTensorInfos;if(dtype==="complex64"){var realValues=this.readSync(complexTensorInfos.real.dataId);var imagValues=this.readSync(complexTensorInfos.imag.dataId);return tf4.backend_util.mergeRealAndImagArrays(realValues,imagValues)}return this.data.get(dataId).values};MathBackendCPU2.prototype.bufferSync=function(t){var data2=this.readSync(t.dataId);var decodedData=data2;if(t.dtype==="string"){try{decodedData=data2.map(function(d){return tf4.util.decodeString(d)})}catch(_a){throw new Error("Failed to decode encoded string bytes into utf-8")}}return tf4.buffer(t.shape,t.dtype,decodedData)};MathBackendCPU2.prototype.makeOutput=function(values,shape,dtype){var dataId=this.write(values,shape,dtype);return tf4.engine().makeTensorFromDataId(dataId,shape,dtype,this)};MathBackendCPU2.prototype.disposeData=function(dataId){if(this.data.has(dataId)){var complexTensorInfos=this.data.get(dataId).complexTensorInfos;if(complexTensorInfos!=null){this.disposeData(complexTensorInfos.real.dataId);this.disposeData(complexTensorInfos.imag.dataId)}this.data.delete(dataId)}};MathBackendCPU2.prototype.disposeIntermediateTensorInfo=function(tensorInfo){var dataId=tensorInfo.dataId;if(this.data.has(dataId)){var tensorData=this.data.get(dataId);tensorData.refCount--;if(tensorData.refCount<1){this.disposeData(dataId)}}};MathBackendCPU2.prototype.time=function(f){return __awaiter(this,void 0,void 0,function(){var start,kernelMs;return __generator(this,function(_a){start=tf4.util.now();f();kernelMs=tf4.util.now()-start;return[2,{kernelMs}]})})};MathBackendCPU2.prototype.memory=function(){return{unreliable:true,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}};MathBackendCPU2.prototype.stridedSlice=function(x,begin,end,strides){assertNotComplex(x,"stridedSlice");var outShape=tf4.slice_util.computeOutShape(begin,end,strides);if(outShape.some(function(axis){return axis===0})){return tf4.tensor([],outShape)}var buffer2=tf4.buffer(outShape,x.dtype);var xBuf=this.bufferSync(x);for(var i=0;imax_1){max_1=value;maxIndex=j}}vals[i]=maxIndex}return result};MathBackendCPU2.prototype.cumsum=function(x,axis,exclusive,reverse2){assertNotComplex(x,"cumsum");if(axis!==x.rank-1){throw new Error("backend.cumsum in CPU expects an inner-most axis="+(x.rank-1)+" "+("but got axis="+axis))}var resultDtype=tf4.upcastType(x.dtype,"int32");var result=tf4.zeros(x.shape,resultDtype);var vals=this.readSync(result.dataId);var aVals=this.readSync(x.dataId);var finalDim=x.shape[x.rank-1];var indexAdjuster=reverse2?function(i2,j2){return i2+finalDim-j2-1}:function(i2,j2){return i2+j2};for(var i=0;ibVal?1:0})};MathBackendCPU2.prototype.greaterEqual=function(a,b){assertNotComplex([a,b],"greaterEqual");return this.broadcastedBinaryOp(a,b,"bool",function(aVal,bVal){return aVal>=bVal?1:0})};MathBackendCPU2.prototype.logicalAnd=function(a,b){assertNotComplex([a,b],"logicalAnd");return this.broadcastedBinaryOp(a,b,"bool",function(aVal,bVal){return aVal&&bVal})};MathBackendCPU2.prototype.logicalOr=function(a,b){assertNotComplex([a,b],"logicalOr");return this.broadcastedBinaryOp(a,b,"bool",function(aVal,bVal){return aVal||bVal})};MathBackendCPU2.prototype.select=function(condition,a,b){assertNotComplex([condition,a,b],"select");var values=this.readSync(condition.dataId);var aValues=this.readSync(a.dataId);var bValues=this.readSync(b.dataId);var result=tf4.zeros(a.shape,tf4.upcastType(a.dtype,b.dtype));var newValues=this.readSync(result.dataId);var index=0;var offset=condition.rank===0||condition.rank>1||a.rank===1?1:tf4.util.sizeFromShape(a.shape.slice(1));for(var i=0;i=0&&bVal>=0){return rem}else{return(rem+bVal)%bVal}})};MathBackendCPU2.prototype.maximum=function(a,b){assertNotComplex([a,b],"maximum");return this.broadcastedBinaryOp(a,b,a.dtype,function(aVal,bVal){return Math.max(aVal,bVal)})};MathBackendCPU2.prototype.all=function(x,axes){assertNotComplex(x,"all");tf4.backend_util.assertAxesAreInnerMostDims("all",axes,x.rank);var _a=tf4.backend_util.computeOutAndReduceShapes(x.shape,axes),outShape=_a[0],reduceShape=_a[1];var result=tf4.zeros(outShape,x.dtype);var reduceSize=tf4.util.sizeFromShape(reduceShape);var vals=this.readSync(result.dataId);var aVals=this.readSync(x.dataId);for(var i=0;i=1){resultValues[i]=dyValues[i]}else{resultValues[i]=dyValues[i]*(v+1)}}return this.makeOutput(resultValues,y.shape,"float32")};MathBackendCPU2.prototype.atan2=function(a,b){assertNotComplex([a,b],"atan2");return this.broadcastedBinaryOp(a,b,a.dtype,function(aValue,bValue){return Math.atan2(aValue,bValue)})};MathBackendCPU2.prototype.tile=function(x,reps){assertNotComplex(x,"tile");return tile2(this.bufferSync(x),reps)};MathBackendCPU2.prototype.gather=function(x,indices,axis){assertNotComplex([x,indices],"gather");var newShape=x.shape.slice();var indicesValues=this.readSync(indices.dataId);newShape[axis]=indicesValues.length;var result=tf4.buffer(newShape,x.dtype);var xBuf=this.bufferSync(x);for(var i=0;iminMaxValue){minMaxValue=pixel}else if(poolType==="avg"){avgValue+=pixel;count++}if(isNaN(minMaxValue)){break}}if(isNaN(minMaxValue)){break}}if(isNaN(minMaxValue)){break}}var outputOffset=outputColOffset+channel;outputVals[outputOffset]=poolType==="avg"?avgValue/count:minMaxValue}}}}}return output.toTensor()};MathBackendCPU2.prototype.avgPool3d=function(x,convInfo){assertNotComplex(x,"avgPool3d");return this.pool3d(x,convInfo,"avg").toFloat()};MathBackendCPU2.prototype.avgPool3dBackprop=function(dy,x,convInfo){assertNotComplex([dy,x],"avgPool3dBackprop");var strideDepth=convInfo.strideDepth;var strideHeight=convInfo.strideHeight;var strideWidth=convInfo.strideWidth;var filterDepth=convInfo.filterDepth;var filterHeight=convInfo.filterHeight;var filterWidth=convInfo.filterWidth;var dilationDepth=convInfo.dilationDepth;var dilationHeight=convInfo.dilationHeight;var dilationWidth=convInfo.dilationWidth;var effectiveFilterDepth=convInfo.effectiveFilterDepth;var effectiveFilterHeight=convInfo.effectiveFilterHeight;var effectiveFilterWidth=convInfo.effectiveFilterWidth;var padFront=effectiveFilterDepth-1-convInfo.padInfo.front;var padLeft=effectiveFilterWidth-1-convInfo.padInfo.left;var padTop=effectiveFilterHeight-1-convInfo.padInfo.top;var dx=tf4.buffer(x.shape,"float32");var avgMultiplier=1/(filterDepth*filterHeight*filterWidth);var dyBuf=this.bufferSync(dy);for(var batch=0;batch=convInfo.outDepth||Math.floor(dyDepth)!==dyDepth){continue}for(var wRow=0;wRow=convInfo.outHeight||Math.floor(dyRow)!==dyRow){continue}for(var wCol=0;wCol=convInfo.outWidth||Math.floor(dyCol)!==dyCol){continue}var pixel=dyBuf.get(batch,dyDepth,dyRow,dyCol,channel);dotProd+=pixel}}}dx.set(dotProd*avgMultiplier,batch,dxDepth,dxRow,dxCol,channel)}}}}}return dx.toTensor()};MathBackendCPU2.prototype.maxPool3d=function(x,convInfo){assertNotComplex(x,"maxPool3d");return this.pool3d(x,convInfo,"max").toFloat()};MathBackendCPU2.prototype.maxPool3dPositions=function(x,convInfo){var maxPositions=tf4.buffer(convInfo.outShape,"int32");var strideDepth=convInfo.strideDepth;var strideHeight=convInfo.strideHeight;var strideWidth=convInfo.strideWidth;var dilationDepth=convInfo.dilationDepth;var dilationHeight=convInfo.dilationHeight;var dilationWidth=convInfo.dilationWidth;var effectiveFilterDepth=convInfo.effectiveFilterDepth;var effectiveFilterHeight=convInfo.effectiveFilterHeight;var effectiveFilterWidth=convInfo.effectiveFilterWidth;var padFront=convInfo.padInfo.front;var padTop=convInfo.padInfo.top;var padLeft=convInfo.padInfo.left;var xBuf=this.bufferSync(x);for(var batch=0;batch=maxValue){maxValue=pixel;maxPosition=wDepth*effectiveFilterHeight*effectiveFilterWidth+wRow*effectiveFilterHeight+wCol}}}}maxPositions.set(maxPosition,batch,yDepth,yRow,yCol,channel)}}}}}return maxPositions.toTensor()};MathBackendCPU2.prototype.maxPool3dBackprop=function(dy,x,y,convInfo){assertNotComplex([x,y],"maxPool3dBackprop");var maxPositions=this.maxPool3dPositions(x,convInfo);var strideDepth=convInfo.strideDepth;var strideHeight=convInfo.strideHeight;var strideWidth=convInfo.strideWidth;var dilationDepth=convInfo.dilationDepth;var dilationHeight=convInfo.dilationHeight;var dilationWidth=convInfo.dilationWidth;var effectiveFilterDepth=convInfo.effectiveFilterDepth;var effectiveFilterHeight=convInfo.effectiveFilterHeight;var effectiveFilterWidth=convInfo.effectiveFilterWidth;var padFront=effectiveFilterDepth-1-convInfo.padInfo.front;var padLeft=effectiveFilterWidth-1-convInfo.padInfo.left;var padTop=effectiveFilterHeight-1-convInfo.padInfo.top;var dx=tf4.buffer(x.shape,"float32");var maxPosBuf=this.bufferSync(maxPositions);var dyBuf=this.bufferSync(dy);for(var batch=0;batch=convInfo.outDepth||Math.floor(dyDepth)!==dyDepth){continue}for(var wRow=0;wRow=convInfo.outHeight||Math.floor(dyRow)!==dyRow){continue}for(var wCol=0;wCol=convInfo.outWidth||Math.floor(dyCol)!==dyCol){continue}var maxPos=effectiveFilterDepth*effectiveFilterHeight*effectiveFilterWidth-1-maxPosBuf.get(batch,dyDepth,dyRow,dyCol,channel);var curPos=wDepth*effectiveFilterHeight*effectiveFilterWidth+wRow*effectiveFilterWidth+wCol;var mask=maxPos===curPos?1:0;if(mask===0){continue}var pixel=dyBuf.get(batch,dyDepth,dyRow,dyCol,channel);dotProd+=pixel*mask}}}dx.set(dotProd,batch,dxDepth,dxRow,dxCol,channel)}}}}}return dx.toTensor()};MathBackendCPU2.prototype.resizeBilinear=function(x,newHeight,newWidth,alignCorners){assertNotComplex(x,"resizeBilinear");var _a=x.shape,batch=_a[0],oldHeight=_a[1],oldWidth=_a[2],numChannels=_a[3];var xValues=this.readSync(x.dataId);var result=new Float32Array(tf4.util.sizeFromShape([batch,newHeight,newWidth,numChannels]));var effectiveInputSize=[alignCorners&&newHeight>1?oldHeight-1:oldHeight,alignCorners&&newWidth>1?oldWidth-1:oldWidth];var effectiveOutputSize=[alignCorners&&newHeight>1?newHeight-1:newHeight,alignCorners&&newWidth>1?newWidth-1:newWidth];var outputIdx=0;var effectiveRowSizeRatio=effectiveInputSize[0]/effectiveOutputSize[0];var effectiveColSizeRatio=effectiveInputSize[1]/effectiveOutputSize[1];for(var b=0;b1?xHeight-1:xHeight,alignCorners&&yWidth>1?xWidth-1:xWidth];var effectiveYSize=[alignCorners&&yHeight>1?yHeight-1:yHeight,alignCorners&&yWidth>1?yWidth-1:yWidth];var heightScale=effectiveXSize[0]/effectiveYSize[0];var widthScale=effectiveXSize[1]/effectiveYSize[1];var dyValues=this.readSync(dy.dataId);var offset=0;for(var b=0;b1?oldHeight-1:oldHeight,alignCorners&&newWidth>1?oldWidth-1:oldWidth];var effectiveOutputSize=[alignCorners&&newHeight>1?newHeight-1:newHeight,alignCorners&&newWidth>1?newWidth-1:newWidth];var effectiveRowSizeRatio=effectiveInputSize[0]/effectiveOutputSize[0];var effectiveColSizeRatio=effectiveInputSize[1]/effectiveOutputSize[1];var outputOffset=0;for(var b=0;b1?xHeight-1:xHeight,alignCorners&&yWidth>1?xWidth-1:xWidth];var effectiveYSize=[alignCorners&&yHeight>1?yHeight-1:yHeight,alignCorners&&yWidth>1?yWidth-1:yWidth];var heightScale=effectiveXSize[0]/effectiveYSize[0];var widthScale=effectiveXSize[1]/effectiveYSize[1];var invHeightScale=1/heightScale;var invWidthScale=1/widthScale;var winHeight=Math.ceil(invHeightScale)*2+2;var winWidth=Math.ceil(invWidthScale)*2+2;for(var b=0;b=yHeight){continue}var dyROffset=batchOffset+dyR*dy.strides[1];var sourceFracRow=dyR*heightScale;var sourceNearestRow=Math.min(xHeight-1,alignCorners?Math.round(sourceFracRow):Math.floor(sourceFracRow));if(r!==sourceNearestRow){continue}for(var dyCIndex=0;dyCIndex=yWidth){continue}var dyCOffset=dyROffset+dyC*dy.strides[2];var sourceFracCol=dyC*widthScale;var sourceNearestCol=Math.min(xWidth-1,alignCorners?Math.round(sourceFracCol):Math.floor(sourceFracCol));if(c===sourceNearestCol){accum+=dyValues[dyCOffset+d]}}}output[colOffset+d]=accum}}}}return tf4.tensor4d(output,x.shape,x.dtype)};MathBackendCPU2.prototype.localResponseNormalization4D=function(x,depthRadius,bias,alpha,beta){assertNotComplex(x,"localResponseNormalization4D");var channels=x.shape[3];var maxD=channels-1;var xValues=this.readSync(x.dataId);var size=x.size;var result=new Float32Array(size);function sumAcrossChannels(offset2){var currentChannel=offset2%channels;var beginSumOffset=offset2-currentChannel+Math.max(0,currentChannel-depthRadius);var endSumOffset=offset2-currentChannel+Math.min(currentChannel+depthRadius,maxD);var sum3=0;for(;beginSumOffset<=endSumOffset;beginSumOffset++){var z=xValues[beginSumOffset];sum3+=z*z}return sum3}for(var offset=0;offset=0&&indicesVal[event_3]1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+blockSize});var batchSize=x.shape[0];var inputHeight=x.shape[1];var inputWidth=x.shape[2];var inputDepth=x.shape[3];var outputHeight=inputHeight*blockSize;var outputWidth=inputWidth*blockSize;var outputDepth=inputDepth/(blockSize*blockSize);var xValues=this.readSync(x.dataId);var result=new Float32Array(batchSize*outputHeight*outputWidth*outputDepth);var outputIdx=0;for(var b=0;b=batch){continue}var heightScale=cropHeight>1?(y2-y1)*(imageHeight-1)/(cropHeight-1):0;var widthScale=cropWidth>1?(x2-x1)*(imageWidth-1)/(cropWidth-1):0;for(var y=0;y1?y1*(imageHeight-1)+y*heightScale:.5*(y1+y2)*(imageHeight-1);if(yInd<0||yInd>imageHeight-1){for(var x=0;x1?x1*(imageWidth-1)+x*widthScale:.5*(x1+x2)*(imageWidth-1);if(xInd<0||xInd>imageWidth-1){for(var c=0;c1?x1*(imageWidth-1)+x*widthScale:.5*(x1+x2)*(imageWidth-1);if(xInd<0||xInd>imageWidth-1){for(var c=0;c=x.size/sliceSize){throw new Error("Invalid indices: "+index+" does not index into "+x.shape)}for(var k=0;k=outputSize/sliceSize){throw new Error("Invalid indices: "+index+" does not index into "+shape)}for(var k=0;kmax2){max2=value}}vals[i]=max2}return vals}var multiplyImpl=createSimpleBinaryKernelImpl(function(aValue,bValue){return aValue*bValue});var multiplyComplexImpl=createComplexBinaryKernelImpl(function(aReal,aImag,bReal,bImag){return{real:aReal*bReal-aImag*bImag,imag:aReal*bImag+aImag*bReal}});var multiply=binaryKernelFunc(tf4.Multiply,multiplyImpl,multiplyComplexImpl);var multiplyConfig2={kernelName:tf4.Multiply,backendName:"cpu",kernelFunc:multiply};var notEqualImpl=createSimpleBinaryKernelImpl(function(a,b){return a!==b?1:0});var notEqual=binaryKernelFunc(tf4.NotEqual,notEqualImpl,null,"bool");var notEqualConfig2={kernelName:tf4.NotEqual,backendName:"cpu",kernelFunc:notEqual};var rsqrtImpl=createSimpleUnaryImpl(function(xi){return 1/Math.sqrt(xi)});var rsqrt=unaryKernelFuncFromImpl(tf4.Rsqrt,rsqrtImpl);var rsqrtConfig2={kernelName:tf4.Rsqrt,backendName:"cpu",kernelFunc:rsqrt};function sliceImpl(vals,begin,size,shape,dtype){var isContinous=tf4.slice_util.isSliceContinous(shape,begin,size);var length=tf4.util.sizeFromShape(size);var xStrides=tf4.util.computeStrides(shape);if(isContinous){var flatOffset=tf4.slice_util.computeFlatOffset(begin,xStrides);return vals.subarray(flatOffset,flatOffset+length)}var outVals=tf4.util.getTypedArrayFromDType(dtype,length);for(var i=0;i=0?xi:Math.exp(xi)-1});var eluConfig={kernelName:tf4.Elu,backendName:"cpu",kernelFunc:elu};var preluImpl=createSimpleBinaryKernelImpl(function(xValue,aValue){return xValue<0?aValue*xValue:xValue});function prelu2(args){var inputs=args.inputs,backend=args.backend;var x=inputs.x,alpha=inputs.alpha;assertNotComplex([x,alpha],"prelu");var aVals=backend.data.get(x.dataId).values;var bVals=backend.data.get(alpha.dataId).values;var _a=preluImpl(x.shape,alpha.shape,aVals,bVals,x.dtype),resultData=_a[0],resultShape=_a[1];return backend.makeTensorInfo(resultShape,x.dtype,resultData)}var preluConfig2={kernelName:tf4.Prelu,backendName:"cpu",kernelFunc:prelu2};var relu=unaryKernelFunc(tf4.Relu,function(xi){return Math.max(0,xi)});var reluConfig2={kernelName:tf4.Relu,backendName:"cpu",kernelFunc:relu};var relu6=unaryKernelFunc(tf4.Relu6,function(xi){return Math.min(Math.max(0,xi),6)});var relu6Config2={kernelName:tf4.Relu6,backendName:"cpu",kernelFunc:relu6};function applyActivation(backend,x,activation,preluActivationWeights){if(activation==="linear"){return identity2({inputs:{x},backend})}else if(activation==="relu"){return relu({inputs:{x},backend})}else if(activation==="elu"){return elu({inputs:{x},backend})}else if(activation==="relu6"){return relu6({inputs:{x},backend})}else if(activation==="prelu"){return prelu2({inputs:{x,alpha:preluActivationWeights},backend})}throw new Error("Activation "+activation+" has not been implemented for the CPU backend.")}function reshape2(args){var inputs=args.inputs,backend=args.backend,attrs=args.attrs;var x=inputs.x;var shape=attrs.shape;var xSize=tf4.util.sizeFromShape(x.shape);var $shape=tf4.util.inferFromImplicitShape(shape,xSize);var $xSize=tf4.util.sizeFromShape($shape);tf4.util.assert(xSize===$xSize,function(){return"The new shape ("+$shape+") has "+$xSize+" elements and the old "+("shape ("+x.shape+") has "+xSize+" elements. The new shape and old ")+"shape must have the same number of elements."});backend.incRef(x.dataId);var xData=backend.data.get(x.dataId);if(xData.complexTensorInfos!=null){var real2=xData.complexTensorInfos.real;var imag2=xData.complexTensorInfos.imag;real2.shape=$shape;imag2.shape=$shape}return{dataId:x.dataId,shape:$shape,dtype:x.dtype}}var reshapeConfig2={kernelName:tf4.Reshape,backendName:"cpu",kernelFunc:reshape2};function batchMatMul2(args){var inputs=args.inputs,backend=args.backend,attrs=args.attrs;var a=inputs.a,b=inputs.b;var transposeA=attrs.transposeA,transposeB=attrs.transposeB;assertNotComplex([a,b],"matMul");var aRank=a.shape.length;var bRank=b.shape.length;var innerShapeA=transposeA?a.shape[aRank-2]:a.shape[aRank-1];var innerShapeB=transposeB?b.shape[bRank-1]:b.shape[bRank-2];var outerShapeA=transposeA?a.shape[aRank-1]:a.shape[aRank-2];var outerShapeB=transposeB?b.shape[bRank-2]:b.shape[bRank-1];var outerDimsA=a.shape.slice(0,-2);var outerDimsB=b.shape.slice(0,-2);var batchDimA=tf4.util.sizeFromShape(outerDimsA);var batchDimB=tf4.util.sizeFromShape(outerDimsB);var batchDimsCompatible=batchDimA===batchDimB||batchDimA===1||batchDimB===1;tf4.util.assert(aRank>=2&&bRank>=2&&batchDimsCompatible,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 ("+outerDimsA+") and ("+outerDimsB+").")});var outShapeOuterDims=batchDimA>batchDimB?a.shape.slice(0,-2):b.shape.slice(0,-2);var outShape=outShapeOuterDims.concat([outerShapeA,outerShapeB]);tf4.util.assert(innerShapeA===innerShapeB,function(){return"Error in matMul: inner shapes ("+innerShapeA+") and ("+(innerShapeB+") of Tensors with shapes "+a.shape+" and ")+(b.shape+" and transposeA="+transposeA)+(" and transposeB="+transposeB+" must match.")});var a3dShape=transposeA?[batchDimA,innerShapeA,outerShapeA]:[batchDimA,outerShapeA,innerShapeA];var b3dShape=transposeB?[batchDimB,outerShapeB,innerShapeB]:[batchDimB,innerShapeB,outerShapeB];var a3d=reshape2({inputs:{x:a},backend,attrs:{shape:a3dShape}});var b3d=reshape2({inputs:{x:b},backend,attrs:{shape:b3dShape}});var sharedDim=transposeA?a3d.shape[1]:a3d.shape[2];var leftDim=transposeA?a3d.shape[2]:a3d.shape[1];var rightDim=transposeB?b3d.shape[1]:b3d.shape[2];var batchDim=Math.max(batchDimA,batchDimB);var a3dValues=backend.data.get(a3d.dataId).values;var b3dValues=backend.data.get(b3d.dataId).values;var a3dStrides=tf4.util.computeStrides(a3d.shape);var b3dStrides=tf4.util.computeStrides(b3d.shape);var _a=transposeA?[a3dStrides[0],1,a3dStrides[1]]:[a3dStrides[0],a3dStrides[1],1],aBatch=_a[0],aOuterStep=_a[1],aInnerStep=_a[2];var _b=transposeB?[1,b3dStrides[1],b3dStrides[0]]:[b3dStrides[1],1,b3dStrides[0]],bInnerStep=_b[0],bOuterStep=_b[1],bBatch=_b[2];var size=leftDim*rightDim;var result=tf4.buffer([batchDim,leftDim,rightDim],a3d.dtype);var resVals=result.values;var blockSize=backend.blockSize;for(var bi=0;biminMaxValue){minMaxValue=pixel}else if(poolType==="avg"){avgValue+=pixel;count++}}if(isNaN(minMaxValue)){break}}var outputOffset=outputRowOffset+yC*outputColStrides+d;outputVals[outputOffset]=poolType==="avg"?avgValue/count:minMaxValue}}}}return output}function maxPoolPositions(xValues,xShape,dtype,convInfo,flattenPositions,includeBatchInIndex){if(flattenPositions===void 0){flattenPositions=false}if(includeBatchInIndex===void 0){includeBatchInIndex=false}var maxPositions=tf4.buffer(convInfo.outShape,"int32");var strideHeight=convInfo.strideHeight;var strideWidth=convInfo.strideWidth;var dilationHeight=convInfo.dilationHeight;var dilationWidth=convInfo.dilationWidth;var effectiveFilterHeight=convInfo.effectiveFilterHeight;var effectiveFilterWidth=convInfo.effectiveFilterWidth;var padTop=convInfo.padInfo.top;var padLeft=convInfo.padInfo.left;var xBuf=tf4.buffer(xShape,dtype,xValues);for(var b=0;bmaxValue){maxValue=pixel;if(flattenPositions){maxPosition=includeBatchInIndex?((b*convInfo.inHeight+xR)*convInfo.inWidth+xC)*convInfo.inChannels+d:(xR*convInfo.inWidth+xC)*convInfo.inChannels+d}else{maxPosition=wR*effectiveFilterWidth+wC}}}}maxPositions.set(maxPosition,b,yR,yC,d)}}}}return maxPositions}function avgPool2(args){var inputs=args.inputs,backend=args.backend,attrs=args.attrs;var x=inputs.x;assertNotComplex(x,"avgPool");var filterSize=attrs.filterSize,strides=attrs.strides,pad2=attrs.pad,dimRoundingMode=attrs.dimRoundingMode;var dilations=1;tf4.util.assert(tf4.backend_util.eitherStridesOrDilationsAreOne(strides,dilations),function(){return"Error in avgPool: Either strides or dilations must be 1. "+("Got strides "+strides+" and dilations '"+dilations+"'")});var convInfo=tf4.backend_util.computePool2DInfo(x.shape,filterSize,strides,dilations,pad2,dimRoundingMode);var res;if(convInfo.filterWidth===1&&convInfo.filterHeight===1&&tf4.util.arraysEqual(convInfo.inShape,convInfo.outShape)){res=identity2({inputs:{x},backend})}else{var xValues=backend.data.get(x.dataId).values;var strides_1=tf4.util.computeStrides(x.shape);var buffer2=pool(xValues,x.shape,x.dtype,strides_1,convInfo,"avg");res=backend.makeTensorInfo(convInfo.outShape,x.dtype,buffer2.values)}return res}var avgPoolConfig2={kernelName:tf4.AvgPool,backendName:"cpu",kernelFunc:avgPool2};function avgPoolBackprop(args){var inputs=args.inputs,backend=args.backend,attrs=args.attrs;var dy=inputs.dy,input=inputs.input;var x=input;assertNotComplex([dy,input],"avgPoolBackprop");var filterSize=attrs.filterSize,strides=attrs.strides,pad2=attrs.pad;var convInfo=tf4.backend_util.computePool2DInfo(x.shape,filterSize,strides,1,pad2);var strideHeight=convInfo.strideHeight;var strideWidth=convInfo.strideWidth;var filterHeight=convInfo.filterHeight;var filterWidth=convInfo.filterWidth;var dilationHeight=convInfo.dilationHeight;var dilationWidth=convInfo.dilationWidth;var effectiveFilterHeight=convInfo.effectiveFilterHeight;var effectiveFilterWidth=convInfo.effectiveFilterWidth;var padLeft=effectiveFilterWidth-1-convInfo.padInfo.left;var padTop=effectiveFilterHeight-1-convInfo.padInfo.top;var dx=tf4.buffer(x.shape,"float32");var avgMultiplier=1/(filterHeight*filterWidth);var dyData=backend.data.get(dy.dataId).values;var dyBuf=tf4.buffer(dy.shape,"float32",dyData);for(var b=0;b=convInfo.outHeight||Math.floor(dyR)!==dyR){continue}for(var wC=0;wC=convInfo.outWidth||Math.floor(dyC)!==dyC){continue}var pixel=dyBuf.get(b,dyR,dyC,d);dotProd+=pixel}}dx.set(dotProd*avgMultiplier,b,dxR,dxC,d)}}}}return backend.makeTensorInfo(dx.shape,dx.dtype,dx.values)}var avgPoolBackpropConfig={kernelName:tf4.AvgPoolBackprop,backendName:"cpu",kernelFunc:avgPoolBackprop};function batchNorm(args){var inputs=args.inputs,backend=args.backend,attrs=args.attrs;var x=inputs.x,scale2=inputs.scale,offset=inputs.offset,mean=inputs.mean,variance=inputs.variance;tf4.util.assert(mean.shape.length===variance.shape.length,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."});tf4.util.assert(offset==null||mean.shape.length===offset.shape.length,function(){return"Batch normalization gradient requires mean and offset to have equal ranks."});tf4.util.assert(scale2==null||mean.shape.length===scale2.shape.length,function(){return"Batch normalization gradient requires mean and scale to have equal ranks."});assertNotComplex([x,mean,variance,scale2,offset],"batchNorm");var varianceEpsilon=attrs.varianceEpsilon;if(varianceEpsilon==null){varianceEpsilon=.001}var xVals=backend.data.get(x.dataId).values;var mVals=backend.data.get(mean.dataId).values;var varVals=backend.data.get(variance.dataId).values;var sVals=scale2?backend.data.get(scale2.dataId).values:new Float32Array([1]);var offVals=offset?backend.data.get(offset.dataId).values:new Float32Array([0]);var outVals=new Float32Array(xVals.length);var offValsLength=offVals.length;var sValsLength=sVals.length;var varValsLength=varVals.length;var mValsLength=mVals.length;var offi=0;var mi=0;var si=0;var vi=0;for(var i=0;i=offValsLength){offi=0}if(mi>=mValsLength){mi=0}if(si>=sValsLength){si=0}if(vi>=varValsLength){vi=0}}return backend.makeTensorInfo(x.shape,x.dtype,outVals)}var batchNormConfig={kernelName:tf4.FusedBatchNorm,backendName:"cpu",kernelFunc:batchNorm};var clip2=unaryKernelFunc(tf4.ClipByValue,function(xi,attrs){var clipAttrs=attrs;if(xi>clipAttrs.clipValueMax){return clipAttrs.clipValueMax}return xi0});if($inputs.length===1){return $inputs[0]}var shapes=$inputs.map(function(t){return t.shape});tf4.backend_util.assertParamsConsistent(shapes,$axis);if($inputs[0].dtype==="complex64"){var reals=$inputs.map(function(t){return real({inputs:{input:t},backend})});var imags=$inputs.map(function(t){return imag({inputs:{input:t},backend})});var realConcated=concat2({inputs:reals,backend,attrs:{axis:$axis}});var imagConcated=concat2({inputs:imags,backend,attrs:{axis:$axis}});var result=complex({inputs:{real:realConcated,imag:imagConcated},backend});reals.forEach(function(r){return backend.disposeIntermediateTensorInfo(r)});imags.forEach(function(i){return backend.disposeIntermediateTensorInfo(i)});backend.disposeIntermediateTensorInfo(realConcated);backend.disposeIntermediateTensorInfo(imagConcated);return result}var inputs2D=$inputs.map(function(t){var innerSize=tf4.util.sizeFromShape(t.shape.slice($axis));var shape=[-1,innerSize];return reshape2({inputs:{x:t},backend,attrs:{shape}})});outShape=tf4.backend_util.computeOutShape(inputs2D.map(function(t){return t.shape}),1);var outVals=tf4.util.getTypedArrayFromDType($inputs[0].dtype,tf4.util.sizeFromShape(outShape));if(inputs2D[0].shape[0]===1){var offset_1=0;inputs2D.forEach(function(t){var val=backend.data.get(t.dataId).values;var size=tf4.util.sizeFromShape(t.shape);outVals.set(val,offset_1);offset_1+=size})}else{var colOffset_1=0;inputs2D.forEach(function(t){var tVals=backend.data.get(t.dataId).values;var tIdx=0;for(var row=0;row=convInfo.inHeight){continue}var wOffset1=wR*filterStrides[0];var xOffset2=xOffset1+xR*xRowStride;for(var yC=0;yC=convInfo.inWidth){continue}var wOffset2=wOffset1+wC*filterStrides[1];var xOffset3=xOffset2+xC*xColStride;var wOffset3=wOffset2;for(var d1=0;d1=convInfo.inDepth){continue}var wOffset1=wF*filterStrides[0];var xOffset2=xOffset1+xF*xStrides[1];for(var yR=0;yR=convInfo.inHeight){continue}var wOffset2=wOffset1+wR*filterStrides[1];var xOffset3=xOffset2+xR*xStrides[2];for(var yC=0;yC=convInfo.inWidth){continue}var wOffset3=wOffset2+wC*filterStrides[2];var xOffset4=xOffset3+xC*convInfo.inChannels;var wOffset4=wOffset3;for(var d1=0;d1=convInfo.inHeight){continue}var wOffset1=wR*filterStrides[0];var xOffset2=xOffset1+xR*xStrides[1];for(var yC=0;yC=convInfo.inWidth){continue}var wOffset2=wOffset1+wC*filterStrides[1];var xOffset3=xOffset2+xC*convInfo.inChannels;var yOffset4=yOffset3;var wOffset3=wOffset2;for(var d1=0;d1=0&&hIn=0&&wIncurVal){curVal=val}}}}}var outputIndex=tf4.util.locToIndex([b,hOut,wOut,d],outRank,tf4.util.computeStrides(outShape));outputVals[outputIndex]=curVal}}}}var dataId=cpuBackend.write(tf4.util.toTypedArray(outputVals,x.dtype),outShape,x.dtype);return{dataId,shape:outShape,dtype:x.dtype}}};var dilation2dBackpropFilterConfig={kernelName:tf4.Dilation2DBackpropFilter,backendName:"cpu",kernelFunc:function(_a){var inputs=_a.inputs,backend=_a.backend,attrs=_a.attrs;var _b=inputs,x=_b.x,filter=_b.filter,dy=_b.dy;var _c=attrs,strides=_c.strides,pad2=_c.pad,dilations=_c.dilations;var cpuBackend=backend;var $x=tf4.util.toNestedArray(x.shape,cpuBackend.data.get(x.dataId).values);var $filter=tf4.util.toNestedArray(filter.shape,cpuBackend.data.get(filter.dataId).values);var _d=tf4.backend_util.computeDilation2DInfo(x.shape,filter.shape,strides,pad2,"NHWC",dilations),batchSize=_d.batchSize,inHeight=_d.inHeight,inWidth=_d.inWidth,inChannels=_d.inChannels,outHeight=_d.outHeight,outWidth=_d.outWidth,padInfo=_d.padInfo,strideHeight=_d.strideHeight,strideWidth=_d.strideWidth,filterHeight=_d.filterHeight,filterWidth=_d.filterWidth,dilationHeight=_d.dilationHeight,dilationWidth=_d.dilationWidth,outShape=_d.outShape;tf4.util.assert(dy.rank===outShape.length,function(){return"Error in "+tf4.Dilation2DBackpropFilter+", dy "+("must have the same rank as output "+outShape.length+", but got ")+(""+dy.rank)});var $dy=tf4.util.toNestedArray(outShape,cpuBackend.data.get(dy.dataId).values);var gradients=tf4.util.makeZerosNestedTypedArray(filter.shape,filter.dtype);for(var b=0;b=0&&hIn=0&&wIncurVal){curVal=val;hMax=h;wMax=w}}}}}gradients[hMax][wMax][d]+=$dy[b][hOut][wOut][d]}}}}var dataId=cpuBackend.write(tf4.util.toTypedArray(gradients,x.dtype),filter.shape,filter.dtype);return{dataId,shape:filter.shape,dtype:filter.dtype}}};var dilation2dBackpropInputConfig={kernelName:tf4.Dilation2DBackpropInput,backendName:"cpu",kernelFunc:function(_a){var inputs=_a.inputs,backend=_a.backend,attrs=_a.attrs;var _b=inputs,x=_b.x,filter=_b.filter,dy=_b.dy;var _c=attrs,strides=_c.strides,pad2=_c.pad,dilations=_c.dilations;var cpuBackend=backend;var $x=tf4.util.toNestedArray(x.shape,cpuBackend.data.get(x.dataId).values);var $filter=tf4.util.toNestedArray(filter.shape,cpuBackend.data.get(filter.dataId).values);var _d=tf4.backend_util.computeDilation2DInfo(x.shape,filter.shape,strides,pad2,"NHWC",dilations),batchSize=_d.batchSize,inHeight=_d.inHeight,inWidth=_d.inWidth,inChannels=_d.inChannels,outHeight=_d.outHeight,outWidth=_d.outWidth,padInfo=_d.padInfo,strideHeight=_d.strideHeight,strideWidth=_d.strideWidth,filterHeight=_d.filterHeight,filterWidth=_d.filterWidth,dilationHeight=_d.dilationHeight,dilationWidth=_d.dilationWidth,outShape=_d.outShape;tf4.util.assert(dy.rank===outShape.length,function(){return"Error in "+tf4.Dilation2DBackpropInput+", dy "+("must have the same rank as output "+outShape.length+", but got ")+(""+dy.rank)});var $dy=tf4.util.toNestedArray(outShape,cpuBackend.data.get(dy.dataId).values);var gradients=tf4.util.makeZerosNestedTypedArray(x.shape,x.dtype);for(var b=0;b=0&&hIn=0&&wIncurVal){curVal=val;hInMax=hIn;wInMax=wIn}}}}}gradients[b][hInMax][wInMax][d]+=$dy[b][hOut][wOut][d]}}}}var dataId=cpuBackend.write(tf4.util.toTypedArray(gradients,x.dtype),x.shape,x.dtype);return{dataId,shape:x.shape,dtype:x.dtype}}};var divImpl=createSimpleBinaryKernelImpl(function(a,b){return a/b});var div=binaryKernelFunc(tf4.Div,divImpl);var divConfig2={kernelName:tf4.Div,backendName:"cpu",kernelFunc:div};var p=tf4.backend_util.ERF_P;var a1=tf4.backend_util.ERF_A1;var a2=tf4.backend_util.ERF_A2;var a3=tf4.backend_util.ERF_A3;var a4=tf4.backend_util.ERF_A4;var a5=tf4.backend_util.ERF_A5;var erf=unaryKernelFunc(tf4.Erf,function(xi){var sign2=Math.sign(xi);var v=Math.abs(xi);var t=1/(1+p*v);return sign2*(1-((((a5*t+a4)*t+a3)*t+a2)*t+a1)*t*Math.exp(-v*v))});var erfConfig={kernelName:tf4.Erf,backendName:"cpu",kernelFunc:erf};function fftBatch(input,inverse,cpuBackend){var inputShape=input.shape;var batch=inputShape[0];var innerDim=inputShape[1];var inputVals=cpuBackend.data.get(input.dataId);var real2D=inputVals.complexTensorInfos.real;var imag2D=inputVals.complexTensorInfos.imag;var resultShape=[batch,innerDim];var resultSize=tf4.util.sizeFromShape(resultShape);var resultReal=tf4.util.getTypedArrayFromDType("float32",resultSize);var resultImag=tf4.util.getTypedArrayFromDType("float32",resultSize);for(var b=0;b=0&&coordX=convInfo.outHeight||Math.floor(dyR)!==dyR){continue}for(var wC=0;wC=convInfo.outWidth||Math.floor(dyC)!==dyC){continue}var maxPos=effectiveFilterHeight*effectiveFilterWidth-1-maxPosBuf.get(b,dyR,dyC,d);var curPos=wR*effectiveFilterWidth+wC;var mask=maxPos===curPos?1:0;if(mask===0){continue}var pixel=dyBuf.get(b,dyR,dyC,d);dotProd+=pixel*mask}}dx.set(dotProd,b,dxR,dxC,d)}}}}return backend.makeTensorInfo(dx.shape,dx.dtype,dx.values)}var maxPoolBackpropConfig={kernelName:tf4.MaxPoolBackprop,backendName:"cpu",kernelFunc:maxPoolBackprop};function maxPoolWithArgmaxImpl(xValues,xShape,dtype,includeBatchInIndex,convInfo){var strides=tf4.util.computeStrides(xShape);var maxPools=pool(xValues,xShape,dtype,strides,convInfo,"max");var maxPositions=maxPoolPositions(xValues,xShape,dtype,convInfo,true,includeBatchInIndex);return[maxPools.values,maxPositions.values]}var maxPoolWithArgmaxConfig={kernelName:tf4.MaxPoolWithArgmax,backendName:"cpu",kernelFunc:function(_a){var inputs=_a.inputs,attrs=_a.attrs,backend=_a.backend;var x=inputs.x;var _b=attrs,filterSize=_b.filterSize,strides=_b.strides,pad2=_b.pad,includeBatchInIndex=_b.includeBatchInIndex;var cpuBackend=backend;assertNotComplex(x,"MaxPoolWithArgmax");var values=cpuBackend.data.get(x.dataId).values;var convInfo=tf4.backend_util.computePool2DInfo(x.shape,filterSize,strides,[1,1],pad2);var _c=maxPoolWithArgmaxImpl(values,x.shape,x.dtype,includeBatchInIndex,convInfo),pooled=_c[0],indexes=_c[1];var pooledDataId=cpuBackend.write(pooled,convInfo.outShape,x.dtype);var indexesDataId=cpuBackend.write(indexes,convInfo.outShape,x.dtype);return[{dataId:pooledDataId,shape:convInfo.outShape,dtype:x.dtype},{dataId:indexesDataId,shape:convInfo.outShape,dtype:"int32"}]}};function mirrorPad(args){var inputs=args.inputs,backend=args.backend,attrs=args.attrs;var x=inputs.x;var paddings=attrs.paddings,mode=attrs.mode;assertNotComplex(x,"mirrorPad");var outShape=paddings.map(function(p2,i2){return p2[0]+x.shape[i2]+p2[1]});var start=paddings.map(function(p2){return p2[0]});var end=paddings.map(function(p2,i2){return p2[0]+x.shape[i2]});var offset=mode==="reflect"?0:1;var xVals=backend.data.get(x.dataId).values;var xRank=x.shape.length;var xStrides=tf4.util.computeStrides(x.shape);var resultSize=tf4.util.sizeFromShape(outShape);var resultRank=outShape.length;var resultStrides=tf4.util.computeStrides(outShape);var resVals=tf4.util.getTypedArrayFromDType(x.dtype,resultSize);for(var i=0;i=end[i_1]){coords[i_1]=(end[i_1]-1)*2-coords[i_1]+offset}}coords=coords.map(function(c,i2){return c-start[i2]});var inIndex=tf4.util.locToIndex(coords,xRank,xStrides);resVals[i]=xVals[inIndex]}var outId=backend.write(resVals,outShape,x.dtype);return{dataId:outId,shape:outShape,dtype:x.dtype}}var mirrorPadConfig={kernelName:tf4.MirrorPad,backendName:"cpu",kernelFunc:mirrorPad};var nonMaxSuppressionV4Impl=tf4.kernel_impls.nonMaxSuppressionV4Impl;var nonMaxSuppressionV4Config2={kernelName:tf4.NonMaxSuppressionV4,backendName:"cpu",kernelFunc:function(_a){var inputs=_a.inputs,backend=_a.backend,attrs=_a.attrs;var _b=inputs,boxes=_b.boxes,scores=_b.scores;var _c=attrs,maxOutputSize=_c.maxOutputSize,iouThreshold=_c.iouThreshold,scoreThreshold=_c.scoreThreshold,padToMaxOutputSize=_c.padToMaxOutputSize;var cpuBackend=backend;assertNotComplex(boxes,"NonMaxSuppressionPadded");var boxesVals=cpuBackend.data.get(boxes.dataId).values;var scoresVals=cpuBackend.data.get(scores.dataId).values;var _d=nonMaxSuppressionV4Impl(boxesVals,scoresVals,maxOutputSize,iouThreshold,scoreThreshold,padToMaxOutputSize),selectedIndices=_d.selectedIndices,validOutputs=_d.validOutputs;return[selectedIndices,validOutputs]}};var nonMaxSuppressionV5Impl=tf4.kernel_impls.nonMaxSuppressionV5Impl;var nonMaxSuppressionV5Config2={kernelName:tf4.NonMaxSuppressionV5,backendName:"cpu",kernelFunc:function(_a){var inputs=_a.inputs,backend=_a.backend,attrs=_a.attrs;var _b=inputs,boxes=_b.boxes,scores=_b.scores;var _c=attrs,maxOutputSize=_c.maxOutputSize,iouThreshold=_c.iouThreshold,scoreThreshold=_c.scoreThreshold,softNmsSigma=_c.softNmsSigma;var cpuBackend=backend;assertNotComplex(boxes,"NonMaxSuppressionWithScore");var boxesVals=cpuBackend.data.get(boxes.dataId).values;var scoresVals=cpuBackend.data.get(scores.dataId).values;var maxOutputSizeVal=maxOutputSize;var iouThresholdVal=iouThreshold;var scoreThresholdVal=scoreThreshold;var softNmsSigmaVal=softNmsSigma;var _d=nonMaxSuppressionV5Impl(boxesVals,scoresVals,maxOutputSizeVal,iouThresholdVal,scoreThresholdVal,softNmsSigmaVal),selectedIndices=_d.selectedIndices,selectedScores=_d.selectedScores;return[selectedIndices,selectedScores]}};function padV2(args){var inputs=args.inputs,backend=args.backend,attrs=args.attrs;var x=inputs.x;var paddings=attrs.paddings,constantValue=attrs.constantValue;assertNotComplex(x,"pad");var outShape=paddings.map(function(p2,i2){return p2[0]+x.shape[i2]+p2[1]});var start=paddings.map(function(p2){return p2[0]});var xVals=backend.data.get(x.dataId).values;var xSize=tf4.util.sizeFromShape(x.shape);var xRank=x.shape.length;var xStrides=tf4.util.computeStrides(x.shape);var resultSize=tf4.util.sizeFromShape(outShape);var resultRank=outShape.length;var resultStrides=tf4.util.computeStrides(outShape);var resVals=tf4.util.getTypedArrayFromDType(x.dtype,resultSize);if(constantValue!==0){resVals.fill(constantValue)}for(var i=0;i=0&&coordX=0&&coordY.5){return Math.ceil(xi)}else{if(base%2===0){return base}else{return base+1}}});var roundConfig={kernelName:tf4.Round,backendName:"cpu",kernelFunc:round};var scaleAlpha=tf4.backend_util.SELU_SCALEALPHA;var scale=tf4.backend_util.SELU_SCALE;var selu=unaryKernelFunc(tf4.Selu,function(xi){if(xi>=0){return scale*xi}else{return scaleAlpha*(Math.exp(xi)-1)}});var seluConfig={kernelName:tf4.Selu,backendName:"cpu",kernelFunc:selu};var sigmoid2=unaryKernelFunc(tf4.Sigmoid,function(xi){return 1/(1+Math.exp(-xi))});var sigmoidConfig2={kernelName:tf4.Sigmoid,backendName:"cpu",kernelFunc:sigmoid2};var sign=unaryKernelFunc(tf4.Sign,function(xi){if(xi<0){return-1}else if(xi>0){return 1}else{return 0}});var signConfig={kernelName:tf4.Sign,backendName:"cpu",kernelFunc:sign};var sin=unaryKernelFunc(tf4.Sin,function(xi){return Math.sin(xi)});var sinConfig2={kernelName:tf4.Sin,backendName:"cpu",kernelFunc:sin};var sinh=unaryKernelFunc(tf4.Sinh,function(xi){return Math.sinh(xi)});var sinhConfig={kernelName:tf4.Sinh,backendName:"cpu",kernelFunc:sinh};var epsilon=11920928955078125e-23;var threshold=Math.log(epsilon)+2;var softplus=unaryKernelFunc(tf4.Softplus,function(xi){var tooLarge=xi>-threshold;var tooSmall=xi0?1:stepAttrs.alpha}});var stepConfig={kernelName:tf4.Step,backendName:"cpu",kernelFunc:step};var tan=unaryKernelFunc(tf4.Tan,function(xi){return Math.tan(xi)});var tanConfig={kernelName:tf4.Tan,backendName:"cpu",kernelFunc:tan};var tanh=unaryKernelFunc(tf4.Tanh,function(xi){return Math.tanh(xi)});var tanhConfig2={kernelName:tf4.Tanh,backendName:"cpu",kernelFunc:tanh};function unique(args){var inputs=args.inputs,attrs=args.attrs,backend=args.backend;var axis=attrs.axis;var x=inputs.x;assertNotComplex(x,"unique");var values=backend.data.get(x.dataId).values;var _a=uniqueImpl(values,axis,x.shape,x.dtype),outputValues=_a.outputValues,outputShape=_a.outputShape,indices=_a.indices;return[backend.makeTensorInfo(outputShape,x.dtype,outputValues),backend.makeTensorInfo([indices.length],"int32",indices)]}var uniqueConfig={kernelName:tf4.Unique,backendName:"cpu",kernelFunc:unique};var kernelConfigs2=[_fusedMatMulConfig,absConfig2,acosConfig,acoshConfig,addConfig2,asinConfig,asinhConfig,atanConfig,atanhConfig,avgPoolConfig2,avgPoolBackpropConfig,batchMatMulConfig2,batchNormConfig,castConfig2,ceilConfig,clipConfig,complexConfig,concatConfig2,conv2DBackpropFilterConfig,conv2DBackpropInputConfig2,conv2DConfig2,conv3DBackpropFilterV2Config,conv3DBackpropInputV2Config,conv3DConfig,cosConfig2,coshConfig,depthwiseConv2dNativeConfig2,depthwiseConv2dNativeBackpropFilterConfig,depthwiseConv2dNativeBackpropInputConfig,dilation2dConfig,dilation2dBackpropInputConfig,dilation2dBackpropFilterConfig,divConfig2,eluConfig,erfConfig,expConfig2,expm1Config,fftConfig,fillConfig2,flipLeftRightConfig2,floorConfig,fusedConv2DConfig2,fusedDepthwiseConv2DConfig2,identityConfig2,ifftConfig,imagConfig,isFiniteConfig,isInfConfig,isNaNConfig,logConfig2,log1pConfig,logicalNotConfig,maxPoolConfig2,maxPoolBackpropConfig,maxPoolWithArgmaxConfig,maxConfig2,mirrorPadConfig,multiplyConfig2,nonMaxSuppressionV4Config2,nonMaxSuppressionV5Config2,notEqualConfig2,padV2Config2,preluConfig2,realConfig,reciprocalConfig,reluConfig2,relu6Config2,reshapeConfig2,rotateWithOffsetConfig2,roundConfig,rsqrtConfig2,seluConfig,sigmoidConfig2,signConfig,sinConfig2,sinhConfig,sliceConfig2,softplusConfig,spaceToBatchNDConfig,sqrtConfig2,squareConfig2,squaredDifferenceConfig2,stepConfig,subConfig2,tanConfig,tanhConfig2,transposeConfig2,uniqueConfig];for(var _i=0,kernelConfigs_1=kernelConfigs2;_i{"use strict";Object.defineProperty(exports2,"__esModule",{value:true});var tf4=require_tf_core_node();var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d2,b2){d2.__proto__=b2}||function(d2,b2){for(var p in b2)if(b2.hasOwnProperty(p))d2[p]=b2[p]};return extendStatics(d,b)};function __extends(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}function __awaiter(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})}function __generator(thisArg,body2){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]maxTextureSize||height>maxTextureSize){var requested="["+width+"x"+height+"]";var max2="["+maxTextureSize+"x"+maxTextureSize+"]";throw new Error("Requested texture size "+requested+" greater than WebGL maximum on this browser / GPU "+max2+".")}}function createFramebuffer(gl){return throwIfNull(gl,function(){return gl.createFramebuffer()},"Unable to create WebGLFramebuffer.")}function bindVertexBufferToProgramAttribute(gl,program,attribute,buffer2,arrayEntriesPerItem,itemStrideInBytes,itemOffsetInBytes){var loc=gl.getAttribLocation(program,attribute);if(loc===-1){return false}callAndCheck(gl,function(){return gl.bindBuffer(gl.ARRAY_BUFFER,buffer2)});callAndCheck(gl,function(){return gl.vertexAttribPointer(loc,arrayEntriesPerItem,gl.FLOAT,false,itemStrideInBytes,itemOffsetInBytes)});callAndCheck(gl,function(){return gl.enableVertexAttribArray(loc)});return true}function bindTextureUnit(gl,texture,textureUnit){validateTextureUnit(gl,textureUnit);callAndCheck(gl,function(){return gl.activeTexture(gl.TEXTURE0+textureUnit)});callAndCheck(gl,function(){return gl.bindTexture(gl.TEXTURE_2D,texture)})}function unbindTextureUnit(gl,textureUnit){validateTextureUnit(gl,textureUnit);callAndCheck(gl,function(){return gl.activeTexture(gl.TEXTURE0+textureUnit)});callAndCheck(gl,function(){return gl.bindTexture(gl.TEXTURE_2D,null)})}function getProgramUniformLocationOrThrow(gl,program,uniformName){return throwIfNull(gl,function(){return gl.getUniformLocation(program,uniformName)},'uniform "'+uniformName+'" not present in program.')}function getProgramUniformLocation(gl,program,uniformName){return gl.getUniformLocation(program,uniformName)}function bindTextureToProgramUniformSampler(gl,texture,uniformSamplerLocation,textureUnit){callAndCheck(gl,function(){return bindTextureUnit(gl,texture,textureUnit)});callAndCheck(gl,function(){return gl.uniform1i(uniformSamplerLocation,textureUnit)})}function bindCanvasToFramebuffer(gl){callAndCheck(gl,function(){return gl.bindFramebuffer(gl.FRAMEBUFFER,null)});callAndCheck(gl,function(){return gl.viewport(0,0,gl.canvas.width,gl.canvas.height)});callAndCheck(gl,function(){return gl.scissor(0,0,gl.canvas.width,gl.canvas.height)})}function bindColorTextureToFramebuffer(gl,texture,framebuffer){callAndCheck(gl,function(){return gl.bindFramebuffer(gl.FRAMEBUFFER,framebuffer)});callAndCheck(gl,function(){return gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,texture,0)})}function unbindColorTextureFromFramebuffer(gl,framebuffer){callAndCheck(gl,function(){return gl.bindFramebuffer(gl.FRAMEBUFFER,framebuffer)});callAndCheck(gl,function(){return gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,null,0)})}function validateFramebuffer(gl){var status=gl.checkFramebufferStatus(gl.FRAMEBUFFER);if(status!==gl.FRAMEBUFFER_COMPLETE){throw new Error("Error binding framebuffer: "+getFramebufferErrorMessage(gl,status))}}function getFramebufferErrorMessage(gl,status){switch(status){case gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case gl.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return"unknown error "+status}}function throwIfNull(gl,returnTOrNull,failureMessage){var tOrNull=callAndCheck(gl,function(){return returnTOrNull()});if(tOrNull==null){throw new Error(failureMessage)}return tOrNull}function validateTextureUnit(gl,textureUnit){var maxTextureUnit=gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1;var glTextureUnit=textureUnit+gl.TEXTURE0;if(glTextureUnitmaxTextureUnit){var textureUnitRange="[gl.TEXTURE0, gl.TEXTURE"+maxTextureUnit+"]";throw new Error("textureUnit must be in "+textureUnitRange+".")}}function getBatchDim(shape,dimsToSkip){if(dimsToSkip===void 0){dimsToSkip=2}return tf4.util.sizeFromShape(shape.slice(0,shape.length-dimsToSkip))}function getRowsCols(shape){if(shape.length===0){throw Error("Cannot get rows and columns of an empty shape array.")}return[shape.length>1?shape[shape.length-2]:1,shape[shape.length-1]]}function getShapeAs3D(shape){var shapeAs3D=[1,1,1];var isScalar=shape.length===0||shape.length===1&&shape[0]===1;if(!isScalar){shapeAs3D=[getBatchDim(shape)].concat(getRowsCols(shape))}return shapeAs3D}function getTextureShapeFromLogicalShape(logShape,isPacked){var _a;if(isPacked===void 0){isPacked=false}var maxTexSize=tf4.env().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(isPacked){maxTexSize=maxTexSize*2;logShape=logShape.map(function(d,i){return i>=logShape.length-2?tf4.util.nearestLargerEven(logShape[i]):logShape[i]});if(logShape.length===1){logShape=[2,logShape[0]]}}if(logShape.length!==2){var squeezeResult=tf4.util.squeezeShape(logShape);logShape=squeezeResult.newShape}var size=tf4.util.sizeFromShape(logShape);if(logShape.length<=1&&size<=maxTexSize){return[1,size]}else if(logShape.length===2&&logShape[0]<=maxTexSize&&logShape[1]<=maxTexSize){return logShape}else if(logShape.length===3&&logShape[0]*logShape[1]<=maxTexSize&&logShape[2]<=maxTexSize){return[logShape[0]*logShape[1],logShape[2]]}else if(logShape.length===3&&logShape[0]<=maxTexSize&&logShape[1]*logShape[2]<=maxTexSize){return[logShape[0],logShape[1]*logShape[2]]}else if(logShape.length===4&&logShape[0]*logShape[1]*logShape[2]<=maxTexSize&&logShape[3]<=maxTexSize){return[logShape[0]*logShape[1]*logShape[2],logShape[3]]}else if(logShape.length===4&&logShape[0]<=maxTexSize&&logShape[1]*logShape[2]*logShape[3]<=maxTexSize){return[logShape[0],logShape[1]*logShape[2]*logShape[3]]}else{if(isPacked){var batchDim=getBatchDim(logShape);var rows=2,cols=2;if(logShape.length){_a=getRowsCols(logShape),rows=_a[0],cols=_a[1]}size=batchDim*(rows/2)*(cols/2);return tf4.util.sizeToSquarishShape(size).map(function(d){return d*2})}return tf4.util.sizeToSquarishShape(size)}}function isEven(n){return n%2===0}function isReshapeFree(shape1,shape2){shape1=shape1.slice(-2);shape2=shape2.slice(-2);if(tf4.util.arraysEqual(shape1,shape2)){return true}if(!shape1.length||!shape2.length){return true}if(shape1[0]===0||shape1[1]===0||shape2[0]===0||shape2[1]===0){return true}if(shape1.length!==shape2.length){var shape1Cols=shape1.slice(-1)[0];var shape2Cols=shape2.slice(-1)[0];if(shape1Cols===shape2Cols){return true}if(isEven(shape1Cols)&&isEven(shape2Cols)&&(shape1[0]===1||shape2[0]===1)){return true}}return shape1[1]===shape2[1]&&isEven(shape1[0])&&isEven(shape2[0])}var MAX_TEXTURE_SIZE;var MAX_TEXTURES_IN_SHADER;function getWebGLMaxTextureSize(webGLVersion){if(MAX_TEXTURE_SIZE==null){var gl=getWebGLContext(webGLVersion);MAX_TEXTURE_SIZE=gl.getParameter(gl.MAX_TEXTURE_SIZE)}return MAX_TEXTURE_SIZE}function resetMaxTextureSize(){MAX_TEXTURE_SIZE=null}function resetMaxTexturesInShader(){MAX_TEXTURES_IN_SHADER=null}function getMaxTexturesInShader(webGLVersion){if(MAX_TEXTURES_IN_SHADER==null){var gl=getWebGLContext(webGLVersion);MAX_TEXTURES_IN_SHADER=gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,MAX_TEXTURES_IN_SHADER)}function getWebGLDisjointQueryTimerVersion(webGLVersion){if(webGLVersion===0){return 0}var queryTimerVersion;var gl=getWebGLContext(webGLVersion);if(hasExtension(gl,"EXT_disjoint_timer_query_webgl2")&&webGLVersion===2){queryTimerVersion=2}else if(hasExtension(gl,"EXT_disjoint_timer_query")){queryTimerVersion=1}else{queryTimerVersion=0}return queryTimerVersion}function hasExtension(gl,extensionName){var ext=gl.getExtension(extensionName);return ext!=null}function isWebGLVersionEnabled(webGLVersion){try{var gl=getWebGLContext(webGLVersion);if(gl!=null){return true}}catch(e){console.log("Error when getting WebGL context: ",e);return false}return false}function isCapableOfRenderingToFloatTexture(webGLVersion){if(webGLVersion===0){return false}var gl=getWebGLContext(webGLVersion);if(webGLVersion===1){if(!hasExtension(gl,"OES_texture_float")){return false}}else{if(!hasExtension(gl,"EXT_color_buffer_float")){return false}}var isFrameBufferComplete=createFloatTextureAndBindToFramebuffer(gl);return isFrameBufferComplete}function isDownloadFloatTextureEnabled(webGLVersion){if(webGLVersion===0){return false}var gl=getWebGLContext(webGLVersion);if(webGLVersion===1){if(!hasExtension(gl,"OES_texture_float")){return false}if(!hasExtension(gl,"WEBGL_color_buffer_float")){return false}}else{if(hasExtension(gl,"EXT_color_buffer_float")){return createFloatTextureAndBindToFramebuffer(gl)}var COLOR_BUFFER_HALF_FLOAT="EXT_color_buffer_half_float";if(hasExtension(gl,COLOR_BUFFER_HALF_FLOAT)){var textureHalfFloatExtension=gl.getExtension(COLOR_BUFFER_HALF_FLOAT);return createHalfFloatTextureAndBindToFramebuffer(gl,textureHalfFloatExtension)}return false}var isFrameBufferComplete=createFloatTextureAndBindToFramebuffer(gl);return isFrameBufferComplete}function createFloatTextureAndBindToFramebuffer(gl){var texConfig=getTextureConfig(gl);var texture=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,texture);var width=1;var height=1;gl.texImage2D(gl.TEXTURE_2D,0,texConfig.internalFormatFloat,width,height,0,texConfig.textureFormatFloat,texConfig.textureTypeFloat,null);var frameBuffer=gl.createFramebuffer();gl.bindFramebuffer(gl.FRAMEBUFFER,frameBuffer);gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,texture,0);var isFrameBufferComplete=gl.checkFramebufferStatus(gl.FRAMEBUFFER)===gl.FRAMEBUFFER_COMPLETE;gl.bindTexture(gl.TEXTURE_2D,null);gl.bindFramebuffer(gl.FRAMEBUFFER,null);gl.deleteTexture(texture);gl.deleteFramebuffer(frameBuffer);return isFrameBufferComplete}function createHalfFloatTextureAndBindToFramebuffer(gl,textureHalfFloatExtension){var texConfig=getTextureConfig(gl,textureHalfFloatExtension);var texture=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,texture);var width=1;var height=1;gl.texImage2D(gl.TEXTURE_2D,0,texConfig.internalFormatHalfFloat,width,height,0,texConfig.textureFormatFloat,texConfig.textureTypeHalfFloat,null);var frameBuffer=gl.createFramebuffer();gl.bindFramebuffer(gl.FRAMEBUFFER,frameBuffer);gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,texture,0);var isFrameBufferComplete=gl.checkFramebufferStatus(gl.FRAMEBUFFER)===gl.FRAMEBUFFER_COMPLETE;gl.bindTexture(gl.TEXTURE_2D,null);gl.bindFramebuffer(gl.FRAMEBUFFER,null);gl.deleteTexture(texture);gl.deleteFramebuffer(frameBuffer);return isFrameBufferComplete}function isWebGLFenceEnabled(webGLVersion){if(webGLVersion!==2){return false}var gl=getWebGLContext(webGLVersion);var isEnabled=gl.fenceSync!=null;return isEnabled}function assertNotComplex(tensor,opName){if(!Array.isArray(tensor)){tensor=[tensor]}tensor.forEach(function(t){if(t!=null){tf4.util.assert(t.dtype!=="complex64",function(){return opName+" does not support complex64 tensors in the WebGL backend."})}})}var webgl_util={__proto__:null,callAndCheck,canBeRepresented,getWebGLErrorMessage,getExtensionOrThrow,createVertexShader,createFragmentShader,createProgram,linkProgram,validateProgram,createStaticVertexBuffer,createStaticIndexBuffer,getNumChannels,createTexture,validateTextureSize,createFramebuffer,bindVertexBufferToProgramAttribute,bindTextureUnit,unbindTextureUnit,getProgramUniformLocationOrThrow,getProgramUniformLocation,bindTextureToProgramUniformSampler,bindCanvasToFramebuffer,bindColorTextureToFramebuffer,unbindColorTextureFromFramebuffer,validateFramebuffer,getFramebufferErrorMessage,getBatchDim,getRowsCols,getShapeAs3D,getTextureShapeFromLogicalShape,isReshapeFree,getWebGLMaxTextureSize,resetMaxTextureSize,resetMaxTexturesInShader,getMaxTexturesInShader,getWebGLDisjointQueryTimerVersion,hasExtension,isWebGLVersionEnabled,isCapableOfRenderingToFloatTexture,isDownloadFloatTextureEnabled,isWebGLFenceEnabled,assertNotComplex};var ENV2=tf4.env();ENV2.registerFlag("HAS_WEBGL",function(){return ENV2.getNumber("WEBGL_VERSION")>0});ENV2.registerFlag("WEBGL_VERSION",function(){if(isWebGLVersionEnabled(2)){return 2}else if(isWebGLVersionEnabled(1)){return 1}return 0});ENV2.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",function(){return false});ENV2.registerFlag("WEBGL_BUFFER_SUPPORTED",function(){return ENV2.get("WEBGL_VERSION")===2});ENV2.registerFlag("WEBGL_CPU_FORWARD",function(){return true});ENV2.registerFlag("WEBGL_FORCE_F16_TEXTURES",function(){return false});ENV2.registerFlag("WEBGL_PACK",function(){return ENV2.getBool("HAS_WEBGL")});ENV2.registerFlag("WEBGL_PACK_NORMALIZATION",function(){return ENV2.getBool("WEBGL_PACK")});ENV2.registerFlag("WEBGL_PACK_CLIP",function(){return ENV2.getBool("WEBGL_PACK")});ENV2.registerFlag("WEBGL_PACK_DEPTHWISECONV",function(){return false});ENV2.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",function(){return ENV2.getBool("WEBGL_PACK")});ENV2.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",function(){return ENV2.getBool("WEBGL_PACK")});ENV2.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",function(){return ENV2.getBool("WEBGL_PACK")});ENV2.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",function(){return ENV2.getBool("WEBGL_PACK")});ENV2.registerFlag("WEBGL_PACK_REDUCE",function(){return ENV2.getBool("WEBGL_PACK")});ENV2.registerFlag("WEBGL_LAZILY_UNPACK",function(){return ENV2.getBool("WEBGL_PACK")});ENV2.registerFlag("WEBGL_CONV_IM2COL",function(){return ENV2.getBool("WEBGL_PACK")});ENV2.registerFlag("WEBGL_MAX_TEXTURE_SIZE",function(){return getWebGLMaxTextureSize(ENV2.getNumber("WEBGL_VERSION"))});ENV2.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",function(){return getMaxTexturesInShader(ENV2.getNumber("WEBGL_VERSION"))});ENV2.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",function(){var webGLVersion=ENV2.getNumber("WEBGL_VERSION");if(webGLVersion===0){return 0}return getWebGLDisjointQueryTimerVersion(webGLVersion)});ENV2.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",function(){return ENV2.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!tf4.device_util.isMobile()});ENV2.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",function(){return isCapableOfRenderingToFloatTexture(ENV2.getNumber("WEBGL_VERSION"))});ENV2.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",function(){return ENV2.getBool("WEBGL_FORCE_F16_TEXTURES")?false:ENV2.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")});ENV2.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",function(){return isDownloadFloatTextureEnabled(ENV2.getNumber("WEBGL_VERSION"))});ENV2.registerFlag("WEBGL_FENCE_API_ENABLED",function(){return isWebGLFenceEnabled(ENV2.getNumber("WEBGL_VERSION"))});ENV2.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",function(){var useUniforms=ENV2.getBool("WEBGL_RENDER_FLOAT32_ENABLED");return useUniforms?4:0});ENV2.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",function(){return-1},function(threshold){if(threshold<0&&threshold!==-1){throw new Error("WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never "+("delete) or at least 0, but got "+threshold+"."))}});function simpleAbsImpl(vals){const resultValues=new Float32Array(vals.length);for(let i=0;i{const newShape=tf4.backend_util.assertAndGetBroadcastShape(aShape,bShape);const resultRank=newShape.length;const resultStrides=tf4.util.computeStrides(newShape);const resultSize=tf4.util.sizeFromShape(newShape);const result=tf4.util.getTypedArrayFromDType(dtype,resultSize);const aRank=aShape.length;const bRank=bShape.length;const aStrides=tf4.util.computeStrides(aShape);const bStrides=tf4.util.computeStrides(bShape);const aBroadcastDims=tf4.backend_util.getBroadcastDims(aShape,newShape);const bBroadcastDims=tf4.backend_util.getBroadcastDims(bShape,newShape);if(aBroadcastDims.length+bBroadcastDims.length===0){for(let i=0;iaLoc[d]=0);const aIndex=tf4.util.locToIndex(aLoc,aRank,aStrides);const bLoc=loc.slice(-bRank);bBroadcastDims.forEach(d=>bLoc[d]=0);const bIndex=tf4.util.locToIndex(bLoc,bRank,bStrides);result[i]=op(aVals[aIndex],bVals[bIndex])}}return[result,newShape]}}const addImpl=createSimpleBinaryKernelImpl((a,b)=>a+b);function createSimpleUnaryImpl(op){return(values,dtype,attrs)=>{const newValues=tf4.util.getTypedArrayFromDType(dtype,values.length);for(let i=0;iMath.ceil(xi));const expImpl=createSimpleUnaryImpl(xi=>Math.exp(xi));const expm1Impl=createSimpleUnaryImpl(xi=>Math.expm1(xi));const floorImpl=createSimpleUnaryImpl(xi=>Math.floor(xi));const logImpl=createSimpleUnaryImpl(xi=>Math.log(xi));function maxImpl(aVals,reduceSize,outShape,dtype){const vals=tf4.util.getTypedArrayFromDType(dtype,tf4.util.sizeFromShape(outShape));for(let i=0;imax2){max2=value}}vals[i]=max2}return vals}const multiplyImpl=createSimpleBinaryKernelImpl((aValue,bValue)=>aValue*bValue);const rsqrtImpl=createSimpleUnaryImpl(xi=>1/Math.sqrt(xi));function sliceImpl(vals,begin,size,shape,dtype){const isContinous=tf4.slice_util.isSliceContinous(shape,begin,size);const length=tf4.util.sizeFromShape(size);const xStrides=tf4.util.computeStrides(shape);if(isContinous){const flatOffset=tf4.slice_util.computeFlatOffset(begin,xStrides);return vals.subarray(flatOffset,flatOffset+length)}const outVals=tf4.util.getTypedArrayFromDType(dtype,length);for(let i=0;iidx+begin[j]);const xIndex=tf4.util.locToIndex(xLoc,shape.length,xStrides);outVals[i]=vals[xIndex]}return outVals}const subImpl=createSimpleBinaryKernelImpl((aValue,bValue)=>aValue-bValue);function transposeImpl(xVals,xShape,dtype,perm,newShape){const xRank=xShape.length;const xSize=tf4.util.sizeFromShape(xShape);const xStrides=tf4.util.computeStrides(xShape);const newStrides=tf4.util.computeStrides(newShape);const result=tf4.util.getTypedArrayFromDType(dtype,tf4.util.sizeFromShape(newShape));for(let i=0;i{for(let m=0;m":"<";var indexSnippet=firstPass?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+windowSize+";\n\n int bestIndex = inOffset;\n float bestValue = getA(batch, bestIndex);\n\n for (int i = 0; i < "+windowSize+"; i++) {\n int inIdx = "+indexSnippet+";\n float candidate = getA(batch, inIdx);\n if (candidate "+compOp+" bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\n "}return ArgMinMaxProgram2}();function getVecChannels(name,rank){return["x","y","z","w","u","v"].slice(0,rank).map(function(d){return name+"."+d})}function getChannels(name,rank){if(rank===1){return[name]}return getVecChannels(name,rank)}function getSourceCoords(rank,dims){if(rank===1){return"rc"}var coords2="";for(var i=0;i1?"["+size+"]":"")+";")}else{prefixSnippets.push("uniform sampler2D "+x.name+";");prefixSnippets.push("uniform int offset"+x.name+";")}});var inputPrefixSnippet=prefixSnippets.join("\n");var inputSamplingSnippet=inputsInfo.map(function(x){return getInputSamplingSnippet(x,outputShape,usesPackedTextures)}).join("\n");var outTexShape=outputShape.texShape;var glsl=getGlslDifferences();var floatTextureSampleSnippet=getFloatTextureSampleSnippet(glsl);var outputSamplingSnippet;var floatTextureSetOutputSnippet;var shaderPrefix=getShaderPrefix(glsl);if(outputShape.isPacked){outputSamplingSnippet=getPackedOutputSamplingSnippet(outputShape.logicalShape,outTexShape);floatTextureSetOutputSnippet=getFloatTextureSetRGBASnippet(glsl)}else{outputSamplingSnippet=getOutputSamplingSnippet(outputShape.logicalShape,outTexShape);floatTextureSetOutputSnippet=getFloatTextureSetRSnippet(glsl)}if(usesPackedTextures){shaderPrefix+=SHADER_PACKED_PREFIX}var source=[shaderPrefix,floatTextureSampleSnippet,floatTextureSetOutputSnippet,inputPrefixSnippet,outputSamplingSnippet,inputSamplingSnippet,userCode].join("\n");return source}function getSamplerFromInInfo(inInfo){var shape=inInfo.shapeInfo.logicalShape;switch(shape.length){case 0:return getSamplerScalar(inInfo);case 1:return getSampler1D(inInfo);case 2:return getSampler2D(inInfo);case 3:return getSampler3D(inInfo);case 4:return getSampler4D(inInfo);case 5:return getSampler5D(inInfo);case 6:return getSampler6D(inInfo);default:throw new Error(shape.length+"-D input sampling is not yet supported")}}function getPackedSamplerFromInInfo(inInfo){var shape=inInfo.shapeInfo.logicalShape;switch(shape.length){case 0:return getPackedSamplerScalar(inInfo);case 1:return getPackedSampler1D(inInfo);case 2:return getPackedSampler2D(inInfo);case 3:return getPackedSampler3D(inInfo);default:return getPackedSamplerND(inInfo)}}function getInputSamplingSnippet(inInfo,outShapeInfo,usesPackedTextures){if(usesPackedTextures===void 0){usesPackedTextures=false}var res="";if(usesPackedTextures){res+=getPackedSamplerFromInInfo(inInfo)}else{res+=getSamplerFromInInfo(inInfo)}var inShape=inInfo.shapeInfo.logicalShape;var outShape=outShapeInfo.logicalShape;if(inShape.length<=outShape.length){if(usesPackedTextures){res+=getPackedSamplerAtOutputCoords(inInfo,outShapeInfo)}else{res+=getSamplerAtOutputCoords(inInfo,outShapeInfo)}}return res}function getPackedOutputSamplingSnippet(outShape,outTexShape){switch(outShape.length){case 0:return getOutputScalarCoords();case 1:return getOutputPacked1DCoords(outShape,outTexShape);case 2:return getOutputPacked2DCoords(outShape,outTexShape);case 3:return getOutputPacked3DCoords(outShape,outTexShape);default:return getOutputPackedNDCoords(outShape,outTexShape)}}function getOutputSamplingSnippet(outShape,outTexShape){switch(outShape.length){case 0:return getOutputScalarCoords();case 1:return getOutput1DCoords(outShape,outTexShape);case 2:return getOutput2DCoords(outShape,outTexShape);case 3:return getOutput3DCoords(outShape,outTexShape);case 4:return getOutput4DCoords(outShape,outTexShape);case 5:return getOutput5DCoords(outShape,outTexShape);case 6:return getOutput6DCoords(outShape,outTexShape);default:throw new Error(outShape.length+"-D output sampling is not yet supported")}}function getFloatTextureSampleSnippet(glsl){return"\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return "+glsl.texture2D+"(textureSampler, uv).r;\n }\n "}function getFloatTextureSetRSnippet(glsl){return"\n void setOutput(float val) {\n "+glsl.output+" = vec4(val, 0, 0, 0);\n }\n "}function getFloatTextureSetRGBASnippet(glsl){return"\n void setOutput(vec4 val) {\n "+glsl.output+" = val;\n }\n "}function getShaderPrefix(glsl){var SHADER_PREFIX=glsl.version+"\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n "+glsl.varyingFs+" vec2 resultUV;\n "+glsl.defineOutput+"\n const vec2 halfCR = vec2(0.5, 0.5);\n\n struct ivec5\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n };\n\n struct ivec6\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n int v;\n };\n\n uniform float NAN;\n "+glsl.defineSpecialNaN+"\n "+glsl.defineSpecialInf+"\n "+glsl.defineRound+"\n\n int imod(int x, int y) {\n return x - y * (x / y);\n }\n\n int idiv(int a, int b, float sign) {\n int res = a / b;\n int mod = imod(a, b);\n if (sign < 0. && mod != 0) {\n res -= 1;\n }\n return res;\n }\n\n //Based on the work of Dave Hoskins\n //https://www.shadertoy.com/view/4djSRW\n #define HASHSCALE1 443.8975\n float random(float seed){\n vec2 p = resultUV * seed;\n vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);\n p3 += dot(p3, p3.yzx + 19.19);\n return fract((p3.x + p3.y) * p3.z);\n }\n\n "+SAMPLE_1D_SNIPPET+"\n "+SAMPLE_2D_SNIPPET+"\n "+SAMPLE_3D_SNIPPET+"\n ";return SHADER_PREFIX}var SAMPLE_1D_SNIPPET="\nvec2 uvFromFlat(int texNumR, int texNumC, int index) {\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\nvec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n int texelIndex = index / 2;\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n";var SAMPLE_2D_SNIPPET="\nvec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,\n int texNumC, int row, int col) {\n int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n";var SAMPLE_3D_SNIPPET="\nvec2 packedUVfrom3D(int texNumR, int texNumC,\n int texelsInBatch, int texelsInLogicalRow, int b,\n int row, int col) {\n int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n";var SHADER_PACKED_PREFIX="\n float getChannel(vec4 frag, vec2 innerDims) {\n vec2 modCoord = mod(innerDims, 2.);\n return modCoord.x == 0. ?\n (modCoord.y == 0. ? frag.r : frag.g) :\n (modCoord.y == 0. ? frag.b : frag.a);\n }\n float getChannel(vec4 frag, int dim) {\n float modCoord = mod(float(dim), 2.);\n return modCoord == 0. ? frag.r : frag.g;\n }\n";function getOutputScalarCoords(){return"\n int getOutputCoords() {\n return 0;\n }\n "}function getOutputPacked1DCoords(shape,texShape){var packedTexShape=[Math.ceil(texShape[0]/2),Math.ceil(texShape[1]/2)];if(packedTexShape[0]===1){return"\n int getOutputCoords() {\n return 2 * int(resultUV.x * "+packedTexShape[1]+".0);\n }\n "}if(packedTexShape[1]===1){return"\n int getOutputCoords() {\n return 2 * int(resultUV.y * "+packedTexShape[0]+".0);\n }\n "}return"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+packedTexShape[0]+", "+packedTexShape[1]+"));\n return 2 * (resTexRC.x * "+packedTexShape[1]+" + resTexRC.y);\n }\n "}function getOutput1DCoords(shape,texShape){if(texShape[0]===1){return"\n int getOutputCoords() {\n return int(resultUV.x * "+texShape[1]+".0);\n }\n "}if(texShape[1]===1){return"\n int getOutputCoords() {\n return int(resultUV.y * "+texShape[0]+".0);\n }\n "}return"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+texShape[0]+", "+texShape[1]+"));\n return resTexRC.x * "+texShape[1]+" + resTexRC.y;\n }\n "}function getOutputPacked3DCoords(shape,texShape){var packedTexShape=[Math.ceil(texShape[0]/2),Math.ceil(texShape[1]/2)];var texelsInLogicalRow=Math.ceil(shape[2]/2);var texelsInBatch=texelsInLogicalRow*Math.ceil(shape[1]/2);return"\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+packedTexShape[0]+", "+packedTexShape[1]+"));\n int index = resTexRC.x * "+packedTexShape[1]+" + resTexRC.y;\n\n int b = index / "+texelsInBatch+";\n index -= b * "+texelsInBatch+";\n\n int r = 2 * (index / "+texelsInLogicalRow+");\n int c = imod(index, "+texelsInLogicalRow+") * 2;\n\n return ivec3(b, r, c);\n }\n "}function getOutput3DCoords(shape,texShape){var coordsFromIndexSnippet=getLogicalCoordinatesFromFlatIndex(["r","c","d"],shape);return"\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+texShape[0]+", "+texShape[1]+"));\n int index = resTexRC.x * "+texShape[1]+" + resTexRC.y;\n "+coordsFromIndexSnippet+"\n return ivec3(r, c, d);\n }\n "}function getOutputPackedNDCoords(shape,texShape){var packedTexShape=[Math.ceil(texShape[0]/2),Math.ceil(texShape[1]/2)];var texelsInLogicalRow=Math.ceil(shape[shape.length-1]/2);var texelsInBatch=texelsInLogicalRow*Math.ceil(shape[shape.length-2]/2);var texelsInBatchN=texelsInBatch;var batches="";var coords2="b, r, c";for(var b=2;b=1){coordsSnippet="coords = 0;"}else{coordsSnippet=broadcastDims.map(function(d){return"coords."+fields[d+rankDiff]+" = 0;"}).join("\n")}var unpackedCoordsSnippet="";if(outRank<2&&inRank>0){unpackedCoordsSnippet="coords"}else{unpackedCoordsSnippet=inputInfo.shapeInfo.logicalShape.map(function(s,i){return"coords."+fields[i+rankDiff]}).join(", ")}var output="return outputValue;";var inSize=tf4.util.sizeFromShape(inputInfo.shapeInfo.logicalShape);var isInputScalar=inSize===1;var outSize=tf4.util.sizeFromShape(outShapeInfo.logicalShape);var isOutputScalar=outSize===1;if(inRank===1&&!isInputScalar&&!isOutputScalar){output="\n return vec4(outputValue.xy, outputValue.xy);\n "}else if(isInputScalar&&!isOutputScalar){if(outRank===1){output="\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n "}else{output="\n return vec4(outputValue.x);\n "}}else if(broadcastDims.length){var rows=inRank-2;var cols=inRank-1;if(broadcastDims.indexOf(rows)>-1&&broadcastDims.indexOf(cols)>-1){output="return vec4(outputValue.x);"}else if(broadcastDims.indexOf(rows)>-1){output="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);"}else if(broadcastDims.indexOf(cols)>-1){output="return vec4(outputValue.xx, outputValue.zz);"}}return"\n vec4 "+funcName+"() {\n "+type+" coords = getOutputCoords();\n "+coordsSnippet+"\n vec4 outputValue = get"+texFuncSnippet+"("+unpackedCoordsSnippet+");\n "+output+"\n }\n "}function getSamplerAtOutputCoords(inputInfo,outShapeInfo){var texName=inputInfo.name;var texFuncSnippet=texName.charAt(0).toUpperCase()+texName.slice(1);var funcName="get"+texFuncSnippet+"AtOutCoords";var outTexShape=outShapeInfo.texShape;var inTexShape=inputInfo.shapeInfo.texShape;var inRank=inputInfo.shapeInfo.logicalShape.length;var outRank=outShapeInfo.logicalShape.length;if(!inputInfo.shapeInfo.isUniform&&inRank===outRank&&inputInfo.shapeInfo.flatOffset==null&&tf4.util.arraysEqual(inTexShape,outTexShape)){return"\n float "+funcName+"() {\n return sampleTexture("+texName+", resultUV);\n }\n "}var type=getCoordsDataType(outRank);var broadcastDims=getBroadcastDims(inputInfo.shapeInfo.logicalShape,outShapeInfo.logicalShape);var rankDiff=outRank-inRank;var coordsSnippet;var fields=["x","y","z","w","u","v"];if(inRank===0){coordsSnippet=""}else if(outRank<2&&broadcastDims.length>=1){coordsSnippet="coords = 0;"}else{coordsSnippet=broadcastDims.map(function(d){return"coords."+fields[d+rankDiff]+" = 0;"}).join("\n")}var unpackedCoordsSnippet="";if(outRank<2&&inRank>0){unpackedCoordsSnippet="coords"}else{unpackedCoordsSnippet=inputInfo.shapeInfo.logicalShape.map(function(s,i){return"coords."+fields[i+rankDiff]}).join(", ")}return"\n float "+funcName+"() {\n "+type+" coords = getOutputCoords();\n "+coordsSnippet+"\n return get"+texFuncSnippet+"("+unpackedCoordsSnippet+");\n }\n "}function getCoordsDataType(rank){if(rank<=1){return"int"}else if(rank===2){return"ivec2"}else if(rank===3){return"ivec3"}else if(rank===4){return"ivec4"}else if(rank===5){return"ivec5"}else if(rank===6){return"ivec6"}else{throw Error("GPU for rank "+rank+" is not yet supported")}}function squeezeInputInfo(inInfo,squeezedShape){var newInputInfo=JSON.parse(JSON.stringify(inInfo));newInputInfo.shapeInfo.logicalShape=squeezedShape;return newInputInfo}function getSqueezedParams(params,keptDims){return keptDims.map(function(d){return params[d]}).join(", ")}var ArgMinMaxPackedProgram=function(){function ArgMinMaxPackedProgram2(shape,windowSize,op,firstPass){this.variableNames=["A"];this.packedInputs=true;this.packedOutput=true;tf4.util.assert(shape.length>2,function(){return"Packed arg"+(op.charAt(0).toUpperCase()+op.slice(1))+" supports only inputs with rank above 2."});var inSize=shape[shape.length-1];var outSize=Math.ceil(inSize/windowSize);this.outputShape=shape.slice(0,-1);if(outSize>1){this.outputShape.push(outSize)}if(!firstPass){this.variableNames.push("bestIndicesA")}var outShape=this.outputShape;var rank=outShape.length;var dtype=getCoordsDataType(rank);var coords2=getChannels("coords",rank);var sourceLocSetup;var sourceRank;if(outSize===1){sourceRank=rank+1;var sourceLocDType=getCoordsDataType(sourceRank);sourceLocSetup="\n "+sourceLocDType+" sourceLocR = "+sourceLocDType+"("+coords2.join()+", 0);\n ++"+coords2[rank-1]+";\n "+sourceLocDType+" sourceLocG = "+sourceLocDType+"("+coords2.join()+", 0);\n ++"+coords2[rank-2]+";\n "+sourceLocDType+" sourceLocA = "+sourceLocDType+"("+coords2.join()+", 0);\n --"+coords2[rank-1]+";\n "+sourceLocDType+" sourceLocB = "+sourceLocDType+"("+coords2.join()+", 0);\n --"+coords2[rank-2]+";"}else{sourceRank=rank;sourceLocSetup="\n "+dtype+" sourceLocR = coords;\n ++"+coords2[rank-1]+";\n "+dtype+" sourceLocG = coords;\n ++"+coords2[rank-2]+";\n "+dtype+" sourceLocA = coords;\n --"+coords2[rank-1]+";\n "+dtype+" sourceLocB = coords;\n --"+coords2[rank-2]+";"}var channels=["x","y","z","w","u","v"].slice(0,sourceRank);var inChannel="."+channels[sourceRank-1];var intChannels=channels.map(function(x){return"int "+x});var srcRCoords=getChannels("sourceLocR",sourceRank-1).concat("inIdx.r");var srcGCoords=getChannels("sourceLocG",sourceRank-1).concat("inIdx.g");var srcBCoords=getChannels("sourceLocB",sourceRank-1).concat("inIdx.b");var srcACoords=getChannels("sourceLocA",sourceRank-1).concat("inIdx.a");var compOp=op==="max"?"greaterThan":"lessThan";var fetchCandidateIdx=firstPass?"":"\n inIdx = round(vec4(getBestIndicesAChannel("+srcRCoords.join()+"),\n getBestIndicesAChannel("+srcGCoords.join()+"),\n getBestIndicesAChannel("+srcBCoords.join()+"),\n getBestIndicesAChannel("+srcACoords.join()+")));";var fetchValue="vec4(\n getAChannel("+srcRCoords.join()+"),\n hasNextCol ? getAChannel("+srcGCoords.join()+") : 0.,\n hasNextRow ? getAChannel("+srcBCoords.join()+") : 0.,\n hasNextRow && hasNextCol ? getAChannel("+srcACoords.join()+") : 0.)";var getBestIndicesAChannelSnippet=firstPass?"":"\n float getBestIndicesAChannel("+intChannels.join()+") {\n return getChannel(getBestIndicesA("+channels.join()+"),\n vec2("+channels.slice(-2).join()+"));\n }";this.userCode="\n float getAChannel("+intChannels.join()+") {\n return getChannel(getA("+channels.join()+"),\n vec2("+channels.slice(-2).join()+"));\n }\n "+getBestIndicesAChannelSnippet+"\n void main() {\n "+dtype+" coords = getOutputCoords();\n bool hasNextCol = "+coords2[rank-1]+" < "+(outShape[rank-1]-1)+";\n bool hasNextRow = "+coords2[rank-2]+" < "+(outShape[rank-2]-1)+";\n "+sourceLocSetup+"\n ivec4 srcIdx = ivec4(sourceLocR"+inChannel+", sourceLocG"+inChannel+",\n sourceLocB"+inChannel+", sourceLocA"+inChannel+") * "+windowSize+";\n ivec4 inIdx = srcIdx;\n vec4 bestIndex = vec4(inIdx);\n vec4 bestValue = "+fetchValue+";\n\n for (int i = 0; i < "+windowSize+"; i++) {\n inIdx = srcIdx;\n "+fetchCandidateIdx+"\n vec4 candidate = "+fetchValue+";\n bvec4 nan = isnan(candidate);\n bvec4 replace = bvec4(\n vec4("+compOp+"(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));\n\n bestValue = vec4(replace.x ? candidate.x : bestValue.x,\n replace.y ? candidate.y : bestValue.y,\n replace.z ? candidate.z : bestValue.z,\n replace.w ? candidate.w : bestValue.w);\n bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));\n srcIdx++;\n }\n setOutput(bestIndex);\n }\n "}return ArgMinMaxPackedProgram2}();var AvgPool2DBackpropProgram=function(){function AvgPool2DBackpropProgram2(convInfo){this.variableNames=["dy"];this.outputShape=convInfo.inShape;var filterHeight=convInfo.filterHeight;var filterWidth=convInfo.filterWidth;var strideHeight=convInfo.strideHeight;var strideWidth=convInfo.strideWidth;var dilationHeight=convInfo.dilationHeight;var dilationWidth=convInfo.dilationWidth;var effectiveFilterHeight=convInfo.effectiveFilterHeight;var effectiveFilterWidth=convInfo.effectiveFilterWidth;var padTop=effectiveFilterHeight-1-convInfo.padInfo.top;var padLeft=effectiveFilterWidth-1-convInfo.padInfo.left;var avgMultiplier=1/(filterHeight*filterWidth);this.userCode="\n const ivec2 pads = ivec2("+padTop+", "+padLeft+");\n const float avgMultiplier = float("+avgMultiplier+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+effectiveFilterHeight+";\n wR += "+dilationHeight+") {\n float dyR = float(dyRCorner + wR) / "+strideHeight+".0;\n\n if (dyR < 0.0 || dyR >= "+convInfo.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+effectiveFilterWidth+";\n wC+= "+dilationWidth+") {\n float dyC = float(dyCCorner + wC) / "+strideWidth+".0;\n\n if (dyC < 0.0 || dyC >= "+convInfo.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n setOutput(dotProd);\n }\n "}return AvgPool2DBackpropProgram2}();var AvgPool3DBackpropProgram=function(){function AvgPool3DBackpropProgram2(convInfo){this.variableNames=["dy"];this.outputShape=convInfo.inShape;var filterDepth=convInfo.filterDepth;var filterHeight=convInfo.filterHeight;var filterWidth=convInfo.filterWidth;var strideDepth=convInfo.strideDepth;var strideHeight=convInfo.strideHeight;var strideWidth=convInfo.strideWidth;var dilationDepth=convInfo.dilationDepth;var dilationHeight=convInfo.dilationHeight;var dilationWidth=convInfo.dilationWidth;var effectiveFilterDepth=convInfo.effectiveFilterDepth;var effectiveFilterHeight=convInfo.effectiveFilterHeight;var effectiveFilterWidth=convInfo.effectiveFilterWidth;var padFront=effectiveFilterDepth-1-convInfo.padInfo.front;var padTop=effectiveFilterHeight-1-convInfo.padInfo.top;var padLeft=effectiveFilterWidth-1-convInfo.padInfo.left;var avgMultiplier=1/(filterDepth*filterHeight*filterWidth);this.userCode="\n const ivec3 pads = ivec3("+padFront+", "+padTop+", "+padLeft+");\n const float avgMultiplier = float("+avgMultiplier+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < "+effectiveFilterDepth+";\n wD += "+dilationDepth+") {\n float dyD = float(dyDCorner + wD) / "+strideDepth+".0;\n\n if (dyD < 0.0 || dyD >= "+convInfo.outDepth+".0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < "+effectiveFilterHeight+";\n wR += "+dilationHeight+") {\n float dyR = float(dyRCorner + wR) / "+strideHeight+".0;\n\n if (dyR < 0.0 || dyR >= "+convInfo.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+effectiveFilterWidth+";\n wC += "+dilationWidth+") {\n float dyC = float(dyCCorner + wC) / "+strideWidth+".0;\n\n if (dyC < 0.0 || dyC >= "+convInfo.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n }\n setOutput(dotProd);\n }\n "}return AvgPool3DBackpropProgram2}();var CHECK_NAN_SNIPPET="\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n";var INT_DIV="\n float s = sign(a) * sign(b);\n int ia = round(a);\n int ib = round(b);\n if (ib != 0) {\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n return float(idiv(ia, ib, s));\n } else {\n return NAN;\n }\n";var POW="\nif(a < 0.0 && floor(b) < b){\n return NAN;\n}\nif (b == 0.0) {\n return 1.0;\n}\nreturn (round(mod(b, 2.0)) != 1) ?\n pow(abs(a), b) : sign(a) * pow(abs(a), b);\n";var EQUAL="return float(a == b);";var LESS="return float(a < b);";var LESS_EQUAL="return float(a <= b);";var GREATER="return float(a > b);";var GREATER_EQUAL="return float(a >= b);";var LOGICAL_AND="return float(a >= 1.0 && b >= 1.0);";var LOGICAL_OR="return float(a >= 1.0 || b >= 1.0);";var MAX=CHECK_NAN_SNIPPET+"\n return max(a, b);\n";var MIN=CHECK_NAN_SNIPPET+"\n return min(a, b);\n";var MOD="if (b == 0.0) return NAN;\n return mod(a, b);";var ELU_DER="return (b >= 1.0) ? a : a * (b + 1.0);";var PRELU="return (a < 0.) ? b * a : a;";var BinaryOpProgram=function(){function BinaryOpProgram2(op,aShape,bShape){this.variableNames=["A","B"];this.outputShape=tf4.backend_util.assertAndGetBroadcastShape(aShape,bShape);this.userCode="\n float binaryOperation(float a, float b) {\n "+op+"\n }\n\n void main() {\n float a = getAAtOutCoords();\n float b = getBAtOutCoords();\n setOutput(binaryOperation(a, b));\n }\n "}return BinaryOpProgram2}();var CHECK_NAN_SNIPPET$1="\n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n";var INT_DIV$1="\n ivec4 ia = round(a);\n ivec4 ib = round(b);\n bvec4 cond = notEqual(ib, ivec4(0));\n ivec4 result = ivec4(0);\n vec4 s = sign(a) * sign(b);\n\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n if (cond[0]) {\n result[0] = idiv(ia[0], ib[0], s[0]);\n }\n if (cond[1]) {\n result[1] = idiv(ia[1], ib[1], s[1]);\n }\n if (cond[2]) {\n result[2] = idiv(ia[2], ib[2], s[2]);\n }\n if (cond[3]) {\n result[3] = idiv(ia[3], ib[3], s[3]);\n }\n return vec4(result);\n";var POW$1="\n // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.\n vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));\n vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);\n vec4 result = multiplier * pow(abs(a), b);\n\n // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS\n bvec4 isExpZero = equal(b, vec4(0.0));\n result.r = isExpZero.r ? 1.0 : result.r;\n result.g = isExpZero.g ? 1.0 : result.g;\n result.b = isExpZero.b ? 1.0 : result.b;\n result.a = isExpZero.a ? 1.0 : result.a;\n\n vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));\n "+CHECK_NAN_SNIPPET$1+"\n return result;\n";var PRELU$1="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n";var ELU_DER$1="\n vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n";var EQUAL$1="\n return vec4(equal(a, b));\n";var LESS$1="\n return vec4(lessThan(a, b));\n";var LESS_EQUAL$1="\n return vec4(lessThanEqual(a, b));\n";var GREATER$1="\n return vec4(greaterThan(a, b));\n";var GREATER_EQUAL$1="\n return vec4(greaterThanEqual(a, b));\n";var LOGICAL_AND$1="\n return vec4(\n vec4(greaterThanEqual(a, vec4(1.0))) *\n vec4(greaterThanEqual(b, vec4(1.0))));\n";var LOGICAL_OR$1="\n return min(\n vec4(greaterThanEqual(a, vec4(1.0))) +\n vec4(greaterThanEqual(b, vec4(1.0))),\n vec4(1.0));\n";var MAX$1="\n vec4 result = vec4(max(a, b));\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n "+CHECK_NAN_SNIPPET$1+"\n return result;\n";var MIN$1="\n vec4 result = vec4(min(a, b));\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n "+CHECK_NAN_SNIPPET$1+"\n return result;\n";var MOD$1="\n vec4 result = mod(a, b);\n vec4 isNaN = vec4(equal(b, vec4(0.0)));\n "+CHECK_NAN_SNIPPET$1+"\n return result;\n";var BinaryOpPackedProgram=function(){function BinaryOpPackedProgram2(op,aShape,bShape,checkOutOfBounds){if(checkOutOfBounds===void 0){checkOutOfBounds=false}this.variableNames=["A","B"];this.supportsBroadcasting=true;this.packedInputs=true;this.packedOutput=true;this.outputShape=tf4.backend_util.assertAndGetBroadcastShape(aShape,bShape);var rank=this.outputShape.length;var checkOutOfBoundsString="";if(checkOutOfBounds){if(rank===0||tf4.util.sizeFromShape(this.outputShape)===1){checkOutOfBoundsString="\n result.y = 0.;\n result.z = 0.;\n result.w = 0.;\n "}else{var dtype=getCoordsDataType(rank);checkOutOfBoundsString="\n "+dtype+" coords = getOutputCoords();\n ";if(rank===1){checkOutOfBoundsString+="\n result.y = (coords + 1) >= "+this.outputShape[0]+" ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n "}else{var channels=getChannels("coords",rank);checkOutOfBoundsString+="\n bool nextRowOutOfBounds =\n ("+channels[rank-2]+" + 1) >= "+this.outputShape[rank-2]+";\n bool nextColOutOfBounds =\n ("+channels[rank-1]+" + 1) >= "+this.outputShape[rank-1]+";\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n "}}}this.userCode="\n vec4 binaryOperation(vec4 a, vec4 b) {\n "+op+"\n }\n\n void main() {\n vec4 a = getAAtOutCoords();\n vec4 b = getBAtOutCoords();\n\n vec4 result = binaryOperation(a, b);\n "+checkOutOfBoundsString+"\n\n setOutput(result);\n }\n "}return BinaryOpPackedProgram2}();var ClipProgram=function(){function ClipProgram2(aShape){this.variableNames=["A"];this.outputShape=aShape;this.userCode="\n uniform float minVal;\n uniform float maxVal;\n\n void main() {\n float value = getAAtOutCoords();\n if (isnan(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, minVal, maxVal));\n }\n "}ClipProgram2.prototype.getCustomSetupFunc=function(min2,max2){var _this=this;return function(gpgpu,webGLProgram){if(_this.minLoc==null){_this.minLoc=gpgpu.getUniformLocationNoThrow(webGLProgram,"minVal");_this.maxLoc=gpgpu.getUniformLocationNoThrow(webGLProgram,"maxVal")}gpgpu.gl.uniform1f(_this.minLoc,min2);gpgpu.gl.uniform1f(_this.maxLoc,max2)}};return ClipProgram2}();var ClipPackedProgram=function(){function ClipPackedProgram2(aShape){this.variableNames=["A"];this.packedInputs=true;this.packedOutput=true;this.outputShape=aShape;this.userCode="\n uniform float minVal;\n uniform float maxVal;\n\n void main() {\n vec4 value = getAAtOutCoords();\n\n if (any(isnan(value))) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, vec4(minVal), vec4(maxVal)));\n }\n "}ClipPackedProgram2.prototype.getCustomSetupFunc=function(min2,max2){var _this=this;return function(gpgpu,webGLProgram){if(_this.minLoc==null){_this.minLoc=gpgpu.getUniformLocationNoThrow(webGLProgram,"minVal");_this.maxLoc=gpgpu.getUniformLocationNoThrow(webGLProgram,"maxVal")}gpgpu.gl.uniform1f(_this.minLoc,min2);gpgpu.gl.uniform1f(_this.maxLoc,max2)}};return ClipPackedProgram2}();var ComplexAbsProgram=function(){function ComplexAbsProgram2(shape){this.variableNames=["real","imag"];this.outputShape=shape;this.userCode="\n void main() {\n float re = abs(getRealAtOutCoords());\n float im = abs(getImagAtOutCoords());\n float mx = max(re, im);\n\n // sadly the length function in glsl is not underflow-safe\n // (at least not on Intel GPUs). So the safe solution is\n // to ensure underflow-safety in all cases.\n setOutput(\n mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))\n );\n }\n "}return ComplexAbsProgram2}();var Conv2DDerFilterProgram=function(){function Conv2DDerFilterProgram2(convInfo){this.variableNames=["x","dy"];this.outputShape=convInfo.filterShape;var strideHeight=convInfo.strideHeight;var strideWidth=convInfo.strideWidth;var padTop=convInfo.padInfo.top;var padLeft=convInfo.padInfo.left;var isChannelsLast=convInfo.dataFormat==="channelsLast";this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int d2 = coords.w;\n\n // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int b = 0; b < "+convInfo.batchSize+"; b++) {\n for (int yR = 0; yR < "+convInfo.outHeight+"; yR++) {\n int xR = wR + yR * "+strideHeight+" - "+padTop+";\n\n if (xR < 0 || xR >= "+convInfo.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+convInfo.outWidth+"; yC++) {\n int xC = wC + yC * "+strideWidth+" - "+padLeft+";\n\n if (xC < 0 || xC >= "+convInfo.inWidth+") {\n continue;\n }\n\n if ("+isChannelsLast+") {\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n } else {\n float dyValue = getDy(b, d2, yR, yC);\n float xValue = getX(b, d1, xR, xC);\n dotProd += (xValue * dyValue);\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n "}return Conv2DDerFilterProgram2}();var Conv2DDerInputProgram=function(){function Conv2DDerInputProgram2(convInfo){this.variableNames=["dy","W"];this.outputShape=convInfo.inShape;var filterHeight=convInfo.filterHeight;var filterWidth=convInfo.filterWidth;var strideHeight=convInfo.strideHeight;var strideWidth=convInfo.strideWidth;var isChannelsLast=convInfo.dataFormat==="channelsLast";var padTop=filterHeight-1-convInfo.padInfo.top;var padLeft=filterWidth-1-convInfo.padInfo.left;var rowDim=isChannelsLast?1:2;var colDim=isChannelsLast?2:3;var channelDim=isChannelsLast?3:1;this.userCode="\n const ivec2 pads = ivec2("+padTop+", "+padLeft+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords["+channelDim+"];\n\n ivec2 dyCorner = ivec2(coords["+rowDim+"], coords["+colDim+"]) - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+filterHeight+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+strideHeight+".0;\n\n if (dyR < 0.0 || dyR >= "+convInfo.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+filterHeight+" - 1 - wR;\n\n for (int wC = 0; wC < "+filterWidth+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+strideWidth+".0;\n\n if (dyC < 0.0 || dyC >= "+convInfo.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+filterWidth+" - 1 - wC;\n\n for (int d2 = 0; d2 < "+convInfo.outChannels+"; d2++) {\n\n if ("+isChannelsLast+") {\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n } else {\n float xValue = getDy(batch, d2, idyR, idyC);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n "}return Conv2DDerInputProgram2}();var Conv3DDerFilterProgram=function(){function Conv3DDerFilterProgram2(convInfo){this.variableNames=["x","dy"];this.outputShape=convInfo.filterShape;var strideDepth=convInfo.strideDepth;var strideHeight=convInfo.strideHeight;var strideWidth=convInfo.strideWidth;var padFront=convInfo.padInfo.front;var padTop=convInfo.padInfo.top;var padLeft=convInfo.padInfo.left;this.userCode="\n void main() {\n ivec5 coords = getOutputCoords();\n int wF = coords.x;\n int wR = coords.y;\n int wC = coords.z;\n int d1 = coords.w;\n int d2 = coords.u;\n\n float dotProd = 0.0;\n\n for (int b = 0; b < "+convInfo.batchSize+"; b++) {\n for (int yF = 0; yF < "+convInfo.outDepth+"; yF++) {\n int xF = wF + yF * "+strideDepth+" - "+padFront+";\n\n if (xF < 0 || xF >= "+convInfo.inDepth+") {\n continue;\n }\n\n for (int yR = 0; yR < "+convInfo.outHeight+"; yR++) {\n int xR = wR + yR * "+strideHeight+" - "+padTop+";\n\n if (xR < 0 || xR >= "+convInfo.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+convInfo.outWidth+"; yC++) {\n int xC = wC + yC * "+strideWidth+" - "+padLeft+";\n\n if (xC < 0 || xC >= "+convInfo.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yF, yR, yC, d2);\n float xValue = getX(b, xF, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "}return Conv3DDerFilterProgram2}();var Conv3DDerInputProgram=function(){function Conv3DDerInputProgram2(convInfo){this.variableNames=["dy","W"];this.outputShape=convInfo.inShape;var filterDepth=convInfo.filterDepth;var filterHeight=convInfo.filterHeight;var filterWidth=convInfo.filterWidth;var strideDepth=convInfo.strideDepth;var strideHeight=convInfo.strideHeight;var strideWidth=convInfo.strideWidth;var padFront=filterDepth-1-convInfo.padInfo.front;var padTop=filterHeight-1-convInfo.padInfo.top;var padLeft=filterWidth-1-convInfo.padInfo.left;this.userCode="\n const ivec3 pads = ivec3("+padFront+", "+padTop+", "+padLeft+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d1 = coords.u;\n\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyFCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n float dotProd = 0.0;\n for (int wF = 0; wF < "+filterDepth+"; wF++) {\n float dyF = float(dyFCorner + wF) / "+strideDepth+".0;\n\n if (dyF < 0.0 || dyF >= "+convInfo.outDepth+".0 || fract(dyF) > 0.0) {\n continue;\n }\n int idyF = int(dyF);\n\n int wFPerm = "+filterDepth+" - 1 - wF;\n\n for (int wR = 0; wR < "+filterHeight+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+strideHeight+".0;\n\n if (dyR < 0.0 || dyR >= "+convInfo.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+filterHeight+" - 1 - wR;\n\n for (int wC = 0; wC < "+filterWidth+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+strideWidth+".0;\n\n if (dyC < 0.0 || dyC >= "+convInfo.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+filterWidth+" - 1 - wC;\n\n for (int d2 = 0; d2 < "+convInfo.outChannels+"; d2++) {\n float xValue = getDy(batch, idyF, idyR, idyC, d2);\n float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "}return Conv3DDerInputProgram2}();var DepthwiseConv2DDerFilterProgram=function(){function DepthwiseConv2DDerFilterProgram2(convInfo){this.variableNames=["x","dy"];this.outputShape=convInfo.filterShape;var strideHeight=convInfo.strideHeight;var strideWidth=convInfo.strideWidth;var padTop=convInfo.padInfo.top;var padLeft=convInfo.padInfo.left;var channelMul=convInfo.outChannels/convInfo.inChannels;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int dm = coords.w;\n int d2 = d1 * "+channelMul+" + dm;\n\n float dotProd = 0.0;\n\n // TO DO: Vec4 over the batch size\n for (int b = 0; b < "+convInfo.batchSize+"; b++) {\n for (int yR = 0; yR < "+convInfo.outHeight+"; yR++) {\n int xR = wR + yR * "+strideHeight+" - "+padTop+";\n\n if (xR < 0 || xR >= "+convInfo.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+convInfo.outWidth+"; yC++) {\n int xC = wC + yC * "+strideWidth+" - "+padLeft+";\n\n if (xC < 0 || xC >= "+convInfo.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n setOutput(dotProd);\n }\n "}return DepthwiseConv2DDerFilterProgram2}();var DepthwiseConv2DDerInputProgram=function(){function DepthwiseConv2DDerInputProgram2(convInfo){this.variableNames=["dy","W"];this.outputShape=convInfo.inShape;var filterHeight=convInfo.filterHeight;var filterWidth=convInfo.filterWidth;var strideHeight=convInfo.strideHeight;var strideWidth=convInfo.strideWidth;var padTop=filterHeight-1-convInfo.padInfo.top;var padLeft=filterWidth-1-convInfo.padInfo.left;var channelMul=convInfo.outChannels/convInfo.inChannels;this.userCode="\n const ivec2 pads = ivec2("+padTop+", "+padLeft+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n float dotProd = 0.0;\n\n for (int wR = 0; wR < "+filterHeight+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+strideHeight+".0;\n\n if (dyR < 0.0 || dyR >= "+convInfo.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+filterHeight+" - 1 - wR;\n\n for (int wC = 0; wC < "+filterWidth+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+strideWidth+".0;\n\n if (dyC < 0.0 || dyC >= "+convInfo.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+filterWidth+" - 1 - wC;\n\n // TO DO: Vec4 over the channelMul\n for (int dm = 0; dm < "+channelMul+"; dm++) {\n int d2 = d1 * "+channelMul+" + dm;\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, dm);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n "}return DepthwiseConv2DDerInputProgram2}();var Conv2DProgram=function(){function Conv2DProgram2(convInfo,addBias,activation,hasPreluActivationWeights){if(addBias===void 0){addBias=false}if(activation===void 0){activation=null}if(hasPreluActivationWeights===void 0){hasPreluActivationWeights=false}this.variableNames=["x","W"];this.outputShape=convInfo.outShape;var padTop=convInfo.padInfo.top;var padLeft=convInfo.padInfo.left;var strideHeight=convInfo.strideHeight;var strideWidth=convInfo.strideWidth;var dilationHeight=convInfo.dilationHeight;var dilationWidth=convInfo.dilationWidth;var filterHeight=convInfo.filterHeight;var filterWidth=convInfo.filterWidth;var inputDepthNearestVec4=Math.floor(convInfo.inChannels/4)*4;var inputDepthVec4Remainder=convInfo.inChannels%4;var isChannelsLast=convInfo.dataFormat==="channelsLast";var rowDim=isChannelsLast?1:2;var colDim=isChannelsLast?2:3;var channelDim=isChannelsLast?3:1;var activationSnippet="",applyActivationSnippet="";if(activation){if(hasPreluActivationWeights){activationSnippet="float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n "+activation+"\n }"}else{activationSnippet="\n float activation(float x) {\n "+activation+"\n }\n "}applyActivationSnippet="result = activation(result);"}var addBiasSnippet=addBias?"result += getBiasAtOutCoords();":"";if(addBias){this.variableNames.push("bias")}if(hasPreluActivationWeights){this.variableNames.push("preluActivationWeights")}this.userCode="\n "+activationSnippet+"\n\n const ivec2 strides = ivec2("+strideHeight+", "+strideWidth+");\n const ivec2 pads = ivec2("+padTop+", "+padLeft+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords["+channelDim+"];\n\n ivec2 xRCCorner =\n ivec2(coords["+rowDim+"], coords["+colDim+"]) * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+filterHeight+"; wR++) {\n int xR = xRCorner + wR * "+dilationHeight+";\n\n if (xR < 0 || xR >= "+convInfo.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+filterWidth+"; wC++) {\n int xC = xCCorner + wC * "+dilationWidth+";\n\n if (xC < 0 || xC >= "+convInfo.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+inputDepthNearestVec4+"; d1 += 4) {\n vec4 wValues = vec4(\n getW(wR, wC, d1, d2),\n getW(wR, wC, d1 + 1, d2),\n getW(wR, wC, d1 + 2, d2),\n getW(wR, wC, d1 + 3, d2)\n );\n\n if ("+isChannelsLast+") {\n vec4 xValues = vec4(\n getX(batch, xR, xC, d1),\n getX(batch, xR, xC, d1 + 1),\n getX(batch, xR, xC, d1 + 2),\n getX(batch, xR, xC, d1 + 3)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec4 xValues = vec4(\n getX(batch, d1, xR, xC),\n getX(batch, d1 + 1, xR, xC),\n getX(batch, d1 + 2, xR, xC),\n getX(batch, d1 + 3, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n\n if ("+(inputDepthVec4Remainder===1)+") {\n\n if ("+isChannelsLast+") {\n dotProd +=\n getX(batch, xR, xC, "+inputDepthNearestVec4+") *\n getW(wR, wC, "+inputDepthNearestVec4+", d2);\n } else {\n dotProd +=\n getX(batch, "+inputDepthNearestVec4+", xR, xC) *\n getW(wR, wC, "+inputDepthNearestVec4+", d2);\n }\n\n } else if ("+(inputDepthVec4Remainder===2)+") {\n vec2 wValues = vec2(\n getW(wR, wC, "+inputDepthNearestVec4+", d2),\n getW(wR, wC, "+inputDepthNearestVec4+" + 1, d2)\n );\n\n if ("+isChannelsLast+") {\n vec2 xValues = vec2(\n getX(batch, xR, xC, "+inputDepthNearestVec4+"),\n getX(batch, xR, xC, "+inputDepthNearestVec4+" + 1)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec2 xValues = vec2(\n getX(batch, "+inputDepthNearestVec4+", xR, xC),\n getX(batch, "+inputDepthNearestVec4+" + 1, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n } else if ("+(inputDepthVec4Remainder===3)+") {\n vec3 wValues = vec3(\n getW(wR, wC, "+inputDepthNearestVec4+", d2),\n getW(wR, wC, "+inputDepthNearestVec4+" + 1, d2),\n getW(wR, wC, "+inputDepthNearestVec4+" + 2, d2)\n );\n\n if ("+isChannelsLast+") {\n vec3 xValues = vec3(\n getX(batch, xR, xC, "+inputDepthNearestVec4+"),\n getX(batch, xR, xC, "+inputDepthNearestVec4+" + 1),\n getX(batch, xR, xC, "+inputDepthNearestVec4+" + 2)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec3 xValues = vec3(\n getX(batch, "+inputDepthNearestVec4+", xR, xC),\n getX(batch, "+inputDepthNearestVec4+" + 1, xR, xC),\n getX(batch, "+inputDepthNearestVec4+" + 2, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n }\n }\n }\n\n float result = dotProd;\n "+addBiasSnippet+"\n "+applyActivationSnippet+"\n setOutput(result);\n }\n "}return Conv2DProgram2}();var Conv3DProgram=function(){function Conv3DProgram2(convInfo){this.variableNames=["x","W"];this.outputShape=convInfo.outShape;var padFront=convInfo.padInfo.front;var padTop=convInfo.padInfo.top;var padLeft=convInfo.padInfo.left;var strideDepth=convInfo.strideDepth;var strideHeight=convInfo.strideHeight;var strideWidth=convInfo.strideWidth;var dilationDepth=convInfo.dilationDepth;var dilationHeight=convInfo.dilationHeight;var dilationWidth=convInfo.dilationWidth;var filterDepth=convInfo.filterDepth;var filterHeight=convInfo.filterHeight;var filterWidth=convInfo.filterWidth;var inputDepthNearestVec4=Math.floor(convInfo.inChannels/4)*4;var inputDepthVec4Remainder=convInfo.inChannels%4;this.userCode="\n const ivec3 strides = ivec3("+strideDepth+", "+strideHeight+", "+strideWidth+");\n const ivec3 pads = ivec3("+padFront+", "+padTop+", "+padLeft+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d2 = coords.u;\n\n ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xFCorner = xFRCCorner.x;\n int xRCorner = xFRCCorner.y;\n int xCCorner = xFRCCorner.z;\n\n // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get\n // y(yF, yR, yC, d2). ? = to be determined. : = across all\n // values in that axis.\n float dotProd = 0.0;\n for (int wF = 0; wF < "+filterDepth+"; wF++) {\n int xF = xFCorner + wF * "+dilationDepth+";\n\n if (xF < 0 || xF >= "+convInfo.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+filterHeight+"; wR++) {\n int xR = xRCorner + wR * "+dilationHeight+";\n\n if (xR < 0 || xR >= "+convInfo.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+filterWidth+"; wC++) {\n int xC = xCCorner + wC * "+dilationWidth+";\n\n if (xC < 0 || xC >= "+convInfo.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+inputDepthNearestVec4+"; d1 += 4) {\n vec4 xValues = vec4(\n getX(batch, xF, xR, xC, d1),\n getX(batch, xF, xR, xC, d1 + 1),\n getX(batch, xF, xR, xC, d1 + 2),\n getX(batch, xF, xR, xC, d1 + 3)\n );\n vec4 wValues = vec4(\n getW(wF, wR, wC, d1, d2),\n getW(wF, wR, wC, d1 + 1, d2),\n getW(wF, wR, wC, d1 + 2, d2),\n getW(wF, wR, wC, d1 + 3, d2)\n );\n\n dotProd += dot(xValues, wValues);\n }\n\n if ("+(inputDepthVec4Remainder===1)+") {\n dotProd +=\n getX(batch, xF, xR, xC, "+inputDepthNearestVec4+") *\n getW(wF, wR, wC, "+inputDepthNearestVec4+", d2);\n } else if ("+(inputDepthVec4Remainder===2)+") {\n vec2 xValues = vec2(\n getX(batch, xF, xR, xC, "+inputDepthNearestVec4+"),\n getX(batch, xF, xR, xC, "+inputDepthNearestVec4+" + 1)\n );\n vec2 wValues = vec2(\n getW(wF, wR, wC, "+inputDepthNearestVec4+", d2),\n getW(wF, wR, wC, "+inputDepthNearestVec4+" + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if ("+(inputDepthVec4Remainder===3)+") {\n vec3 xValues = vec3(\n getX(batch, xF, xR, xC, "+inputDepthNearestVec4+"),\n getX(batch, xF, xR, xC, "+inputDepthNearestVec4+" + 1),\n getX(batch, xF, xR, xC, "+inputDepthNearestVec4+" + 2)\n );\n vec3 wValues = vec3(\n getW(wF, wR, wC, "+inputDepthNearestVec4+", d2),\n getW(wF, wR, wC, "+inputDepthNearestVec4+" + 1, d2),\n getW(wF, wR, wC, "+inputDepthNearestVec4+" + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "}return Conv3DProgram2}();var DepthwiseConv2DProgram=function(){function DepthwiseConv2DProgram2(convInfo,addBias,activation,hasPreluActivation){if(addBias===void 0){addBias=false}if(activation===void 0){activation=null}if(hasPreluActivation===void 0){hasPreluActivation=false}this.variableNames=["x","W"];this.outputShape=convInfo.outShape;var xNumRows=convInfo.inHeight;var xNumCols=convInfo.inWidth;var padTop=convInfo.padInfo.top;var padLeft=convInfo.padInfo.left;var strideHeight=convInfo.strideHeight;var strideWidth=convInfo.strideWidth;var dilationHeight=convInfo.dilationHeight;var dilationWidth=convInfo.dilationWidth;var filterHeight=convInfo.filterHeight;var filterWidth=convInfo.filterWidth;var channelMul=convInfo.outChannels/convInfo.inChannels;var activationSnippet="",applyActivationSnippet="";if(activation){if(hasPreluActivation){activationSnippet="float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n "+activation+"\n }"}else{activationSnippet="\n float activation(float x) {\n "+activation+"\n }\n "}applyActivationSnippet="result = activation(result);"}var addBiasSnippet=addBias?"result += getBiasAtOutCoords();":"";if(addBias){this.variableNames.push("bias")}if(hasPreluActivation){this.variableNames.push("preluActivationWeights")}this.userCode="\n "+activationSnippet+"\n\n const ivec2 strides = ivec2("+strideHeight+", "+strideWidth+");\n const ivec2 pads = ivec2("+padTop+", "+padLeft+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2 / "+channelMul+";\n int q = d2 - d1 * "+channelMul+";\n\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.\n for (int wR = 0; wR < "+filterHeight+"; wR++) {\n int xR = xRCorner + wR * "+dilationHeight+";\n\n if (xR < 0 || xR >= "+xNumRows+") {\n continue;\n }\n\n for (int wC = 0; wC < "+filterWidth+"; wC++) {\n int xC = xCCorner + wC * "+dilationWidth+";\n\n if (xC < 0 || xC >= "+xNumCols+") {\n continue;\n }\n\n float xVal = getX(batch, xR, xC, d1);\n float wVal = getW(wR, wC, d1, q);\n dotProd += xVal * wVal;\n }\n }\n\n float result = dotProd;\n "+addBiasSnippet+"\n "+applyActivationSnippet+"\n setOutput(result);\n }\n "}return DepthwiseConv2DProgram2}();var DepthwiseConvPacked2DProgram=function(){function DepthwiseConvPacked2DProgram2(convInfo,addBias,activation,hasPreluActivation){if(addBias===void 0){addBias=false}if(activation===void 0){activation=null}if(hasPreluActivation===void 0){hasPreluActivation=false}this.variableNames=["x","W"];this.packedInputs=true;this.packedOutput=true;this.outputShape=convInfo.outShape;var xNumRows=convInfo.inHeight;var xNumCols=convInfo.inWidth;var padTop=convInfo.padInfo.top;var padLeft=convInfo.padInfo.left;var strideHeight=convInfo.strideHeight;var strideWidth=convInfo.strideWidth;var dilationHeight=convInfo.dilationHeight;var dilationWidth=convInfo.dilationWidth;var filterHeight=convInfo.filterHeight;var filterWidth=convInfo.filterWidth;var texelsAcross=filterWidth;var mainLoop="int xR; int xC; int xCOffset;";for(var r=0;r= 0 && xR < "+xNumRows+" && xCOffset >= 0 && xCOffset < "+xNumCols+") {\n xTexelR"+r+"C"+c+" = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if(xCOffset + 1 >= "+xNumCols+") {\n xTexelR"+r+"C"+c+".zw = vec2(0.);\n }\n } else {\n xTexelR"+r+"C"+c+" = vec4(0.);\n }\n\n xCOffset = xC + 1 - 2;\n if(xR >= 0 && xR < "+xNumRows+" && xCOffset >= 0 && xCOffset < "+xNumCols+") {\n vec4 previous = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if(xCOffset + 1 >= "+xNumCols+") {\n previous.zw = vec2(0.);\n }\n\n xR"+r+"C"+c+" = vec4(previous.zw, xTexelR"+r+"C"+c+".xy);\n } else {\n xR"+r+"C"+c+" = vec4(0, 0, xTexelR"+r+"C"+c+".xy);\n }\n "}else{mainLoop+="\n if(xR >= 0 && xR < "+xNumRows+" && xC >= 0 && xC < "+xNumCols+") {\n xTexelR"+r+"C"+c+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+r+"C"+c+" = vec4(0.);\n }\n\n xR"+r+"C"+c+" = xTexelR"+r+"C"+c+";\n "}if(c+1= 0 && xR < "+xNumRows+" &&\n xCOffset >= 0 && xCOffset < "+xNumCols+") {\n xTexelR"+r+"C"+(c+2)+" = getX(batch, xR, xCOffset, d1);\n }\n ";if(dilationWidth>1){mainLoop+="\n xCOffset -= 2;\n if(xR >= 0 && xR < "+xNumRows+" &&\n xCOffset >= 0 && xCOffset < "+xNumCols+") {\n xTexelR"+r+"C"+c+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+r+"C"+c+" = vec4(0.);\n }\n "}mainLoop+="\n xR"+r+"C"+(c+1)+" = vec4(\n xTexelR"+r+"C"+c+".zw, xTexelR"+r+"C"+(c+2)+".xy);\n "}else{mainLoop+="\n xCOffset = xC + "+nextTexelOffset+";\n\n if(xR >= 0 && xR < "+xNumRows+" &&\n xCOffset >= 0 && xCOffset < "+xNumCols+") {\n xTexelR"+r+"C"+(c+2)+" = getX(batch, xR, xCOffset, d1);\n }\n\n xR"+r+"C"+(c+1)+" = xTexelR"+r+"C"+(c+2)+";\n "}}}}else{if(c= 0 && xR < "+xNumRows+") {\n ";if(padLeft%2===1){mainLoop+="\n xCOffset = xC + 1 - "+strideWidth+";\n if(xCOffset >= 0 && xCOffset < "+xNumCols+") {\n xTexelR"+r+"C"+c+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+r+"C"+c+" = vec4(0.);\n }\n\n if(xC + 1 >= 0 && xC + 1 < "+xNumCols+") {\n xTexelR"+r+"C"+(c+2)+" = getX(batch, xR, xC + 1, d1);\n } else {\n xTexelR"+r+"C"+(c+2)+" = vec4(0.);\n }\n\n xR"+r+"C"+c+" = vec4(\n xTexelR"+r+"C"+c+".zw, xTexelR"+r+"C"+(c+2)+".zw);\n ";if(c+1= 0 && xCOffset < "+xNumCols+") {\n final = getX(batch, xR, xCOffset, d1);\n }\n xR"+r+"C"+(c+1)+" = vec4(xTexelR"+r+"C"+(c+2)+".xy, final.xy);\n "}}else{mainLoop+="\n if(xC >= 0 && xC < "+xNumCols+") {\n xTexelR"+r+"C"+c+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+r+"C"+c+" = vec4(0.);\n }\n\n xCOffset = xC + "+strideWidth+";\n if(xCOffset >= 0 && xCOffset < "+xNumCols+") {\n xTexelR"+r+"C"+(c+2)+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+r+"C"+(c+2)+" = vec4(0.);\n }\n\n xR"+r+"C"+c+" = vec4(\n xTexelR"+r+"C"+c+".xy, xTexelR"+r+"C"+(c+2)+".xy);\n ";if(c+11?[""+(imageHeight-1)/(cropHeight-1),"(y2-y1) * height_ratio","y1*"+inputHeightFloat+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+inputHeightFloat],heightRatio=_b[0],heightScale=_b[1],inY=_b[2];var _c=cropWidth>1?[""+(imageWidth-1)/(cropWidth-1),"(x2-x1) * width_ratio","x1*"+inputWidthFloat+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+inputWidthFloat],widthRatio=_c[0],widthScale=_c[1],inX=_c[2];this.userCode="\n const float height_ratio = float("+heightRatio+");\n const float width_ratio = float("+widthRatio+");\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int y = coords[1];\n int x = coords[2];\n int d = coords[3];\n\n // get box vals\n float y1 = getBoxes(b,0);\n float x1 = getBoxes(b,1);\n float y2 = getBoxes(b,2);\n float x2 = getBoxes(b,3);\n\n // get image in batch index\n int bInd = round(getBoxInd(b));\n if(bInd < 0 || bInd >= "+batch+") {\n return;\n }\n\n float height_scale = "+heightScale+";\n float width_scale = "+widthScale+";\n\n float in_y = "+inY+";\n if( in_y < 0.0 || in_y > "+inputHeightFloat+" ) {\n setOutput(float("+extrapolationValue+"));\n return;\n }\n float in_x = "+inX+";\n if( in_x < 0.0 || in_x > "+inputWidthFloat+" ) {\n setOutput(float("+extrapolationValue+"));\n return;\n }\n\n vec2 sourceFracIndexCR = vec2(in_x,in_y);\n if("+methodId+" == 1) {\n // Compute the four integer indices.\n ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);\n ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));\n\n float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);\n float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);\n float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);\n float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);\n\n vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);\n\n float top = topLeft + (topRight - topLeft) * fracCR.x;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;\n float newValue = top + (bottom - top) * fracCR.y;\n setOutput(newValue);\n } else {\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestCR = ivec2(floor(\n sourceFracIndexCR + vec2(0.5,0.5)));\n float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);\n setOutput(newValue);\n }\n }\n "}return CropAndResizeProgram2}();var CumSumProgram=function(){function CumSumProgram2(shape,exclusive,reverse2){this.variableNames=["x"];this.outputShape=shape;var rank=shape.length;var val=exclusive?"0.0":"getX("+getCoords(rank,"coords")+")";var length=shape[shape.length-1];var condition="";var idxString="";if(exclusive){condition=reverse2?"end != "+(length-1):"end != 0";idxString=reverse2?"end + 1":"end - 1"}else{condition=reverse2?"end + pow2 < "+length:"end >= pow2";idxString=reverse2?"end + pow2":"end - pow2"}this.userCode="\n uniform float index;\n void main() {\n "+getCoordsDataType(rank)+" coords = getOutputCoords();\n int end = "+getFinalCoord(rank,"coords")+";\n float val = "+val+";\n int pow2 = int(pow(2.0, index));\n if ("+condition+") {\n int idx = "+idxString+";\n "+getFinalCoord(rank,"coords")+" = idx;\n val += getX("+getCoords(rank,"coords")+");\n }\n setOutput(val);\n }\n "}CumSumProgram2.prototype.getCustomSetupFunc=function(index){var _this=this;return function(gpgpu,webGLProgram){if(_this.index==null){_this.index=gpgpu.getUniformLocation(webGLProgram,"index")}gpgpu.gl.uniform1f(_this.index,index)}};return CumSumProgram2}();function getCoords(rank,name){if(rank===1){return""+name}else if(rank===2){return name+".x, "+name+".y"}else if(rank===3){return name+".x, "+name+".y, "+name+".z"}else if(rank===4){return name+".x, "+name+".y, "+name+".z, "+name+".w"}else{throw Error("Cumulative sum for rank "+rank+" is not yet supported")}}function getFinalCoord(rank,name){if(rank===1){return""+name}else if(rank===2){return name+".y"}else if(rank===3){return name+".z"}else if(rank===4){return name+".w"}else{throw Error("Cumulative sum for rank "+rank+" is not yet supported")}}var DecodeMatrixProgram=function(){function DecodeMatrixProgram2(outputShape){this.variableNames=["A"];this.packedInputs=false;this.packedOutput=true;this.outPackingScheme=PackingScheme.DENSE;var texShape=getDenseTexShape(outputShape);var glsl=getGlslDifferences();this.outputShape=outputShape;this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+getLogicalCoordinatesFromFlatIndex(["r","c","d"],outputShape)+"\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+texShape[0]+", "+texShape[1]+"));\n int index = 4 * (resTexRC.x * "+texShape[1]+" + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getA(rc.x, rc.y, rc.z);\n }\n\n "+glsl.output+" = result;\n }\n "}return DecodeMatrixProgram2}();var DecodeMatrixPackedProgram=function(){function DecodeMatrixPackedProgram2(outputShape){this.variableNames=["A"];this.packedInputs=true;this.packedOutput=true;this.outPackingScheme=PackingScheme.DENSE;var texShape=getDenseTexShape(outputShape);var glsl=getGlslDifferences();this.outputShape=outputShape;this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+getLogicalCoordinatesFromFlatIndex(["r","c","d"],outputShape)+"\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+texShape[0]+", "+texShape[1]+"));\n int index = 4 * (resTexRC.x * "+texShape[1]+" + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));\n }\n\n "+glsl.output+" = result;\n }\n "}return DecodeMatrixPackedProgram2}();var DepthToSpaceProgram=function(){function DepthToSpaceProgram2(outputShape,blockSize,dataFormat){this.variableNames=["x"];this.outputShape=[];this.outputShape=outputShape;this.blockSize=blockSize;this.dataFormat=dataFormat;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int h = "+this.getHeightCoordString()+";\n int w = "+this.getWidthCoordString()+";\n int d = "+this.getDepthCoordString()+";\n\n int in_h = h / "+blockSize+";\n int offset_h = imod(h, "+blockSize+");\n int in_w = w / "+blockSize+";\n int offset_w = imod(w, "+blockSize+");\n int offset_d = (offset_h * "+blockSize+" + offset_w) *\n "+this.getOutputDepthSize()+";\n int in_d = d + offset_d;\n\n float result = "+this.getInputSamplingString()+";\n setOutput(result);\n }\n "}DepthToSpaceProgram2.prototype.getHeightCoordString=function(){if(this.dataFormat==="NHWC"){return"coords[1]"}else{return"coords[2]"}};DepthToSpaceProgram2.prototype.getWidthCoordString=function(){if(this.dataFormat==="NHWC"){return"coords[2]"}else{return"coords[3]"}};DepthToSpaceProgram2.prototype.getDepthCoordString=function(){if(this.dataFormat==="NHWC"){return"coords[3]"}else{return"coords[1]"}};DepthToSpaceProgram2.prototype.getOutputDepthSize=function(){if(this.dataFormat==="NHWC"){return this.outputShape[3]}else{return this.outputShape[1]}};DepthToSpaceProgram2.prototype.getInputSamplingString=function(){if(this.dataFormat==="NHWC"){return"getX(b, in_h, in_w, in_d)"}else{return"getX(b, in_d, in_h, in_w)"}};return DepthToSpaceProgram2}();var DiagProgram=function(){function DiagProgram2(size){this.variableNames=["X"];this.outputShape=[size,size];this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;\n setOutput(val);\n }\n "}return DiagProgram2}();var EncodeFloatProgram=function(){function EncodeFloatProgram2(outputShape){this.variableNames=["A"];this.outTexUsage=TextureUsage.DOWNLOAD;var glsl=getGlslDifferences();this.outputShape=outputShape;this.userCode="\n "+ENCODE_FLOAT_SNIPPET+"\n\n void main() {\n float x = getAAtOutCoords();\n "+glsl.output+" = encode_float(x);\n }\n "}return EncodeFloatProgram2}();var EncodeFloatPackedProgram=function(){function EncodeFloatPackedProgram2(outputShape){this.variableNames=["A"];this.packedInputs=true;this.packedOutput=false;this.outTexUsage=TextureUsage.DOWNLOAD;var glsl=getGlslDifferences();this.outputShape=outputShape;this.userCode="\n "+ENCODE_FLOAT_SNIPPET+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));\n "+glsl.output+" = encode_float(x);\n }\n "}return EncodeFloatPackedProgram2}();var EncodeMatrixProgram=function(){function EncodeMatrixProgram2(outputShape,texShape,inputIsUnsignedByte){if(inputIsUnsignedByte===void 0){inputIsUnsignedByte=false}this.variableNames=["A"];var glsl=getGlslDifferences();var height=texShape[0],width=texShape[1];this.outputShape=outputShape;var output="result";if(inputIsUnsignedByte){output="floor(result * 255. + 0.5)"}this.userCode="\n "+getFlatIndexFrom3D(outputShape)+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n int flatIndex = getFlatIndex(coords);\n int offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n\n int r = flatIndex / "+width+";\n int c = imod(flatIndex, "+width+");\n vec2 uv = (vec2(c, r) + halfCR) / vec2("+width+".0, "+height+".0);\n vec4 values = "+glsl.texture2D+"(A, uv);\n\n float result;\n\n if(offset == 0) {\n result = values[0];\n } else if(offset == 1) {\n result = values[1];\n } else if(offset == 2) {\n result = values[2];\n } else {\n result = values[3];\n }\n\n "+glsl.output+" = vec4("+output+", 0., 0., 0.);\n }\n "}return EncodeMatrixProgram2}();var EncodeMatrixPackedProgram=function(){function EncodeMatrixPackedProgram2(outputShape,texShape,inputIsUnsignedByte){if(inputIsUnsignedByte===void 0){inputIsUnsignedByte=false}this.variableNames=["A"];this.packedInputs=false;this.packedOutput=true;var glsl=getGlslDifferences();var height=texShape[0],width=texShape[1];this.outputShape=outputShape;var mainLoop="";var output="result";if(inputIsUnsignedByte){output="floor(result * 255. + 0.5)"}for(var row=0;row<=1;row++){for(var col=0;col<=1;col++){var channel=row*2+col;mainLoop+="\n localCoords = coords;\n if(localCoords[2] + "+col+" < "+outputShape[2]+") {\n localCoords[2] += "+col+";\n if(localCoords[1] + "+row+" < "+outputShape[1]+") {\n localCoords[1] += "+row+";\n\n flatIndex = getFlatIndex(localCoords);\n offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n\n r = flatIndex / "+width+";\n c = imod(flatIndex, "+width+");\n uv = (vec2(c, r) + halfCR) / vec2("+width+".0, "+height+".0);\n values = "+glsl.texture2D+"(A, uv);\n\n if(offset == 0) {\n result["+channel+"] = values[0];\n } else if(offset == 1) {\n result["+channel+"] = values[1];\n } else if(offset == 2) {\n result["+channel+"] = values[2];\n } else {\n result["+channel+"] = values[3];\n }\n }\n }\n "}}this.userCode="\n "+getFlatIndexFrom3D(outputShape)+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n vec4 result = vec4(0.);\n int flatIndex, r, c, offset;\n ivec3 localCoords;\n vec2 uv;\n vec4 values;\n\n "+mainLoop+"\n\n "+glsl.output+" = "+output+";\n }\n "}return EncodeMatrixPackedProgram2}();var FillProgram=function(){function FillProgram2(shape,value){this.outputShape=[];this.variableNames=["x"];this.outputShape=shape;this.userCode="\n uniform float value;\n void main() {\n // Input can be obtained from uniform value.\n setOutput(value);\n }\n "}FillProgram2.prototype.getCustomSetupFunc=function(value){var _this=this;return function(gpgpu,webGLProgram){if(_this.valueLoc==null){_this.valueLoc=gpgpu.getUniformLocationNoThrow(webGLProgram,"value")}gpgpu.gl.uniform1f(_this.valueLoc,value)}};return FillProgram2}();var GatherProgram=function(){function GatherProgram2(aShape,indicesLength,axis){this.variableNames=["A","indices"];var outputShape=aShape.slice();outputShape[axis]=indicesLength;this.outputShape=outputShape;this.rank=outputShape.length;var dtype=getCoordsDataType(this.rank);var sourceCoords=getSourceCoords$1(aShape,axis);this.userCode="\n void main() {\n "+dtype+" resRC = getOutputCoords();\n setOutput(getA("+sourceCoords+"));\n }\n "}return GatherProgram2}();function getSourceCoords$1(aShape,axis){var rank=aShape.length;if(rank>4){throw Error("Gather for rank "+rank+" is not yet supported")}if(rank===1){return"int(getIndices(resRC))"}var currentCoords=["resRC.x","resRC.y","resRC.z","resRC.w"];var sourceCoords=[];for(var i=0;i1?"strides[j]":"strides";this.userCode="\n "+stridesType+" strides = "+stridesType+"("+this.strides+");\n void main() {\n "+dtype+" coords = getOutputCoords();\n int flattenIndex = 0;\n for (int j = 0; j < "+this.sliceDim+"; j++) {\n int index = round(getIndices(coords[0], j));\n flattenIndex += index * "+strideString+";\n }\n setOutput(getX(flattenIndex, coords[1]));\n }\n "}return GatherNDProgram2}();function createVertexShader$1(gl){var glsl=getGlslDifferences();var vertexShaderSource=glsl.version+"\n precision highp float;\n "+glsl.attribute+" vec3 clipSpacePos;\n "+glsl.attribute+" vec2 uv;\n "+glsl.varyingVs+" vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }";return createVertexShader(gl,vertexShaderSource)}function createVertexBuffer(gl){var vertexArray=new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]);return createStaticVertexBuffer(gl,vertexArray)}function createIndexBuffer(gl){var triangleVertexIndices=new Uint16Array([0,1,2,2,1,3]);return createStaticIndexBuffer(gl,triangleVertexIndices)}function createAndConfigureTexture(gl,width,height,internalFormat,textureFormat,textureType){validateTextureSize(width,height);var texture=createTexture(gl);var tex2d=gl.TEXTURE_2D;callAndCheck(gl,function(){return gl.bindTexture(tex2d,texture)});callAndCheck(gl,function(){return gl.texParameteri(tex2d,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE)});callAndCheck(gl,function(){return gl.texParameteri(tex2d,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE)});callAndCheck(gl,function(){return gl.texParameteri(tex2d,gl.TEXTURE_MIN_FILTER,gl.NEAREST)});callAndCheck(gl,function(){return gl.texParameteri(tex2d,gl.TEXTURE_MAG_FILTER,gl.NEAREST)});callAndCheck(gl,function(){return gl.texImage2D(tex2d,0,internalFormat,width,height,0,textureFormat,textureType,null)});callAndCheck(gl,function(){return gl.bindTexture(gl.TEXTURE_2D,null)});return texture}function getInternalFormatForFloat32MatrixTexture(textureConfig){return textureConfig.internalFormatFloat}function createFloat32MatrixTexture(gl,rows,columns,textureConfig){var _a=getUnpackedMatrixTextureShapeWidthHeight(rows,columns),width=_a[0],height=_a[1];return createAndConfigureTexture(gl,width,height,getInternalFormatForFloat32MatrixTexture(textureConfig),textureConfig.textureFormatFloat,gl.FLOAT)}function getInternalFormatForFloat16MatrixTexture(textureConfig){return textureConfig.internalFormatHalfFloat}function createFloat16MatrixTexture(gl,rows,columns,textureConfig){var _a=getUnpackedMatrixTextureShapeWidthHeight(rows,columns),width=_a[0],height=_a[1];return createAndConfigureTexture(gl,width,height,getInternalFormatForFloat16MatrixTexture(textureConfig),textureConfig.textureFormatFloat,textureConfig.textureTypeHalfFloat)}function getInternalFormatForUnsignedBytesMatrixTexture(textureConfig){return textureConfig.downloadTextureFormat}function createUnsignedBytesMatrixTexture(gl,rows,columns,textureConfig){var _a=getUnpackedMatrixTextureShapeWidthHeight(rows,columns),width=_a[0],height=_a[1];return createAndConfigureTexture(gl,width,height,getInternalFormatForUnsignedBytesMatrixTexture(textureConfig),gl.RGBA,gl.UNSIGNED_BYTE)}function getInternalFormatForPackedMatrixTexture(textureConfig){return textureConfig.internalFormatPackedFloat}function createPackedMatrixTexture(gl,rows,columns,textureConfig){var _a=getPackedMatrixTextureShapeWidthHeight(rows,columns),width=_a[0],height=_a[1];return createAndConfigureTexture(gl,width,height,getInternalFormatForPackedMatrixTexture(textureConfig),gl.RGBA,gl.FLOAT)}function getInternalFormatForFloat16PackedMatrixTexture(textureConfig){return textureConfig.internalFormatPackedHalfFloat}function createFloat16PackedMatrixTexture(gl,rows,columns,textureConfig){var _a=getPackedMatrixTextureShapeWidthHeight(rows,columns),width=_a[0],height=_a[1];return createAndConfigureTexture(gl,width,height,getInternalFormatForFloat16PackedMatrixTexture(textureConfig),gl.RGBA,textureConfig.textureTypeHalfFloat)}function bindVertexProgramAttributeStreams(gl,program,vertexBuffer){var posOffset=0;var uvOffset=3*4;var stride=3*4+2*4;callAndCheck(gl,function(){return gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer)});var success=bindVertexBufferToProgramAttribute(gl,program,"clipSpacePos",vertexBuffer,3,stride,posOffset);return success&&bindVertexBufferToProgramAttribute(gl,program,"uv",vertexBuffer,2,stride,uvOffset)}function uploadDenseMatrixToTexture(gl,texture,width,height,data2,textureConfig){callAndCheck(gl,function(){return gl.bindTexture(gl.TEXTURE_2D,texture)});var dataForUpload,texelDataType,internalFormat;if(data2 instanceof Uint8Array){dataForUpload=new Uint8Array(width*height*4);texelDataType=gl.UNSIGNED_BYTE;internalFormat=gl.RGBA}else{dataForUpload=new Float32Array(width*height*4);texelDataType=gl.FLOAT;internalFormat=textureConfig.internalFormatPackedFloat}dataForUpload.set(data2);callAndCheck(gl,function(){return gl.texImage2D(gl.TEXTURE_2D,0,internalFormat,width,height,0,gl.RGBA,texelDataType,dataForUpload)});callAndCheck(gl,function(){return gl.bindTexture(gl.TEXTURE_2D,null)})}function uploadPixelDataToTexture(gl,texture,pixels){callAndCheck(gl,function(){return gl.bindTexture(gl.TEXTURE_2D,texture)});if(pixels.data instanceof Uint8Array){callAndCheck(gl,function(){return gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,pixels.width,pixels.height,0,gl.RGBA,gl.UNSIGNED_BYTE,pixels.data)})}else{callAndCheck(gl,function(){return gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,gl.RGBA,gl.UNSIGNED_BYTE,pixels)})}callAndCheck(gl,function(){return gl.bindTexture(gl.TEXTURE_2D,null)})}function createBufferFromOutputTexture(gl2,rows,columns,textureConfig){var buffer2=gl2.createBuffer();callAndCheck(gl2,function(){return gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER,buffer2)});var bytesPerFloat=4;var valuesPerTexel=4;var bufferSizeBytes=bytesPerFloat*valuesPerTexel*rows*columns;callAndCheck(gl2,function(){return gl2.bufferData(gl2.PIXEL_PACK_BUFFER,bufferSizeBytes,gl2.STREAM_READ)});callAndCheck(gl2,function(){return gl2.readPixels(0,0,columns,rows,gl2.RGBA,gl2.FLOAT,0)});callAndCheck(gl2,function(){return gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER,null)});return buffer2}function downloadFloat32MatrixFromBuffer(gl,buffer2,size){var gl2=gl;var downloadTarget=new Float32Array(size);gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER,buffer2);gl2.getBufferSubData(gl2.PIXEL_PACK_BUFFER,0,downloadTarget);gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER,null);return downloadTarget}function downloadByteEncodedFloatMatrixFromOutputTexture(gl,rows,columns,textureConfig){var _a=getUnpackedMatrixTextureShapeWidthHeight(rows,columns),w=_a[0],h=_a[1];var numChannels=4;var downloadTarget=new Uint8Array(getUnpackedArraySizeFromMatrixSize(rows*columns,numChannels));callAndCheck(gl,function(){return gl.readPixels(0,0,w,h,textureConfig.downloadTextureFormat,gl.UNSIGNED_BYTE,downloadTarget)});return new Float32Array(downloadTarget.buffer)}function downloadPackedMatrixFromBuffer(gl,buffer2,batch,rows,cols,physicalRows,physicalCols,textureConfig){var gl2=gl;var downloadTarget=new Float32Array(getPackedRGBAArraySizeFromMatrixShape(physicalRows,physicalCols));gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER,buffer2);gl2.getBufferSubData(gl2.PIXEL_PACK_BUFFER,0,downloadTarget);gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER,null);return downloadTarget}function downloadMatrixFromPackedOutputTexture(gl,physicalRows,physicalCols){var packedRGBA=new Float32Array(physicalRows*physicalCols*4);callAndCheck(gl,function(){return gl.readPixels(0,0,physicalCols,physicalRows,gl.RGBA,gl.FLOAT,packedRGBA)});return packedRGBA}var gpgpu_util={__proto__:null,createVertexShader:createVertexShader$1,createVertexBuffer,createIndexBuffer,getInternalFormatForFloat32MatrixTexture,createFloat32MatrixTexture,getInternalFormatForFloat16MatrixTexture,createFloat16MatrixTexture,getInternalFormatForUnsignedBytesMatrixTexture,createUnsignedBytesMatrixTexture,getInternalFormatForPackedMatrixTexture,createPackedMatrixTexture,getInternalFormatForFloat16PackedMatrixTexture,createFloat16PackedMatrixTexture,bindVertexProgramAttributeStreams,uploadDenseMatrixToTexture,uploadPixelDataToTexture,createBufferFromOutputTexture,downloadFloat32MatrixFromBuffer,downloadByteEncodedFloatMatrixFromOutputTexture,downloadPackedMatrixFromBuffer,downloadMatrixFromPackedOutputTexture};var GPGPUContext=function(){function GPGPUContext2(gl){this.outputTexture=null;this.program=null;this.disposed=false;this.vertexAttrsAreBound=false;this.itemsToPoll=[];var glVersion=tf4.env().getNumber("WEBGL_VERSION");if(gl!=null){this.gl=gl;setWebGLContext(glVersion,gl)}else{this.gl=getWebGLContext(glVersion)}var COLOR_BUFFER_FLOAT="WEBGL_color_buffer_float";var COLOR_BUFFER_HALF_FLOAT="EXT_color_buffer_half_float";if(tf4.env().getNumber("WEBGL_VERSION")===1){var TEXTURE_FLOAT="OES_texture_float";var TEXTURE_HALF_FLOAT="OES_texture_half_float";this.textureFloatExtension=getExtensionOrThrow(this.gl,TEXTURE_FLOAT);if(hasExtension(this.gl,TEXTURE_HALF_FLOAT)){this.textureHalfFloatExtension=getExtensionOrThrow(this.gl,TEXTURE_HALF_FLOAT)}else if(tf4.env().get("WEBGL_FORCE_F16_TEXTURES")){throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}this.colorBufferFloatExtension=this.gl.getExtension(COLOR_BUFFER_FLOAT);if(hasExtension(this.gl,COLOR_BUFFER_HALF_FLOAT)){this.colorBufferHalfFloatExtension=getExtensionOrThrow(this.gl,COLOR_BUFFER_HALF_FLOAT)}else if(tf4.env().get("WEBGL_FORCE_F16_TEXTURES")){throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}}else{COLOR_BUFFER_FLOAT="EXT_color_buffer_float";if(hasExtension(this.gl,COLOR_BUFFER_FLOAT)){this.colorBufferFloatExtension=this.gl.getExtension(COLOR_BUFFER_FLOAT)}else if(hasExtension(this.gl,COLOR_BUFFER_HALF_FLOAT)){this.colorBufferHalfFloatExtension=this.gl.getExtension(COLOR_BUFFER_HALF_FLOAT)}else{throw new Error("GL context does not support color renderable floats")}}this.vertexBuffer=createVertexBuffer(this.gl);this.indexBuffer=createIndexBuffer(this.gl);this.framebuffer=createFramebuffer(this.gl);this.textureConfig=getTextureConfig(this.gl,this.textureHalfFloatExtension)}Object.defineProperty(GPGPUContext2.prototype,"debug",{get:function(){return tf4.env().getBool("DEBUG")},enumerable:true,configurable:true});GPGPUContext2.prototype.dispose=function(){var _this=this;if(this.disposed){return}if(this.program!=null){console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing.")}if(this.outputTexture!=null){console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.")}var gl=this.gl;callAndCheck(gl,function(){return gl.finish()});callAndCheck(gl,function(){return gl.bindFramebuffer(gl.FRAMEBUFFER,null)});callAndCheck(gl,function(){return gl.deleteFramebuffer(_this.framebuffer)});callAndCheck(gl,function(){return gl.bindBuffer(gl.ARRAY_BUFFER,null)});callAndCheck(gl,function(){return gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,null)});callAndCheck(gl,function(){return gl.deleteBuffer(_this.indexBuffer)});this.disposed=true};GPGPUContext2.prototype.createFloat32MatrixTexture=function(rows,columns){this.throwIfDisposed();return createFloat32MatrixTexture(this.gl,rows,columns,this.textureConfig)};GPGPUContext2.prototype.createFloat16MatrixTexture=function(rows,columns){this.throwIfDisposed();return createFloat16MatrixTexture(this.gl,rows,columns,this.textureConfig)};GPGPUContext2.prototype.createUnsignedBytesMatrixTexture=function(rows,columns){this.throwIfDisposed();return createUnsignedBytesMatrixTexture(this.gl,rows,columns,this.textureConfig)};GPGPUContext2.prototype.uploadPixelDataToTexture=function(texture,pixels){this.throwIfDisposed();uploadPixelDataToTexture(this.gl,texture,pixels)};GPGPUContext2.prototype.uploadDenseMatrixToTexture=function(texture,width,height,data2){this.throwIfDisposed();uploadDenseMatrixToTexture(this.gl,texture,width,height,data2,this.textureConfig)};GPGPUContext2.prototype.createFloat16PackedMatrixTexture=function(rows,columns){this.throwIfDisposed();return createFloat16PackedMatrixTexture(this.gl,rows,columns,this.textureConfig)};GPGPUContext2.prototype.createPackedMatrixTexture=function(rows,columns){this.throwIfDisposed();return createPackedMatrixTexture(this.gl,rows,columns,this.textureConfig)};GPGPUContext2.prototype.deleteMatrixTexture=function(texture){var _this=this;this.throwIfDisposed();if(this.outputTexture===texture){unbindColorTextureFromFramebuffer(this.gl,this.framebuffer);this.outputTexture=null}callAndCheck(this.gl,function(){return _this.gl.deleteTexture(texture)})};GPGPUContext2.prototype.downloadByteEncodedFloatMatrixFromOutputTexture=function(texture,rows,columns){var _this=this;return this.downloadMatrixDriver(texture,function(){return downloadByteEncodedFloatMatrixFromOutputTexture(_this.gl,rows,columns,_this.textureConfig)})};GPGPUContext2.prototype.downloadPackedMatrixFromBuffer=function(buffer2,batch,rows,columns,physicalRows,physicalCols){return downloadPackedMatrixFromBuffer(this.gl,buffer2,batch,rows,columns,physicalRows,physicalCols,this.textureConfig)};GPGPUContext2.prototype.downloadFloat32MatrixFromBuffer=function(buffer2,size){return downloadFloat32MatrixFromBuffer(this.gl,buffer2,size)};GPGPUContext2.prototype.createBufferFromTexture=function(texture,rows,columns){this.bindTextureToFrameBuffer(texture);var result=createBufferFromOutputTexture(this.gl,rows,columns,this.textureConfig);this.unbindTextureToFrameBuffer();return result};GPGPUContext2.prototype.createAndWaitForFence=function(){var fenceContext=this.createFence(this.gl);return this.pollFence(fenceContext)};GPGPUContext2.prototype.createFence=function(gl){var _this=this;var query;var isFencePassed;if(tf4.env().getBool("WEBGL_FENCE_API_ENABLED")){var gl2_1=gl;var sync_1=gl2_1.fenceSync(gl2_1.SYNC_GPU_COMMANDS_COMPLETE,0);gl.flush();isFencePassed=function(){var status=gl2_1.clientWaitSync(sync_1,0,0);return status===gl2_1.ALREADY_SIGNALED||status===gl2_1.CONDITION_SATISFIED};query=sync_1}else if(tf4.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0){query=this.beginQuery();this.endQuery();isFencePassed=function(){return _this.isQueryAvailable(query,tf4.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}}else{isFencePassed=function(){return true}}return{query,isFencePassed}};GPGPUContext2.prototype.downloadMatrixFromPackedTexture=function(texture,physicalRows,physicalCols){var _this=this;return this.downloadMatrixDriver(texture,function(){return downloadMatrixFromPackedOutputTexture(_this.gl,physicalRows,physicalCols)})};GPGPUContext2.prototype.createProgram=function(fragmentShaderSource){this.throwIfDisposed();var gl=this.gl;var fragmentShader=createFragmentShader(gl,fragmentShaderSource);var vertexShader=createVertexShader$1(gl);var program=createProgram(gl);callAndCheck(gl,function(){return gl.attachShader(program,vertexShader)});callAndCheck(gl,function(){return gl.attachShader(program,fragmentShader)});linkProgram(gl,program);if(this.debug){validateProgram(gl,program)}if(!this.vertexAttrsAreBound){this.setProgram(program);this.vertexAttrsAreBound=bindVertexProgramAttributeStreams(gl,this.program,this.vertexBuffer)}return program};GPGPUContext2.prototype.deleteProgram=function(program){var _this=this;this.throwIfDisposed();if(program===this.program){this.program=null}if(program!=null){callAndCheck(this.gl,function(){return _this.gl.deleteProgram(program)})}};GPGPUContext2.prototype.setProgram=function(program){var _this=this;this.throwIfDisposed();this.program=program;if(this.program!=null&&this.debug){validateProgram(this.gl,this.program)}callAndCheck(this.gl,function(){return _this.gl.useProgram(program)})};GPGPUContext2.prototype.getUniformLocation=function(program,uniformName,shouldThrow){if(shouldThrow===void 0){shouldThrow=true}this.throwIfDisposed();if(shouldThrow){return getProgramUniformLocationOrThrow(this.gl,program,uniformName)}else{return getProgramUniformLocation(this.gl,program,uniformName)}};GPGPUContext2.prototype.getAttributeLocation=function(program,attribute){var _this=this;this.throwIfDisposed();return callAndCheck(this.gl,function(){return _this.gl.getAttribLocation(program,attribute)})};GPGPUContext2.prototype.getUniformLocationNoThrow=function(program,uniformName){this.throwIfDisposed();return this.gl.getUniformLocation(program,uniformName)};GPGPUContext2.prototype.setInputMatrixTexture=function(inputMatrixTexture,uniformLocation,textureUnit){this.throwIfDisposed();this.throwIfNoProgram();bindTextureToProgramUniformSampler(this.gl,inputMatrixTexture,uniformLocation,textureUnit)};GPGPUContext2.prototype.setOutputMatrixTexture=function(outputMatrixTexture,rows,columns){this.setOutputMatrixTextureDriver(outputMatrixTexture,columns,rows)};GPGPUContext2.prototype.setOutputPackedMatrixTexture=function(outputPackedMatrixTexture,rows,columns){this.throwIfDisposed();var _a=getPackedMatrixTextureShapeWidthHeight(rows,columns),width=_a[0],height=_a[1];this.setOutputMatrixTextureDriver(outputPackedMatrixTexture,width,height)};GPGPUContext2.prototype.setOutputMatrixWriteRegion=function(startRow,numRows,startColumn,numColumns){this.setOutputMatrixWriteRegionDriver(startColumn,startRow,numColumns,numRows)};GPGPUContext2.prototype.setOutputPackedMatrixWriteRegion=function(startRow,numRows,startColumn,numColumns){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")};GPGPUContext2.prototype.debugValidate=function(){if(this.program!=null){validateProgram(this.gl,this.program)}validateFramebuffer(this.gl)};GPGPUContext2.prototype.executeProgram=function(){this.throwIfDisposed();this.throwIfNoProgram();var gl=this.gl;if(this.debug){this.debugValidate()}callAndCheck(gl,function(){return gl.drawElements(gl.TRIANGLES,6,gl.UNSIGNED_SHORT,0)})};GPGPUContext2.prototype.blockUntilAllProgramsCompleted=function(){var _this=this;this.throwIfDisposed();callAndCheck(this.gl,function(){return _this.gl.finish()})};GPGPUContext2.prototype.getQueryTimerExtension=function(){if(this.disjointQueryTimerExtension==null){this.disjointQueryTimerExtension=getExtensionOrThrow(this.gl,tf4.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")}return this.disjointQueryTimerExtension};GPGPUContext2.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension()};GPGPUContext2.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension()};GPGPUContext2.prototype.beginQuery=function(){if(tf4.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){var gl2=this.gl;var ext_1=this.getQueryTimerExtensionWebGL2();var query_1=gl2.createQuery();gl2.beginQuery(ext_1.TIME_ELAPSED_EXT,query_1);return query_1}var ext=this.getQueryTimerExtensionWebGL1();var query=ext.createQueryEXT();ext.beginQueryEXT(ext.TIME_ELAPSED_EXT,query);return query};GPGPUContext2.prototype.endQuery=function(){if(tf4.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){var gl2=this.gl;var ext_2=this.getQueryTimerExtensionWebGL2();gl2.endQuery(ext_2.TIME_ELAPSED_EXT);return}var ext=this.getQueryTimerExtensionWebGL1();ext.endQueryEXT(ext.TIME_ELAPSED_EXT)};GPGPUContext2.prototype.waitForQueryAndGetTime=function(query){return __awaiter(this,void 0,void 0,function(){var _this=this;return __generator(this,function(_a){switch(_a.label){case 0:return[4,tf4.util.repeatedTry(function(){return _this.disposed||_this.isQueryAvailable(query,tf4.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))})];case 1:_a.sent();return[2,this.getQueryTime(query,tf4.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))]}})})};GPGPUContext2.prototype.getQueryTime=function(query,queryTimerVersion){if(queryTimerVersion===0){return null}if(queryTimerVersion===2){var gl2=this.gl;var timeElapsedNanos=gl2.getQueryParameter(query,gl2.QUERY_RESULT);return timeElapsedNanos/1e6}else{var ext=this.getQueryTimerExtensionWebGL1();var timeElapsedNanos=ext.getQueryObjectEXT(query,ext.QUERY_RESULT_EXT);return timeElapsedNanos/1e6}};GPGPUContext2.prototype.isQueryAvailable=function(query,queryTimerVersion){if(queryTimerVersion===0){return true}if(queryTimerVersion===2){var gl2=this.gl;var ext=this.getQueryTimerExtensionWebGL2();var available=gl2.getQueryParameter(query,gl2.QUERY_RESULT_AVAILABLE);if(this.disjoint==null){this.disjoint=this.gl.getParameter(ext.GPU_DISJOINT_EXT)}return available&&!this.disjoint}else{var ext=this.getQueryTimerExtensionWebGL1();var available=ext.getQueryObjectEXT(query,ext.QUERY_RESULT_AVAILABLE_EXT);if(this.disjoint==null){this.disjoint=this.gl.getParameter(ext.GPU_DISJOINT_EXT)}return available&&!this.disjoint}};GPGPUContext2.prototype.pollFence=function(fenceContext){var _this=this;return new Promise(function(resolve){_this.addItemToPoll(function(){return fenceContext.isFencePassed()},function(){return resolve()})})};GPGPUContext2.prototype.pollItems=function(){var index=linearSearchLastTrue(this.itemsToPoll.map(function(x){return x.isDoneFn}));for(var i=0;i<=index;++i){var resolveFn=this.itemsToPoll[i].resolveFn;resolveFn()}this.itemsToPoll=this.itemsToPoll.slice(index+1)};GPGPUContext2.prototype.addItemToPoll=function(isDoneFn,resolveFn){var _this=this;this.itemsToPoll.push({isDoneFn,resolveFn});if(this.itemsToPoll.length>1){return}tf4.util.repeatedTry(function(){_this.pollItems();return _this.itemsToPoll.length===0})};GPGPUContext2.prototype.bindTextureToFrameBuffer=function(texture){this.throwIfDisposed();bindColorTextureToFramebuffer(this.gl,texture,this.framebuffer);if(this.debug){validateFramebuffer(this.gl)}};GPGPUContext2.prototype.unbindTextureToFrameBuffer=function(){if(this.outputTexture!=null){bindColorTextureToFramebuffer(this.gl,this.outputTexture,this.framebuffer);if(this.debug){validateFramebuffer(this.gl)}}else{unbindColorTextureFromFramebuffer(this.gl,this.framebuffer)}};GPGPUContext2.prototype.downloadMatrixDriver=function(texture,downloadAndDecode){this.bindTextureToFrameBuffer(texture);var result=downloadAndDecode();this.unbindTextureToFrameBuffer();return result};GPGPUContext2.prototype.setOutputMatrixTextureDriver=function(outputMatrixTextureMaybePacked,width,height){this.throwIfDisposed();var gl=this.gl;bindColorTextureToFramebuffer(gl,outputMatrixTextureMaybePacked,this.framebuffer);if(this.debug){validateFramebuffer(gl)}this.outputTexture=outputMatrixTextureMaybePacked;callAndCheck(gl,function(){return gl.viewport(0,0,width,height)});callAndCheck(gl,function(){return gl.scissor(0,0,width,height)})};GPGPUContext2.prototype.setOutputMatrixWriteRegionDriver=function(x,y,width,height){var _this=this;this.throwIfDisposed();callAndCheck(this.gl,function(){return _this.gl.scissor(x,y,width,height)})};GPGPUContext2.prototype.throwIfDisposed=function(){if(this.disposed){throw new Error("Attempted to use disposed GPGPUContext.")}};GPGPUContext2.prototype.throwIfNoProgram=function(){if(this.program==null){throw new Error("No GPU program is currently set.")}};return GPGPUContext2}();function linearSearchLastTrue(arr){var i=0;for(;i0){shapeInfo.flatOffset=input.texData.slice.flatOffset}return{name:program.variableNames[i2],shapeInfo}});var inShapeInfos=inputInfos.map(function(x){return x.shapeInfo});var outShapeInfo={logicalShape:output.shape,texShape:output.texData.texShape,isUniform:false,isPacked:output.texData.isPacked,flatOffset:null};var source=makeShader(inputInfos,outShapeInfo,userCode,program.packedInputs);var webGLProgram=gpgpu.createProgram(source);var infLoc=null;var nanLoc=gpgpu.getUniformLocation(webGLProgram,"NAN",false);if(tf4.env().getNumber("WEBGL_VERSION")===1){infLoc=gpgpu.getUniformLocation(webGLProgram,"INFINITY",false)}var uniformLocations={};for(var i=0;i0;var texShape=x.isUniform?"uniform":x.texData.texShape;keyInputs+=x.shape+"_"+texShape+"_"+hasOffset});var keyUserCode=program.userCode;var key=program.constructor.name;key+="_"+keyInputs+"_"+keyUserCode;return key}var Im2ColPackedProgram=function(){function Im2ColPackedProgram2(outputShape,inputShape,convInfo){this.variableNames=["A"];this.packedInputs=true;this.packedOutput=true;this.outputShape=outputShape;var filterWidth=convInfo.filterWidth,inChannels=convInfo.inChannels,strideWidth=convInfo.strideWidth,strideHeight=convInfo.strideHeight,padInfo=convInfo.padInfo,outWidth=convInfo.outWidth,dilationWidth=convInfo.dilationWidth,dilationHeight=convInfo.dilationHeight,dataFormat=convInfo.dataFormat;var left=padInfo.left,top=padInfo.top;var itemsPerBlockRow=inChannels*filterWidth;var glsl=getGlslDifferences();var isChannelsLast=dataFormat==="channelsLast";var rowDim=isChannelsLast?0:1;var colDim=isChannelsLast?1:2;var unrolled="";for(var row=0;row<=1;row++){for(var col=0;col<=1;col++){unrolled+="\n blockIndex = rc.y + "+col+";\n pos = rc.x + "+row+";\n\n if(blockIndex < "+outputShape[1]+" && pos < "+outputShape[0]+") {\n offsetY = int(blockIndex / ("+outWidth+")) * "+strideHeight+" - "+top+";\n d0 = offsetY + "+dilationHeight+" * (pos / "+itemsPerBlockRow+");\n\n if(d0 < "+inputShape[rowDim]+" && d0 >= 0) {\n\n offsetX = int(mod(float(blockIndex), "+outWidth+".) * "+strideWidth+". - "+left+".);\n d1 = offsetX + "+dilationWidth+" * (int(mod(float(pos), "+itemsPerBlockRow+".) / "+inChannels+".));\n\n if(d1 < "+inputShape[colDim]+" && d1 >= 0) {\n\n ch = int(mod(float(pos), "+inChannels+".));\n\n if ("+isChannelsLast+") {\n innerDims = vec2(d1, ch);\n result["+(row*2+col)+"] = getChannel(\n getA(d0, int(innerDims.x),\n int(innerDims.y)), innerDims);\n } else {\n innerDims = vec2(d0, d1);\n result["+(row*2+col)+"] = getChannel(\n getA(ch, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n }\n }\n "}}this.userCode="\n void main() {\n ivec2 rc = getOutputCoords();\n\n vec4 result = vec4(0);\n\n int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n vec2 innerDims;\n\n "+unrolled+"\n\n "+glsl.output+" = result;\n }\n "}return Im2ColPackedProgram2}();var LRNProgram=function(){function LRNProgram2(xShape,radius,bias,alpha,beta){this.variableNames=["x"];this.outputShape=[];var rad=radius;var maxD=xShape[3]-1;this.outputShape=xShape;var powOperator;var basis="float("+bias+") + float("+alpha+") * sum";if(beta===.5){powOperator="inversesqrt("+basis+")"}else if(beta===1){powOperator="1.0/("+basis+")"}else{powOperator="exp(log("+basis+") * float(-"+beta+"));"}this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n int d = coords[3];\n float x = getX(b, r, c, d);\n float sum = 0.0;\n for (int j = -"+rad+"; j <= "+rad+"; j++) {\n int idx = d + j;\n if (idx >= 0 && idx <= "+maxD+") {\n float z = getX(b, r, c, idx);\n sum += z * z;\n }\n }\n float val = x * "+powOperator+";\n setOutput(val);\n }\n "}return LRNProgram2}();var LRNGradProgram=function(){function LRNGradProgram2(inputShape,depthRadius,bias,alpha,beta){this.variableNames=["inputImage","outputImage","dy"];this.outputShape=[];this.outputShape=inputShape;this.depth=inputShape[3];this.depthRadius=depthRadius;this.bias=bias;this.alpha=alpha;this.beta=beta;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n\n float result = 0.0;\n for (int d = 0; d < "+this.depth+"; ++d) {\n int depthBegin = int(max(0.0, float(d - "+depthRadius+")));\n int depthEnd = int(min(float("+this.depth+"),\n float(d + "+depthRadius+" + 1)));\n\n const int MIN_DEPTH_BEGIN = 0;\n const int MAX_DEPTH_END = "+this.depth+";\n\n float norm = 0.0;\n for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd) {\n norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);\n }\n else {\n break;\n }\n }\n\n norm = float("+alpha+") * norm + float("+bias+");\n\n for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd){\n float dyi = -2.0 * float("+alpha+")\n * float("+beta+")\n * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)\n / norm;\n if (k == d) {\n dyi += pow(norm, -1.0 * "+beta+");\n }\n if (k == coords[3]) {\n dyi *= getDy(b, r, c, d);\n result += dyi;\n }\n }\n else {\n break;\n }\n }\n }\n setOutput(result);\n }\n "}return LRNGradProgram2}();var LRNPackedProgram=function(){function LRNPackedProgram2(xShape,radius,bias,alpha,beta){this.variableNames=["x"];this.outputShape=[];this.packedInputs=true;this.packedOutput=true;var rad=radius;var maxD=xShape[3]-1;this.outputShape=xShape;var powOperator;var basis="float("+bias+") + float("+alpha+") * sum";if(beta===.5){powOperator="inversesqrt("+basis+")"}else if(beta===1){powOperator="1.0/("+basis+")"}else{powOperator="exp(log("+basis+") * float(-"+beta+"));"}this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords.x;\n int r = coords.y;\n int c = coords.z;\n int d = coords.w;\n\n bool hasNextCol = d < "+this.outputShape[3]+";\n bool hasNextRow = c < "+this.outputShape[2]+";\n\n vec4 sum = vec4(0.);\n vec4 xFragAtOutputCoords = getX(b, r, c, d);\n\n vec4 xAtOutputCoords = vec4(\n getChannel(xFragAtOutputCoords, vec2(c, d)),\n hasNextCol ?\n getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,\n hasNextRow ?\n getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,\n (hasNextRow && hasNextCol) ?\n getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0\n );\n\n int firstChannel = d - "+rad+";\n vec2 cache = vec2(0.);\n if(firstChannel >= 0){\n vec4 firstChannelFrag = getX(b, r, c, firstChannel);\n cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));\n if(hasNextRow){\n cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));\n }\n }\n\n ivec2 depth = ivec2(d, d + 1);\n for (int j = - "+rad+"; j <= "+rad+"; j++) {\n ivec2 idx = depth + j;\n bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));\n bvec2 belowUpperBound = lessThanEqual(idx, ivec2("+maxD+"));\n\n bool depthInRange = aboveLowerBound.x && belowUpperBound.x;\n bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;\n\n if(depthInRange || depthPlusOneInRange){\n vec4 z = vec4(0.);\n vec4 xFragAtCurrentDepth;\n z.xz = cache.xy;\n if(depthPlusOneInRange && hasNextCol){\n xFragAtCurrentDepth = idx.y != d ?\n getX(b, r, c, idx.y) : xFragAtOutputCoords;\n z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));\n if(hasNextRow){\n z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));\n }\n }\n cache.xy = z.yw;\n sum += z * z;\n }\n }\n vec4 result = xAtOutputCoords * "+powOperator+";\n setOutput(result);\n }\n "}return LRNPackedProgram2}();var MaxPool2DBackpropProgram=function(){function MaxPool2DBackpropProgram2(convInfo){this.variableNames=["dy","maxPos"];this.outputShape=convInfo.inShape;var strideHeight=convInfo.strideHeight;var strideWidth=convInfo.strideWidth;var dilationHeight=convInfo.dilationHeight;var effectiveFilterHeight=convInfo.effectiveFilterHeight;var effectiveFilterWidth=convInfo.effectiveFilterWidth;var padTop=effectiveFilterHeight-1-convInfo.padInfo.top;var padLeft=effectiveFilterWidth-1-convInfo.padInfo.left;var lastIndex=effectiveFilterHeight*effectiveFilterWidth-1;this.userCode="\n const ivec2 pads = ivec2("+padTop+", "+padLeft+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+effectiveFilterHeight+";\n wR += "+dilationHeight+") {\n float dyR = float(dyRCorner + wR) / "+strideHeight+".0;\n\n if (dyR < 0.0 || dyR >= "+convInfo.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+effectiveFilterWidth+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+strideWidth+".0;\n\n if (dyC < 0.0 || dyC >= "+convInfo.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n int maxPosValue = "+lastIndex+" - int(getMaxPos(b, idyR, idyC, d));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue = wR * "+effectiveFilterWidth+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n "}return MaxPool2DBackpropProgram2}();var MaxPool3DBackpropProgram=function(){function MaxPool3DBackpropProgram2(convInfo){this.variableNames=["dy","maxPos"];this.outputShape=convInfo.inShape;var strideDepth=convInfo.strideDepth;var strideHeight=convInfo.strideHeight;var strideWidth=convInfo.strideWidth;var dilationDepth=convInfo.dilationDepth;var dilationHeight=convInfo.dilationHeight;var dilationWidth=convInfo.dilationWidth;var effectiveFilterDepth=convInfo.effectiveFilterDepth;var effectiveFilterHeight=convInfo.effectiveFilterHeight;var effectiveFilterWidth=convInfo.effectiveFilterWidth;var padFront=effectiveFilterDepth-1-convInfo.padInfo.front;var padTop=effectiveFilterHeight-1-convInfo.padInfo.top;var padLeft=effectiveFilterWidth-1-convInfo.padInfo.left;var lastIndex=effectiveFilterDepth*effectiveFilterHeight*effectiveFilterWidth-1;this.userCode="\n const ivec3 pads = ivec3("+padFront+", "+padTop+", "+padLeft+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < "+effectiveFilterDepth+";\n wD += "+dilationDepth+") {\n float dyD = float(dyDCorner + wD) / "+strideDepth+".0;\n\n if (dyD < 0.0 || dyD >= "+convInfo.outDepth+".0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < "+effectiveFilterHeight+";\n wR += "+dilationHeight+") {\n float dyR = float(dyRCorner + wR) / "+strideHeight+".0;\n\n if (dyR < 0.0 || dyR >= "+convInfo.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+effectiveFilterWidth+";\n wC += "+dilationWidth+") {\n float dyC = float(dyCCorner + wC) / "+strideWidth+".0;\n\n if (dyC < 0.0 || dyC >= "+convInfo.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n int maxPosValue = "+lastIndex+" -\n int(getMaxPos(batch, idyD, idyR, idyC, ch));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue =\n wD * "+effectiveFilterHeight+" * "+effectiveFilterWidth+" +\n wR * "+effectiveFilterWidth+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n }\n setOutput(dotProd);\n }\n "}return MaxPool3DBackpropProgram2}();var MatMulPackedProgram=function(){function MatMulPackedProgram2(aShape,bShape,outputShape,transposeA,transposeB,addBias,activation,hasPreluActivation){if(transposeA===void 0){transposeA=false}if(transposeB===void 0){transposeB=false}if(addBias===void 0){addBias=false}if(activation===void 0){activation=null}if(hasPreluActivation===void 0){hasPreluActivation=false}this.variableNames=["matrixA","matrixB"];this.packedInputs=true;this.packedOutput=true;this.outputShape=outputShape;var sharedDim=transposeA?aShape[1]:aShape[2];var sharedDimensionPacked=Math.ceil(sharedDim/2);var aSample=transposeA?"i * 2, rc.y":"rc.y, i * 2";var bSample=transposeB?"rc.z, i * 2":"i * 2, rc.z";var aSwizzle=transposeA?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"];var bSwizzle=transposeB?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];var activationSnippet="",applyActivationSnippet="";if(activation){if(hasPreluActivation){activationSnippet="vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n "+activation+"\n }"}else{activationSnippet="vec4 activation(vec4 x) {\n "+activation+"\n }"}applyActivationSnippet="result = activation(result);"}var addBiasSnippet=addBias?"result += getBiasAtOutCoords();":"";if(addBias){this.variableNames.push("bias")}if(hasPreluActivation){this.variableNames.push("preluActivationWeights")}var batchASnippet="rc.x";var batchBSnippet="rc.x";if(aShape[0] "+shape[0]}var cond="";for(var i=rank-2;i= "+shape[i];if(i= "+cols+";\n bool rEdge = rp1 >= "+rows+";\n "}function getOutput(shape,dims){var rank=shape.length;var sourceCoords=getSourceCoordsArr(rank,dims);if(rank===1){return"getA(rc),\n rc + 1 >= "+shape[0]+" ? 0. : getA(rc + 1),\n 0, 0"}return"getA("+sourceCoords[0]+"),\n cEdge ? 0. : getA("+sourceCoords[1]+"),\n rEdge ? 0. : getA("+sourceCoords[2]+"),\n rEdge || cEdge ? 0. : getA("+sourceCoords[3]+")"}var PadProgram=function(){function PadProgram2(xShape,paddings,constantValue){this.variableNames=["x"];this.outputShape=paddings.map(function(p,i){return p[0]+xShape[i]+p[1]});var rank=xShape.length;var type=getCoordsDataType(rank);var start=paddings.map(function(p){return p[0]}).join(",");var end=paddings.map(function(p,i){return p[0]+xShape[i]}).join(",");var unpackedCoords=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,rank);if(rank===1){this.userCode="\n int start = "+start+";\n int end = "+end+";\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(float("+constantValue+"));\n } else {\n setOutput(getX(outC - start));\n }\n }\n ";return}this.userCode="\n "+type+" start = "+type+"("+start+");\n "+type+" end = "+type+"("+end+");\n\n void main() {\n "+type+" outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(float("+constantValue+"));\n } else {\n "+type+" coords = outC - start;\n setOutput(getX("+unpackedCoords+"));\n }\n }\n "}return PadProgram2}();var PadPackedProgram=function(){function PadPackedProgram2(xShape,paddings,constantValue){this.variableNames=["x"];this.packedInputs=true;this.packedOutput=true;this.outputShape=paddings.map(function(p,i2){return p[0]+xShape[i2]+p[1]});var rank=xShape.length;var dtype=getCoordsDataType(rank);var start=paddings.map(function(p){return p[0]}).join(",");var end=paddings.map(function(p,i2){return p[0]+xShape[i2]}).join(",");var coords2=getChannels("rc",rank);var source=getChannels("source",rank);var cLimit=coords2[rank-1]+" < "+this.outputShape[rank-1];var innerDims=rank===1?"source":"vec2("+source.slice(-2).join()+")";var componentSetup=[dtype+" rc = outputLoc;",coords2[rank-1]+" += 1;\n if("+cLimit+") {\n ",rank===1?"":"}\n rc = outputLoc;\n "+coords2[rank-2]+" += 1;\n if("+coords2[rank-2]+" < "+this.outputShape[rank-2]+") {",rank===1?"":" "+coords2[rank-1]+" += 1;\n if("+cLimit+") {"];var paddingArea=rank===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";var mainLoop="";for(var i=0,j=rank===1?2:4;i= "+convInfo.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+effectiveFilterWidth+";\n wC += "+dilationWidth+") {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= "+convInfo.inWidth+") {\n continue;\n }\n\n float value = getX(batch, xR, xC, d);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value "+compareOp_1+" currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = "+(flattenPositions?includeBatchInIndex?batchFlattenPositionStr:flattenPositionStr:"wR * "+effectiveFilterWidth+" + wC")+";\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";return}var compareOp="max";var returnValue=poolType+"("+poolType+"("+poolType+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";if(poolType==="avg"){returnValue="avgValue / count"}var filterWidthNearestVec4=Math.floor(filterWidth/4)*4;var filterWidthVec4Remainder=filterWidth%4;var updateSnippet="\n if ("+isAvgPool+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = "+compareOp+"(values, minMaxValue);\n }\n ";this.userCode="\n const ivec2 strides = ivec2("+strideHeight+", "+strideWidth+");\n const ivec2 pads = ivec2("+padTop+", "+padLeft+");\n const float initializationValue = "+initializationValue+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xR, int xC, int d) {\n if (xC < 0 || xC >= "+convInfo.inWidth+") {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xR, xC, d);\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n vec4 minMaxValue = vec4("+initializationValue+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < "+effectiveFilterHeight+";\n wR += "+dilationHeight+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+convInfo.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+filterWidthNearestVec4+"; wC += 4) {\n int xC = xCCorner + wC * "+dilationWidth+";\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+dilationWidth+", d),\n getValue(batch, xR, xC + 2 * "+dilationWidth+", d),\n getValue(batch, xR, xC + 3 * "+dilationWidth+", d)\n );\n\n "+updateSnippet+"\n }\n\n int xC = xCCorner + "+filterWidthNearestVec4+";\n if ("+(filterWidthVec4Remainder===1)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+updateSnippet+"\n } else if ("+(filterWidthVec4Remainder===2)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+dilationWidth+", d),\n initializationValue,\n initializationValue\n );\n\n "+updateSnippet+"\n } else if ("+(filterWidthVec4Remainder===3)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+dilationWidth+", d),\n getValue(batch, xR, xC + 2 * "+dilationWidth+", d),\n initializationValue\n );\n\n "+updateSnippet+"\n }\n }\n setOutput("+returnValue+");\n }\n "}return Pool2DProgram2}();var Pool3DProgram=function(){function Pool3DProgram2(convInfo,poolType,computePositions,flattenPositions,includeBatchInIndex){if(flattenPositions===void 0){flattenPositions=false}if(includeBatchInIndex===void 0){includeBatchInIndex=false}this.variableNames=["x"];if(poolType==="avg"&&computePositions){throw new Error("Cannot compute positions for average pool.")}var filterWidth=convInfo.filterWidth;var strideDepth=convInfo.strideDepth;var strideHeight=convInfo.strideHeight;var strideWidth=convInfo.strideWidth;var dilationDepth=convInfo.dilationDepth;var dilationHeight=convInfo.dilationHeight;var dilationWidth=convInfo.dilationWidth;var effectiveFilterDepth=convInfo.effectiveFilterDepth;var effectiveFilterHeight=convInfo.effectiveFilterHeight;var effectiveFilterWidth=convInfo.effectiveFilterWidth;var padFront=convInfo.padInfo.front;var padTop=convInfo.padInfo.top;var padLeft=convInfo.padInfo.left;this.outputShape=convInfo.outShape;var isAvgPool=poolType==="avg";var initializationValue="0.0";if(!isAvgPool){initializationValue="-1.0 / 1e-20"}if(computePositions){var compareOp_2=">=";this.userCode="\n const ivec3 strides =\n ivec3("+strideDepth+", "+strideHeight+", "+strideWidth+");\n const ivec3 pads = ivec3("+padFront+", "+padTop+", "+padLeft+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n\n for (int wD = 0; wD < "+effectiveFilterDepth+";\n wD += "+dilationDepth+") {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= "+convInfo.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+effectiveFilterHeight+";\n wR += "+dilationHeight+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+convInfo.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+effectiveFilterWidth+";\n wC += "+dilationWidth+") {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= "+convInfo.inWidth+") {\n continue;\n }\n\n float value = getX(batch, xD, xR, xC, ch);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value "+compareOp_2+" currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = "+(flattenPositions?includeBatchInIndex?"(((batch * "+convInfo.inDepth+" + xD) * "+convInfo.inHeight+" + xR) * "+convInfo.inWidth+" + xC) * "+convInfo.inChannels+" + ch":"((xD * "+convInfo.inHeight+" + xR) * "+convInfo.inWidth+" + xC) * "+convInfo.inChannels+" + ch":"wD * "+effectiveFilterHeight+" * "+effectiveFilterWidth+" +\n wR * "+effectiveFilterWidth+" + wC")+";\n }\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";return}var compareOp="max";var returnValue=poolType+"("+poolType+"("+poolType+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";if(poolType==="avg"){returnValue="avgValue / count"}var filterWidthNearestVec4=Math.floor(filterWidth/4)*4;var filterWidthVec4Remainder=filterWidth%4;var updateSnippet="\n if ("+isAvgPool+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = "+compareOp+"(values, minMaxValue);\n }\n ";this.userCode="\n const ivec3 strides =\n ivec3("+strideDepth+", "+strideHeight+", "+strideWidth+");\n const ivec3 pads = ivec3("+padFront+", "+padTop+", "+padLeft+");\n const float initializationValue = "+initializationValue+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xD, int xR, int xC, int ch) {\n if (xC < 0 || xC >= "+convInfo.inWidth+") {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xD, xR, xC, ch);\n }\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).\n // ? = to be determined\n vec4 minMaxValue = vec4("+initializationValue+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wD = 0; wD < "+effectiveFilterDepth+";\n wD += "+dilationDepth+") {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= "+convInfo.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+effectiveFilterHeight+";\n wR += "+dilationHeight+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+convInfo.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+filterWidthNearestVec4+"; wC += 4) {\n int xC = xCCorner + wC * "+dilationWidth+";\n\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+dilationWidth+", ch),\n getValue(batch, xD, xR, xC + 2 * "+dilationWidth+", ch),\n getValue(batch, xD, xR, xC + 3 * "+dilationWidth+", ch)\n );\n\n "+updateSnippet+"\n }\n\n int xC = xCCorner + "+filterWidthNearestVec4+";\n if ("+(filterWidthVec4Remainder===1)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+updateSnippet+"\n } else if ("+(filterWidthVec4Remainder===2)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+dilationWidth+", ch),\n initializationValue,\n initializationValue\n );\n\n "+updateSnippet+"\n } else if ("+(filterWidthVec4Remainder===3)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+dilationWidth+", ch),\n getValue(batch, xD, xR, xC + 2 * "+dilationWidth+", ch),\n initializationValue\n );\n\n "+updateSnippet+"\n }\n }\n setOutput("+returnValue+");\n }\n }\n "}return Pool3DProgram2}();var ReduceProgram=function(){function ReduceProgram2(reduceInfo,reduceType){this.variableNames=["x"];var windowSize=reduceInfo.windowSize,batchSize=reduceInfo.batchSize,inSize=reduceInfo.inSize,outSize=reduceInfo.outSize;this.outputShape=[batchSize,outSize];var initializationValue="0.0";var compareOp="";if(reduceType==="prod"){initializationValue="1.0"}else if(reduceType==="min"){initializationValue="1.0 / 1e-20";compareOp="min"}else if(reduceType==="max"){initializationValue="-1.0 / 1e-20";compareOp="max"}var returnValue=reduceType+"("+reduceType+"("+reduceType+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";if(reduceType==="sum"){returnValue="sumValue"}else if(reduceType==="prod"){returnValue="prodValue"}else if(reduceType==="all"){returnValue="allValue"}else if(reduceType==="any"){returnValue="anyValue"}var windowSizeNearestVec4=Math.floor(windowSize/4)*4;var windowSizeVec4Remainder=windowSize%4;var updateSnippet="\n if ("+(reduceType==="sum")+") {\n sumValue += dot(values, ones);\n } else if ("+(reduceType==="prod")+") {\n vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n prodValue *= tmp[0] * tmp[1];\n } else {\n minMaxValue = "+compareOp+"(values, minMaxValue);\n }\n ";var vecType="vec4";if(reduceType==="all"){initializationValue="1.0";updateSnippet="\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n ";vecType="bvec4"}else if(reduceType==="any"){initializationValue="0.0";updateSnippet="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ";vecType="bvec4"}var checkOutOfBounds="";if(inSize%windowSize>0){checkOutOfBounds="\n if (inIdx < 0 || inIdx >= "+inSize+") {\n return initializationValue;\n }\n "}this.userCode="\n const float initializationValue = "+initializationValue+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n "+checkOutOfBounds+"\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+windowSize+";\n\n vec4 minMaxValue = vec4("+initializationValue+");\n float prodValue = 1.0;\n float sumValue = 0.0;\n float allValue = 1.0;\n float anyValue = 0.0;\n\n for (int i = 0; i < "+windowSizeNearestVec4+"; i += 4) {\n int inIdx = inOffset + i;\n "+vecType+" values = "+vecType+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n "+updateSnippet+"\n }\n\n int inIdx = inOffset + "+windowSizeNearestVec4+";\n if ("+(windowSizeVec4Remainder===1)+") {\n "+vecType+" values = "+vecType+"(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+updateSnippet+"\n } else if ("+(windowSizeVec4Remainder===2)+") {\n "+vecType+" values = "+vecType+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n "+updateSnippet+"\n } else if ("+(windowSizeVec4Remainder===3)+") {\n "+vecType+" values = "+vecType+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n "+updateSnippet+"\n }\n setOutput("+returnValue+");\n }\n "}return ReduceProgram2}();var ReshapePackedProgram=function(){function ReshapePackedProgram2(outputShape,inputShape){this.variableNames=["A"];this.packedInputs=true;this.packedOutput=true;this.outputShape=outputShape;var mainLoop="";for(var i=0;i<4;i++){var thisRC="thisRC = rc;";if(i%2===1){thisRC+="thisRC.z += 1;"}if(i>1){thisRC+="thisRC.y += 1;"}mainLoop+="\n "+thisRC+"\n "+(i>0?"if(thisRC.y < rows && thisRC.z < cols){":"")+"\n int flatIndex = getFlatIndex(thisRC);\n\n ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);\n vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n result["+i+"] =\n getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n "+(i>0?"}":"")+"\n "}this.userCode="\n "+getReshapedInputCoords(inputShape)+"\n "+getFlatIndexFrom3D(outputShape)+"\n\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0.);\n\n ivec3 thisRC;\n int rows = "+outputShape[1]+";\n int cols = "+outputShape[2]+";\n\n "+mainLoop+"\n\n setOutput(result);\n }\n "}return ReshapePackedProgram2}();function getReshapedInputCoords(shape){var coordsFromIndexSnippet=getLogicalCoordinatesFromFlatIndex(["r","c","d"],shape);return"\n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n "+coordsFromIndexSnippet+"\n return ivec3(r, c, d);\n }\n "}var ResizeBilinearBackpropProgram=function(){function ResizeBilinearBackpropProgram2(dy,x,alignCorners){this.variableNames=["dy"];this.outputShape=[];this.outputShape=x.shape;var _a=x.shape,xHeight=_a[1],xWidth=_a[2];var _b=dy.shape,yHeight=_b[1],yWidth=_b[2];var effectiveXSize=[alignCorners&&yHeight>1?xHeight-1:xHeight,alignCorners&&yWidth>1?xWidth-1:xWidth];var effectiveYSize=[alignCorners&&yHeight>1?yHeight-1:yHeight,alignCorners&&yWidth>1?yWidth-1:yWidth];var heightScale=effectiveXSize[0]/effectiveYSize[0];var widthScale=effectiveXSize[1]/effectiveYSize[1];var invHeightScale=1/heightScale;var invWidthScale=1/widthScale;var winHeight=Math.ceil(invHeightScale)*2+2;var winWidth=Math.ceil(invWidthScale)*2+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+heightScale+");\n const float widthScale = float("+widthScale+");\n\n const float invHeightScale = float("+invHeightScale+");\n const float invWidthScale = float("+invWidthScale+");\n\n const int winHeight = int("+winHeight+");\n const int winWidth = int("+winWidth+");\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(startRLerp - float(winHeight / 2));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(startCLerp - float(winWidth / 2));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= "+yHeight+") {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= "+yWidth+") {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), "+(xHeight-1)+".0));\n float dxRLerp = dxR - float(topDxRIndex);\n float inverseDxRLerp = 1.0 - dxRLerp;\n\n float dxC = float(dyC) * widthScale;\n int leftDxCIndex = int(floor(dxC));\n int rightDxCIndex = int(min(ceil(dxC), "+(xWidth-1)+".0));\n float dxCLerp = dxC - float(leftDxCIndex);\n float inverseDxCLerp = 1.0 - dxCLerp;\n\n if (r == topDxRIndex && c == leftDxCIndex) {\n // topLeft\n accumulator +=\n getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;\n }\n\n if (r == topDxRIndex && c == rightDxCIndex) {\n // topRight\n accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;\n }\n\n if (r == bottomDxRIndex && c == leftDxCIndex) {\n // bottomLeft\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;\n }\n\n if (r == bottomDxRIndex && c == rightDxCIndex) {\n // bottomRight\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n "}return ResizeBilinearBackpropProgram2}();var ResizeBilinearProgram=function(){function ResizeBilinearProgram2(inputShape,newHeight,newWidth,alignCorners){this.variableNames=["A"];this.outputShape=[];var batch=inputShape[0],oldHeight=inputShape[1],oldWidth=inputShape[2],depth=inputShape[3];this.outputShape=[batch,newHeight,newWidth,depth];var effectiveInSize=[alignCorners&&newHeight>1?oldHeight-1:oldHeight,alignCorners&&newWidth>1?oldWidth-1:oldWidth];var effectiveOutSize=[alignCorners&&newHeight>1?newHeight-1:newHeight,alignCorners&&newWidth>1?newWidth-1:newWidth];this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+effectiveInSize[0]/effectiveOutSize[0]+",\n "+effectiveInSize[1]/effectiveOutSize[1]+");\n const vec2 inputShapeRC = vec2("+oldHeight+".0, "+oldWidth+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);\n ivec2 sourceCeilRC = ivec2(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n float top = topLeft + (topRight - topLeft) * fracRC.y;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n float newValue = top + (bottom - top) * fracRC.x;\n\n setOutput(newValue);\n }\n "}return ResizeBilinearProgram2}();var ResizeBilinearPackedProgram=function(){function ResizeBilinearPackedProgram2(inputShape,newHeight,newWidth,alignCorners){this.variableNames=["A"];this.packedInputs=true;this.packedOutput=true;this.outputShape=[];var batch=inputShape[0],oldHeight=inputShape[1],oldWidth=inputShape[2],depth=inputShape[3];this.outputShape=[batch,newHeight,newWidth,depth];var effectiveInSize=[alignCorners&&newHeight>1?oldHeight-1:oldHeight,alignCorners&&newWidth>1?oldWidth-1:oldWidth];var effectiveOutSize=[alignCorners&&newHeight>1?newHeight-1:newHeight,alignCorners&&newWidth>1?newWidth-1:newWidth];this.userCode="\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n "+effectiveInSize[0]/effectiveOutSize[0]+",\n "+effectiveInSize[1]/effectiveOutSize[1]+",\n "+effectiveInSize[1]/effectiveOutSize[1]+");\n const vec3 inputShapeRC = vec3("+oldHeight+".0, "+oldWidth+".0,\n "+oldWidth+".0);\n\n float getAValue(int b, int r, int c, int d) {\n return getChannel(getA(b, r, c, d), vec2(c, d));\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n // Calculate values for next column in yRC.z.\n ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n // Fractional source index.\n vec3 sourceFracIndexRC = vec3(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec3 sourceFloorRC = ivec3(sourceFracIndexRC);\n ivec3 sourceCeilRC = ivec3(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < "+(depth-1)+";\n bool hasNextRow = coords.z < "+(newWidth-1)+";\n\n // In parallel, construct four corners for all four components in\n // packed 2x2 cell.\n vec4 topLeft = vec4(\n getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 bottomLeft = vec4(\n getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 topRight = vec4(\n getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec4 bottomRight = vec4(\n getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);\n\n vec4 top = mix(topLeft, topRight, fracRC.yyzz);\n vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);\n vec4 newValue = mix(top, bottom, fracRC.x);\n\n setOutput(newValue);\n }\n "}return ResizeBilinearPackedProgram2}();var ResizeNearestNeigborBackpropProgram=function(){function ResizeNearestNeigborBackpropProgram2(dy,x,alignCorners){this.variableNames=["dy"];this.outputShape=[];this.outputShape=x.shape;var _a=x.shape,xHeight=_a[1],xWidth=_a[2];var _b=dy.shape,yHeight=_b[1],yWidth=_b[2];var effectiveXSize=[alignCorners&&yHeight>1?xHeight-1:xHeight,alignCorners&&yWidth>1?xWidth-1:xWidth];var effectiveYSize=[alignCorners&&yHeight>1?yHeight-1:yHeight,alignCorners&&yWidth>1?yWidth-1:yWidth];var heightScale=effectiveXSize[0]/effectiveYSize[0];var widthScale=effectiveXSize[1]/effectiveYSize[1];var invHeightScale=1/heightScale;var invWidthScale=1/widthScale;var winHeight=Math.ceil(invHeightScale)*2+2;var winWidth=Math.ceil(invWidthScale)*2+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+heightScale+");\n const float widthScale = float("+widthScale+");\n\n const float invHeightScale = float("+invHeightScale+");\n const float invWidthScale = float("+invWidthScale+");\n\n const int winHeight = int("+winHeight+");\n const int winWidth = int("+winWidth+");\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(floor(startRLerp - float(winHeight / 2)));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(floor(startCLerp - float(winWidth / 2)));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= "+yHeight+") {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= "+yWidth+") {\n continue;\n }\n\n float sourceFracRow =\n float("+effectiveXSize[0]+") *\n (float(dyR) / float("+effectiveYSize[0]+"));\n\n float sourceFracCol =\n float("+effectiveXSize[1]+") *\n (float(dyC) / float("+effectiveYSize[1]+"));\n\n int sourceNearestRow = int(min(\n float(int("+xHeight+") - 1),\n "+alignCorners+" ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int("+xWidth+") - 1),\n "+alignCorners+" ? float(round(sourceFracCol)) :\n float(floor(sourceFracCol))));\n\n if (r == sourceNearestRow && c == sourceNearestCol) {\n accumulator += getDy(b, dyR, dyC, d);\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n "}return ResizeNearestNeigborBackpropProgram2}();var ResizeNearestNeighborProgram=function(){function ResizeNearestNeighborProgram2(inputShape,newHeight,newWidth,alignCorners){this.variableNames=["A"];this.outputShape=[];var batch=inputShape[0],oldHeight=inputShape[1],oldWidth=inputShape[2],depth=inputShape[3];this.outputShape=[batch,newHeight,newWidth,depth];var effectiveInSize=[alignCorners&&newHeight>1?oldHeight-1:oldHeight,alignCorners&&newWidth>1?oldWidth-1:oldWidth];var effectiveOutSize=[alignCorners&&newHeight>1?newHeight-1:newHeight,alignCorners&&newWidth>1?newWidth-1:newWidth];var roundBase=alignCorners?"0.5":"0.0";this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+effectiveInSize[0]/effectiveOutSize[0]+",\n "+effectiveInSize[1]/effectiveOutSize[1]+");\n const vec2 inputShapeRC = vec2("+oldHeight+".0, "+oldWidth+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + "+roundBase+")));\n\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\n "}return ResizeNearestNeighborProgram2}();var ReverseProgram=function(){function ReverseProgram2(xShape,axis){this.variableNames=["x"];var rank=xShape.length;if(rank>4){throw new Error("WebGL backend: Reverse of rank-"+rank+" tensor is not yet supported")}this.outputShape=xShape;if(rank===1){this.userCode="\n void main() {\n int coord = getOutputCoords();\n setOutput(getX("+xShape[0]+" - coord - 1));\n }\n ";return}var getInCoord=function(i){if(axis.indexOf(i)!==-1&&xShape[i]!==1){return xShape[i]+" - coords["+i+"] - 1"}return"coords["+i+"]"};var inCoords=xShape.map(function(_,i){return getInCoord(i)}).join(",");var type=getCoordsDataType(rank);this.userCode="\n void main() {\n "+type+" coords = getOutputCoords();\n setOutput(getX("+inCoords+"));\n }\n "}return ReverseProgram2}();var ReversePackedProgram=function(){function ReversePackedProgram2(xShape,axis){this.variableNames=["x"];this.packedInputs=true;this.packedOutput=true;var rank=xShape.length;if(rank>4){throw new Error("WebGL backend: Reverse of rank-"+rank+" tensor is not yet supported")}this.outputShape=xShape;var channels=getChannels("rc",rank);var nextColumn=channels[rank-1]+" + 1 < "+this.outputShape[rank-1];var nextRow=channels[rank-2]+" + 1 < "+this.outputShape[rank-2];var type=getCoordsDataType(rank);if(rank===1){this.userCode="\n void main(){\n int rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = getChannel(getX("+xShape[0]+" - rc - 1),\n "+xShape[0]+" - rc - 1);\n if("+nextColumn+"){\n result.g = getChannel(getX("+xShape[0]+" - (rc + 1) - 1),\n "+xShape[0]+" - (rc + 1) - 1);\n }\n setOutput(result);\n }\n "}else{this.userCode="\n void main() {\n "+type+" rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = "+getR(channels.slice())+";\n if("+nextColumn+"){\n result.g = "+getG(channels.slice())+";\n }\n if("+nextRow+") {\n result.b = "+getB(channels.slice())+";\n if("+nextColumn+") {\n result.a = "+getA(channels.slice())+";\n }\n }\n setOutput(result);\n }\n "}function getR(channels2){return getChannel(channels2)}function getG(channels2){channels2[rank-1]="("+channels2[rank-1]+" + 1)";return getChannel(channels2)}function getB(channels2){channels2[rank-2]="("+channels2[rank-2]+" + 1)";return getChannel(channels2)}function getA(channels2){channels2[rank-1]="("+channels2[rank-1]+" + 1)";channels2[rank-2]="("+channels2[rank-2]+" + 1)";return getChannel(channels2)}function getChannel(channels2){var inCoordsArray=xShape.map(function(_,i){return getInCoord(i,channels2)});var inCoords=inCoordsArray.join(",");var innerDims=inCoordsArray.slice(-2).join(",");return"getChannel(getX("+inCoords+"), vec2("+innerDims+"))"}function getInCoord(i,channels1){if(axis.indexOf(i)!==-1&&xShape[i]!==1){return xShape[i]+" - "+channels1[i]+" - 1"}else{return""+channels1[i]}}}return ReversePackedProgram2}();var ScatterProgram=function(){function ScatterProgram2(updateSize,sliceDim,indicesRank,updatesRank,strides,shape,summingDupeIndex){this.variableNames=["updates","indices","defaultValue"];this.outputShape=shape;var stridesType=getCoordsDataType(strides.length);var dtype=getCoordsDataType(shape.length);var indicesString="";if(indicesRank===1){indicesString="i"}else if(indicesRank===2){indicesString="i, j"}var indicesSnippet="getIndices("+indicesString+")";var updatesString="";if(updatesRank===1){updatesString="i"}else if(updatesRank===2){updatesString="i, coords[1]"}var updatesSnippet="getUpdates("+updatesString+")";var strideString=sliceDim>1?"strides[j]":"strides";this.userCode="\n "+stridesType+" strides = "+stridesType+"("+strides+");\n\n void main() {\n "+dtype+" coords = getOutputCoords();\n float sum = 0.0;\n bool found = false;\n for (int i = 0; i < "+updateSize+"; i++) {\n int flattenedIndex = 0;\n for (int j = 0; j < "+sliceDim+"; j++) {\n int index = round("+indicesSnippet+");\n flattenedIndex += index * "+strideString+";\n }\n if (flattenedIndex == coords[0]) {\n sum += "+updatesSnippet+";\n found = true;\n }\n }\n setOutput(mix(getDefaultValue(), sum, float(found)));\n }\n "}return ScatterProgram2}();var SegmentOpProgram=function(){function SegmentOpProgram2(segOpInfo,segOpType){this.variableNames=["x","segmentIds"];var windowSize=segOpInfo.windowSize;var batchSize=segOpInfo.batchSize;var inSize=segOpInfo.inSize;var numSegments=segOpInfo.numSegments;var outSize=numSegments*Math.ceil(inSize/windowSize);this.outputShape=[batchSize,outSize];var initializationValue="0.0";var returnValue="sumValue";var windowSizeNearestVec4=Math.floor(windowSize/4)*4;var windowSizeVec4Remainder=windowSize%4;var updateSnippet="\n sumValue += dot(values, segFilter);\n ";var checkValueOutOfBounds="";if(inSize%windowSize>0){checkValueOutOfBounds="\n if (inIdx < 0 || inIdx >= "+inSize+") {\n return initializationValue;\n }\n "}var checkSegmentIdOutOfBounds="";if(inSize%windowSize>0){checkSegmentIdOutOfBounds="\n if (inIdx < 0 || inIdx >= "+inSize+") {\n return -1.0;\n }\n "}this.userCode="\n const float initializationValue = "+initializationValue+";\n\n float getValue(int batch, int inIdx) {\n "+checkValueOutOfBounds+"\n return getX(batch, inIdx);\n }\n\n float getSegmentIdAtIndex(int inIdx) {\n "+checkSegmentIdOutOfBounds+"\n return getSegmentIds(inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = int(floor(float(outIdx) / float(\n "+numSegments+")) * float("+windowSize+"));\n int currentSeg = int(mod(float(outIdx), float("+numSegments+")));\n\n float sumValue = 0.0;\n\n for (int i = 0; i < "+windowSizeNearestVec4+"; i += 4) {\n int inIdx = inOffset + i;\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0\n );\n\n "+updateSnippet+"\n }\n\n int inIdx = inOffset + "+windowSizeNearestVec4+";\n if ("+(windowSizeVec4Remainder===1)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n int inIdxSeg = int(getSegmentIdAtIndex(inIdx));\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n 0,\n 0,\n 0\n );\n\n "+updateSnippet+"\n } else if ("+(windowSizeVec4Remainder===2)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n 0,\n 0\n );\n\n "+updateSnippet+"\n } else if ("+(windowSizeVec4Remainder===3)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n 0\n );\n\n "+updateSnippet+"\n }\n setOutput("+returnValue+");\n }\n "}return SegmentOpProgram2}();var SelectProgram=function(){function SelectProgram2(cRank,shape,rank){this.variableNames=["c","a","b"];this.outputShape=shape;var cCoords;var abCoords;if(rank>4){throw Error("Where for rank "+rank+" is not yet supported")}if(rank===1){abCoords="resRC";cCoords="resRC"}else{var currentCoords=["resRC.x","resRC.y","resRC.z","resRC.w"];var cCoordVars=[];var abCoordVars=[];for(var i=0;i= 1.0) {\n setOutput(getA("+abCoords+"));\n } else {\n setOutput(getB("+abCoords+"));\n }\n }\n "}return SelectProgram2}();var SliceProgram=function(){function SliceProgram2(destSize){this.variableNames=["source"];this.outputShape=destSize;this.rank=destSize.length;var dtype=getCoordsDataType(this.rank);var uniformPart="uniform int start["+this.rank+"];";var sourceCoords=getCoords$1(this.rank);var body2;var coordSum=destSize.map(function(_,i){return"sourceLoc."+coords[i]+" = start["+i+"] + coords."+coords[i]+";"});body2="\n "+dtype+" sourceLoc;\n "+dtype+" coords = getOutputCoords();\n "+coordSum.join("\n")+"\n ";this.userCode="\n "+uniformPart+"\n void main() {\n "+body2+"\n setOutput(getSource("+sourceCoords+"));\n }\n "}SliceProgram2.prototype.getCustomSetupFunc=function(start){var _this=this;if(start.length!==this.rank){throw Error("The rank ("+this.rank+") of the program must match the "+("length of start ("+start.length+")"))}return function(gpgpu,webGLProgram){if(_this.startLoc==null){_this.startLoc=gpgpu.getUniformLocationNoThrow(webGLProgram,"start");if(_this.startLoc==null){return}}gpgpu.gl.uniform1iv(_this.startLoc,start)}};return SliceProgram2}();var coords=["x","y","z","w","u","v"];function getCoords$1(rank){if(rank===1){return"sourceLoc"}else if(rank<=6){return coords.slice(0,rank).map(function(x){return"sourceLoc."+x}).join(",")}else{throw Error("Slicing for rank "+rank+" is not yet supported")}}var SlicePackedProgram=function(){function SlicePackedProgram2(destSize){this.variableNames=["source"];this.packedInputs=true;this.packedOutput=true;this.outputShape=destSize;this.rank=destSize.length;var dtype=getCoordsDataType(this.rank);var coords2=getChannels("coords",this.rank);var sourceLoc=getChannels("sourceLoc",this.rank);var innerDims=this.rank===1?"sourceLoc":"vec2("+sourceLoc.slice(-2).join()+")";var getChannel="getChannel(getSource("+sourceLoc.join()+"), "+innerDims+")";var upperRow="\n result.x = "+getChannel+";\n if (++"+coords2[this.rank-1]+" < "+destSize[this.rank-1]+") {\n ++"+sourceLoc[this.rank-1]+";\n result.y = "+getChannel+";\n --"+sourceLoc[this.rank-1]+";\n }\n ";var lowerRow=this.rank===1?"":"\n --"+coords2[this.rank-1]+";\n if (++"+coords2[this.rank-2]+" < "+destSize[this.rank-2]+") {\n ++"+sourceLoc[this.rank-2]+";\n result.z = "+getChannel+";\n if (++"+coords2[this.rank-1]+" < "+destSize[this.rank-1]+") {\n ++"+sourceLoc[this.rank-1]+";\n result.w = "+getChannel+";\n }\n }\n ";var sourceLocSetup=this.rank<=4?"sourceLoc = coords +\n "+dtype+"("+destSize.map(function(_,i){return"start["+i+"]"}).join()+");":destSize.map(function(_,i){return sourceLoc[i]+" = "+coords2[i]+" + start["+i+"];"}).join("\n");this.userCode="\n uniform int start["+this.rank+"];\n void main() {\n "+dtype+" coords = getOutputCoords();\n "+dtype+" sourceLoc;\n "+sourceLocSetup+"\n vec4 result = vec4(0.);\n "+upperRow+"\n "+lowerRow+"\n setOutput(result);\n }\n "}SlicePackedProgram2.prototype.getCustomSetupFunc=function(start){var _this=this;if(start.length!==this.rank){throw Error("The rank ("+this.rank+") of the program must match the "+("length of start ("+start.length+")"))}return function(gpgpu,webGLProgram){if(_this.startLoc==null){_this.startLoc=gpgpu.getUniformLocationNoThrow(webGLProgram,"start");if(_this.startLoc==null){return}}gpgpu.gl.uniform1iv(_this.startLoc,start)}};return SlicePackedProgram2}();var StridedSliceProgram=function(){function StridedSliceProgram2(begin,strides,size){this.variableNames=["x"];this.outputShape=size;var rank=size.length;var inputDtype=getCoordsDataType(size.length);var dtype=getCoordsDataType(size.length);var newCoords="";if(rank===1){newCoords="coords * strides + begin"}else{var outputAxis_1=0;newCoords=size.map(function(_,i){outputAxis_1++;return size.length===1?"coords * strides["+i+"] + begin["+i+"]":"coords["+(outputAxis_1-1)+"] * strides["+i+"] + begin["+i+"]"}).join(",")}this.userCode="\n "+inputDtype+" begin = "+inputDtype+"("+begin+");\n "+inputDtype+" strides = "+inputDtype+"("+strides+");\n\n void main() {\n "+dtype+" coords = getOutputCoords();\n setOutput(getX("+newCoords+"));\n }\n "}return StridedSliceProgram2}();var TextureManager=function(){function TextureManager2(gpgpu){this.gpgpu=gpgpu;this.numUsedTextures=0;this.numFreeTextures=0;this._numBytesAllocated=0;this._numBytesFree=0;this.freeTextures={};this.logEnabled=false;this.usedTextures={}}TextureManager2.prototype.acquireTexture=function(shapeRC,usage,isPacked){var physicalTexType=getPhysicalFromLogicalTextureType(usage,isPacked);var shapeKey=getKeyFromTextureShape(shapeRC,physicalTexType,isPacked);if(!(shapeKey in this.freeTextures)){this.freeTextures[shapeKey]=[]}if(!(shapeKey in this.usedTextures)){this.usedTextures[shapeKey]=[]}var texBytes=computeBytes(shapeRC,physicalTexType,this.gpgpu.gl,this.gpgpu.textureConfig,isPacked);if(this.freeTextures[shapeKey].length>0){this.numFreeTextures--;this.numUsedTextures++;this._numBytesFree-=texBytes;this.log();var newTexture_1=this.freeTextures[shapeKey].shift();this.usedTextures[shapeKey].push(newTexture_1);return newTexture_1}var newTexture;if(physicalTexType===PhysicalTextureType.PACKED_2X2_FLOAT32){newTexture=this.gpgpu.createPackedMatrixTexture(shapeRC[0],shapeRC[1])}else if(physicalTexType===PhysicalTextureType.PACKED_2X2_FLOAT16){newTexture=this.gpgpu.createFloat16PackedMatrixTexture(shapeRC[0],shapeRC[1])}else if(physicalTexType===PhysicalTextureType.UNPACKED_FLOAT32){newTexture=this.gpgpu.createFloat32MatrixTexture(shapeRC[0],shapeRC[1])}else if(physicalTexType===PhysicalTextureType.UNPACKED_FLOAT16){newTexture=this.gpgpu.createFloat16MatrixTexture(shapeRC[0],shapeRC[1])}else if(physicalTexType===PhysicalTextureType.PACKED_4X1_UNSIGNED_BYTE){newTexture=this.gpgpu.createUnsignedBytesMatrixTexture(shapeRC[0],shapeRC[1])}this.usedTextures[shapeKey].push(newTexture);this.numUsedTextures++;this._numBytesAllocated+=texBytes;this.log();return newTexture};TextureManager2.prototype.releaseTexture=function(texture,shape,logicalTexType,isPacked){if(this.freeTextures==null){return}var physicalTexType=getPhysicalFromLogicalTextureType(logicalTexType,isPacked);var shapeKey=getKeyFromTextureShape(shape,physicalTexType,isPacked);if(!(shapeKey in this.freeTextures)){this.freeTextures[shapeKey]=[]}var texBytes=computeBytes(shape,physicalTexType,this.gpgpu.gl,this.gpgpu.textureConfig,isPacked);var deleteTexThreshold=tf4.env().get("WEBGL_DELETE_TEXTURE_THRESHOLD");if(deleteTexThreshold!==-1&&this._numBytesAllocated>deleteTexThreshold){this.gpgpu.deleteMatrixTexture(texture);this._numBytesAllocated-=texBytes}else{this.freeTextures[shapeKey].push(texture);this.numFreeTextures++;this._numBytesFree+=texBytes}this.numUsedTextures--;var texList=this.usedTextures[shapeKey];var texIndex=texList.indexOf(texture);if(texIndex<0){throw new Error("Cannot release a texture that was never provided by this texture manager")}texList.splice(texIndex,1);this.log()};TextureManager2.prototype.log=function(){if(!this.logEnabled){return}var total=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+total+")");var freeRatio=this._numBytesFree/this._numBytesAllocated;console.log("Bytes allocated: "+this._numBytesAllocated);console.log("Bytes unused: "+this._numBytesFree+" ("+Math.round(100*freeRatio)+"%)")};Object.defineProperty(TextureManager2.prototype,"numBytesAllocated",{get:function(){return this._numBytesAllocated},enumerable:true,configurable:true});Object.defineProperty(TextureManager2.prototype,"numBytesFree",{get:function(){return this._numBytesFree},enumerable:true,configurable:true});TextureManager2.prototype.getNumUsedTextures=function(){return this.numUsedTextures};TextureManager2.prototype.getNumFreeTextures=function(){return this.numFreeTextures};TextureManager2.prototype.dispose=function(){var _this=this;if(this.freeTextures==null){return}for(var texShape in this.freeTextures){this.freeTextures[texShape].forEach(function(tex){_this.gpgpu.deleteMatrixTexture(tex)})}for(var texShape in this.usedTextures){this.usedTextures[texShape].forEach(function(tex){_this.gpgpu.deleteMatrixTexture(tex)})}this.freeTextures=null;this.usedTextures=null;this.numUsedTextures=0;this.numFreeTextures=0;this._numBytesAllocated=0;this._numBytesFree=0};return TextureManager2}();function numBytesForInternalFormat(gl,internalFormat){var glany=gl;if(internalFormat===glany.R32F){return 4}else if(internalFormat===glany.R16F){return 2}else if(internalFormat===glany.RGBA32F){return 16}else if(internalFormat===gl.RGBA){return 16}else if(internalFormat===glany.RGBA16F){return 8}throw new Error("Unknown internal format "+internalFormat)}function computeBytes(shape,physicalTexType,gl,textureConfig,isPacked){var internalFormat=internalFormatForPhysicalTexType(physicalTexType,textureConfig);var numElements;if(isPacked){var _a=getPackedMatrixTextureShapeWidthHeight(shape[0],shape[1]),packedWidth=_a[0],packedHeight=_a[1];numElements=packedWidth*packedHeight}else{var _b=getUnpackedMatrixTextureShapeWidthHeight(shape[0],shape[1]),width=_b[0],height=_b[1];numElements=width*height}var bytesPerElement=numBytesForInternalFormat(gl,internalFormat);return numElements*bytesPerElement}function internalFormatForPhysicalTexType(physicalTexType,textureConfig){switch(physicalTexType){case PhysicalTextureType.PACKED_2X2_FLOAT32:return getInternalFormatForPackedMatrixTexture(textureConfig);case PhysicalTextureType.PACKED_2X2_FLOAT16:return getInternalFormatForFloat16PackedMatrixTexture(textureConfig);case PhysicalTextureType.UNPACKED_FLOAT32:return getInternalFormatForFloat32MatrixTexture(textureConfig);case PhysicalTextureType.UNPACKED_FLOAT16:return getInternalFormatForFloat16MatrixTexture(textureConfig);case PhysicalTextureType.PACKED_4X1_UNSIGNED_BYTE:return getInternalFormatForUnsignedBytesMatrixTexture(textureConfig);default:throw new Error("Unknown physical texture type "+physicalTexType)}}function getPhysicalTextureForRendering(isPacked){if(tf4.env().getBool("WEBGL_RENDER_FLOAT32_ENABLED")){if(isPacked){return PhysicalTextureType.PACKED_2X2_FLOAT32}return PhysicalTextureType.UNPACKED_FLOAT32}if(isPacked){return PhysicalTextureType.PACKED_2X2_FLOAT16}return PhysicalTextureType.UNPACKED_FLOAT16}function getPhysicalFromLogicalTextureType(logicalTexType,isPacked){if(logicalTexType===TextureUsage.UPLOAD){return PhysicalTextureType.PACKED_2X2_FLOAT32}else if(logicalTexType===TextureUsage.RENDER||logicalTexType==null){return getPhysicalTextureForRendering(isPacked)}else if(logicalTexType===TextureUsage.DOWNLOAD||logicalTexType===TextureUsage.PIXELS){return PhysicalTextureType.PACKED_4X1_UNSIGNED_BYTE}throw new Error("Unknown logical texture type "+logicalTexType)}function getKeyFromTextureShape(shapeRowsCol,physicalTexType,isPacked){return shapeRowsCol[0]+"_"+shapeRowsCol[1]+"_"+physicalTexType+"_"+isPacked}var TileProgram=function(){function TileProgram2(aShape,reps){this.variableNames=["A"];var outputShape=new Array(aShape.length);for(var i=0;i5){throw Error("Tile for rank "+rank+" is not yet supported")}if(rank===1){return"imod(resRC, "+aShape[0]+")"}var currentCoords=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"];var sourceCoords=[];for(var i=0;i= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n";function STEP(alpha){if(alpha===void 0){alpha=0}return CHECK_NAN_SNIPPET$2+("\n return x > 0.0 ? 1.0 : float("+alpha+");\n ")}var NEG="return -x;";var CEIL="return ceil(x);";var FLOOR="return floor(x);";var SIGN="\n if (isnan(x)) { return 0.0; }\n return sign(x);\n";var IS_NAN="return float(isnan(x));";var IS_INF="return float(isinf(x));";var IS_FINITE="return float(!isnan(x) && !isinf(x));";var ROUND="\n // OpenGL ES does not support round function.\n // The algorithm is based on banker's rounding.\n float base = floor(x);\n if ((x - base) < 0.5) {\n return floor(x);\n } else if ((x - base) > 0.5) {\n return ceil(x);\n } else {\n if (mod(base, 2.0) == 0.0) {\n return base;\n } else {\n return base + 1.0;\n }\n }\n";var EXP="return exp(x);";var EXPM1="return exp(x) - 1.0;";var LOG="if (x < 0.0) return NAN;\n return log(x);";var LOG1P="return log(1.0 + x);";var SQRT="return sqrt(x);";var RSQRT="return inversesqrt(x);";var SIGMOID="return 1.0 / (1.0 + exp(-1.0 * x));";var SOFTPLUS="\n float epsilon = 1.1920928955078125e-7;\n float threshold = log(epsilon) + 2.0;\n\n bool too_large = x > -threshold;\n bool too_small = x < threshold;\n\n float result;\n float exp_x = exp(x);\n\n if (too_large){\n result = x;\n }\n else if (too_small){\n result = exp_x;\n }\n else{\n result = log(exp_x + 1.0);\n }\n return result;\n";var ASIN=CHECK_NAN_SNIPPET$2+"\n if (abs(x) > 1.) {\n return NAN;\n }\n return asin(x);\n";var ACOS=CHECK_NAN_SNIPPET$2+"\n if (abs(x) > 1.) {\n return NAN;\n }\n return acos(x);\n";var ATAN=CHECK_NAN_SNIPPET$2+"\n return atan(x);\n";var SINH="\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n";var COSH="\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n";var TANH="\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n";var ASINH=CHECK_NAN_SNIPPET$2+"return log(x + sqrt(x * x + 1.0));";var ACOSH=CHECK_NAN_SNIPPET$2+"\n if (x < 1.0) return NAN;\n return log(x + sqrt(x * x - 1.0));";var ATANH=CHECK_NAN_SNIPPET$2+"\n if ((x < -1.0) || (x > 1.0)) return NAN;\n return (log(1.0 + x) - log(1.0 - x)) / 2.0;";var ERF='\n // Error function is calculated approximately with elementary function.\n // See "Handbook of Mathematical Functions with Formulas,\n // Graphs, and Mathematical Tables", Abramowitz and Stegun.\n float p = '+tf4.backend_util.ERF_P+";\n float a1 = "+tf4.backend_util.ERF_A1+";\n float a2 = "+tf4.backend_util.ERF_A2+";\n float a3 = "+tf4.backend_util.ERF_A3+";\n float a4 = "+tf4.backend_util.ERF_A4+";\n float a5 = "+tf4.backend_util.ERF_A5+";\n\n float sign = sign(x);\n x = abs(x);\n float t = 1.0 / (1.0 + p * x);\n return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));\n";var RECIPROCAL="return 1.0 / x;";var LOGICAL_NOT="return float(!(x >= 1.0));";var CLONE="return x;";var LINEAR$1="return x;";var LOG$1="\n vec4 result = log(x);\n vec4 isNaN = vec4(lessThan(x, vec4(0.0)));\n result.r = isNaN.r == 1.0 ? NAN : result.r;\n result.g = isNaN.g == 1.0 ? NAN : result.g;\n result.b = isNaN.b == 1.0 ? NAN : result.b;\n result.a = isNaN.a == 1.0 ? NAN : result.a;\n\n return result;\n";var RELU$1="\n vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n";var RELU6$1="\n vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n";var ELU$1="\n vec4 result;\n\n result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n return result;\n";var UnaryOpPackedProgram=function(){function UnaryOpPackedProgram2(aShape,opSnippet){this.variableNames=["A"];this.packedInputs=true;this.packedOutput=true;this.outputShape=aShape;this.userCode="\n vec4 unaryOperation(vec4 x) {\n "+opSnippet+"\n }\n\n void main() {\n vec4 x = getAAtOutCoords();\n vec4 y = unaryOperation(x);\n\n setOutput(y);\n }\n "}return UnaryOpPackedProgram2}();var UnpackProgram=function(){function UnpackProgram2(outputShape){this.variableNames=["A"];this.packedInputs=true;this.packedOutput=false;this.outputShape=outputShape;var rank=outputShape.length;var channels=getChannels("rc",rank);var dtype=getCoordsDataType(rank);var sourceCoords=getSourceCoords(rank,channels);var innerDims=channels.slice(-2);var coords2=rank<=1?"rc":"vec2("+innerDims.join(",")+")";this.userCode="\n void main() {\n "+dtype+" rc = getOutputCoords();\n vec4 packedInput = getA("+sourceCoords+");\n\n setOutput(getChannel(packedInput, "+coords2+"));\n }\n "}return UnpackProgram2}();var segment_util=tf4.backend_util.segment_util;var split2=tf4.kernel_impls.split;var tile2=tf4.kernel_impls.tile;var topkImpl=tf4.kernel_impls.topkImpl;var whereImpl=tf4.kernel_impls.whereImpl;var EPSILON_FLOAT32=1e-7;var EPSILON_FLOAT16=1e-4;var binaryCaches={};function getBinaryCache(webGLVersion){if(webGLVersion in binaryCaches){return binaryCaches[webGLVersion]}binaryCaches[webGLVersion]={};return binaryCaches[webGLVersion]}function mapActivationToShaderProgram(activation,packed){if(packed===void 0){packed=false}if(activation==="linear"){if(packed){return LINEAR$1}return LINEAR}else if(activation==="relu"){if(packed){return RELU$1}return RELU}else if(activation==="elu"){if(packed){return ELU$1}return ELU}else if(activation==="relu6"){if(packed){return RELU6$1}return RELU6}else if(activation==="prelu"){if(packed){return PRELU$1}return PRELU}throw new Error("Activation "+activation+" has not been implemented for the WebGL backend.")}var CPU_HANDOFF_SIZE_THRESHOLD=128;var BEFORE_PAGING_CONSTANT=600;function numMBBeforeWarning(){if(tf4.env().global.screen==null){return 1024}return tf4.env().global.screen.height*tf4.env().global.screen.width*window.devicePixelRatio*BEFORE_PAGING_CONSTANT/1024/1024}var MATMUL_SHARED_DIM_THRESHOLD=1e3;var MathBackendWebGL=function(_super){__extends(MathBackendWebGL2,_super);function MathBackendWebGL2(gpgpu){var _this=_super.call(this)||this;_this.pendingRead=new WeakMap;_this.pendingDisposal=new WeakSet;_this.dataRefCount=new WeakMap;_this.numBytesInGPU=0;_this.uploadWaitMs=0;_this.downloadWaitMs=0;_this.warnedAboutMemory=false;_this.warnedAboutCPUBackend=false;_this.pendingDeletes=0;_this.disposed=false;if(!tf4.env().getBool("HAS_WEBGL")){throw new Error("WebGL is not supported on this device")}if(gpgpu==null){var gl=getWebGLContext(tf4.env().getNumber("WEBGL_VERSION"));_this.binaryCache=getBinaryCache(tf4.env().getNumber("WEBGL_VERSION"));_this.gpgpu=new GPGPUContext(gl);_this.canvas=gl.canvas;_this.gpgpuCreatedLocally=true}else{_this.gpgpu=gpgpu;_this.binaryCache={};_this.gpgpuCreatedLocally=false;_this.canvas=gpgpu.gl.canvas}_this.textureManager=new TextureManager(_this.gpgpu);_this.numMBBeforeWarning=numMBBeforeWarning();_this.texData=new tf4.DataStorage(_this,tf4.engine());return _this}MathBackendWebGL2.prototype.numDataIds=function(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes};MathBackendWebGL2.prototype.write=function(values,shape,dtype){if(tf4.env().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||tf4.env().getBool("DEBUG")){this.checkNumericalProblems(values)}if(dtype==="complex64"&&values!=null){throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).")}var dataId={};this.texData.set(dataId,{shape,dtype,values,usage:TextureUsage.UPLOAD,refCount:1,complexParentRefCount:0});return dataId};MathBackendWebGL2.prototype.incRef=function(dataId){var texData=this.texData.get(dataId);texData.refCount++};MathBackendWebGL2.prototype.decRef=function(dataId){if(this.texData.has(dataId)){var texData=this.texData.get(dataId);texData.refCount--}};MathBackendWebGL2.prototype.move=function(dataId,values,shape,dtype){if(tf4.env().getBool("DEBUG")){this.checkNumericalProblems(values)}if(dtype==="complex64"){throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).")}this.texData.set(dataId,{shape,dtype,values,usage:TextureUsage.UPLOAD,refCount:1,complexParentRefCount:0})};MathBackendWebGL2.prototype.disposeIntermediateTensorInfo=function(tensorInfo){var dataId=tensorInfo.dataId;if(this.texData.has(dataId)){var textureData=this.texData.get(dataId);textureData.refCount--;if(textureData.refCount<1){this.disposeData(dataId)}}};MathBackendWebGL2.prototype.readSync=function(dataId){var texData=this.texData.get(dataId);var values=texData.values,dtype=texData.dtype,complexTensorInfos=texData.complexTensorInfos,slice2=texData.slice,shape=texData.shape,isPacked=texData.isPacked;if(slice2!=null){var program=void 0;if(isPacked){program=new UnaryOpPackedProgram(shape,CLONE)}else{program=new UnaryOpProgram(shape,CLONE)}var res=this.runWebGLProgram(program,[{dataId,shape,dtype}],dtype);var data2=this.readSync(res.dataId);this.disposeIntermediateTensorInfo(res);return data2}if(values!=null){return this.convertAndCacheOnCPU(dataId)}if(dtype==="string"){return values}var shouldTimeProgram=this.activeTimers!=null;var start;if(shouldTimeProgram){start=tf4.util.now()}var result;if(dtype==="complex64"){var realValues=this.readSync(complexTensorInfos.real.dataId);var imagValues=this.readSync(complexTensorInfos.imag.dataId);result=tf4.backend_util.mergeRealAndImagArrays(realValues,imagValues)}else{result=this.getValuesFromTexture(dataId)}if(shouldTimeProgram){this.downloadWaitMs+=tf4.util.now()-start}return this.convertAndCacheOnCPU(dataId,result)};MathBackendWebGL2.prototype.read=function(dataId){return __awaiter(this,void 0,void 0,function(){var subscribers_1,texData,values,shape,slice2,dtype,complexTensorInfos,isPacked,program,res,data2,buffer2,tmpDownloadTarget,tmpData,vals,ps,realValues,imagValues,size,dTypeVals,subscribers;var _a;return __generator(this,function(_b){switch(_b.label){case 0:if(this.pendingRead.has(dataId)){subscribers_1=this.pendingRead.get(dataId);return[2,new Promise(function(resolve){return subscribers_1.push(resolve)})]}texData=this.texData.get(dataId);values=texData.values,shape=texData.shape,slice2=texData.slice,dtype=texData.dtype,complexTensorInfos=texData.complexTensorInfos,isPacked=texData.isPacked;if(slice2!=null){program=void 0;if(isPacked){program=new UnaryOpPackedProgram(shape,CLONE)}else{program=new UnaryOpProgram(shape,CLONE)}res=this.runWebGLProgram(program,[{dataId,shape,dtype}],dtype);data2=this.read(res.dataId);this.disposeIntermediateTensorInfo(res);return[2,data2]}if(values!=null){return[2,this.convertAndCacheOnCPU(dataId)]}if(!tf4.env().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&tf4.env().getNumber("WEBGL_VERSION")===2){throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.")}buffer2=null;if(dtype!=="complex64"&&tf4.env().get("WEBGL_BUFFER_SUPPORTED")){tmpDownloadTarget=this.decode(dataId);tmpData=this.texData.get(tmpDownloadTarget.dataId);buffer2=(_a=this.gpgpu).createBufferFromTexture.apply(_a,[tmpData.texture].concat(getDenseTexShape(shape)))}this.pendingRead.set(dataId,[]);if(!(dtype!=="complex64"))return[3,2];return[4,this.gpgpu.createAndWaitForFence()];case 1:_b.sent();_b.label=2;case 2:if(!(dtype==="complex64"))return[3,4];return[4,Promise.all([this.read(complexTensorInfos.real.dataId),this.read(complexTensorInfos.imag.dataId)])];case 3:ps=_b.sent();realValues=ps[0];imagValues=ps[1];vals=tf4.backend_util.mergeRealAndImagArrays(realValues,imagValues);return[3,5];case 4:if(buffer2==null){vals=this.getValuesFromTexture(dataId)}else{size=tf4.util.sizeFromShape(shape);vals=this.gpgpu.downloadFloat32MatrixFromBuffer(buffer2,size)}_b.label=5;case 5:if(tmpDownloadTarget!=null){this.disposeIntermediateTensorInfo(tmpDownloadTarget)}dTypeVals=this.convertAndCacheOnCPU(dataId,vals);subscribers=this.pendingRead.get(dataId);this.pendingRead.delete(dataId);subscribers.forEach(function(resolve){return resolve(dTypeVals)});if(this.pendingDisposal.has(dataId)){this.pendingDisposal.delete(dataId);this.disposeData(dataId);this.pendingDeletes--}return[2,dTypeVals]}})})};MathBackendWebGL2.prototype.checkNumericalProblems=function(values){if(values==null){return}for(var i=0;i0))return[3,2];return[4,Promise.all(flattenedActiveTimerQueries)];case 1:kernelMs_1=_a.sent();res["kernelMs"]=tf4.util.sum(kernelMs_1);res["getExtraProfileInfo"]=function(){return kernelMs_1.map(function(d,i){return{name:flattenedActiveTimerNames[i],ms:d}}).map(function(d){return d.name+": "+d.ms}).join(", ")};return[3,3];case 2:res["kernelMs"]={error:"WebGL query timers are not supported in this environment."};_a.label=3;case 3:this.uploadWaitMs=0;this.downloadWaitMs=0;return[2,res]}})})};MathBackendWebGL2.prototype.memory=function(){return{unreliable:false,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}};MathBackendWebGL2.prototype.startTimer=function(){if(tf4.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){return this.gpgpu.beginQuery()}return{startMs:tf4.util.now(),endMs:null}};MathBackendWebGL2.prototype.endTimer=function(query){if(tf4.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){this.gpgpu.endQuery();return query}query.endMs=tf4.util.now();return query};MathBackendWebGL2.prototype.getQueryTime=function(query){return __awaiter(this,void 0,void 0,function(){var timerQuery;return __generator(this,function(_a){if(tf4.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){return[2,this.gpgpu.waitForQueryAndGetTime(query)]}timerQuery=query;return[2,timerQuery.endMs-timerQuery.startMs]})})};MathBackendWebGL2.prototype.disposeData=function(dataId){if(this.pendingDisposal.has(dataId)){return}if(this.pendingRead.has(dataId)){this.pendingDisposal.add(dataId);this.pendingDeletes++;return}if(!this.texData.has(dataId)){return}if(this.texData.get(dataId).complexParentRefCount>0){this.texData.get(dataId).refCount--;return}this.releaseGPUData(dataId);var complexTensorInfos=this.texData.get(dataId).complexTensorInfos;if(complexTensorInfos!=null){this.texData.get(complexTensorInfos.real.dataId).complexParentRefCount--;this.disposeIntermediateTensorInfo(complexTensorInfos.real);this.texData.get(complexTensorInfos.imag.dataId).complexParentRefCount--;this.disposeIntermediateTensorInfo(complexTensorInfos.imag)}this.texData.delete(dataId)};MathBackendWebGL2.prototype.releaseGPUData=function(dataId){var _a=this.texData.get(dataId),texture=_a.texture,dtype=_a.dtype,texShape=_a.texShape,usage=_a.usage,isPacked=_a.isPacked,slice2=_a.slice;var key=slice2&&slice2.origDataId||dataId;var refCount=this.dataRefCount.get(key);if(refCount>1){this.dataRefCount.set(key,refCount-1)}else{this.dataRefCount.delete(key);if(texture!=null){this.numBytesInGPU-=this.computeBytes(texShape,dtype);this.textureManager.releaseTexture(texture,texShape,usage,isPacked)}}var texData=this.texData.get(dataId);texData.texture=null;texData.texShape=null;texData.isPacked=false;texData.slice=null};MathBackendWebGL2.prototype.getTexture=function(dataId){this.uploadToGPU(dataId);return this.texData.get(dataId).texture};MathBackendWebGL2.prototype.getDataInfo=function(dataId){return this.texData.get(dataId)};MathBackendWebGL2.prototype.getCPUBackend=function(){if(!tf4.env().getBool("WEBGL_CPU_FORWARD")){return null}if(this.cpuBackend==null){this.cpuBackend=tf4.engine().findBackend("cpu")}return this.cpuBackend};MathBackendWebGL2.prototype.shouldExecuteOnCPU=function(inputs,sizeThreshold){var _this=this;if(sizeThreshold===void 0){sizeThreshold=CPU_HANDOFF_SIZE_THRESHOLD}var cpuBackend=this.getCPUBackend();if(!this.warnedAboutCPUBackend&&cpuBackend==null){console.warn("Your application contains ops that are small enough to be executed on the CPU backend, however the CPU backend cannot be found. Consider importing the CPU backend (@tensorflow/tfjs-backend-cpu) for better performance.");this.warnedAboutCPUBackend=true}return cpuBackend!=null&&inputs.every(function(input){return _this.texData.get(input.dataId).texture==null&&tf4.util.sizeFromShape(input.shape)MATMUL_SHARED_DIM_THRESHOLD){if(transposeA){a=tf4.transpose(a,[0,2,1])}if(transposeB){b=tf4.transpose(b,[0,2,1])}var a3D=outerShapeB===1?a:a.as3D(batch,sharedDim,1);var axis=outerShapeB===1?2:1;var b3D=outerShapeB===1?b.as3D(batch,1,sharedDim):b;var product=tf4.mul(a3D,b3D);return product.sum(axis,true)}var dtype=tf4.upcastType(a.dtype,b.dtype);var program=new MatMulPackedProgram(a.shape,b.shape,[batch,outerShapeA,outerShapeB],transposeA,transposeB);return this.compileAndRun(program,[a,b],dtype)};MathBackendWebGL2.prototype.fusedBatchMatMul=function(_a){var a=_a.a,b=_a.b,transposeA=_a.transposeA,transposeB=_a.transposeB,bias=_a.bias,activation=_a.activation,preluActivationWeights=_a.preluActivationWeights;var outerShapeA=transposeA?a.shape[2]:a.shape[1];var outerShapeB=transposeB?b.shape[1]:b.shape[2];var batch=Math.max(a.shape[0],b.shape[0]);var dtype=tf4.upcastType(a.dtype,b.dtype);var hasBias=bias!=null;var hasPreluActivationWeights=preluActivationWeights!=null;var fusedActivation=activation?mapActivationToShaderProgram(activation,true):null;var program=new MatMulPackedProgram(a.shape,b.shape,[batch,outerShapeA,outerShapeB],transposeA,transposeB,hasBias,fusedActivation,hasPreluActivationWeights);var inputs=[a,b];if(bias){inputs.push(bias)}if(preluActivationWeights){inputs.push(preluActivationWeights)}return this.compileAndRun(program,inputs,dtype)};MathBackendWebGL2.prototype.localResponseNormalization4D=function(x,radius,bias,alpha,beta){var program=tf4.env().getBool("WEBGL_PACK_NORMALIZATION")?new LRNPackedProgram(x.shape,radius,bias,alpha,beta):new LRNProgram(x.shape,radius,bias,alpha,beta);return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.LRNGrad=function(dy,inputImage,outputImage,depthRadius,bias,alpha,beta){var program=new LRNGradProgram(inputImage.shape,depthRadius,bias,alpha,beta);return this.compileAndRun(program,[inputImage,outputImage,dy])};MathBackendWebGL2.prototype.tile=function(x,reps){if(x.dtype==="string"){var data2=this.readSync(x.dataId);var decodedData=data2.map(function(d){return tf4.util.decodeString(d)});var buf=tf4.buffer(x.shape,x.dtype,decodedData);return tile2(buf,reps)}var program=new TileProgram(x.shape,reps);return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.pad=function(x,paddings,constantValue){var program=tf4.env().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new PadPackedProgram(x.shape,paddings,constantValue):new PadProgram(x.shape,paddings,constantValue);return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.gather=function(x,indices,axis){var _this=this;var cpuRes=this.tryRunOnCpuOrThrow([x,indices],function(){return _this.cpuBackend.gather(x,indices,axis)});if(cpuRes){return cpuRes}var program=new GatherProgram(x.shape,indices.size,axis);return this.compileAndRun(program,[x,indices])};MathBackendWebGL2.prototype.batchToSpaceND=function(x,blockShape,crops){tf4.util.assert(x.rank<=4,function(){return"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"});var prod=blockShape.reduce(function(a,b){return a*b});var reshaped=tf4.backend_util.getReshaped(x.shape,blockShape,prod);var permuted=tf4.backend_util.getPermuted(reshaped.length,blockShape.length);var reshapedPermuted=tf4.backend_util.getReshapedPermuted(x.shape,blockShape,prod);var sliceBeginCoords=tf4.backend_util.getSliceBeginCoords(crops,blockShape.length);var sliceSize=tf4.backend_util.getSliceSize(reshapedPermuted,crops,blockShape.length);return tf4.transpose(x.reshape(reshaped),permuted).reshape(reshapedPermuted).slice(sliceBeginCoords,sliceSize)};MathBackendWebGL2.prototype.spaceToBatchND=function(x,blockShape,paddings){tf4.util.assert(x.rank<=4,function(){return"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"});var prod=blockShape.reduce(function(a,b){return a*b});var completePaddings=[[0,0]];completePaddings.push.apply(completePaddings,paddings);for(var i=1+blockShape.length;itf4.env().get("WEBGL_MAX_TEXTURES_IN_SHADER")){var midIndex=Math.floor(tensors.length/2);var leftSide=this.addN(tensors.slice(0,midIndex));var rightSide=this.addN(tensors.slice(midIndex));return this.addN([leftSide,rightSide])}var dtype=tensors.map(function(t){return t.dtype}).reduce(function(d1,d2){return tf4.upcastType(d1,d2)});var shapes=tensors.map(function(t){return t.shape});var usePackedOp=tf4.env().getBool("WEBGL_PACK");var program=usePackedOp?new AddNPackedProgram(tensors[0].shape,shapes):new AddNProgram(tensors[0].shape,shapes);return this.compileAndRun(program,tensors,dtype)};MathBackendWebGL2.prototype.pow=function(a,b){var usePackedOp=tf4.env().getBool("WEBGL_PACK_BINARY_OPERATIONS");var program=usePackedOp?new BinaryOpPackedProgram(POW$1,a.shape,b.shape):new BinaryOpProgram(POW,a.shape,b.shape);var dtype=tf4.upcastType(a.dtype,b.dtype);return this.compileAndRun(program,[a,b],dtype)};MathBackendWebGL2.prototype.ceil=function(x){if(this.shouldExecuteOnCPU([x])){var outValues=ceilImplCPU(this.texData.get(x.dataId).values,x.dtype);return this.makeOutput(x.shape,x.dtype,outValues)}if(tf4.env().getBool("WEBGL_PACK_UNARY_OPERATIONS")){return this.packedUnaryOp(x,CEIL,x.dtype)}var program=new UnaryOpProgram(x.shape,CEIL);return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.floor=function(x){if(this.shouldExecuteOnCPU([x])){var outValues=floorImplCPU(this.texData.get(x.dataId).values,x.dtype);return this.makeOutput(x.shape,x.dtype,outValues)}if(tf4.env().getBool("WEBGL_PACK_UNARY_OPERATIONS")){return this.packedUnaryOp(x,FLOOR,x.dtype)}var program=new UnaryOpProgram(x.shape,FLOOR);return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.sign=function(x){var program=new UnaryOpProgram(x.shape,SIGN);return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.isNaN=function(x){var program=new UnaryOpProgram(x.shape,IS_NAN);return this.compileAndRun(program,[x],"bool")};MathBackendWebGL2.prototype.isInf=function(x){var program=new UnaryOpProgram(x.shape,IS_INF);return this.compileAndRun(program,[x],"bool")};MathBackendWebGL2.prototype.isFinite=function(x){var program=new UnaryOpProgram(x.shape,IS_FINITE);return this.compileAndRun(program,[x],"bool")};MathBackendWebGL2.prototype.round=function(x){var program=new UnaryOpProgram(x.shape,ROUND);return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.exp=function(x){if(this.shouldExecuteOnCPU([x])){var outValues=expImplCPU(this.texData.get(x.dataId).values,x.dtype);return this.makeOutput(x.shape,x.dtype,outValues)}if(tf4.env().getBool("WEBGL_PACK_UNARY_OPERATIONS")){return this.packedUnaryOp(x,EXP,x.dtype)}var program=new UnaryOpProgram(x.shape,EXP);return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.expm1=function(x){if(this.shouldExecuteOnCPU([x])){var outValues=expm1ImplCPU(this.texData.get(x.dataId).values,x.dtype);return this.makeOutput(x.shape,x.dtype,outValues)}if(tf4.env().getBool("WEBGL_PACK_UNARY_OPERATIONS")){return this.packedUnaryOp(x,EXPM1,x.dtype)}var program=new UnaryOpProgram(x.shape,EXPM1);return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.softmax=function(logits,dim){var axes=tf4.util.parseAxisParam([dim],logits.shape);var maxLogit=tf4.max(logits,axes);var expandedShape=tf4.backend_util.expandShapeToKeepDim(maxLogit.shape,axes);var a=tf4.sub(logits,maxLogit.reshape(expandedShape));var b=this.exp(a);var sumExp=this.sum(b,axes).reshape(expandedShape);return tf4.div(b,sumExp)};MathBackendWebGL2.prototype.log=function(x){if(this.shouldExecuteOnCPU([x])){var outValues=logImplCPU(this.texData.get(x.dataId).values,x.dtype);return this.makeOutput(x.shape,x.dtype,outValues)}if(tf4.env().getBool("WEBGL_PACK_UNARY_OPERATIONS")){return this.packedUnaryOp(x,LOG$1,x.dtype)}var program=new UnaryOpProgram(x.shape,LOG);return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.log1p=function(x){var program=new UnaryOpProgram(x.shape,LOG1P);return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.sqrt=function(x){var program=new UnaryOpProgram(x.shape,SQRT);return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.rsqrt=function(x){if(this.shouldExecuteOnCPU([x])){var outValues=rsqrtImplCPU(this.texData.get(x.dataId).values,x.dtype);return this.makeOutput(x.shape,x.dtype,outValues)}var program=new UnaryOpProgram(x.shape,RSQRT);return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.reciprocal=function(x){var program=new UnaryOpProgram(x.shape,RECIPROCAL);return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.relu=function(x){var program;if(tf4.env().getBool("WEBGL_PACK")){program=new UnaryOpPackedProgram(x.shape,RELU$1)}else{program=new UnaryOpProgram(x.shape,RELU)}return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.relu6=function(x){var program;if(tf4.env().getBool("WEBGL_PACK")){program=new UnaryOpPackedProgram(x.shape,RELU6$1)}else{program=new UnaryOpProgram(x.shape,RELU6)}return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.prelu=function(x,alpha){var program=tf4.env().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new BinaryOpPackedProgram(PRELU$1,x.shape,alpha.shape):new BinaryOpProgram(PRELU,x.shape,alpha.shape);return this.compileAndRun(program,[x,alpha])};MathBackendWebGL2.prototype.elu=function(x){if(tf4.env().getBool("WEBGL_PACK_UNARY_OPERATIONS")){return this.packedUnaryOp(x,ELU$1,x.dtype)}var program=new UnaryOpProgram(x.shape,ELU);return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.eluDer=function(dy,y){var program=tf4.env().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new BinaryOpPackedProgram(ELU_DER$1,dy.shape,y.shape):new BinaryOpProgram(ELU_DER,dy.shape,y.shape);return this.compileAndRun(program,[dy,y])};MathBackendWebGL2.prototype.selu=function(x){var program=new UnaryOpProgram(x.shape,SELU);return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.clip=function(x,min2,max2){var program;if(tf4.env().getBool("WEBGL_PACK_CLIP")){program=new ClipPackedProgram(x.shape)}else{program=new ClipProgram(x.shape)}var customSetup=program.getCustomSetupFunc(min2,max2);return this.compileAndRun(program,[x],null,customSetup)};MathBackendWebGL2.prototype.abs=function(x){if(this.shouldExecuteOnCPU([x])&&x.dtype!=="complex64"){var outValues=simpleAbsImplCPU(this.texData.get(x.dataId).values);return this.makeOutput(x.shape,x.dtype,outValues)}if(tf4.env().getBool("WEBGL_PACK_UNARY_OPERATIONS")){return this.packedUnaryOp(x,ABS,x.dtype)}var program=new UnaryOpProgram(x.shape,ABS);return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.complexAbs=function(x){var xData=this.texData.get(x.dataId);var program=new ComplexAbsProgram(x.shape);var inputs=[this.makeComplexComponentTensorInfo(x,xData.complexTensorInfos.real),this.makeComplexComponentTensorInfo(x,xData.complexTensorInfos.imag)];return this.compileAndRun(program,inputs)};MathBackendWebGL2.prototype.sigmoid=function(x){var program=new UnaryOpProgram(x.shape,SIGMOID);return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.softplus=function(x){var program=new UnaryOpProgram(x.shape,SOFTPLUS);return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.asin=function(x){var program=new UnaryOpProgram(x.shape,ASIN);return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.acos=function(x){var program=new UnaryOpProgram(x.shape,ACOS);return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.atan=function(x){var program=new UnaryOpProgram(x.shape,ATAN);return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.sinh=function(x){var program=new UnaryOpProgram(x.shape,SINH);return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.cosh=function(x){var program=new UnaryOpProgram(x.shape,COSH);return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.tanh=function(x){var program=new UnaryOpProgram(x.shape,TANH);return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.asinh=function(x){var program=new UnaryOpProgram(x.shape,ASINH);return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.acosh=function(x){var program=new UnaryOpProgram(x.shape,ACOSH);return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.atanh=function(x){var program=new UnaryOpProgram(x.shape,ATANH);return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.erf=function(x){var program=new UnaryOpProgram(x.shape,ERF);return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.step=function(x,alpha){var program=new UnaryOpProgram(x.shape,STEP(alpha));return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.conv2dByMatMul=function(x,filter,convInfo,bias,activation,preluActivationWeights){var xShape=x.shape;var xTexData=this.texData.get(x.dataId);var sharedMatMulDim=convInfo.inChannels;var outerShapeX=xShape[0]*xShape[1]*xShape[2];var outerShapeFilter=convInfo.outChannels;var isChannelsLast=convInfo.dataFormat==="channelsLast";var transposeA=false;var transposeB=false;var batchMatMulWillBeUnpacked=(outerShapeX===1||outerShapeFilter===1)&&sharedMatMulDim>MATMUL_SHARED_DIM_THRESHOLD;var reshapeWillBeExpensive=xShape[2]%2!==0&&!!xTexData.isPacked;if(batchMatMulWillBeUnpacked||!tf4.env().getBool("WEBGL_LAZILY_UNPACK")||!tf4.env().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!reshapeWillBeExpensive){var targetShape_1=isChannelsLast?xShape[0]*xShape[1]*xShape[2]:xShape[0]*xShape[2]*xShape[3];var xReshaped_1=tf4.reshape(x,[1,targetShape_1,convInfo.inChannels]);var filterReshaped_1=tf4.reshape(filter,[1,convInfo.inChannels,convInfo.outChannels]);var result=this.fusedBatchMatMul({a:xReshaped_1,b:filterReshaped_1,transposeA,transposeB,bias,activation,preluActivationWeights});return tf4.reshape(result,convInfo.outShape)}var targetShape=isChannelsLast?xShape[0]*xShape[1]*(xShape[2]+1):xShape[0]*xShape[2]*(xShape[3]+1);var xReshaped={dataId:x.dataId,shape:[1,targetShape,convInfo.inChannels],dtype:x.dtype};var originalXTexDataShape=xTexData.shape;xTexData.shape=xTexData.shape.slice();xTexData.shape[xTexData.shape.length-2]++;tf4.util.assert(isReshapeFree(xTexData.shape,xReshaped.shape),function(){return"packed reshape "+xTexData.shape+" to "+xReshaped.shape+" isn't free"});var filterReshaped=tf4.reshape(filter,[1,convInfo.inChannels,convInfo.outChannels]);var pointwiseConv=this.fusedBatchMatMul({a:xReshaped,b:filterReshaped,transposeA,transposeB,bias,activation,preluActivationWeights});var pointwiseConvTexData=this.texData.get(pointwiseConv.dataId);tf4.util.assert(pointwiseConvTexData.isPacked,function(){return"batchMatMul result is expected to be packed"});xTexData.shape=originalXTexDataShape;pointwiseConvTexData.shape=convInfo.outShape;return tf4.engine().makeTensorFromDataId(pointwiseConv.dataId,convInfo.outShape,pointwiseConv.dtype)};MathBackendWebGL2.prototype.conv2dWithIm2Row=function(x,filter,convInfo,bias,activation,preluActivationWeights){var filterWidth=convInfo.filterWidth,filterHeight=convInfo.filterHeight,inChannels=convInfo.inChannels,outWidth=convInfo.outWidth,outHeight=convInfo.outHeight,dataFormat=convInfo.dataFormat;var isChannelsLast=dataFormat==="channelsLast";var sharedDim=filterWidth*filterHeight*inChannels;var numCols=outHeight*outWidth;var x2ColShape=[sharedDim,numCols];var transposeA=true;var transposeB=false;var xSqueezed=x.squeeze([0]);var w2Row=filter.reshape([1,sharedDim,-1]);var im2ColProgram=new Im2ColPackedProgram(x2ColShape,xSqueezed.shape,convInfo);var im2Col=this.compileAndRun(im2ColProgram,[xSqueezed]).reshape([1,x2ColShape[0],x2ColShape[1]]);var hasBias=bias!=null;var hasPreluActivationWeights=preluActivationWeights!=null;var fusedActivation=activation?mapActivationToShaderProgram(activation,true):null;var matmulProgram=new MatMulPackedProgram(im2Col.shape,w2Row.shape,[1,numCols,convInfo.outChannels],transposeA,transposeB,hasBias,fusedActivation,hasPreluActivationWeights);var inputs=[im2Col,w2Row];if(bias){inputs.push(bias)}if(hasPreluActivationWeights){inputs.push(preluActivationWeights)}var product=this.compileAndRun(matmulProgram,inputs);if(isChannelsLast){return product.reshape([1,outHeight,outWidth,convInfo.outChannels])}else{return product.reshape([1,convInfo.outChannels,outHeight,outWidth])}};MathBackendWebGL2.prototype.fusedConv2d=function(_a){var input=_a.input,filter=_a.filter,convInfo=_a.convInfo,bias=_a.bias,activation=_a.activation,preluActivationWeights=_a.preluActivationWeights;if(convInfo.filterHeight===1&&convInfo.filterWidth===1&&convInfo.dilationHeight===1&&convInfo.dilationWidth===1&&convInfo.strideHeight===1&&convInfo.strideWidth===1&&(convInfo.padInfo.type==="SAME"||convInfo.padInfo.type==="VALID")){return this.conv2dByMatMul(input,filter,convInfo,bias,activation,preluActivationWeights)}if(tf4.env().getBool("WEBGL_CONV_IM2COL")&&input.shape[0]===1){return this.conv2dWithIm2Row(input,filter,convInfo,bias,activation,preluActivationWeights)}var hasBias=bias!=null;var hasPreluActivationWeights=preluActivationWeights!=null;var fusedActivation=activation?mapActivationToShaderProgram(activation,false):null;var program=new Conv2DProgram(convInfo,hasBias,fusedActivation,hasPreluActivationWeights);var inputs=[input,filter];if(bias){inputs.push(bias)}if(preluActivationWeights){inputs.push(preluActivationWeights)}return this.compileAndRun(program,inputs)};MathBackendWebGL2.prototype.conv2d=function(x,filter,convInfo){if(convInfo.filterHeight===1&&convInfo.filterWidth===1&&convInfo.dilationHeight===1&&convInfo.dilationWidth===1&&convInfo.strideHeight===1&&convInfo.strideWidth===1&&(convInfo.padInfo.type==="SAME"||convInfo.padInfo.type==="VALID")){return this.conv2dByMatMul(x,filter,convInfo)}if(tf4.env().getBool("WEBGL_CONV_IM2COL")&&x.shape[0]===1){return this.conv2dWithIm2Row(x,filter,convInfo)}var program=new Conv2DProgram(convInfo);return this.compileAndRun(program,[x,filter])};MathBackendWebGL2.prototype.conv2dDerInput=function(dy,filter,convInfo){var program=new Conv2DDerInputProgram(convInfo);return this.compileAndRun(program,[dy,filter])};MathBackendWebGL2.prototype.conv2dDerFilter=function(x,dy,convInfo){var program=new Conv2DDerFilterProgram(convInfo);return this.compileAndRun(program,[x,dy])};MathBackendWebGL2.prototype.fusedDepthwiseConv2D=function(_a){var input=_a.input,filter=_a.filter,convInfo=_a.convInfo,bias=_a.bias,activation=_a.activation,preluActivationWeights=_a.preluActivationWeights;var shouldPackDepthwiseConv=tf4.env().getBool("WEBGL_PACK_DEPTHWISECONV")&&convInfo.strideWidth<=2&&convInfo.outChannels/convInfo.inChannels===1;var fusedActivation=activation?mapActivationToShaderProgram(activation,shouldPackDepthwiseConv):null;var inputs=[input,filter];var hasBias=bias!=null;var hasPreluActivationWeights=preluActivationWeights!=null;if(hasBias){inputs.push(bias)}if(hasPreluActivationWeights){inputs.push(preluActivationWeights)}var program;if(shouldPackDepthwiseConv){program=new DepthwiseConvPacked2DProgram(convInfo,hasBias,fusedActivation,hasPreluActivationWeights);return this.compileAndRun(program,inputs)}program=new DepthwiseConv2DProgram(convInfo,hasBias,fusedActivation,hasPreluActivationWeights);return this.compileAndRun(program,inputs)};MathBackendWebGL2.prototype.depthwiseConv2D=function(x,filter,convInfo){var program;if(tf4.env().getBool("WEBGL_PACK_DEPTHWISECONV")&&convInfo.strideWidth<=2&&convInfo.outChannels/convInfo.inChannels===1){program=new DepthwiseConvPacked2DProgram(convInfo);return this.compileAndRun(program,[x,filter])}program=new DepthwiseConv2DProgram(convInfo);return this.compileAndRun(program,[x,filter])};MathBackendWebGL2.prototype.depthwiseConv2DDerInput=function(dy,filter,convInfo){var program=new DepthwiseConv2DDerInputProgram(convInfo);return this.compileAndRun(program,[dy,filter])};MathBackendWebGL2.prototype.depthwiseConv2DDerFilter=function(x,dy,convInfo){var program=new DepthwiseConv2DDerFilterProgram(convInfo);return this.compileAndRun(program,[x,dy])};MathBackendWebGL2.prototype.conv3d=function(x,filter,convInfo){var program=new Conv3DProgram(convInfo);return this.compileAndRun(program,[x,filter])};MathBackendWebGL2.prototype.conv3dDerInput=function(dy,filter,convInfo){var program=new Conv3DDerInputProgram(convInfo);return this.compileAndRun(program,[dy,filter])};MathBackendWebGL2.prototype.conv3dDerFilter=function(x,dy,convInfo){var program=new Conv3DDerFilterProgram(convInfo);return this.compileAndRun(program,[x,dy])};MathBackendWebGL2.prototype.unstack=function(x,axis){var num=x.shape[axis];var outShape=new Array(x.rank-1);var outIndex=0;for(var i=0;i1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+blockSize});var batchSize=x.shape[0];var inputHeight=dataFormat==="NHWC"?x.shape[1]:x.shape[2];var inputWidth=dataFormat==="NHWC"?x.shape[2]:x.shape[3];var inputDepth=dataFormat==="NHWC"?x.shape[3]:x.shape[1];var outputHeight=inputHeight*blockSize;var outputWidth=inputWidth*blockSize;var outputDepth=inputDepth/(blockSize*blockSize);var outputShape=dataFormat==="NHWC"?[batchSize,outputHeight,outputWidth,outputDepth]:[batchSize,outputDepth,outputHeight,outputWidth];var program=new DepthToSpaceProgram(outputShape,blockSize,dataFormat);return this.compileAndRun(program,[x])};MathBackendWebGL2.prototype.split=function(x,sizeSplits,axis){return split2(x,sizeSplits,axis)};MathBackendWebGL2.prototype.scatterND=function(indices,updates,shape){var _a=tf4.backend_util.calculateShapes(updates,indices,shape),sliceRank=_a.sliceRank,numUpdates=_a.numUpdates,sliceSize=_a.sliceSize,strides=_a.strides,outputSize=_a.outputSize;var flattenShape=[outputSize/sliceSize,sliceSize];var flattenIndices=indices.reshape([numUpdates,sliceRank]);var flattenX=updates.reshape([numUpdates,sliceSize]);if(outputSize===0){return tf4.backend_util.reshapeTensor(tf4.tensor([]),shape)}var defaultValue=tf4.scalar(0);var program=new ScatterProgram(numUpdates,sliceRank,flattenIndices.rank,flattenX.rank,strides,flattenShape);var res=this.compileAndRun(program,[flattenX,flattenIndices,defaultValue]);return res.reshape(shape)};MathBackendWebGL2.prototype.sparseToDense=function(sparseIndices,sparseValues,outputShape,defaultValue){var _a=tf4.backend_util.calculateShapes(sparseValues,sparseIndices,outputShape),sliceRank=_a.sliceRank,numUpdates=_a.numUpdates,strides=_a.strides,outputSize=_a.outputSize;var sumDupeIndices=false;var program=new ScatterProgram(numUpdates,sliceRank,sparseIndices.rank,sparseValues.rank,strides,[outputSize,1],sumDupeIndices);var res=this.compileAndRun(program,[sparseValues,sparseIndices,defaultValue]);return res.reshape(outputShape)};MathBackendWebGL2.prototype.gatherND=function(x,indices){var indicesShape=indices.shape;var sliceRank=indicesShape[indicesShape.length-1];var _a=tf4.backend_util.prepareAndValidate(x,indices),resultShape=_a[0],numSlices=_a[1],sliceSize=_a[2],strides=_a[3];var flattenIndices=indices.reshape([numSlices,sliceRank]);var flattenX=x.reshape([x.size/sliceSize,sliceSize]);var program=new GatherNDProgram(sliceRank,strides,[numSlices,sliceSize]);var res=this.compileAndRun(program,[flattenX,flattenIndices]);return res.reshape(resultShape)};MathBackendWebGL2.prototype.fill=function(shape,value,dtype){dtype=dtype||tf4.util.inferDtype(value);if(dtype==="string"){var values=tf4.util.getArrayFromDType(dtype,tf4.util.sizeFromShape(shape));values.fill(value);return tf4.engine().makeTensor(values,shape,dtype,this)}else{var program=new FillProgram(shape,value);var customSetup=program.getCustomSetupFunc(value);return this.compileAndRun(program,[],dtype,customSetup)}};MathBackendWebGL2.prototype.onesLike=function(x){if(x.dtype==="string"){throw new Error("onesLike is not supported under string dtype")}else{return this.fill(x.shape,1,x.dtype)}};MathBackendWebGL2.prototype.zerosLike=function(x){return this.fill(x.shape,x.dtype==="string"?"":0,x.dtype)};MathBackendWebGL2.prototype.linspace=function(start,stop,num){return tf4.backend_util.linspaceImpl(start,stop,num)};MathBackendWebGL2.prototype.makeTensorInfo=function(shape,dtype,values){var dataId=this.write(values,shape,dtype);this.texData.get(dataId).usage=null;return{dataId,shape,dtype}};MathBackendWebGL2.prototype.makeOutput=function(shape,dtype,values){var dataId=this.makeTensorInfo(shape,dtype,values).dataId;return tf4.engine().makeTensorFromDataId(dataId,shape,dtype,this)};MathBackendWebGL2.prototype.unpackTensor=function(input){var program=new UnpackProgram(input.shape);return this.runWebGLProgram(program,[input],input.dtype)};MathBackendWebGL2.prototype.packTensor=function(input){var program=new PackProgram(input.shape);var preventEagerUnpackingOutput=true;return this.runWebGLProgram(program,[input],input.dtype,null,preventEagerUnpackingOutput)};MathBackendWebGL2.prototype.packedReshape=function(input,afterShape){var input3DShape=[getBatchDim(input.shape)].concat(getRowsCols(input.shape));var input3D={dtype:input.dtype,shape:input3DShape,dataId:input.dataId};var afterShapeAs3D=[getBatchDim(afterShape)].concat(getRowsCols(afterShape));var program=new ReshapePackedProgram(afterShapeAs3D,input3DShape);var preventEagerUnpackingOfOutput=true;var output=this.runWebGLProgram(program,[input3D],input.dtype,null,preventEagerUnpackingOfOutput);return{dataId:output.dataId,shape:afterShape,dtype:output.dtype}};MathBackendWebGL2.prototype.decode=function(dataId){var texData=this.texData.get(dataId);var isPacked=texData.isPacked,shape=texData.shape,dtype=texData.dtype;var shapeAs3D=getShapeAs3D(shape);var program;if(isPacked){program=new DecodeMatrixPackedProgram(shapeAs3D)}else{program=new DecodeMatrixProgram(shapeAs3D)}var preventEagerUnpackingOfOutput=true;var out=this.runWebGLProgram(program,[{shape:shapeAs3D,dtype,dataId}],dtype,null,preventEagerUnpackingOfOutput);return{dtype,shape,dataId:out.dataId}};MathBackendWebGL2.prototype.runWebGLProgram=function(program,inputs,outputDtype,customSetup,preventEagerUnpackingOfOutput){var _this=this;if(preventEagerUnpackingOfOutput===void 0){preventEagerUnpackingOfOutput=false}var output=this.makeTensorInfo(program.outputShape,outputDtype);var outData=this.texData.get(output.dataId);if(program.packedOutput){outData.isPacked=true}if(program.outPackingScheme===PackingScheme.DENSE){var texelShape=getDenseTexShape(program.outputShape);outData.texShape=texelShape.map(function(d){return d*2})}if(program.outTexUsage!=null){outData.usage=program.outTexUsage}if(tf4.util.sizeFromShape(output.shape)===0){outData.values=tf4.util.getTypedArrayFromDType(output.dtype,0);return output}var dataToDispose=[];var inputsData=inputs.map(function(input){if(input.dtype==="complex64"){throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.")}var texData=_this.texData.get(input.dataId);if(texData.texture==null){if(!program.packedInputs&&tf4.util.sizeFromShape(input.shape)<=tf4.env().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM")){return{shape:input.shape,texData:null,isUniform:true,uniformValues:texData.values}}if(program.packedInputs){texData.isPacked=true;texData.shape=input.shape}}else if(!!texData.isPacked!==!!program.packedInputs){input=texData.isPacked?_this.unpackTensor(input):_this.packTensor(input);dataToDispose.push(input);texData=_this.texData.get(input.dataId)}else if(texData.isPacked&&!isReshapeFree(texData.shape,input.shape)){var savedInput=input;var targetShape=input.shape;input.shape=texData.shape;input=_this.packedReshape(input,targetShape);dataToDispose.push(input);texData=_this.texData.get(input.dataId);savedInput.shape=targetShape}_this.uploadToGPU(input.dataId);return{shape:input.shape,texData,isUniform:false}});this.uploadToGPU(output.dataId);var outputData={shape:output.shape,texData:outData,isUniform:false};var key=makeShaderKey(program,inputsData,outputData);var binary=this.getAndSaveBinary(key,function(){return compileProgram(_this.gpgpu,program,inputsData,outputData)});var shouldTimeProgram=this.activeTimers!=null;var query;if(shouldTimeProgram){query=this.startTimer()}runProgram(this.gpgpu,binary,inputsData,outputData,customSetup);dataToDispose.forEach(function(info){return _this.disposeIntermediateTensorInfo(info)});if(shouldTimeProgram){query=this.endTimer(query);this.activeTimers.push({name:program.constructor.name,query:this.getQueryTime(query)})}if(!tf4.env().getBool("WEBGL_LAZILY_UNPACK")&&outData.isPacked&&preventEagerUnpackingOfOutput===false){var unpacked=this.unpackTensor(output);this.disposeIntermediateTensorInfo(output);return unpacked}return output};MathBackendWebGL2.prototype.compileAndRun=function(program,inputs,outputDtype,customSetup,preventEagerUnpackingOfOutput){if(preventEagerUnpackingOfOutput===void 0){preventEagerUnpackingOfOutput=false}outputDtype=outputDtype||inputs[0].dtype;var outInfo=this.runWebGLProgram(program,inputs,outputDtype,customSetup,preventEagerUnpackingOfOutput);return tf4.engine().makeTensorFromDataId(outInfo.dataId,outInfo.shape,outInfo.dtype)};MathBackendWebGL2.prototype.getAndSaveBinary=function(key,getBinary){if(!(key in this.binaryCache)){this.binaryCache[key]=getBinary()}return this.binaryCache[key]};MathBackendWebGL2.prototype.getTextureManager=function(){return this.textureManager};MathBackendWebGL2.prototype.dispose=function(){var _this=this;if(this.disposed){return}if(!tf4.env().getBool("IS_TEST")){var allKeys=Object.keys(this.binaryCache);allKeys.forEach(function(key){_this.gpgpu.deleteProgram(_this.binaryCache[key].webGLProgram);delete _this.binaryCache[key]})}this.textureManager.dispose();if(this.canvas!=null&&(typeof HTMLCanvasElement!=="undefined"&&this.canvas instanceof HTMLCanvasElement)){this.canvas.remove()}else{this.canvas=null}if(this.gpgpuCreatedLocally){this.gpgpu.program=null;this.gpgpu.dispose()}this.disposed=true};MathBackendWebGL2.prototype.floatPrecision=function(){var _this=this;if(this.floatPrecisionValue==null){this.floatPrecisionValue=tf4.tidy(function(){if(!tf4.env().get("WEBGL_RENDER_FLOAT32_ENABLED")){var debugFlag=tf4.env().getBool("DEBUG");tf4.env().set("DEBUG",false);var underflowCheckValue=_this.abs(tf4.scalar(1e-8)).dataSync()[0];tf4.env().set("DEBUG",debugFlag);if(underflowCheckValue>0){return 32}}return 16})}return this.floatPrecisionValue};MathBackendWebGL2.prototype.epsilon=function(){return this.floatPrecision()===32?EPSILON_FLOAT32:EPSILON_FLOAT16};MathBackendWebGL2.prototype.uploadToGPU=function(dataId){var _a;var texData=this.texData.get(dataId);var shape=texData.shape,dtype=texData.dtype,values=texData.values,texture=texData.texture,usage=texData.usage,isPacked=texData.isPacked;if(texture!=null){return}var shouldTimeProgram=this.activeTimers!=null;var start;if(shouldTimeProgram){start=tf4.util.now()}var texShape=texData.texShape;if(texShape==null){texShape=getTextureShapeFromLogicalShape(shape,isPacked);texData.texShape=texShape}if(values!=null){var shapeAs3D=getShapeAs3D(shape);var program=void 0;var width=texShape[1],height=texShape[0];var isByteArray=values instanceof Uint8Array;if(isPacked){_a=getPackedMatrixTextureShapeWidthHeight(texShape[0],texShape[1]),width=_a[0],height=_a[1];program=new EncodeMatrixPackedProgram(shapeAs3D,[height,width],isByteArray)}else{program=new EncodeMatrixProgram(shapeAs3D,[height,width],isByteArray)}var tempDenseInputHandle=this.makeTensorInfo([height,width],dtype);if(isByteArray){this.texData.get(tempDenseInputHandle.dataId).usage=TextureUsage.PIXELS}else{this.texData.get(tempDenseInputHandle.dataId).usage=TextureUsage.UPLOAD}this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(tempDenseInputHandle.dataId),width,height,values);var preventEagerUnpacking=true;var encodedOutputTarget=this.runWebGLProgram(program,[tempDenseInputHandle],dtype,null,preventEagerUnpacking);var outputTexData=this.texData.get(encodedOutputTarget.dataId);texData.texture=outputTexData.texture;texData.texShape=outputTexData.texShape;texData.isPacked=outputTexData.isPacked;texData.usage=outputTexData.usage;this.disposeIntermediateTensorInfo(tempDenseInputHandle);this.texData.delete(encodedOutputTarget.dataId);texData.values=null;if(shouldTimeProgram){this.uploadWaitMs+=tf4.util.now()-start}}else{var newTexture=this.acquireTexture(texShape,usage,dtype,isPacked);texData.texture=newTexture}};MathBackendWebGL2.prototype.convertAndCacheOnCPU=function(dataId,float32Values){var texData=this.texData.get(dataId);var dtype=texData.dtype;this.releaseGPUData(dataId);if(float32Values!=null){texData.values=float32ToTypedArray(float32Values,dtype)}return texData.values};MathBackendWebGL2.prototype.acquireTexture=function(texShape,texType,dtype,isPacked){this.numBytesInGPU+=this.computeBytes(texShape,dtype);if(!this.warnedAboutMemory&&this.numBytesInGPU>this.numMBBeforeWarning*1024*1024){var mb=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=true;console.warn("High memory usage in GPU: "+mb+" MB, most likely due to a memory leak")}return this.textureManager.acquireTexture(texShape,texType,isPacked)};MathBackendWebGL2.prototype.computeBytes=function(shape,dtype){return shape[0]*shape[1]*tf4.util.bytesPerElement(dtype)};MathBackendWebGL2.prototype.tryRunOnCpuOrThrow=function(inputs,fn){if(this.shouldExecuteOnCPU(inputs)){try{return fn()}catch(e){if(tf4.env().getBool("IS_TEST")){throw new Error("CPU forwarding failed")}}}return null};return MathBackendWebGL2}(tf4.KernelBackend);function float32ToTypedArray(a,dtype){if(dtype==="float32"||dtype==="complex64"){return a}else if(dtype==="int32"||dtype==="bool"){var result=dtype==="int32"?new Int32Array(a.length):new Uint8Array(a.length);for(var i=0;i= "+offsets[i-1]+") {\n return getChannel(\n getT"+i+"("+shiftedChannels(channels,channel,shift_1)+"),\n vec2("+shiftedChannels(lastChannels,channel,shift_1)+"));\n }"}var lastIndex=offsets.length;var shift=offsets[offsets.length-1];getValueSnippet+="\n return getChannel(\n getT"+lastIndex+"("+shiftedChannels(channels,channel,shift)+"),\n vec2("+shiftedChannels(lastChannels,channel,shift)+"));";this.userCode="\n float getValue("+channels.map(function(x){return"int "+x})+") {\n "+getValueSnippet+"\n }\n\n void main() {\n "+dtype+" coords = getOutputCoords();\n vec4 result = vec4(getValue("+coords2+"), 0., 0., 0.);\n\n "+coords2[rank-1]+" = "+coords2[rank-1]+" + 1;\n if ("+coords2[rank-1]+" < "+shape[rank-1]+") {\n result.g = getValue("+coords2+");\n }\n\n "+coords2[rank-2]+" = "+coords2[rank-2]+" + 1;\n if ("+coords2[rank-2]+" < "+shape[rank-2]+") {\n result.a = getValue("+coords2+");\n }\n\n "+coords2[rank-1]+" = "+coords2[rank-1]+" - 1;\n if ("+coords2[rank-2]+" < "+shape[rank-2]+" &&\n "+coords2[rank-1]+" < "+shape[rank-1]+") {\n result.b = getValue("+coords2+");\n }\n setOutput(result);\n }\n "}return ConcatPackedProgram2}();function shiftedChannels(channels,channel,shift){var channelIdx=channels.indexOf(channel);var res=channels.map(function(c,idx){if(idx===channelIdx){return c+" - "+shift}else{return c}});return res.join()}function imag(args){var inputs=args.inputs,backend=args.backend;var input=inputs.input;var inputData=backend.texData.get(input.dataId);return identity2({inputs:{x:inputData.complexTensorInfos.imag},backend})}var imagConfig={kernelName:tf4.Imag,backendName:"webgl",kernelFunc:imag};function packedReshape(input,afterShape,backend){var input3DShape=[getBatchDim(input.shape)].concat(getRowsCols(input.shape));var input3D={dtype:input.dtype,shape:input3DShape,dataId:input.dataId};var afterShapeAs3D=[getBatchDim(afterShape)].concat(getRowsCols(afterShape));var program=new ReshapePackedProgram(afterShapeAs3D,input3DShape);var preventEagerUnpackingOfOutput=true;var output=backend.runWebGLProgram(program,[input3D],input.dtype,null,preventEagerUnpackingOfOutput);return{dataId:output.dataId,shape:afterShape,dtype:output.dtype}}function reshape2(args){var inputs=args.inputs,backend=args.backend,attrs=args.attrs;var x=inputs.x;var shape=attrs.shape;var webglBackend=backend;var xSize=tf4.util.sizeFromShape(x.shape);var $shape=tf4.util.inferFromImplicitShape(shape,xSize);var $xSize=tf4.util.sizeFromShape($shape);tf4.util.assert(xSize===$xSize,function(){return"The new shape ("+$shape+") has "+$xSize+" elements and the old "+("shape ("+x.shape+") has "+xSize+" elements. The new shape and old ")+"shape must have the same number of elements."});var xTexData=webglBackend.texData.get(x.dataId);if(xTexData.isPacked&&!isReshapeFree(x.shape,$shape)&&!(xTexData.texture!==null&&isReshapeFree(xTexData.shape,$shape))){return packedReshape(x,$shape,webglBackend)}webglBackend.incRef(x.dataId);return{dataId:x.dataId,shape:$shape,dtype:x.dtype}}var reshapeConfig2={kernelName:tf4.Reshape,backendName:"webgl",kernelFunc:reshape2};function concatImpl(inputs,axis,backend){var dtype=inputs[0].dtype;if(dtype==="complex64"){var reals=inputs.map(function(t){return real({inputs:{input:t},backend})});var imags=inputs.map(function(t){return imag({inputs:{input:t},backend})});var realConcated=concatImpl(reals,axis,backend);var imagConcated=concatImpl(imags,axis,backend);var result_1=complex({inputs:{real:realConcated,imag:imagConcated},backend});reals.forEach(function(r){return backend.disposeIntermediateTensorInfo(r)});imags.forEach(function(i){return backend.disposeIntermediateTensorInfo(i)});backend.disposeIntermediateTensorInfo(realConcated);backend.disposeIntermediateTensorInfo(imagConcated);return result_1}if(inputs.length>tf4.env().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){var midIndex=Math.floor(inputs.length/2);var leftSide=concatImpl(inputs.slice(0,midIndex),axis,backend);var rightSide=concatImpl(inputs.slice(midIndex),axis,backend);var result_2=concatImpl([leftSide,rightSide],axis,backend);backend.disposeIntermediateTensorInfo(leftSide);backend.disposeIntermediateTensorInfo(rightSide);return result_2}if(tf4.env().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&inputs[0].shape.length>1){var program_1=new ConcatPackedProgram(inputs.map(function(t){return t.shape}),axis);return backend.runWebGLProgram(program_1,inputs,dtype)}var outShape=tf4.backend_util.computeOutShape(inputs.map(function(t){return t.shape}),axis);var tensors2D=inputs.map(function(x){return reshape2({inputs:{x},attrs:{shape:[-1,tf4.util.sizeFromShape(x.shape.slice(axis))]},backend})});var program=new ConcatProgram(tensors2D.map(function(t){return t.shape}));var result=backend.runWebGLProgram(program,tensors2D,dtype);tensors2D.forEach(function(r){return backend.disposeIntermediateTensorInfo(r)});var reshapedResult=reshape2({inputs:{x:result},attrs:{shape:outShape},backend});backend.disposeIntermediateTensorInfo(result);return reshapedResult}function concat2(args){var inputs=args.inputs,backend=args.backend,attrs=args.attrs;var axis=attrs.axis;var $axis=tf4.util.parseAxisParam(axis,inputs[0].shape)[0];var outShape=tf4.backend_util.computeOutShape(inputs.map(function(t){return t.shape}),$axis);if(tf4.util.sizeFromShape(outShape)===0){return backend.makeTensorInfo(outShape,inputs[0].dtype,[])}var $inputs=inputs.filter(function(t){return tf4.util.sizeFromShape(t.shape)>0});if($inputs.length===1){return $inputs[0]}var shapes=$inputs.map(function(t){return t.shape});tf4.backend_util.assertParamsConsistent(shapes,$axis);return concatImpl($inputs,$axis,backend)}var concatConfig2={kernelName:tf4.Concat,backendName:"webgl",kernelFunc:concat2};var COS=CHECK_NAN_SNIPPET_UNARY+"\n return cos(x);\n";var cos=unaryKernelFunc(COS);var cosConfig2={kernelName:tf4.Cos,backendName:"webgl",kernelFunc:cos};var DIV="\nif (a == b) {\n return 1.0;\n};\nreturn a / b;";var DIV_PACKED="\n // vec4 one = vec4(equal(a, b));\n // return one + (vec4(1.0) - one) * a / b;\n vec4 result = a / b;\n if(a.x == b.x) {\n result.x = 1.;\n }\n if(a.y == b.y) {\n result.y = 1.;\n }\n if(a.z == b.z) {\n result.z = 1.;\n }\n if(a.w == b.w) {\n result.w = 1.;\n }\n\n return result;\n";var div=binaryKernelFunc({opSnippet:DIV,packedOpSnippet:DIV_PACKED,checkOutOfBounds:true});var divConfig2={kernelName:tf4.Div,backendName:"webgl",kernelFunc:div};var FFTProgram=function(){function FFTProgram2(component,inputShape,inverse){this.variableNames=["real","imag"];var innerDim=inputShape[1];this.outputShape=inputShape;var exponentMultiplierSnippet=inverse?"2.0 * "+Math.PI:"-2.0 * "+Math.PI;var resultDenominator=inverse?innerDim+".0":"1.0";var opString;if(component==="real"){opString="return real * expR - imag * expI;"}else if(component==="imag"){opString="return real * expI + imag * expR;"}else{throw new Error('FFT component must be either "real" or "imag", got '+component+".")}this.userCode="\n const float exponentMultiplier = "+exponentMultiplierSnippet+";\n\n float unaryOpComplex(float real, float expR, float imag, float expI) {\n "+opString+"\n }\n\n float mulMatDFT(int batch, int index) {\n float indexRatio = float(index) / float("+innerDim+");\n float exponentMultiplierTimesIndexRatio =\n exponentMultiplier * indexRatio;\n\n float result = 0.0;\n\n for (int i = 0; i < "+innerDim+"; i++) {\n // x = (-2|2 * PI / N) * index * i;\n float x = exponentMultiplierTimesIndexRatio * float(i);\n float expR = cos(x);\n float expI = sin(x);\n float real = getReal(batch, i);\n float imag = getImag(batch, i);\n\n result +=\n unaryOpComplex(real, expR, imag, expI) / "+resultDenominator+";\n }\n\n return result;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n setOutput(mulMatDFT(coords[0], coords[1]));\n }\n "}return FFTProgram2}();function fftImpl(x,inverse,backend){var xData=backend.texData.get(x.dataId);var inputSize=tf4.util.sizeFromShape(x.shape);var innerDimensionSize=x.shape[x.shape.length-1];var batch=inputSize/innerDimensionSize;var input2D=reshape2({inputs:{x},backend,attrs:{shape:[batch,innerDimensionSize]}});var xShape=input2D.shape;var realProgram=new FFTProgram("real",xShape,inverse);var imagProgram=new FFTProgram("imag",xShape,inverse);var inputs=[{dataId:xData.complexTensorInfos.real.dataId,dtype:xData.complexTensorInfos.real.dtype,shape:xShape},{dataId:xData.complexTensorInfos.imag.dataId,dtype:xData.complexTensorInfos.imag.dtype,shape:xShape}];var realPart=backend.runWebGLProgram(realProgram,inputs,"float32");var imagPart=backend.runWebGLProgram(imagProgram,inputs,"float32");var complexOutput=complex({inputs:{real:realPart,imag:imagPart},backend});backend.disposeIntermediateTensorInfo(realPart);backend.disposeIntermediateTensorInfo(imagPart);var complexOutputReshaped=reshape2({inputs:{x:complexOutput},backend,attrs:{shape:x.shape}});backend.disposeIntermediateTensorInfo(complexOutputReshaped);return complexOutputReshaped}function fft(args){var inputs=args.inputs,backend=args.backend;var input=inputs.input;return fftImpl(input,false,backend)}var fftConfig={kernelName:tf4.FFT,backendName:"webgl",kernelFunc:fft};var FlipLeftRightProgram=function(){function FlipLeftRightProgram2(imageShape){this.variableNames=["Image"];this.outputShape=[];var imageWidth=imageShape[2];this.outputShape=imageShape;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int x = coords[2];\n\n int coordX = "+imageWidth+" - x;\n float outputValue;\n if(coordX >= 0 && coordX < "+imageWidth+") {\n outputValue = getImage(coords[0], coords[1], coordX, coords[3]);\n } else {\n outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);\n }\n setOutput(outputValue);\n }\n "}return FlipLeftRightProgram2}();var flipLeftRightConfig2={kernelName:tf4.FlipLeftRight,backendName:"webgl",kernelFunc:function(_a){var inputs=_a.inputs,backend=_a.backend;var image2=inputs.image;var webglBackend=backend;var program=new FlipLeftRightProgram(image2.shape);var output=webglBackend.runWebGLProgram(program,[image2],image2.dtype);return output}};var FromPixelsProgram=function(){function FromPixelsProgram2(outputShape){this.variableNames=["A"];var glsl=getGlslDifferences();var height=outputShape[0],width=outputShape[1];this.outputShape=outputShape;this.userCode="\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+width+".0, "+height+".0);\n\n vec4 values = "+glsl.texture2D+"(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n setOutput(floor(value * 255.0 + 0.5));\n }\n "}return FromPixelsProgram2}();var FromPixelsPackedProgram=function(){function FromPixelsPackedProgram2(outputShape){this.variableNames=["A"];this.packedInputs=false;this.packedOutput=true;var glsl=getGlslDifferences();var height=outputShape[0],width=outputShape[1];this.outputShape=outputShape;this.userCode="\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n\n vec4 result = vec4(0.);\n\n for(int row=0; row<=1; row++) {\n for(int col=0; col<=1; col++) {\n texC = coords[1] + row;\n depth = coords[2] + col;\n\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+width+".0, "+height+".0);\n vec4 values = "+glsl.texture2D+"(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n result[row * 2 + col] = floor(value * 255.0 + 0.5);\n }\n }\n\n "+glsl.output+" = result;\n }\n "}return FromPixelsPackedProgram2}();var fromPixelsConfig={kernelName:tf4.FromPixels,backendName:"webgl",kernelFunc:fromPixels};var fromPixels2DContext;function fromPixels(args){var inputs=args.inputs,backend=args.backend,attrs=args.attrs;var pixels=inputs.pixels;var numChannels=attrs.numChannels;var isVideo=typeof HTMLVideoElement!=="undefined"&&pixels instanceof HTMLVideoElement;var isImage=typeof HTMLImageElement!=="undefined"&&pixels instanceof HTMLImageElement;var _a=isVideo?[pixels.videoWidth,pixels.videoHeight]:[pixels.width,pixels.height],width=_a[0],height=_a[1];var texShape=[height,width];var outShape=[height,width,numChannels];if(isImage||isVideo){if(fromPixels2DContext==null){fromPixels2DContext=document.createElement("canvas").getContext("2d")}fromPixels2DContext.canvas.width=width;fromPixels2DContext.canvas.height=height;fromPixels2DContext.drawImage(pixels,0,0,width,height);pixels=fromPixels2DContext.canvas}var tempPixelHandle=backend.makeTensorInfo(texShape,"int32");backend.texData.get(tempPixelHandle.dataId).usage=TextureUsage.PIXELS;backend.gpgpu.uploadPixelDataToTexture(backend.getTexture(tempPixelHandle.dataId),pixels);var program=tf4.env().getBool("WEBGL_PACK")?new FromPixelsPackedProgram(outShape):new FromPixelsProgram(outShape);var res=backend.runWebGLProgram(program,[tempPixelHandle],"int32");backend.disposeData(tempPixelHandle.dataId);return res}function ifft(args){var inputs=args.inputs,backend=args.backend;var input=inputs.input;return fftImpl(input,true,backend)}var ifftConfig={kernelName:tf4.IFFT,backendName:"webgl",kernelFunc:ifft};var MeanProgram=function(){function MeanProgram2(reduceInfo,divisor){this.variableNames=["x"];var windowSize=reduceInfo.windowSize,batchSize=reduceInfo.batchSize,inSize=reduceInfo.inSize,outSize=reduceInfo.outSize;this.outputShape=[batchSize,outSize];var windowSizeNearestVec4=Math.floor(windowSize/4)*4;var windowSizeVec4Remainder=windowSize%4;var updateSnippet="sumValue += dot(values, ones);";if(divisor!=null){var denominator=1/divisor;updateSnippet="sumValue += dot(values * "+(tf4.util.isInt(denominator)?denominator.toPrecision(2):denominator)+", ones);"}var checkOutOfBounds="";if(inSize%windowSize>0){checkOutOfBounds="\n if (inIdx < 0 || inIdx >= "+inSize+") {\n return 0.0;\n }\n "}this.userCode="\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n "+checkOutOfBounds+"\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+windowSize+";\n\n float sumValue = 0.0;\n\n for (int i = 0; i < "+windowSizeNearestVec4+"; i += 4) {\n int inIdx = inOffset + i;\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n "+updateSnippet+"\n }\n\n int inIdx = inOffset + "+windowSizeNearestVec4+";\n if ("+(windowSizeVec4Remainder===1)+") {\n vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);\n\n "+updateSnippet+"\n } else if ("+(windowSizeVec4Remainder===2)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1), 0.0, 0.0);\n\n "+updateSnippet+"\n } else if ("+(windowSizeVec4Remainder===3)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2), 0.0);\n\n "+updateSnippet+"\n }\n setOutput(sumValue);\n }\n "}return MeanProgram2}();function getReductionStages(inShape){var stages=[];while(stages.length===0||stages[stages.length-1].outSize!==1){var outSize=stages.length?stages[stages.length-1].outSize:inShape[1];var windowSize=tf4.backend_util.computeOptimalWindowSize(outSize);stages.push({inSize:outSize,windowSize,outSize:Math.ceil(outSize/windowSize)})}return stages}function reduce(x,dtype,reductionType,backend){var reductionStages=getReductionStages(x.shape);var result=x;for(var i=0;i6){throw Error("Transpose for rank "+rank+" is not yet supported")}var originalOrder=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"];var switchedCoords=new Array(rank);for(var i=0;i6){throw Error("Packed transpose for rank "+this.rank+" is not yet supported.")}var dtype=getCoordsDataType(this.rank);var outputOrder=getVecChannels("rc",this.rank);var switchedOrder=new Array(this.rank);for(var i=0;i= end) {\n outC = (end - 1) * 2 - outC + "+offset+";\n }\n setOutput(getX(outC - start));\n }\n ";return}this.userCode="\n "+dtype+" start = "+dtype+"("+start+");\n "+dtype+" end = "+dtype+"("+end+");\n\n void main() {\n "+dtype+" outC = getOutputCoords();\n for (int i = 0; i < "+rank+"; i++) {\n if (outC[i] < start[i]) {\n outC[i] = start[i] * 2 - outC[i] - "+offset+";\n } else if(outC[i] >= end[i]) {\n outC[i] = (end[i] - 1) * 2 - outC[i] + "+offset+";\n }\n }\n "+dtype+" coords = outC - start;\n setOutput(getX("+unpackedCoords+"));\n }\n "}return MirrorPadProgram2}();var MirrorPadPackedProgram=function(){function MirrorPadPackedProgram2(xShape,paddings,mode){this.variableNames=["x"];this.packedInputs=true;this.packedOutput=true;this.outputShape=paddings.map(function(p,i){return p[0]+xShape[i]+p[1]});var rank=xShape.length;var dtype=getCoordsDataType(rank);var start=paddings.map(function(p){return p[0]}).join(",");var end=paddings.map(function(p,i){return p[0]+xShape[i]}).join(",");var coords2=getChannels("rc",rank);var source=getChannels("source",rank);var cLimit=coords2[rank-1]+" < "+this.outputShape[rank-1];var innerDims=rank===1?"source":"vec2("+source.slice(-2).join()+")";var offset=mode==="reflect"?0:1;var mainLoop="";if(rank===1){var padSetup="\n "+dtype+" source = rc;\n if (source < start) {\n source = start * 2 - source - "+offset+";\n } else if (source >= end) {\n source = (end - 1) * 2 - source + "+offset+";\n }\n source -= start;\n ";mainLoop="\n "+dtype+" rc = outputLoc;\n "+padSetup+"\n result[0] = getChannel(getX("+source.join()+"), "+innerDims+");\n "+coords2[rank-1]+" += 1;\n if("+cLimit+") {\n "+padSetup+"\n result[1] = getChannel(getX("+source.join()+"), "+innerDims+");\n }\n "}else{var padSetup="\n "+dtype+" source = rc;\n "+dtype+" lt = "+dtype+"(lessThan(source, start));\n "+dtype+" gte = "+dtype+"(greaterThanEqual(source, end));\n "+dtype+" orig = 1 - (lt + gte);\n source = orig * source +\n lt * (start * 2 - source - "+offset+") +\n gte * ((end - 1) * 2 - source + "+offset+");\n source -= start;\n ";mainLoop="\n "+dtype+" rc = outputLoc;\n "+padSetup+"\n result[0] = getChannel(getX("+source.join()+"), "+innerDims+");\n "+coords2[rank-1]+" += 1;\n if("+cLimit+") {\n "+padSetup+"\n result[1] = getChannel(getX("+source.join()+"), "+innerDims+");\n }\n rc = outputLoc;\n "+coords2[rank-2]+" += 1;\n if("+coords2[rank-2]+" < "+this.outputShape[rank-2]+") {\n "+padSetup+"\n result[2] = getChannel(getX("+source.join()+"), "+innerDims+");\n "+coords2[rank-1]+" += 1;\n if("+cLimit+") {\n "+padSetup+"\n result[3] = getChannel(getX("+source.join()+"), "+innerDims+");\n }\n }\n "}this.userCode="\n const "+dtype+" start = "+dtype+"("+start+");\n const "+dtype+" end = "+dtype+"("+end+");\n\n void main() {\n "+dtype+" outputLoc = getOutputCoords();\n vec4 result = vec4(0.);\n "+mainLoop+"\n setOutput(result);\n }\n "}return MirrorPadPackedProgram2}();var mirrorPadKernelFunc=function(_a){var inputs=_a.inputs,backend=_a.backend,attrs=_a.attrs;var x=inputs.x;var paddings=attrs.paddings,mode=attrs.mode;var program=tf4.env().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new MirrorPadPackedProgram(x.shape,paddings,mode):new MirrorPadProgram(x.shape,paddings,mode);var output=backend.runWebGLProgram(program,[x],x.dtype);return output};var mirrorPadConfig={kernelName:tf4.MirrorPad,backendName:"webgl",kernelFunc:mirrorPadKernelFunc};var COMPLEX_MULTIPLY={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"};var BinaryOpComplexProgram=function(){function BinaryOpComplexProgram2(op,aShape,bShape){this.variableNames=["AReal","AImag","BReal","BImag"];this.outputShape=tf4.backend_util.assertAndGetBroadcastShape(aShape,bShape);this.userCode="\n float binaryOpComplex(\n float areal, float aimag, float breal, float bimag) {\n "+op+"\n }\n\n void main() {\n float areal = getARealAtOutCoords();\n float aimag = getAImagAtOutCoords();\n float breal = getBRealAtOutCoords();\n float bimag = getBImagAtOutCoords();\n setOutput(binaryOpComplex(areal, aimag, breal, bimag));\n }\n "}return BinaryOpComplexProgram2}();var MUL="return a * b;";function multiply(args){var inputs=args.inputs,backend=args.backend;var a=inputs.a,b=inputs.b;var dtype=tf4.backend_util.upcastType(a.dtype,b.dtype);if(a.dtype==="complex64"){var aData=backend.texData.get(a.dataId);var bData=backend.texData.get(b.dataId);var realProgram=new BinaryOpComplexProgram(COMPLEX_MULTIPLY.REAL,a.shape,b.shape);var imagProgram=new BinaryOpComplexProgram(COMPLEX_MULTIPLY.IMAG,a.shape,b.shape);var inputs_1=[{dataId:aData.complexTensorInfos.real.dataId,dtype:aData.complexTensorInfos.real.dtype,shape:a.shape},{dataId:aData.complexTensorInfos.imag.dataId,dtype:aData.complexTensorInfos.imag.dtype,shape:a.shape},{dataId:bData.complexTensorInfos.real.dataId,dtype:bData.complexTensorInfos.real.dtype,shape:b.shape},{dataId:bData.complexTensorInfos.imag.dataId,dtype:bData.complexTensorInfos.imag.dtype,shape:b.shape}];var realPart=backend.runWebGLProgram(realProgram,inputs_1,"float32");var imagPart=backend.runWebGLProgram(imagProgram,inputs_1,"float32");var complexOutput=complex({inputs:{real:realPart,imag:imagPart},backend});backend.disposeIntermediateTensorInfo(realPart);backend.disposeIntermediateTensorInfo(imagPart);return complexOutput}if(backend.shouldExecuteOnCPU([a,b])){var aData=backend.texData.get(a.dataId);var bData=backend.texData.get(b.dataId);var _a=multiplyImplCPU(a.shape,b.shape,aData.values,bData.values,dtype),outValues=_a[0],outShape=_a[1];var out=backend.makeTensorInfo(outShape,dtype);var outData=backend.texData.get(out.dataId);outData.values=outValues;return out}var program;if(tf4.env().getBool("WEBGL_PACK_BINARY_OPERATIONS")){program=new BinaryOpPackedProgram(MUL,a.shape,b.shape)}else{program=new BinaryOpProgram(MUL,a.shape,b.shape)}return backend.runWebGLProgram(program,[a,b],dtype)}var multiplyConfig2={kernelName:tf4.Multiply,backendName:"webgl",kernelFunc:multiply};var nonMaxSuppressionV3Config2={kernelName:tf4.NonMaxSuppressionV3,backendName:"webgl",kernelFunc:function(_a){var inputs=_a.inputs,backend=_a.backend,attrs=_a.attrs;tf4.backend_util.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");var _b=inputs,boxes=_b.boxes,scores=_b.scores;var _c=attrs,maxOutputSize=_c.maxOutputSize,iouThreshold=_c.iouThreshold,scoreThreshold=_c.scoreThreshold;var gpuBackend=backend;var boxesVals=gpuBackend.readSync(boxes.dataId);var scoresVals=gpuBackend.readSync(scores.dataId);var maxOutputSizeVal=maxOutputSize;var iouThresholdVal=iouThreshold;var scoreThresholdVal=scoreThreshold;return tf4.kernel_impls.nonMaxSuppressionV3Impl(boxesVals,scoresVals,maxOutputSizeVal,iouThresholdVal,scoreThresholdVal)}};var nonMaxSuppressionV4Impl=tf4.kernel_impls.nonMaxSuppressionV4Impl;var nonMaxSuppressionV4Config2={kernelName:tf4.NonMaxSuppressionV4,backendName:"webgl",kernelFunc:function(_a){var inputs=_a.inputs,backend=_a.backend,attrs=_a.attrs;tf4.backend_util.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");var _b=inputs,boxes=_b.boxes,scores=_b.scores;var _c=attrs,maxOutputSize=_c.maxOutputSize,iouThreshold=_c.iouThreshold,scoreThreshold=_c.scoreThreshold,padToMaxOutputSize=_c.padToMaxOutputSize;var gpuBackend=backend;var boxesVals=gpuBackend.readSync(boxes.dataId);var scoresVals=gpuBackend.readSync(scores.dataId);var _d=nonMaxSuppressionV4Impl(boxesVals,scoresVals,maxOutputSize,iouThreshold,scoreThreshold,padToMaxOutputSize),selectedIndices=_d.selectedIndices,validOutputs=_d.validOutputs;return[selectedIndices,validOutputs]}};var nonMaxSuppressionV5Impl=tf4.kernel_impls.nonMaxSuppressionV5Impl;var nonMaxSuppressionV5Config2={kernelName:tf4.NonMaxSuppressionV5,backendName:"webgl",kernelFunc:function(_a){var inputs=_a.inputs,backend=_a.backend,attrs=_a.attrs;tf4.backend_util.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");var _b=inputs,boxes=_b.boxes,scores=_b.scores;var _c=attrs,maxOutputSize=_c.maxOutputSize,iouThreshold=_c.iouThreshold,scoreThreshold=_c.scoreThreshold,softNmsSigma=_c.softNmsSigma;var gpuBackend=backend;var boxesVals=gpuBackend.readSync(boxes.dataId);var scoresVals=gpuBackend.readSync(scores.dataId);var maxOutputSizeVal=maxOutputSize;var iouThresholdVal=iouThreshold;var scoreThresholdVal=scoreThreshold;var softNmsSigmaVal=softNmsSigma;var _d=nonMaxSuppressionV5Impl(boxesVals,scoresVals,maxOutputSizeVal,iouThresholdVal,scoreThresholdVal,softNmsSigmaVal),selectedIndices=_d.selectedIndices,selectedScores=_d.selectedScores;return[selectedIndices,selectedScores]}};var RotateProgram=function(){function RotateProgram2(imageShape,radians,fillValue,center){this.variableNames=["Image"];this.outputShape=[];var imageHeight=imageShape[1];var imageWidth=imageShape[2];var sinFactor=Math.sin(radians).toFixed(3);var cosFactor=Math.cos(radians).toFixed(3);this.outputShape=imageShape;var _a=tf4.backend_util.getImageCenter(center,imageHeight,imageWidth),centerX=_a[0],centerY=_a[1];var centerXString=centerX.toFixed(3);var centerYString=centerY.toFixed(3);var fillSnippet="";if(typeof fillValue==="number"){fillSnippet="float outputValue = "+fillValue.toFixed(2)+";"}else{fillSnippet="\n vec3 fill = vec3("+fillValue.join(",")+");\n float outputValue = fill[coords[3]];"}this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int x = coords[2];\n int y = coords[1];\n float coordXFloat = (float(x) - "+centerXString+") * "+cosFactor+" - (float(y) - "+centerYString+") * "+sinFactor+";\n float coordYFloat = (float(x) - "+centerXString+") * "+sinFactor+" + (float(y) - "+centerYString+") * "+cosFactor+";\n int coordX = int(round(coordXFloat + "+centerXString+"));\n int coordY = int(round(coordYFloat + "+centerYString+"));\n "+fillSnippet+"\n if(coordX >= 0 && coordX < "+imageWidth+" && coordY >= 0 && coordY < "+imageHeight+") {\n outputValue = getImage(coords[0], coordY, coordX, coords[3]);\n }\n setOutput(outputValue);\n }\n "}return RotateProgram2}();var rotateWithOffsetConfig2={kernelName:tf4.RotateWithOffset,backendName:"webgl",kernelFunc:function(_a){var inputs=_a.inputs,attrs=_a.attrs,backend=_a.backend;var image2=inputs.image;var _b=attrs,radians=_b.radians,fillValue=_b.fillValue,center=_b.center;var webglBackend=backend;var program=new RotateProgram(image2.shape,radians,fillValue,center);var output=webglBackend.runWebGLProgram(program,[image2],image2.dtype);return output}};var SIN=CHECK_NAN_SNIPPET_UNARY+"\n return sin(x);\n";var sin=unaryKernelFunc(SIN);var sinConfig2={kernelName:tf4.Sin,backendName:"webgl",kernelFunc:sin};var SQUARE="return x * x;";var square=unaryKernelFunc(SQUARE);var squareConfig2={kernelName:tf4.Square,backendName:"webgl",kernelFunc:square};var SQUARED_DIFFERENCE="return (a - b) * (a - b);";var squaredDifference=binaryKernelFunc({opSnippet:SQUARED_DIFFERENCE,packedOpSnippet:SQUARED_DIFFERENCE});var squaredDifferenceConfig2={kernelName:tf4.SquaredDifference,backendName:"webgl",kernelFunc:squaredDifference};var SUB="return a - b;";var subKernelFunc=binaryKernelFunc({opSnippet:SUB,packedOpSnippet:SUB,supportsComplex:true,cpuKernelImpl:subImplCPU});var subConfig2={kernelName:tf4.Sub,backendName:"webgl",kernelFunc:subKernelFunc};var TAN="return tan(x);";var tan=unaryKernelFunc(TAN);var tanConfig={kernelName:tf4.Tan,backendName:"webgl",kernelFunc:tan};var transposeConfig2={kernelName:tf4.Transpose,backendName:"webgl",kernelFunc:function(_a){var inputs=_a.inputs,attrs=_a.attrs,backend=_a.backend;var x=inputs.x;var perm=attrs.perm;var webglBackend=backend;var xRank=x.shape.length;var newShape=new Array(xRank);for(var i=0;i{__export(exports2,{data:()=>data2,version:()=>version5});__exportStar(exports2,__toModule(require_tf_core_node()));__exportStar(exports2,__toModule(require_tf_layers_node()));__exportStar(exports2,__toModule(require_tf_converter_node()));const data2=__toModule(require_tf_data_node());const tfjs_core86=__toModule(require_tf_core_node());const tfjs_backend_cpu2=__toModule(require_tf_backend_cpu_node());const tfjs_backend_webgl2=__toModule(require_tf_backend_webgl_node());const tfjs_data=__toModule(require_tf_data_node());const tfjs_layers=__toModule(require_tf_layers_node());const tfjs_converter=__toModule(require_tf_converter_node());const version5={"tfjs-core":tfjs_core86.version_core,"tfjs-backend-cpu":tfjs_backend_cpu2.version_cpu,"tfjs-backend-webgl":tfjs_backend_webgl2.version_webgl,"tfjs-data":tfjs_data.version_data,"tfjs-layers":tfjs_layers.version_layers,"tfjs-converter":tfjs_converter.version_converter,tfjs:version}});var require_tfjs_backend_wasm_threaded_simd=__commonJS((exports2,module2)=>{var WasmBackendModuleThreadedSimd=function(){var _scriptDir=typeof document!=="undefined"&&document.currentScript?document.currentScript.src:void 0;if(typeof __filename!=="undefined")_scriptDir=_scriptDir||__filename;return function(WasmBackendModuleThreadedSimd2){WasmBackendModuleThreadedSimd2=WasmBackendModuleThreadedSimd2||{};function GROWABLE_HEAP_I8(){if(wasmMemory.buffer!=buffer2){updateGlobalBufferAndViews(wasmMemory.buffer)}return HEAP8}function GROWABLE_HEAP_U8(){if(wasmMemory.buffer!=buffer2){updateGlobalBufferAndViews(wasmMemory.buffer)}return HEAPU8}function GROWABLE_HEAP_I32(){if(wasmMemory.buffer!=buffer2){updateGlobalBufferAndViews(wasmMemory.buffer)}return HEAP32}function GROWABLE_HEAP_U32(){if(wasmMemory.buffer!=buffer2){updateGlobalBufferAndViews(wasmMemory.buffer)}return HEAPU32}function GROWABLE_HEAP_F64(){if(wasmMemory.buffer!=buffer2){updateGlobalBufferAndViews(wasmMemory.buffer)}return HEAPF64}var Module=typeof WasmBackendModuleThreadedSimd2!=="undefined"?WasmBackendModuleThreadedSimd2:{};var moduleOverrides={};var key;for(key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var arguments_=[];var thisProgram="./this.program";var quit_=function(status,toThrow){throw toThrow};var ENVIRONMENT_IS_WEB=false;var ENVIRONMENT_IS_WORKER=false;var ENVIRONMENT_IS_NODE=false;var ENVIRONMENT_IS_SHELL=false;ENVIRONMENT_IS_WEB=typeof window==="object";ENVIRONMENT_IS_WORKER=typeof importScripts==="function";ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string";ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;var ENVIRONMENT_IS_PTHREAD=Module["ENVIRONMENT_IS_PTHREAD"]||false;if(ENVIRONMENT_IS_PTHREAD){buffer2=Module["buffer"];DYNAMIC_BASE=Module["DYNAMIC_BASE"];DYNAMICTOP_PTR=Module["DYNAMICTOP_PTR"]}var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary,setWindowTitle;var nodeFS;var nodePath;if(ENVIRONMENT_IS_NODE){if(ENVIRONMENT_IS_WORKER){scriptDirectory=require("path").dirname(scriptDirectory)+"/"}else{scriptDirectory=__dirname+"/"}read_=function shell_read(filename,binary){if(!nodeFS)nodeFS=require("fs");if(!nodePath)nodePath=require("path");filename=nodePath["normalize"](filename);return nodeFS["readFileSync"](filename,binary?null:"utf8")};readBinary=function readBinary2(filename){var ret=read_(filename,true);if(!ret.buffer){ret=new Uint8Array(ret)}assert(ret.buffer);return ret};if(process["argv"].length>1){thisProgram=process["argv"][1].replace(/\\/g,"/")}arguments_=process["argv"].slice(2);process["on"]("uncaughtException",function(ex){if(!(ex instanceof ExitStatus)){throw ex}});process["on"]("unhandledRejection",abort);quit_=function(status){process["exit"](status)};Module["inspect"]=function(){return"[Emscripten Module object]"};var nodeWorkerThreads;try{nodeWorkerThreads=require("worker_threads")}catch(e){console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?');throw e}Worker=nodeWorkerThreads.Worker}else if(ENVIRONMENT_IS_SHELL){if(typeof read!="undefined"){read_=function shell_read(f){return read(f)}}readBinary=function readBinary2(f){var data2;if(typeof readbuffer==="function"){return new Uint8Array(readbuffer(f))}data2=read(f,"binary");assert(typeof data2==="object");return data2};if(typeof scriptArgs!="undefined"){arguments_=scriptArgs}else if(typeof arguments!="undefined"){arguments_=arguments}if(typeof quit==="function"){quit_=function(status){quit(status)}}if(typeof print!=="undefined"){if(typeof console==="undefined")console={};console.log=print;console.warn=console.error=typeof printErr!=="undefined"?printErr:print}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptDir){scriptDirectory=_scriptDir}if(scriptDirectory.indexOf("blob:")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.lastIndexOf("/")+1)}else{scriptDirectory=""}if(ENVIRONMENT_IS_NODE){read_=function shell_read(filename,binary){if(!nodeFS)nodeFS=require("fs");if(!nodePath)nodePath=require("path");filename=nodePath["normalize"](filename);return nodeFS["readFileSync"](filename,binary?null:"utf8")};readBinary=function readBinary2(filename){var ret=read_(filename,true);if(!ret.buffer){ret=new Uint8Array(ret)}assert(ret.buffer);return ret}}else{read_=function shell_read(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText};if(ENVIRONMENT_IS_WORKER){readBinary=function readBinary2(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=function readAsync2(url,onload,onerror){var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=function xhr_onload(){if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()};xhr.onerror=onerror;xhr.send(null)}}setWindowTitle=function(title){document.title=title}}else{}if(ENVIRONMENT_IS_NODE){if(typeof performance==="undefined"){performance=require("perf_hooks").performance}}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.warn.bind(console);for(key in moduleOverrides){if(moduleOverrides.hasOwnProperty(key)){Module[key]=moduleOverrides[key]}}moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];var Atomics_load=Atomics.load;var Atomics_store=Atomics.store;var Atomics_compareExchange=Atomics.compareExchange;var wasmBinary;if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];var noExitRuntime;if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(typeof WebAssembly!=="object"){err("no native wasm support detected")}var wasmMemory;var wasmTable=new WebAssembly.Table({initial:165,maximum:165+0,element:"anyfunc"});var wasmModule;var threadInfoStruct=0;var selfThreadId=0;var ABORT=false;var EXITSTATUS=0;function assert(condition,text){if(!condition){abort("Assertion failed: "+text)}}function getCFunc(ident){var func=Module["_"+ident];assert(func,"Cannot call unknown function "+ident+", make sure it is exported");return func}function ccall(ident,returnType,argTypes,args,opts){var toC={string:function(str){var ret2=0;if(str!==null&&str!==void 0&&str!==0){var len=(str.length<<2)+1;ret2=stackAlloc(len);stringToUTF8(str,ret2,len)}return ret2},array:function(arr){var ret2=stackAlloc(arr.length);writeArrayToMemory(arr,ret2);return ret2}};function convertReturnValue(ret2){if(returnType==="string")return UTF8ToString(ret2);if(returnType==="boolean")return Boolean(ret2);return ret2}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i=endIdx)){var u0=heap[idx++];if(!u0)return str;if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heap[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heap[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heap[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str}function UTF8ToString(ptr,maxBytesToRead){return ptr?UTF8ArrayToString(GROWABLE_HEAP_U8(),ptr,maxBytesToRead):""}function stringToUTF8Array(str,heap,outIdx,maxBytesToWrite){if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx}function stringToUTF8(str,outPtr,maxBytesToWrite){return stringToUTF8Array(str,GROWABLE_HEAP_U8(),outPtr,maxBytesToWrite)}function lengthBytesUTF8(str){var len=0;for(var i=0;i=55296&&u<=57343)u=65536+((u&1023)<<10)|str.charCodeAt(++i)&1023;if(u<=127)++len;else if(u<=2047)len+=2;else if(u<=65535)len+=3;else len+=4}return len}function writeArrayToMemory(array,buffer3){GROWABLE_HEAP_I8().set(array,buffer3)}var WASM_PAGE_SIZE=65536;function alignUp(x,multiple){if(x%multiple>0){x+=multiple-x%multiple}return x}var buffer2,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateGlobalBufferAndViews(buf){buffer2=buf;Module["HEAP8"]=HEAP8=new Int8Array(buf);Module["HEAP16"]=HEAP16=new Int16Array(buf);Module["HEAP32"]=HEAP32=new Int32Array(buf);Module["HEAPU8"]=HEAPU8=new Uint8Array(buf);Module["HEAPU16"]=HEAPU16=new Uint16Array(buf);Module["HEAPU32"]=HEAPU32=new Uint32Array(buf);Module["HEAPF32"]=HEAPF32=new Float32Array(buf);Module["HEAPF64"]=HEAPF64=new Float64Array(buf)}var STACK_BASE=5256384,STACKTOP=STACK_BASE,STACK_MAX=13504,DYNAMIC_BASE=5256384,DYNAMICTOP_PTR=12576;if(ENVIRONMENT_IS_PTHREAD){}var INITIAL_INITIAL_MEMORY=Module["INITIAL_MEMORY"]||16777216;if(ENVIRONMENT_IS_PTHREAD){wasmMemory=Module["wasmMemory"];buffer2=Module["buffer"]}else{if(Module["wasmMemory"]){wasmMemory=Module["wasmMemory"]}else{wasmMemory=new WebAssembly.Memory({initial:INITIAL_INITIAL_MEMORY/WASM_PAGE_SIZE,maximum:2147483648/WASM_PAGE_SIZE,shared:true});if(!(wasmMemory.buffer instanceof SharedArrayBuffer)){err("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag");if(ENVIRONMENT_IS_NODE){console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)")}throw Error("bad memory")}}}if(wasmMemory){buffer2=wasmMemory.buffer}INITIAL_INITIAL_MEMORY=buffer2.byteLength;updateGlobalBufferAndViews(buffer2);if(!ENVIRONMENT_IS_PTHREAD){GROWABLE_HEAP_I32()[DYNAMICTOP_PTR>>2]=DYNAMIC_BASE}function callRuntimeCallbacks(callbacks){while(callbacks.length>0){var callback=callbacks.shift();if(typeof callback=="function"){callback(Module);continue}var func=callback.func;if(typeof func==="number"){if(callback.arg===void 0){Module["dynCall_v"](func)}else{Module["dynCall_vi"](func,callback.arg)}}else{func(callback.arg===void 0?null:callback.arg)}}}var __ATPRERUN__=[];var __ATINIT__=[];var __ATMAIN__=[];var __ATEXIT__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;if(ENVIRONMENT_IS_PTHREAD)runtimeInitialized=true;function preRun(){if(ENVIRONMENT_IS_PTHREAD)return;if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;callRuntimeCallbacks(__ATINIT__)}function preMain(){if(ENVIRONMENT_IS_PTHREAD)return;callRuntimeCallbacks(__ATMAIN__)}function postRun(){if(ENVIRONMENT_IS_PTHREAD)return;if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var Math_ceil=Math.ceil;var Math_floor=Math.floor;var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function addRunDependency(id){assert(!ENVIRONMENT_IS_PTHREAD,"addRunDependency cannot be used in a pthread worker");runDependencies++;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}}function removeRunDependency(id){runDependencies--;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}Module["preloadedImages"]={};Module["preloadedAudios"]={};function abort(what){if(Module["onAbort"]){Module["onAbort"](what)}if(ENVIRONMENT_IS_PTHREAD)console.error("Pthread aborting at "+new Error().stack);what+="";out(what);err(what);ABORT=true;EXITSTATUS=1;what="abort("+what+"). Build with -s ASSERTIONS=1 for more info.";throw new WebAssembly.RuntimeError(what)}function hasPrefix(str,prefix){return String.prototype.startsWith?str.startsWith(prefix):str.indexOf(prefix)===0}var dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(filename){return hasPrefix(filename,dataURIPrefix)}var fileURIPrefix="file://";function isFileURI(filename){return hasPrefix(filename,fileURIPrefix)}var wasmBinaryFile="tfjs-backend-wasm-threaded-simd.wasm";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}function getBinary(){try{if(wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(wasmBinaryFile)}else{throw"both async and sync fetching of the wasm failed"}}catch(err2){abort(err2)}}function getBinaryPromise(){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)&&typeof fetch==="function"&&!isFileURI(wasmBinaryFile)){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){if(!response["ok"]){throw"failed to load wasm binary file at '"+wasmBinaryFile+"'"}return response["arrayBuffer"]()}).catch(function(){return getBinary()})}return new Promise(function(resolve,reject){resolve(getBinary())})}function createWasm(){var info={a:asmLibraryArg};function receiveInstance(instance,module3){var exports4=instance.exports;Module["asm"]=exports4;wasmModule=module3;if(!ENVIRONMENT_IS_PTHREAD){var numWorkersToLoad=PThread.unusedWorkers.length;PThread.unusedWorkers.forEach(function(w){PThread.loadWasmModuleToWorker(w,function(){if(!--numWorkersToLoad)removeRunDependency("wasm-instantiate")})})}}if(!ENVIRONMENT_IS_PTHREAD){addRunDependency("wasm-instantiate")}function receiveInstantiatedSource(output){receiveInstance(output["instance"],output["module"])}function instantiateArrayBuffer(receiver){return getBinaryPromise().then(function(binary){return WebAssembly.instantiate(binary,info)}).then(receiver,function(reason){err("failed to asynchronously prepare wasm: "+reason);abort(reason)})}function instantiateAsync(){if(!wasmBinary&&typeof WebAssembly.instantiateStreaming==="function"&&!isDataURI(wasmBinaryFile)&&!isFileURI(wasmBinaryFile)&&typeof fetch==="function"){fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){var result=WebAssembly.instantiateStreaming(response,info);return result.then(receiveInstantiatedSource,function(reason){err("wasm streaming compile failed: "+reason);err("falling back to ArrayBuffer instantiation");instantiateArrayBuffer(receiveInstantiatedSource)})})}else{return instantiateArrayBuffer(receiveInstantiatedSource)}}if(Module["instantiateWasm"]){try{var exports3=Module["instantiateWasm"](info,receiveInstance);return exports3}catch(e){err("Module.instantiateWasm callback failed with error: "+e);return false}}instantiateAsync();return{}}var ASM_CONSTS={};function initPthreadsJS(){PThread.initRuntime()}if(!ENVIRONMENT_IS_PTHREAD)__ATINIT__.push({func:function(){___wasm_call_ctors()}});var __pthread_ptr=0;var __pthread_is_main_runtime_thread=0;var __pthread_is_main_browser_thread=0;function __register_pthread_ptr(pthreadPtr,isMainBrowserThread,isMainRuntimeThread){pthreadPtr=pthreadPtr|0;isMainBrowserThread=isMainBrowserThread|0;isMainRuntimeThread=isMainRuntimeThread|0;__pthread_ptr=pthreadPtr;__pthread_is_main_browser_thread=isMainBrowserThread;__pthread_is_main_runtime_thread=isMainRuntimeThread}Module["__register_pthread_ptr"]=__register_pthread_ptr;var ERRNO_CODES={EPERM:63,ENOENT:44,ESRCH:71,EINTR:27,EIO:29,ENXIO:60,E2BIG:1,ENOEXEC:45,EBADF:8,ECHILD:12,EAGAIN:6,EWOULDBLOCK:6,ENOMEM:48,EACCES:2,EFAULT:21,ENOTBLK:105,EBUSY:10,EEXIST:20,EXDEV:75,ENODEV:43,ENOTDIR:54,EISDIR:31,EINVAL:28,ENFILE:41,EMFILE:33,ENOTTY:59,ETXTBSY:74,EFBIG:22,ENOSPC:51,ESPIPE:70,EROFS:69,EMLINK:34,EPIPE:64,EDOM:18,ERANGE:68,ENOMSG:49,EIDRM:24,ECHRNG:106,EL2NSYNC:156,EL3HLT:107,EL3RST:108,ELNRNG:109,EUNATCH:110,ENOCSI:111,EL2HLT:112,EDEADLK:16,ENOLCK:46,EBADE:113,EBADR:114,EXFULL:115,ENOANO:104,EBADRQC:103,EBADSLT:102,EDEADLOCK:16,EBFONT:101,ENOSTR:100,ENODATA:116,ETIME:117,ENOSR:118,ENONET:119,ENOPKG:120,EREMOTE:121,ENOLINK:47,EADV:122,ESRMNT:123,ECOMM:124,EPROTO:65,EMULTIHOP:36,EDOTDOT:125,EBADMSG:9,ENOTUNIQ:126,EBADFD:127,EREMCHG:128,ELIBACC:129,ELIBBAD:130,ELIBSCN:131,ELIBMAX:132,ELIBEXEC:133,ENOSYS:52,ENOTEMPTY:55,ENAMETOOLONG:37,ELOOP:32,EOPNOTSUPP:138,EPFNOSUPPORT:139,ECONNRESET:15,ENOBUFS:42,EAFNOSUPPORT:5,EPROTOTYPE:67,ENOTSOCK:57,ENOPROTOOPT:50,ESHUTDOWN:140,ECONNREFUSED:14,EADDRINUSE:3,ECONNABORTED:13,ENETUNREACH:40,ENETDOWN:38,ETIMEDOUT:73,EHOSTDOWN:142,EHOSTUNREACH:23,EINPROGRESS:26,EALREADY:7,EDESTADDRREQ:17,EMSGSIZE:35,EPROTONOSUPPORT:66,ESOCKTNOSUPPORT:137,EADDRNOTAVAIL:4,ENETRESET:39,EISCONN:30,ENOTCONN:53,ETOOMANYREFS:141,EUSERS:136,EDQUOT:19,ESTALE:72,ENOTSUP:138,ENOMEDIUM:148,EILSEQ:25,EOVERFLOW:61,ECANCELED:11,ENOTRECOVERABLE:56,EOWNERDEAD:62,ESTRPIPE:135};var __main_thread_futex_wait_address=13488;function _emscripten_futex_wake(addr,count){if(addr<=0||addr>GROWABLE_HEAP_I8().length||addr&true||count<0)return-28;if(count==0)return 0;if(count>=2147483647)count=Infinity;var mainThreadWaitAddress=Atomics.load(GROWABLE_HEAP_I32(),__main_thread_futex_wait_address>>2);var mainThreadWoken=0;if(mainThreadWaitAddress==addr){var loadedAddr=Atomics.compareExchange(GROWABLE_HEAP_I32(),__main_thread_futex_wait_address>>2,mainThreadWaitAddress,0);if(loadedAddr==mainThreadWaitAddress){--count;mainThreadWoken=1;if(count<=0)return 1}}var ret=Atomics.notify(GROWABLE_HEAP_I32(),addr>>2,count);if(ret>=0)return ret+mainThreadWoken;throw"Atomics.notify returned an unexpected value "+ret}Module["_emscripten_futex_wake"]=_emscripten_futex_wake;function __kill_thread(pthread_ptr){if(ENVIRONMENT_IS_PTHREAD)throw"Internal Error! _kill_thread() can only ever be called from main application thread!";if(!pthread_ptr)throw"Internal Error! Null pthread_ptr in _kill_thread!";GROWABLE_HEAP_I32()[pthread_ptr+12>>2]=0;var pthread=PThread.pthreads[pthread_ptr];pthread.worker.terminate();PThread.freeThreadData(pthread);PThread.runningWorkers.splice(PThread.runningWorkers.indexOf(pthread.worker),1);pthread.worker.pthread=void 0}function __cancel_thread(pthread_ptr){if(ENVIRONMENT_IS_PTHREAD)throw"Internal Error! _cancel_thread() can only ever be called from main application thread!";if(!pthread_ptr)throw"Internal Error! Null pthread_ptr in _cancel_thread!";var pthread=PThread.pthreads[pthread_ptr];pthread.worker.postMessage({cmd:"cancel"})}function __cleanup_thread(pthread_ptr){if(ENVIRONMENT_IS_PTHREAD)throw"Internal Error! _cleanup_thread() can only ever be called from main application thread!";if(!pthread_ptr)throw"Internal Error! Null pthread_ptr in _cleanup_thread!";GROWABLE_HEAP_I32()[pthread_ptr+12>>2]=0;var pthread=PThread.pthreads[pthread_ptr];if(pthread){var worker=pthread.worker;PThread.returnWorkerToPool(worker)}}var PThread={MAIN_THREAD_ID:1,mainThreadInfo:{schedPolicy:0,schedPrio:0},unusedWorkers:[],runningWorkers:[],initRuntime:function(){__register_pthread_ptr(PThread.mainThreadBlock,!ENVIRONMENT_IS_WORKER,1);_emscripten_register_main_browser_thread_id(PThread.mainThreadBlock)},initMainThreadBlock:function(){var pthreadPoolSize=8;for(var i=0;i>2]=PThread.mainThreadBlock;var headPtr=PThread.mainThreadBlock+156;GROWABLE_HEAP_I32()[headPtr>>2]=headPtr;var tlsMemory=12976;for(var i=0;i<128;++i)GROWABLE_HEAP_U32()[tlsMemory/4+i]=0;Atomics.store(GROWABLE_HEAP_U32(),PThread.mainThreadBlock+104>>2,tlsMemory);Atomics.store(GROWABLE_HEAP_U32(),PThread.mainThreadBlock+40>>2,PThread.mainThreadBlock);Atomics.store(GROWABLE_HEAP_U32(),PThread.mainThreadBlock+44>>2,42)},initWorker:function(){},pthreads:{},exitHandlers:null,setThreadStatus:function(){},runExitHandlers:function(){if(PThread.exitHandlers!==null){while(PThread.exitHandlers.length>0){PThread.exitHandlers.pop()()}PThread.exitHandlers=null}if(ENVIRONMENT_IS_PTHREAD&&threadInfoStruct)___pthread_tsd_run_dtors()},threadExit:function(exitCode){var tb=_pthread_self();if(tb){Atomics.store(GROWABLE_HEAP_U32(),tb+4>>2,exitCode);Atomics.store(GROWABLE_HEAP_U32(),tb+0>>2,1);Atomics.store(GROWABLE_HEAP_U32(),tb+60>>2,1);Atomics.store(GROWABLE_HEAP_U32(),tb+64>>2,0);PThread.runExitHandlers();_emscripten_futex_wake(tb+0,2147483647);__register_pthread_ptr(0,0,0);threadInfoStruct=0;if(ENVIRONMENT_IS_PTHREAD){postMessage({cmd:"exit"})}}},threadCancel:function(){PThread.runExitHandlers();Atomics.store(GROWABLE_HEAP_U32(),threadInfoStruct+4>>2,-1);Atomics.store(GROWABLE_HEAP_U32(),threadInfoStruct+0>>2,1);_emscripten_futex_wake(threadInfoStruct+0,2147483647);threadInfoStruct=selfThreadId=0;__register_pthread_ptr(0,0,0);postMessage({cmd:"cancelDone"})},terminateAllThreads:function(){for(var t in PThread.pthreads){var pthread=PThread.pthreads[t];if(pthread&&pthread.worker){PThread.returnWorkerToPool(pthread.worker)}}PThread.pthreads={};for(var i=0;i>2];GROWABLE_HEAP_I32()[pthread.threadInfoStruct+104>>2]=0;_free(tlsMemory);_free(pthread.threadInfoStruct)}pthread.threadInfoStruct=0;if(pthread.allocatedOwnStack&&pthread.stackBase)_free(pthread.stackBase);pthread.stackBase=0;if(pthread.worker)pthread.worker.pthread=null},returnWorkerToPool:function(worker){delete PThread.pthreads[worker.pthread.thread];PThread.unusedWorkers.push(worker);PThread.runningWorkers.splice(PThread.runningWorkers.indexOf(worker),1);PThread.freeThreadData(worker.pthread);worker.pthread=void 0},receiveObjectTransfer:function(data2){},loadWasmModuleToWorker:function(worker,onFinishedLoading){worker.onmessage=function(e){var d=e["data"];var cmd=d["cmd"];if(worker.pthread)PThread.currentProxiedOperationCallerThread=worker.pthread.threadInfoStruct;if(d["targetThread"]&&d["targetThread"]!=_pthread_self()){var thread=PThread.pthreads[d.targetThread];if(thread){thread.worker.postMessage(e.data,d["transferList"])}else{console.error('Internal error! Worker sent a message "'+cmd+'" to target pthread '+d["targetThread"]+", but that thread no longer exists!")}PThread.currentProxiedOperationCallerThread=void 0;return}if(cmd==="processQueuedMainThreadWork"){_emscripten_main_thread_process_queued_calls()}else if(cmd==="spawnThread"){__spawn_thread(e.data)}else if(cmd==="cleanupThread"){__cleanup_thread(d["thread"])}else if(cmd==="killThread"){__kill_thread(d["thread"])}else if(cmd==="cancelThread"){__cancel_thread(d["thread"])}else if(cmd==="loaded"){worker.loaded=true;if(onFinishedLoading)onFinishedLoading(worker);if(worker.runPthread){worker.runPthread();delete worker.runPthread}}else if(cmd==="print"){out("Thread "+d["threadId"]+": "+d["text"])}else if(cmd==="printErr"){err("Thread "+d["threadId"]+": "+d["text"])}else if(cmd==="alert"){alert("Thread "+d["threadId"]+": "+d["text"])}else if(cmd==="exit"){var detached=worker.pthread&&Atomics.load(GROWABLE_HEAP_U32(),worker.pthread.thread+68>>2);if(detached){PThread.returnWorkerToPool(worker)}}else if(cmd==="cancelDone"){PThread.returnWorkerToPool(worker)}else if(cmd==="objectTransfer"){PThread.receiveObjectTransfer(e.data)}else if(e.data.target==="setimmediate"){worker.postMessage(e.data)}else{err("worker sent an unknown command "+cmd)}PThread.currentProxiedOperationCallerThread=void 0};worker.onerror=function(e){err("pthread sent an error! "+e.filename+":"+e.lineno+": "+e.message)};if(ENVIRONMENT_IS_NODE){worker.on("message",function(data2){worker.onmessage({data:data2})});worker.on("error",function(data2){worker.onerror(data2)});worker.on("exit",function(data2){console.log("worker exited - TODO: update the worker queue?")})}worker.postMessage({cmd:"load",urlOrBlob:Module["mainScriptUrlOrBlob"]||_scriptDir,wasmMemory,wasmModule,DYNAMIC_BASE,DYNAMICTOP_PTR})},allocateUnusedWorker:function(){var pthreadMainJs=locateFile("tfjs-backend-wasm-threaded-simd.worker.js");PThread.unusedWorkers.push(new Worker(pthreadMainJs))},getNewWorker:function(){if(PThread.unusedWorkers.length==0){PThread.allocateUnusedWorker();PThread.loadWasmModuleToWorker(PThread.unusedWorkers[0])}if(PThread.unusedWorkers.length>0)return PThread.unusedWorkers.pop();else return null},busySpinWait:function(msecs){var t=performance.now()+msecs;while(performance.now()>2]=value;return value}function _atexit(func,arg){if(ENVIRONMENT_IS_PTHREAD)return _emscripten_proxy_to_main_thread_js(1,1,func,arg);__ATEXIT__.unshift({func,arg})}function __emscripten_notify_thread_queue(targetThreadId,mainThreadId){if(targetThreadId==mainThreadId){postMessage({cmd:"processQueuedMainThreadWork"})}else if(ENVIRONMENT_IS_PTHREAD){postMessage({targetThread:targetThreadId,cmd:"processThreadQueue"})}else{var pthread=PThread.pthreads[targetThreadId];var worker=pthread&&pthread.worker;if(!worker){return}worker.postMessage({cmd:"processThreadQueue"})}return 1}function _abort(){abort()}function _emscripten_conditional_set_current_thread_status(expectedStatus,newStatus){expectedStatus=expectedStatus|0;newStatus=newStatus|0}function _emscripten_futex_wait(addr,val,timeout){if(addr<=0||addr>GROWABLE_HEAP_I8().length||addr&true)return-28;if(ENVIRONMENT_IS_WORKER){var ret=Atomics.wait(GROWABLE_HEAP_I32(),addr>>2,val,timeout);if(ret==="timed-out")return-73;if(ret==="not-equal")return-6;if(ret==="ok")return 0;throw"Atomics.wait returned an unexpected value "+ret}else{var loadedVal=Atomics.load(GROWABLE_HEAP_I32(),addr>>2);if(val!=loadedVal)return-6;var tNow=performance.now();var tEnd=tNow+timeout;Atomics.store(GROWABLE_HEAP_I32(),__main_thread_futex_wait_address>>2,addr);var ourWaitAddress=addr;while(addr==ourWaitAddress){tNow=performance.now();if(tNow>tEnd){return-73}_emscripten_main_thread_process_queued_calls();addr=Atomics.load(GROWABLE_HEAP_I32(),__main_thread_futex_wait_address>>2)}return 0}}function _emscripten_is_main_browser_thread(){return __pthread_is_main_browser_thread|0}function _emscripten_is_main_runtime_thread(){return __pthread_is_main_runtime_thread|0}function _emscripten_memcpy_big(dest,src,num){GROWABLE_HEAP_U8().copyWithin(dest,src,src+num)}function _emscripten_num_logical_cores(){return navigator["hardwareConcurrency"]}function _emscripten_proxy_to_main_thread_js(index,sync){var numCallArgs=arguments.length-2;var stack=stackSave();var args=stackAlloc(numCallArgs*8);var b=args>>3;for(var i=0;i>3]);buf+=8}else{buf=buf+3&~3;args.push(GROWABLE_HEAP_I32()[buf>>2]);buf+=4}}return args}function _emscripten_receive_on_main_thread_js(index,numCallArgs,args){_emscripten_receive_on_main_thread_js_callArgs.length=numCallArgs;var b=args>>3;for(var i=0;i>>16);updateGlobalBufferAndViews(wasmMemory.buffer);return 1}catch(e){}}function _emscripten_resize_heap(requestedSize){requestedSize=requestedSize>>>0;var oldSize=_emscripten_get_heap_size();if(requestedSize<=oldSize){return false}var PAGE_MULTIPLE=65536;var maxHeapSize=2147483648;if(requestedSize>maxHeapSize){return false}var minHeapSize=16777216;for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignUp(Math.max(minHeapSize,requestedSize,overGrownHeapSize),PAGE_MULTIPLE));var replacement=emscripten_realloc_buffer(newSize);if(replacement){return true}}return false}var JSEvents={keyEvent:0,mouseEvent:0,wheelEvent:0,uiEvent:0,focusEvent:0,deviceOrientationEvent:0,deviceMotionEvent:0,fullscreenChangeEvent:0,pointerlockChangeEvent:0,visibilityChangeEvent:0,touchEvent:0,previousFullscreenElement:null,previousScreenX:null,previousScreenY:null,removeEventListenersRegistered:false,removeAllEventListeners:function(){for(var i=JSEvents.eventHandlers.length-1;i>=0;--i){JSEvents._removeHandler(i)}JSEvents.eventHandlers=[];JSEvents.deferredCalls=[]},registerRemoveEventListeners:function(){if(!JSEvents.removeEventListenersRegistered){__ATEXIT__.push(JSEvents.removeAllEventListeners);JSEvents.removeEventListenersRegistered=true}},deferredCalls:[],deferCall:function(targetFunction,precedence,argsList){function arraysHaveEqualContent(arrA,arrB){if(arrA.length!=arrB.length)return false;for(var i2 in arrA){if(arrA[i2]!=arrB[i2])return false}return true}for(var i in JSEvents.deferredCalls){var call=JSEvents.deferredCalls[i];if(call.targetFunction==targetFunction&&arraysHaveEqualContent(call.argsList,argsList)){return}}JSEvents.deferredCalls.push({targetFunction,precedence,argsList});JSEvents.deferredCalls.sort(function(x,y){return x.precedence>2]=eventTypeId;GROWABLE_HEAP_I32()[varargs+4>>2]=eventData;GROWABLE_HEAP_I32()[varargs+8>>2]=userData;_emscripten_async_queue_on_thread_(targetThread,637534208,eventHandlerFunc,eventData,varargs);stackRestore(stackTop)},getTargetThreadForEventCallback:function(targetThread){switch(targetThread){case 1:return 0;case 2:return PThread.currentProxiedOperationCallerThread;default:return targetThread}},getNodeNameForTarget:function(target){if(!target)return"";if(target==window)return"#window";if(target==screen)return"#screen";return target&&target.nodeName?target.nodeName:""},fullscreenEnabled:function(){return document.fullscreenEnabled||document.webkitFullscreenEnabled}};function stringToNewUTF8(jsString){var length=lengthBytesUTF8(jsString)+1;var cString=_malloc(length);stringToUTF8(jsString,cString,length);return cString}function _emscripten_set_offscreencanvas_size_on_target_thread_js(targetThread,targetCanvas,width,height){var stackTop=stackSave();var varargs=stackAlloc(12);var targetCanvasPtr=0;if(targetCanvas){targetCanvasPtr=stringToNewUTF8(targetCanvas)}GROWABLE_HEAP_I32()[varargs>>2]=targetCanvasPtr;GROWABLE_HEAP_I32()[varargs+4>>2]=width;GROWABLE_HEAP_I32()[varargs+8>>2]=height;_emscripten_async_queue_on_thread_(targetThread,657457152,0,targetCanvasPtr,varargs);stackRestore(stackTop)}function _emscripten_set_offscreencanvas_size_on_target_thread(targetThread,targetCanvas,width,height){targetCanvas=targetCanvas?UTF8ToString(targetCanvas):"";_emscripten_set_offscreencanvas_size_on_target_thread_js(targetThread,targetCanvas,width,height)}function __maybeCStringToJsString(cString){return cString>2?UTF8ToString(cString):cString}var specialHTMLTargets=[0,typeof document!=="undefined"?document:0,typeof window!=="undefined"?window:0];function __findEventTarget(target){target=__maybeCStringToJsString(target);var domElement=specialHTMLTargets[target]||(typeof document!=="undefined"?document.querySelector(target):void 0);return domElement}function __findCanvasEventTarget(target){return __findEventTarget(target)}function _emscripten_set_canvas_element_size_calling_thread(target,width,height){var canvas=__findCanvasEventTarget(target);if(!canvas)return-4;if(canvas.canvasSharedPtr){GROWABLE_HEAP_I32()[canvas.canvasSharedPtr>>2]=width;GROWABLE_HEAP_I32()[canvas.canvasSharedPtr+4>>2]=height}if(canvas.offscreenCanvas||!canvas.controlTransferredOffscreen){if(canvas.offscreenCanvas)canvas=canvas.offscreenCanvas;var autoResizeViewport=false;if(canvas.GLctxObject&&canvas.GLctxObject.GLctx){var prevViewport=canvas.GLctxObject.GLctx.getParameter(2978);autoResizeViewport=prevViewport[0]===0&&prevViewport[1]===0&&prevViewport[2]===canvas.width&&prevViewport[3]===canvas.height}canvas.width=width;canvas.height=height;if(autoResizeViewport){canvas.GLctxObject.GLctx.viewport(0,0,width,height)}}else if(canvas.canvasSharedPtr){var targetThread=GROWABLE_HEAP_I32()[canvas.canvasSharedPtr+8>>2];_emscripten_set_offscreencanvas_size_on_target_thread(targetThread,target,width,height);return 1}else{return-4}return 0}function _emscripten_set_canvas_element_size_main_thread(target,width,height){if(ENVIRONMENT_IS_PTHREAD)return _emscripten_proxy_to_main_thread_js(2,1,target,width,height);return _emscripten_set_canvas_element_size_calling_thread(target,width,height)}function _emscripten_set_canvas_element_size(target,width,height){var canvas=__findCanvasEventTarget(target);if(canvas){return _emscripten_set_canvas_element_size_calling_thread(target,width,height)}else{return _emscripten_set_canvas_element_size_main_thread(target,width,height)}}function _emscripten_set_current_thread_status(newStatus){newStatus=newStatus|0}function _emscripten_set_thread_name(threadId,name){threadId=threadId|0;name=name|0}function __webgl_enable_ANGLE_instanced_arrays(ctx){var ext=ctx.getExtension("ANGLE_instanced_arrays");if(ext){ctx["vertexAttribDivisor"]=function(index,divisor){ext["vertexAttribDivisorANGLE"](index,divisor)};ctx["drawArraysInstanced"]=function(mode,first,count,primcount){ext["drawArraysInstancedANGLE"](mode,first,count,primcount)};ctx["drawElementsInstanced"]=function(mode,count,type,indices,primcount){ext["drawElementsInstancedANGLE"](mode,count,type,indices,primcount)};return 1}}function __webgl_enable_OES_vertex_array_object(ctx){var ext=ctx.getExtension("OES_vertex_array_object");if(ext){ctx["createVertexArray"]=function(){return ext["createVertexArrayOES"]()};ctx["deleteVertexArray"]=function(vao){ext["deleteVertexArrayOES"](vao)};ctx["bindVertexArray"]=function(vao){ext["bindVertexArrayOES"](vao)};ctx["isVertexArray"]=function(vao){return ext["isVertexArrayOES"](vao)};return 1}}function __webgl_enable_WEBGL_draw_buffers(ctx){var ext=ctx.getExtension("WEBGL_draw_buffers");if(ext){ctx["drawBuffers"]=function(n,bufs){ext["drawBuffersWEBGL"](n,bufs)};return 1}}var GL={counter:1,lastError:0,buffers:[],mappedBuffers:{},programs:[],framebuffers:[],renderbuffers:[],textures:[],uniforms:[],shaders:[],vaos:[],contexts:{},currentContext:null,offscreenCanvases:{},timerQueriesEXT:[],programInfos:{},stringCache:{},unpackAlignment:4,init:function(){var miniTempFloatBuffer=new Float32Array(GL.MINI_TEMP_BUFFER_SIZE);for(var i=0;i>2]:-1;source+=UTF8ToString(GROWABLE_HEAP_I32()[string+i*4>>2],len<0?void 0:len)}return source},createContext:function(canvas,webGLContextAttributes){var ctx=canvas.getContext("webgl",webGLContextAttributes);if(!ctx)return 0;var handle=GL.registerContext(ctx,webGLContextAttributes);return handle},registerContext:function(ctx,webGLContextAttributes){var handle=_malloc(8);GROWABLE_HEAP_I32()[handle+4>>2]=_pthread_self();var context={handle,attributes:webGLContextAttributes,version:webGLContextAttributes.majorVersion,GLctx:ctx};if(ctx.canvas)ctx.canvas.GLctxObject=context;GL.contexts[handle]=context;if(typeof webGLContextAttributes.enableExtensionsByDefault==="undefined"||webGLContextAttributes.enableExtensionsByDefault){GL.initExtensions(context)}return handle},makeContextCurrent:function(contextHandle){GL.currentContext=GL.contexts[contextHandle];Module.ctx=GLctx=GL.currentContext&&GL.currentContext.GLctx;return!(contextHandle&&!GLctx)},getContext:function(contextHandle){return GL.contexts[contextHandle]},deleteContext:function(contextHandle){if(GL.currentContext===GL.contexts[contextHandle])GL.currentContext=null;if(typeof JSEvents==="object")JSEvents.removeAllHandlersOnTarget(GL.contexts[contextHandle].GLctx.canvas);if(GL.contexts[contextHandle]&&GL.contexts[contextHandle].GLctx.canvas)GL.contexts[contextHandle].GLctx.canvas.GLctxObject=void 0;_free(GL.contexts[contextHandle].handle);GL.contexts[contextHandle]=null},initExtensions:function(context){if(!context)context=GL.currentContext;if(context.initExtensionsDone)return;context.initExtensionsDone=true;var GLctx2=context.GLctx;__webgl_enable_ANGLE_instanced_arrays(GLctx2);__webgl_enable_OES_vertex_array_object(GLctx2);__webgl_enable_WEBGL_draw_buffers(GLctx2);GLctx2.disjointTimerQueryExt=GLctx2.getExtension("EXT_disjoint_timer_query");var automaticallyEnabledExtensions=["OES_texture_float","OES_texture_half_float","OES_standard_derivatives","OES_vertex_array_object","WEBGL_compressed_texture_s3tc","WEBGL_depth_texture","OES_element_index_uint","EXT_texture_filter_anisotropic","EXT_frag_depth","WEBGL_draw_buffers","ANGLE_instanced_arrays","OES_texture_float_linear","OES_texture_half_float_linear","EXT_blend_minmax","EXT_shader_texture_lod","EXT_texture_norm16","WEBGL_compressed_texture_pvrtc","EXT_color_buffer_half_float","WEBGL_color_buffer_float","EXT_sRGB","WEBGL_compressed_texture_etc1","EXT_disjoint_timer_query","WEBGL_compressed_texture_etc","WEBGL_compressed_texture_astc","EXT_color_buffer_float","WEBGL_compressed_texture_s3tc_srgb","EXT_disjoint_timer_query_webgl2","WEBKIT_WEBGL_compressed_texture_pvrtc"];var exts=GLctx2.getSupportedExtensions()||[];exts.forEach(function(ext){if(automaticallyEnabledExtensions.indexOf(ext)!=-1){GLctx2.getExtension(ext)}})},populateUniformTable:function(program){var p=GL.programs[program];var ptable=GL.programInfos[program]={uniforms:{},maxUniformLength:0,maxAttributeLength:-1,maxUniformBlockNameLength:-1};var utable=ptable.uniforms;var numUniforms=GLctx.getProgramParameter(p,35718);for(var i=0;i>2;contextAttributes["alpha"]=!!GROWABLE_HEAP_I32()[a+(0>>2)];contextAttributes["depth"]=!!GROWABLE_HEAP_I32()[a+(4>>2)];contextAttributes["stencil"]=!!GROWABLE_HEAP_I32()[a+(8>>2)];contextAttributes["antialias"]=!!GROWABLE_HEAP_I32()[a+(12>>2)];contextAttributes["premultipliedAlpha"]=!!GROWABLE_HEAP_I32()[a+(16>>2)];contextAttributes["preserveDrawingBuffer"]=!!GROWABLE_HEAP_I32()[a+(20>>2)];var powerPreference=GROWABLE_HEAP_I32()[a+(24>>2)];contextAttributes["powerPreference"]=__emscripten_webgl_power_preferences[powerPreference];contextAttributes["failIfMajorPerformanceCaveat"]=!!GROWABLE_HEAP_I32()[a+(28>>2)];contextAttributes.majorVersion=GROWABLE_HEAP_I32()[a+(32>>2)];contextAttributes.minorVersion=GROWABLE_HEAP_I32()[a+(36>>2)];contextAttributes.enableExtensionsByDefault=GROWABLE_HEAP_I32()[a+(40>>2)];contextAttributes.explicitSwapControl=GROWABLE_HEAP_I32()[a+(44>>2)];contextAttributes.proxyContextToMainThread=GROWABLE_HEAP_I32()[a+(48>>2)];contextAttributes.renderViaOffscreenBackBuffer=GROWABLE_HEAP_I32()[a+(52>>2)];var canvas=__findCanvasEventTarget(target);if(!canvas){return-4}if(contextAttributes.explicitSwapControl){return-1}var contextHandle=GL.createContext(canvas,contextAttributes);return contextHandle}function _emscripten_webgl_create_context(a0,a1){return _emscripten_webgl_do_create_context(a0,a1)}var PATH={splitPath:function(filename){var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return splitPathRe.exec(filename).slice(1)},normalizeArray:function(parts,allowAboveRoot){var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up;up--){parts.unshift("..")}}return parts},normalize:function(path){var isAbsolute=path.charAt(0)==="/",trailingSlash=path.substr(-1)==="/";path=PATH.normalizeArray(path.split("/").filter(function(p){return!!p}),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path},dirname:function(path){var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.substr(0,dir.length-1)}return root+dir},basename:function(path){if(path==="/")return"/";var lastSlash=path.lastIndexOf("/");if(lastSlash===-1)return path;return path.substr(lastSlash+1)},extname:function(path){return PATH.splitPath(path)[3]},join:function(){var paths=Array.prototype.slice.call(arguments,0);return PATH.normalize(paths.join("/"))},join2:function(l,r){return PATH.normalize(l+"/"+r)}};var SYSCALLS={mappings:{},buffers:[null,[],[]],printChar:function(stream,curr){var buffer3=SYSCALLS.buffers[stream];if(curr===0||curr===10){(stream===1?out:err)(UTF8ArrayToString(buffer3,0));buffer3.length=0}else{buffer3.push(curr)}},varargs:void 0,get:function(){SYSCALLS.varargs+=4;var ret=GROWABLE_HEAP_I32()[SYSCALLS.varargs-4>>2];return ret},getStr:function(ptr){var ret=UTF8ToString(ptr);return ret},get64:function(low,high){return low}};function _fd_close(fd){if(ENVIRONMENT_IS_PTHREAD)return _emscripten_proxy_to_main_thread_js(3,1,fd);return 0}function _fd_seek(fd,offset_low,offset_high,whence,newOffset){if(ENVIRONMENT_IS_PTHREAD)return _emscripten_proxy_to_main_thread_js(4,1,fd,offset_low,offset_high,whence,newOffset)}function _fd_write(fd,iov,iovcnt,pnum){if(ENVIRONMENT_IS_PTHREAD)return _emscripten_proxy_to_main_thread_js(5,1,fd,iov,iovcnt,pnum);var num=0;for(var i=0;i>2];var len=GROWABLE_HEAP_I32()[iov+(i*8+4)>>2];for(var j=0;j>2]=num;return 0}function _pthread_cleanup_pop(execute){var routine=PThread.exitHandlers.pop();if(execute)routine()}function _pthread_cleanup_push(routine,arg){if(PThread.exitHandlers===null){PThread.exitHandlers=[]}PThread.exitHandlers.push(function(){dynCall_vi(routine,arg)})}function __spawn_thread(threadParams){if(ENVIRONMENT_IS_PTHREAD)throw"Internal Error! _spawn_thread() can only ever be called from main application thread!";var worker=PThread.getNewWorker();if(worker.pthread!==void 0)throw"Internal error!";if(!threadParams.pthread_ptr)throw"Internal error, no pthread ptr!";PThread.runningWorkers.push(worker);var tlsMemory=_malloc(128*4);for(var i=0;i<128;++i){GROWABLE_HEAP_I32()[tlsMemory+i*4>>2]=0}var stackHigh=threadParams.stackBase+threadParams.stackSize;var pthread=PThread.pthreads[threadParams.pthread_ptr]={worker,stackBase:threadParams.stackBase,stackSize:threadParams.stackSize,allocatedOwnStack:threadParams.allocatedOwnStack,thread:threadParams.pthread_ptr,threadInfoStruct:threadParams.pthread_ptr};var tis=pthread.threadInfoStruct>>2;Atomics.store(GROWABLE_HEAP_U32(),tis+(0>>2),0);Atomics.store(GROWABLE_HEAP_U32(),tis+(4>>2),0);Atomics.store(GROWABLE_HEAP_U32(),tis+(8>>2),0);Atomics.store(GROWABLE_HEAP_U32(),tis+(68>>2),threadParams.detached);Atomics.store(GROWABLE_HEAP_U32(),tis+(104>>2),tlsMemory);Atomics.store(GROWABLE_HEAP_U32(),tis+(48>>2),0);Atomics.store(GROWABLE_HEAP_U32(),tis+(40>>2),pthread.threadInfoStruct);Atomics.store(GROWABLE_HEAP_U32(),tis+(44>>2),42);Atomics.store(GROWABLE_HEAP_U32(),tis+(108>>2),threadParams.stackSize);Atomics.store(GROWABLE_HEAP_U32(),tis+(84>>2),threadParams.stackSize);Atomics.store(GROWABLE_HEAP_U32(),tis+(80>>2),stackHigh);Atomics.store(GROWABLE_HEAP_U32(),tis+(108+8>>2),stackHigh);Atomics.store(GROWABLE_HEAP_U32(),tis+(108+12>>2),threadParams.detached);Atomics.store(GROWABLE_HEAP_U32(),tis+(108+20>>2),threadParams.schedPolicy);Atomics.store(GROWABLE_HEAP_U32(),tis+(108+24>>2),threadParams.schedPrio);var global_libc=_emscripten_get_global_libc();var global_locale=global_libc+40;Atomics.store(GROWABLE_HEAP_U32(),tis+(176>>2),global_locale);worker.pthread=pthread;var msg={cmd:"run",start_routine:threadParams.startRoutine,arg:threadParams.arg,threadInfoStruct:threadParams.pthread_ptr,selfThreadId:threadParams.pthread_ptr,parentThreadId:threadParams.parent_pthread_ptr,stackBase:threadParams.stackBase,stackSize:threadParams.stackSize};worker.runPthread=function(){msg.time=performance.now();worker.postMessage(msg,threadParams.transferList)};if(worker.loaded){worker.runPthread();delete worker.runPthread}}function _pthread_getschedparam(thread,policy,schedparam){if(!policy&&!schedparam)return ERRNO_CODES.EINVAL;if(!thread){err("pthread_getschedparam called with a null thread pointer!");return ERRNO_CODES.ESRCH}var self2=GROWABLE_HEAP_I32()[thread+12>>2];if(self2!==thread){err("pthread_getschedparam attempted on thread "+thread+", which does not point to a valid thread, or does not exist anymore!");return ERRNO_CODES.ESRCH}var schedPolicy=Atomics.load(GROWABLE_HEAP_U32(),thread+108+20>>2);var schedPrio=Atomics.load(GROWABLE_HEAP_U32(),thread+108+24>>2);if(policy)GROWABLE_HEAP_I32()[policy>>2]=schedPolicy;if(schedparam)GROWABLE_HEAP_I32()[schedparam>>2]=schedPrio;return 0}function _pthread_self(){return __pthread_ptr|0}Module["_pthread_self"]=_pthread_self;function _pthread_create(pthread_ptr,attr,start_routine,arg){if(typeof SharedArrayBuffer==="undefined"){err("Current environment does not support SharedArrayBuffer, pthreads are not available!");return 6}if(!pthread_ptr){err("pthread_create called with a null thread pointer!");return 28}var transferList=[];var error=0;if(ENVIRONMENT_IS_PTHREAD&&(transferList.length===0||error)){return _emscripten_sync_run_in_main_thread_4(687865856,pthread_ptr,attr,start_routine,arg)}if(error)return error;var stackSize=0;var stackBase=0;var detached=0;var schedPolicy=0;var schedPrio=0;if(attr){stackSize=GROWABLE_HEAP_I32()[attr>>2];stackSize+=81920;stackBase=GROWABLE_HEAP_I32()[attr+8>>2];detached=GROWABLE_HEAP_I32()[attr+12>>2]!==0;var inheritSched=GROWABLE_HEAP_I32()[attr+16>>2]===0;if(inheritSched){var prevSchedPolicy=GROWABLE_HEAP_I32()[attr+20>>2];var prevSchedPrio=GROWABLE_HEAP_I32()[attr+24>>2];var parentThreadPtr=PThread.currentProxiedOperationCallerThread?PThread.currentProxiedOperationCallerThread:_pthread_self();_pthread_getschedparam(parentThreadPtr,attr+20,attr+24);schedPolicy=GROWABLE_HEAP_I32()[attr+20>>2];schedPrio=GROWABLE_HEAP_I32()[attr+24>>2];GROWABLE_HEAP_I32()[attr+20>>2]=prevSchedPolicy;GROWABLE_HEAP_I32()[attr+24>>2]=prevSchedPrio}else{schedPolicy=GROWABLE_HEAP_I32()[attr+20>>2];schedPrio=GROWABLE_HEAP_I32()[attr+24>>2]}}else{stackSize=2097152}var allocatedOwnStack=stackBase==0;if(allocatedOwnStack){stackBase=_memalign(16,stackSize)}else{stackBase-=stackSize;assert(stackBase>0)}var threadInfoStruct2=_malloc(232);for(var i=0;i<232>>2;++i)GROWABLE_HEAP_U32()[(threadInfoStruct2>>2)+i]=0;GROWABLE_HEAP_I32()[pthread_ptr>>2]=threadInfoStruct2;GROWABLE_HEAP_I32()[threadInfoStruct2+12>>2]=threadInfoStruct2;var headPtr=threadInfoStruct2+156;GROWABLE_HEAP_I32()[headPtr>>2]=headPtr;var threadParams={stackBase,stackSize,allocatedOwnStack,schedPolicy,schedPrio,detached,startRoutine:start_routine,pthread_ptr:threadInfoStruct2,parent_pthread_ptr:_pthread_self(),arg,transferList};if(ENVIRONMENT_IS_PTHREAD){threadParams.cmd="spawnThread";postMessage(threadParams,transferList)}else{__spawn_thread(threadParams)}return 0}function _roundf(d){d=+d;return d>=0?+Math_floor(d+.5):+Math_ceil(d-.5)}function _sysconf(name){if(ENVIRONMENT_IS_PTHREAD)return _emscripten_proxy_to_main_thread_js(6,1,name);switch(name){case 30:return 16384;case 85:var maxHeapSize=2147483648;return maxHeapSize/16384;case 132:case 133:case 12:case 137:case 138:case 15:case 235:case 16:case 17:case 18:case 19:case 20:case 149:case 13:case 10:case 236:case 153:case 9:case 21:case 22:case 159:case 154:case 14:case 77:case 78:case 139:case 80:case 81:case 82:case 68:case 67:case 164:case 11:case 29:case 47:case 48:case 95:case 52:case 51:case 46:case 79:return 200809;case 27:case 246:case 127:case 128:case 23:case 24:case 160:case 161:case 181:case 182:case 242:case 183:case 184:case 243:case 244:case 245:case 165:case 178:case 179:case 49:case 50:case 168:case 169:case 175:case 170:case 171:case 172:case 97:case 76:case 32:case 173:case 35:return-1;case 176:case 177:case 7:case 155:case 8:case 157:case 125:case 126:case 92:case 93:case 129:case 130:case 131:case 94:case 91:return 1;case 74:case 60:case 69:case 70:case 4:return 1024;case 31:case 42:case 72:return 32;case 87:case 26:case 33:return 2147483647;case 34:case 1:return 47839;case 38:case 36:return 99;case 43:case 37:return 2048;case 0:return 2097152;case 3:return 65536;case 28:return 32768;case 44:return 32767;case 75:return 16384;case 39:return 1e3;case 89:return 700;case 71:return 256;case 40:return 255;case 2:return 100;case 180:return 64;case 25:return 20;case 5:return 16;case 6:return 6;case 73:return 4;case 84:{if(typeof navigator==="object")return navigator["hardwareConcurrency"]||1;return 1}}setErrNo(28);return-1}if(!ENVIRONMENT_IS_PTHREAD)PThread.initMainThreadBlock();else PThread.initWorker();var GLctx;GL.init();var proxiedFunctionTable=[null,_atexit,_emscripten_set_canvas_element_size_main_thread,_fd_close,_fd_seek,_fd_write,_sysconf];var asmLibraryArg={e:___assert_fail,r:___call_main,w:__emscripten_notify_thread_queue,a:_abort,l:_emscripten_conditional_set_current_thread_status,d:_emscripten_futex_wait,c:_emscripten_futex_wake,h:_emscripten_get_now,g:_emscripten_is_main_browser_thread,x:_emscripten_is_main_runtime_thread,q:_emscripten_memcpy_big,B:_emscripten_num_logical_cores,t:_emscripten_receive_on_main_thread_js,A:_emscripten_resize_heap,u:_emscripten_set_canvas_element_size,k:_emscripten_set_current_thread_status,s:_emscripten_set_thread_name,v:_emscripten_webgl_create_context,m:_fd_close,o:_fd_seek,i:_fd_write,p:initPthreadsJS,memory:wasmMemory||Module["wasmMemory"],y:_pthread_cleanup_pop,z:_pthread_cleanup_push,j:_pthread_create,b:_pthread_self,f:_roundf,n:_sysconf,table:wasmTable};var asm=createWasm();Module["asm"]=asm;var ___wasm_call_ctors=Module["___wasm_call_ctors"]=function(){return(___wasm_call_ctors=Module["___wasm_call_ctors"]=Module["asm"]["C"]).apply(null,arguments)};var _init=Module["_init"]=function(){return(_init=Module["_init"]=Module["asm"]["D"]).apply(null,arguments)};var _register_tensor=Module["_register_tensor"]=function(){return(_register_tensor=Module["_register_tensor"]=Module["asm"]["E"]).apply(null,arguments)};var _dispose_data=Module["_dispose_data"]=function(){return(_dispose_data=Module["_dispose_data"]=Module["asm"]["F"]).apply(null,arguments)};var _dispose=Module["_dispose"]=function(){return(_dispose=Module["_dispose"]=Module["asm"]["G"]).apply(null,arguments)};var _Abs=Module["_Abs"]=function(){return(_Abs=Module["_Abs"]=Module["asm"]["H"]).apply(null,arguments)};var _Add=Module["_Add"]=function(){return(_Add=Module["_Add"]=Module["asm"]["I"]).apply(null,arguments)};var _AddN=Module["_AddN"]=function(){return(_AddN=Module["_AddN"]=Module["asm"]["J"]).apply(null,arguments)};var _ArgMax=Module["_ArgMax"]=function(){return(_ArgMax=Module["_ArgMax"]=Module["asm"]["K"]).apply(null,arguments)};var _AvgPool=Module["_AvgPool"]=function(){return(_AvgPool=Module["_AvgPool"]=Module["asm"]["L"]).apply(null,arguments)};var _BatchMatMul=Module["_BatchMatMul"]=function(){return(_BatchMatMul=Module["_BatchMatMul"]=Module["asm"]["M"]).apply(null,arguments)};var _ClipByValue=Module["_ClipByValue"]=function(){return(_ClipByValue=Module["_ClipByValue"]=Module["asm"]["N"]).apply(null,arguments)};var _Conv2D=Module["_Conv2D"]=function(){return(_Conv2D=Module["_Conv2D"]=Module["asm"]["O"]).apply(null,arguments)};var _Conv2DBackpropInput=Module["_Conv2DBackpropInput"]=function(){return(_Conv2DBackpropInput=Module["_Conv2DBackpropInput"]=Module["asm"]["P"]).apply(null,arguments)};var _Cos=Module["_Cos"]=function(){return(_Cos=Module["_Cos"]=Module["asm"]["Q"]).apply(null,arguments)};var _CropAndResize=Module["_CropAndResize"]=function(){return(_CropAndResize=Module["_CropAndResize"]=Module["asm"]["R"]).apply(null,arguments)};var _Cumsum=Module["_Cumsum"]=function(){return(_Cumsum=Module["_Cumsum"]=Module["asm"]["S"]).apply(null,arguments)};var _DepthToSpace=Module["_DepthToSpace"]=function(){return(_DepthToSpace=Module["_DepthToSpace"]=Module["asm"]["T"]).apply(null,arguments)};var _DepthwiseConv2dNative=Module["_DepthwiseConv2dNative"]=function(){return(_DepthwiseConv2dNative=Module["_DepthwiseConv2dNative"]=Module["asm"]["U"]).apply(null,arguments)};var _Div=Module["_Div"]=function(){return(_Div=Module["_Div"]=Module["asm"]["V"]).apply(null,arguments)};var _Equal=Module["_Equal"]=function(){return(_Equal=Module["_Equal"]=Module["asm"]["W"]).apply(null,arguments)};var _Exp=Module["_Exp"]=function(){return(_Exp=Module["_Exp"]=Module["asm"]["X"]).apply(null,arguments)};var _FlipLeftRight=Module["_FlipLeftRight"]=function(){return(_FlipLeftRight=Module["_FlipLeftRight"]=Module["asm"]["Y"]).apply(null,arguments)};var _FloorDiv=Module["_FloorDiv"]=function(){return(_FloorDiv=Module["_FloorDiv"]=Module["asm"]["Z"]).apply(null,arguments)};var _FusedBatchNorm=Module["_FusedBatchNorm"]=function(){return(_FusedBatchNorm=Module["_FusedBatchNorm"]=Module["asm"]["_"]).apply(null,arguments)};var _FusedConv2D=Module["_FusedConv2D"]=function(){return(_FusedConv2D=Module["_FusedConv2D"]=Module["asm"]["$"]).apply(null,arguments)};var _FusedDepthwiseConv2D=Module["_FusedDepthwiseConv2D"]=function(){return(_FusedDepthwiseConv2D=Module["_FusedDepthwiseConv2D"]=Module["asm"]["aa"]).apply(null,arguments)};var _Gather=Module["_Gather"]=function(){return(_Gather=Module["_Gather"]=Module["asm"]["ba"]).apply(null,arguments)};var _GatherNd=Module["_GatherNd"]=function(){return(_GatherNd=Module["_GatherNd"]=Module["asm"]["ca"]).apply(null,arguments)};var _Greater=Module["_Greater"]=function(){return(_Greater=Module["_Greater"]=Module["asm"]["da"]).apply(null,arguments)};var _GreaterEqual=Module["_GreaterEqual"]=function(){return(_GreaterEqual=Module["_GreaterEqual"]=Module["asm"]["ea"]).apply(null,arguments)};var _Less=Module["_Less"]=function(){return(_Less=Module["_Less"]=Module["asm"]["fa"]).apply(null,arguments)};var _LessEqual=Module["_LessEqual"]=function(){return(_LessEqual=Module["_LessEqual"]=Module["asm"]["ga"]).apply(null,arguments)};var _Log=Module["_Log"]=function(){return(_Log=Module["_Log"]=Module["asm"]["ha"]).apply(null,arguments)};var _LogicalAnd=Module["_LogicalAnd"]=function(){return(_LogicalAnd=Module["_LogicalAnd"]=Module["asm"]["ia"]).apply(null,arguments)};var _Max=Module["_Max"]=function(){return(_Max=Module["_Max"]=Module["asm"]["ja"]).apply(null,arguments)};var _MaxPool=Module["_MaxPool"]=function(){return(_MaxPool=Module["_MaxPool"]=Module["asm"]["ka"]).apply(null,arguments)};var _Maximum=Module["_Maximum"]=function(){return(_Maximum=Module["_Maximum"]=Module["asm"]["la"]).apply(null,arguments)};var _Min=Module["_Min"]=function(){return(_Min=Module["_Min"]=Module["asm"]["ma"]).apply(null,arguments)};var _Minimum=Module["_Minimum"]=function(){return(_Minimum=Module["_Minimum"]=Module["asm"]["na"]).apply(null,arguments)};var _Multiply=Module["_Multiply"]=function(){return(_Multiply=Module["_Multiply"]=Module["asm"]["oa"]).apply(null,arguments)};var _Negate=Module["_Negate"]=function(){return(_Negate=Module["_Negate"]=Module["asm"]["pa"]).apply(null,arguments)};var _NonMaxSuppressionV3=Module["_NonMaxSuppressionV3"]=function(){return(_NonMaxSuppressionV3=Module["_NonMaxSuppressionV3"]=Module["asm"]["qa"]).apply(null,arguments)};var _NonMaxSuppressionV4=Module["_NonMaxSuppressionV4"]=function(){return(_NonMaxSuppressionV4=Module["_NonMaxSuppressionV4"]=Module["asm"]["ra"]).apply(null,arguments)};var _NonMaxSuppressionV5=Module["_NonMaxSuppressionV5"]=function(){return(_NonMaxSuppressionV5=Module["_NonMaxSuppressionV5"]=Module["asm"]["sa"]).apply(null,arguments)};var _NotEqual=Module["_NotEqual"]=function(){return(_NotEqual=Module["_NotEqual"]=Module["asm"]["ta"]).apply(null,arguments)};var _OneHot=Module["_OneHot"]=function(){return(_OneHot=Module["_OneHot"]=Module["asm"]["ua"]).apply(null,arguments)};var _PadV2=Module["_PadV2"]=function(){return(_PadV2=Module["_PadV2"]=Module["asm"]["va"]).apply(null,arguments)};var _Pow=Module["_Pow"]=function(){return(_Pow=Module["_Pow"]=Module["asm"]["wa"]).apply(null,arguments)};var _Prelu=Module["_Prelu"]=function(){return(_Prelu=Module["_Prelu"]=Module["asm"]["xa"]).apply(null,arguments)};var _Relu=Module["_Relu"]=function(){return(_Relu=Module["_Relu"]=Module["asm"]["ya"]).apply(null,arguments)};var _Relu6=Module["_Relu6"]=function(){return(_Relu6=Module["_Relu6"]=Module["asm"]["za"]).apply(null,arguments)};var _ResizeBilinear=Module["_ResizeBilinear"]=function(){return(_ResizeBilinear=Module["_ResizeBilinear"]=Module["asm"]["Aa"]).apply(null,arguments)};var _Reverse=Module["_Reverse"]=function(){return(_Reverse=Module["_Reverse"]=Module["asm"]["Ba"]).apply(null,arguments)};var _RotateWithOffset=Module["_RotateWithOffset"]=function(){return(_RotateWithOffset=Module["_RotateWithOffset"]=Module["asm"]["Ca"]).apply(null,arguments)};var _Rsqrt=Module["_Rsqrt"]=function(){return(_Rsqrt=Module["_Rsqrt"]=Module["asm"]["Da"]).apply(null,arguments)};var _ScatterNd=Module["_ScatterNd"]=function(){return(_ScatterNd=Module["_ScatterNd"]=Module["asm"]["Ea"]).apply(null,arguments)};var _SelectV2=Module["_SelectV2"]=function(){return(_SelectV2=Module["_SelectV2"]=Module["asm"]["Fa"]).apply(null,arguments)};var _Sigmoid=Module["_Sigmoid"]=function(){return(_Sigmoid=Module["_Sigmoid"]=Module["asm"]["Ga"]).apply(null,arguments)};var _Sin=Module["_Sin"]=function(){return(_Sin=Module["_Sin"]=Module["asm"]["Ha"]).apply(null,arguments)};var _Softmax=Module["_Softmax"]=function(){return(_Softmax=Module["_Softmax"]=Module["asm"]["Ia"]).apply(null,arguments)};var _Sqrt=Module["_Sqrt"]=function(){return(_Sqrt=Module["_Sqrt"]=Module["asm"]["Ja"]).apply(null,arguments)};var _Square=Module["_Square"]=function(){return(_Square=Module["_Square"]=Module["asm"]["Ka"]).apply(null,arguments)};var _SquaredDifference=Module["_SquaredDifference"]=function(){return(_SquaredDifference=Module["_SquaredDifference"]=Module["asm"]["La"]).apply(null,arguments)};var _StridedSlice=Module["_StridedSlice"]=function(){return(_StridedSlice=Module["_StridedSlice"]=Module["asm"]["Ma"]).apply(null,arguments)};var _Sub=Module["_Sub"]=function(){return(_Sub=Module["_Sub"]=Module["asm"]["Na"]).apply(null,arguments)};var _Sum=Module["_Sum"]=function(){return(_Sum=Module["_Sum"]=Module["asm"]["Oa"]).apply(null,arguments)};var _Tanh=Module["_Tanh"]=function(){return(_Tanh=Module["_Tanh"]=Module["asm"]["Pa"]).apply(null,arguments)};var _Tile=Module["_Tile"]=function(){return(_Tile=Module["_Tile"]=Module["asm"]["Qa"]).apply(null,arguments)};var _Transpose=Module["_Transpose"]=function(){return(_Transpose=Module["_Transpose"]=Module["asm"]["Ra"]).apply(null,arguments)};var __FusedMatMul=Module["__FusedMatMul"]=function(){return(__FusedMatMul=Module["__FusedMatMul"]=Module["asm"]["Sa"]).apply(null,arguments)};var _malloc=Module["_malloc"]=function(){return(_malloc=Module["_malloc"]=Module["asm"]["Ta"]).apply(null,arguments)};var _free=Module["_free"]=function(){return(_free=Module["_free"]=Module["asm"]["Ua"]).apply(null,arguments)};var _emscripten_get_global_libc=Module["_emscripten_get_global_libc"]=function(){return(_emscripten_get_global_libc=Module["_emscripten_get_global_libc"]=Module["asm"]["Va"]).apply(null,arguments)};var ___errno_location=Module["___errno_location"]=function(){return(___errno_location=Module["___errno_location"]=Module["asm"]["Wa"]).apply(null,arguments)};var ___em_js__initPthreadsJS=Module["___em_js__initPthreadsJS"]=function(){return(___em_js__initPthreadsJS=Module["___em_js__initPthreadsJS"]=Module["asm"]["Xa"]).apply(null,arguments)};var _memalign=Module["_memalign"]=function(){return(_memalign=Module["_memalign"]=Module["asm"]["Ya"]).apply(null,arguments)};var ___pthread_tsd_run_dtors=Module["___pthread_tsd_run_dtors"]=function(){return(___pthread_tsd_run_dtors=Module["___pthread_tsd_run_dtors"]=Module["asm"]["Za"]).apply(null,arguments)};var _emscripten_main_thread_process_queued_calls=Module["_emscripten_main_thread_process_queued_calls"]=function(){return(_emscripten_main_thread_process_queued_calls=Module["_emscripten_main_thread_process_queued_calls"]=Module["asm"]["_a"]).apply(null,arguments)};var _emscripten_current_thread_process_queued_calls=Module["_emscripten_current_thread_process_queued_calls"]=function(){return(_emscripten_current_thread_process_queued_calls=Module["_emscripten_current_thread_process_queued_calls"]=Module["asm"]["$a"]).apply(null,arguments)};var _emscripten_register_main_browser_thread_id=Module["_emscripten_register_main_browser_thread_id"]=function(){return(_emscripten_register_main_browser_thread_id=Module["_emscripten_register_main_browser_thread_id"]=Module["asm"]["ab"]).apply(null,arguments)};var _emscripten_main_browser_thread_id=Module["_emscripten_main_browser_thread_id"]=function(){return(_emscripten_main_browser_thread_id=Module["_emscripten_main_browser_thread_id"]=Module["asm"]["bb"]).apply(null,arguments)};var _emscripten_async_run_in_main_thread=Module["_emscripten_async_run_in_main_thread"]=function(){return(_emscripten_async_run_in_main_thread=Module["_emscripten_async_run_in_main_thread"]=Module["asm"]["cb"]).apply(null,arguments)};var _emscripten_sync_run_in_main_thread=Module["_emscripten_sync_run_in_main_thread"]=function(){return(_emscripten_sync_run_in_main_thread=Module["_emscripten_sync_run_in_main_thread"]=Module["asm"]["db"]).apply(null,arguments)};var _emscripten_sync_run_in_main_thread_0=Module["_emscripten_sync_run_in_main_thread_0"]=function(){return(_emscripten_sync_run_in_main_thread_0=Module["_emscripten_sync_run_in_main_thread_0"]=Module["asm"]["eb"]).apply(null,arguments)};var _emscripten_sync_run_in_main_thread_1=Module["_emscripten_sync_run_in_main_thread_1"]=function(){return(_emscripten_sync_run_in_main_thread_1=Module["_emscripten_sync_run_in_main_thread_1"]=Module["asm"]["fb"]).apply(null,arguments)};var _emscripten_sync_run_in_main_thread_2=Module["_emscripten_sync_run_in_main_thread_2"]=function(){return(_emscripten_sync_run_in_main_thread_2=Module["_emscripten_sync_run_in_main_thread_2"]=Module["asm"]["gb"]).apply(null,arguments)};var _emscripten_sync_run_in_main_thread_xprintf_varargs=Module["_emscripten_sync_run_in_main_thread_xprintf_varargs"]=function(){return(_emscripten_sync_run_in_main_thread_xprintf_varargs=Module["_emscripten_sync_run_in_main_thread_xprintf_varargs"]=Module["asm"]["hb"]).apply(null,arguments)};var _emscripten_sync_run_in_main_thread_3=Module["_emscripten_sync_run_in_main_thread_3"]=function(){return(_emscripten_sync_run_in_main_thread_3=Module["_emscripten_sync_run_in_main_thread_3"]=Module["asm"]["ib"]).apply(null,arguments)};var _emscripten_sync_run_in_main_thread_4=Module["_emscripten_sync_run_in_main_thread_4"]=function(){return(_emscripten_sync_run_in_main_thread_4=Module["_emscripten_sync_run_in_main_thread_4"]=Module["asm"]["jb"]).apply(null,arguments)};var _emscripten_sync_run_in_main_thread_5=Module["_emscripten_sync_run_in_main_thread_5"]=function(){return(_emscripten_sync_run_in_main_thread_5=Module["_emscripten_sync_run_in_main_thread_5"]=Module["asm"]["kb"]).apply(null,arguments)};var _emscripten_sync_run_in_main_thread_6=Module["_emscripten_sync_run_in_main_thread_6"]=function(){return(_emscripten_sync_run_in_main_thread_6=Module["_emscripten_sync_run_in_main_thread_6"]=Module["asm"]["lb"]).apply(null,arguments)};var _emscripten_sync_run_in_main_thread_7=Module["_emscripten_sync_run_in_main_thread_7"]=function(){return(_emscripten_sync_run_in_main_thread_7=Module["_emscripten_sync_run_in_main_thread_7"]=Module["asm"]["mb"]).apply(null,arguments)};var _emscripten_run_in_main_runtime_thread_js=Module["_emscripten_run_in_main_runtime_thread_js"]=function(){return(_emscripten_run_in_main_runtime_thread_js=Module["_emscripten_run_in_main_runtime_thread_js"]=Module["asm"]["nb"]).apply(null,arguments)};var _emscripten_async_queue_on_thread_=Module["_emscripten_async_queue_on_thread_"]=function(){return(_emscripten_async_queue_on_thread_=Module["_emscripten_async_queue_on_thread_"]=Module["asm"]["ob"]).apply(null,arguments)};var _emscripten_tls_init=Module["_emscripten_tls_init"]=function(){return(_emscripten_tls_init=Module["_emscripten_tls_init"]=Module["asm"]["pb"]).apply(null,arguments)};var stackSave=Module["stackSave"]=function(){return(stackSave=Module["stackSave"]=Module["asm"]["qb"]).apply(null,arguments)};var stackAlloc=Module["stackAlloc"]=function(){return(stackAlloc=Module["stackAlloc"]=Module["asm"]["rb"]).apply(null,arguments)};var stackRestore=Module["stackRestore"]=function(){return(stackRestore=Module["stackRestore"]=Module["asm"]["sb"]).apply(null,arguments)};var dynCall_vi=Module["dynCall_vi"]=function(){return(dynCall_vi=Module["dynCall_vi"]=Module["asm"]["tb"]).apply(null,arguments)};var dynCall_v=Module["dynCall_v"]=function(){return(dynCall_v=Module["dynCall_v"]=Module["asm"]["ub"]).apply(null,arguments)};var dynCall_ii=Module["dynCall_ii"]=function(){return(dynCall_ii=Module["dynCall_ii"]=Module["asm"]["vb"]).apply(null,arguments)};Module["asm"]=asm;Module["cwrap"]=cwrap;Module["PThread"]=PThread;Module["PThread"]=PThread;Module["_pthread_self"]=_pthread_self;Module["wasmMemory"]=wasmMemory;Module["ExitStatus"]=ExitStatus;var calledRun;Module["then"]=function(func){if(calledRun){func(Module)}else{var old=Module["onRuntimeInitialized"];Module["onRuntimeInitialized"]=function(){if(old)old();func(Module)}}return Module};function ExitStatus(status){this.name="ExitStatus";this.message="Program terminated with exit("+status+")";this.status=status}dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function run(args){args=args||arguments_;if(runDependencies>0){return}preRun();if(runDependencies>0)return;function doRun(){if(calledRun)return;calledRun=true;Module["calledRun"]=true;if(ABORT)return;initRuntime();preMain();if(Module["onRuntimeInitialized"])Module["onRuntimeInitialized"]();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(function(){setTimeout(function(){Module["setStatus"]("")},1);doRun()},1)}else{doRun()}}Module["run"]=run;if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}if(!ENVIRONMENT_IS_PTHREAD)noExitRuntime=true;if(!ENVIRONMENT_IS_PTHREAD)run();return WasmBackendModuleThreadedSimd2}}();if(typeof exports2==="object"&&typeof module2==="object")module2.exports=WasmBackendModuleThreadedSimd;else if(typeof define==="function"&&define["amd"])define([],function(){return WasmBackendModuleThreadedSimd});else if(typeof exports2==="object")exports2["WasmBackendModuleThreadedSimd"]=WasmBackendModuleThreadedSimd});var require_tfjs_backend_wasm=__commonJS((exports2,module2)=>{var WasmBackendModule=function(){var _scriptDir=typeof document!=="undefined"&&document.currentScript?document.currentScript.src:void 0;if(typeof __filename!=="undefined")_scriptDir=_scriptDir||__filename;return function(WasmBackendModule2){WasmBackendModule2=WasmBackendModule2||{};var Module=typeof WasmBackendModule2!=="undefined"?WasmBackendModule2:{};var moduleOverrides={};var key;for(key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var arguments_=[];var thisProgram="./this.program";var quit_=function(status,toThrow){throw toThrow};var ENVIRONMENT_IS_WEB=false;var ENVIRONMENT_IS_WORKER=false;var ENVIRONMENT_IS_NODE=false;var ENVIRONMENT_IS_SHELL=false;ENVIRONMENT_IS_WEB=typeof window==="object";ENVIRONMENT_IS_WORKER=typeof importScripts==="function";ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string";ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary,setWindowTitle;var nodeFS;var nodePath;if(ENVIRONMENT_IS_NODE){if(ENVIRONMENT_IS_WORKER){scriptDirectory=require("path").dirname(scriptDirectory)+"/"}else{scriptDirectory=__dirname+"/"}read_=function shell_read(filename,binary){if(!nodeFS)nodeFS=require("fs");if(!nodePath)nodePath=require("path");filename=nodePath["normalize"](filename);return nodeFS["readFileSync"](filename,binary?null:"utf8")};readBinary=function readBinary2(filename){var ret=read_(filename,true);if(!ret.buffer){ret=new Uint8Array(ret)}assert(ret.buffer);return ret};if(process["argv"].length>1){thisProgram=process["argv"][1].replace(/\\/g,"/")}arguments_=process["argv"].slice(2);process["on"]("uncaughtException",function(ex){if(!(ex instanceof ExitStatus)){throw ex}});process["on"]("unhandledRejection",abort);quit_=function(status){process["exit"](status)};Module["inspect"]=function(){return"[Emscripten Module object]"}}else if(ENVIRONMENT_IS_SHELL){if(typeof read!="undefined"){read_=function shell_read(f){return read(f)}}readBinary=function readBinary2(f){var data2;if(typeof readbuffer==="function"){return new Uint8Array(readbuffer(f))}data2=read(f,"binary");assert(typeof data2==="object");return data2};if(typeof scriptArgs!="undefined"){arguments_=scriptArgs}else if(typeof arguments!="undefined"){arguments_=arguments}if(typeof quit==="function"){quit_=function(status){quit(status)}}if(typeof print!=="undefined"){if(typeof console==="undefined")console={};console.log=print;console.warn=console.error=typeof printErr!=="undefined"?printErr:print}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptDir){scriptDirectory=_scriptDir}if(scriptDirectory.indexOf("blob:")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.lastIndexOf("/")+1)}else{scriptDirectory=""}{read_=function shell_read(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText};if(ENVIRONMENT_IS_WORKER){readBinary=function readBinary2(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=function readAsync2(url,onload,onerror){var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=function xhr_onload(){if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()};xhr.onerror=onerror;xhr.send(null)}}setWindowTitle=function(title){document.title=title}}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.warn.bind(console);for(key in moduleOverrides){if(moduleOverrides.hasOwnProperty(key)){Module[key]=moduleOverrides[key]}}moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];var wasmBinary;if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];var noExitRuntime;if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(typeof WebAssembly!=="object"){err("no native wasm support detected")}var wasmMemory;var wasmTable=new WebAssembly.Table({initial:147,maximum:147+0,element:"anyfunc"});var ABORT=false;var EXITSTATUS=0;function assert(condition,text){if(!condition){abort("Assertion failed: "+text)}}function getCFunc(ident){var func=Module["_"+ident];assert(func,"Cannot call unknown function "+ident+", make sure it is exported");return func}function ccall(ident,returnType,argTypes,args,opts){var toC={string:function(str){var ret2=0;if(str!==null&&str!==void 0&&str!==0){var len=(str.length<<2)+1;ret2=stackAlloc(len);stringToUTF8(str,ret2,len)}return ret2},array:function(arr){var ret2=stackAlloc(arr.length);writeArrayToMemory(arr,ret2);return ret2}};function convertReturnValue(ret2){if(returnType==="string")return UTF8ToString(ret2);if(returnType==="boolean")return Boolean(ret2);return ret2}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i=endIdx))++endPtr;if(endPtr-idx>16&&heap.subarray&&UTF8Decoder){return UTF8Decoder.decode(heap.subarray(idx,endPtr))}else{var str="";while(idx>10,56320|ch&1023)}}}return str}function UTF8ToString(ptr,maxBytesToRead){return ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):""}function stringToUTF8Array(str,heap,outIdx,maxBytesToWrite){if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx}function stringToUTF8(str,outPtr,maxBytesToWrite){return stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite)}function writeArrayToMemory(array,buffer3){HEAP8.set(array,buffer3)}var buffer2,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateGlobalBufferAndViews(buf){buffer2=buf;Module["HEAP8"]=HEAP8=new Int8Array(buf);Module["HEAP16"]=HEAP16=new Int16Array(buf);Module["HEAP32"]=HEAP32=new Int32Array(buf);Module["HEAPU8"]=HEAPU8=new Uint8Array(buf);Module["HEAPU16"]=HEAPU16=new Uint16Array(buf);Module["HEAPU32"]=HEAPU32=new Uint32Array(buf);Module["HEAPF32"]=HEAPF32=new Float32Array(buf);Module["HEAPF64"]=HEAPF64=new Float64Array(buf)}var INITIAL_INITIAL_MEMORY=Module["INITIAL_MEMORY"]||16777216;function callRuntimeCallbacks(callbacks){while(callbacks.length>0){var callback=callbacks.shift();if(typeof callback=="function"){callback(Module);continue}var func=callback.func;if(typeof func==="number"){if(callback.arg===void 0){Module["dynCall_v"](func)}else{Module["dynCall_vi"](func,callback.arg)}}else{func(callback.arg===void 0?null:callback.arg)}}}var __ATPRERUN__=[];var __ATINIT__=[];var __ATMAIN__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;var runtimeExited=false;function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;callRuntimeCallbacks(__ATINIT__)}function preMain(){callRuntimeCallbacks(__ATMAIN__)}function exitRuntime(){runtimeExited=true}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var Math_ceil=Math.ceil;var Math_floor=Math.floor;var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function addRunDependency(id){runDependencies++;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}}function removeRunDependency(id){runDependencies--;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}Module["preloadedImages"]={};Module["preloadedAudios"]={};function abort(what){if(Module["onAbort"]){Module["onAbort"](what)}what+="";out(what);err(what);ABORT=true;EXITSTATUS=1;what="abort("+what+"). Build with -s ASSERTIONS=1 for more info.";throw new WebAssembly.RuntimeError(what)}function hasPrefix(str,prefix){return String.prototype.startsWith?str.startsWith(prefix):str.indexOf(prefix)===0}var dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(filename){return hasPrefix(filename,dataURIPrefix)}var fileURIPrefix="file://";function isFileURI(filename){return hasPrefix(filename,fileURIPrefix)}var wasmBinaryFile="tfjs-backend-wasm.wasm";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}function getBinary(){try{if(wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(wasmBinaryFile)}else{throw"both async and sync fetching of the wasm failed"}}catch(err2){abort(err2)}}function getBinaryPromise(){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)&&typeof fetch==="function"&&!isFileURI(wasmBinaryFile)){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){if(!response["ok"]){throw"failed to load wasm binary file at '"+wasmBinaryFile+"'"}return response["arrayBuffer"]()}).catch(function(){return getBinary()})}return new Promise(function(resolve,reject){resolve(getBinary())})}function createWasm(){var info={env:asmLibraryArg,wasi_snapshot_preview1:asmLibraryArg};function receiveInstance(instance,module3){var exports4=instance.exports;Module["asm"]=exports4;wasmMemory=exports4["memory"];updateGlobalBufferAndViews(wasmMemory.buffer);removeRunDependency("wasm-instantiate")}addRunDependency("wasm-instantiate");function receiveInstantiatedSource(output){receiveInstance(output["instance"])}function instantiateArrayBuffer(receiver){return getBinaryPromise().then(function(binary){return WebAssembly.instantiate(binary,info)}).then(receiver,function(reason){err("failed to asynchronously prepare wasm: "+reason);abort(reason)})}function instantiateAsync(){if(!wasmBinary&&typeof WebAssembly.instantiateStreaming==="function"&&!isDataURI(wasmBinaryFile)&&!isFileURI(wasmBinaryFile)&&typeof fetch==="function"){fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){var result=WebAssembly.instantiateStreaming(response,info);return result.then(receiveInstantiatedSource,function(reason){err("wasm streaming compile failed: "+reason);err("falling back to ArrayBuffer instantiation");instantiateArrayBuffer(receiveInstantiatedSource)})})}else{return instantiateArrayBuffer(receiveInstantiatedSource)}}if(Module["instantiateWasm"]){try{var exports3=Module["instantiateWasm"](info,receiveInstance);return exports3}catch(e){err("Module.instantiateWasm callback failed with error: "+e);return false}}instantiateAsync();return{}}__ATINIT__.push();function _emscripten_notify_memory_growth(memoryIndex){updateGlobalBufferAndViews(wasmMemory.buffer)}var PATH={splitPath:function(filename){var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return splitPathRe.exec(filename).slice(1)},normalizeArray:function(parts,allowAboveRoot){var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up;up--){parts.unshift("..")}}return parts},normalize:function(path){var isAbsolute=path.charAt(0)==="/",trailingSlash=path.substr(-1)==="/";path=PATH.normalizeArray(path.split("/").filter(function(p){return!!p}),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path},dirname:function(path){var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.substr(0,dir.length-1)}return root+dir},basename:function(path){if(path==="/")return"/";var lastSlash=path.lastIndexOf("/");if(lastSlash===-1)return path;return path.substr(lastSlash+1)},extname:function(path){return PATH.splitPath(path)[3]},join:function(){var paths=Array.prototype.slice.call(arguments,0);return PATH.normalize(paths.join("/"))},join2:function(l,r){return PATH.normalize(l+"/"+r)}};var SYSCALLS={mappings:{},buffers:[null,[],[]],printChar:function(stream,curr){var buffer3=SYSCALLS.buffers[stream];if(curr===0||curr===10){(stream===1?out:err)(UTF8ArrayToString(buffer3,0));buffer3.length=0}else{buffer3.push(curr)}},varargs:void 0,get:function(){SYSCALLS.varargs+=4;var ret=HEAP32[SYSCALLS.varargs-4>>2];return ret},getStr:function(ptr){var ret=UTF8ToString(ptr);return ret},get64:function(low,high){return low}};function _fd_close(fd){return 0}function _fd_seek(fd,offset_low,offset_high,whence,newOffset){}function _fd_write(fd,iov,iovcnt,pnum){var num=0;for(var i=0;i>2];var len=HEAP32[iov+(i*8+4)>>2];for(var j=0;j>2]=num;return 0}function _exit(status){exit(status)}function _proc_exit(code){_exit(code)}function _roundf(d){d=+d;return d>=0?+Math_floor(d+.5):+Math_ceil(d-.5)}var asmLibraryArg={emscripten_notify_memory_growth:_emscripten_notify_memory_growth,fd_close:_fd_close,fd_seek:_fd_seek,fd_write:_fd_write,proc_exit:_proc_exit,roundf:_roundf};var asm=createWasm();Module["asm"]=asm;var _init=Module["_init"]=function(){return(_init=Module["_init"]=Module["asm"]["init"]).apply(null,arguments)};var _register_tensor=Module["_register_tensor"]=function(){return(_register_tensor=Module["_register_tensor"]=Module["asm"]["register_tensor"]).apply(null,arguments)};var _dispose_data=Module["_dispose_data"]=function(){return(_dispose_data=Module["_dispose_data"]=Module["asm"]["dispose_data"]).apply(null,arguments)};var _dispose=Module["_dispose"]=function(){return(_dispose=Module["_dispose"]=Module["asm"]["dispose"]).apply(null,arguments)};var _Abs=Module["_Abs"]=function(){return(_Abs=Module["_Abs"]=Module["asm"]["Abs"]).apply(null,arguments)};var _Add=Module["_Add"]=function(){return(_Add=Module["_Add"]=Module["asm"]["Add"]).apply(null,arguments)};var _AddN=Module["_AddN"]=function(){return(_AddN=Module["_AddN"]=Module["asm"]["AddN"]).apply(null,arguments)};var _ArgMax=Module["_ArgMax"]=function(){return(_ArgMax=Module["_ArgMax"]=Module["asm"]["ArgMax"]).apply(null,arguments)};var _AvgPool=Module["_AvgPool"]=function(){return(_AvgPool=Module["_AvgPool"]=Module["asm"]["AvgPool"]).apply(null,arguments)};var _BatchMatMul=Module["_BatchMatMul"]=function(){return(_BatchMatMul=Module["_BatchMatMul"]=Module["asm"]["BatchMatMul"]).apply(null,arguments)};var _ClipByValue=Module["_ClipByValue"]=function(){return(_ClipByValue=Module["_ClipByValue"]=Module["asm"]["ClipByValue"]).apply(null,arguments)};var _Conv2D=Module["_Conv2D"]=function(){return(_Conv2D=Module["_Conv2D"]=Module["asm"]["Conv2D"]).apply(null,arguments)};var _Conv2DBackpropInput=Module["_Conv2DBackpropInput"]=function(){return(_Conv2DBackpropInput=Module["_Conv2DBackpropInput"]=Module["asm"]["Conv2DBackpropInput"]).apply(null,arguments)};var _Cos=Module["_Cos"]=function(){return(_Cos=Module["_Cos"]=Module["asm"]["Cos"]).apply(null,arguments)};var _CropAndResize=Module["_CropAndResize"]=function(){return(_CropAndResize=Module["_CropAndResize"]=Module["asm"]["CropAndResize"]).apply(null,arguments)};var _Cumsum=Module["_Cumsum"]=function(){return(_Cumsum=Module["_Cumsum"]=Module["asm"]["Cumsum"]).apply(null,arguments)};var _DepthToSpace=Module["_DepthToSpace"]=function(){return(_DepthToSpace=Module["_DepthToSpace"]=Module["asm"]["DepthToSpace"]).apply(null,arguments)};var _DepthwiseConv2dNative=Module["_DepthwiseConv2dNative"]=function(){return(_DepthwiseConv2dNative=Module["_DepthwiseConv2dNative"]=Module["asm"]["DepthwiseConv2dNative"]).apply(null,arguments)};var _Div=Module["_Div"]=function(){return(_Div=Module["_Div"]=Module["asm"]["Div"]).apply(null,arguments)};var _Equal=Module["_Equal"]=function(){return(_Equal=Module["_Equal"]=Module["asm"]["Equal"]).apply(null,arguments)};var _Exp=Module["_Exp"]=function(){return(_Exp=Module["_Exp"]=Module["asm"]["Exp"]).apply(null,arguments)};var _FlipLeftRight=Module["_FlipLeftRight"]=function(){return(_FlipLeftRight=Module["_FlipLeftRight"]=Module["asm"]["FlipLeftRight"]).apply(null,arguments)};var _FloorDiv=Module["_FloorDiv"]=function(){return(_FloorDiv=Module["_FloorDiv"]=Module["asm"]["FloorDiv"]).apply(null,arguments)};var _FusedBatchNorm=Module["_FusedBatchNorm"]=function(){return(_FusedBatchNorm=Module["_FusedBatchNorm"]=Module["asm"]["FusedBatchNorm"]).apply(null,arguments)};var _FusedConv2D=Module["_FusedConv2D"]=function(){return(_FusedConv2D=Module["_FusedConv2D"]=Module["asm"]["FusedConv2D"]).apply(null,arguments)};var _FusedDepthwiseConv2D=Module["_FusedDepthwiseConv2D"]=function(){return(_FusedDepthwiseConv2D=Module["_FusedDepthwiseConv2D"]=Module["asm"]["FusedDepthwiseConv2D"]).apply(null,arguments)};var _Gather=Module["_Gather"]=function(){return(_Gather=Module["_Gather"]=Module["asm"]["Gather"]).apply(null,arguments)};var _GatherNd=Module["_GatherNd"]=function(){return(_GatherNd=Module["_GatherNd"]=Module["asm"]["GatherNd"]).apply(null,arguments)};var _Greater=Module["_Greater"]=function(){return(_Greater=Module["_Greater"]=Module["asm"]["Greater"]).apply(null,arguments)};var _GreaterEqual=Module["_GreaterEqual"]=function(){return(_GreaterEqual=Module["_GreaterEqual"]=Module["asm"]["GreaterEqual"]).apply(null,arguments)};var _Less=Module["_Less"]=function(){return(_Less=Module["_Less"]=Module["asm"]["Less"]).apply(null,arguments)};var _LessEqual=Module["_LessEqual"]=function(){return(_LessEqual=Module["_LessEqual"]=Module["asm"]["LessEqual"]).apply(null,arguments)};var _Log=Module["_Log"]=function(){return(_Log=Module["_Log"]=Module["asm"]["Log"]).apply(null,arguments)};var _LogicalAnd=Module["_LogicalAnd"]=function(){return(_LogicalAnd=Module["_LogicalAnd"]=Module["asm"]["LogicalAnd"]).apply(null,arguments)};var _Max=Module["_Max"]=function(){return(_Max=Module["_Max"]=Module["asm"]["Max"]).apply(null,arguments)};var _MaxPool=Module["_MaxPool"]=function(){return(_MaxPool=Module["_MaxPool"]=Module["asm"]["MaxPool"]).apply(null,arguments)};var _Maximum=Module["_Maximum"]=function(){return(_Maximum=Module["_Maximum"]=Module["asm"]["Maximum"]).apply(null,arguments)};var _Min=Module["_Min"]=function(){return(_Min=Module["_Min"]=Module["asm"]["Min"]).apply(null,arguments)};var _Minimum=Module["_Minimum"]=function(){return(_Minimum=Module["_Minimum"]=Module["asm"]["Minimum"]).apply(null,arguments)};var _Multiply=Module["_Multiply"]=function(){return(_Multiply=Module["_Multiply"]=Module["asm"]["Multiply"]).apply(null,arguments)};var _Negate=Module["_Negate"]=function(){return(_Negate=Module["_Negate"]=Module["asm"]["Negate"]).apply(null,arguments)};var _NonMaxSuppressionV3=Module["_NonMaxSuppressionV3"]=function(){return(_NonMaxSuppressionV3=Module["_NonMaxSuppressionV3"]=Module["asm"]["NonMaxSuppressionV3"]).apply(null,arguments)};var _NonMaxSuppressionV4=Module["_NonMaxSuppressionV4"]=function(){return(_NonMaxSuppressionV4=Module["_NonMaxSuppressionV4"]=Module["asm"]["NonMaxSuppressionV4"]).apply(null,arguments)};var _NonMaxSuppressionV5=Module["_NonMaxSuppressionV5"]=function(){return(_NonMaxSuppressionV5=Module["_NonMaxSuppressionV5"]=Module["asm"]["NonMaxSuppressionV5"]).apply(null,arguments)};var _NotEqual=Module["_NotEqual"]=function(){return(_NotEqual=Module["_NotEqual"]=Module["asm"]["NotEqual"]).apply(null,arguments)};var _OneHot=Module["_OneHot"]=function(){return(_OneHot=Module["_OneHot"]=Module["asm"]["OneHot"]).apply(null,arguments)};var _PadV2=Module["_PadV2"]=function(){return(_PadV2=Module["_PadV2"]=Module["asm"]["PadV2"]).apply(null,arguments)};var _Pow=Module["_Pow"]=function(){return(_Pow=Module["_Pow"]=Module["asm"]["Pow"]).apply(null,arguments)};var _Prelu=Module["_Prelu"]=function(){return(_Prelu=Module["_Prelu"]=Module["asm"]["Prelu"]).apply(null,arguments)};var _Relu=Module["_Relu"]=function(){return(_Relu=Module["_Relu"]=Module["asm"]["Relu"]).apply(null,arguments)};var _Relu6=Module["_Relu6"]=function(){return(_Relu6=Module["_Relu6"]=Module["asm"]["Relu6"]).apply(null,arguments)};var _ResizeBilinear=Module["_ResizeBilinear"]=function(){return(_ResizeBilinear=Module["_ResizeBilinear"]=Module["asm"]["ResizeBilinear"]).apply(null,arguments)};var _Reverse=Module["_Reverse"]=function(){return(_Reverse=Module["_Reverse"]=Module["asm"]["Reverse"]).apply(null,arguments)};var _RotateWithOffset=Module["_RotateWithOffset"]=function(){return(_RotateWithOffset=Module["_RotateWithOffset"]=Module["asm"]["RotateWithOffset"]).apply(null,arguments)};var _Rsqrt=Module["_Rsqrt"]=function(){return(_Rsqrt=Module["_Rsqrt"]=Module["asm"]["Rsqrt"]).apply(null,arguments)};var _ScatterNd=Module["_ScatterNd"]=function(){return(_ScatterNd=Module["_ScatterNd"]=Module["asm"]["ScatterNd"]).apply(null,arguments)};var _SelectV2=Module["_SelectV2"]=function(){return(_SelectV2=Module["_SelectV2"]=Module["asm"]["SelectV2"]).apply(null,arguments)};var _Sigmoid=Module["_Sigmoid"]=function(){return(_Sigmoid=Module["_Sigmoid"]=Module["asm"]["Sigmoid"]).apply(null,arguments)};var _Sin=Module["_Sin"]=function(){return(_Sin=Module["_Sin"]=Module["asm"]["Sin"]).apply(null,arguments)};var _Softmax=Module["_Softmax"]=function(){return(_Softmax=Module["_Softmax"]=Module["asm"]["Softmax"]).apply(null,arguments)};var _Sqrt=Module["_Sqrt"]=function(){return(_Sqrt=Module["_Sqrt"]=Module["asm"]["Sqrt"]).apply(null,arguments)};var _Square=Module["_Square"]=function(){return(_Square=Module["_Square"]=Module["asm"]["Square"]).apply(null,arguments)};var _SquaredDifference=Module["_SquaredDifference"]=function(){return(_SquaredDifference=Module["_SquaredDifference"]=Module["asm"]["SquaredDifference"]).apply(null,arguments)};var _StridedSlice=Module["_StridedSlice"]=function(){return(_StridedSlice=Module["_StridedSlice"]=Module["asm"]["StridedSlice"]).apply(null,arguments)};var _Sub=Module["_Sub"]=function(){return(_Sub=Module["_Sub"]=Module["asm"]["Sub"]).apply(null,arguments)};var _Sum=Module["_Sum"]=function(){return(_Sum=Module["_Sum"]=Module["asm"]["Sum"]).apply(null,arguments)};var _Tanh=Module["_Tanh"]=function(){return(_Tanh=Module["_Tanh"]=Module["asm"]["Tanh"]).apply(null,arguments)};var _Tile=Module["_Tile"]=function(){return(_Tile=Module["_Tile"]=Module["asm"]["Tile"]).apply(null,arguments)};var _Transpose=Module["_Transpose"]=function(){return(_Transpose=Module["_Transpose"]=Module["asm"]["Transpose"]).apply(null,arguments)};var __FusedMatMul=Module["__FusedMatMul"]=function(){return(__FusedMatMul=Module["__FusedMatMul"]=Module["asm"]["_FusedMatMul"]).apply(null,arguments)};var _malloc=Module["_malloc"]=function(){return(_malloc=Module["_malloc"]=Module["asm"]["malloc"]).apply(null,arguments)};var _free=Module["_free"]=function(){return(_free=Module["_free"]=Module["asm"]["free"]).apply(null,arguments)};var __start=Module["__start"]=function(){return(__start=Module["__start"]=Module["asm"]["_start"]).apply(null,arguments)};var stackSave=Module["stackSave"]=function(){return(stackSave=Module["stackSave"]=Module["asm"]["stackSave"]).apply(null,arguments)};var stackAlloc=Module["stackAlloc"]=function(){return(stackAlloc=Module["stackAlloc"]=Module["asm"]["stackAlloc"]).apply(null,arguments)};var stackRestore=Module["stackRestore"]=function(){return(stackRestore=Module["stackRestore"]=Module["asm"]["stackRestore"]).apply(null,arguments)};Module["asm"]=asm;Module["cwrap"]=cwrap;var calledRun;Module["then"]=function(func){if(calledRun){func(Module)}else{var old=Module["onRuntimeInitialized"];Module["onRuntimeInitialized"]=function(){if(old)old();func(Module)}}return Module};function ExitStatus(status){this.name="ExitStatus";this.message="Program terminated with exit("+status+")";this.status=status}var calledMain=false;dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function callMain(args){var entryFunction=Module["__start"];try{entryFunction();var ret=0;exit(ret,true)}catch(e){if(e instanceof ExitStatus){return}else if(e=="unwind"){noExitRuntime=true;return}else{var toLog=e;if(e&&typeof e==="object"&&e.stack){toLog=[e,e.stack]}err("exception thrown: "+toLog);quit_(1,e)}}finally{calledMain=true}}function run(args){args=args||arguments_;if(runDependencies>0){return}preRun();if(runDependencies>0)return;function doRun(){if(calledRun)return;calledRun=true;Module["calledRun"]=true;if(ABORT)return;initRuntime();preMain();if(Module["onRuntimeInitialized"])Module["onRuntimeInitialized"]();if(shouldRunNow)callMain(args);postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(function(){setTimeout(function(){Module["setStatus"]("")},1);doRun()},1)}else{doRun()}}Module["run"]=run;function exit(status,implicit){if(implicit&&noExitRuntime&&status===0){return}if(noExitRuntime){}else{ABORT=true;EXITSTATUS=status;exitRuntime();if(Module["onExit"])Module["onExit"](status)}quit_(status,new ExitStatus(status))}if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}var shouldRunNow=true;if(Module["noInitialRun"])shouldRunNow=false;noExitRuntime=true;run();return WasmBackendModule2}}();if(typeof exports2==="object"&&typeof module2==="object")module2.exports=WasmBackendModule;else if(typeof define==="function"&&define["amd"])define([],function(){return WasmBackendModule});else if(typeof exports2==="object")exports2["WasmBackendModule"]=WasmBackendModule});var require_blazeface=__commonJS(exports2=>{const NUM_LANDMARKS=6;function generateAnchors(inputSize){const spec={strides:[inputSize/16,inputSize/8],anchors:[2,6]};const anchors=[];for(let i=0;i{box.startEndTensor.dispose();box.startPoint.dispose();box.endPoint.dispose()};const createBox=startEndTensor=>({startEndTensor,startPoint:tf.slice(startEndTensor,[0,0],[-1,2]),endPoint:tf.slice(startEndTensor,[0,2],[-1,2])});const scaleBox=(box,factors)=>{const starts=tf.mul(box.startPoint,factors);const ends=tf.mul(box.endPoint,factors);const newCoordinates=tf.concat2d([starts,ends],1);return createBox(newCoordinates)};function decodeBounds(boxOutputs,anchors,inputSize){const boxStarts=tf.slice(boxOutputs,[0,1],[-1,2]);const centers=tf.add(boxStarts,anchors);const boxSizes=tf.slice(boxOutputs,[0,3],[-1,2]);const boxSizesNormalized=tf.div(boxSizes,inputSize);const centersNormalized=tf.div(centers,inputSize);const halfBoxSize=tf.div(boxSizesNormalized,2);const starts=tf.sub(centersNormalized,halfBoxSize);const ends=tf.add(centersNormalized,halfBoxSize);const startNormalized=tf.mul(starts,inputSize);const endNormalized=tf.mul(ends,inputSize);const concatAxis=1;return tf.concat2d([startNormalized,endNormalized],concatAxis)}function scaleBoxFromPrediction(face2,scaleFactor){return tf.tidy(()=>{const box=face2["box"]?face2["box"]:face2;return scaleBox(box,scaleFactor).startEndTensor.squeeze()})}class BlazeFaceModel{constructor(model,config2){this.blazeFaceModel=model;this.width=config2.detector.inputSize;this.height=config2.detector.inputSize;this.anchorsData=generateAnchors(config2.detector.inputSize);this.anchors=tf.tensor2d(this.anchorsData);this.inputSize=tf.tensor1d([this.width,this.height]);this.config=config2;this.scaleFaces=.8}async getBoundingBoxes(inputImage){if(!inputImage||inputImage.isDisposedInternal||inputImage.shape.length!==4||inputImage.shape[1]<1||inputImage.shape[2]<1)return null;const[detectedOutputs,boxes,scores]=tf.tidy(()=>{const resizedImage=inputImage.resizeBilinear([this.width,this.height]);const normalizedImage=tf.sub(resizedImage.div(127.5),1);const batchedPrediction=this.blazeFaceModel.predict(normalizedImage);let prediction;if(Array.isArray(batchedPrediction)){const sorted=batchedPrediction.sort((a,b)=>a.size-b.size);const concat384=tf.concat([sorted[0],sorted[2]],2);const concat512=tf.concat([sorted[1],sorted[3]],2);const concat2=tf.concat([concat512,concat384],1);prediction=concat2.squeeze(0)}else{prediction=batchedPrediction.squeeze()}const decodedBounds=decodeBounds(prediction,this.anchors,this.inputSize);const logits=tf.slice(prediction,[0,0],[-1,1]);const scoresOut=tf.sigmoid(logits).squeeze();return[prediction,decodedBounds,scoresOut]});const boxIndicesTensor=await tf.image.nonMaxSuppressionAsync(boxes,scores,this.config.detector.maxFaces,this.config.detector.iouThreshold,this.config.detector.scoreThreshold);const boxIndices=boxIndicesTensor.arraySync();boxIndicesTensor.dispose();const boundingBoxesMap=boxIndices.map(boxIndex=>tf.slice(boxes,[boxIndex,0],[1,-1]));const boundingBoxes=boundingBoxesMap.map(boundingBox=>{const vals=boundingBox.arraySync();boundingBox.dispose();return vals});const scoresVal=scores.dataSync();const annotatedBoxes=[];for(const i in boundingBoxes){const boxIndex=boxIndices[i];const confidence=scoresVal[boxIndex];if(confidence>this.config.detector.minConfidence){const box=createBox(boundingBoxes[i]);const anchor=this.anchorsData[boxIndex];const landmarks=tf.tidy(()=>tf.slice(detectedOutputs,[boxIndex,NUM_LANDMARKS-1],[1,-1]).squeeze().reshape([NUM_LANDMARKS,-1]));annotatedBoxes.push({box,landmarks,anchor,confidence})}}detectedOutputs.dispose();boxes.dispose();scores.dispose();detectedOutputs.dispose();return{boxes:annotatedBoxes,scaleFactor:[inputImage.shape[2]/this.width,inputImage.shape[1]/this.height]}}async estimateFaces(input){const{boxes,scaleFactor}=await this.getBoundingBoxes(input);const faces=[];for(const face2 of boxes){const landmarkData=face2.landmarks.arraySync();const scaledBox=scaleBoxFromPrediction(face2,scaleFactor);const boxData=scaleBox.arraySync();const probabilityData=face2.probability.arraySync();const anchor=face2.anchor;const[scaleFactorX,scaleFactorY]=scaleFactor;const scaledLandmarks=landmarkData.map(landmark=>[(landmark[0]+anchor[0])*scaleFactorX,(landmark[1]+anchor[1])*scaleFactorY]);const normalizedFace={topLeft:boxData.slice(0,2),bottomRight:boxData.slice(2),landmarks:scaledLandmarks,probability:probabilityData};disposeBox(face2.box);face2.landmarks.dispose();face2.probability.dispose();scaledBox.dispose();faces.push(normalizedFace)}return faces}}async function load2(config2){const blazeface=await tf.loadGraphModel(config2.detector.modelPath,{fromTFHub:config2.detector.modelPath.includes("tfhub.dev")});const model=new BlazeFaceModel(blazeface,config2);console.log(`Human: load model: ${config2.detector.modelPath.match(/\/(.*)\./)[1]}`);return model}exports2.load=load2;exports2.BlazeFaceModel=BlazeFaceModel;exports2.disposeBox=disposeBox});var require_box=__commonJS(exports2=>{function scaleBoxCoordinates2(box,factor){const startPoint=[box.startPoint[0]*factor[0],box.startPoint[1]*factor[1]];const endPoint=[box.endPoint[0]*factor[0],box.endPoint[1]*factor[1]];return{startPoint,endPoint}}exports2.scaleBoxCoordinates=scaleBoxCoordinates2;function getBoxSize2(box){return[Math.abs(box.endPoint[0]-box.startPoint[0]),Math.abs(box.endPoint[1]-box.startPoint[1])]}exports2.getBoxSize=getBoxSize2;function getBoxCenter2(box){return[box.startPoint[0]+(box.endPoint[0]-box.startPoint[0])/2,box.startPoint[1]+(box.endPoint[1]-box.startPoint[1])/2]}exports2.getBoxCenter=getBoxCenter2;function cutBoxFromImageAndResize2(box,image2,cropSize){const h=image2.shape[1];const w=image2.shape[2];const boxes=[[box.startPoint[1]/h,box.startPoint[0]/w,box.endPoint[1]/h,box.endPoint[0]/w]];return tf.image.cropAndResize(image2,boxes,[0],cropSize)}exports2.cutBoxFromImageAndResize=cutBoxFromImageAndResize2;function enlargeBox2(box,factor=1.5){const center=getBoxCenter2(box);const size=getBoxSize2(box);const newHalfSize=[factor*size[0]/2,factor*size[1]/2];const startPoint=[center[0]-newHalfSize[0],center[1]-newHalfSize[1]];const endPoint=[center[0]+newHalfSize[0],center[1]+newHalfSize[1]];return{startPoint,endPoint,landmarks:box.landmarks}}exports2.enlargeBox=enlargeBox2;function squarifyBox2(box){const centers=getBoxCenter2(box);const size=getBoxSize2(box);const maxEdge=Math.max(...size);const halfSize=maxEdge/2;const startPoint=[centers[0]-halfSize,centers[1]-halfSize];const endPoint=[centers[0]+halfSize,centers[1]+halfSize];return{startPoint,endPoint,landmarks:box.landmarks}}exports2.squarifyBox=squarifyBox2});var require_util=__commonJS(exports2=>{exports2.IDENTITY_MATRIX=[[1,0,0],[0,1,0],[0,0,1]];function normalizeRadians2(angle){return angle-2*Math.PI*Math.floor((angle+Math.PI)/(2*Math.PI))}exports2.normalizeRadians=normalizeRadians2;function computeRotation2(point1,point2){const radians=Math.PI/2-Math.atan2(-(point2[1]-point1[1]),point2[0]-point1[0]);return normalizeRadians2(radians)}exports2.computeRotation=computeRotation2;function radToDegrees(rad){return rad*180/Math.PI}exports2.radToDegrees=radToDegrees;function buildTranslationMatrix2(x,y){return[[1,0,x],[0,1,y],[0,0,1]]}function dot2(v1,v2){let product=0;for(let i=0;i{const MESH_ANNOTATIONS={silhouette:[10,338,297,332,284,251,389,356,454,323,361,288,397,365,379,378,400,377,152,148,176,149,150,136,172,58,132,93,234,127,162,21,54,103,67,109],lipsUpperOuter:[61,185,40,39,37,0,267,269,270,409,291],lipsLowerOuter:[146,91,181,84,17,314,405,321,375,291],lipsUpperInner:[78,191,80,81,82,13,312,311,310,415,308],lipsLowerInner:[78,95,88,178,87,14,317,402,318,324,308],rightEyeUpper0:[246,161,160,159,158,157,173],rightEyeLower0:[33,7,163,144,145,153,154,155,133],rightEyeUpper1:[247,30,29,27,28,56,190],rightEyeLower1:[130,25,110,24,23,22,26,112,243],rightEyeUpper2:[113,225,224,223,222,221,189],rightEyeLower2:[226,31,228,229,230,231,232,233,244],rightEyeLower3:[143,111,117,118,119,120,121,128,245],rightEyebrowUpper:[156,70,63,105,66,107,55,193],rightEyebrowLower:[35,124,46,53,52,65],rightEyeIris:[473,474,475,476,477],leftEyeUpper0:[466,388,387,386,385,384,398],leftEyeLower0:[263,249,390,373,374,380,381,382,362],leftEyeUpper1:[467,260,259,257,258,286,414],leftEyeLower1:[359,255,339,254,253,252,256,341,463],leftEyeUpper2:[342,445,444,443,442,441,413],leftEyeLower2:[446,261,448,449,450,451,452,453,464],leftEyeLower3:[372,340,346,347,348,349,350,357,465],leftEyebrowUpper:[383,300,293,334,296,336,285,417],leftEyebrowLower:[265,353,276,283,282,295],leftEyeIris:[468,469,470,471,472],midwayBetweenEyes:[168],noseTip:[1],noseBottom:[2],noseRightCorner:[98],noseLeftCorner:[327],rightCheek:[205],leftCheek:[425]};const MESH_TO_IRIS_INDICES_MAP=[{key:"EyeUpper0",indices:[9,10,11,12,13,14,15]},{key:"EyeUpper1",indices:[25,26,27,28,29,30,31]},{key:"EyeUpper2",indices:[41,42,43,44,45,46,47]},{key:"EyeLower0",indices:[0,1,2,3,4,5,6,7,8]},{key:"EyeLower1",indices:[16,17,18,19,20,21,22,23,24]},{key:"EyeLower2",indices:[32,33,34,35,36,37,38,39,40]},{key:"EyeLower3",indices:[54,55,56,57,58,59,60,61,62]},{key:"EyebrowUpper",indices:[63,64,65,66,67,68,69,70]},{key:"EyebrowLower",indices:[48,49,50,51,52,53]}];const UV468=[[.499976992607117,.652534008026123],[.500025987625122,.547487020492554],[.499974012374878,.602371990680695],[.482113003730774,.471979022026062],[.500150978565216,.527155995368958],[.499909996986389,.498252987861633],[.499523013830185,.40106201171875],[.289712011814117,.380764007568359],[.499954998493195,.312398016452789],[.499987006187439,.269918978214264],[.500023007392883,.107050001621246],[.500023007392883,.666234016418457],[.5000159740448,.679224014282227],[.500023007392883,.692348003387451],[.499976992607117,.695277988910675],[.499976992607117,.70593398809433],[.499976992607117,.719385027885437],[.499976992607117,.737019002437592],[.499967992305756,.781370997428894],[.499816000461578,.562981009483337],[.473773002624512,.573909997940063],[.104906998574734,.254140973091125],[.365929991006851,.409575998783112],[.338757991790771,.41302502155304],[.311120003461838,.409460008144379],[.274657994508743,.389131009578705],[.393361985683441,.403706014156342],[.345234006643295,.344011008739471],[.370094001293182,.346076011657715],[.319321990013123,.347265005111694],[.297903001308441,.353591024875641],[.24779200553894,.410809993743896],[.396889001131058,.842755019664764],[.280097991228104,.375599980354309],[.106310002505779,.399955987930298],[.2099249958992,.391353011131287],[.355807989835739,.534406006336212],[.471751004457474,.65040397644043],[.474155008792877,.680191993713379],[.439785003662109,.657229006290436],[.414617002010345,.66654098033905],[.450374007225037,.680860996246338],[.428770989179611,.682690978050232],[.374971002340317,.727805018424988],[.486716985702515,.547628998756409],[.485300987958908,.527395009994507],[.257764995098114,.314490020275116],[.401223003864288,.455172002315521],[.429818987846375,.548614978790283],[.421351999044418,.533740997314453],[.276895999908447,.532056987285614],[.483370006084442,.499586999416351],[.33721199631691,.282882988452911],[.296391993761063,.293242990970612],[.169294998049736,.193813979625702],[.447580009698868,.302609980106354],[.392390012741089,.353887975215912],[.354490011930466,.696784019470215],[.067304998636246,.730105042457581],[.442739009857178,.572826027870178],[.457098007202148,.584792017936707],[.381974011659622,.694710969924927],[.392388999462128,.694203019142151],[.277076005935669,.271932005882263],[.422551989555359,.563233017921448],[.385919004678726,.281364023685455],[.383103013038635,.255840003490448],[.331431001424789,.119714021682739],[.229923993349075,.232002973556519],[.364500999450684,.189113974571228],[.229622006416321,.299540996551514],[.173287004232407,.278747975826263],[.472878992557526,.666198015213013],[.446828007698059,.668527007102966],[.422762006521225,.673889994621277],[.445307999849319,.580065965652466],[.388103008270264,.693961024284363],[.403039008378983,.706539988517761],[.403629004955292,.693953037261963],[.460041999816895,.557139039039612],[.431158006191254,.692366003990173],[.452181994915009,.692366003990173],[.475387006998062,.692366003990173],[.465828001499176,.779190003871918],[.472328990697861,.736225962638855],[.473087012767792,.717857003211975],[.473122000694275,.704625964164734],[.473033010959625,.695277988910675],[.427942007780075,.695277988910675],[.426479011774063,.703539967536926],[.423162013292313,.711845993995667],[.4183090031147,.720062971115112],[.390094995498657,.639572978019714],[.013953999616206,.560034036636353],[.499913990497589,.58014702796936],[.413199990987778,.69539999961853],[.409626007080078,.701822996139526],[.468080013990402,.601534962654114],[.422728985548019,.585985004901886],[.463079988956451,.593783974647522],[.37211999297142,.47341400384903],[.334562003612518,.496073007583618],[.411671012639999,.546965003013611],[.242175996303558,.14767599105835],[.290776997804642,.201445996761322],[.327338010072708,.256527006626129],[.399509996175766,.748921036720276],[.441727995872498,.261676013469696],[.429764986038208,.187834024429321],[.412198007106781,.108901023864746],[.288955003023148,.398952007293701],[.218936994671822,.435410976409912],[.41278201341629,.398970007896423],[.257135003805161,.355440020561218],[.427684992551804,.437960982322693],[.448339998722076,.536936044692993],[.178560003638268,.45755398273468],[.247308000922203,.457193970680237],[.286267012357712,.467674970626831],[.332827985286713,.460712015628815],[.368755996227264,.447206974029541],[.398963987827301,.432654976844788],[.476410001516342,.405806005001068],[.189241006970406,.523923993110657],[.228962004184723,.348950982093811],[.490725994110107,.562400996685028],[.404670000076294,.485132992267609],[.019469000399113,.401564002037048],[.426243007183075,.420431017875671],[.396993011236191,.548797011375427],[.266469985246658,.376977026462555],[.439121007919312,.51895797252655],[.032313998788595,.644356966018677],[.419054001569748,.387154996395111],[.462783008813858,.505746960639954],[.238978996872902,.779744982719421],[.198220998048782,.831938028335571],[.107550002634525,.540755033493042],[.183610007166862,.740257024765015],[.134409993886948,.333683013916016],[.385764002799988,.883153975009918],[.490967005491257,.579378008842468],[.382384985685349,.508572995662689],[.174399003386497,.397670984268188],[.318785011768341,.39623498916626],[.343364000320435,.400596976280212],[.396100014448166,.710216999053955],[.187885001301765,.588537991046906],[.430987000465393,.944064974784851],[.318993002176285,.898285031318665],[.266247987747192,.869701027870178],[.500023007392883,.190576016902924],[.499976992607117,.954452991485596],[.366169989109039,.398822009563446],[.393207013607025,.39553701877594],[.410373002290726,.391080021858215],[.194993004202843,.342101991176605],[.388664990663528,.362284004688263],[.365961998701096,.355970978736877],[.343364000320435,.355356991291046],[.318785011768341,.35834002494812],[.301414996385574,.363156020641327],[.058132998645306,.319076001644135],[.301414996385574,.387449026107788],[.499987989664078,.618434011936188],[.415838003158569,.624195992946625],[.445681989192963,.566076993942261],[.465844005346298,.620640993118286],[.49992299079895,.351523995399475],[.288718998432159,.819945991039276],[.335278987884521,.852819979190826],[.440512001514435,.902418971061707],[.128294005990028,.791940987110138],[.408771991729736,.373893976211548],[.455606997013092,.451801002025604],[.499877005815506,.908990025520325],[.375436991453171,.924192011356354],[.11421000212431,.615022003650665],[.448662012815475,.695277988910675],[.4480200111866,.704632043838501],[.447111994028091,.715808033943176],[.444831997156143,.730794012546539],[.430011987686157,.766808986663818],[.406787008047104,.685672998428345],[.400738000869751,.681069016456604],[.392399996519089,.677703022956848],[.367855995893478,.663918972015381],[.247923001646996,.601333022117615],[.452769994735718,.420849978923798],[.43639200925827,.359887003898621],[.416164010763168,.368713974952698],[.413385987281799,.692366003990173],[.228018000721931,.683571994304657],[.468268007040024,.352671027183533],[.411361992359161,.804327011108398],[.499989002943039,.469825029373169],[.479153990745544,.442654013633728],[.499974012374878,.439637005329132],[.432112008333206,.493588984012604],[.499886006116867,.866917014122009],[.49991300702095,.821729004383087],[.456548988819122,.819200992584229],[.344549000263214,.745438992977142],[.37890899181366,.574010014533997],[.374292999505997,.780184984207153],[.319687992334366,.570737957954407],[.357154995203018,.604269981384277],[.295284003019333,.621580958366394],[.447750002145767,.862477004528046],[.410986006259918,.508723020553589],[.31395098567009,.775308012962341],[.354128003120422,.812552988529205],[.324548006057739,.703992962837219],[.189096003770828,.646299958229065],[.279776990413666,.71465802192688],[.1338230073452,.682700991630554],[.336768001317978,.644733011722565],[.429883986711502,.466521978378296],[.455527991056442,.548622965812683],[.437114000320435,.558896005153656],[.467287987470627,.529924988746643],[.414712011814117,.335219979286194],[.37704598903656,.322777986526489],[.344107985496521,.320150971412659],[.312875986099243,.32233202457428],[.283526003360748,.333190023899078],[.241245999932289,.382785975933075],[.102986000478268,.468762993812561],[.267612010240555,.424560010433197],[.297879010438919,.433175981044769],[.333433985710144,.433878004550934],[.366427004337311,.426115989685059],[.396012008190155,.416696012020111],[.420121014118195,.41022801399231],[.007561000064015,.480777025222778],[.432949006557465,.569517970085144],[.458638995885849,.479089021682739],[.473466008901596,.545744001865387],[.476087987422943,.563830018043518],[.468472003936768,.555056989192963],[.433990985155106,.582361996173859],[.483518004417419,.562983989715576],[.482482999563217,.57784903049469],[.42645001411438,.389798998832703],[.438998997211456,.39649498462677],[.450067013502121,.400434017181396],[.289712011814117,.368252992630005],[.276670008897781,.363372981548309],[.517862021923065,.471948027610779],[.710287988185883,.380764007568359],[.526226997375488,.573909997940063],[.895093023777008,.254140973091125],[.634069979190826,.409575998783112],[.661242008209229,.41302502155304],[.688880026340485,.409460008144379],[.725341975688934,.389131009578705],[.606630027294159,.40370500087738],[.654766023159027,.344011008739471],[.629905998706818,.346076011657715],[.680678009986877,.347265005111694],[.702096998691559,.353591024875641],[.75221198797226,.410804986953735],[.602918028831482,.842862963676453],[.719901978969574,.375599980354309],[.893692970275879,.399959981441498],[.790081977844238,.391354024410248],[.643998026847839,.534487962722778],[.528249025344849,.65040397644043],[.525849997997284,.680191040039062],[.560214996337891,.657229006290436],[.585384011268616,.66654098033905],[.549625992774963,.680860996246338],[.57122802734375,.682691991329193],[.624852001667023,.72809898853302],[.513050019741058,.547281980514526],[.51509702205658,.527251958847046],[.742246985435486,.314507007598877],[.598631024360657,.454979002475739],[.570338010787964,.548575043678284],[.578631997108459,.533622980117798],[.723087012767792,.532054007053375],[.516445994377136,.499638974666595],[.662801027297974,.282917976379395],[.70362401008606,.293271005153656],[.830704987049103,.193813979625702],[.552385985851288,.302568018436432],[.607609987258911,.353887975215912],[.645429015159607,.696707010269165],[.932694971561432,.730105042457581],[.557260990142822,.572826027870178],[.542901992797852,.584792017936707],[.6180260181427,.694710969924927],[.607590973377228,.694203019142151],[.722943007946014,.271963000297546],[.577413976192474,.563166975975037],[.614082992076874,.281386971473694],[.616907000541687,.255886018276215],[.668509006500244,.119913995265961],[.770092010498047,.232020974159241],[.635536015033722,.189248979091644],[.77039098739624,.299556016921997],[.826722025871277,.278755009174347],[.527121007442474,.666198015213013],[.553171992301941,.668527007102966],[.577238023281097,.673889994621277],[.554691970348358,.580065965652466],[.611896991729736,.693961024284363],[.59696102142334,.706539988517761],[.596370995044708,.693953037261963],[.539958000183105,.557139039039612],[.568841993808746,.692366003990173],[.547818005084991,.692366003990173],[.52461302280426,.692366003990173],[.534089982509613,.779141008853912],[.527670979499817,.736225962638855],[.526912987232208,.717857003211975],[.526877999305725,.704625964164734],[.526966989040375,.695277988910675],[.572058022022247,.695277988910675],[.573521018028259,.703539967536926],[.57683801651001,.711845993995667],[.581691026687622,.720062971115112],[.609944999217987,.639909982681274],[.986046016216278,.560034036636353],[.5867999792099,.69539999961853],[.590372025966644,.701822996139526],[.531915009021759,.601536989212036],[.577268004417419,.585934996604919],[.536915004253387,.593786001205444],[.627542972564697,.473352015018463],[.665585994720459,.495950996875763],[.588353991508484,.546862006187439],[.757824003696442,.14767599105835],[.709249973297119,.201507985591888],[.672684013843536,.256581008434296],[.600408971309662,.74900496006012],[.55826598405838,.261672019958496],[.570303976535797,.187870979309082],[.588165998458862,.109044015407562],[.711045026779175,.398952007293701],[.781069993972778,.435405015945435],[.587247014045715,.398931980133057],[.742869973182678,.355445981025696],[.572156012058258,.437651991844177],[.55186802148819,.536570012569427],[.821442008018494,.457556009292603],[.752701997756958,.457181990146637],[.71375697851181,.467626988887787],[.66711300611496,.460672974586487],[.631101012229919,.447153985500336],[.6008620262146,.432473003864288],[.523481011390686,.405627012252808],[.810747981071472,.523926019668579],[.771045982837677,.348959028720856],[.509127020835876,.562718033790588],[.595292985439301,.485023975372314],[.980530977249146,.401564002037048],[.573499977588654,.420000016689301],[.602994978427887,.548687994480133],[.733529984951019,.376977026462555],[.560611009597778,.519016981124878],[.967685997486115,.644356966018677],[.580985009670258,.387160003185272],[.537728011608124,.505385041236877],[.760966002941132,.779752969741821],[.801778972148895,.831938028335571],[.892440974712372,.54076099395752],[.816350996494293,.740260004997253],[.865594983100891,.333687007427216],[.614073991775513,.883246004581451],[.508952975273132,.579437971115112],[.617941975593567,.508316040039062],[.825608015060425,.397674977779388],[.681214988231659,.39623498916626],[.656635999679565,.400596976280212],[.603900015354156,.710216999053955],[.81208598613739,.588539004325867],[.56801301240921,.944564998149872],[.681007981300354,.898285031318665],[.733752012252808,.869701027870178],[.633830010890961,.398822009563446],[.606792986392975,.39553701877594],[.589659988880157,.391062021255493],[.805015981197357,.342108011245728],[.611334979534149,.362284004688263],[.634037971496582,.355970978736877],[.656635999679565,.355356991291046],[.681214988231659,.35834002494812],[.698584973812103,.363156020641327],[.941866993904114,.319076001644135],[.698584973812103,.387449026107788],[.584177017211914,.624107003211975],[.554318010807037,.566076993942261],[.534153997898102,.62064003944397],[.711217999458313,.819975018501282],[.664629995822906,.852871000766754],[.559099972248077,.902631998062134],[.871706008911133,.791940987110138],[.591234028339386,.373893976211548],[.544341027736664,.451583981513977],[.624562978744507,.924192011356354],[.88577002286911,.615028977394104],[.551338016986847,.695277988910675],[.551980018615723,.704632043838501],[.552887976169586,.715808033943176],[.555167973041534,.730794012546539],[.569944024085999,.767035007476807],[.593203008174896,.685675978660583],[.599261999130249,.681069016456604],[.607599973678589,.677703022956848],[.631937980651855,.663500010967255],[.752032995223999,.601315021514893],[.547226011753082,.420395016670227],[.563543975353241,.359827995300293],[.583841025829315,.368713974952698],[.586614012718201,.692366003990173],[.771915018558502,.683578014373779],[.531597018241882,.352482974529266],[.588370978832245,.804440975189209],[.52079701423645,.442565023899078],[.567984998226166,.493479013442993],[.543282985687256,.819254994392395],[.655317008495331,.745514988899231],[.621008992195129,.574018001556396],[.625559985637665,.78031200170517],[.680198013782501,.570719003677368],[.64276397228241,.604337990283966],[.704662978649139,.621529996395111],[.552012026309967,.862591981887817],[.589071989059448,.508637011051178],[.685944974422455,.775357007980347],[.645735025405884,.812640011310577],[.675342977046967,.703978002071381],[.810858011245728,.646304965019226],[.72012197971344,.714666962623596],[.866151988506317,.682704985141754],[.663187026977539,.644596993923187],[.570082008838654,.466325998306274],[.544561982154846,.548375964164734],[.562758982181549,.558784961700439],[.531987011432648,.530140042304993],[.585271000862122,.335177004337311],[.622952997684479,.32277899980545],[.655896008014679,.320163011550903],[.687132000923157,.322345972061157],[.716481983661652,.333200991153717],[.758756995201111,.382786989212036],[.897013008594513,.468769013881683],[.732392013072968,.424547016620636],[.70211398601532,.433162987232208],[.66652500629425,.433866024017334],[.633504986763,.426087975502014],[.603875994682312,.416586995124817],[.579657971858978,.409945011138916],[.992439985275269,.480777025222778],[.567192018032074,.569419980049133],[.54136598110199,.478899002075195],[.526564002037048,.546118021011353],[.523913025856018,.563830018043518],[.531529009342194,.555056989192963],[.566035985946655,.582329034805298],[.51631098985672,.563053965568542],[.5174720287323,.577877044677734],[.573594987392426,.389806985855103],[.560697972774506,.395331978797913],[.549755990505219,.399751007556915],[.710287988185883,.368252992630005],[.723330020904541,.363372981548309]];const TRI468=[127,34,139,11,0,37,232,231,120,72,37,39,128,121,47,232,121,128,104,69,67,175,171,148,157,154,155,118,50,101,73,39,40,9,151,108,48,115,131,194,204,211,74,40,185,80,42,183,40,92,186,230,229,118,202,212,214,83,18,17,76,61,146,160,29,30,56,157,173,106,204,194,135,214,192,203,165,98,21,71,68,51,45,4,144,24,23,77,146,91,205,50,187,201,200,18,91,106,182,90,91,181,85,84,17,206,203,36,148,171,140,92,40,39,193,189,244,159,158,28,247,246,161,236,3,196,54,68,104,193,168,8,117,228,31,189,193,55,98,97,99,126,47,100,166,79,218,155,154,26,209,49,131,135,136,150,47,126,217,223,52,53,45,51,134,211,170,140,67,69,108,43,106,91,230,119,120,226,130,247,63,53,52,238,20,242,46,70,156,78,62,96,46,53,63,143,34,227,173,155,133,123,117,111,44,125,19,236,134,51,216,206,205,154,153,22,39,37,167,200,201,208,36,142,100,57,212,202,20,60,99,28,158,157,35,226,113,160,159,27,204,202,210,113,225,46,43,202,204,62,76,77,137,123,116,41,38,72,203,129,142,64,98,240,49,102,64,41,73,74,212,216,207,42,74,184,169,170,211,170,149,176,105,66,69,122,6,168,123,147,187,96,77,90,65,55,107,89,90,180,101,100,120,63,105,104,93,137,227,15,86,85,129,102,49,14,87,86,55,8,9,100,47,121,145,23,22,88,89,179,6,122,196,88,95,96,138,172,136,215,58,172,115,48,219,42,80,81,195,3,51,43,146,61,171,175,199,81,82,38,53,46,225,144,163,110,246,33,7,52,65,66,229,228,117,34,127,234,107,108,69,109,108,151,48,64,235,62,78,191,129,209,126,111,35,143,163,161,246,117,123,50,222,65,52,19,125,141,221,55,65,3,195,197,25,7,33,220,237,44,70,71,139,122,193,245,247,130,33,71,21,162,153,158,159,170,169,150,188,174,196,216,186,92,144,160,161,2,97,167,141,125,241,164,167,37,72,38,12,145,159,160,38,82,13,63,68,71,226,35,111,158,153,154,101,50,205,206,92,165,209,198,217,165,167,97,220,115,218,133,112,243,239,238,241,214,135,169,190,173,133,171,208,32,125,44,237,86,87,178,85,86,179,84,85,180,83,84,181,201,83,182,137,93,132,76,62,183,61,76,184,57,61,185,212,57,186,214,207,187,34,143,156,79,239,237,123,137,177,44,1,4,201,194,32,64,102,129,213,215,138,59,166,219,242,99,97,2,94,141,75,59,235,24,110,228,25,130,226,23,24,229,22,23,230,26,22,231,112,26,232,189,190,243,221,56,190,28,56,221,27,28,222,29,27,223,30,29,224,247,30,225,238,79,20,166,59,75,60,75,240,147,177,215,20,79,166,187,147,213,112,233,244,233,128,245,128,114,188,114,217,174,131,115,220,217,198,236,198,131,134,177,132,58,143,35,124,110,163,7,228,110,25,356,389,368,11,302,267,452,350,349,302,303,269,357,343,277,452,453,357,333,332,297,175,152,377,384,398,382,347,348,330,303,304,270,9,336,337,278,279,360,418,262,431,304,408,409,310,415,407,270,409,410,450,348,347,422,430,434,313,314,17,306,307,375,387,388,260,286,414,398,335,406,418,364,367,416,423,358,327,251,284,298,281,5,4,373,374,253,307,320,321,425,427,411,421,313,18,321,405,406,320,404,405,315,16,17,426,425,266,377,400,369,322,391,269,417,465,464,386,257,258,466,260,388,456,399,419,284,332,333,417,285,8,346,340,261,413,441,285,327,460,328,355,371,329,392,439,438,382,341,256,429,420,360,364,394,379,277,343,437,443,444,283,275,440,363,431,262,369,297,338,337,273,375,321,450,451,349,446,342,467,293,334,282,458,461,462,276,353,383,308,324,325,276,300,293,372,345,447,382,398,362,352,345,340,274,1,19,456,248,281,436,427,425,381,256,252,269,391,393,200,199,428,266,330,329,287,273,422,250,462,328,258,286,384,265,353,342,387,259,257,424,431,430,342,353,276,273,335,424,292,325,307,366,447,345,271,303,302,423,266,371,294,455,460,279,278,294,271,272,304,432,434,427,272,407,408,394,430,431,395,369,400,334,333,299,351,417,168,352,280,411,325,319,320,295,296,336,319,403,404,330,348,349,293,298,333,323,454,447,15,16,315,358,429,279,14,15,316,285,336,9,329,349,350,374,380,252,318,402,403,6,197,419,318,319,325,367,364,365,435,367,397,344,438,439,272,271,311,195,5,281,273,287,291,396,428,199,311,271,268,283,444,445,373,254,339,263,466,249,282,334,296,449,347,346,264,447,454,336,296,299,338,10,151,278,439,455,292,407,415,358,371,355,340,345,372,390,249,466,346,347,280,442,443,282,19,94,370,441,442,295,248,419,197,263,255,359,440,275,274,300,383,368,351,412,465,263,467,466,301,368,389,380,374,386,395,378,379,412,351,419,436,426,322,373,390,388,2,164,393,370,462,461,164,0,267,302,11,12,374,373,387,268,12,13,293,300,301,446,261,340,385,384,381,330,266,425,426,423,391,429,355,437,391,327,326,440,457,438,341,382,362,459,457,461,434,430,394,414,463,362,396,369,262,354,461,457,316,403,402,315,404,403,314,405,404,313,406,405,421,418,406,366,401,361,306,408,407,291,409,408,287,410,409,432,436,410,434,416,411,264,368,383,309,438,457,352,376,401,274,275,4,421,428,262,294,327,358,433,416,367,289,455,439,462,370,326,2,326,370,305,460,455,254,449,448,255,261,446,253,450,449,252,451,450,256,452,451,341,453,452,413,464,463,441,413,414,258,442,441,257,443,442,259,444,443,260,445,444,467,342,445,459,458,250,289,392,290,290,328,460,376,433,435,250,290,392,411,416,433,341,463,464,453,464,465,357,465,412,343,412,399,360,363,440,437,399,456,420,456,363,401,435,288,372,383,353,339,255,249,448,261,255,133,243,190,133,155,112,33,246,247,33,130,25,398,384,286,362,398,414,362,463,341,263,359,467,263,249,255,466,467,260,75,60,166,238,239,79,162,127,139,72,11,37,121,232,120,73,72,39,114,128,47,233,232,128,103,104,67,152,175,148,173,157,155,119,118,101,74,73,40,107,9,108,49,48,131,32,194,211,184,74,185,191,80,183,185,40,186,119,230,118,210,202,214,84,83,17,77,76,146,161,160,30,190,56,173,182,106,194,138,135,192,129,203,98,54,21,68,5,51,4,145,144,23,90,77,91,207,205,187,83,201,18,181,91,182,180,90,181,16,85,17,205,206,36,176,148,140,165,92,39,245,193,244,27,159,28,30,247,161,174,236,196,103,54,104,55,193,8,111,117,31,221,189,55,240,98,99,142,126,100,219,166,218,112,155,26,198,209,131,169,135,150,114,47,217,224,223,53,220,45,134,32,211,140,109,67,108,146,43,91,231,230,120,113,226,247,105,63,52,241,238,242,124,46,156,95,78,96,70,46,63,116,143,227,116,123,111,1,44,19,3,236,51,207,216,205,26,154,22,165,39,167,199,200,208,101,36,100,43,57,202,242,20,99,56,28,157,124,35,113,29,160,27,211,204,210,124,113,46,106,43,204,96,62,77,227,137,116,73,41,72,36,203,142,235,64,240,48,49,64,42,41,74,214,212,207,183,42,184,210,169,211,140,170,176,104,105,69,193,122,168,50,123,187,89,96,90,66,65,107,179,89,180,119,101,120,68,63,104,234,93,227,16,15,85,209,129,49,15,14,86,107,55,9,120,100,121,153,145,22,178,88,179,197,6,196,89,88,96,135,138,136,138,215,172,218,115,219,41,42,81,5,195,51,57,43,61,208,171,199,41,81,38,224,53,225,24,144,110,105,52,66,118,229,117,227,34,234,66,107,69,10,109,151,219,48,235,183,62,191,142,129,126,116,111,143,7,163,246,118,117,50,223,222,52,94,19,141,222,221,65,196,3,197,45,220,44,156,70,139,188,122,245,139,71,162,145,153,159,149,170,150,122,188,196,206,216,92,163,144,161,164,2,167,242,141,241,0,164,37,11,72,12,144,145,160,12,38,13,70,63,71,31,226,111,157,158,154,36,101,205,203,206,165,126,209,217,98,165,97,237,220,218,237,239,241,210,214,169,140,171,32,241,125,237,179,86,178,180,85,179,181,84,180,182,83,181,194,201,182,177,137,132,184,76,183,185,61,184,186,57,185,216,212,186,192,214,187,139,34,156,218,79,237,147,123,177,45,44,4,208,201,32,98,64,129,192,213,138,235,59,219,141,242,97,97,2,141,240,75,235,229,24,228,31,25,226,230,23,229,231,22,230,232,26,231,233,112,232,244,189,243,189,221,190,222,28,221,223,27,222,224,29,223,225,30,224,113,247,225,99,60,240,213,147,215,60,20,166,192,187,213,243,112,244,244,233,245,245,128,188,188,114,174,134,131,220,174,217,236,236,198,134,215,177,58,156,143,124,25,110,7,31,228,25,264,356,368,0,11,267,451,452,349,267,302,269,350,357,277,350,452,357,299,333,297,396,175,377,381,384,382,280,347,330,269,303,270,151,9,337,344,278,360,424,418,431,270,304,409,272,310,407,322,270,410,449,450,347,432,422,434,18,313,17,291,306,375,259,387,260,424,335,418,434,364,416,391,423,327,301,251,298,275,281,4,254,373,253,375,307,321,280,425,411,200,421,18,335,321,406,321,320,405,314,315,17,423,426,266,396,377,369,270,322,269,413,417,464,385,386,258,248,456,419,298,284,333,168,417,8,448,346,261,417,413,285,326,327,328,277,355,329,309,392,438,381,382,256,279,429,360,365,364,379,355,277,437,282,443,283,281,275,363,395,431,369,299,297,337,335,273,321,348,450,349,359,446,467,283,293,282,250,458,462,300,276,383,292,308,325,283,276,293,264,372,447,346,352,340,354,274,19,363,456,281,426,436,425,380,381,252,267,269,393,421,200,428,371,266,329,432,287,422,290,250,328,385,258,384,446,265,342,386,387,257,422,424,430,445,342,276,422,273,424,306,292,307,352,366,345,268,271,302,358,423,371,327,294,460,331,279,294,303,271,304,436,432,427,304,272,408,395,394,431,378,395,400,296,334,299,6,351,168,376,352,411,307,325,320,285,295,336,320,319,404,329,330,349,334,293,333,366,323,447,316,15,315,331,358,279,317,14,316,8,285,9,277,329,350,253,374,252,319,318,403,351,6,419,324,318,325,397,367,365,288,435,397,278,344,439,310,272,311,248,195,281,375,273,291,175,396,199,312,311,268,276,283,445,390,373,339,295,282,296,448,449,346,356,264,454,337,336,299,337,338,151,294,278,455,308,292,415,429,358,355,265,340,372,388,390,466,352,346,280,295,442,282,354,19,370,285,441,295,195,248,197,457,440,274,301,300,368,417,351,465,251,301,389,385,380,386,394,395,379,399,412,419,410,436,322,387,373,388,326,2,393,354,370,461,393,164,267,268,302,12,386,374,387,312,268,13,298,293,301,265,446,340,380,385,381,280,330,425,322,426,391,420,429,437,393,391,326,344,440,438,458,459,461,364,434,394,428,396,262,274,354,457,317,316,402,316,315,403,315,314,404,314,313,405,313,421,406,323,366,361,292,306,407,306,291,408,291,287,409,287,432,410,427,434,411,372,264,383,459,309,457,366,352,401,1,274,4,418,421,262,331,294,358,435,433,367,392,289,439,328,462,326,94,2,370,289,305,455,339,254,448,359,255,446,254,253,449,253,252,450,252,256,451,256,341,452,414,413,463,286,441,414,286,258,441,258,257,442,257,259,443,259,260,444,260,467,445,309,459,250,305,289,290,305,290,460,401,376,435,309,250,392,376,411,433,453,341,464,357,453,465,343,357,412,437,343,399,344,360,440,420,437,456,360,420,363,361,401,288,265,372,353,390,339,249,339,448,255];const TRI68=[0,1,36,0,36,17,1,2,41,1,41,36,2,3,31,2,31,41,3,4,48,3,48,31,4,5,48,5,6,48,6,7,59,6,59,48,7,8,58,7,58,59,8,9,56,8,56,57,8,57,58,9,10,55,9,55,56,10,11,54,10,54,55,11,12,54,12,13,54,13,14,35,13,35,54,14,15,46,14,46,35,15,16,45,15,45,46,16,26,45,17,36,18,18,37,19,18,36,37,19,38,20,19,37,38,20,39,21,20,38,39,21,39,27,22,42,23,22,27,42,23,43,24,23,42,43,24,44,25,24,43,44,25,45,26,25,44,45,27,39,28,27,28,42,28,39,29,28,29,42,29,31,30,29,30,35,29,40,31,29,35,47,29,39,40,29,47,42,30,31,32,30,32,33,30,33,34,30,34,35,31,50,32,31,40,41,31,48,49,31,49,50,32,51,33,32,50,51,33,51,34,34,52,35,34,51,52,35,46,47,35,52,53,35,53,54,36,41,37,37,40,38,37,41,40,38,40,39,42,47,43,43,47,44,44,46,45,44,47,46,48,60,49,48,59,60,49,61,50,49,60,61,50,62,51,50,61,62,51,62,52,52,63,53,52,62,63,53,64,54,53,63,64,54,64,55,55,65,56,55,64,65,56,66,57,56,65,66,57,66,58,58,67,59,58,66,67,59,67,60,60,67,61,61,66,62,61,67,66,62,66,63,63,65,64,63,66,65,21,27,22];const TRI33=[0,8,7,7,8,1,2,10,9,9,10,3,17,0,18,18,0,7,18,7,19,19,7,1,19,1,11,19,11,20,21,3,22,21,9,3,20,9,21,20,2,9,20,11,2,23,17,18,25,21,22,24,19,20,24,18,19,24,20,21,24,23,18,24,21,25,11,12,4,11,4,13,1,12,11,11,13,2,12,14,4,4,14,13,14,5,15,14,15,6,12,5,14,14,6,13,8,12,1,2,13,10,8,26,12,10,13,27,26,5,12,13,6,27,0,26,8,10,27,3,5,32,16,16,32,6,5,30,32,6,32,31,26,30,5,27,6,31,0,28,26,3,27,29,17,28,0,3,29,22,23,28,17,22,29,25,28,30,26,27,31,29];const TRI7=[0,4,1,2,4,3,4,5,6];const VTX68=[127,234,132,58,172,150,149,148,152,377,378,379,397,288,361,454,356,70,63,105,66,107,336,296,334,293,300,168,6,195,4,98,97,2,326,327,33,160,158,133,153,144,362,385,387,263,373,380,57,40,37,0,267,270,287,321,314,17,84,91,78,81,13,311,308,402,14,178];const VTX33=[33,133,362,263,1,62,308,159,145,386,374,6,102,331,2,13,14,70,105,107,336,334,300,54,10,284,50,280,234,454,58,288,152];const VTX7=[33,133,362,263,1,78,308];exports2.MESH_ANNOTATIONS=MESH_ANNOTATIONS;exports2.MESH_TO_IRIS_INDICES_MAP=MESH_TO_IRIS_INDICES_MAP;exports2.TRI468=TRI468;exports2.TRI68=TRI68;exports2.TRI33=TRI33;exports2.TRI7=TRI7;exports2.UV468=UV468;exports2.UV68=VTX68.map(x=>UV468[x]);exports2.UV33=VTX33.map(x=>UV468[x]);exports2.UV7=VTX7.map(x=>UV468[x])});var require_facepipeline=__commonJS(exports2=>{const bounding=__toModule(require_box());const util27=__toModule(require_util());const coords=__toModule(require_coords());const LANDMARKS_COUNT=468;const MESH_MOUTH_INDEX=13;const MESH_KEYPOINTS_LINE_OF_SYMMETRY_INDICES=[MESH_MOUTH_INDEX,coords.MESH_ANNOTATIONS["midwayBetweenEyes"][0]];const BLAZEFACE_MOUTH_INDEX=3;const BLAZEFACE_NOSE_INDEX=2;const BLAZEFACE_KEYPOINTS_LINE_OF_SYMMETRY_INDICES=[BLAZEFACE_MOUTH_INDEX,BLAZEFACE_NOSE_INDEX];const LEFT_EYE_OUTLINE=coords.MESH_ANNOTATIONS["leftEyeLower0"];const LEFT_EYE_BOUNDS=[LEFT_EYE_OUTLINE[0],LEFT_EYE_OUTLINE[LEFT_EYE_OUTLINE.length-1]];const RIGHT_EYE_OUTLINE=coords.MESH_ANNOTATIONS["rightEyeLower0"];const RIGHT_EYE_BOUNDS=[RIGHT_EYE_OUTLINE[0],RIGHT_EYE_OUTLINE[RIGHT_EYE_OUTLINE.length-1]];const IRIS_UPPER_CENTER_INDEX=3;const IRIS_LOWER_CENTER_INDEX=4;const IRIS_IRIS_INDEX=71;const IRIS_NUM_COORDINATES=76;function replaceRawCoordinates(rawCoords,newCoords,prefix,keys){for(let i=0;i[scaleFactor[0]*(coord[0]-this.meshWidth/2),scaleFactor[1]*(coord[1]-this.meshHeight/2),coord[2]]);const coordsRotationMatrix=util27.buildRotationMatrix(angle,[0,0]);const coordsRotated=coordsScaled.map(coord=>[...util27.rotatePoint(coord,coordsRotationMatrix),coord[2]]);const inverseRotationMatrix=util27.invertTransformMatrix(rotationMatrix);const boxCenter=[...bounding.getBoxCenter({startPoint:box.startPoint,endPoint:box.endPoint}),1];const originalBoxCenter=[util27.dot(boxCenter,inverseRotationMatrix[0]),util27.dot(boxCenter,inverseRotationMatrix[1])];return coordsRotated.map(coord=>[coord[0]+originalBoxCenter[0],coord[1]+originalBoxCenter[1],coord[2]])}getLeftToRightEyeDepthDifference(rawCoords){const leftEyeZ=rawCoords[LEFT_EYE_BOUNDS[0]][2];const rightEyeZ=rawCoords[RIGHT_EYE_BOUNDS[0]][2];return leftEyeZ-rightEyeZ}getEyeBox(rawCoords,face2,eyeInnerCornerIndex,eyeOuterCornerIndex,flip=false){const box=bounding.squarifyBox(bounding.enlargeBox(this.calculateLandmarksBoundingBox([rawCoords[eyeInnerCornerIndex],rawCoords[eyeOuterCornerIndex]]),this.irisEnlarge));const boxSize=bounding.getBoxSize(box);let crop=tf.image.cropAndResize(face2,[[box.startPoint[1]/this.meshHeight,box.startPoint[0]/this.meshWidth,box.endPoint[1]/this.meshHeight,box.endPoint[0]/this.meshWidth]],[0],[this.irisSize,this.irisSize]);if(flip){crop=tf.image.flipLeftRight(crop)}return{box,boxSize,crop}}getEyeCoords(eyeData,eyeBox,eyeBoxSize,flip=false){const eyeRawCoords=[];for(let i=0;i{let z=averageZ;if(i===2){z=upperCenterZ}else if(i===4){z=lowerCenterZ}return[coord[0],coord[1],z]})}async predict(input,config2){this.skipped++;let useFreshBox=false;let detector;if(this.skipped>config2.detector.skipFrames||!config2.mesh.enabled||!config2.videoOptimized){detector=await this.boundingBoxDetector.getBoundingBoxes(input);if(input.shape[1]!==255&&input.shape[2]!==255)this.skipped=0}if(detector&&detector.boxes&&detector.boxes.length>0&&(!config2.mesh.enabled||detector.boxes.length!==this.detectedFaces&&this.detectedFaces!==config2.detector.maxFaces)){this.storedBoxes=[];this.detectedFaces=0;for(const possible of detector.boxes){this.storedBoxes.push({startPoint:possible.box.startPoint.dataSync(),endPoint:possible.box.endPoint.dataSync(),landmarks:possible.landmarks,confidence:possible.confidence})}if(this.storedBoxes.length>0)useFreshBox=true}if(useFreshBox){if(!detector||!detector.boxes||detector.boxes.length===0){this.storedBoxes=[];this.detectedFaces=0;return null}for(const i in this.storedBoxes){const scaledBox=bounding.scaleBoxCoordinates({startPoint:this.storedBoxes[i].startPoint,endPoint:this.storedBoxes[i].endPoint},detector.scaleFactor);const enlargedBox=bounding.enlargeBox(scaledBox);const landmarks=this.storedBoxes[i].landmarks.arraySync();const confidence=this.storedBoxes[i].confidence;this.storedBoxes[i]={...enlargedBox,confidence,landmarks}}this.runsWithoutFaceDetector=0}if(detector&&detector.boxes){detector.boxes.forEach(prediction=>{prediction.box.startPoint.dispose();prediction.box.endPoint.dispose();prediction.landmarks.dispose()})}let results=tf.tidy(()=>this.storedBoxes.map((box,i)=>{let angle=0;const boxLandmarksFromMeshModel=box.landmarks.length>=LANDMARKS_COUNT;let[indexOfMouth,indexOfForehead]=MESH_KEYPOINTS_LINE_OF_SYMMETRY_INDICES;if(boxLandmarksFromMeshModel===false){[indexOfMouth,indexOfForehead]=BLAZEFACE_KEYPOINTS_LINE_OF_SYMMETRY_INDICES}angle=util27.computeRotation(box.landmarks[indexOfMouth],box.landmarks[indexOfForehead]);const faceCenter=bounding.getBoxCenter({startPoint:box.startPoint,endPoint:box.endPoint});const faceCenterNormalized=[faceCenter[0]/input.shape[2],faceCenter[1]/input.shape[1]];let rotatedImage=input;let rotationMatrix=util27.IDENTITY_MATRIX;if(angle!==0){rotatedImage=tf.image.rotateWithOffset(input,angle,0,faceCenterNormalized);rotationMatrix=util27.buildRotationMatrix(-angle,faceCenter)}const face2=bounding.cutBoxFromImageAndResize({startPoint:box.startPoint,endPoint:box.endPoint},rotatedImage,[this.meshHeight,this.meshWidth]).div(255);const outputFace=config2.detector.rotation?tf.image.rotateWithOffset(face2,angle):face2;if(!config2.mesh.enabled){const prediction2={coords:null,box,faceConfidence:null,confidence:box.confidence,image:outputFace};return prediction2}const[,confidence,contourCoords]=this.meshDetector.predict(face2);const confidenceVal=confidence.dataSync()[0];confidence.dispose();if(confidenceVala!==null);this.detectedFaces=results.length;return results}calculateLandmarksBoundingBox(landmarks){const xs=landmarks.map(d=>d[0]);const ys=landmarks.map(d=>d[1]);const startPoint=[Math.min(...xs),Math.min(...ys)];const endPoint=[Math.max(...xs),Math.max(...ys)];return{startPoint,endPoint,landmarks}}}exports2.Pipeline=Pipeline});var require_facemesh=__commonJS(exports2=>{const blazeface=__toModule(require_blazeface());const pipe=__toModule(require_facepipeline());const coords=__toModule(require_coords());class MediaPipeFaceMesh{constructor(blazeFace,blazeMeshModel,irisModel,config2){this.pipeline=new pipe.Pipeline(blazeFace,blazeMeshModel,irisModel,config2);if(config2)this.config=config2}async estimateFaces(input,config2){if(config2)this.config=config2;const predictions=await this.pipeline.predict(input,config2);const results=[];for(const prediction of predictions||[]){if(prediction.isDisposedInternal)continue;const mesh=prediction.coords?prediction.coords.arraySync():null;const annotations={};if(mesh&&mesh.length>0){for(const key in coords.MESH_ANNOTATIONS){if(this.config.iris.enabled||key.includes("Iris")===false){annotations[key]=coords.MESH_ANNOTATIONS[key].map(index=>mesh[index])}}}results.push({confidence:prediction.confidence||0,box:prediction.box?[prediction.box.startPoint[0],prediction.box.startPoint[1],prediction.box.endPoint[0]-prediction.box.startPoint[0],prediction.box.endPoint[1]-prediction.box.startPoint[1]]:0,mesh,annotations,image:prediction.image?tf.clone(prediction.image):null});if(prediction.coords)prediction.coords.dispose();if(prediction.image)prediction.image.dispose()}return results}}async function load2(config2){const models=await Promise.all([blazeface.load(config2),tf.loadGraphModel(config2.mesh.modelPath,{fromTFHub:config2.mesh.modelPath.includes("tfhub.dev")}),tf.loadGraphModel(config2.iris.modelPath,{fromTFHub:config2.iris.modelPath.includes("tfhub.dev")})]);const faceMesh=new MediaPipeFaceMesh(models[0],models[1],models[2],config2);console.log(`Human: load model: ${config2.mesh.modelPath.match(/\/(.*)\./)[1]}`);console.log(`Human: load model: ${config2.iris.modelPath.match(/\/(.*)\./)[1]}`);return faceMesh}exports2.load=load2;exports2.MediaPipeFaceMesh=MediaPipeFaceMesh;exports2.triangulation=coords.TRI468});var require_profile=__commonJS(exports2=>{const profileData={};function profile2(name,data2){if(!data2||!data2.kernels)return;const maxResults=5;const time=data2.kernels.filter(a=>a.kernelTimeMs>0).reduce((a,b)=>a+=b.kernelTimeMs,0);const slowest=data2.kernels.map((a,i)=>{a.id=i;return a}).filter(a=>a.kernelTimeMs>0).sort((a,b)=>b.kernelTimeMs-a.kernelTimeMs);const largest=data2.kernels.map((a,i)=>{a.id=i;return a}).filter(a=>a.totalBytesSnapshot>0).sort((a,b)=>b.totalBytesSnapshot-a.totalBytesSnapshot);if(slowest.length>maxResults)slowest.length=maxResults;if(largest.length>maxResults)largest.length=maxResults;const res={newBytes:data2.newBytes,newTensors:data2.newTensors,peakBytes:data2.peakBytes,numKernelOps:data2.kernels.length,timeKernelOps:time,slowestKernelOps:slowest,largestKernelOps:largest};profileData[name]=res;console.log("Human profiler",name,res)}exports2.run=profile2});var require_age=__commonJS(exports2=>{const profile2=__toModule(require_profile());const models={};let last={age:0};let frame=Number.MAX_SAFE_INTEGER;async function load2(config2){if(!models.age){models.age=await tf.loadGraphModel(config2.face.age.modelPath);console.log(`Human: load model: ${config2.face.age.modelPath.match(/\/(.*)\./)[1]}`)}return models.age}async function predict2(image2,config2){if(!models.age)return null;if(frame0){frame+=1;return last}frame=0;return new Promise(async resolve=>{const resize=tf.image.resizeBilinear(image2,[config2.face.age.inputSize,config2.face.age.inputSize],false);const enhance=tf.mul(resize,[255]);tf.dispose(resize);let ageT;const obj={};if(!config2.profile){if(config2.face.age.enabled)ageT=await models.age.predict(enhance)}else{const profileAge=config2.face.age.enabled?await tf.profile(()=>models.age.predict(enhance)):{};ageT=profileAge.result.clone();profileAge.result.dispose();profile2.run("age",profileAge)}enhance.dispose();if(ageT){const data2=ageT.dataSync();obj.age=Math.trunc(10*data2[0])/10}ageT.dispose();last=obj;resolve(obj)})}exports2.predict=predict2;exports2.load=load2});var require_gender=__commonJS(exports2=>{const profile2=__toModule(require_profile());const models={};let last={gender:""};let frame=Number.MAX_SAFE_INTEGER;let alternative=false;const rgb=[.2989,.587,.114];async function load2(config2){if(!models.gender){models.gender=await tf.loadGraphModel(config2.face.gender.modelPath);alternative=models.gender.inputs[0].shape[3]===1;console.log(`Human: load model: ${config2.face.gender.modelPath.match(/\/(.*)\./)[1]}`)}return models.gender}async function predict2(image2,config2){if(!models.gender)return null;if(frame{const resize=tf.image.resizeBilinear(image2,[config2.face.gender.inputSize,config2.face.gender.inputSize],false);let enhance;if(alternative){enhance=tf.tidy(()=>{const[red,green,blue]=tf.split(resize,3,3);const redNorm=tf.mul(red,rgb[0]);const greenNorm=tf.mul(green,rgb[1]);const blueNorm=tf.mul(blue,rgb[2]);const grayscale=tf.addN([redNorm,greenNorm,blueNorm]);return grayscale.sub(.5).mul(2)})}else{enhance=tf.mul(resize,[255])}tf.dispose(resize);let genderT;const obj={};if(!config2.profile){if(config2.face.gender.enabled)genderT=await models.gender.predict(enhance)}else{const profileGender=config2.face.gender.enabled?await tf.profile(()=>models.gender.predict(enhance)):{};genderT=profileGender.result.clone();profileGender.result.dispose();profile2.run("gender",profileGender)}enhance.dispose();if(genderT){const data2=genderT.dataSync();if(alternative){const confidence=Math.trunc(100*Math.abs(data2[0]-data2[1]))/100;if(confidence>config2.face.gender.minConfidence){obj.gender=data2[0]>data2[1]?"female":"male";obj.confidence=confidence}}else{const confidence=Math.trunc(200*Math.abs(data2[0]-.5))/100;if(confidence>config2.face.gender.minConfidence){obj.gender=data2[0]<=.5?"female":"male";obj.confidence=Math.min(.99,confidence)}}}genderT.dispose();last=obj;resolve(obj)})}exports2.predict=predict2;exports2.load=load2});var require_emotion=__commonJS(exports2=>{const profile2=__toModule(require_profile());const annotations=["angry","disgust","fear","happy","sad","surpise","neutral"];const models={};let last=[];let frame=Number.MAX_SAFE_INTEGER;const rgb=[.2989,.587,.114];const scale=1;async function load2(config2){if(!models.emotion){models.emotion=await tf.loadGraphModel(config2.face.emotion.modelPath);console.log(`Human: load model: ${config2.face.emotion.modelPath.match(/\/(.*)\./)[1]}`)}return models.emotion}async function predict2(image2,config2){if(!models.emotion)return null;if(frame0){frame+=1;return last}frame=0;return new Promise(async resolve=>{const resize=tf.image.resizeBilinear(image2,[config2.face.emotion.inputSize,config2.face.emotion.inputSize],false);const[red,green,blue]=tf.split(resize,3,3);resize.dispose();const redNorm=tf.mul(red,rgb[0]);const greenNorm=tf.mul(green,rgb[1]);const blueNorm=tf.mul(blue,rgb[2]);red.dispose();green.dispose();blue.dispose();const grayscale=tf.addN([redNorm,greenNorm,blueNorm]);redNorm.dispose();greenNorm.dispose();blueNorm.dispose();const normalize=tf.tidy(()=>grayscale.sub(.5).mul(2));grayscale.dispose();const obj=[];if(config2.face.emotion.enabled){let data2;if(!config2.profile){const emotionT=await models.emotion.predict(normalize);data2=emotionT.dataSync();tf.dispose(emotionT)}else{const profileData=await tf.profile(()=>models.emotion.predict(normalize));data2=profileData.result.dataSync();profileData.result.dispose();profile2.run("emotion",profileData)}for(let i=0;iconfig2.face.emotion.minConfidence)obj.push({score:Math.min(.99,Math.trunc(100*scale*data2[i])/100),emotion:annotations[i]})}obj.sort((a,b)=>b.score-a.score)}normalize.dispose();last=obj;resolve(obj)})}exports2.predict=predict2;exports2.load=load2});var require_embedding=__commonJS(exports2=>{const profile2=__toModule(require_profile());const models={};async function load2(config2){if(!models.embedding){models.embedding=await tf.loadGraphModel(config2.face.embedding.modelPath);console.log(`Human: load model: ${config2.face.embedding.modelPath.match(/\/(.*)\./)[1]}`)}return models.embedding}function simmilarity2(embedding1,embedding2){if((embedding1==null?void 0:embedding1.length)!==(embedding2==null?void 0:embedding2.length))return 0;const distance=10*Math.sqrt(embedding1.map((val,i)=>val-embedding2[i]).reduce((dist,diff)=>dist+diff**2,0));const confidence=2*(.5-distance);return Math.trunc(1e3*confidence)/1e3}async function predict2(image2,config2){if(!models.embedding)return null;return new Promise(async resolve=>{const resize=tf.image.resizeBilinear(image2,[config2.face.embedding.inputSize,config2.face.embedding.inputSize],false);let data2=[];if(config2.face.embedding.enabled){if(!config2.profile){const embeddingT=await models.embedding.predict({img_inputs:resize});data2=[...embeddingT.dataSync()];tf.dispose(embeddingT)}else{const profileData=await tf.profile(()=>models.embedding.predict({img_inputs:resize}));data2=[...profileData.result.dataSync()];profileData.result.dispose();profile2.run("emotion",profileData)}}resize.dispose();resolve(data2)})}exports2.predict=predict2;exports2.simmilarity=simmilarity2;exports2.load=load2});var require_modelBase=__commonJS(exports2=>{class BaseModel{constructor(model,outputStride){this.model=model;this.outputStride=outputStride}predict(input){return tf.tidy(()=>{const asFloat=this.preprocessInput(input.toFloat());const asBatch=asFloat.expandDims(0);const results=this.model.predict(asBatch);const results3d=results.map(y=>y.squeeze([0]));const namedResults=this.nameOutputResults(results3d);return{heatmapScores:namedResults.heatmap.sigmoid(),offsets:namedResults.offsets,displacementFwd:namedResults.displacementFwd,displacementBwd:namedResults.displacementBwd}})}dispose(){this.model.dispose()}}exports2.BaseModel=BaseModel});var require_modelMobileNet=__commonJS(exports2=>{const modelBase=__toModule(require_modelBase());class MobileNet extends modelBase.BaseModel{preprocessInput(input){return tf.tidy(()=>tf.div(input,127.5).sub(1))}nameOutputResults(results){const[offsets,heatmap,displacementFwd,displacementBwd]=results;return{offsets,heatmap,displacementFwd,displacementBwd}}}exports2.MobileNet=MobileNet});var require_heapSort=__commonJS(exports2=>{function half(k){return Math.floor(k/2)}class MaxHeap{constructor(maxSize,getElementValue){this.priorityQueue=new Array(maxSize);this.numberOfElements=-1;this.getElementValue=getElementValue}enqueue(x){this.priorityQueue[++this.numberOfElements]=x;this.swim(this.numberOfElements)}dequeue(){const max2=this.priorityQueue[0];this.exchange(0,this.numberOfElements--);this.sink(0);this.priorityQueue[this.numberOfElements+1]=null;return max2}empty(){return this.numberOfElements===-1}size(){return this.numberOfElements+1}all(){return this.priorityQueue.slice(0,this.numberOfElements+1)}max(){return this.priorityQueue[0]}swim(k){while(k>0&&this.less(half(k),k)){this.exchange(k,half(k));k=half(k)}}sink(k){while(2*k<=this.numberOfElements){let j=2*k;if(j{const heapSort=__toModule(require_heapSort());function scoreIsMaximumInLocalWindow(keypointId,score,heatmapY,heatmapX,localMaximumRadius,scores){const[height,width]=scores.shape;let localMaximum=true;const yStart=Math.max(heatmapY-localMaximumRadius,0);const yEnd=Math.min(heatmapY+localMaximumRadius+1,height);for(let yCurrent=yStart;yCurrentscore){localMaximum=false;break}}if(!localMaximum){break}}return localMaximum}function buildPartWithScoreQueue(scoreThreshold,localMaximumRadius,scores){const[height,width,numKeypoints]=scores.shape;const queue=new heapSort.MaxHeap(height*width*numKeypoints,({score})=>score);for(let heatmapY=0;heatmapY{exports2.partNames=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"];exports2.NUM_KEYPOINTS=exports2.partNames.length;exports2.partIds=exports2.partNames.reduce((result,jointName,i)=>{result[jointName]=i;return result},{});const connectedPartNames=[["leftHip","leftShoulder"],["leftElbow","leftShoulder"],["leftElbow","leftWrist"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["rightHip","rightShoulder"],["rightElbow","rightShoulder"],["rightElbow","rightWrist"],["rightHip","rightKnee"],["rightKnee","rightAnkle"],["leftShoulder","rightShoulder"],["leftHip","rightHip"]];exports2.poseChain=[["nose","leftEye"],["leftEye","leftEar"],["nose","rightEye"],["rightEye","rightEar"],["nose","leftShoulder"],["leftShoulder","leftElbow"],["leftElbow","leftWrist"],["leftShoulder","leftHip"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["nose","rightShoulder"],["rightShoulder","rightElbow"],["rightElbow","rightWrist"],["rightShoulder","rightHip"],["rightHip","rightKnee"],["rightKnee","rightAnkle"]];exports2.connectedPartIndices=connectedPartNames.map(([jointNameA,jointNameB])=>[exports2.partIds[jointNameA],exports2.partIds[jointNameB]]);exports2.partChannels=["left_face","right_face","right_upper_leg_front","right_lower_leg_back","right_upper_leg_back","left_lower_leg_front","left_upper_leg_front","left_upper_leg_back","left_lower_leg_back","right_feet","right_lower_leg_front","left_feet","torso_front","torso_back","right_upper_arm_front","right_upper_arm_back","right_lower_arm_back","left_lower_arm_front","left_upper_arm_front","left_upper_arm_back","left_lower_arm_back","right_hand","right_lower_arm_front","left_hand"]});var require_vectors=__commonJS(exports2=>{const kpt=__toModule(require_keypoints());function getOffsetPoint(y,x,keypoint,offsets){return{y:offsets.get(y,x,keypoint),x:offsets.get(y,x,keypoint+kpt.NUM_KEYPOINTS)}}exports2.getOffsetPoint=getOffsetPoint;function getImageCoords(part,outputStride,offsets){const{heatmapY,heatmapX,id:keypoint}=part;const{y,x}=getOffsetPoint(heatmapY,heatmapX,keypoint,offsets);return{x:part.heatmapX*outputStride+x,y:part.heatmapY*outputStride+y}}exports2.getImageCoords=getImageCoords;function fillArray(element,size){const result=new Array(size);for(let i=0;imax2)return max2;return a}exports2.clamp=clamp;function squaredDistance(y1,x1,y2,x2){const dy=y2-y1;const dx=x2-x1;return dy*dy+dx*dx}exports2.squaredDistance=squaredDistance;function addVectors(a,b){return{x:a.x+b.x,y:a.y+b.y}}exports2.addVectors=addVectors;function clampVector(a,min2,max2){return{y:clamp(a.y,min2,max2),x:clamp(a.x,min2,max2)}}exports2.clampVector=clampVector});var require_decodePose=__commonJS(exports2=>{const keypoints=__toModule(require_keypoints());const vectors=__toModule(require_vectors());const parentChildrenTuples=keypoints.poseChain.map(([parentJoinName,childJoinName])=>[keypoints.partIds[parentJoinName],keypoints.partIds[childJoinName]]);const parentToChildEdges=parentChildrenTuples.map(([,childJointId])=>childJointId);const childToParentEdges=parentChildrenTuples.map(([parentJointId])=>parentJointId);function getDisplacement(edgeId,point,displacements){const numEdges=displacements.shape[2]/2;return{y:displacements.get(point.y,point.x,edgeId),x:displacements.get(point.y,point.x,numEdges+edgeId)}}function getStridedIndexNearPoint(point,outputStride,height,width){return{y:vectors.clamp(Math.round(point.y/outputStride),0,height-1),x:vectors.clamp(Math.round(point.x/outputStride),0,width-1)}}function traverseToTargetKeypoint(edgeId,sourceKeypoint,targetKeypointId,scoresBuffer,offsets,outputStride,displacements,offsetRefineStep=2){const[height,width]=scoresBuffer.shape;const sourceKeypointIndices=getStridedIndexNearPoint(sourceKeypoint.position,outputStride,height,width);const displacement=getDisplacement(edgeId,sourceKeypointIndices,displacements);const displacedPoint=vectors.addVectors(sourceKeypoint.position,displacement);let targetKeypoint=displacedPoint;for(let i=0;i=0;--edge){const sourceKeypointId=parentToChildEdges[edge];const targetKeypointId=childToParentEdges[edge];if(instanceKeypoints[sourceKeypointId]&&!instanceKeypoints[targetKeypointId]){instanceKeypoints[targetKeypointId]=traverseToTargetKeypoint(edge,instanceKeypoints[sourceKeypointId],targetKeypointId,scores,offsets,outputStride,displacementsBwd)}}for(let edge=0;edge{const buildParts=__toModule(require_buildParts());const decodePose=__toModule(require_decodePose());const vectors=__toModule(require_vectors());function withinNmsRadiusOfCorrespondingPoint(poses,squaredNmsRadius,{x,y},keypointId){return poses.some(({keypoints})=>{const correspondingKeypoint=keypoints[keypointId].position;return vectors.squaredDistance(y,x,correspondingKeypoint.y,correspondingKeypoint.x)<=squaredNmsRadius})}function getInstanceScore(existingPoses,squaredNmsRadius,instanceKeypoints){const notOverlappedKeypointScores=instanceKeypoints.reduce((result,{position,score},keypointId)=>{if(!withinNmsRadiusOfCorrespondingPoint(existingPoses,squaredNmsRadius,position,keypointId)){result+=score}return result},0);return notOverlappedKeypointScores/instanceKeypoints.length}const kLocalMaximumRadius=1;function decodeMultiplePoses(scoresBuffer,offsetsBuffer,displacementsFwdBuffer,displacementsBwdBuffer,outputStride,maxPoseDetections,scoreThreshold=.5,nmsRadius=20){const poses=[];const queue=buildParts.buildPartWithScoreQueue(scoreThreshold,kLocalMaximumRadius,scoresBuffer);const squaredNmsRadius=nmsRadius*nmsRadius;while(poses.length{const kpt=__toModule(require_keypoints());function eitherPointDoesntMeetConfidence(a,b,minConfidence){return a{if(eitherPointDoesntMeetConfidence(keypoints[leftJoint].score,keypoints[rightJoint].score,minConfidence)){return result}result.push([keypoints[leftJoint],keypoints[rightJoint]]);return result},[])}exports2.getAdjacentKeyPoints=getAdjacentKeyPoints;const{NEGATIVE_INFINITY,POSITIVE_INFINITY}=Number;function getBoundingBox(keypoints){return keypoints.reduce(({maxX,maxY,minX,minY},{position:{x,y}})=>({maxX:Math.max(maxX,x),maxY:Math.max(maxY,y),minX:Math.min(minX,x),minY:Math.min(minY,y)}),{maxX:NEGATIVE_INFINITY,maxY:NEGATIVE_INFINITY,minX:POSITIVE_INFINITY,minY:POSITIVE_INFINITY})}exports2.getBoundingBox=getBoundingBox;function getBoundingBoxPoints(keypoints){const{minX,minY,maxX,maxY}=getBoundingBox(keypoints);return[{x:minX,y:minY},{x:maxX,y:minY},{x:maxX,y:maxY},{x:minX,y:maxY}]}exports2.getBoundingBoxPoints=getBoundingBoxPoints;async function toTensorBuffers3D(tensors){return Promise.all(tensors.map(tensor=>tensor.buffer()))}exports2.toTensorBuffers3D=toTensorBuffers3D;function scalePose(pose,scaleY,scaleX){return{score:pose.score,keypoints:pose.keypoints.map(({score,part,position})=>({score,part,position:{x:position.x*scaleX,y:position.y*scaleY}}))}}exports2.scalePose=scalePose;function resizeTo(image2,[targetH,targetW]){const input=image2.squeeze(0);const resized=input.resizeBilinear([targetH,targetW]);input.dispose();return resized}exports2.resizeTo=resizeTo;function scaleAndFlipPoses(poses,[height,width],[inputResolutionHeight,inputResolutionWidth]){const scaledPoses=poses.map(pose=>scalePose(pose,height/inputResolutionHeight,width/inputResolutionWidth));return scaledPoses}exports2.scaleAndFlipPoses=scaleAndFlipPoses});var require_modelPoseNet=__commonJS(exports2=>{const modelMobileNet=__toModule(require_modelMobileNet());const decodeMultiple=__toModule(require_decodeMultiple());const util27=__toModule(require_util2());class PoseNet{constructor(net){this.baseModel=net;this.outputStride=16}async estimatePoses(input,config2){return new Promise(async resolve=>{const height=input.shape[1];const width=input.shape[2];const resized=util27.resizeTo(input,[config2.body.inputSize,config2.body.inputSize]);const res=this.baseModel.predict(resized);const allTensorBuffers=await util27.toTensorBuffers3D([res.heatmapScores,res.offsets,res.displacementFwd,res.displacementBwd]);const scoresBuffer=allTensorBuffers[0];const offsetsBuffer=allTensorBuffers[1];const displacementsFwdBuffer=allTensorBuffers[2];const displacementsBwdBuffer=allTensorBuffers[3];const poses=await decodeMultiple.decodeMultiplePoses(scoresBuffer,offsetsBuffer,displacementsFwdBuffer,displacementsBwdBuffer,this.outputStride,config2.body.maxDetections,config2.body.scoreThreshold,config2.body.nmsRadius);const resultPoses=util27.scaleAndFlipPoses(poses,[height,width],[config2.body.inputSize,config2.body.inputSize]);res.heatmapScores.dispose();res.offsets.dispose();res.displacementFwd.dispose();res.displacementBwd.dispose();resized.dispose();resolve(resultPoses)})}dispose(){this.baseModel.dispose()}}exports2.PoseNet=PoseNet;async function load2(config2){const graphModel=await tf.loadGraphModel(config2.body.modelPath);const mobilenet=new modelMobileNet.MobileNet(graphModel,this.outputStride);console.log(`Human: load model: ${config2.body.modelPath.match(/\/(.*)\./)[1]}`);return new PoseNet(mobilenet)}exports2.load=load2});var require_posenet=__commonJS(exports2=>{const modelMobileNet=__toModule(require_modelMobileNet());const modelPoseNet=__toModule(require_modelPoseNet());const decodeMultiple=__toModule(require_decodeMultiple());const keypoints=__toModule(require_keypoints());const util27=__toModule(require_util2());exports2.load=modelPoseNet.load;exports2.PoseNet=modelPoseNet.PoseNet;exports2.MobileNet=modelMobileNet.MobileNet;exports2.decodeMultiplePoses=decodeMultiple.decodeMultiplePoses;exports2.partChannels=keypoints.partChannels;exports2.partIds=keypoints.partIds;exports2.partNames=keypoints.partNames;exports2.poseChain=keypoints.poseChain;exports2.getAdjacentKeyPoints=util27.getAdjacentKeyPoints;exports2.getBoundingBox=util27.getBoundingBox;exports2.getBoundingBoxPoints=util27.getBoundingBoxPoints;exports2.scaleAndFlipPoses=util27.scaleAndFlipPoses;exports2.scalePose=util27.scalePose});var require_handdetector=__commonJS(exports2=>{class HandDetector{constructor(model,inputSize,anchorsAnnotated){this.model=model;this.anchors=anchorsAnnotated.map(anchor=>[anchor.x_center,anchor.y_center]);this.anchorsTensor=tf.tensor2d(this.anchors);this.inputSizeTensor=tf.tensor1d([inputSize,inputSize]);this.doubleInputSizeTensor=tf.tensor1d([inputSize*2,inputSize*2])}normalizeBoxes(boxes){return tf.tidy(()=>{const boxOffsets=tf.slice(boxes,[0,0],[-1,2]);const boxSizes=tf.slice(boxes,[0,2],[-1,2]);const boxCenterPoints=tf.add(tf.div(boxOffsets,this.inputSizeTensor),this.anchorsTensor);const halfBoxSizes=tf.div(boxSizes,this.doubleInputSizeTensor);const startPoints=tf.mul(tf.sub(boxCenterPoints,halfBoxSizes),this.inputSizeTensor);const endPoints=tf.mul(tf.add(boxCenterPoints,halfBoxSizes),this.inputSizeTensor);return tf.concat2d([startPoints,endPoints],1)})}normalizeLandmarks(rawPalmLandmarks,index){return tf.tidy(()=>{const landmarks=tf.add(tf.div(rawPalmLandmarks.reshape([-1,7,2]),this.inputSizeTensor),this.anchors[index]);return tf.mul(landmarks,this.inputSizeTensor)})}async getBoxes(input,config2){const batched=this.model.predict(input);const predictions=batched.squeeze();batched.dispose();const scores=tf.tidy(()=>tf.sigmoid(tf.slice(predictions,[0,0],[-1,1])).squeeze());const scoresVal=scores.dataSync();const rawBoxes=tf.slice(predictions,[0,1],[-1,4]);const boxes=this.normalizeBoxes(rawBoxes);rawBoxes.dispose();const filteredT=await tf.image.nonMaxSuppressionAsync(boxes,scores,config2.maxHands,config2.iouThreshold,config2.scoreThreshold);const filtered=filteredT.arraySync();scores.dispose();filteredT.dispose();const hands=[];for(const boxIndex of filtered){if(scoresVal[boxIndex]>=config2.minConfidence){const matchingBox=tf.slice(boxes,[boxIndex,0],[1,-1]);const rawPalmLandmarks=tf.slice(predictions,[boxIndex,5],[1,14]);const palmLandmarks=tf.tidy(()=>this.normalizeLandmarks(rawPalmLandmarks,boxIndex).reshape([-1,2]));rawPalmLandmarks.dispose();hands.push({box:matchingBox,palmLandmarks,confidence:scoresVal[boxIndex]})}}predictions.dispose();boxes.dispose();return hands}async estimateHandBounds(input,config2){const inputHeight=input.shape[1];const inputWidth=input.shape[2];const image2=tf.tidy(()=>input.resizeBilinear([config2.inputSize,config2.inputSize]).div(127.5).sub(1));const predictions=await this.getBoxes(image2,config2);image2.dispose();if(!predictions||predictions.length===0)return null;const hands=[];for(const prediction of predictions){const boxes=prediction.box.dataSync();const startPoint=boxes.slice(0,2);const endPoint=boxes.slice(2,4);const palmLandmarks=prediction.palmLandmarks.arraySync();prediction.box.dispose();prediction.palmLandmarks.dispose();hands.push(scaleBoxCoordinates({startPoint,endPoint,palmLandmarks,confidence:prediction.confidence},[inputWidth/config2.inputSize,inputHeight/config2.inputSize]))}return hands}}exports2.HandDetector=HandDetector});var require_handpipeline=__commonJS(exports2=>{const PALM_BOX_SHIFT_VECTOR=[0,-.4];const PALM_BOX_ENLARGE_FACTOR=3;const HAND_BOX_SHIFT_VECTOR=[0,-.1];const HAND_BOX_ENLARGE_FACTOR=1.65;const PALM_LANDMARK_IDS=[0,5,9,13,17,1,2];const PALM_LANDMARKS_INDEX_OF_PALM_BASE=0;const PALM_LANDMARKS_INDEX_OF_MIDDLE_FINGER_BASE=2;class HandPipeline{constructor(boundingBoxDetector,meshDetector,inputSize){this.boxDetector=boundingBoxDetector;this.meshDetector=meshDetector;this.inputSize=inputSize;this.storedBoxes=[];this.skipped=1e3;this.detectedHands=0}getBoxForPalmLandmarks(palmLandmarks,rotationMatrix){const rotatedPalmLandmarks=palmLandmarks.map(coord=>{const homogeneousCoordinate=[...coord,1];return rotatePoint(homogeneousCoordinate,rotationMatrix)});const boxAroundPalm=this.calculateLandmarksBoundingBox(rotatedPalmLandmarks);return enlargeBox(squarifyBox(shiftBox(boxAroundPalm,PALM_BOX_SHIFT_VECTOR)),PALM_BOX_ENLARGE_FACTOR)}getBoxForHandLandmarks(landmarks){const boundingBox=this.calculateLandmarksBoundingBox(landmarks);const boxAroundHand=enlargeBox(squarifyBox(shiftBox(boundingBox,HAND_BOX_SHIFT_VECTOR)),HAND_BOX_ENLARGE_FACTOR);const palmLandmarks=[];for(let i=0;i[scaleFactor[0]*(coord[0]-this.inputSize/2),scaleFactor[1]*(coord[1]-this.inputSize/2),coord[2]]);const coordsRotationMatrix=buildRotationMatrix(angle,[0,0]);const coordsRotated=coordsScaled.map(coord=>{const rotated=rotatePoint(coord,coordsRotationMatrix);return[...rotated,coord[2]]});const inverseRotationMatrix=invertTransformMatrix(rotationMatrix);const boxCenter=[...getBoxCenter(box2),1];const originalBoxCenter=[dot(boxCenter,inverseRotationMatrix[0]),dot(boxCenter,inverseRotationMatrix[1])];return coordsRotated.map(coord=>[coord[0]+originalBoxCenter[0],coord[1]+originalBoxCenter[1],coord[2]])}async estimateHands(image2,config2){this.skipped++;let useFreshBox=false;let boxes;if(this.skipped>config2.skipFrames||!config2.landmarks||!config2.videoOptimized){boxes=await this.boxDetector.estimateHandBounds(image2,config2);if(image2.shape[1]!==255&&image2.shape[2]!==255)this.skipped=0}if(boxes&&boxes.length>0&&(boxes.length!==this.detectedHands&&this.detectedHands!==config2.maxHands||!config2.landmarks)){this.storedBoxes=[];this.detectedHands=0;for(const possible of boxes)this.storedBoxes.push(possible);if(this.storedBoxes.length>0)useFreshBox=true}const hands=[];for(const i in this.storedBoxes){const currentBox=this.storedBoxes[i];if(!currentBox)continue;if(config2.landmarks){const angle=computeRotation(currentBox.palmLandmarks[PALM_LANDMARKS_INDEX_OF_PALM_BASE],currentBox.palmLandmarks[PALM_LANDMARKS_INDEX_OF_MIDDLE_FINGER_BASE]);const palmCenter=getBoxCenter(currentBox);const palmCenterNormalized=[palmCenter[0]/image2.shape[2],palmCenter[1]/image2.shape[1]];const rotatedImage=tf.image.rotateWithOffset(image2,angle,0,palmCenterNormalized);const rotationMatrix=buildRotationMatrix(-angle,palmCenter);const newBox=useFreshBox?this.getBoxForPalmLandmarks(currentBox.palmLandmarks,rotationMatrix):currentBox;const croppedInput=cutBoxFromImageAndResize(newBox,rotatedImage,[this.inputSize,this.inputSize]);const handImage=croppedInput.div(255);croppedInput.dispose();rotatedImage.dispose();const[confidence,keypoints]=await this.meshDetector.predict(handImage);handImage.dispose();const confidenceValue=confidence.dataSync()[0];confidence.dispose();if(confidenceValue>=config2.minConfidence){const keypointsReshaped=tf.reshape(keypoints,[-1,3]);const rawCoords=keypointsReshaped.arraySync();keypoints.dispose();keypointsReshaped.dispose();const coords=this.transformRawCoords(rawCoords,newBox,angle,rotationMatrix);const nextBoundingBox=this.getBoxForHandLandmarks(coords);this.storedBoxes[i]=nextBoundingBox;const result={landmarks:coords,confidence:confidenceValue,box:{topLeft:nextBoundingBox.startPoint,bottomRight:nextBoundingBox.endPoint}};hands.push(result)}else{this.storedBoxes[i]=null}keypoints.dispose()}else{const enlarged=enlargeBox(squarifyBox(shiftBox(currentBox,HAND_BOX_SHIFT_VECTOR)),HAND_BOX_ENLARGE_FACTOR);const result={confidence:currentBox.confidence,box:{topLeft:enlarged.startPoint,bottomRight:enlarged.endPoint}};hands.push(result)}}this.storedBoxes=this.storedBoxes.filter(a=>a!==null);this.detectedHands=hands.length;return hands}calculateLandmarksBoundingBox(landmarks){const xs=landmarks.map(d=>d[0]);const ys=landmarks.map(d=>d[1]);const startPoint=[Math.min(...xs),Math.min(...ys)];const endPoint=[Math.max(...xs),Math.max(...ys)];return{startPoint,endPoint}}}exports2.HandPipeline=HandPipeline});var require_anchors=__commonJS(exports2=>{exports2.anchors=[{w:1,h:1,x_center:.015625,y_center:.015625},{w:1,h:1,x_center:.015625,y_center:.015625},{w:1,h:1,x_center:.046875,y_center:.015625},{w:1,h:1,x_center:.046875,y_center:.015625},{w:1,h:1,x_center:.078125,y_center:.015625},{w:1,h:1,x_center:.078125,y_center:.015625},{w:1,h:1,x_center:.109375,y_center:.015625},{w:1,h:1,x_center:.109375,y_center:.015625},{w:1,h:1,x_center:.140625,y_center:.015625},{w:1,h:1,x_center:.140625,y_center:.015625},{w:1,h:1,x_center:.171875,y_center:.015625},{w:1,h:1,x_center:.171875,y_center:.015625},{w:1,h:1,x_center:.203125,y_center:.015625},{w:1,h:1,x_center:.203125,y_center:.015625},{w:1,h:1,x_center:.234375,y_center:.015625},{w:1,h:1,x_center:.234375,y_center:.015625},{w:1,h:1,x_center:.265625,y_center:.015625},{w:1,h:1,x_center:.265625,y_center:.015625},{w:1,h:1,x_center:.296875,y_center:.015625},{w:1,h:1,x_center:.296875,y_center:.015625},{w:1,h:1,x_center:.328125,y_center:.015625},{w:1,h:1,x_center:.328125,y_center:.015625},{w:1,h:1,x_center:.359375,y_center:.015625},{w:1,h:1,x_center:.359375,y_center:.015625},{w:1,h:1,x_center:.390625,y_center:.015625},{w:1,h:1,x_center:.390625,y_center:.015625},{w:1,h:1,x_center:.421875,y_center:.015625},{w:1,h:1,x_center:.421875,y_center:.015625},{w:1,h:1,x_center:.453125,y_center:.015625},{w:1,h:1,x_center:.453125,y_center:.015625},{w:1,h:1,x_center:.484375,y_center:.015625},{w:1,h:1,x_center:.484375,y_center:.015625},{w:1,h:1,x_center:.515625,y_center:.015625},{w:1,h:1,x_center:.515625,y_center:.015625},{w:1,h:1,x_center:.546875,y_center:.015625},{w:1,h:1,x_center:.546875,y_center:.015625},{w:1,h:1,x_center:.578125,y_center:.015625},{w:1,h:1,x_center:.578125,y_center:.015625},{w:1,h:1,x_center:.609375,y_center:.015625},{w:1,h:1,x_center:.609375,y_center:.015625},{w:1,h:1,x_center:.640625,y_center:.015625},{w:1,h:1,x_center:.640625,y_center:.015625},{w:1,h:1,x_center:.671875,y_center:.015625},{w:1,h:1,x_center:.671875,y_center:.015625},{w:1,h:1,x_center:.703125,y_center:.015625},{w:1,h:1,x_center:.703125,y_center:.015625},{w:1,h:1,x_center:.734375,y_center:.015625},{w:1,h:1,x_center:.734375,y_center:.015625},{w:1,h:1,x_center:.765625,y_center:.015625},{w:1,h:1,x_center:.765625,y_center:.015625},{w:1,h:1,x_center:.796875,y_center:.015625},{w:1,h:1,x_center:.796875,y_center:.015625},{w:1,h:1,x_center:.828125,y_center:.015625},{w:1,h:1,x_center:.828125,y_center:.015625},{w:1,h:1,x_center:.859375,y_center:.015625},{w:1,h:1,x_center:.859375,y_center:.015625},{w:1,h:1,x_center:.890625,y_center:.015625},{w:1,h:1,x_center:.890625,y_center:.015625},{w:1,h:1,x_center:.921875,y_center:.015625},{w:1,h:1,x_center:.921875,y_center:.015625},{w:1,h:1,x_center:.953125,y_center:.015625},{w:1,h:1,x_center:.953125,y_center:.015625},{w:1,h:1,x_center:.984375,y_center:.015625},{w:1,h:1,x_center:.984375,y_center:.015625},{w:1,h:1,x_center:.015625,y_center:.046875},{w:1,h:1,x_center:.015625,y_center:.046875},{w:1,h:1,x_center:.046875,y_center:.046875},{w:1,h:1,x_center:.046875,y_center:.046875},{w:1,h:1,x_center:.078125,y_center:.046875},{w:1,h:1,x_center:.078125,y_center:.046875},{w:1,h:1,x_center:.109375,y_center:.046875},{w:1,h:1,x_center:.109375,y_center:.046875},{w:1,h:1,x_center:.140625,y_center:.046875},{w:1,h:1,x_center:.140625,y_center:.046875},{w:1,h:1,x_center:.171875,y_center:.046875},{w:1,h:1,x_center:.171875,y_center:.046875},{w:1,h:1,x_center:.203125,y_center:.046875},{w:1,h:1,x_center:.203125,y_center:.046875},{w:1,h:1,x_center:.234375,y_center:.046875},{w:1,h:1,x_center:.234375,y_center:.046875},{w:1,h:1,x_center:.265625,y_center:.046875},{w:1,h:1,x_center:.265625,y_center:.046875},{w:1,h:1,x_center:.296875,y_center:.046875},{w:1,h:1,x_center:.296875,y_center:.046875},{w:1,h:1,x_center:.328125,y_center:.046875},{w:1,h:1,x_center:.328125,y_center:.046875},{w:1,h:1,x_center:.359375,y_center:.046875},{w:1,h:1,x_center:.359375,y_center:.046875},{w:1,h:1,x_center:.390625,y_center:.046875},{w:1,h:1,x_center:.390625,y_center:.046875},{w:1,h:1,x_center:.421875,y_center:.046875},{w:1,h:1,x_center:.421875,y_center:.046875},{w:1,h:1,x_center:.453125,y_center:.046875},{w:1,h:1,x_center:.453125,y_center:.046875},{w:1,h:1,x_center:.484375,y_center:.046875},{w:1,h:1,x_center:.484375,y_center:.046875},{w:1,h:1,x_center:.515625,y_center:.046875},{w:1,h:1,x_center:.515625,y_center:.046875},{w:1,h:1,x_center:.546875,y_center:.046875},{w:1,h:1,x_center:.546875,y_center:.046875},{w:1,h:1,x_center:.578125,y_center:.046875},{w:1,h:1,x_center:.578125,y_center:.046875},{w:1,h:1,x_center:.609375,y_center:.046875},{w:1,h:1,x_center:.609375,y_center:.046875},{w:1,h:1,x_center:.640625,y_center:.046875},{w:1,h:1,x_center:.640625,y_center:.046875},{w:1,h:1,x_center:.671875,y_center:.046875},{w:1,h:1,x_center:.671875,y_center:.046875},{w:1,h:1,x_center:.703125,y_center:.046875},{w:1,h:1,x_center:.703125,y_center:.046875},{w:1,h:1,x_center:.734375,y_center:.046875},{w:1,h:1,x_center:.734375,y_center:.046875},{w:1,h:1,x_center:.765625,y_center:.046875},{w:1,h:1,x_center:.765625,y_center:.046875},{w:1,h:1,x_center:.796875,y_center:.046875},{w:1,h:1,x_center:.796875,y_center:.046875},{w:1,h:1,x_center:.828125,y_center:.046875},{w:1,h:1,x_center:.828125,y_center:.046875},{w:1,h:1,x_center:.859375,y_center:.046875},{w:1,h:1,x_center:.859375,y_center:.046875},{w:1,h:1,x_center:.890625,y_center:.046875},{w:1,h:1,x_center:.890625,y_center:.046875},{w:1,h:1,x_center:.921875,y_center:.046875},{w:1,h:1,x_center:.921875,y_center:.046875},{w:1,h:1,x_center:.953125,y_center:.046875},{w:1,h:1,x_center:.953125,y_center:.046875},{w:1,h:1,x_center:.984375,y_center:.046875},{w:1,h:1,x_center:.984375,y_center:.046875},{w:1,h:1,x_center:.015625,y_center:.078125},{w:1,h:1,x_center:.015625,y_center:.078125},{w:1,h:1,x_center:.046875,y_center:.078125},{w:1,h:1,x_center:.046875,y_center:.078125},{w:1,h:1,x_center:.078125,y_center:.078125},{w:1,h:1,x_center:.078125,y_center:.078125},{w:1,h:1,x_center:.109375,y_center:.078125},{w:1,h:1,x_center:.109375,y_center:.078125},{w:1,h:1,x_center:.140625,y_center:.078125},{w:1,h:1,x_center:.140625,y_center:.078125},{w:1,h:1,x_center:.171875,y_center:.078125},{w:1,h:1,x_center:.171875,y_center:.078125},{w:1,h:1,x_center:.203125,y_center:.078125},{w:1,h:1,x_center:.203125,y_center:.078125},{w:1,h:1,x_center:.234375,y_center:.078125},{w:1,h:1,x_center:.234375,y_center:.078125},{w:1,h:1,x_center:.265625,y_center:.078125},{w:1,h:1,x_center:.265625,y_center:.078125},{w:1,h:1,x_center:.296875,y_center:.078125},{w:1,h:1,x_center:.296875,y_center:.078125},{w:1,h:1,x_center:.328125,y_center:.078125},{w:1,h:1,x_center:.328125,y_center:.078125},{w:1,h:1,x_center:.359375,y_center:.078125},{w:1,h:1,x_center:.359375,y_center:.078125},{w:1,h:1,x_center:.390625,y_center:.078125},{w:1,h:1,x_center:.390625,y_center:.078125},{w:1,h:1,x_center:.421875,y_center:.078125},{w:1,h:1,x_center:.421875,y_center:.078125},{w:1,h:1,x_center:.453125,y_center:.078125},{w:1,h:1,x_center:.453125,y_center:.078125},{w:1,h:1,x_center:.484375,y_center:.078125},{w:1,h:1,x_center:.484375,y_center:.078125},{w:1,h:1,x_center:.515625,y_center:.078125},{w:1,h:1,x_center:.515625,y_center:.078125},{w:1,h:1,x_center:.546875,y_center:.078125},{w:1,h:1,x_center:.546875,y_center:.078125},{w:1,h:1,x_center:.578125,y_center:.078125},{w:1,h:1,x_center:.578125,y_center:.078125},{w:1,h:1,x_center:.609375,y_center:.078125},{w:1,h:1,x_center:.609375,y_center:.078125},{w:1,h:1,x_center:.640625,y_center:.078125},{w:1,h:1,x_center:.640625,y_center:.078125},{w:1,h:1,x_center:.671875,y_center:.078125},{w:1,h:1,x_center:.671875,y_center:.078125},{w:1,h:1,x_center:.703125,y_center:.078125},{w:1,h:1,x_center:.703125,y_center:.078125},{w:1,h:1,x_center:.734375,y_center:.078125},{w:1,h:1,x_center:.734375,y_center:.078125},{w:1,h:1,x_center:.765625,y_center:.078125},{w:1,h:1,x_center:.765625,y_center:.078125},{w:1,h:1,x_center:.796875,y_center:.078125},{w:1,h:1,x_center:.796875,y_center:.078125},{w:1,h:1,x_center:.828125,y_center:.078125},{w:1,h:1,x_center:.828125,y_center:.078125},{w:1,h:1,x_center:.859375,y_center:.078125},{w:1,h:1,x_center:.859375,y_center:.078125},{w:1,h:1,x_center:.890625,y_center:.078125},{w:1,h:1,x_center:.890625,y_center:.078125},{w:1,h:1,x_center:.921875,y_center:.078125},{w:1,h:1,x_center:.921875,y_center:.078125},{w:1,h:1,x_center:.953125,y_center:.078125},{w:1,h:1,x_center:.953125,y_center:.078125},{w:1,h:1,x_center:.984375,y_center:.078125},{w:1,h:1,x_center:.984375,y_center:.078125},{w:1,h:1,x_center:.015625,y_center:.109375},{w:1,h:1,x_center:.015625,y_center:.109375},{w:1,h:1,x_center:.046875,y_center:.109375},{w:1,h:1,x_center:.046875,y_center:.109375},{w:1,h:1,x_center:.078125,y_center:.109375},{w:1,h:1,x_center:.078125,y_center:.109375},{w:1,h:1,x_center:.109375,y_center:.109375},{w:1,h:1,x_center:.109375,y_center:.109375},{w:1,h:1,x_center:.140625,y_center:.109375},{w:1,h:1,x_center:.140625,y_center:.109375},{w:1,h:1,x_center:.171875,y_center:.109375},{w:1,h:1,x_center:.171875,y_center:.109375},{w:1,h:1,x_center:.203125,y_center:.109375},{w:1,h:1,x_center:.203125,y_center:.109375},{w:1,h:1,x_center:.234375,y_center:.109375},{w:1,h:1,x_center:.234375,y_center:.109375},{w:1,h:1,x_center:.265625,y_center:.109375},{w:1,h:1,x_center:.265625,y_center:.109375},{w:1,h:1,x_center:.296875,y_center:.109375},{w:1,h:1,x_center:.296875,y_center:.109375},{w:1,h:1,x_center:.328125,y_center:.109375},{w:1,h:1,x_center:.328125,y_center:.109375},{w:1,h:1,x_center:.359375,y_center:.109375},{w:1,h:1,x_center:.359375,y_center:.109375},{w:1,h:1,x_center:.390625,y_center:.109375},{w:1,h:1,x_center:.390625,y_center:.109375},{w:1,h:1,x_center:.421875,y_center:.109375},{w:1,h:1,x_center:.421875,y_center:.109375},{w:1,h:1,x_center:.453125,y_center:.109375},{w:1,h:1,x_center:.453125,y_center:.109375},{w:1,h:1,x_center:.484375,y_center:.109375},{w:1,h:1,x_center:.484375,y_center:.109375},{w:1,h:1,x_center:.515625,y_center:.109375},{w:1,h:1,x_center:.515625,y_center:.109375},{w:1,h:1,x_center:.546875,y_center:.109375},{w:1,h:1,x_center:.546875,y_center:.109375},{w:1,h:1,x_center:.578125,y_center:.109375},{w:1,h:1,x_center:.578125,y_center:.109375},{w:1,h:1,x_center:.609375,y_center:.109375},{w:1,h:1,x_center:.609375,y_center:.109375},{w:1,h:1,x_center:.640625,y_center:.109375},{w:1,h:1,x_center:.640625,y_center:.109375},{w:1,h:1,x_center:.671875,y_center:.109375},{w:1,h:1,x_center:.671875,y_center:.109375},{w:1,h:1,x_center:.703125,y_center:.109375},{w:1,h:1,x_center:.703125,y_center:.109375},{w:1,h:1,x_center:.734375,y_center:.109375},{w:1,h:1,x_center:.734375,y_center:.109375},{w:1,h:1,x_center:.765625,y_center:.109375},{w:1,h:1,x_center:.765625,y_center:.109375},{w:1,h:1,x_center:.796875,y_center:.109375},{w:1,h:1,x_center:.796875,y_center:.109375},{w:1,h:1,x_center:.828125,y_center:.109375},{w:1,h:1,x_center:.828125,y_center:.109375},{w:1,h:1,x_center:.859375,y_center:.109375},{w:1,h:1,x_center:.859375,y_center:.109375},{w:1,h:1,x_center:.890625,y_center:.109375},{w:1,h:1,x_center:.890625,y_center:.109375},{w:1,h:1,x_center:.921875,y_center:.109375},{w:1,h:1,x_center:.921875,y_center:.109375},{w:1,h:1,x_center:.953125,y_center:.109375},{w:1,h:1,x_center:.953125,y_center:.109375},{w:1,h:1,x_center:.984375,y_center:.109375},{w:1,h:1,x_center:.984375,y_center:.109375},{w:1,h:1,x_center:.015625,y_center:.140625},{w:1,h:1,x_center:.015625,y_center:.140625},{w:1,h:1,x_center:.046875,y_center:.140625},{w:1,h:1,x_center:.046875,y_center:.140625},{w:1,h:1,x_center:.078125,y_center:.140625},{w:1,h:1,x_center:.078125,y_center:.140625},{w:1,h:1,x_center:.109375,y_center:.140625},{w:1,h:1,x_center:.109375,y_center:.140625},{w:1,h:1,x_center:.140625,y_center:.140625},{w:1,h:1,x_center:.140625,y_center:.140625},{w:1,h:1,x_center:.171875,y_center:.140625},{w:1,h:1,x_center:.171875,y_center:.140625},{w:1,h:1,x_center:.203125,y_center:.140625},{w:1,h:1,x_center:.203125,y_center:.140625},{w:1,h:1,x_center:.234375,y_center:.140625},{w:1,h:1,x_center:.234375,y_center:.140625},{w:1,h:1,x_center:.265625,y_center:.140625},{w:1,h:1,x_center:.265625,y_center:.140625},{w:1,h:1,x_center:.296875,y_center:.140625},{w:1,h:1,x_center:.296875,y_center:.140625},{w:1,h:1,x_center:.328125,y_center:.140625},{w:1,h:1,x_center:.328125,y_center:.140625},{w:1,h:1,x_center:.359375,y_center:.140625},{w:1,h:1,x_center:.359375,y_center:.140625},{w:1,h:1,x_center:.390625,y_center:.140625},{w:1,h:1,x_center:.390625,y_center:.140625},{w:1,h:1,x_center:.421875,y_center:.140625},{w:1,h:1,x_center:.421875,y_center:.140625},{w:1,h:1,x_center:.453125,y_center:.140625},{w:1,h:1,x_center:.453125,y_center:.140625},{w:1,h:1,x_center:.484375,y_center:.140625},{w:1,h:1,x_center:.484375,y_center:.140625},{w:1,h:1,x_center:.515625,y_center:.140625},{w:1,h:1,x_center:.515625,y_center:.140625},{w:1,h:1,x_center:.546875,y_center:.140625},{w:1,h:1,x_center:.546875,y_center:.140625},{w:1,h:1,x_center:.578125,y_center:.140625},{w:1,h:1,x_center:.578125,y_center:.140625},{w:1,h:1,x_center:.609375,y_center:.140625},{w:1,h:1,x_center:.609375,y_center:.140625},{w:1,h:1,x_center:.640625,y_center:.140625},{w:1,h:1,x_center:.640625,y_center:.140625},{w:1,h:1,x_center:.671875,y_center:.140625},{w:1,h:1,x_center:.671875,y_center:.140625},{w:1,h:1,x_center:.703125,y_center:.140625},{w:1,h:1,x_center:.703125,y_center:.140625},{w:1,h:1,x_center:.734375,y_center:.140625},{w:1,h:1,x_center:.734375,y_center:.140625},{w:1,h:1,x_center:.765625,y_center:.140625},{w:1,h:1,x_center:.765625,y_center:.140625},{w:1,h:1,x_center:.796875,y_center:.140625},{w:1,h:1,x_center:.796875,y_center:.140625},{w:1,h:1,x_center:.828125,y_center:.140625},{w:1,h:1,x_center:.828125,y_center:.140625},{w:1,h:1,x_center:.859375,y_center:.140625},{w:1,h:1,x_center:.859375,y_center:.140625},{w:1,h:1,x_center:.890625,y_center:.140625},{w:1,h:1,x_center:.890625,y_center:.140625},{w:1,h:1,x_center:.921875,y_center:.140625},{w:1,h:1,x_center:.921875,y_center:.140625},{w:1,h:1,x_center:.953125,y_center:.140625},{w:1,h:1,x_center:.953125,y_center:.140625},{w:1,h:1,x_center:.984375,y_center:.140625},{w:1,h:1,x_center:.984375,y_center:.140625},{w:1,h:1,x_center:.015625,y_center:.171875},{w:1,h:1,x_center:.015625,y_center:.171875},{w:1,h:1,x_center:.046875,y_center:.171875},{w:1,h:1,x_center:.046875,y_center:.171875},{w:1,h:1,x_center:.078125,y_center:.171875},{w:1,h:1,x_center:.078125,y_center:.171875},{w:1,h:1,x_center:.109375,y_center:.171875},{w:1,h:1,x_center:.109375,y_center:.171875},{w:1,h:1,x_center:.140625,y_center:.171875},{w:1,h:1,x_center:.140625,y_center:.171875},{w:1,h:1,x_center:.171875,y_center:.171875},{w:1,h:1,x_center:.171875,y_center:.171875},{w:1,h:1,x_center:.203125,y_center:.171875},{w:1,h:1,x_center:.203125,y_center:.171875},{w:1,h:1,x_center:.234375,y_center:.171875},{w:1,h:1,x_center:.234375,y_center:.171875},{w:1,h:1,x_center:.265625,y_center:.171875},{w:1,h:1,x_center:.265625,y_center:.171875},{w:1,h:1,x_center:.296875,y_center:.171875},{w:1,h:1,x_center:.296875,y_center:.171875},{w:1,h:1,x_center:.328125,y_center:.171875},{w:1,h:1,x_center:.328125,y_center:.171875},{w:1,h:1,x_center:.359375,y_center:.171875},{w:1,h:1,x_center:.359375,y_center:.171875},{w:1,h:1,x_center:.390625,y_center:.171875},{w:1,h:1,x_center:.390625,y_center:.171875},{w:1,h:1,x_center:.421875,y_center:.171875},{w:1,h:1,x_center:.421875,y_center:.171875},{w:1,h:1,x_center:.453125,y_center:.171875},{w:1,h:1,x_center:.453125,y_center:.171875},{w:1,h:1,x_center:.484375,y_center:.171875},{w:1,h:1,x_center:.484375,y_center:.171875},{w:1,h:1,x_center:.515625,y_center:.171875},{w:1,h:1,x_center:.515625,y_center:.171875},{w:1,h:1,x_center:.546875,y_center:.171875},{w:1,h:1,x_center:.546875,y_center:.171875},{w:1,h:1,x_center:.578125,y_center:.171875},{w:1,h:1,x_center:.578125,y_center:.171875},{w:1,h:1,x_center:.609375,y_center:.171875},{w:1,h:1,x_center:.609375,y_center:.171875},{w:1,h:1,x_center:.640625,y_center:.171875},{w:1,h:1,x_center:.640625,y_center:.171875},{w:1,h:1,x_center:.671875,y_center:.171875},{w:1,h:1,x_center:.671875,y_center:.171875},{w:1,h:1,x_center:.703125,y_center:.171875},{w:1,h:1,x_center:.703125,y_center:.171875},{w:1,h:1,x_center:.734375,y_center:.171875},{w:1,h:1,x_center:.734375,y_center:.171875},{w:1,h:1,x_center:.765625,y_center:.171875},{w:1,h:1,x_center:.765625,y_center:.171875},{w:1,h:1,x_center:.796875,y_center:.171875},{w:1,h:1,x_center:.796875,y_center:.171875},{w:1,h:1,x_center:.828125,y_center:.171875},{w:1,h:1,x_center:.828125,y_center:.171875},{w:1,h:1,x_center:.859375,y_center:.171875},{w:1,h:1,x_center:.859375,y_center:.171875},{w:1,h:1,x_center:.890625,y_center:.171875},{w:1,h:1,x_center:.890625,y_center:.171875},{w:1,h:1,x_center:.921875,y_center:.171875},{w:1,h:1,x_center:.921875,y_center:.171875},{w:1,h:1,x_center:.953125,y_center:.171875},{w:1,h:1,x_center:.953125,y_center:.171875},{w:1,h:1,x_center:.984375,y_center:.171875},{w:1,h:1,x_center:.984375,y_center:.171875},{w:1,h:1,x_center:.015625,y_center:.203125},{w:1,h:1,x_center:.015625,y_center:.203125},{w:1,h:1,x_center:.046875,y_center:.203125},{w:1,h:1,x_center:.046875,y_center:.203125},{w:1,h:1,x_center:.078125,y_center:.203125},{w:1,h:1,x_center:.078125,y_center:.203125},{w:1,h:1,x_center:.109375,y_center:.203125},{w:1,h:1,x_center:.109375,y_center:.203125},{w:1,h:1,x_center:.140625,y_center:.203125},{w:1,h:1,x_center:.140625,y_center:.203125},{w:1,h:1,x_center:.171875,y_center:.203125},{w:1,h:1,x_center:.171875,y_center:.203125},{w:1,h:1,x_center:.203125,y_center:.203125},{w:1,h:1,x_center:.203125,y_center:.203125},{w:1,h:1,x_center:.234375,y_center:.203125},{w:1,h:1,x_center:.234375,y_center:.203125},{w:1,h:1,x_center:.265625,y_center:.203125},{w:1,h:1,x_center:.265625,y_center:.203125},{w:1,h:1,x_center:.296875,y_center:.203125},{w:1,h:1,x_center:.296875,y_center:.203125},{w:1,h:1,x_center:.328125,y_center:.203125},{w:1,h:1,x_center:.328125,y_center:.203125},{w:1,h:1,x_center:.359375,y_center:.203125},{w:1,h:1,x_center:.359375,y_center:.203125},{w:1,h:1,x_center:.390625,y_center:.203125},{w:1,h:1,x_center:.390625,y_center:.203125},{w:1,h:1,x_center:.421875,y_center:.203125},{w:1,h:1,x_center:.421875,y_center:.203125},{w:1,h:1,x_center:.453125,y_center:.203125},{w:1,h:1,x_center:.453125,y_center:.203125},{w:1,h:1,x_center:.484375,y_center:.203125},{w:1,h:1,x_center:.484375,y_center:.203125},{w:1,h:1,x_center:.515625,y_center:.203125},{w:1,h:1,x_center:.515625,y_center:.203125},{w:1,h:1,x_center:.546875,y_center:.203125},{w:1,h:1,x_center:.546875,y_center:.203125},{w:1,h:1,x_center:.578125,y_center:.203125},{w:1,h:1,x_center:.578125,y_center:.203125},{w:1,h:1,x_center:.609375,y_center:.203125},{w:1,h:1,x_center:.609375,y_center:.203125},{w:1,h:1,x_center:.640625,y_center:.203125},{w:1,h:1,x_center:.640625,y_center:.203125},{w:1,h:1,x_center:.671875,y_center:.203125},{w:1,h:1,x_center:.671875,y_center:.203125},{w:1,h:1,x_center:.703125,y_center:.203125},{w:1,h:1,x_center:.703125,y_center:.203125},{w:1,h:1,x_center:.734375,y_center:.203125},{w:1,h:1,x_center:.734375,y_center:.203125},{w:1,h:1,x_center:.765625,y_center:.203125},{w:1,h:1,x_center:.765625,y_center:.203125},{w:1,h:1,x_center:.796875,y_center:.203125},{w:1,h:1,x_center:.796875,y_center:.203125},{w:1,h:1,x_center:.828125,y_center:.203125},{w:1,h:1,x_center:.828125,y_center:.203125},{w:1,h:1,x_center:.859375,y_center:.203125},{w:1,h:1,x_center:.859375,y_center:.203125},{w:1,h:1,x_center:.890625,y_center:.203125},{w:1,h:1,x_center:.890625,y_center:.203125},{w:1,h:1,x_center:.921875,y_center:.203125},{w:1,h:1,x_center:.921875,y_center:.203125},{w:1,h:1,x_center:.953125,y_center:.203125},{w:1,h:1,x_center:.953125,y_center:.203125},{w:1,h:1,x_center:.984375,y_center:.203125},{w:1,h:1,x_center:.984375,y_center:.203125},{w:1,h:1,x_center:.015625,y_center:.234375},{w:1,h:1,x_center:.015625,y_center:.234375},{w:1,h:1,x_center:.046875,y_center:.234375},{w:1,h:1,x_center:.046875,y_center:.234375},{w:1,h:1,x_center:.078125,y_center:.234375},{w:1,h:1,x_center:.078125,y_center:.234375},{w:1,h:1,x_center:.109375,y_center:.234375},{w:1,h:1,x_center:.109375,y_center:.234375},{w:1,h:1,x_center:.140625,y_center:.234375},{w:1,h:1,x_center:.140625,y_center:.234375},{w:1,h:1,x_center:.171875,y_center:.234375},{w:1,h:1,x_center:.171875,y_center:.234375},{w:1,h:1,x_center:.203125,y_center:.234375},{w:1,h:1,x_center:.203125,y_center:.234375},{w:1,h:1,x_center:.234375,y_center:.234375},{w:1,h:1,x_center:.234375,y_center:.234375},{w:1,h:1,x_center:.265625,y_center:.234375},{w:1,h:1,x_center:.265625,y_center:.234375},{w:1,h:1,x_center:.296875,y_center:.234375},{w:1,h:1,x_center:.296875,y_center:.234375},{w:1,h:1,x_center:.328125,y_center:.234375},{w:1,h:1,x_center:.328125,y_center:.234375},{w:1,h:1,x_center:.359375,y_center:.234375},{w:1,h:1,x_center:.359375,y_center:.234375},{w:1,h:1,x_center:.390625,y_center:.234375},{w:1,h:1,x_center:.390625,y_center:.234375},{w:1,h:1,x_center:.421875,y_center:.234375},{w:1,h:1,x_center:.421875,y_center:.234375},{w:1,h:1,x_center:.453125,y_center:.234375},{w:1,h:1,x_center:.453125,y_center:.234375},{w:1,h:1,x_center:.484375,y_center:.234375},{w:1,h:1,x_center:.484375,y_center:.234375},{w:1,h:1,x_center:.515625,y_center:.234375},{w:1,h:1,x_center:.515625,y_center:.234375},{w:1,h:1,x_center:.546875,y_center:.234375},{w:1,h:1,x_center:.546875,y_center:.234375},{w:1,h:1,x_center:.578125,y_center:.234375},{w:1,h:1,x_center:.578125,y_center:.234375},{w:1,h:1,x_center:.609375,y_center:.234375},{w:1,h:1,x_center:.609375,y_center:.234375},{w:1,h:1,x_center:.640625,y_center:.234375},{w:1,h:1,x_center:.640625,y_center:.234375},{w:1,h:1,x_center:.671875,y_center:.234375},{w:1,h:1,x_center:.671875,y_center:.234375},{w:1,h:1,x_center:.703125,y_center:.234375},{w:1,h:1,x_center:.703125,y_center:.234375},{w:1,h:1,x_center:.734375,y_center:.234375},{w:1,h:1,x_center:.734375,y_center:.234375},{w:1,h:1,x_center:.765625,y_center:.234375},{w:1,h:1,x_center:.765625,y_center:.234375},{w:1,h:1,x_center:.796875,y_center:.234375},{w:1,h:1,x_center:.796875,y_center:.234375},{w:1,h:1,x_center:.828125,y_center:.234375},{w:1,h:1,x_center:.828125,y_center:.234375},{w:1,h:1,x_center:.859375,y_center:.234375},{w:1,h:1,x_center:.859375,y_center:.234375},{w:1,h:1,x_center:.890625,y_center:.234375},{w:1,h:1,x_center:.890625,y_center:.234375},{w:1,h:1,x_center:.921875,y_center:.234375},{w:1,h:1,x_center:.921875,y_center:.234375},{w:1,h:1,x_center:.953125,y_center:.234375},{w:1,h:1,x_center:.953125,y_center:.234375},{w:1,h:1,x_center:.984375,y_center:.234375},{w:1,h:1,x_center:.984375,y_center:.234375},{w:1,h:1,x_center:.015625,y_center:.265625},{w:1,h:1,x_center:.015625,y_center:.265625},{w:1,h:1,x_center:.046875,y_center:.265625},{w:1,h:1,x_center:.046875,y_center:.265625},{w:1,h:1,x_center:.078125,y_center:.265625},{w:1,h:1,x_center:.078125,y_center:.265625},{w:1,h:1,x_center:.109375,y_center:.265625},{w:1,h:1,x_center:.109375,y_center:.265625},{w:1,h:1,x_center:.140625,y_center:.265625},{w:1,h:1,x_center:.140625,y_center:.265625},{w:1,h:1,x_center:.171875,y_center:.265625},{w:1,h:1,x_center:.171875,y_center:.265625},{w:1,h:1,x_center:.203125,y_center:.265625},{w:1,h:1,x_center:.203125,y_center:.265625},{w:1,h:1,x_center:.234375,y_center:.265625},{w:1,h:1,x_center:.234375,y_center:.265625},{w:1,h:1,x_center:.265625,y_center:.265625},{w:1,h:1,x_center:.265625,y_center:.265625},{w:1,h:1,x_center:.296875,y_center:.265625},{w:1,h:1,x_center:.296875,y_center:.265625},{w:1,h:1,x_center:.328125,y_center:.265625},{w:1,h:1,x_center:.328125,y_center:.265625},{w:1,h:1,x_center:.359375,y_center:.265625},{w:1,h:1,x_center:.359375,y_center:.265625},{w:1,h:1,x_center:.390625,y_center:.265625},{w:1,h:1,x_center:.390625,y_center:.265625},{w:1,h:1,x_center:.421875,y_center:.265625},{w:1,h:1,x_center:.421875,y_center:.265625},{w:1,h:1,x_center:.453125,y_center:.265625},{w:1,h:1,x_center:.453125,y_center:.265625},{w:1,h:1,x_center:.484375,y_center:.265625},{w:1,h:1,x_center:.484375,y_center:.265625},{w:1,h:1,x_center:.515625,y_center:.265625},{w:1,h:1,x_center:.515625,y_center:.265625},{w:1,h:1,x_center:.546875,y_center:.265625},{w:1,h:1,x_center:.546875,y_center:.265625},{w:1,h:1,x_center:.578125,y_center:.265625},{w:1,h:1,x_center:.578125,y_center:.265625},{w:1,h:1,x_center:.609375,y_center:.265625},{w:1,h:1,x_center:.609375,y_center:.265625},{w:1,h:1,x_center:.640625,y_center:.265625},{w:1,h:1,x_center:.640625,y_center:.265625},{w:1,h:1,x_center:.671875,y_center:.265625},{w:1,h:1,x_center:.671875,y_center:.265625},{w:1,h:1,x_center:.703125,y_center:.265625},{w:1,h:1,x_center:.703125,y_center:.265625},{w:1,h:1,x_center:.734375,y_center:.265625},{w:1,h:1,x_center:.734375,y_center:.265625},{w:1,h:1,x_center:.765625,y_center:.265625},{w:1,h:1,x_center:.765625,y_center:.265625},{w:1,h:1,x_center:.796875,y_center:.265625},{w:1,h:1,x_center:.796875,y_center:.265625},{w:1,h:1,x_center:.828125,y_center:.265625},{w:1,h:1,x_center:.828125,y_center:.265625},{w:1,h:1,x_center:.859375,y_center:.265625},{w:1,h:1,x_center:.859375,y_center:.265625},{w:1,h:1,x_center:.890625,y_center:.265625},{w:1,h:1,x_center:.890625,y_center:.265625},{w:1,h:1,x_center:.921875,y_center:.265625},{w:1,h:1,x_center:.921875,y_center:.265625},{w:1,h:1,x_center:.953125,y_center:.265625},{w:1,h:1,x_center:.953125,y_center:.265625},{w:1,h:1,x_center:.984375,y_center:.265625},{w:1,h:1,x_center:.984375,y_center:.265625},{w:1,h:1,x_center:.015625,y_center:.296875},{w:1,h:1,x_center:.015625,y_center:.296875},{w:1,h:1,x_center:.046875,y_center:.296875},{w:1,h:1,x_center:.046875,y_center:.296875},{w:1,h:1,x_center:.078125,y_center:.296875},{w:1,h:1,x_center:.078125,y_center:.296875},{w:1,h:1,x_center:.109375,y_center:.296875},{w:1,h:1,x_center:.109375,y_center:.296875},{w:1,h:1,x_center:.140625,y_center:.296875},{w:1,h:1,x_center:.140625,y_center:.296875},{w:1,h:1,x_center:.171875,y_center:.296875},{w:1,h:1,x_center:.171875,y_center:.296875},{w:1,h:1,x_center:.203125,y_center:.296875},{w:1,h:1,x_center:.203125,y_center:.296875},{w:1,h:1,x_center:.234375,y_center:.296875},{w:1,h:1,x_center:.234375,y_center:.296875},{w:1,h:1,x_center:.265625,y_center:.296875},{w:1,h:1,x_center:.265625,y_center:.296875},{w:1,h:1,x_center:.296875,y_center:.296875},{w:1,h:1,x_center:.296875,y_center:.296875},{w:1,h:1,x_center:.328125,y_center:.296875},{w:1,h:1,x_center:.328125,y_center:.296875},{w:1,h:1,x_center:.359375,y_center:.296875},{w:1,h:1,x_center:.359375,y_center:.296875},{w:1,h:1,x_center:.390625,y_center:.296875},{w:1,h:1,x_center:.390625,y_center:.296875},{w:1,h:1,x_center:.421875,y_center:.296875},{w:1,h:1,x_center:.421875,y_center:.296875},{w:1,h:1,x_center:.453125,y_center:.296875},{w:1,h:1,x_center:.453125,y_center:.296875},{w:1,h:1,x_center:.484375,y_center:.296875},{w:1,h:1,x_center:.484375,y_center:.296875},{w:1,h:1,x_center:.515625,y_center:.296875},{w:1,h:1,x_center:.515625,y_center:.296875},{w:1,h:1,x_center:.546875,y_center:.296875},{w:1,h:1,x_center:.546875,y_center:.296875},{w:1,h:1,x_center:.578125,y_center:.296875},{w:1,h:1,x_center:.578125,y_center:.296875},{w:1,h:1,x_center:.609375,y_center:.296875},{w:1,h:1,x_center:.609375,y_center:.296875},{w:1,h:1,x_center:.640625,y_center:.296875},{w:1,h:1,x_center:.640625,y_center:.296875},{w:1,h:1,x_center:.671875,y_center:.296875},{w:1,h:1,x_center:.671875,y_center:.296875},{w:1,h:1,x_center:.703125,y_center:.296875},{w:1,h:1,x_center:.703125,y_center:.296875},{w:1,h:1,x_center:.734375,y_center:.296875},{w:1,h:1,x_center:.734375,y_center:.296875},{w:1,h:1,x_center:.765625,y_center:.296875},{w:1,h:1,x_center:.765625,y_center:.296875},{w:1,h:1,x_center:.796875,y_center:.296875},{w:1,h:1,x_center:.796875,y_center:.296875},{w:1,h:1,x_center:.828125,y_center:.296875},{w:1,h:1,x_center:.828125,y_center:.296875},{w:1,h:1,x_center:.859375,y_center:.296875},{w:1,h:1,x_center:.859375,y_center:.296875},{w:1,h:1,x_center:.890625,y_center:.296875},{w:1,h:1,x_center:.890625,y_center:.296875},{w:1,h:1,x_center:.921875,y_center:.296875},{w:1,h:1,x_center:.921875,y_center:.296875},{w:1,h:1,x_center:.953125,y_center:.296875},{w:1,h:1,x_center:.953125,y_center:.296875},{w:1,h:1,x_center:.984375,y_center:.296875},{w:1,h:1,x_center:.984375,y_center:.296875},{w:1,h:1,x_center:.015625,y_center:.328125},{w:1,h:1,x_center:.015625,y_center:.328125},{w:1,h:1,x_center:.046875,y_center:.328125},{w:1,h:1,x_center:.046875,y_center:.328125},{w:1,h:1,x_center:.078125,y_center:.328125},{w:1,h:1,x_center:.078125,y_center:.328125},{w:1,h:1,x_center:.109375,y_center:.328125},{w:1,h:1,x_center:.109375,y_center:.328125},{w:1,h:1,x_center:.140625,y_center:.328125},{w:1,h:1,x_center:.140625,y_center:.328125},{w:1,h:1,x_center:.171875,y_center:.328125},{w:1,h:1,x_center:.171875,y_center:.328125},{w:1,h:1,x_center:.203125,y_center:.328125},{w:1,h:1,x_center:.203125,y_center:.328125},{w:1,h:1,x_center:.234375,y_center:.328125},{w:1,h:1,x_center:.234375,y_center:.328125},{w:1,h:1,x_center:.265625,y_center:.328125},{w:1,h:1,x_center:.265625,y_center:.328125},{w:1,h:1,x_center:.296875,y_center:.328125},{w:1,h:1,x_center:.296875,y_center:.328125},{w:1,h:1,x_center:.328125,y_center:.328125},{w:1,h:1,x_center:.328125,y_center:.328125},{w:1,h:1,x_center:.359375,y_center:.328125},{w:1,h:1,x_center:.359375,y_center:.328125},{w:1,h:1,x_center:.390625,y_center:.328125},{w:1,h:1,x_center:.390625,y_center:.328125},{w:1,h:1,x_center:.421875,y_center:.328125},{w:1,h:1,x_center:.421875,y_center:.328125},{w:1,h:1,x_center:.453125,y_center:.328125},{w:1,h:1,x_center:.453125,y_center:.328125},{w:1,h:1,x_center:.484375,y_center:.328125},{w:1,h:1,x_center:.484375,y_center:.328125},{w:1,h:1,x_center:.515625,y_center:.328125},{w:1,h:1,x_center:.515625,y_center:.328125},{w:1,h:1,x_center:.546875,y_center:.328125},{w:1,h:1,x_center:.546875,y_center:.328125},{w:1,h:1,x_center:.578125,y_center:.328125},{w:1,h:1,x_center:.578125,y_center:.328125},{w:1,h:1,x_center:.609375,y_center:.328125},{w:1,h:1,x_center:.609375,y_center:.328125},{w:1,h:1,x_center:.640625,y_center:.328125},{w:1,h:1,x_center:.640625,y_center:.328125},{w:1,h:1,x_center:.671875,y_center:.328125},{w:1,h:1,x_center:.671875,y_center:.328125},{w:1,h:1,x_center:.703125,y_center:.328125},{w:1,h:1,x_center:.703125,y_center:.328125},{w:1,h:1,x_center:.734375,y_center:.328125},{w:1,h:1,x_center:.734375,y_center:.328125},{w:1,h:1,x_center:.765625,y_center:.328125},{w:1,h:1,x_center:.765625,y_center:.328125},{w:1,h:1,x_center:.796875,y_center:.328125},{w:1,h:1,x_center:.796875,y_center:.328125},{w:1,h:1,x_center:.828125,y_center:.328125},{w:1,h:1,x_center:.828125,y_center:.328125},{w:1,h:1,x_center:.859375,y_center:.328125},{w:1,h:1,x_center:.859375,y_center:.328125},{w:1,h:1,x_center:.890625,y_center:.328125},{w:1,h:1,x_center:.890625,y_center:.328125},{w:1,h:1,x_center:.921875,y_center:.328125},{w:1,h:1,x_center:.921875,y_center:.328125},{w:1,h:1,x_center:.953125,y_center:.328125},{w:1,h:1,x_center:.953125,y_center:.328125},{w:1,h:1,x_center:.984375,y_center:.328125},{w:1,h:1,x_center:.984375,y_center:.328125},{w:1,h:1,x_center:.015625,y_center:.359375},{w:1,h:1,x_center:.015625,y_center:.359375},{w:1,h:1,x_center:.046875,y_center:.359375},{w:1,h:1,x_center:.046875,y_center:.359375},{w:1,h:1,x_center:.078125,y_center:.359375},{w:1,h:1,x_center:.078125,y_center:.359375},{w:1,h:1,x_center:.109375,y_center:.359375},{w:1,h:1,x_center:.109375,y_center:.359375},{w:1,h:1,x_center:.140625,y_center:.359375},{w:1,h:1,x_center:.140625,y_center:.359375},{w:1,h:1,x_center:.171875,y_center:.359375},{w:1,h:1,x_center:.171875,y_center:.359375},{w:1,h:1,x_center:.203125,y_center:.359375},{w:1,h:1,x_center:.203125,y_center:.359375},{w:1,h:1,x_center:.234375,y_center:.359375},{w:1,h:1,x_center:.234375,y_center:.359375},{w:1,h:1,x_center:.265625,y_center:.359375},{w:1,h:1,x_center:.265625,y_center:.359375},{w:1,h:1,x_center:.296875,y_center:.359375},{w:1,h:1,x_center:.296875,y_center:.359375},{w:1,h:1,x_center:.328125,y_center:.359375},{w:1,h:1,x_center:.328125,y_center:.359375},{w:1,h:1,x_center:.359375,y_center:.359375},{w:1,h:1,x_center:.359375,y_center:.359375},{w:1,h:1,x_center:.390625,y_center:.359375},{w:1,h:1,x_center:.390625,y_center:.359375},{w:1,h:1,x_center:.421875,y_center:.359375},{w:1,h:1,x_center:.421875,y_center:.359375},{w:1,h:1,x_center:.453125,y_center:.359375},{w:1,h:1,x_center:.453125,y_center:.359375},{w:1,h:1,x_center:.484375,y_center:.359375},{w:1,h:1,x_center:.484375,y_center:.359375},{w:1,h:1,x_center:.515625,y_center:.359375},{w:1,h:1,x_center:.515625,y_center:.359375},{w:1,h:1,x_center:.546875,y_center:.359375},{w:1,h:1,x_center:.546875,y_center:.359375},{w:1,h:1,x_center:.578125,y_center:.359375},{w:1,h:1,x_center:.578125,y_center:.359375},{w:1,h:1,x_center:.609375,y_center:.359375},{w:1,h:1,x_center:.609375,y_center:.359375},{w:1,h:1,x_center:.640625,y_center:.359375},{w:1,h:1,x_center:.640625,y_center:.359375},{w:1,h:1,x_center:.671875,y_center:.359375},{w:1,h:1,x_center:.671875,y_center:.359375},{w:1,h:1,x_center:.703125,y_center:.359375},{w:1,h:1,x_center:.703125,y_center:.359375},{w:1,h:1,x_center:.734375,y_center:.359375},{w:1,h:1,x_center:.734375,y_center:.359375},{w:1,h:1,x_center:.765625,y_center:.359375},{w:1,h:1,x_center:.765625,y_center:.359375},{w:1,h:1,x_center:.796875,y_center:.359375},{w:1,h:1,x_center:.796875,y_center:.359375},{w:1,h:1,x_center:.828125,y_center:.359375},{w:1,h:1,x_center:.828125,y_center:.359375},{w:1,h:1,x_center:.859375,y_center:.359375},{w:1,h:1,x_center:.859375,y_center:.359375},{w:1,h:1,x_center:.890625,y_center:.359375},{w:1,h:1,x_center:.890625,y_center:.359375},{w:1,h:1,x_center:.921875,y_center:.359375},{w:1,h:1,x_center:.921875,y_center:.359375},{w:1,h:1,x_center:.953125,y_center:.359375},{w:1,h:1,x_center:.953125,y_center:.359375},{w:1,h:1,x_center:.984375,y_center:.359375},{w:1,h:1,x_center:.984375,y_center:.359375},{w:1,h:1,x_center:.015625,y_center:.390625},{w:1,h:1,x_center:.015625,y_center:.390625},{w:1,h:1,x_center:.046875,y_center:.390625},{w:1,h:1,x_center:.046875,y_center:.390625},{w:1,h:1,x_center:.078125,y_center:.390625},{w:1,h:1,x_center:.078125,y_center:.390625},{w:1,h:1,x_center:.109375,y_center:.390625},{w:1,h:1,x_center:.109375,y_center:.390625},{w:1,h:1,x_center:.140625,y_center:.390625},{w:1,h:1,x_center:.140625,y_center:.390625},{w:1,h:1,x_center:.171875,y_center:.390625},{w:1,h:1,x_center:.171875,y_center:.390625},{w:1,h:1,x_center:.203125,y_center:.390625},{w:1,h:1,x_center:.203125,y_center:.390625},{w:1,h:1,x_center:.234375,y_center:.390625},{w:1,h:1,x_center:.234375,y_center:.390625},{w:1,h:1,x_center:.265625,y_center:.390625},{w:1,h:1,x_center:.265625,y_center:.390625},{w:1,h:1,x_center:.296875,y_center:.390625},{w:1,h:1,x_center:.296875,y_center:.390625},{w:1,h:1,x_center:.328125,y_center:.390625},{w:1,h:1,x_center:.328125,y_center:.390625},{w:1,h:1,x_center:.359375,y_center:.390625},{w:1,h:1,x_center:.359375,y_center:.390625},{w:1,h:1,x_center:.390625,y_center:.390625},{w:1,h:1,x_center:.390625,y_center:.390625},{w:1,h:1,x_center:.421875,y_center:.390625},{w:1,h:1,x_center:.421875,y_center:.390625},{w:1,h:1,x_center:.453125,y_center:.390625},{w:1,h:1,x_center:.453125,y_center:.390625},{w:1,h:1,x_center:.484375,y_center:.390625},{w:1,h:1,x_center:.484375,y_center:.390625},{w:1,h:1,x_center:.515625,y_center:.390625},{w:1,h:1,x_center:.515625,y_center:.390625},{w:1,h:1,x_center:.546875,y_center:.390625},{w:1,h:1,x_center:.546875,y_center:.390625},{w:1,h:1,x_center:.578125,y_center:.390625},{w:1,h:1,x_center:.578125,y_center:.390625},{w:1,h:1,x_center:.609375,y_center:.390625},{w:1,h:1,x_center:.609375,y_center:.390625},{w:1,h:1,x_center:.640625,y_center:.390625},{w:1,h:1,x_center:.640625,y_center:.390625},{w:1,h:1,x_center:.671875,y_center:.390625},{w:1,h:1,x_center:.671875,y_center:.390625},{w:1,h:1,x_center:.703125,y_center:.390625},{w:1,h:1,x_center:.703125,y_center:.390625},{w:1,h:1,x_center:.734375,y_center:.390625},{w:1,h:1,x_center:.734375,y_center:.390625},{w:1,h:1,x_center:.765625,y_center:.390625},{w:1,h:1,x_center:.765625,y_center:.390625},{w:1,h:1,x_center:.796875,y_center:.390625},{w:1,h:1,x_center:.796875,y_center:.390625},{w:1,h:1,x_center:.828125,y_center:.390625},{w:1,h:1,x_center:.828125,y_center:.390625},{w:1,h:1,x_center:.859375,y_center:.390625},{w:1,h:1,x_center:.859375,y_center:.390625},{w:1,h:1,x_center:.890625,y_center:.390625},{w:1,h:1,x_center:.890625,y_center:.390625},{w:1,h:1,x_center:.921875,y_center:.390625},{w:1,h:1,x_center:.921875,y_center:.390625},{w:1,h:1,x_center:.953125,y_center:.390625},{w:1,h:1,x_center:.953125,y_center:.390625},{w:1,h:1,x_center:.984375,y_center:.390625},{w:1,h:1,x_center:.984375,y_center:.390625},{w:1,h:1,x_center:.015625,y_center:.421875},{w:1,h:1,x_center:.015625,y_center:.421875},{w:1,h:1,x_center:.046875,y_center:.421875},{w:1,h:1,x_center:.046875,y_center:.421875},{w:1,h:1,x_center:.078125,y_center:.421875},{w:1,h:1,x_center:.078125,y_center:.421875},{w:1,h:1,x_center:.109375,y_center:.421875},{w:1,h:1,x_center:.109375,y_center:.421875},{w:1,h:1,x_center:.140625,y_center:.421875},{w:1,h:1,x_center:.140625,y_center:.421875},{w:1,h:1,x_center:.171875,y_center:.421875},{w:1,h:1,x_center:.171875,y_center:.421875},{w:1,h:1,x_center:.203125,y_center:.421875},{w:1,h:1,x_center:.203125,y_center:.421875},{w:1,h:1,x_center:.234375,y_center:.421875},{w:1,h:1,x_center:.234375,y_center:.421875},{w:1,h:1,x_center:.265625,y_center:.421875},{w:1,h:1,x_center:.265625,y_center:.421875},{w:1,h:1,x_center:.296875,y_center:.421875},{w:1,h:1,x_center:.296875,y_center:.421875},{w:1,h:1,x_center:.328125,y_center:.421875},{w:1,h:1,x_center:.328125,y_center:.421875},{w:1,h:1,x_center:.359375,y_center:.421875},{w:1,h:1,x_center:.359375,y_center:.421875},{w:1,h:1,x_center:.390625,y_center:.421875},{w:1,h:1,x_center:.390625,y_center:.421875},{w:1,h:1,x_center:.421875,y_center:.421875},{w:1,h:1,x_center:.421875,y_center:.421875},{w:1,h:1,x_center:.453125,y_center:.421875},{w:1,h:1,x_center:.453125,y_center:.421875},{w:1,h:1,x_center:.484375,y_center:.421875},{w:1,h:1,x_center:.484375,y_center:.421875},{w:1,h:1,x_center:.515625,y_center:.421875},{w:1,h:1,x_center:.515625,y_center:.421875},{w:1,h:1,x_center:.546875,y_center:.421875},{w:1,h:1,x_center:.546875,y_center:.421875},{w:1,h:1,x_center:.578125,y_center:.421875},{w:1,h:1,x_center:.578125,y_center:.421875},{w:1,h:1,x_center:.609375,y_center:.421875},{w:1,h:1,x_center:.609375,y_center:.421875},{w:1,h:1,x_center:.640625,y_center:.421875},{w:1,h:1,x_center:.640625,y_center:.421875},{w:1,h:1,x_center:.671875,y_center:.421875},{w:1,h:1,x_center:.671875,y_center:.421875},{w:1,h:1,x_center:.703125,y_center:.421875},{w:1,h:1,x_center:.703125,y_center:.421875},{w:1,h:1,x_center:.734375,y_center:.421875},{w:1,h:1,x_center:.734375,y_center:.421875},{w:1,h:1,x_center:.765625,y_center:.421875},{w:1,h:1,x_center:.765625,y_center:.421875},{w:1,h:1,x_center:.796875,y_center:.421875},{w:1,h:1,x_center:.796875,y_center:.421875},{w:1,h:1,x_center:.828125,y_center:.421875},{w:1,h:1,x_center:.828125,y_center:.421875},{w:1,h:1,x_center:.859375,y_center:.421875},{w:1,h:1,x_center:.859375,y_center:.421875},{w:1,h:1,x_center:.890625,y_center:.421875},{w:1,h:1,x_center:.890625,y_center:.421875},{w:1,h:1,x_center:.921875,y_center:.421875},{w:1,h:1,x_center:.921875,y_center:.421875},{w:1,h:1,x_center:.953125,y_center:.421875},{w:1,h:1,x_center:.953125,y_center:.421875},{w:1,h:1,x_center:.984375,y_center:.421875},{w:1,h:1,x_center:.984375,y_center:.421875},{w:1,h:1,x_center:.015625,y_center:.453125},{w:1,h:1,x_center:.015625,y_center:.453125},{w:1,h:1,x_center:.046875,y_center:.453125},{w:1,h:1,x_center:.046875,y_center:.453125},{w:1,h:1,x_center:.078125,y_center:.453125},{w:1,h:1,x_center:.078125,y_center:.453125},{w:1,h:1,x_center:.109375,y_center:.453125},{w:1,h:1,x_center:.109375,y_center:.453125},{w:1,h:1,x_center:.140625,y_center:.453125},{w:1,h:1,x_center:.140625,y_center:.453125},{w:1,h:1,x_center:.171875,y_center:.453125},{w:1,h:1,x_center:.171875,y_center:.453125},{w:1,h:1,x_center:.203125,y_center:.453125},{w:1,h:1,x_center:.203125,y_center:.453125},{w:1,h:1,x_center:.234375,y_center:.453125},{w:1,h:1,x_center:.234375,y_center:.453125},{w:1,h:1,x_center:.265625,y_center:.453125},{w:1,h:1,x_center:.265625,y_center:.453125},{w:1,h:1,x_center:.296875,y_center:.453125},{w:1,h:1,x_center:.296875,y_center:.453125},{w:1,h:1,x_center:.328125,y_center:.453125},{w:1,h:1,x_center:.328125,y_center:.453125},{w:1,h:1,x_center:.359375,y_center:.453125},{w:1,h:1,x_center:.359375,y_center:.453125},{w:1,h:1,x_center:.390625,y_center:.453125},{w:1,h:1,x_center:.390625,y_center:.453125},{w:1,h:1,x_center:.421875,y_center:.453125},{w:1,h:1,x_center:.421875,y_center:.453125},{w:1,h:1,x_center:.453125,y_center:.453125},{w:1,h:1,x_center:.453125,y_center:.453125},{w:1,h:1,x_center:.484375,y_center:.453125},{w:1,h:1,x_center:.484375,y_center:.453125},{w:1,h:1,x_center:.515625,y_center:.453125},{w:1,h:1,x_center:.515625,y_center:.453125},{w:1,h:1,x_center:.546875,y_center:.453125},{w:1,h:1,x_center:.546875,y_center:.453125},{w:1,h:1,x_center:.578125,y_center:.453125},{w:1,h:1,x_center:.578125,y_center:.453125},{w:1,h:1,x_center:.609375,y_center:.453125},{w:1,h:1,x_center:.609375,y_center:.453125},{w:1,h:1,x_center:.640625,y_center:.453125},{w:1,h:1,x_center:.640625,y_center:.453125},{w:1,h:1,x_center:.671875,y_center:.453125},{w:1,h:1,x_center:.671875,y_center:.453125},{w:1,h:1,x_center:.703125,y_center:.453125},{w:1,h:1,x_center:.703125,y_center:.453125},{w:1,h:1,x_center:.734375,y_center:.453125},{w:1,h:1,x_center:.734375,y_center:.453125},{w:1,h:1,x_center:.765625,y_center:.453125},{w:1,h:1,x_center:.765625,y_center:.453125},{w:1,h:1,x_center:.796875,y_center:.453125},{w:1,h:1,x_center:.796875,y_center:.453125},{w:1,h:1,x_center:.828125,y_center:.453125},{w:1,h:1,x_center:.828125,y_center:.453125},{w:1,h:1,x_center:.859375,y_center:.453125},{w:1,h:1,x_center:.859375,y_center:.453125},{w:1,h:1,x_center:.890625,y_center:.453125},{w:1,h:1,x_center:.890625,y_center:.453125},{w:1,h:1,x_center:.921875,y_center:.453125},{w:1,h:1,x_center:.921875,y_center:.453125},{w:1,h:1,x_center:.953125,y_center:.453125},{w:1,h:1,x_center:.953125,y_center:.453125},{w:1,h:1,x_center:.984375,y_center:.453125},{w:1,h:1,x_center:.984375,y_center:.453125},{w:1,h:1,x_center:.015625,y_center:.484375},{w:1,h:1,x_center:.015625,y_center:.484375},{w:1,h:1,x_center:.046875,y_center:.484375},{w:1,h:1,x_center:.046875,y_center:.484375},{w:1,h:1,x_center:.078125,y_center:.484375},{w:1,h:1,x_center:.078125,y_center:.484375},{w:1,h:1,x_center:.109375,y_center:.484375},{w:1,h:1,x_center:.109375,y_center:.484375},{w:1,h:1,x_center:.140625,y_center:.484375},{w:1,h:1,x_center:.140625,y_center:.484375},{w:1,h:1,x_center:.171875,y_center:.484375},{w:1,h:1,x_center:.171875,y_center:.484375},{w:1,h:1,x_center:.203125,y_center:.484375},{w:1,h:1,x_center:.203125,y_center:.484375},{w:1,h:1,x_center:.234375,y_center:.484375},{w:1,h:1,x_center:.234375,y_center:.484375},{w:1,h:1,x_center:.265625,y_center:.484375},{w:1,h:1,x_center:.265625,y_center:.484375},{w:1,h:1,x_center:.296875,y_center:.484375},{w:1,h:1,x_center:.296875,y_center:.484375},{w:1,h:1,x_center:.328125,y_center:.484375},{w:1,h:1,x_center:.328125,y_center:.484375},{w:1,h:1,x_center:.359375,y_center:.484375},{w:1,h:1,x_center:.359375,y_center:.484375},{w:1,h:1,x_center:.390625,y_center:.484375},{w:1,h:1,x_center:.390625,y_center:.484375},{w:1,h:1,x_center:.421875,y_center:.484375},{w:1,h:1,x_center:.421875,y_center:.484375},{w:1,h:1,x_center:.453125,y_center:.484375},{w:1,h:1,x_center:.453125,y_center:.484375},{w:1,h:1,x_center:.484375,y_center:.484375},{w:1,h:1,x_center:.484375,y_center:.484375},{w:1,h:1,x_center:.515625,y_center:.484375},{w:1,h:1,x_center:.515625,y_center:.484375},{w:1,h:1,x_center:.546875,y_center:.484375},{w:1,h:1,x_center:.546875,y_center:.484375},{w:1,h:1,x_center:.578125,y_center:.484375},{w:1,h:1,x_center:.578125,y_center:.484375},{w:1,h:1,x_center:.609375,y_center:.484375},{w:1,h:1,x_center:.609375,y_center:.484375},{w:1,h:1,x_center:.640625,y_center:.484375},{w:1,h:1,x_center:.640625,y_center:.484375},{w:1,h:1,x_center:.671875,y_center:.484375},{w:1,h:1,x_center:.671875,y_center:.484375},{w:1,h:1,x_center:.703125,y_center:.484375},{w:1,h:1,x_center:.703125,y_center:.484375},{w:1,h:1,x_center:.734375,y_center:.484375},{w:1,h:1,x_center:.734375,y_center:.484375},{w:1,h:1,x_center:.765625,y_center:.484375},{w:1,h:1,x_center:.765625,y_center:.484375},{w:1,h:1,x_center:.796875,y_center:.484375},{w:1,h:1,x_center:.796875,y_center:.484375},{w:1,h:1,x_center:.828125,y_center:.484375},{w:1,h:1,x_center:.828125,y_center:.484375},{w:1,h:1,x_center:.859375,y_center:.484375},{w:1,h:1,x_center:.859375,y_center:.484375},{w:1,h:1,x_center:.890625,y_center:.484375},{w:1,h:1,x_center:.890625,y_center:.484375},{w:1,h:1,x_center:.921875,y_center:.484375},{w:1,h:1,x_center:.921875,y_center:.484375},{w:1,h:1,x_center:.953125,y_center:.484375},{w:1,h:1,x_center:.953125,y_center:.484375},{w:1,h:1,x_center:.984375,y_center:.484375},{w:1,h:1,x_center:.984375,y_center:.484375},{w:1,h:1,x_center:.015625,y_center:.515625},{w:1,h:1,x_center:.015625,y_center:.515625},{w:1,h:1,x_center:.046875,y_center:.515625},{w:1,h:1,x_center:.046875,y_center:.515625},{w:1,h:1,x_center:.078125,y_center:.515625},{w:1,h:1,x_center:.078125,y_center:.515625},{w:1,h:1,x_center:.109375,y_center:.515625},{w:1,h:1,x_center:.109375,y_center:.515625},{w:1,h:1,x_center:.140625,y_center:.515625},{w:1,h:1,x_center:.140625,y_center:.515625},{w:1,h:1,x_center:.171875,y_center:.515625},{w:1,h:1,x_center:.171875,y_center:.515625},{w:1,h:1,x_center:.203125,y_center:.515625},{w:1,h:1,x_center:.203125,y_center:.515625},{w:1,h:1,x_center:.234375,y_center:.515625},{w:1,h:1,x_center:.234375,y_center:.515625},{w:1,h:1,x_center:.265625,y_center:.515625},{w:1,h:1,x_center:.265625,y_center:.515625},{w:1,h:1,x_center:.296875,y_center:.515625},{w:1,h:1,x_center:.296875,y_center:.515625},{w:1,h:1,x_center:.328125,y_center:.515625},{w:1,h:1,x_center:.328125,y_center:.515625},{w:1,h:1,x_center:.359375,y_center:.515625},{w:1,h:1,x_center:.359375,y_center:.515625},{w:1,h:1,x_center:.390625,y_center:.515625},{w:1,h:1,x_center:.390625,y_center:.515625},{w:1,h:1,x_center:.421875,y_center:.515625},{w:1,h:1,x_center:.421875,y_center:.515625},{w:1,h:1,x_center:.453125,y_center:.515625},{w:1,h:1,x_center:.453125,y_center:.515625},{w:1,h:1,x_center:.484375,y_center:.515625},{w:1,h:1,x_center:.484375,y_center:.515625},{w:1,h:1,x_center:.515625,y_center:.515625},{w:1,h:1,x_center:.515625,y_center:.515625},{w:1,h:1,x_center:.546875,y_center:.515625},{w:1,h:1,x_center:.546875,y_center:.515625},{w:1,h:1,x_center:.578125,y_center:.515625},{w:1,h:1,x_center:.578125,y_center:.515625},{w:1,h:1,x_center:.609375,y_center:.515625},{w:1,h:1,x_center:.609375,y_center:.515625},{w:1,h:1,x_center:.640625,y_center:.515625},{w:1,h:1,x_center:.640625,y_center:.515625},{w:1,h:1,x_center:.671875,y_center:.515625},{w:1,h:1,x_center:.671875,y_center:.515625},{w:1,h:1,x_center:.703125,y_center:.515625},{w:1,h:1,x_center:.703125,y_center:.515625},{w:1,h:1,x_center:.734375,y_center:.515625},{w:1,h:1,x_center:.734375,y_center:.515625},{w:1,h:1,x_center:.765625,y_center:.515625},{w:1,h:1,x_center:.765625,y_center:.515625},{w:1,h:1,x_center:.796875,y_center:.515625},{w:1,h:1,x_center:.796875,y_center:.515625},{w:1,h:1,x_center:.828125,y_center:.515625},{w:1,h:1,x_center:.828125,y_center:.515625},{w:1,h:1,x_center:.859375,y_center:.515625},{w:1,h:1,x_center:.859375,y_center:.515625},{w:1,h:1,x_center:.890625,y_center:.515625},{w:1,h:1,x_center:.890625,y_center:.515625},{w:1,h:1,x_center:.921875,y_center:.515625},{w:1,h:1,x_center:.921875,y_center:.515625},{w:1,h:1,x_center:.953125,y_center:.515625},{w:1,h:1,x_center:.953125,y_center:.515625},{w:1,h:1,x_center:.984375,y_center:.515625},{w:1,h:1,x_center:.984375,y_center:.515625},{w:1,h:1,x_center:.015625,y_center:.546875},{w:1,h:1,x_center:.015625,y_center:.546875},{w:1,h:1,x_center:.046875,y_center:.546875},{w:1,h:1,x_center:.046875,y_center:.546875},{w:1,h:1,x_center:.078125,y_center:.546875},{w:1,h:1,x_center:.078125,y_center:.546875},{w:1,h:1,x_center:.109375,y_center:.546875},{w:1,h:1,x_center:.109375,y_center:.546875},{w:1,h:1,x_center:.140625,y_center:.546875},{w:1,h:1,x_center:.140625,y_center:.546875},{w:1,h:1,x_center:.171875,y_center:.546875},{w:1,h:1,x_center:.171875,y_center:.546875},{w:1,h:1,x_center:.203125,y_center:.546875},{w:1,h:1,x_center:.203125,y_center:.546875},{w:1,h:1,x_center:.234375,y_center:.546875},{w:1,h:1,x_center:.234375,y_center:.546875},{w:1,h:1,x_center:.265625,y_center:.546875},{w:1,h:1,x_center:.265625,y_center:.546875},{w:1,h:1,x_center:.296875,y_center:.546875},{w:1,h:1,x_center:.296875,y_center:.546875},{w:1,h:1,x_center:.328125,y_center:.546875},{w:1,h:1,x_center:.328125,y_center:.546875},{w:1,h:1,x_center:.359375,y_center:.546875},{w:1,h:1,x_center:.359375,y_center:.546875},{w:1,h:1,x_center:.390625,y_center:.546875},{w:1,h:1,x_center:.390625,y_center:.546875},{w:1,h:1,x_center:.421875,y_center:.546875},{w:1,h:1,x_center:.421875,y_center:.546875},{w:1,h:1,x_center:.453125,y_center:.546875},{w:1,h:1,x_center:.453125,y_center:.546875},{w:1,h:1,x_center:.484375,y_center:.546875},{w:1,h:1,x_center:.484375,y_center:.546875},{w:1,h:1,x_center:.515625,y_center:.546875},{w:1,h:1,x_center:.515625,y_center:.546875},{w:1,h:1,x_center:.546875,y_center:.546875},{w:1,h:1,x_center:.546875,y_center:.546875},{w:1,h:1,x_center:.578125,y_center:.546875},{w:1,h:1,x_center:.578125,y_center:.546875},{w:1,h:1,x_center:.609375,y_center:.546875},{w:1,h:1,x_center:.609375,y_center:.546875},{w:1,h:1,x_center:.640625,y_center:.546875},{w:1,h:1,x_center:.640625,y_center:.546875},{w:1,h:1,x_center:.671875,y_center:.546875},{w:1,h:1,x_center:.671875,y_center:.546875},{w:1,h:1,x_center:.703125,y_center:.546875},{w:1,h:1,x_center:.703125,y_center:.546875},{w:1,h:1,x_center:.734375,y_center:.546875},{w:1,h:1,x_center:.734375,y_center:.546875},{w:1,h:1,x_center:.765625,y_center:.546875},{w:1,h:1,x_center:.765625,y_center:.546875},{w:1,h:1,x_center:.796875,y_center:.546875},{w:1,h:1,x_center:.796875,y_center:.546875},{w:1,h:1,x_center:.828125,y_center:.546875},{w:1,h:1,x_center:.828125,y_center:.546875},{w:1,h:1,x_center:.859375,y_center:.546875},{w:1,h:1,x_center:.859375,y_center:.546875},{w:1,h:1,x_center:.890625,y_center:.546875},{w:1,h:1,x_center:.890625,y_center:.546875},{w:1,h:1,x_center:.921875,y_center:.546875},{w:1,h:1,x_center:.921875,y_center:.546875},{w:1,h:1,x_center:.953125,y_center:.546875},{w:1,h:1,x_center:.953125,y_center:.546875},{w:1,h:1,x_center:.984375,y_center:.546875},{w:1,h:1,x_center:.984375,y_center:.546875},{w:1,h:1,x_center:.015625,y_center:.578125},{w:1,h:1,x_center:.015625,y_center:.578125},{w:1,h:1,x_center:.046875,y_center:.578125},{w:1,h:1,x_center:.046875,y_center:.578125},{w:1,h:1,x_center:.078125,y_center:.578125},{w:1,h:1,x_center:.078125,y_center:.578125},{w:1,h:1,x_center:.109375,y_center:.578125},{w:1,h:1,x_center:.109375,y_center:.578125},{w:1,h:1,x_center:.140625,y_center:.578125},{w:1,h:1,x_center:.140625,y_center:.578125},{w:1,h:1,x_center:.171875,y_center:.578125},{w:1,h:1,x_center:.171875,y_center:.578125},{w:1,h:1,x_center:.203125,y_center:.578125},{w:1,h:1,x_center:.203125,y_center:.578125},{w:1,h:1,x_center:.234375,y_center:.578125},{w:1,h:1,x_center:.234375,y_center:.578125},{w:1,h:1,x_center:.265625,y_center:.578125},{w:1,h:1,x_center:.265625,y_center:.578125},{w:1,h:1,x_center:.296875,y_center:.578125},{w:1,h:1,x_center:.296875,y_center:.578125},{w:1,h:1,x_center:.328125,y_center:.578125},{w:1,h:1,x_center:.328125,y_center:.578125},{w:1,h:1,x_center:.359375,y_center:.578125},{w:1,h:1,x_center:.359375,y_center:.578125},{w:1,h:1,x_center:.390625,y_center:.578125},{w:1,h:1,x_center:.390625,y_center:.578125},{w:1,h:1,x_center:.421875,y_center:.578125},{w:1,h:1,x_center:.421875,y_center:.578125},{w:1,h:1,x_center:.453125,y_center:.578125},{w:1,h:1,x_center:.453125,y_center:.578125},{w:1,h:1,x_center:.484375,y_center:.578125},{w:1,h:1,x_center:.484375,y_center:.578125},{w:1,h:1,x_center:.515625,y_center:.578125},{w:1,h:1,x_center:.515625,y_center:.578125},{w:1,h:1,x_center:.546875,y_center:.578125},{w:1,h:1,x_center:.546875,y_center:.578125},{w:1,h:1,x_center:.578125,y_center:.578125},{w:1,h:1,x_center:.578125,y_center:.578125},{w:1,h:1,x_center:.609375,y_center:.578125},{w:1,h:1,x_center:.609375,y_center:.578125},{w:1,h:1,x_center:.640625,y_center:.578125},{w:1,h:1,x_center:.640625,y_center:.578125},{w:1,h:1,x_center:.671875,y_center:.578125},{w:1,h:1,x_center:.671875,y_center:.578125},{w:1,h:1,x_center:.703125,y_center:.578125},{w:1,h:1,x_center:.703125,y_center:.578125},{w:1,h:1,x_center:.734375,y_center:.578125},{w:1,h:1,x_center:.734375,y_center:.578125},{w:1,h:1,x_center:.765625,y_center:.578125},{w:1,h:1,x_center:.765625,y_center:.578125},{w:1,h:1,x_center:.796875,y_center:.578125},{w:1,h:1,x_center:.796875,y_center:.578125},{w:1,h:1,x_center:.828125,y_center:.578125},{w:1,h:1,x_center:.828125,y_center:.578125},{w:1,h:1,x_center:.859375,y_center:.578125},{w:1,h:1,x_center:.859375,y_center:.578125},{w:1,h:1,x_center:.890625,y_center:.578125},{w:1,h:1,x_center:.890625,y_center:.578125},{w:1,h:1,x_center:.921875,y_center:.578125},{w:1,h:1,x_center:.921875,y_center:.578125},{w:1,h:1,x_center:.953125,y_center:.578125},{w:1,h:1,x_center:.953125,y_center:.578125},{w:1,h:1,x_center:.984375,y_center:.578125},{w:1,h:1,x_center:.984375,y_center:.578125},{w:1,h:1,x_center:.015625,y_center:.609375},{w:1,h:1,x_center:.015625,y_center:.609375},{w:1,h:1,x_center:.046875,y_center:.609375},{w:1,h:1,x_center:.046875,y_center:.609375},{w:1,h:1,x_center:.078125,y_center:.609375},{w:1,h:1,x_center:.078125,y_center:.609375},{w:1,h:1,x_center:.109375,y_center:.609375},{w:1,h:1,x_center:.109375,y_center:.609375},{w:1,h:1,x_center:.140625,y_center:.609375},{w:1,h:1,x_center:.140625,y_center:.609375},{w:1,h:1,x_center:.171875,y_center:.609375},{w:1,h:1,x_center:.171875,y_center:.609375},{w:1,h:1,x_center:.203125,y_center:.609375},{w:1,h:1,x_center:.203125,y_center:.609375},{w:1,h:1,x_center:.234375,y_center:.609375},{w:1,h:1,x_center:.234375,y_center:.609375},{w:1,h:1,x_center:.265625,y_center:.609375},{w:1,h:1,x_center:.265625,y_center:.609375},{w:1,h:1,x_center:.296875,y_center:.609375},{w:1,h:1,x_center:.296875,y_center:.609375},{w:1,h:1,x_center:.328125,y_center:.609375},{w:1,h:1,x_center:.328125,y_center:.609375},{w:1,h:1,x_center:.359375,y_center:.609375},{w:1,h:1,x_center:.359375,y_center:.609375},{w:1,h:1,x_center:.390625,y_center:.609375},{w:1,h:1,x_center:.390625,y_center:.609375},{w:1,h:1,x_center:.421875,y_center:.609375},{w:1,h:1,x_center:.421875,y_center:.609375},{w:1,h:1,x_center:.453125,y_center:.609375},{w:1,h:1,x_center:.453125,y_center:.609375},{w:1,h:1,x_center:.484375,y_center:.609375},{w:1,h:1,x_center:.484375,y_center:.609375},{w:1,h:1,x_center:.515625,y_center:.609375},{w:1,h:1,x_center:.515625,y_center:.609375},{w:1,h:1,x_center:.546875,y_center:.609375},{w:1,h:1,x_center:.546875,y_center:.609375},{w:1,h:1,x_center:.578125,y_center:.609375},{w:1,h:1,x_center:.578125,y_center:.609375},{w:1,h:1,x_center:.609375,y_center:.609375},{w:1,h:1,x_center:.609375,y_center:.609375},{w:1,h:1,x_center:.640625,y_center:.609375},{w:1,h:1,x_center:.640625,y_center:.609375},{w:1,h:1,x_center:.671875,y_center:.609375},{w:1,h:1,x_center:.671875,y_center:.609375},{w:1,h:1,x_center:.703125,y_center:.609375},{w:1,h:1,x_center:.703125,y_center:.609375},{w:1,h:1,x_center:.734375,y_center:.609375},{w:1,h:1,x_center:.734375,y_center:.609375},{w:1,h:1,x_center:.765625,y_center:.609375},{w:1,h:1,x_center:.765625,y_center:.609375},{w:1,h:1,x_center:.796875,y_center:.609375},{w:1,h:1,x_center:.796875,y_center:.609375},{w:1,h:1,x_center:.828125,y_center:.609375},{w:1,h:1,x_center:.828125,y_center:.609375},{w:1,h:1,x_center:.859375,y_center:.609375},{w:1,h:1,x_center:.859375,y_center:.609375},{w:1,h:1,x_center:.890625,y_center:.609375},{w:1,h:1,x_center:.890625,y_center:.609375},{w:1,h:1,x_center:.921875,y_center:.609375},{w:1,h:1,x_center:.921875,y_center:.609375},{w:1,h:1,x_center:.953125,y_center:.609375},{w:1,h:1,x_center:.953125,y_center:.609375},{w:1,h:1,x_center:.984375,y_center:.609375},{w:1,h:1,x_center:.984375,y_center:.609375},{w:1,h:1,x_center:.015625,y_center:.640625},{w:1,h:1,x_center:.015625,y_center:.640625},{w:1,h:1,x_center:.046875,y_center:.640625},{w:1,h:1,x_center:.046875,y_center:.640625},{w:1,h:1,x_center:.078125,y_center:.640625},{w:1,h:1,x_center:.078125,y_center:.640625},{w:1,h:1,x_center:.109375,y_center:.640625},{w:1,h:1,x_center:.109375,y_center:.640625},{w:1,h:1,x_center:.140625,y_center:.640625},{w:1,h:1,x_center:.140625,y_center:.640625},{w:1,h:1,x_center:.171875,y_center:.640625},{w:1,h:1,x_center:.171875,y_center:.640625},{w:1,h:1,x_center:.203125,y_center:.640625},{w:1,h:1,x_center:.203125,y_center:.640625},{w:1,h:1,x_center:.234375,y_center:.640625},{w:1,h:1,x_center:.234375,y_center:.640625},{w:1,h:1,x_center:.265625,y_center:.640625},{w:1,h:1,x_center:.265625,y_center:.640625},{w:1,h:1,x_center:.296875,y_center:.640625},{w:1,h:1,x_center:.296875,y_center:.640625},{w:1,h:1,x_center:.328125,y_center:.640625},{w:1,h:1,x_center:.328125,y_center:.640625},{w:1,h:1,x_center:.359375,y_center:.640625},{w:1,h:1,x_center:.359375,y_center:.640625},{w:1,h:1,x_center:.390625,y_center:.640625},{w:1,h:1,x_center:.390625,y_center:.640625},{w:1,h:1,x_center:.421875,y_center:.640625},{w:1,h:1,x_center:.421875,y_center:.640625},{w:1,h:1,x_center:.453125,y_center:.640625},{w:1,h:1,x_center:.453125,y_center:.640625},{w:1,h:1,x_center:.484375,y_center:.640625},{w:1,h:1,x_center:.484375,y_center:.640625},{w:1,h:1,x_center:.515625,y_center:.640625},{w:1,h:1,x_center:.515625,y_center:.640625},{w:1,h:1,x_center:.546875,y_center:.640625},{w:1,h:1,x_center:.546875,y_center:.640625},{w:1,h:1,x_center:.578125,y_center:.640625},{w:1,h:1,x_center:.578125,y_center:.640625},{w:1,h:1,x_center:.609375,y_center:.640625},{w:1,h:1,x_center:.609375,y_center:.640625},{w:1,h:1,x_center:.640625,y_center:.640625},{w:1,h:1,x_center:.640625,y_center:.640625},{w:1,h:1,x_center:.671875,y_center:.640625},{w:1,h:1,x_center:.671875,y_center:.640625},{w:1,h:1,x_center:.703125,y_center:.640625},{w:1,h:1,x_center:.703125,y_center:.640625},{w:1,h:1,x_center:.734375,y_center:.640625},{w:1,h:1,x_center:.734375,y_center:.640625},{w:1,h:1,x_center:.765625,y_center:.640625},{w:1,h:1,x_center:.765625,y_center:.640625},{w:1,h:1,x_center:.796875,y_center:.640625},{w:1,h:1,x_center:.796875,y_center:.640625},{w:1,h:1,x_center:.828125,y_center:.640625},{w:1,h:1,x_center:.828125,y_center:.640625},{w:1,h:1,x_center:.859375,y_center:.640625},{w:1,h:1,x_center:.859375,y_center:.640625},{w:1,h:1,x_center:.890625,y_center:.640625},{w:1,h:1,x_center:.890625,y_center:.640625},{w:1,h:1,x_center:.921875,y_center:.640625},{w:1,h:1,x_center:.921875,y_center:.640625},{w:1,h:1,x_center:.953125,y_center:.640625},{w:1,h:1,x_center:.953125,y_center:.640625},{w:1,h:1,x_center:.984375,y_center:.640625},{w:1,h:1,x_center:.984375,y_center:.640625},{w:1,h:1,x_center:.015625,y_center:.671875},{w:1,h:1,x_center:.015625,y_center:.671875},{w:1,h:1,x_center:.046875,y_center:.671875},{w:1,h:1,x_center:.046875,y_center:.671875},{w:1,h:1,x_center:.078125,y_center:.671875},{w:1,h:1,x_center:.078125,y_center:.671875},{w:1,h:1,x_center:.109375,y_center:.671875},{w:1,h:1,x_center:.109375,y_center:.671875},{w:1,h:1,x_center:.140625,y_center:.671875},{w:1,h:1,x_center:.140625,y_center:.671875},{w:1,h:1,x_center:.171875,y_center:.671875},{w:1,h:1,x_center:.171875,y_center:.671875},{w:1,h:1,x_center:.203125,y_center:.671875},{w:1,h:1,x_center:.203125,y_center:.671875},{w:1,h:1,x_center:.234375,y_center:.671875},{w:1,h:1,x_center:.234375,y_center:.671875},{w:1,h:1,x_center:.265625,y_center:.671875},{w:1,h:1,x_center:.265625,y_center:.671875},{w:1,h:1,x_center:.296875,y_center:.671875},{w:1,h:1,x_center:.296875,y_center:.671875},{w:1,h:1,x_center:.328125,y_center:.671875},{w:1,h:1,x_center:.328125,y_center:.671875},{w:1,h:1,x_center:.359375,y_center:.671875},{w:1,h:1,x_center:.359375,y_center:.671875},{w:1,h:1,x_center:.390625,y_center:.671875},{w:1,h:1,x_center:.390625,y_center:.671875},{w:1,h:1,x_center:.421875,y_center:.671875},{w:1,h:1,x_center:.421875,y_center:.671875},{w:1,h:1,x_center:.453125,y_center:.671875},{w:1,h:1,x_center:.453125,y_center:.671875},{w:1,h:1,x_center:.484375,y_center:.671875},{w:1,h:1,x_center:.484375,y_center:.671875},{w:1,h:1,x_center:.515625,y_center:.671875},{w:1,h:1,x_center:.515625,y_center:.671875},{w:1,h:1,x_center:.546875,y_center:.671875},{w:1,h:1,x_center:.546875,y_center:.671875},{w:1,h:1,x_center:.578125,y_center:.671875},{w:1,h:1,x_center:.578125,y_center:.671875},{w:1,h:1,x_center:.609375,y_center:.671875},{w:1,h:1,x_center:.609375,y_center:.671875},{w:1,h:1,x_center:.640625,y_center:.671875},{w:1,h:1,x_center:.640625,y_center:.671875},{w:1,h:1,x_center:.671875,y_center:.671875},{w:1,h:1,x_center:.671875,y_center:.671875},{w:1,h:1,x_center:.703125,y_center:.671875},{w:1,h:1,x_center:.703125,y_center:.671875},{w:1,h:1,x_center:.734375,y_center:.671875},{w:1,h:1,x_center:.734375,y_center:.671875},{w:1,h:1,x_center:.765625,y_center:.671875},{w:1,h:1,x_center:.765625,y_center:.671875},{w:1,h:1,x_center:.796875,y_center:.671875},{w:1,h:1,x_center:.796875,y_center:.671875},{w:1,h:1,x_center:.828125,y_center:.671875},{w:1,h:1,x_center:.828125,y_center:.671875},{w:1,h:1,x_center:.859375,y_center:.671875},{w:1,h:1,x_center:.859375,y_center:.671875},{w:1,h:1,x_center:.890625,y_center:.671875},{w:1,h:1,x_center:.890625,y_center:.671875},{w:1,h:1,x_center:.921875,y_center:.671875},{w:1,h:1,x_center:.921875,y_center:.671875},{w:1,h:1,x_center:.953125,y_center:.671875},{w:1,h:1,x_center:.953125,y_center:.671875},{w:1,h:1,x_center:.984375,y_center:.671875},{w:1,h:1,x_center:.984375,y_center:.671875},{w:1,h:1,x_center:.015625,y_center:.703125},{w:1,h:1,x_center:.015625,y_center:.703125},{w:1,h:1,x_center:.046875,y_center:.703125},{w:1,h:1,x_center:.046875,y_center:.703125},{w:1,h:1,x_center:.078125,y_center:.703125},{w:1,h:1,x_center:.078125,y_center:.703125},{w:1,h:1,x_center:.109375,y_center:.703125},{w:1,h:1,x_center:.109375,y_center:.703125},{w:1,h:1,x_center:.140625,y_center:.703125},{w:1,h:1,x_center:.140625,y_center:.703125},{w:1,h:1,x_center:.171875,y_center:.703125},{w:1,h:1,x_center:.171875,y_center:.703125},{w:1,h:1,x_center:.203125,y_center:.703125},{w:1,h:1,x_center:.203125,y_center:.703125},{w:1,h:1,x_center:.234375,y_center:.703125},{w:1,h:1,x_center:.234375,y_center:.703125},{w:1,h:1,x_center:.265625,y_center:.703125},{w:1,h:1,x_center:.265625,y_center:.703125},{w:1,h:1,x_center:.296875,y_center:.703125},{w:1,h:1,x_center:.296875,y_center:.703125},{w:1,h:1,x_center:.328125,y_center:.703125},{w:1,h:1,x_center:.328125,y_center:.703125},{w:1,h:1,x_center:.359375,y_center:.703125},{w:1,h:1,x_center:.359375,y_center:.703125},{w:1,h:1,x_center:.390625,y_center:.703125},{w:1,h:1,x_center:.390625,y_center:.703125},{w:1,h:1,x_center:.421875,y_center:.703125},{w:1,h:1,x_center:.421875,y_center:.703125},{w:1,h:1,x_center:.453125,y_center:.703125},{w:1,h:1,x_center:.453125,y_center:.703125},{w:1,h:1,x_center:.484375,y_center:.703125},{w:1,h:1,x_center:.484375,y_center:.703125},{w:1,h:1,x_center:.515625,y_center:.703125},{w:1,h:1,x_center:.515625,y_center:.703125},{w:1,h:1,x_center:.546875,y_center:.703125},{w:1,h:1,x_center:.546875,y_center:.703125},{w:1,h:1,x_center:.578125,y_center:.703125},{w:1,h:1,x_center:.578125,y_center:.703125},{w:1,h:1,x_center:.609375,y_center:.703125},{w:1,h:1,x_center:.609375,y_center:.703125},{w:1,h:1,x_center:.640625,y_center:.703125},{w:1,h:1,x_center:.640625,y_center:.703125},{w:1,h:1,x_center:.671875,y_center:.703125},{w:1,h:1,x_center:.671875,y_center:.703125},{w:1,h:1,x_center:.703125,y_center:.703125},{w:1,h:1,x_center:.703125,y_center:.703125},{w:1,h:1,x_center:.734375,y_center:.703125},{w:1,h:1,x_center:.734375,y_center:.703125},{w:1,h:1,x_center:.765625,y_center:.703125},{w:1,h:1,x_center:.765625,y_center:.703125},{w:1,h:1,x_center:.796875,y_center:.703125},{w:1,h:1,x_center:.796875,y_center:.703125},{w:1,h:1,x_center:.828125,y_center:.703125},{w:1,h:1,x_center:.828125,y_center:.703125},{w:1,h:1,x_center:.859375,y_center:.703125},{w:1,h:1,x_center:.859375,y_center:.703125},{w:1,h:1,x_center:.890625,y_center:.703125},{w:1,h:1,x_center:.890625,y_center:.703125},{w:1,h:1,x_center:.921875,y_center:.703125},{w:1,h:1,x_center:.921875,y_center:.703125},{w:1,h:1,x_center:.953125,y_center:.703125},{w:1,h:1,x_center:.953125,y_center:.703125},{w:1,h:1,x_center:.984375,y_center:.703125},{w:1,h:1,x_center:.984375,y_center:.703125},{w:1,h:1,x_center:.015625,y_center:.734375},{w:1,h:1,x_center:.015625,y_center:.734375},{w:1,h:1,x_center:.046875,y_center:.734375},{w:1,h:1,x_center:.046875,y_center:.734375},{w:1,h:1,x_center:.078125,y_center:.734375},{w:1,h:1,x_center:.078125,y_center:.734375},{w:1,h:1,x_center:.109375,y_center:.734375},{w:1,h:1,x_center:.109375,y_center:.734375},{w:1,h:1,x_center:.140625,y_center:.734375},{w:1,h:1,x_center:.140625,y_center:.734375},{w:1,h:1,x_center:.171875,y_center:.734375},{w:1,h:1,x_center:.171875,y_center:.734375},{w:1,h:1,x_center:.203125,y_center:.734375},{w:1,h:1,x_center:.203125,y_center:.734375},{w:1,h:1,x_center:.234375,y_center:.734375},{w:1,h:1,x_center:.234375,y_center:.734375},{w:1,h:1,x_center:.265625,y_center:.734375},{w:1,h:1,x_center:.265625,y_center:.734375},{w:1,h:1,x_center:.296875,y_center:.734375},{w:1,h:1,x_center:.296875,y_center:.734375},{w:1,h:1,x_center:.328125,y_center:.734375},{w:1,h:1,x_center:.328125,y_center:.734375},{w:1,h:1,x_center:.359375,y_center:.734375},{w:1,h:1,x_center:.359375,y_center:.734375},{w:1,h:1,x_center:.390625,y_center:.734375},{w:1,h:1,x_center:.390625,y_center:.734375},{w:1,h:1,x_center:.421875,y_center:.734375},{w:1,h:1,x_center:.421875,y_center:.734375},{w:1,h:1,x_center:.453125,y_center:.734375},{w:1,h:1,x_center:.453125,y_center:.734375},{w:1,h:1,x_center:.484375,y_center:.734375},{w:1,h:1,x_center:.484375,y_center:.734375},{w:1,h:1,x_center:.515625,y_center:.734375},{w:1,h:1,x_center:.515625,y_center:.734375},{w:1,h:1,x_center:.546875,y_center:.734375},{w:1,h:1,x_center:.546875,y_center:.734375},{w:1,h:1,x_center:.578125,y_center:.734375},{w:1,h:1,x_center:.578125,y_center:.734375},{w:1,h:1,x_center:.609375,y_center:.734375},{w:1,h:1,x_center:.609375,y_center:.734375},{w:1,h:1,x_center:.640625,y_center:.734375},{w:1,h:1,x_center:.640625,y_center:.734375},{w:1,h:1,x_center:.671875,y_center:.734375},{w:1,h:1,x_center:.671875,y_center:.734375},{w:1,h:1,x_center:.703125,y_center:.734375},{w:1,h:1,x_center:.703125,y_center:.734375},{w:1,h:1,x_center:.734375,y_center:.734375},{w:1,h:1,x_center:.734375,y_center:.734375},{w:1,h:1,x_center:.765625,y_center:.734375},{w:1,h:1,x_center:.765625,y_center:.734375},{w:1,h:1,x_center:.796875,y_center:.734375},{w:1,h:1,x_center:.796875,y_center:.734375},{w:1,h:1,x_center:.828125,y_center:.734375},{w:1,h:1,x_center:.828125,y_center:.734375},{w:1,h:1,x_center:.859375,y_center:.734375},{w:1,h:1,x_center:.859375,y_center:.734375},{w:1,h:1,x_center:.890625,y_center:.734375},{w:1,h:1,x_center:.890625,y_center:.734375},{w:1,h:1,x_center:.921875,y_center:.734375},{w:1,h:1,x_center:.921875,y_center:.734375},{w:1,h:1,x_center:.953125,y_center:.734375},{w:1,h:1,x_center:.953125,y_center:.734375},{w:1,h:1,x_center:.984375,y_center:.734375},{w:1,h:1,x_center:.984375,y_center:.734375},{w:1,h:1,x_center:.015625,y_center:.765625},{w:1,h:1,x_center:.015625,y_center:.765625},{w:1,h:1,x_center:.046875,y_center:.765625},{w:1,h:1,x_center:.046875,y_center:.765625},{w:1,h:1,x_center:.078125,y_center:.765625},{w:1,h:1,x_center:.078125,y_center:.765625},{w:1,h:1,x_center:.109375,y_center:.765625},{w:1,h:1,x_center:.109375,y_center:.765625},{w:1,h:1,x_center:.140625,y_center:.765625},{w:1,h:1,x_center:.140625,y_center:.765625},{w:1,h:1,x_center:.171875,y_center:.765625},{w:1,h:1,x_center:.171875,y_center:.765625},{w:1,h:1,x_center:.203125,y_center:.765625},{w:1,h:1,x_center:.203125,y_center:.765625},{w:1,h:1,x_center:.234375,y_center:.765625},{w:1,h:1,x_center:.234375,y_center:.765625},{w:1,h:1,x_center:.265625,y_center:.765625},{w:1,h:1,x_center:.265625,y_center:.765625},{w:1,h:1,x_center:.296875,y_center:.765625},{w:1,h:1,x_center:.296875,y_center:.765625},{w:1,h:1,x_center:.328125,y_center:.765625},{w:1,h:1,x_center:.328125,y_center:.765625},{w:1,h:1,x_center:.359375,y_center:.765625},{w:1,h:1,x_center:.359375,y_center:.765625},{w:1,h:1,x_center:.390625,y_center:.765625},{w:1,h:1,x_center:.390625,y_center:.765625},{w:1,h:1,x_center:.421875,y_center:.765625},{w:1,h:1,x_center:.421875,y_center:.765625},{w:1,h:1,x_center:.453125,y_center:.765625},{w:1,h:1,x_center:.453125,y_center:.765625},{w:1,h:1,x_center:.484375,y_center:.765625},{w:1,h:1,x_center:.484375,y_center:.765625},{w:1,h:1,x_center:.515625,y_center:.765625},{w:1,h:1,x_center:.515625,y_center:.765625},{w:1,h:1,x_center:.546875,y_center:.765625},{w:1,h:1,x_center:.546875,y_center:.765625},{w:1,h:1,x_center:.578125,y_center:.765625},{w:1,h:1,x_center:.578125,y_center:.765625},{w:1,h:1,x_center:.609375,y_center:.765625},{w:1,h:1,x_center:.609375,y_center:.765625},{w:1,h:1,x_center:.640625,y_center:.765625},{w:1,h:1,x_center:.640625,y_center:.765625},{w:1,h:1,x_center:.671875,y_center:.765625},{w:1,h:1,x_center:.671875,y_center:.765625},{w:1,h:1,x_center:.703125,y_center:.765625},{w:1,h:1,x_center:.703125,y_center:.765625},{w:1,h:1,x_center:.734375,y_center:.765625},{w:1,h:1,x_center:.734375,y_center:.765625},{w:1,h:1,x_center:.765625,y_center:.765625},{w:1,h:1,x_center:.765625,y_center:.765625},{w:1,h:1,x_center:.796875,y_center:.765625},{w:1,h:1,x_center:.796875,y_center:.765625},{w:1,h:1,x_center:.828125,y_center:.765625},{w:1,h:1,x_center:.828125,y_center:.765625},{w:1,h:1,x_center:.859375,y_center:.765625},{w:1,h:1,x_center:.859375,y_center:.765625},{w:1,h:1,x_center:.890625,y_center:.765625},{w:1,h:1,x_center:.890625,y_center:.765625},{w:1,h:1,x_center:.921875,y_center:.765625},{w:1,h:1,x_center:.921875,y_center:.765625},{w:1,h:1,x_center:.953125,y_center:.765625},{w:1,h:1,x_center:.953125,y_center:.765625},{w:1,h:1,x_center:.984375,y_center:.765625},{w:1,h:1,x_center:.984375,y_center:.765625},{w:1,h:1,x_center:.015625,y_center:.796875},{w:1,h:1,x_center:.015625,y_center:.796875},{w:1,h:1,x_center:.046875,y_center:.796875},{w:1,h:1,x_center:.046875,y_center:.796875},{w:1,h:1,x_center:.078125,y_center:.796875},{w:1,h:1,x_center:.078125,y_center:.796875},{w:1,h:1,x_center:.109375,y_center:.796875},{w:1,h:1,x_center:.109375,y_center:.796875},{w:1,h:1,x_center:.140625,y_center:.796875},{w:1,h:1,x_center:.140625,y_center:.796875},{w:1,h:1,x_center:.171875,y_center:.796875},{w:1,h:1,x_center:.171875,y_center:.796875},{w:1,h:1,x_center:.203125,y_center:.796875},{w:1,h:1,x_center:.203125,y_center:.796875},{w:1,h:1,x_center:.234375,y_center:.796875},{w:1,h:1,x_center:.234375,y_center:.796875},{w:1,h:1,x_center:.265625,y_center:.796875},{w:1,h:1,x_center:.265625,y_center:.796875},{w:1,h:1,x_center:.296875,y_center:.796875},{w:1,h:1,x_center:.296875,y_center:.796875},{w:1,h:1,x_center:.328125,y_center:.796875},{w:1,h:1,x_center:.328125,y_center:.796875},{w:1,h:1,x_center:.359375,y_center:.796875},{w:1,h:1,x_center:.359375,y_center:.796875},{w:1,h:1,x_center:.390625,y_center:.796875},{w:1,h:1,x_center:.390625,y_center:.796875},{w:1,h:1,x_center:.421875,y_center:.796875},{w:1,h:1,x_center:.421875,y_center:.796875},{w:1,h:1,x_center:.453125,y_center:.796875},{w:1,h:1,x_center:.453125,y_center:.796875},{w:1,h:1,x_center:.484375,y_center:.796875},{w:1,h:1,x_center:.484375,y_center:.796875},{w:1,h:1,x_center:.515625,y_center:.796875},{w:1,h:1,x_center:.515625,y_center:.796875},{w:1,h:1,x_center:.546875,y_center:.796875},{w:1,h:1,x_center:.546875,y_center:.796875},{w:1,h:1,x_center:.578125,y_center:.796875},{w:1,h:1,x_center:.578125,y_center:.796875},{w:1,h:1,x_center:.609375,y_center:.796875},{w:1,h:1,x_center:.609375,y_center:.796875},{w:1,h:1,x_center:.640625,y_center:.796875},{w:1,h:1,x_center:.640625,y_center:.796875},{w:1,h:1,x_center:.671875,y_center:.796875},{w:1,h:1,x_center:.671875,y_center:.796875},{w:1,h:1,x_center:.703125,y_center:.796875},{w:1,h:1,x_center:.703125,y_center:.796875},{w:1,h:1,x_center:.734375,y_center:.796875},{w:1,h:1,x_center:.734375,y_center:.796875},{w:1,h:1,x_center:.765625,y_center:.796875},{w:1,h:1,x_center:.765625,y_center:.796875},{w:1,h:1,x_center:.796875,y_center:.796875},{w:1,h:1,x_center:.796875,y_center:.796875},{w:1,h:1,x_center:.828125,y_center:.796875},{w:1,h:1,x_center:.828125,y_center:.796875},{w:1,h:1,x_center:.859375,y_center:.796875},{w:1,h:1,x_center:.859375,y_center:.796875},{w:1,h:1,x_center:.890625,y_center:.796875},{w:1,h:1,x_center:.890625,y_center:.796875},{w:1,h:1,x_center:.921875,y_center:.796875},{w:1,h:1,x_center:.921875,y_center:.796875},{w:1,h:1,x_center:.953125,y_center:.796875},{w:1,h:1,x_center:.953125,y_center:.796875},{w:1,h:1,x_center:.984375,y_center:.796875},{w:1,h:1,x_center:.984375,y_center:.796875},{w:1,h:1,x_center:.015625,y_center:.828125},{w:1,h:1,x_center:.015625,y_center:.828125},{w:1,h:1,x_center:.046875,y_center:.828125},{w:1,h:1,x_center:.046875,y_center:.828125},{w:1,h:1,x_center:.078125,y_center:.828125},{w:1,h:1,x_center:.078125,y_center:.828125},{w:1,h:1,x_center:.109375,y_center:.828125},{w:1,h:1,x_center:.109375,y_center:.828125},{w:1,h:1,x_center:.140625,y_center:.828125},{w:1,h:1,x_center:.140625,y_center:.828125},{w:1,h:1,x_center:.171875,y_center:.828125},{w:1,h:1,x_center:.171875,y_center:.828125},{w:1,h:1,x_center:.203125,y_center:.828125},{w:1,h:1,x_center:.203125,y_center:.828125},{w:1,h:1,x_center:.234375,y_center:.828125},{w:1,h:1,x_center:.234375,y_center:.828125},{w:1,h:1,x_center:.265625,y_center:.828125},{w:1,h:1,x_center:.265625,y_center:.828125},{w:1,h:1,x_center:.296875,y_center:.828125},{w:1,h:1,x_center:.296875,y_center:.828125},{w:1,h:1,x_center:.328125,y_center:.828125},{w:1,h:1,x_center:.328125,y_center:.828125},{w:1,h:1,x_center:.359375,y_center:.828125},{w:1,h:1,x_center:.359375,y_center:.828125},{w:1,h:1,x_center:.390625,y_center:.828125},{w:1,h:1,x_center:.390625,y_center:.828125},{w:1,h:1,x_center:.421875,y_center:.828125},{w:1,h:1,x_center:.421875,y_center:.828125},{w:1,h:1,x_center:.453125,y_center:.828125},{w:1,h:1,x_center:.453125,y_center:.828125},{w:1,h:1,x_center:.484375,y_center:.828125},{w:1,h:1,x_center:.484375,y_center:.828125},{w:1,h:1,x_center:.515625,y_center:.828125},{w:1,h:1,x_center:.515625,y_center:.828125},{w:1,h:1,x_center:.546875,y_center:.828125},{w:1,h:1,x_center:.546875,y_center:.828125},{w:1,h:1,x_center:.578125,y_center:.828125},{w:1,h:1,x_center:.578125,y_center:.828125},{w:1,h:1,x_center:.609375,y_center:.828125},{w:1,h:1,x_center:.609375,y_center:.828125},{w:1,h:1,x_center:.640625,y_center:.828125},{w:1,h:1,x_center:.640625,y_center:.828125},{w:1,h:1,x_center:.671875,y_center:.828125},{w:1,h:1,x_center:.671875,y_center:.828125},{w:1,h:1,x_center:.703125,y_center:.828125},{w:1,h:1,x_center:.703125,y_center:.828125},{w:1,h:1,x_center:.734375,y_center:.828125},{w:1,h:1,x_center:.734375,y_center:.828125},{w:1,h:1,x_center:.765625,y_center:.828125},{w:1,h:1,x_center:.765625,y_center:.828125},{w:1,h:1,x_center:.796875,y_center:.828125},{w:1,h:1,x_center:.796875,y_center:.828125},{w:1,h:1,x_center:.828125,y_center:.828125},{w:1,h:1,x_center:.828125,y_center:.828125},{w:1,h:1,x_center:.859375,y_center:.828125},{w:1,h:1,x_center:.859375,y_center:.828125},{w:1,h:1,x_center:.890625,y_center:.828125},{w:1,h:1,x_center:.890625,y_center:.828125},{w:1,h:1,x_center:.921875,y_center:.828125},{w:1,h:1,x_center:.921875,y_center:.828125},{w:1,h:1,x_center:.953125,y_center:.828125},{w:1,h:1,x_center:.953125,y_center:.828125},{w:1,h:1,x_center:.984375,y_center:.828125},{w:1,h:1,x_center:.984375,y_center:.828125},{w:1,h:1,x_center:.015625,y_center:.859375},{w:1,h:1,x_center:.015625,y_center:.859375},{w:1,h:1,x_center:.046875,y_center:.859375},{w:1,h:1,x_center:.046875,y_center:.859375},{w:1,h:1,x_center:.078125,y_center:.859375},{w:1,h:1,x_center:.078125,y_center:.859375},{w:1,h:1,x_center:.109375,y_center:.859375},{w:1,h:1,x_center:.109375,y_center:.859375},{w:1,h:1,x_center:.140625,y_center:.859375},{w:1,h:1,x_center:.140625,y_center:.859375},{w:1,h:1,x_center:.171875,y_center:.859375},{w:1,h:1,x_center:.171875,y_center:.859375},{w:1,h:1,x_center:.203125,y_center:.859375},{w:1,h:1,x_center:.203125,y_center:.859375},{w:1,h:1,x_center:.234375,y_center:.859375},{w:1,h:1,x_center:.234375,y_center:.859375},{w:1,h:1,x_center:.265625,y_center:.859375},{w:1,h:1,x_center:.265625,y_center:.859375},{w:1,h:1,x_center:.296875,y_center:.859375},{w:1,h:1,x_center:.296875,y_center:.859375},{w:1,h:1,x_center:.328125,y_center:.859375},{w:1,h:1,x_center:.328125,y_center:.859375},{w:1,h:1,x_center:.359375,y_center:.859375},{w:1,h:1,x_center:.359375,y_center:.859375},{w:1,h:1,x_center:.390625,y_center:.859375},{w:1,h:1,x_center:.390625,y_center:.859375},{w:1,h:1,x_center:.421875,y_center:.859375},{w:1,h:1,x_center:.421875,y_center:.859375},{w:1,h:1,x_center:.453125,y_center:.859375},{w:1,h:1,x_center:.453125,y_center:.859375},{w:1,h:1,x_center:.484375,y_center:.859375},{w:1,h:1,x_center:.484375,y_center:.859375},{w:1,h:1,x_center:.515625,y_center:.859375},{w:1,h:1,x_center:.515625,y_center:.859375},{w:1,h:1,x_center:.546875,y_center:.859375},{w:1,h:1,x_center:.546875,y_center:.859375},{w:1,h:1,x_center:.578125,y_center:.859375},{w:1,h:1,x_center:.578125,y_center:.859375},{w:1,h:1,x_center:.609375,y_center:.859375},{w:1,h:1,x_center:.609375,y_center:.859375},{w:1,h:1,x_center:.640625,y_center:.859375},{w:1,h:1,x_center:.640625,y_center:.859375},{w:1,h:1,x_center:.671875,y_center:.859375},{w:1,h:1,x_center:.671875,y_center:.859375},{w:1,h:1,x_center:.703125,y_center:.859375},{w:1,h:1,x_center:.703125,y_center:.859375},{w:1,h:1,x_center:.734375,y_center:.859375},{w:1,h:1,x_center:.734375,y_center:.859375},{w:1,h:1,x_center:.765625,y_center:.859375},{w:1,h:1,x_center:.765625,y_center:.859375},{w:1,h:1,x_center:.796875,y_center:.859375},{w:1,h:1,x_center:.796875,y_center:.859375},{w:1,h:1,x_center:.828125,y_center:.859375},{w:1,h:1,x_center:.828125,y_center:.859375},{w:1,h:1,x_center:.859375,y_center:.859375},{w:1,h:1,x_center:.859375,y_center:.859375},{w:1,h:1,x_center:.890625,y_center:.859375},{w:1,h:1,x_center:.890625,y_center:.859375},{w:1,h:1,x_center:.921875,y_center:.859375},{w:1,h:1,x_center:.921875,y_center:.859375},{w:1,h:1,x_center:.953125,y_center:.859375},{w:1,h:1,x_center:.953125,y_center:.859375},{w:1,h:1,x_center:.984375,y_center:.859375},{w:1,h:1,x_center:.984375,y_center:.859375},{w:1,h:1,x_center:.015625,y_center:.890625},{w:1,h:1,x_center:.015625,y_center:.890625},{w:1,h:1,x_center:.046875,y_center:.890625},{w:1,h:1,x_center:.046875,y_center:.890625},{w:1,h:1,x_center:.078125,y_center:.890625},{w:1,h:1,x_center:.078125,y_center:.890625},{w:1,h:1,x_center:.109375,y_center:.890625},{w:1,h:1,x_center:.109375,y_center:.890625},{w:1,h:1,x_center:.140625,y_center:.890625},{w:1,h:1,x_center:.140625,y_center:.890625},{w:1,h:1,x_center:.171875,y_center:.890625},{w:1,h:1,x_center:.171875,y_center:.890625},{w:1,h:1,x_center:.203125,y_center:.890625},{w:1,h:1,x_center:.203125,y_center:.890625},{w:1,h:1,x_center:.234375,y_center:.890625},{w:1,h:1,x_center:.234375,y_center:.890625},{w:1,h:1,x_center:.265625,y_center:.890625},{w:1,h:1,x_center:.265625,y_center:.890625},{w:1,h:1,x_center:.296875,y_center:.890625},{w:1,h:1,x_center:.296875,y_center:.890625},{w:1,h:1,x_center:.328125,y_center:.890625},{w:1,h:1,x_center:.328125,y_center:.890625},{w:1,h:1,x_center:.359375,y_center:.890625},{w:1,h:1,x_center:.359375,y_center:.890625},{w:1,h:1,x_center:.390625,y_center:.890625},{w:1,h:1,x_center:.390625,y_center:.890625},{w:1,h:1,x_center:.421875,y_center:.890625},{w:1,h:1,x_center:.421875,y_center:.890625},{w:1,h:1,x_center:.453125,y_center:.890625},{w:1,h:1,x_center:.453125,y_center:.890625},{w:1,h:1,x_center:.484375,y_center:.890625},{w:1,h:1,x_center:.484375,y_center:.890625},{w:1,h:1,x_center:.515625,y_center:.890625},{w:1,h:1,x_center:.515625,y_center:.890625},{w:1,h:1,x_center:.546875,y_center:.890625},{w:1,h:1,x_center:.546875,y_center:.890625},{w:1,h:1,x_center:.578125,y_center:.890625},{w:1,h:1,x_center:.578125,y_center:.890625},{w:1,h:1,x_center:.609375,y_center:.890625},{w:1,h:1,x_center:.609375,y_center:.890625},{w:1,h:1,x_center:.640625,y_center:.890625},{w:1,h:1,x_center:.640625,y_center:.890625},{w:1,h:1,x_center:.671875,y_center:.890625},{w:1,h:1,x_center:.671875,y_center:.890625},{w:1,h:1,x_center:.703125,y_center:.890625},{w:1,h:1,x_center:.703125,y_center:.890625},{w:1,h:1,x_center:.734375,y_center:.890625},{w:1,h:1,x_center:.734375,y_center:.890625},{w:1,h:1,x_center:.765625,y_center:.890625},{w:1,h:1,x_center:.765625,y_center:.890625},{w:1,h:1,x_center:.796875,y_center:.890625},{w:1,h:1,x_center:.796875,y_center:.890625},{w:1,h:1,x_center:.828125,y_center:.890625},{w:1,h:1,x_center:.828125,y_center:.890625},{w:1,h:1,x_center:.859375,y_center:.890625},{w:1,h:1,x_center:.859375,y_center:.890625},{w:1,h:1,x_center:.890625,y_center:.890625},{w:1,h:1,x_center:.890625,y_center:.890625},{w:1,h:1,x_center:.921875,y_center:.890625},{w:1,h:1,x_center:.921875,y_center:.890625},{w:1,h:1,x_center:.953125,y_center:.890625},{w:1,h:1,x_center:.953125,y_center:.890625},{w:1,h:1,x_center:.984375,y_center:.890625},{w:1,h:1,x_center:.984375,y_center:.890625},{w:1,h:1,x_center:.015625,y_center:.921875},{w:1,h:1,x_center:.015625,y_center:.921875},{w:1,h:1,x_center:.046875,y_center:.921875},{w:1,h:1,x_center:.046875,y_center:.921875},{w:1,h:1,x_center:.078125,y_center:.921875},{w:1,h:1,x_center:.078125,y_center:.921875},{w:1,h:1,x_center:.109375,y_center:.921875},{w:1,h:1,x_center:.109375,y_center:.921875},{w:1,h:1,x_center:.140625,y_center:.921875},{w:1,h:1,x_center:.140625,y_center:.921875},{w:1,h:1,x_center:.171875,y_center:.921875},{w:1,h:1,x_center:.171875,y_center:.921875},{w:1,h:1,x_center:.203125,y_center:.921875},{w:1,h:1,x_center:.203125,y_center:.921875},{w:1,h:1,x_center:.234375,y_center:.921875},{w:1,h:1,x_center:.234375,y_center:.921875},{w:1,h:1,x_center:.265625,y_center:.921875},{w:1,h:1,x_center:.265625,y_center:.921875},{w:1,h:1,x_center:.296875,y_center:.921875},{w:1,h:1,x_center:.296875,y_center:.921875},{w:1,h:1,x_center:.328125,y_center:.921875},{w:1,h:1,x_center:.328125,y_center:.921875},{w:1,h:1,x_center:.359375,y_center:.921875},{w:1,h:1,x_center:.359375,y_center:.921875},{w:1,h:1,x_center:.390625,y_center:.921875},{w:1,h:1,x_center:.390625,y_center:.921875},{w:1,h:1,x_center:.421875,y_center:.921875},{w:1,h:1,x_center:.421875,y_center:.921875},{w:1,h:1,x_center:.453125,y_center:.921875},{w:1,h:1,x_center:.453125,y_center:.921875},{w:1,h:1,x_center:.484375,y_center:.921875},{w:1,h:1,x_center:.484375,y_center:.921875},{w:1,h:1,x_center:.515625,y_center:.921875},{w:1,h:1,x_center:.515625,y_center:.921875},{w:1,h:1,x_center:.546875,y_center:.921875},{w:1,h:1,x_center:.546875,y_center:.921875},{w:1,h:1,x_center:.578125,y_center:.921875},{w:1,h:1,x_center:.578125,y_center:.921875},{w:1,h:1,x_center:.609375,y_center:.921875},{w:1,h:1,x_center:.609375,y_center:.921875},{w:1,h:1,x_center:.640625,y_center:.921875},{w:1,h:1,x_center:.640625,y_center:.921875},{w:1,h:1,x_center:.671875,y_center:.921875},{w:1,h:1,x_center:.671875,y_center:.921875},{w:1,h:1,x_center:.703125,y_center:.921875},{w:1,h:1,x_center:.703125,y_center:.921875},{w:1,h:1,x_center:.734375,y_center:.921875},{w:1,h:1,x_center:.734375,y_center:.921875},{w:1,h:1,x_center:.765625,y_center:.921875},{w:1,h:1,x_center:.765625,y_center:.921875},{w:1,h:1,x_center:.796875,y_center:.921875},{w:1,h:1,x_center:.796875,y_center:.921875},{w:1,h:1,x_center:.828125,y_center:.921875},{w:1,h:1,x_center:.828125,y_center:.921875},{w:1,h:1,x_center:.859375,y_center:.921875},{w:1,h:1,x_center:.859375,y_center:.921875},{w:1,h:1,x_center:.890625,y_center:.921875},{w:1,h:1,x_center:.890625,y_center:.921875},{w:1,h:1,x_center:.921875,y_center:.921875},{w:1,h:1,x_center:.921875,y_center:.921875},{w:1,h:1,x_center:.953125,y_center:.921875},{w:1,h:1,x_center:.953125,y_center:.921875},{w:1,h:1,x_center:.984375,y_center:.921875},{w:1,h:1,x_center:.984375,y_center:.921875},{w:1,h:1,x_center:.015625,y_center:.953125},{w:1,h:1,x_center:.015625,y_center:.953125},{w:1,h:1,x_center:.046875,y_center:.953125},{w:1,h:1,x_center:.046875,y_center:.953125},{w:1,h:1,x_center:.078125,y_center:.953125},{w:1,h:1,x_center:.078125,y_center:.953125},{w:1,h:1,x_center:.109375,y_center:.953125},{w:1,h:1,x_center:.109375,y_center:.953125},{w:1,h:1,x_center:.140625,y_center:.953125},{w:1,h:1,x_center:.140625,y_center:.953125},{w:1,h:1,x_center:.171875,y_center:.953125},{w:1,h:1,x_center:.171875,y_center:.953125},{w:1,h:1,x_center:.203125,y_center:.953125},{w:1,h:1,x_center:.203125,y_center:.953125},{w:1,h:1,x_center:.234375,y_center:.953125},{w:1,h:1,x_center:.234375,y_center:.953125},{w:1,h:1,x_center:.265625,y_center:.953125},{w:1,h:1,x_center:.265625,y_center:.953125},{w:1,h:1,x_center:.296875,y_center:.953125},{w:1,h:1,x_center:.296875,y_center:.953125},{w:1,h:1,x_center:.328125,y_center:.953125},{w:1,h:1,x_center:.328125,y_center:.953125},{w:1,h:1,x_center:.359375,y_center:.953125},{w:1,h:1,x_center:.359375,y_center:.953125},{w:1,h:1,x_center:.390625,y_center:.953125},{w:1,h:1,x_center:.390625,y_center:.953125},{w:1,h:1,x_center:.421875,y_center:.953125},{w:1,h:1,x_center:.421875,y_center:.953125},{w:1,h:1,x_center:.453125,y_center:.953125},{w:1,h:1,x_center:.453125,y_center:.953125},{w:1,h:1,x_center:.484375,y_center:.953125},{w:1,h:1,x_center:.484375,y_center:.953125},{w:1,h:1,x_center:.515625,y_center:.953125},{w:1,h:1,x_center:.515625,y_center:.953125},{w:1,h:1,x_center:.546875,y_center:.953125},{w:1,h:1,x_center:.546875,y_center:.953125},{w:1,h:1,x_center:.578125,y_center:.953125},{w:1,h:1,x_center:.578125,y_center:.953125},{w:1,h:1,x_center:.609375,y_center:.953125},{w:1,h:1,x_center:.609375,y_center:.953125},{w:1,h:1,x_center:.640625,y_center:.953125},{w:1,h:1,x_center:.640625,y_center:.953125},{w:1,h:1,x_center:.671875,y_center:.953125},{w:1,h:1,x_center:.671875,y_center:.953125},{w:1,h:1,x_center:.703125,y_center:.953125},{w:1,h:1,x_center:.703125,y_center:.953125},{w:1,h:1,x_center:.734375,y_center:.953125},{w:1,h:1,x_center:.734375,y_center:.953125},{w:1,h:1,x_center:.765625,y_center:.953125},{w:1,h:1,x_center:.765625,y_center:.953125},{w:1,h:1,x_center:.796875,y_center:.953125},{w:1,h:1,x_center:.796875,y_center:.953125},{w:1,h:1,x_center:.828125,y_center:.953125},{w:1,h:1,x_center:.828125,y_center:.953125},{w:1,h:1,x_center:.859375,y_center:.953125},{w:1,h:1,x_center:.859375,y_center:.953125},{w:1,h:1,x_center:.890625,y_center:.953125},{w:1,h:1,x_center:.890625,y_center:.953125},{w:1,h:1,x_center:.921875,y_center:.953125},{w:1,h:1,x_center:.921875,y_center:.953125},{w:1,h:1,x_center:.953125,y_center:.953125},{w:1,h:1,x_center:.953125,y_center:.953125},{w:1,h:1,x_center:.984375,y_center:.953125},{w:1,h:1,x_center:.984375,y_center:.953125},{w:1,h:1,x_center:.015625,y_center:.984375},{w:1,h:1,x_center:.015625,y_center:.984375},{w:1,h:1,x_center:.046875,y_center:.984375},{w:1,h:1,x_center:.046875,y_center:.984375},{w:1,h:1,x_center:.078125,y_center:.984375},{w:1,h:1,x_center:.078125,y_center:.984375},{w:1,h:1,x_center:.109375,y_center:.984375},{w:1,h:1,x_center:.109375,y_center:.984375},{w:1,h:1,x_center:.140625,y_center:.984375},{w:1,h:1,x_center:.140625,y_center:.984375},{w:1,h:1,x_center:.171875,y_center:.984375},{w:1,h:1,x_center:.171875,y_center:.984375},{w:1,h:1,x_center:.203125,y_center:.984375},{w:1,h:1,x_center:.203125,y_center:.984375},{w:1,h:1,x_center:.234375,y_center:.984375},{w:1,h:1,x_center:.234375,y_center:.984375},{w:1,h:1,x_center:.265625,y_center:.984375},{w:1,h:1,x_center:.265625,y_center:.984375},{w:1,h:1,x_center:.296875,y_center:.984375},{w:1,h:1,x_center:.296875,y_center:.984375},{w:1,h:1,x_center:.328125,y_center:.984375},{w:1,h:1,x_center:.328125,y_center:.984375},{w:1,h:1,x_center:.359375,y_center:.984375},{w:1,h:1,x_center:.359375,y_center:.984375},{w:1,h:1,x_center:.390625,y_center:.984375},{w:1,h:1,x_center:.390625,y_center:.984375},{w:1,h:1,x_center:.421875,y_center:.984375},{w:1,h:1,x_center:.421875,y_center:.984375},{w:1,h:1,x_center:.453125,y_center:.984375},{w:1,h:1,x_center:.453125,y_center:.984375},{w:1,h:1,x_center:.484375,y_center:.984375},{w:1,h:1,x_center:.484375,y_center:.984375},{w:1,h:1,x_center:.515625,y_center:.984375},{w:1,h:1,x_center:.515625,y_center:.984375},{w:1,h:1,x_center:.546875,y_center:.984375},{w:1,h:1,x_center:.546875,y_center:.984375},{w:1,h:1,x_center:.578125,y_center:.984375},{w:1,h:1,x_center:.578125,y_center:.984375},{w:1,h:1,x_center:.609375,y_center:.984375},{w:1,h:1,x_center:.609375,y_center:.984375},{w:1,h:1,x_center:.640625,y_center:.984375},{w:1,h:1,x_center:.640625,y_center:.984375},{w:1,h:1,x_center:.671875,y_center:.984375},{w:1,h:1,x_center:.671875,y_center:.984375},{w:1,h:1,x_center:.703125,y_center:.984375},{w:1,h:1,x_center:.703125,y_center:.984375},{w:1,h:1,x_center:.734375,y_center:.984375},{w:1,h:1,x_center:.734375,y_center:.984375},{w:1,h:1,x_center:.765625,y_center:.984375},{w:1,h:1,x_center:.765625,y_center:.984375},{w:1,h:1,x_center:.796875,y_center:.984375},{w:1,h:1,x_center:.796875,y_center:.984375},{w:1,h:1,x_center:.828125,y_center:.984375},{w:1,h:1,x_center:.828125,y_center:.984375},{w:1,h:1,x_center:.859375,y_center:.984375},{w:1,h:1,x_center:.859375,y_center:.984375},{w:1,h:1,x_center:.890625,y_center:.984375},{w:1,h:1,x_center:.890625,y_center:.984375},{w:1,h:1,x_center:.921875,y_center:.984375},{w:1,h:1,x_center:.921875,y_center:.984375},{w:1,h:1,x_center:.953125,y_center:.984375},{w:1,h:1,x_center:.953125,y_center:.984375},{w:1,h:1,x_center:.984375,y_center:.984375},{w:1,h:1,x_center:.984375,y_center:.984375},{w:1,h:1,x_center:.03125,y_center:.03125},{w:1,h:1,x_center:.03125,y_center:.03125},{w:1,h:1,x_center:.09375,y_center:.03125},{w:1,h:1,x_center:.09375,y_center:.03125},{w:1,h:1,x_center:.15625,y_center:.03125},{w:1,h:1,x_center:.15625,y_center:.03125},{w:1,h:1,x_center:.21875,y_center:.03125},{w:1,h:1,x_center:.21875,y_center:.03125},{w:1,h:1,x_center:.28125,y_center:.03125},{w:1,h:1,x_center:.28125,y_center:.03125},{w:1,h:1,x_center:.34375,y_center:.03125},{w:1,h:1,x_center:.34375,y_center:.03125},{w:1,h:1,x_center:.40625,y_center:.03125},{w:1,h:1,x_center:.40625,y_center:.03125},{w:1,h:1,x_center:.46875,y_center:.03125},{w:1,h:1,x_center:.46875,y_center:.03125},{w:1,h:1,x_center:.53125,y_center:.03125},{w:1,h:1,x_center:.53125,y_center:.03125},{w:1,h:1,x_center:.59375,y_center:.03125},{w:1,h:1,x_center:.59375,y_center:.03125},{w:1,h:1,x_center:.65625,y_center:.03125},{w:1,h:1,x_center:.65625,y_center:.03125},{w:1,h:1,x_center:.71875,y_center:.03125},{w:1,h:1,x_center:.71875,y_center:.03125},{w:1,h:1,x_center:.78125,y_center:.03125},{w:1,h:1,x_center:.78125,y_center:.03125},{w:1,h:1,x_center:.84375,y_center:.03125},{w:1,h:1,x_center:.84375,y_center:.03125},{w:1,h:1,x_center:.90625,y_center:.03125},{w:1,h:1,x_center:.90625,y_center:.03125},{w:1,h:1,x_center:.96875,y_center:.03125},{w:1,h:1,x_center:.96875,y_center:.03125},{w:1,h:1,x_center:.03125,y_center:.09375},{w:1,h:1,x_center:.03125,y_center:.09375},{w:1,h:1,x_center:.09375,y_center:.09375},{w:1,h:1,x_center:.09375,y_center:.09375},{w:1,h:1,x_center:.15625,y_center:.09375},{w:1,h:1,x_center:.15625,y_center:.09375},{w:1,h:1,x_center:.21875,y_center:.09375},{w:1,h:1,x_center:.21875,y_center:.09375},{w:1,h:1,x_center:.28125,y_center:.09375},{w:1,h:1,x_center:.28125,y_center:.09375},{w:1,h:1,x_center:.34375,y_center:.09375},{w:1,h:1,x_center:.34375,y_center:.09375},{w:1,h:1,x_center:.40625,y_center:.09375},{w:1,h:1,x_center:.40625,y_center:.09375},{w:1,h:1,x_center:.46875,y_center:.09375},{w:1,h:1,x_center:.46875,y_center:.09375},{w:1,h:1,x_center:.53125,y_center:.09375},{w:1,h:1,x_center:.53125,y_center:.09375},{w:1,h:1,x_center:.59375,y_center:.09375},{w:1,h:1,x_center:.59375,y_center:.09375},{w:1,h:1,x_center:.65625,y_center:.09375},{w:1,h:1,x_center:.65625,y_center:.09375},{w:1,h:1,x_center:.71875,y_center:.09375},{w:1,h:1,x_center:.71875,y_center:.09375},{w:1,h:1,x_center:.78125,y_center:.09375},{w:1,h:1,x_center:.78125,y_center:.09375},{w:1,h:1,x_center:.84375,y_center:.09375},{w:1,h:1,x_center:.84375,y_center:.09375},{w:1,h:1,x_center:.90625,y_center:.09375},{w:1,h:1,x_center:.90625,y_center:.09375},{w:1,h:1,x_center:.96875,y_center:.09375},{w:1,h:1,x_center:.96875,y_center:.09375},{w:1,h:1,x_center:.03125,y_center:.15625},{w:1,h:1,x_center:.03125,y_center:.15625},{w:1,h:1,x_center:.09375,y_center:.15625},{w:1,h:1,x_center:.09375,y_center:.15625},{w:1,h:1,x_center:.15625,y_center:.15625},{w:1,h:1,x_center:.15625,y_center:.15625},{w:1,h:1,x_center:.21875,y_center:.15625},{w:1,h:1,x_center:.21875,y_center:.15625},{w:1,h:1,x_center:.28125,y_center:.15625},{w:1,h:1,x_center:.28125,y_center:.15625},{w:1,h:1,x_center:.34375,y_center:.15625},{w:1,h:1,x_center:.34375,y_center:.15625},{w:1,h:1,x_center:.40625,y_center:.15625},{w:1,h:1,x_center:.40625,y_center:.15625},{w:1,h:1,x_center:.46875,y_center:.15625},{w:1,h:1,x_center:.46875,y_center:.15625},{w:1,h:1,x_center:.53125,y_center:.15625},{w:1,h:1,x_center:.53125,y_center:.15625},{w:1,h:1,x_center:.59375,y_center:.15625},{w:1,h:1,x_center:.59375,y_center:.15625},{w:1,h:1,x_center:.65625,y_center:.15625},{w:1,h:1,x_center:.65625,y_center:.15625},{w:1,h:1,x_center:.71875,y_center:.15625},{w:1,h:1,x_center:.71875,y_center:.15625},{w:1,h:1,x_center:.78125,y_center:.15625},{w:1,h:1,x_center:.78125,y_center:.15625},{w:1,h:1,x_center:.84375,y_center:.15625},{w:1,h:1,x_center:.84375,y_center:.15625},{w:1,h:1,x_center:.90625,y_center:.15625},{w:1,h:1,x_center:.90625,y_center:.15625},{w:1,h:1,x_center:.96875,y_center:.15625},{w:1,h:1,x_center:.96875,y_center:.15625},{w:1,h:1,x_center:.03125,y_center:.21875},{w:1,h:1,x_center:.03125,y_center:.21875},{w:1,h:1,x_center:.09375,y_center:.21875},{w:1,h:1,x_center:.09375,y_center:.21875},{w:1,h:1,x_center:.15625,y_center:.21875},{w:1,h:1,x_center:.15625,y_center:.21875},{w:1,h:1,x_center:.21875,y_center:.21875},{w:1,h:1,x_center:.21875,y_center:.21875},{w:1,h:1,x_center:.28125,y_center:.21875},{w:1,h:1,x_center:.28125,y_center:.21875},{w:1,h:1,x_center:.34375,y_center:.21875},{w:1,h:1,x_center:.34375,y_center:.21875},{w:1,h:1,x_center:.40625,y_center:.21875},{w:1,h:1,x_center:.40625,y_center:.21875},{w:1,h:1,x_center:.46875,y_center:.21875},{w:1,h:1,x_center:.46875,y_center:.21875},{w:1,h:1,x_center:.53125,y_center:.21875},{w:1,h:1,x_center:.53125,y_center:.21875},{w:1,h:1,x_center:.59375,y_center:.21875},{w:1,h:1,x_center:.59375,y_center:.21875},{w:1,h:1,x_center:.65625,y_center:.21875},{w:1,h:1,x_center:.65625,y_center:.21875},{w:1,h:1,x_center:.71875,y_center:.21875},{w:1,h:1,x_center:.71875,y_center:.21875},{w:1,h:1,x_center:.78125,y_center:.21875},{w:1,h:1,x_center:.78125,y_center:.21875},{w:1,h:1,x_center:.84375,y_center:.21875},{w:1,h:1,x_center:.84375,y_center:.21875},{w:1,h:1,x_center:.90625,y_center:.21875},{w:1,h:1,x_center:.90625,y_center:.21875},{w:1,h:1,x_center:.96875,y_center:.21875},{w:1,h:1,x_center:.96875,y_center:.21875},{w:1,h:1,x_center:.03125,y_center:.28125},{w:1,h:1,x_center:.03125,y_center:.28125},{w:1,h:1,x_center:.09375,y_center:.28125},{w:1,h:1,x_center:.09375,y_center:.28125},{w:1,h:1,x_center:.15625,y_center:.28125},{w:1,h:1,x_center:.15625,y_center:.28125},{w:1,h:1,x_center:.21875,y_center:.28125},{w:1,h:1,x_center:.21875,y_center:.28125},{w:1,h:1,x_center:.28125,y_center:.28125},{w:1,h:1,x_center:.28125,y_center:.28125},{w:1,h:1,x_center:.34375,y_center:.28125},{w:1,h:1,x_center:.34375,y_center:.28125},{w:1,h:1,x_center:.40625,y_center:.28125},{w:1,h:1,x_center:.40625,y_center:.28125},{w:1,h:1,x_center:.46875,y_center:.28125},{w:1,h:1,x_center:.46875,y_center:.28125},{w:1,h:1,x_center:.53125,y_center:.28125},{w:1,h:1,x_center:.53125,y_center:.28125},{w:1,h:1,x_center:.59375,y_center:.28125},{w:1,h:1,x_center:.59375,y_center:.28125},{w:1,h:1,x_center:.65625,y_center:.28125},{w:1,h:1,x_center:.65625,y_center:.28125},{w:1,h:1,x_center:.71875,y_center:.28125},{w:1,h:1,x_center:.71875,y_center:.28125},{w:1,h:1,x_center:.78125,y_center:.28125},{w:1,h:1,x_center:.78125,y_center:.28125},{w:1,h:1,x_center:.84375,y_center:.28125},{w:1,h:1,x_center:.84375,y_center:.28125},{w:1,h:1,x_center:.90625,y_center:.28125},{w:1,h:1,x_center:.90625,y_center:.28125},{w:1,h:1,x_center:.96875,y_center:.28125},{w:1,h:1,x_center:.96875,y_center:.28125},{w:1,h:1,x_center:.03125,y_center:.34375},{w:1,h:1,x_center:.03125,y_center:.34375},{w:1,h:1,x_center:.09375,y_center:.34375},{w:1,h:1,x_center:.09375,y_center:.34375},{w:1,h:1,x_center:.15625,y_center:.34375},{w:1,h:1,x_center:.15625,y_center:.34375},{w:1,h:1,x_center:.21875,y_center:.34375},{w:1,h:1,x_center:.21875,y_center:.34375},{w:1,h:1,x_center:.28125,y_center:.34375},{w:1,h:1,x_center:.28125,y_center:.34375},{w:1,h:1,x_center:.34375,y_center:.34375},{w:1,h:1,x_center:.34375,y_center:.34375},{w:1,h:1,x_center:.40625,y_center:.34375},{w:1,h:1,x_center:.40625,y_center:.34375},{w:1,h:1,x_center:.46875,y_center:.34375},{w:1,h:1,x_center:.46875,y_center:.34375},{w:1,h:1,x_center:.53125,y_center:.34375},{w:1,h:1,x_center:.53125,y_center:.34375},{w:1,h:1,x_center:.59375,y_center:.34375},{w:1,h:1,x_center:.59375,y_center:.34375},{w:1,h:1,x_center:.65625,y_center:.34375},{w:1,h:1,x_center:.65625,y_center:.34375},{w:1,h:1,x_center:.71875,y_center:.34375},{w:1,h:1,x_center:.71875,y_center:.34375},{w:1,h:1,x_center:.78125,y_center:.34375},{w:1,h:1,x_center:.78125,y_center:.34375},{w:1,h:1,x_center:.84375,y_center:.34375},{w:1,h:1,x_center:.84375,y_center:.34375},{w:1,h:1,x_center:.90625,y_center:.34375},{w:1,h:1,x_center:.90625,y_center:.34375},{w:1,h:1,x_center:.96875,y_center:.34375},{w:1,h:1,x_center:.96875,y_center:.34375},{w:1,h:1,x_center:.03125,y_center:.40625},{w:1,h:1,x_center:.03125,y_center:.40625},{w:1,h:1,x_center:.09375,y_center:.40625},{w:1,h:1,x_center:.09375,y_center:.40625},{w:1,h:1,x_center:.15625,y_center:.40625},{w:1,h:1,x_center:.15625,y_center:.40625},{w:1,h:1,x_center:.21875,y_center:.40625},{w:1,h:1,x_center:.21875,y_center:.40625},{w:1,h:1,x_center:.28125,y_center:.40625},{w:1,h:1,x_center:.28125,y_center:.40625},{w:1,h:1,x_center:.34375,y_center:.40625},{w:1,h:1,x_center:.34375,y_center:.40625},{w:1,h:1,x_center:.40625,y_center:.40625},{w:1,h:1,x_center:.40625,y_center:.40625},{w:1,h:1,x_center:.46875,y_center:.40625},{w:1,h:1,x_center:.46875,y_center:.40625},{w:1,h:1,x_center:.53125,y_center:.40625},{w:1,h:1,x_center:.53125,y_center:.40625},{w:1,h:1,x_center:.59375,y_center:.40625},{w:1,h:1,x_center:.59375,y_center:.40625},{w:1,h:1,x_center:.65625,y_center:.40625},{w:1,h:1,x_center:.65625,y_center:.40625},{w:1,h:1,x_center:.71875,y_center:.40625},{w:1,h:1,x_center:.71875,y_center:.40625},{w:1,h:1,x_center:.78125,y_center:.40625},{w:1,h:1,x_center:.78125,y_center:.40625},{w:1,h:1,x_center:.84375,y_center:.40625},{w:1,h:1,x_center:.84375,y_center:.40625},{w:1,h:1,x_center:.90625,y_center:.40625},{w:1,h:1,x_center:.90625,y_center:.40625},{w:1,h:1,x_center:.96875,y_center:.40625},{w:1,h:1,x_center:.96875,y_center:.40625},{w:1,h:1,x_center:.03125,y_center:.46875},{w:1,h:1,x_center:.03125,y_center:.46875},{w:1,h:1,x_center:.09375,y_center:.46875},{w:1,h:1,x_center:.09375,y_center:.46875},{w:1,h:1,x_center:.15625,y_center:.46875},{w:1,h:1,x_center:.15625,y_center:.46875},{w:1,h:1,x_center:.21875,y_center:.46875},{w:1,h:1,x_center:.21875,y_center:.46875},{w:1,h:1,x_center:.28125,y_center:.46875},{w:1,h:1,x_center:.28125,y_center:.46875},{w:1,h:1,x_center:.34375,y_center:.46875},{w:1,h:1,x_center:.34375,y_center:.46875},{w:1,h:1,x_center:.40625,y_center:.46875},{w:1,h:1,x_center:.40625,y_center:.46875},{w:1,h:1,x_center:.46875,y_center:.46875},{w:1,h:1,x_center:.46875,y_center:.46875},{w:1,h:1,x_center:.53125,y_center:.46875},{w:1,h:1,x_center:.53125,y_center:.46875},{w:1,h:1,x_center:.59375,y_center:.46875},{w:1,h:1,x_center:.59375,y_center:.46875},{w:1,h:1,x_center:.65625,y_center:.46875},{w:1,h:1,x_center:.65625,y_center:.46875},{w:1,h:1,x_center:.71875,y_center:.46875},{w:1,h:1,x_center:.71875,y_center:.46875},{w:1,h:1,x_center:.78125,y_center:.46875},{w:1,h:1,x_center:.78125,y_center:.46875},{w:1,h:1,x_center:.84375,y_center:.46875},{w:1,h:1,x_center:.84375,y_center:.46875},{w:1,h:1,x_center:.90625,y_center:.46875},{w:1,h:1,x_center:.90625,y_center:.46875},{w:1,h:1,x_center:.96875,y_center:.46875},{w:1,h:1,x_center:.96875,y_center:.46875},{w:1,h:1,x_center:.03125,y_center:.53125},{w:1,h:1,x_center:.03125,y_center:.53125},{w:1,h:1,x_center:.09375,y_center:.53125},{w:1,h:1,x_center:.09375,y_center:.53125},{w:1,h:1,x_center:.15625,y_center:.53125},{w:1,h:1,x_center:.15625,y_center:.53125},{w:1,h:1,x_center:.21875,y_center:.53125},{w:1,h:1,x_center:.21875,y_center:.53125},{w:1,h:1,x_center:.28125,y_center:.53125},{w:1,h:1,x_center:.28125,y_center:.53125},{w:1,h:1,x_center:.34375,y_center:.53125},{w:1,h:1,x_center:.34375,y_center:.53125},{w:1,h:1,x_center:.40625,y_center:.53125},{w:1,h:1,x_center:.40625,y_center:.53125},{w:1,h:1,x_center:.46875,y_center:.53125},{w:1,h:1,x_center:.46875,y_center:.53125},{w:1,h:1,x_center:.53125,y_center:.53125},{w:1,h:1,x_center:.53125,y_center:.53125},{w:1,h:1,x_center:.59375,y_center:.53125},{w:1,h:1,x_center:.59375,y_center:.53125},{w:1,h:1,x_center:.65625,y_center:.53125},{w:1,h:1,x_center:.65625,y_center:.53125},{w:1,h:1,x_center:.71875,y_center:.53125},{w:1,h:1,x_center:.71875,y_center:.53125},{w:1,h:1,x_center:.78125,y_center:.53125},{w:1,h:1,x_center:.78125,y_center:.53125},{w:1,h:1,x_center:.84375,y_center:.53125},{w:1,h:1,x_center:.84375,y_center:.53125},{w:1,h:1,x_center:.90625,y_center:.53125},{w:1,h:1,x_center:.90625,y_center:.53125},{w:1,h:1,x_center:.96875,y_center:.53125},{w:1,h:1,x_center:.96875,y_center:.53125},{w:1,h:1,x_center:.03125,y_center:.59375},{w:1,h:1,x_center:.03125,y_center:.59375},{w:1,h:1,x_center:.09375,y_center:.59375},{w:1,h:1,x_center:.09375,y_center:.59375},{w:1,h:1,x_center:.15625,y_center:.59375},{w:1,h:1,x_center:.15625,y_center:.59375},{w:1,h:1,x_center:.21875,y_center:.59375},{w:1,h:1,x_center:.21875,y_center:.59375},{w:1,h:1,x_center:.28125,y_center:.59375},{w:1,h:1,x_center:.28125,y_center:.59375},{w:1,h:1,x_center:.34375,y_center:.59375},{w:1,h:1,x_center:.34375,y_center:.59375},{w:1,h:1,x_center:.40625,y_center:.59375},{w:1,h:1,x_center:.40625,y_center:.59375},{w:1,h:1,x_center:.46875,y_center:.59375},{w:1,h:1,x_center:.46875,y_center:.59375},{w:1,h:1,x_center:.53125,y_center:.59375},{w:1,h:1,x_center:.53125,y_center:.59375},{w:1,h:1,x_center:.59375,y_center:.59375},{w:1,h:1,x_center:.59375,y_center:.59375},{w:1,h:1,x_center:.65625,y_center:.59375},{w:1,h:1,x_center:.65625,y_center:.59375},{w:1,h:1,x_center:.71875,y_center:.59375},{w:1,h:1,x_center:.71875,y_center:.59375},{w:1,h:1,x_center:.78125,y_center:.59375},{w:1,h:1,x_center:.78125,y_center:.59375},{w:1,h:1,x_center:.84375,y_center:.59375},{w:1,h:1,x_center:.84375,y_center:.59375},{w:1,h:1,x_center:.90625,y_center:.59375},{w:1,h:1,x_center:.90625,y_center:.59375},{w:1,h:1,x_center:.96875,y_center:.59375},{w:1,h:1,x_center:.96875,y_center:.59375},{w:1,h:1,x_center:.03125,y_center:.65625},{w:1,h:1,x_center:.03125,y_center:.65625},{w:1,h:1,x_center:.09375,y_center:.65625},{w:1,h:1,x_center:.09375,y_center:.65625},{w:1,h:1,x_center:.15625,y_center:.65625},{w:1,h:1,x_center:.15625,y_center:.65625},{w:1,h:1,x_center:.21875,y_center:.65625},{w:1,h:1,x_center:.21875,y_center:.65625},{w:1,h:1,x_center:.28125,y_center:.65625},{w:1,h:1,x_center:.28125,y_center:.65625},{w:1,h:1,x_center:.34375,y_center:.65625},{w:1,h:1,x_center:.34375,y_center:.65625},{w:1,h:1,x_center:.40625,y_center:.65625},{w:1,h:1,x_center:.40625,y_center:.65625},{w:1,h:1,x_center:.46875,y_center:.65625},{w:1,h:1,x_center:.46875,y_center:.65625},{w:1,h:1,x_center:.53125,y_center:.65625},{w:1,h:1,x_center:.53125,y_center:.65625},{w:1,h:1,x_center:.59375,y_center:.65625},{w:1,h:1,x_center:.59375,y_center:.65625},{w:1,h:1,x_center:.65625,y_center:.65625},{w:1,h:1,x_center:.65625,y_center:.65625},{w:1,h:1,x_center:.71875,y_center:.65625},{w:1,h:1,x_center:.71875,y_center:.65625},{w:1,h:1,x_center:.78125,y_center:.65625},{w:1,h:1,x_center:.78125,y_center:.65625},{w:1,h:1,x_center:.84375,y_center:.65625},{w:1,h:1,x_center:.84375,y_center:.65625},{w:1,h:1,x_center:.90625,y_center:.65625},{w:1,h:1,x_center:.90625,y_center:.65625},{w:1,h:1,x_center:.96875,y_center:.65625},{w:1,h:1,x_center:.96875,y_center:.65625},{w:1,h:1,x_center:.03125,y_center:.71875},{w:1,h:1,x_center:.03125,y_center:.71875},{w:1,h:1,x_center:.09375,y_center:.71875},{w:1,h:1,x_center:.09375,y_center:.71875},{w:1,h:1,x_center:.15625,y_center:.71875},{w:1,h:1,x_center:.15625,y_center:.71875},{w:1,h:1,x_center:.21875,y_center:.71875},{w:1,h:1,x_center:.21875,y_center:.71875},{w:1,h:1,x_center:.28125,y_center:.71875},{w:1,h:1,x_center:.28125,y_center:.71875},{w:1,h:1,x_center:.34375,y_center:.71875},{w:1,h:1,x_center:.34375,y_center:.71875},{w:1,h:1,x_center:.40625,y_center:.71875},{w:1,h:1,x_center:.40625,y_center:.71875},{w:1,h:1,x_center:.46875,y_center:.71875},{w:1,h:1,x_center:.46875,y_center:.71875},{w:1,h:1,x_center:.53125,y_center:.71875},{w:1,h:1,x_center:.53125,y_center:.71875},{w:1,h:1,x_center:.59375,y_center:.71875},{w:1,h:1,x_center:.59375,y_center:.71875},{w:1,h:1,x_center:.65625,y_center:.71875},{w:1,h:1,x_center:.65625,y_center:.71875},{w:1,h:1,x_center:.71875,y_center:.71875},{w:1,h:1,x_center:.71875,y_center:.71875},{w:1,h:1,x_center:.78125,y_center:.71875},{w:1,h:1,x_center:.78125,y_center:.71875},{w:1,h:1,x_center:.84375,y_center:.71875},{w:1,h:1,x_center:.84375,y_center:.71875},{w:1,h:1,x_center:.90625,y_center:.71875},{w:1,h:1,x_center:.90625,y_center:.71875},{w:1,h:1,x_center:.96875,y_center:.71875},{w:1,h:1,x_center:.96875,y_center:.71875},{w:1,h:1,x_center:.03125,y_center:.78125},{w:1,h:1,x_center:.03125,y_center:.78125},{w:1,h:1,x_center:.09375,y_center:.78125},{w:1,h:1,x_center:.09375,y_center:.78125},{w:1,h:1,x_center:.15625,y_center:.78125},{w:1,h:1,x_center:.15625,y_center:.78125},{w:1,h:1,x_center:.21875,y_center:.78125},{w:1,h:1,x_center:.21875,y_center:.78125},{w:1,h:1,x_center:.28125,y_center:.78125},{w:1,h:1,x_center:.28125,y_center:.78125},{w:1,h:1,x_center:.34375,y_center:.78125},{w:1,h:1,x_center:.34375,y_center:.78125},{w:1,h:1,x_center:.40625,y_center:.78125},{w:1,h:1,x_center:.40625,y_center:.78125},{w:1,h:1,x_center:.46875,y_center:.78125},{w:1,h:1,x_center:.46875,y_center:.78125},{w:1,h:1,x_center:.53125,y_center:.78125},{w:1,h:1,x_center:.53125,y_center:.78125},{w:1,h:1,x_center:.59375,y_center:.78125},{w:1,h:1,x_center:.59375,y_center:.78125},{w:1,h:1,x_center:.65625,y_center:.78125},{w:1,h:1,x_center:.65625,y_center:.78125},{w:1,h:1,x_center:.71875,y_center:.78125},{w:1,h:1,x_center:.71875,y_center:.78125},{w:1,h:1,x_center:.78125,y_center:.78125},{w:1,h:1,x_center:.78125,y_center:.78125},{w:1,h:1,x_center:.84375,y_center:.78125},{w:1,h:1,x_center:.84375,y_center:.78125},{w:1,h:1,x_center:.90625,y_center:.78125},{w:1,h:1,x_center:.90625,y_center:.78125},{w:1,h:1,x_center:.96875,y_center:.78125},{w:1,h:1,x_center:.96875,y_center:.78125},{w:1,h:1,x_center:.03125,y_center:.84375},{w:1,h:1,x_center:.03125,y_center:.84375},{w:1,h:1,x_center:.09375,y_center:.84375},{w:1,h:1,x_center:.09375,y_center:.84375},{w:1,h:1,x_center:.15625,y_center:.84375},{w:1,h:1,x_center:.15625,y_center:.84375},{w:1,h:1,x_center:.21875,y_center:.84375},{w:1,h:1,x_center:.21875,y_center:.84375},{w:1,h:1,x_center:.28125,y_center:.84375},{w:1,h:1,x_center:.28125,y_center:.84375},{w:1,h:1,x_center:.34375,y_center:.84375},{w:1,h:1,x_center:.34375,y_center:.84375},{w:1,h:1,x_center:.40625,y_center:.84375},{w:1,h:1,x_center:.40625,y_center:.84375},{w:1,h:1,x_center:.46875,y_center:.84375},{w:1,h:1,x_center:.46875,y_center:.84375},{w:1,h:1,x_center:.53125,y_center:.84375},{w:1,h:1,x_center:.53125,y_center:.84375},{w:1,h:1,x_center:.59375,y_center:.84375},{w:1,h:1,x_center:.59375,y_center:.84375},{w:1,h:1,x_center:.65625,y_center:.84375},{w:1,h:1,x_center:.65625,y_center:.84375},{w:1,h:1,x_center:.71875,y_center:.84375},{w:1,h:1,x_center:.71875,y_center:.84375},{w:1,h:1,x_center:.78125,y_center:.84375},{w:1,h:1,x_center:.78125,y_center:.84375},{w:1,h:1,x_center:.84375,y_center:.84375},{w:1,h:1,x_center:.84375,y_center:.84375},{w:1,h:1,x_center:.90625,y_center:.84375},{w:1,h:1,x_center:.90625,y_center:.84375},{w:1,h:1,x_center:.96875,y_center:.84375},{w:1,h:1,x_center:.96875,y_center:.84375},{w:1,h:1,x_center:.03125,y_center:.90625},{w:1,h:1,x_center:.03125,y_center:.90625},{w:1,h:1,x_center:.09375,y_center:.90625},{w:1,h:1,x_center:.09375,y_center:.90625},{w:1,h:1,x_center:.15625,y_center:.90625},{w:1,h:1,x_center:.15625,y_center:.90625},{w:1,h:1,x_center:.21875,y_center:.90625},{w:1,h:1,x_center:.21875,y_center:.90625},{w:1,h:1,x_center:.28125,y_center:.90625},{w:1,h:1,x_center:.28125,y_center:.90625},{w:1,h:1,x_center:.34375,y_center:.90625},{w:1,h:1,x_center:.34375,y_center:.90625},{w:1,h:1,x_center:.40625,y_center:.90625},{w:1,h:1,x_center:.40625,y_center:.90625},{w:1,h:1,x_center:.46875,y_center:.90625},{w:1,h:1,x_center:.46875,y_center:.90625},{w:1,h:1,x_center:.53125,y_center:.90625},{w:1,h:1,x_center:.53125,y_center:.90625},{w:1,h:1,x_center:.59375,y_center:.90625},{w:1,h:1,x_center:.59375,y_center:.90625},{w:1,h:1,x_center:.65625,y_center:.90625},{w:1,h:1,x_center:.65625,y_center:.90625},{w:1,h:1,x_center:.71875,y_center:.90625},{w:1,h:1,x_center:.71875,y_center:.90625},{w:1,h:1,x_center:.78125,y_center:.90625},{w:1,h:1,x_center:.78125,y_center:.90625},{w:1,h:1,x_center:.84375,y_center:.90625},{w:1,h:1,x_center:.84375,y_center:.90625},{w:1,h:1,x_center:.90625,y_center:.90625},{w:1,h:1,x_center:.90625,y_center:.90625},{w:1,h:1,x_center:.96875,y_center:.90625},{w:1,h:1,x_center:.96875,y_center:.90625},{w:1,h:1,x_center:.03125,y_center:.96875},{w:1,h:1,x_center:.03125,y_center:.96875},{w:1,h:1,x_center:.09375,y_center:.96875},{w:1,h:1,x_center:.09375,y_center:.96875},{w:1,h:1,x_center:.15625,y_center:.96875},{w:1,h:1,x_center:.15625,y_center:.96875},{w:1,h:1,x_center:.21875,y_center:.96875},{w:1,h:1,x_center:.21875,y_center:.96875},{w:1,h:1,x_center:.28125,y_center:.96875},{w:1,h:1,x_center:.28125,y_center:.96875},{w:1,h:1,x_center:.34375,y_center:.96875},{w:1,h:1,x_center:.34375,y_center:.96875},{w:1,h:1,x_center:.40625,y_center:.96875},{w:1,h:1,x_center:.40625,y_center:.96875},{w:1,h:1,x_center:.46875,y_center:.96875},{w:1,h:1,x_center:.46875,y_center:.96875},{w:1,h:1,x_center:.53125,y_center:.96875},{w:1,h:1,x_center:.53125,y_center:.96875},{w:1,h:1,x_center:.59375,y_center:.96875},{w:1,h:1,x_center:.59375,y_center:.96875},{w:1,h:1,x_center:.65625,y_center:.96875},{w:1,h:1,x_center:.65625,y_center:.96875},{w:1,h:1,x_center:.71875,y_center:.96875},{w:1,h:1,x_center:.71875,y_center:.96875},{w:1,h:1,x_center:.78125,y_center:.96875},{w:1,h:1,x_center:.78125,y_center:.96875},{w:1,h:1,x_center:.84375,y_center:.96875},{w:1,h:1,x_center:.84375,y_center:.96875},{w:1,h:1,x_center:.90625,y_center:.96875},{w:1,h:1,x_center:.90625,y_center:.96875},{w:1,h:1,x_center:.96875,y_center:.96875},{w:1,h:1,x_center:.96875,y_center:.96875},{w:1,h:1,x_center:.0625,y_center:.0625},{w:1,h:1,x_center:.0625,y_center:.0625},{w:1,h:1,x_center:.0625,y_center:.0625},{w:1,h:1,x_center:.0625,y_center:.0625},{w:1,h:1,x_center:.0625,y_center:.0625},{w:1,h:1,x_center:.0625,y_center:.0625},{w:1,h:1,x_center:.1875,y_center:.0625},{w:1,h:1,x_center:.1875,y_center:.0625},{w:1,h:1,x_center:.1875,y_center:.0625},{w:1,h:1,x_center:.1875,y_center:.0625},{w:1,h:1,x_center:.1875,y_center:.0625},{w:1,h:1,x_center:.1875,y_center:.0625},{w:1,h:1,x_center:.3125,y_center:.0625},{w:1,h:1,x_center:.3125,y_center:.0625},{w:1,h:1,x_center:.3125,y_center:.0625},{w:1,h:1,x_center:.3125,y_center:.0625},{w:1,h:1,x_center:.3125,y_center:.0625},{w:1,h:1,x_center:.3125,y_center:.0625},{w:1,h:1,x_center:.4375,y_center:.0625},{w:1,h:1,x_center:.4375,y_center:.0625},{w:1,h:1,x_center:.4375,y_center:.0625},{w:1,h:1,x_center:.4375,y_center:.0625},{w:1,h:1,x_center:.4375,y_center:.0625},{w:1,h:1,x_center:.4375,y_center:.0625},{w:1,h:1,x_center:.5625,y_center:.0625},{w:1,h:1,x_center:.5625,y_center:.0625},{w:1,h:1,x_center:.5625,y_center:.0625},{w:1,h:1,x_center:.5625,y_center:.0625},{w:1,h:1,x_center:.5625,y_center:.0625},{w:1,h:1,x_center:.5625,y_center:.0625},{w:1,h:1,x_center:.6875,y_center:.0625},{w:1,h:1,x_center:.6875,y_center:.0625},{w:1,h:1,x_center:.6875,y_center:.0625},{w:1,h:1,x_center:.6875,y_center:.0625},{w:1,h:1,x_center:.6875,y_center:.0625},{w:1,h:1,x_center:.6875,y_center:.0625},{w:1,h:1,x_center:.8125,y_center:.0625},{w:1,h:1,x_center:.8125,y_center:.0625},{w:1,h:1,x_center:.8125,y_center:.0625},{w:1,h:1,x_center:.8125,y_center:.0625},{w:1,h:1,x_center:.8125,y_center:.0625},{w:1,h:1,x_center:.8125,y_center:.0625},{w:1,h:1,x_center:.9375,y_center:.0625},{w:1,h:1,x_center:.9375,y_center:.0625},{w:1,h:1,x_center:.9375,y_center:.0625},{w:1,h:1,x_center:.9375,y_center:.0625},{w:1,h:1,x_center:.9375,y_center:.0625},{w:1,h:1,x_center:.9375,y_center:.0625},{w:1,h:1,x_center:.0625,y_center:.1875},{w:1,h:1,x_center:.0625,y_center:.1875},{w:1,h:1,x_center:.0625,y_center:.1875},{w:1,h:1,x_center:.0625,y_center:.1875},{w:1,h:1,x_center:.0625,y_center:.1875},{w:1,h:1,x_center:.0625,y_center:.1875},{w:1,h:1,x_center:.1875,y_center:.1875},{w:1,h:1,x_center:.1875,y_center:.1875},{w:1,h:1,x_center:.1875,y_center:.1875},{w:1,h:1,x_center:.1875,y_center:.1875},{w:1,h:1,x_center:.1875,y_center:.1875},{w:1,h:1,x_center:.1875,y_center:.1875},{w:1,h:1,x_center:.3125,y_center:.1875},{w:1,h:1,x_center:.3125,y_center:.1875},{w:1,h:1,x_center:.3125,y_center:.1875},{w:1,h:1,x_center:.3125,y_center:.1875},{w:1,h:1,x_center:.3125,y_center:.1875},{w:1,h:1,x_center:.3125,y_center:.1875},{w:1,h:1,x_center:.4375,y_center:.1875},{w:1,h:1,x_center:.4375,y_center:.1875},{w:1,h:1,x_center:.4375,y_center:.1875},{w:1,h:1,x_center:.4375,y_center:.1875},{w:1,h:1,x_center:.4375,y_center:.1875},{w:1,h:1,x_center:.4375,y_center:.1875},{w:1,h:1,x_center:.5625,y_center:.1875},{w:1,h:1,x_center:.5625,y_center:.1875},{w:1,h:1,x_center:.5625,y_center:.1875},{w:1,h:1,x_center:.5625,y_center:.1875},{w:1,h:1,x_center:.5625,y_center:.1875},{w:1,h:1,x_center:.5625,y_center:.1875},{w:1,h:1,x_center:.6875,y_center:.1875},{w:1,h:1,x_center:.6875,y_center:.1875},{w:1,h:1,x_center:.6875,y_center:.1875},{w:1,h:1,x_center:.6875,y_center:.1875},{w:1,h:1,x_center:.6875,y_center:.1875},{w:1,h:1,x_center:.6875,y_center:.1875},{w:1,h:1,x_center:.8125,y_center:.1875},{w:1,h:1,x_center:.8125,y_center:.1875},{w:1,h:1,x_center:.8125,y_center:.1875},{w:1,h:1,x_center:.8125,y_center:.1875},{w:1,h:1,x_center:.8125,y_center:.1875},{w:1,h:1,x_center:.8125,y_center:.1875},{w:1,h:1,x_center:.9375,y_center:.1875},{w:1,h:1,x_center:.9375,y_center:.1875},{w:1,h:1,x_center:.9375,y_center:.1875},{w:1,h:1,x_center:.9375,y_center:.1875},{w:1,h:1,x_center:.9375,y_center:.1875},{w:1,h:1,x_center:.9375,y_center:.1875},{w:1,h:1,x_center:.0625,y_center:.3125},{w:1,h:1,x_center:.0625,y_center:.3125},{w:1,h:1,x_center:.0625,y_center:.3125},{w:1,h:1,x_center:.0625,y_center:.3125},{w:1,h:1,x_center:.0625,y_center:.3125},{w:1,h:1,x_center:.0625,y_center:.3125},{w:1,h:1,x_center:.1875,y_center:.3125},{w:1,h:1,x_center:.1875,y_center:.3125},{w:1,h:1,x_center:.1875,y_center:.3125},{w:1,h:1,x_center:.1875,y_center:.3125},{w:1,h:1,x_center:.1875,y_center:.3125},{w:1,h:1,x_center:.1875,y_center:.3125},{w:1,h:1,x_center:.3125,y_center:.3125},{w:1,h:1,x_center:.3125,y_center:.3125},{w:1,h:1,x_center:.3125,y_center:.3125},{w:1,h:1,x_center:.3125,y_center:.3125},{w:1,h:1,x_center:.3125,y_center:.3125},{w:1,h:1,x_center:.3125,y_center:.3125},{w:1,h:1,x_center:.4375,y_center:.3125},{w:1,h:1,x_center:.4375,y_center:.3125},{w:1,h:1,x_center:.4375,y_center:.3125},{w:1,h:1,x_center:.4375,y_center:.3125},{w:1,h:1,x_center:.4375,y_center:.3125},{w:1,h:1,x_center:.4375,y_center:.3125},{w:1,h:1,x_center:.5625,y_center:.3125},{w:1,h:1,x_center:.5625,y_center:.3125},{w:1,h:1,x_center:.5625,y_center:.3125},{w:1,h:1,x_center:.5625,y_center:.3125},{w:1,h:1,x_center:.5625,y_center:.3125},{w:1,h:1,x_center:.5625,y_center:.3125},{w:1,h:1,x_center:.6875,y_center:.3125},{w:1,h:1,x_center:.6875,y_center:.3125},{w:1,h:1,x_center:.6875,y_center:.3125},{w:1,h:1,x_center:.6875,y_center:.3125},{w:1,h:1,x_center:.6875,y_center:.3125},{w:1,h:1,x_center:.6875,y_center:.3125},{w:1,h:1,x_center:.8125,y_center:.3125},{w:1,h:1,x_center:.8125,y_center:.3125},{w:1,h:1,x_center:.8125,y_center:.3125},{w:1,h:1,x_center:.8125,y_center:.3125},{w:1,h:1,x_center:.8125,y_center:.3125},{w:1,h:1,x_center:.8125,y_center:.3125},{w:1,h:1,x_center:.9375,y_center:.3125},{w:1,h:1,x_center:.9375,y_center:.3125},{w:1,h:1,x_center:.9375,y_center:.3125},{w:1,h:1,x_center:.9375,y_center:.3125},{w:1,h:1,x_center:.9375,y_center:.3125},{w:1,h:1,x_center:.9375,y_center:.3125},{w:1,h:1,x_center:.0625,y_center:.4375},{w:1,h:1,x_center:.0625,y_center:.4375},{w:1,h:1,x_center:.0625,y_center:.4375},{w:1,h:1,x_center:.0625,y_center:.4375},{w:1,h:1,x_center:.0625,y_center:.4375},{w:1,h:1,x_center:.0625,y_center:.4375},{w:1,h:1,x_center:.1875,y_center:.4375},{w:1,h:1,x_center:.1875,y_center:.4375},{w:1,h:1,x_center:.1875,y_center:.4375},{w:1,h:1,x_center:.1875,y_center:.4375},{w:1,h:1,x_center:.1875,y_center:.4375},{w:1,h:1,x_center:.1875,y_center:.4375},{w:1,h:1,x_center:.3125,y_center:.4375},{w:1,h:1,x_center:.3125,y_center:.4375},{w:1,h:1,x_center:.3125,y_center:.4375},{w:1,h:1,x_center:.3125,y_center:.4375},{w:1,h:1,x_center:.3125,y_center:.4375},{w:1,h:1,x_center:.3125,y_center:.4375},{w:1,h:1,x_center:.4375,y_center:.4375},{w:1,h:1,x_center:.4375,y_center:.4375},{w:1,h:1,x_center:.4375,y_center:.4375},{w:1,h:1,x_center:.4375,y_center:.4375},{w:1,h:1,x_center:.4375,y_center:.4375},{w:1,h:1,x_center:.4375,y_center:.4375},{w:1,h:1,x_center:.5625,y_center:.4375},{w:1,h:1,x_center:.5625,y_center:.4375},{w:1,h:1,x_center:.5625,y_center:.4375},{w:1,h:1,x_center:.5625,y_center:.4375},{w:1,h:1,x_center:.5625,y_center:.4375},{w:1,h:1,x_center:.5625,y_center:.4375},{w:1,h:1,x_center:.6875,y_center:.4375},{w:1,h:1,x_center:.6875,y_center:.4375},{w:1,h:1,x_center:.6875,y_center:.4375},{w:1,h:1,x_center:.6875,y_center:.4375},{w:1,h:1,x_center:.6875,y_center:.4375},{w:1,h:1,x_center:.6875,y_center:.4375},{w:1,h:1,x_center:.8125,y_center:.4375},{w:1,h:1,x_center:.8125,y_center:.4375},{w:1,h:1,x_center:.8125,y_center:.4375},{w:1,h:1,x_center:.8125,y_center:.4375},{w:1,h:1,x_center:.8125,y_center:.4375},{w:1,h:1,x_center:.8125,y_center:.4375},{w:1,h:1,x_center:.9375,y_center:.4375},{w:1,h:1,x_center:.9375,y_center:.4375},{w:1,h:1,x_center:.9375,y_center:.4375},{w:1,h:1,x_center:.9375,y_center:.4375},{w:1,h:1,x_center:.9375,y_center:.4375},{w:1,h:1,x_center:.9375,y_center:.4375},{w:1,h:1,x_center:.0625,y_center:.5625},{w:1,h:1,x_center:.0625,y_center:.5625},{w:1,h:1,x_center:.0625,y_center:.5625},{w:1,h:1,x_center:.0625,y_center:.5625},{w:1,h:1,x_center:.0625,y_center:.5625},{w:1,h:1,x_center:.0625,y_center:.5625},{w:1,h:1,x_center:.1875,y_center:.5625},{w:1,h:1,x_center:.1875,y_center:.5625},{w:1,h:1,x_center:.1875,y_center:.5625},{w:1,h:1,x_center:.1875,y_center:.5625},{w:1,h:1,x_center:.1875,y_center:.5625},{w:1,h:1,x_center:.1875,y_center:.5625},{w:1,h:1,x_center:.3125,y_center:.5625},{w:1,h:1,x_center:.3125,y_center:.5625},{w:1,h:1,x_center:.3125,y_center:.5625},{w:1,h:1,x_center:.3125,y_center:.5625},{w:1,h:1,x_center:.3125,y_center:.5625},{w:1,h:1,x_center:.3125,y_center:.5625},{w:1,h:1,x_center:.4375,y_center:.5625},{w:1,h:1,x_center:.4375,y_center:.5625},{w:1,h:1,x_center:.4375,y_center:.5625},{w:1,h:1,x_center:.4375,y_center:.5625},{w:1,h:1,x_center:.4375,y_center:.5625},{w:1,h:1,x_center:.4375,y_center:.5625},{w:1,h:1,x_center:.5625,y_center:.5625},{w:1,h:1,x_center:.5625,y_center:.5625},{w:1,h:1,x_center:.5625,y_center:.5625},{w:1,h:1,x_center:.5625,y_center:.5625},{w:1,h:1,x_center:.5625,y_center:.5625},{w:1,h:1,x_center:.5625,y_center:.5625},{w:1,h:1,x_center:.6875,y_center:.5625},{w:1,h:1,x_center:.6875,y_center:.5625},{w:1,h:1,x_center:.6875,y_center:.5625},{w:1,h:1,x_center:.6875,y_center:.5625},{w:1,h:1,x_center:.6875,y_center:.5625},{w:1,h:1,x_center:.6875,y_center:.5625},{w:1,h:1,x_center:.8125,y_center:.5625},{w:1,h:1,x_center:.8125,y_center:.5625},{w:1,h:1,x_center:.8125,y_center:.5625},{w:1,h:1,x_center:.8125,y_center:.5625},{w:1,h:1,x_center:.8125,y_center:.5625},{w:1,h:1,x_center:.8125,y_center:.5625},{w:1,h:1,x_center:.9375,y_center:.5625},{w:1,h:1,x_center:.9375,y_center:.5625},{w:1,h:1,x_center:.9375,y_center:.5625},{w:1,h:1,x_center:.9375,y_center:.5625},{w:1,h:1,x_center:.9375,y_center:.5625},{w:1,h:1,x_center:.9375,y_center:.5625},{w:1,h:1,x_center:.0625,y_center:.6875},{w:1,h:1,x_center:.0625,y_center:.6875},{w:1,h:1,x_center:.0625,y_center:.6875},{w:1,h:1,x_center:.0625,y_center:.6875},{w:1,h:1,x_center:.0625,y_center:.6875},{w:1,h:1,x_center:.0625,y_center:.6875},{w:1,h:1,x_center:.1875,y_center:.6875},{w:1,h:1,x_center:.1875,y_center:.6875},{w:1,h:1,x_center:.1875,y_center:.6875},{w:1,h:1,x_center:.1875,y_center:.6875},{w:1,h:1,x_center:.1875,y_center:.6875},{w:1,h:1,x_center:.1875,y_center:.6875},{w:1,h:1,x_center:.3125,y_center:.6875},{w:1,h:1,x_center:.3125,y_center:.6875},{w:1,h:1,x_center:.3125,y_center:.6875},{w:1,h:1,x_center:.3125,y_center:.6875},{w:1,h:1,x_center:.3125,y_center:.6875},{w:1,h:1,x_center:.3125,y_center:.6875},{w:1,h:1,x_center:.4375,y_center:.6875},{w:1,h:1,x_center:.4375,y_center:.6875},{w:1,h:1,x_center:.4375,y_center:.6875},{w:1,h:1,x_center:.4375,y_center:.6875},{w:1,h:1,x_center:.4375,y_center:.6875},{w:1,h:1,x_center:.4375,y_center:.6875},{w:1,h:1,x_center:.5625,y_center:.6875},{w:1,h:1,x_center:.5625,y_center:.6875},{w:1,h:1,x_center:.5625,y_center:.6875},{w:1,h:1,x_center:.5625,y_center:.6875},{w:1,h:1,x_center:.5625,y_center:.6875},{w:1,h:1,x_center:.5625,y_center:.6875},{w:1,h:1,x_center:.6875,y_center:.6875},{w:1,h:1,x_center:.6875,y_center:.6875},{w:1,h:1,x_center:.6875,y_center:.6875},{w:1,h:1,x_center:.6875,y_center:.6875},{w:1,h:1,x_center:.6875,y_center:.6875},{w:1,h:1,x_center:.6875,y_center:.6875},{w:1,h:1,x_center:.8125,y_center:.6875},{w:1,h:1,x_center:.8125,y_center:.6875},{w:1,h:1,x_center:.8125,y_center:.6875},{w:1,h:1,x_center:.8125,y_center:.6875},{w:1,h:1,x_center:.8125,y_center:.6875},{w:1,h:1,x_center:.8125,y_center:.6875},{w:1,h:1,x_center:.9375,y_center:.6875},{w:1,h:1,x_center:.9375,y_center:.6875},{w:1,h:1,x_center:.9375,y_center:.6875},{w:1,h:1,x_center:.9375,y_center:.6875},{w:1,h:1,x_center:.9375,y_center:.6875},{w:1,h:1,x_center:.9375,y_center:.6875},{w:1,h:1,x_center:.0625,y_center:.8125},{w:1,h:1,x_center:.0625,y_center:.8125},{w:1,h:1,x_center:.0625,y_center:.8125},{w:1,h:1,x_center:.0625,y_center:.8125},{w:1,h:1,x_center:.0625,y_center:.8125},{w:1,h:1,x_center:.0625,y_center:.8125},{w:1,h:1,x_center:.1875,y_center:.8125},{w:1,h:1,x_center:.1875,y_center:.8125},{w:1,h:1,x_center:.1875,y_center:.8125},{w:1,h:1,x_center:.1875,y_center:.8125},{w:1,h:1,x_center:.1875,y_center:.8125},{w:1,h:1,x_center:.1875,y_center:.8125},{w:1,h:1,x_center:.3125,y_center:.8125},{w:1,h:1,x_center:.3125,y_center:.8125},{w:1,h:1,x_center:.3125,y_center:.8125},{w:1,h:1,x_center:.3125,y_center:.8125},{w:1,h:1,x_center:.3125,y_center:.8125},{w:1,h:1,x_center:.3125,y_center:.8125},{w:1,h:1,x_center:.4375,y_center:.8125},{w:1,h:1,x_center:.4375,y_center:.8125},{w:1,h:1,x_center:.4375,y_center:.8125},{w:1,h:1,x_center:.4375,y_center:.8125},{w:1,h:1,x_center:.4375,y_center:.8125},{w:1,h:1,x_center:.4375,y_center:.8125},{w:1,h:1,x_center:.5625,y_center:.8125},{w:1,h:1,x_center:.5625,y_center:.8125},{w:1,h:1,x_center:.5625,y_center:.8125},{w:1,h:1,x_center:.5625,y_center:.8125},{w:1,h:1,x_center:.5625,y_center:.8125},{w:1,h:1,x_center:.5625,y_center:.8125},{w:1,h:1,x_center:.6875,y_center:.8125},{w:1,h:1,x_center:.6875,y_center:.8125},{w:1,h:1,x_center:.6875,y_center:.8125},{w:1,h:1,x_center:.6875,y_center:.8125},{w:1,h:1,x_center:.6875,y_center:.8125},{w:1,h:1,x_center:.6875,y_center:.8125},{w:1,h:1,x_center:.8125,y_center:.8125},{w:1,h:1,x_center:.8125,y_center:.8125},{w:1,h:1,x_center:.8125,y_center:.8125},{w:1,h:1,x_center:.8125,y_center:.8125},{w:1,h:1,x_center:.8125,y_center:.8125},{w:1,h:1,x_center:.8125,y_center:.8125},{w:1,h:1,x_center:.9375,y_center:.8125},{w:1,h:1,x_center:.9375,y_center:.8125},{w:1,h:1,x_center:.9375,y_center:.8125},{w:1,h:1,x_center:.9375,y_center:.8125},{w:1,h:1,x_center:.9375,y_center:.8125},{w:1,h:1,x_center:.9375,y_center:.8125},{w:1,h:1,x_center:.0625,y_center:.9375},{w:1,h:1,x_center:.0625,y_center:.9375},{w:1,h:1,x_center:.0625,y_center:.9375},{w:1,h:1,x_center:.0625,y_center:.9375},{w:1,h:1,x_center:.0625,y_center:.9375},{w:1,h:1,x_center:.0625,y_center:.9375},{w:1,h:1,x_center:.1875,y_center:.9375},{w:1,h:1,x_center:.1875,y_center:.9375},{w:1,h:1,x_center:.1875,y_center:.9375},{w:1,h:1,x_center:.1875,y_center:.9375},{w:1,h:1,x_center:.1875,y_center:.9375},{w:1,h:1,x_center:.1875,y_center:.9375},{w:1,h:1,x_center:.3125,y_center:.9375},{w:1,h:1,x_center:.3125,y_center:.9375},{w:1,h:1,x_center:.3125,y_center:.9375},{w:1,h:1,x_center:.3125,y_center:.9375},{w:1,h:1,x_center:.3125,y_center:.9375},{w:1,h:1,x_center:.3125,y_center:.9375},{w:1,h:1,x_center:.4375,y_center:.9375},{w:1,h:1,x_center:.4375,y_center:.9375},{w:1,h:1,x_center:.4375,y_center:.9375},{w:1,h:1,x_center:.4375,y_center:.9375},{w:1,h:1,x_center:.4375,y_center:.9375},{w:1,h:1,x_center:.4375,y_center:.9375},{w:1,h:1,x_center:.5625,y_center:.9375},{w:1,h:1,x_center:.5625,y_center:.9375},{w:1,h:1,x_center:.5625,y_center:.9375},{w:1,h:1,x_center:.5625,y_center:.9375},{w:1,h:1,x_center:.5625,y_center:.9375},{w:1,h:1,x_center:.5625,y_center:.9375},{w:1,h:1,x_center:.6875,y_center:.9375},{w:1,h:1,x_center:.6875,y_center:.9375},{w:1,h:1,x_center:.6875,y_center:.9375},{w:1,h:1,x_center:.6875,y_center:.9375},{w:1,h:1,x_center:.6875,y_center:.9375},{w:1,h:1,x_center:.6875,y_center:.9375},{w:1,h:1,x_center:.8125,y_center:.9375},{w:1,h:1,x_center:.8125,y_center:.9375},{w:1,h:1,x_center:.8125,y_center:.9375},{w:1,h:1,x_center:.8125,y_center:.9375},{w:1,h:1,x_center:.8125,y_center:.9375},{w:1,h:1,x_center:.8125,y_center:.9375},{w:1,h:1,x_center:.9375,y_center:.9375},{w:1,h:1,x_center:.9375,y_center:.9375},{w:1,h:1,x_center:.9375,y_center:.9375},{w:1,h:1,x_center:.9375,y_center:.9375},{w:1,h:1,x_center:.9375,y_center:.9375},{w:1,h:1,x_center:.9375,y_center:.9375}]});var require_handpose=__commonJS(exports2=>{const handdetector=__toModule(require_handdetector());const pipeline=__toModule(require_handpipeline());const anchors=__toModule(require_anchors());const MESH_ANNOTATIONS={thumb:[1,2,3,4],indexFinger:[5,6,7,8],middleFinger:[9,10,11,12],ringFinger:[13,14,15,16],pinky:[17,18,19,20],palmBase:[0]};class HandPose{constructor(pipe){this.pipeline=pipe}static getAnnotations(){return MESH_ANNOTATIONS}async estimateHands(input,config2){const predictions=await this.pipeline.estimateHands(input,config2);if(!predictions)return[];const hands=[];for(const prediction of predictions){const annotations={};if(prediction.landmarks){for(const key of Object.keys(MESH_ANNOTATIONS)){annotations[key]=MESH_ANNOTATIONS[key].map(index=>prediction.landmarks[index])}}hands.push({confidence:prediction.confidence,box:prediction.box?[prediction.box.topLeft[0],prediction.box.topLeft[1],prediction.box.bottomRight[0]-prediction.box.topLeft[0],prediction.box.bottomRight[1]-prediction.box.topLeft[1]]:0,landmarks:prediction.landmarks,annotations})}return hands}}exports2.HandPose=HandPose;async function load2(config2){const[handDetectorModel,handPoseModel]=await Promise.all([tf.loadGraphModel(config2.detector.modelPath,{fromTFHub:config2.detector.modelPath.includes("tfhub.dev")}),tf.loadGraphModel(config2.skeleton.modelPath,{fromTFHub:config2.skeleton.modelPath.includes("tfhub.dev")})]);const detector=new handdetector.HandDetector(handDetectorModel,config2.inputSize,anchors.anchors);const pipe=new pipeline.HandPipeline(detector,handPoseModel,config2.inputSize);const handpose2=new HandPose(pipe);console.log(`Human: load model: ${config2.detector.modelPath.match(/\/(.*)\./)[1]}`);console.log(`Human: load model: ${config2.skeleton.modelPath.match(/\/(.*)\./)[1]}`);return handpose2}exports2.load=load2});var require_gesture=__commonJS(exports2=>{exports2.body=res=>{if(!res)return[];const gestures=[];for(const pose of res){const leftWrist=pose.keypoints.find(a=>a.part==="leftWrist");const rightWrist=pose.keypoints.find(a=>a.part==="rightWrist");const nose=pose.keypoints.find(a=>a.part==="nose");if(nose&&leftWrist&&rightWrist&&leftWrist.position.ya.part==="leftShoulder");const rightShoulder=pose.keypoints.find(a=>a.part==="rightShoulder");if(leftShoulder&&rightShoulder)gestures.push(`leaning ${leftShoulder.position.y>rightShoulder.position.y?"left":"right"}`)}return gestures};exports2.face=res=>{if(!res)return[];const gestures=[];for(const face2 of res){if(face2.mesh&&face2.mesh.length>0){const eyeFacing=face2.mesh[35][2]-face2.mesh[263][2];if(Math.abs(eyeFacing)<10)gestures.push("facing camera");else gestures.push(`facing ${eyeFacing<0?"right":"left"}`);const openLeft=Math.abs(face2.mesh[374][1]-face2.mesh[386][1])/Math.abs(face2.mesh[443][1]-face2.mesh[450][1]);if(openLeft<.2)gestures.push("blink left eye");const openRight=Math.abs(face2.mesh[145][1]-face2.mesh[159][1])/Math.abs(face2.mesh[223][1]-face2.mesh[230][1]);if(openRight<.2)gestures.push("blink right eye");const mouthOpen=Math.min(100,500*Math.abs(face2.mesh[13][1]-face2.mesh[14][1])/Math.abs(face2.mesh[10][1]-face2.mesh[152][1]));if(mouthOpen>10)gestures.push(`mouth ${Math.trunc(mouthOpen)}% open`);const chinDepth=face2.mesh[152][2];if(Math.abs(chinDepth)>10)gestures.push(`head ${chinDepth<0?"up":"down"}`)}}return gestures};exports2.hand=res=>{if(!res)return[];const gestures=[];for(const hand2 of res){const fingers=[];for(const[finger,pos]of Object.entries(hand2["annotations"])){if(finger!=="palmBase")fingers.push({name:finger.toLowerCase(),position:pos[0]})}if(fingers&&fingers.length>0){const closest=fingers.reduce((best,a)=>best.position[2]best.position[1]{const WebGLProgram=function(gl,vertexSource,fragmentSource){const _collect=function(source,prefix,collection){const r=new RegExp("\\b"+prefix+" \\w+ (\\w+)","ig");source.replace(r,(match,name)=>{collection[name]=0;return match})};const _compile=function(source,type){const shader=gl.createShader(type);gl.shaderSource(shader,source);gl.compileShader(shader);if(!gl.getShaderParameter(shader,gl.COMPILE_STATUS)){throw new Error("Filter: GL compile failed",gl.getShaderInfoLog(shader))}return shader};this.uniform={};this.attribute={};const _vsh=_compile(vertexSource,gl.VERTEX_SHADER);const _fsh=_compile(fragmentSource,gl.FRAGMENT_SHADER);this.id=gl.createProgram();gl.attachShader(this.id,_vsh);gl.attachShader(this.id,_fsh);gl.linkProgram(this.id);if(!gl.getProgramParameter(this.id,gl.LINK_STATUS)){throw new Error("Filter: GL link failed",gl.getProgramInfoLog(this.id))}gl.useProgram(this.id);_collect(vertexSource,"attribute",this.attribute);for(const a in this.attribute){this.attribute[a]=gl.getAttribLocation(this.id,a)}_collect(vertexSource,"uniform",this.uniform);_collect(fragmentSource,"uniform",this.uniform);for(const u in this.uniform){this.uniform[u]=gl.getUniformLocation(this.id,u)}};const WebGLImageFilter=function(params){if(!params)params={};let _drawCount=0;let _sourceTexture=null;let _lastInChain=false;let _currentFramebufferIndex=-1;let _tempFramebuffers=[null,null];let _filterChain=[];let _width=-1;let _height=-1;let _vertexBuffer=null;let _currentProgram=null;const _canvas=params.canvas||document.createElement("canvas");const _shaderProgramCache={};const gl=_canvas.getContext("webgl");if(!gl)throw new Error("Filter: getContext() failed");this.addFilter=function(name){const args=Array.prototype.slice.call(arguments,1);const filter=_filter[name];_filterChain.push({func:filter,args})};this.reset=function(){_filterChain=[]};this.apply=function(image2){_resize(image2.width,image2.height);_drawCount=0;if(!_sourceTexture)_sourceTexture=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,_sourceTexture);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.NEAREST);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,gl.RGBA,gl.UNSIGNED_BYTE,image2);if(_filterChain.length===0){_draw();return _canvas}for(let i=0;i<_filterChain.length;i++){_lastInChain=i===_filterChain.length-1;const f=_filterChain[i];f.func.apply(this,f.args||[])}return _canvas};const _resize=function(width,height){if(width===_width&&height===_height){return}_canvas.width=width;_width=width;_canvas.height=height;_height=height;if(!_vertexBuffer){const vertices=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,-1,1,0,0,1,-1,1,1,1,1,1,0]);_vertexBuffer=gl.createBuffer(),gl.bindBuffer(gl.ARRAY_BUFFER,_vertexBuffer);gl.bufferData(gl.ARRAY_BUFFER,vertices,gl.STATIC_DRAW);gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,true)}gl.viewport(0,0,_width,_height);_tempFramebuffers=[null,null]};const _getTempFramebuffer=function(index){_tempFramebuffers[index]=_tempFramebuffers[index]||_createFramebufferTexture(_width,_height);return _tempFramebuffers[index]};const _createFramebufferTexture=function(width,height){const fbo=gl.createFramebuffer();gl.bindFramebuffer(gl.FRAMEBUFFER,fbo);const renderbuffer=gl.createRenderbuffer();gl.bindRenderbuffer(gl.RENDERBUFFER,renderbuffer);const texture=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,texture);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,width,height,0,gl.RGBA,gl.UNSIGNED_BYTE,null);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.LINEAR);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.LINEAR);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,texture,0);gl.bindTexture(gl.TEXTURE_2D,null);gl.bindFramebuffer(gl.FRAMEBUFFER,null);return{fbo,texture}};const _draw=function(flags){let source=null;let target=null;let flipY=false;if(_drawCount===0){source=_sourceTexture}else{source=_getTempFramebuffer(_currentFramebufferIndex).texture}_drawCount++;if(_lastInChain&&!(flags&DRAW.INTERMEDIATE)){target=null;flipY=_drawCount%2===0}else{_currentFramebufferIndex=(_currentFramebufferIndex+1)%2;target=_getTempFramebuffer(_currentFramebufferIndex).fbo}gl.bindTexture(gl.TEXTURE_2D,source);gl.bindFramebuffer(gl.FRAMEBUFFER,target);gl.uniform1f(_currentProgram.uniform.flipY,flipY?-1:1);gl.drawArrays(gl.TRIANGLES,0,6)};const _compileShader=function(fragmentSource){if(_shaderProgramCache[fragmentSource]){_currentProgram=_shaderProgramCache[fragmentSource];gl.useProgram(_currentProgram.id);return _currentProgram}_currentProgram=new WebGLProgram(gl,SHADER.VERTEX_IDENTITY,fragmentSource);const floatSize=Float32Array.BYTES_PER_ELEMENT;const vertSize=4*floatSize;gl.enableVertexAttribArray(_currentProgram.attribute.pos);gl.vertexAttribPointer(_currentProgram.attribute.pos,2,gl.FLOAT,false,vertSize,0*floatSize);gl.enableVertexAttribArray(_currentProgram.attribute.uv);gl.vertexAttribPointer(_currentProgram.attribute.uv,2,gl.FLOAT,false,vertSize,2*floatSize);_shaderProgramCache[fragmentSource]=_currentProgram;return _currentProgram};let DRAW={INTERMEDIATE:1};let SHADER={};SHADER.VERTEX_IDENTITY=["precision highp float;","attribute vec2 pos;","attribute vec2 uv;","varying vec2 vUv;","uniform float flipY;","void main(void) {","vUv = uv;","gl_Position = vec4(pos.x, pos.y*flipY, 0.0, 1.);","}"].join("\n");SHADER.FRAGMENT_IDENTITY=["precision highp float;","varying vec2 vUv;","uniform sampler2D texture;","void main(void) {","gl_FragColor = texture2D(texture, vUv);","}"].join("\n");let _filter={};_filter.colorMatrix=function(matrix){const m=new Float32Array(matrix);m[4]/=255;m[9]/=255;m[14]/=255;m[19]/=255;const shader=m[18]===1&&m[3]===0&&m[8]===0&&m[13]===0&&m[15]===0&&m[16]===0&&m[17]===0&&m[19]===0?_filter.colorMatrix.SHADER.WITHOUT_ALPHA:_filter.colorMatrix.SHADER.WITH_ALPHA;const program=_compileShader(shader);gl.uniform1fv(program.uniform.m,m);_draw()};_filter.colorMatrix.SHADER={};_filter.colorMatrix.SHADER.WITH_ALPHA=["precision highp float;","varying vec2 vUv;","uniform sampler2D texture;","uniform float m[20];","void main(void) {","vec4 c = texture2D(texture, vUv);","gl_FragColor.r = m[0] * c.r + m[1] * c.g + m[2] * c.b + m[3] * c.a + m[4];","gl_FragColor.g = m[5] * c.r + m[6] * c.g + m[7] * c.b + m[8] * c.a + m[9];","gl_FragColor.b = m[10] * c.r + m[11] * c.g + m[12] * c.b + m[13] * c.a + m[14];","gl_FragColor.a = m[15] * c.r + m[16] * c.g + m[17] * c.b + m[18] * c.a + m[19];","}"].join("\n");_filter.colorMatrix.SHADER.WITHOUT_ALPHA=["precision highp float;","varying vec2 vUv;","uniform sampler2D texture;","uniform float m[20];","void main(void) {","vec4 c = texture2D(texture, vUv);","gl_FragColor.r = m[0] * c.r + m[1] * c.g + m[2] * c.b + m[4];","gl_FragColor.g = m[5] * c.r + m[6] * c.g + m[7] * c.b + m[9];","gl_FragColor.b = m[10] * c.r + m[11] * c.g + m[12] * c.b + m[14];","gl_FragColor.a = c.a;","}"].join("\n");_filter.brightness=function(brightness){const b=(brightness||0)+1;_filter.colorMatrix([b,0,0,0,0,0,b,0,0,0,0,0,b,0,0,0,0,0,1,0])};_filter.saturation=function(amount){const x=(amount||0)*2/3+1;const y=(x-1)*-.5;_filter.colorMatrix([x,y,y,0,0,y,x,y,0,0,y,y,x,0,0,0,0,0,1,0])};_filter.desaturate=function(){_filter.saturation(-1)};_filter.contrast=function(amount){const v=(amount||0)+1;const o=-128*(v-1);_filter.colorMatrix([v,0,0,0,o,0,v,0,0,o,0,0,v,0,o,0,0,0,1,0])};_filter.negative=function(){_filter.contrast(-2)};_filter.hue=function(rotation){rotation=(rotation||0)/180*Math.PI;const cos=Math.cos(rotation);const sin=Math.sin(rotation);const lumR=.213;const lumG=.715;const lumB=.072;_filter.colorMatrix([lumR+cos*(1-lumR)+sin*-lumR,lumG+cos*-lumG+sin*-lumG,lumB+cos*-lumB+sin*(1-lumB),0,0,lumR+cos*-lumR+sin*.143,lumG+cos*(1-lumG)+sin*.14,lumB+cos*-lumB+sin*-.283,0,0,lumR+cos*-lumR+sin*-(1-lumR),lumG+cos*-lumG+sin*lumG,lumB+cos*(1-lumB)+sin*lumB,0,0,0,0,0,1,0])};_filter.desaturateLuminance=function(){_filter.colorMatrix([.2764723,.929708,.0938197,0,-37.1,.2764723,.929708,.0938197,0,-37.1,.2764723,.929708,.0938197,0,-37.1,0,0,0,1,0])};_filter.sepia=function(){_filter.colorMatrix([.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0])};_filter.brownie=function(){_filter.colorMatrix([.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0])};_filter.vintagePinhole=function(){_filter.colorMatrix([.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0])};_filter.kodachrome=function(){_filter.colorMatrix([1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0])};_filter.technicolor=function(){_filter.colorMatrix([1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0])};_filter.polaroid=function(){_filter.colorMatrix([1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0])};_filter.shiftToBGR=function(){_filter.colorMatrix([0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0])};_filter.convolution=function(matrix){const m=new Float32Array(matrix);const pixelSizeX=1/_width;const pixelSizeY=1/_height;const program=_compileShader(_filter.convolution.SHADER);gl.uniform1fv(program.uniform.m,m);gl.uniform2f(program.uniform.px,pixelSizeX,pixelSizeY);_draw()};_filter.convolution.SHADER=["precision highp float;","varying vec2 vUv;","uniform sampler2D texture;","uniform vec2 px;","uniform float m[9];","void main(void) {","vec4 c11 = texture2D(texture, vUv - px);","vec4 c12 = texture2D(texture, vec2(vUv.x, vUv.y - px.y));","vec4 c13 = texture2D(texture, vec2(vUv.x + px.x, vUv.y - px.y));","vec4 c21 = texture2D(texture, vec2(vUv.x - px.x, vUv.y) );","vec4 c22 = texture2D(texture, vUv);","vec4 c23 = texture2D(texture, vec2(vUv.x + px.x, vUv.y) );","vec4 c31 = texture2D(texture, vec2(vUv.x - px.x, vUv.y + px.y) );","vec4 c32 = texture2D(texture, vec2(vUv.x, vUv.y + px.y) );","vec4 c33 = texture2D(texture, vUv + px );","gl_FragColor = ","c11 * m[0] + c12 * m[1] + c22 * m[2] +","c21 * m[3] + c22 * m[4] + c23 * m[5] +","c31 * m[6] + c32 * m[7] + c33 * m[8];","gl_FragColor.a = c22.a;","}"].join("\n");_filter.detectEdges=function(){_filter.convolution.call(this,[0,1,0,1,-4,1,0,1,0])};_filter.sobelX=function(){_filter.convolution.call(this,[-1,0,1,-2,0,2,-1,0,1])};_filter.sobelY=function(){_filter.convolution.call(this,[-1,-2,-1,0,0,0,1,2,1])};_filter.sharpen=function(amount){const a=amount||1;_filter.convolution.call(this,[0,-1*a,0,-1*a,1+4*a,-1*a,0,-1*a,0])};_filter.emboss=function(size){const s=size||1;_filter.convolution.call(this,[-2*s,-1*s,0,-1*s,1,1*s,0,1*s,2*s])};_filter.blur=function(size){const blurSizeX=size/7/_width;const blurSizeY=size/7/_height;const program=_compileShader(_filter.blur.SHADER);gl.uniform2f(program.uniform.px,0,blurSizeY);_draw(DRAW.INTERMEDIATE);gl.uniform2f(program.uniform.px,blurSizeX,0);_draw()};_filter.blur.SHADER=["precision highp float;","varying vec2 vUv;","uniform sampler2D texture;","uniform vec2 px;","void main(void) {","gl_FragColor = vec4(0.0);","gl_FragColor += texture2D(texture, vUv + vec2(-7.0*px.x, -7.0*px.y))*0.0044299121055113265;","gl_FragColor += texture2D(texture, vUv + vec2(-6.0*px.x, -6.0*px.y))*0.00895781211794;","gl_FragColor += texture2D(texture, vUv + vec2(-5.0*px.x, -5.0*px.y))*0.0215963866053;","gl_FragColor += texture2D(texture, vUv + vec2(-4.0*px.x, -4.0*px.y))*0.0443683338718;","gl_FragColor += texture2D(texture, vUv + vec2(-3.0*px.x, -3.0*px.y))*0.0776744219933;","gl_FragColor += texture2D(texture, vUv + vec2(-2.0*px.x, -2.0*px.y))*0.115876621105;","gl_FragColor += texture2D(texture, vUv + vec2(-1.0*px.x, -1.0*px.y))*0.147308056121;","gl_FragColor += texture2D(texture, vUv )*0.159576912161;","gl_FragColor += texture2D(texture, vUv + vec2( 1.0*px.x, 1.0*px.y))*0.147308056121;","gl_FragColor += texture2D(texture, vUv + vec2( 2.0*px.x, 2.0*px.y))*0.115876621105;","gl_FragColor += texture2D(texture, vUv + vec2( 3.0*px.x, 3.0*px.y))*0.0776744219933;","gl_FragColor += texture2D(texture, vUv + vec2( 4.0*px.x, 4.0*px.y))*0.0443683338718;","gl_FragColor += texture2D(texture, vUv + vec2( 5.0*px.x, 5.0*px.y))*0.0215963866053;","gl_FragColor += texture2D(texture, vUv + vec2( 6.0*px.x, 6.0*px.y))*0.00895781211794;","gl_FragColor += texture2D(texture, vUv + vec2( 7.0*px.x, 7.0*px.y))*0.0044299121055113265;","}"].join("\n");_filter.pixelate=function(size){const blurSizeX=size/_width;const blurSizeY=size/_height;const program=_compileShader(_filter.pixelate.SHADER);gl.uniform2f(program.uniform.size,blurSizeX,blurSizeY);_draw()};_filter.pixelate.SHADER=["precision highp float;","varying vec2 vUv;","uniform vec2 size;","uniform sampler2D texture;","vec2 pixelate(vec2 coord, vec2 size) {","return floor( coord / size ) * size;","}","void main(void) {","gl_FragColor = vec4(0.0);","vec2 coord = pixelate(vUv, size);","gl_FragColor += texture2D(texture, coord);","}"].join("\n")};exports2.Canvas=WebGLImageFilter});var require_image=__commonJS(exports2=>{const fxImage=__toModule(require_imagefx());let inCanvas=null;let outCanvas=null;function process3(input,config2){let tensor;if(input instanceof tf.Tensor){tensor=tf.clone(input)}else{const originalWidth=input.naturalWidth||input.videoWidth||input.width||input.shape&&input.shape[1]>0;const originalHeight=input.naturalHeight||input.videoHeight||input.height||input.shape&&input.shape[2]>0;let targetWidth=originalWidth;let targetHeight=originalHeight;if(config2.filter.width>0)targetWidth=config2.filter.width;else if(config2.filter.height>0)targetWidth=originalWidth*(config2.filter.height/originalHeight);if(config2.filter.height>0)targetHeight=config2.filter.height;else if(config2.filter.width>0)targetHeight=originalHeight*(config2.filter.width/originalWidth);if(!inCanvas||inCanvas.width!==targetWidth||inCanvas.height!==targetHeight){inCanvas=typeof OffscreenCanvas!=="undefined"?new OffscreenCanvas(targetWidth,targetHeight):document.createElement("canvas");if(inCanvas.width!==targetWidth)inCanvas.width=targetWidth;if(inCanvas.height!==targetHeight)inCanvas.height=targetHeight}const ctx=inCanvas.getContext("2d");if(input instanceof ImageData)ctx.putImageData(input,0,0);else ctx.drawImage(input,0,0,originalWidth,originalHeight,0,0,inCanvas.width,inCanvas.height);if(config2.filter.enabled){if(!this.fx||!outCanvas||inCanvas.width!==outCanvas.width||inCanvas.height!==outCanvas.height){outCanvas=typeof OffscreenCanvas!=="undefined"?new OffscreenCanvas(inCanvas.width,inCanvas.height):document.createElement("canvas");if(outCanvas.width!==inCanvas.width)outCanvas.width=inCanvas.width;if(outCanvas.height!==inCanvas.height)outCanvas.height=inCanvas.height;this.fx=tf.ENV.flags.IS_BROWSER?new fxImage.Canvas({canvas:outCanvas}):null}this.fx.reset();this.fx.addFilter("brightness",config2.filter.brightness);if(config2.filter.contrast!==0)this.fx.addFilter("contrast",config2.filter.contrast);if(config2.filter.sharpness!==0)this.fx.addFilter("sharpen",config2.filter.sharpness);if(config2.filter.blur!==0)this.fx.addFilter("blur",config2.filter.blur);if(config2.filter.saturation!==0)this.fx.addFilter("saturation",config2.filter.saturation);if(config2.filter.hue!==0)this.fx.addFilter("hue",config2.filter.hue);if(config2.filter.negative)this.fx.addFilter("negative");if(config2.filter.sepia)this.fx.addFilter("sepia");if(config2.filter.vintage)this.fx.addFilter("brownie");if(config2.filter.sepia)this.fx.addFilter("sepia");if(config2.filter.kodachrome)this.fx.addFilter("kodachrome");if(config2.filter.technicolor)this.fx.addFilter("technicolor");if(config2.filter.polaroid)this.fx.addFilter("polaroid");if(config2.filter.pixelate!==0)this.fx.addFilter("pixelate",config2.filter.pixelate);this.fx.apply(inCanvas);const gl=false;if(gl){const glBuffer=new Uint8Array(outCanvas.width*outCanvas.height*4);const pixBuffer=new Uint8Array(outCanvas.width*outCanvas.height*3);gl.readPixels(0,0,outCanvas.width,outCanvas.height,gl.RGBA,gl.UNSIGNED_BYTE,glBuffer);let i=0;for(let y=outCanvas.height-1;y>=0;y--){for(let x=0;xHuman});const version="2.7.0";const tf=__toModule(require_dist());const dist_exports={};__export(dist_exports,{BackendWasm:()=>BackendWasm,setWasmPath:()=>setWasmPath,setWasmPaths:()=>setWasmPaths,version_wasm:()=>version2});const tfjs_core83=__toModule(require_tf_core_node());const tfjs_core=__toModule(require_tf_core_node());var CppDType;(function(CppDType2){CppDType2[CppDType2["float32"]=0]="float32";CppDType2[CppDType2["int32"]=1]="int32";CppDType2[CppDType2["bool"]=2]="bool";CppDType2[CppDType2["string"]=3]="string";CppDType2[CppDType2["complex64"]=4]="complex64"})(CppDType||(CppDType={}));var FusableActivation;(function(FusableActivation2){FusableActivation2[FusableActivation2["linear"]=0]="linear";FusableActivation2[FusableActivation2["relu"]=1]="relu";FusableActivation2[FusableActivation2["relu6"]=2]="relu6";FusableActivation2[FusableActivation2["prelu"]=3]="prelu"})(FusableActivation||(FusableActivation={}));let wasmFusedMatMul;function setup(backend){wasmFusedMatMul=backend.wasm.cwrap(tfjs_core._FusedMatMul,null,["number","array","number","number","array","number","number","number","number","number","number","number"])}function fusedBatchMatMul(args){const{inputs,backend,attrs}=args;const{a,b,bias,preluActivationWeights}=inputs;if(a.dtype!=="float32"||b.dtype!=="float32"){throw new Error(`_FusedMatMul for non non-float32 tensors not yet supported.`)}const{transposeA,transposeB,activation}=attrs;const aId=backend.dataIdMap.get(a.dataId).id;const bId=backend.dataIdMap.get(b.dataId).id;let biasId=0;if(bias!=null){const biasData=backend.dataIdMap.get(bias.dataId);if(biasData.shape.length!==1){throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${biasData.shape.length}.`)}biasId=biasData.id}const preluActivationWeightsId=preluActivationWeights==null?0:backend.dataIdMap.get(preluActivationWeights.dataId).id;const fusedActivation=FusableActivation[activation];if(fusedActivation==null){throw new Error(`${activation} activation not yet supported for FusedConv2D in the wasm backend.`)}const leftDim=transposeA?a.shape[2]:a.shape[1];const rightDim=transposeB?b.shape[1]:b.shape[2];const batchDim=a.shape[0];const out=backend.makeOutput([batchDim,leftDim,rightDim],a.dtype);const outId=backend.dataIdMap.get(out.dataId).id;const aShapeBytes=new Uint8Array(new Int32Array(a.shape).buffer);const bShapeBytes=new Uint8Array(new Int32Array(b.shape).buffer);wasmFusedMatMul(aId,aShapeBytes,a.shape.length,bId,bShapeBytes,b.shape.length,transposeA,transposeB,fusedActivation,biasId,preluActivationWeightsId,outId);return out}const fusedMatMulConfig={kernelName:tfjs_core._FusedMatMul,backendName:"wasm",setupFunc:setup,kernelFunc:fusedBatchMatMul};const tfjs_core3=__toModule(require_tf_core_node());const tfjs_core2=__toModule(require_tf_core_node());function createUnaryKernelConfig(kernelName){let wasmFunc8;function setupFunc2(backend){wasmFunc8=backend.wasm.cwrap(kernelName,null,["number","number"])}function kernelFunc3(args){const{backend,inputs:{x}}=args;const xId=backend.dataIdMap.get(x.dataId).id;const out=backend.makeOutput(x.shape,x.dtype);const outId=backend.dataIdMap.get(out.dataId).id;if(tfjs_core2.util.sizeFromShape(out.shape)===0){return out}wasmFunc8(xId,outId);return out}return{kernelName,backendName:"wasm",setupFunc:setupFunc2,kernelFunc:kernelFunc3}}const absConfig=createUnaryKernelConfig(tfjs_core3.Abs);const tfjs_core5=__toModule(require_tf_core_node());const tfjs_core4=__toModule(require_tf_core_node());function createBinaryKernelConfig(kernelName,supportsFullBroadcast17,dtype){let wasmFunc8;function setupFunc2(backend){wasmFunc8=backend.wasm.cwrap(kernelName,null,["number","array","number","number","array","number","number","number"])}function kernelFunc3(args){const{backend,inputs}=args;const{a,b}=inputs;const aId=backend.dataIdMap.get(a.dataId).id;const bId=backend.dataIdMap.get(b.dataId).id;const outputType=dtype!=null?dtype:a.dtype;const newShape=tfjs_core4.backend_util.assertAndGetBroadcastShape(a.shape,b.shape);const out=backend.makeOutput(newShape,outputType);if(tfjs_core4.util.sizeFromShape(newShape)===0){return out}const aShapeBytes=new Uint8Array(new Int32Array(a.shape).buffer);const bShapeBytes=new Uint8Array(new Int32Array(b.shape).buffer);const outId=backend.dataIdMap.get(out.dataId).id;const kernelFunc4=()=>wasmFunc8(aId,aShapeBytes,a.shape.length,bId,bShapeBytes,b.shape.length,CppDType[a.dtype],outId);if(supportsFullBroadcast17&&a.dtype==="float32"){kernelFunc4();return out}const aBroadcastDims=tfjs_core4.backend_util.getBroadcastDims(a.shape,newShape);const bBroadcastDims=tfjs_core4.backend_util.getBroadcastDims(b.shape,newShape);const loopsOverAllOfA=aBroadcastDims.every((v,i)=>v===i);const loopsOverAllOfB=bBroadcastDims.every((v,i)=>v===i);if(loopsOverAllOfA&&loopsOverAllOfB){kernelFunc4();return out}else{throw new Error(`Broadcasting along outer dims is not yet supported for ${a.dtype} ${kernelName}.`)}}return{kernelName,backendName:"wasm",setupFunc:setupFunc2,kernelFunc:kernelFunc3}}const supportsFullBroadcast=true;const addConfig=createBinaryKernelConfig(tfjs_core5.Add,supportsFullBroadcast);const tfjs_core6=__toModule(require_tf_core_node());let wasmFunc;function setupFunc(backend){wasmFunc=backend.wasm.cwrap(tfjs_core6.AddN,null,["array","number","number","number"])}function addn(args){const{inputs,backend}=args;const out=backend.makeOutput(inputs[0].shape,inputs[0].dtype);if(tfjs_core6.util.sizeFromShape(out.shape)===0){return out}const inputIds=inputs.map(x=>backend.dataIdMap.get(x.dataId).id);const inputIdsBytes=new Uint8Array(new Int32Array(inputIds).buffer);const outId=backend.dataIdMap.get(out.dataId).id;wasmFunc(inputIdsBytes,inputIds.length,CppDType[out.dtype],outId);return out}const addNConfig={kernelName:tfjs_core6.AddN,backendName:"wasm",setupFunc,kernelFunc:addn};const tfjs_core10=__toModule(require_tf_core_node());const tfjs_core9=__toModule(require_tf_core_node());const tfjs_core8=__toModule(require_tf_core_node());const tfjs_core7=__toModule(require_tf_core_node());function identity(args){const{inputs:{x},backend}=args;const out=backend.makeOutput(x.shape,x.dtype);const inVals=backend.typedArrayFromHeap(x);const outVals=backend.typedArrayFromHeap(out);outVals.set(inVals);return out}const identityConfig={kernelName:tfjs_core7.Identity,backendName:"wasm",kernelFunc:identity};let wasmTranspose;function setup2(backend){wasmTranspose=backend.wasm.cwrap(tfjs_core8.Transpose,null,["number","array","number","number","number","array","number"])}function transpose(args){const{inputs,backend,attrs}=args;const[reducedShape,perm]=removeOneSizeDims(inputs.x.shape,attrs.perm);let permIsNoOp=true;for(let i=0;i=i&&(minValIdx===-1||newPerm[minValIdx]>newPerm[j])){minValIdx=j}}newPerm[minValIdx]=i}return[newShape,newPerm]}const transposeConfig={kernelName:tfjs_core8.Transpose,backendName:"wasm",kernelFunc:transpose,setupFunc:setup2};function permuteAxesAndTranspose(x,axis,backend){const xShape=x.shape;const xRank=x.shape.length;const originalAxes=tfjs_core9.util.parseAxisParam(axis,xShape);let axes=originalAxes;const permutedAxes=tfjs_core9.backend_util.getAxesPermutation(axes,xRank);let xTransposed=null;let inputWasTransposed=false;if(permutedAxes!=null){const newShape=new Array(xRank);for(let i=0;i`new shape: ${$shape}, old shape: ${x.shape}. New shape and old shape must have the same number of elements.`);return{dataId:x.dataId,shape:$shape,dtype:x.dtype}}const reshapeConfig={kernelName:tfjs_core12.Reshape,backendName:"wasm",kernelFunc:reshape};let wasmBatchMatMul;function setup5(backend){wasmBatchMatMul=backend.wasm.cwrap(tfjs_core13.BatchMatMul,null,["number","array","number","number","array","number","number","number","number"])}function batchMatMul(args){const{inputs,backend,attrs}=args;const{a,b}=inputs;const{transposeA,transposeB}=attrs;if(a.dtype!=="float32"||b.dtype!=="float32"){throw new Error(`BatchMatMul for non non-float32 tensors not yet supported.`)}const aRank=a.shape.length;const bRank=b.shape.length;const innerShapeA=transposeA?a.shape[aRank-2]:a.shape[aRank-1];const innerShapeB=transposeB?b.shape[bRank-1]:b.shape[bRank-2];const outerShapeA=transposeA?a.shape[aRank-1]:a.shape[aRank-2];const outerShapeB=transposeB?b.shape[bRank-2]:b.shape[bRank-1];const outerDimsA=a.shape.slice(0,-2);const outerDimsB=b.shape.slice(0,-2);const batchDimA=tfjs_core13.util.sizeFromShape(outerDimsA);const batchDimB=tfjs_core13.util.sizeFromShape(outerDimsB);const batchDimsCompatible=batchDimA===batchDimB||batchDimA===1||batchDimB===1;tfjs_core13.util.assert(aRank>=2&&bRank>=2&&batchDimsCompatible,()=>`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 (${outerDimsA}) and (${outerDimsB}).`);const outShapeOuterDims=batchDimA>batchDimB?a.shape.slice(0,-2):b.shape.slice(0,-2);const outShape=outShapeOuterDims.concat([outerShapeA,outerShapeB]);tfjs_core13.util.assert(innerShapeA===innerShapeB,()=>`Error in matMul: inner shapes (${innerShapeA}) and (${innerShapeB}) of Tensors with shapes ${a.shape} and ${b.shape} and transposeA=${transposeA} and transposeB=${transposeB} must match.`);const a3dShape=transposeA?[batchDimA,innerShapeA,outerShapeA]:[batchDimA,outerShapeA,innerShapeA];const b3dShape=transposeB?[batchDimB,outerShapeB,innerShapeB]:[batchDimB,innerShapeB,outerShapeB];const a3d=reshape({inputs:{x:a},backend,attrs:{shape:a3dShape}});const b3d=reshape({inputs:{x:b},backend,attrs:{shape:b3dShape}});const a3dId=backend.dataIdMap.get(a3d.dataId).id;const b3dId=backend.dataIdMap.get(b3d.dataId).id;const leftDim=transposeA?a3d.shape[2]:a3d.shape[1];const rightDim=transposeB?b3d.shape[1]:b3d.shape[2];const batchDim=Math.max(batchDimA,batchDimB);const out=backend.makeOutput([batchDim,leftDim,rightDim],a3d.dtype);const outId=backend.dataIdMap.get(out.dataId).id;const aShapeBytes=new Uint8Array(new Int32Array(a3d.shape).buffer);const bShapeBytes=new Uint8Array(new Int32Array(b3d.shape).buffer);wasmBatchMatMul(a3dId,aShapeBytes,a3d.shape.length,b3dId,bShapeBytes,b3d.shape.length,transposeA,transposeB,outId);out.shape=outShape;return out}const batchMatMulConfig={kernelName:tfjs_core13.BatchMatMul,backendName:"wasm",setupFunc:setup5,kernelFunc:batchMatMul};const tfjs_core14=__toModule(require_tf_core_node());function cast(args){const{inputs:{x},attrs:{dtype},backend}=args;const out=backend.makeOutput(x.shape,dtype);const inVals=backend.typedArrayFromHeap(x);const outVals=backend.typedArrayFromHeap(out);outVals.set(inVals);return out}const castConfig={kernelName:tfjs_core14.Cast,backendName:"wasm",kernelFunc:cast};const tfjs_core15=__toModule(require_tf_core_node());let wasmClip;function setup6(backend){wasmClip=backend.wasm.cwrap(tfjs_core15.ClipByValue,null,["number","number","number","number"])}function clip(args){const{inputs,backend,attrs}=args;const{x}=inputs;const{clipValueMin,clipValueMax}=attrs;const xId=backend.dataIdMap.get(x.dataId).id;const out=backend.makeOutput(x.shape,x.dtype);const outId=backend.dataIdMap.get(out.dataId).id;wasmClip(xId,clipValueMin,clipValueMax,outId);return out}const clipByValueConfig={kernelName:tfjs_core15.ClipByValue,backendName:"wasm",setupFunc:setup6,kernelFunc:clip};const tfjs_core16=__toModule(require_tf_core_node());function concat(args){const{inputs,backend}=args;const axis=tfjs_core16.util.parseAxisParam(args.attrs.axis,inputs[0].shape)[0];const outShape=tfjs_core16.backend_util.computeOutShape(inputs.map(t=>t.shape),axis);const out=backend.makeOutput(outShape,inputs[0].dtype);if(tfjs_core16.util.sizeFromShape(outShape)===0){return out}const $inputs=inputs.filter(t=>tfjs_core16.util.sizeFromShape(t.shape)>0);if($inputs.length===1){return $inputs[0]}const shapes=$inputs.map(t=>t.shape);tfjs_core16.backend_util.assertParamsConsistent(shapes,axis);const batchDim=tfjs_core16.util.sizeFromShape($inputs[0].shape.slice(0,axis));let sumInnerDims=0;const innerDims=$inputs.map(input=>{const innerDim=tfjs_core16.util.sizeFromShape(input.shape.slice(axis));sumInnerDims+=innerDim;return innerDim});const inVals=$inputs.map(input=>backend.typedArrayFromHeap(input));const outVals=backend.typedArrayFromHeap(out);for(let b=0;b`cumsum does not support ${x.dtype} tensors in the WASM backend`);const permutation=tfjs_core21.backend_util.getAxesPermutation([axis],xRank);let permutedX=x;if(permutation!==null){permutedX=transpose({inputs:{x},attrs:{perm:permutation},backend})}const permutedAxis=tfjs_core21.backend_util.getInnerMostAxes(1,xRank)[0];tfjs_core21.backend_util.assertAxesAreInnerMostDims("cumsum",[permutedAxis],xRank);const permutedOut=backend.makeOutput(permutedX.shape,permutedX.dtype);const finalDim=permutedX.shape[permutedAxis];const permutedXId=backend.dataIdMap.get(permutedX.dataId).id;const permutedOutId=backend.dataIdMap.get(permutedOut.dataId).id;wasmCumsum(permutedXId,exclusive?1:0,reverse2?1:0,finalDim,permutedOutId,CppDType[x.dtype]);let out=permutedOut;if(permutation!==null){const undoPermutation=tfjs_core21.backend_util.getUndoAxesPermutation(permutation);out=transpose({inputs:{x:permutedOut},attrs:{perm:undoPermutation},backend});backend.disposeData(permutedX.dataId);backend.disposeData(permutedOut.dataId)}return out}const cumsumConfig={kernelName:tfjs_core21.Cumsum,backendName:"wasm",setupFunc:setup10,kernelFunc:cumsum};const tfjs_core22=__toModule(require_tf_core_node());let wasmDepthToSpace;function setup11(backend){wasmDepthToSpace=backend.wasm.cwrap(tfjs_core22.DepthToSpace,null,["number","number","number","array","number","array","array","number","number"])}function depthToSpace(args){const{backend,inputs,attrs}=args;const{x}=inputs;const{blockSize,dataFormat}=attrs;tfjs_core22.util.assert(blockSize>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${blockSize}`);const batchSize=x.shape[0];const inputHeight=dataFormat==="NHWC"?x.shape[1]:x.shape[2];const inputWidth=dataFormat==="NHWC"?x.shape[2]:x.shape[3];const inputDepth=dataFormat==="NHWC"?x.shape[3]:x.shape[1];const outputHeight=inputHeight*blockSize;const outputWidth=inputWidth*blockSize;const outputDepth=inputDepth/(blockSize*blockSize);const outputShape=dataFormat==="NHWC"?[batchSize,outputHeight,outputWidth,outputDepth]:[batchSize,outputDepth,outputHeight,outputWidth];const out=backend.makeOutput(outputShape,"float32");const xData=backend.dataIdMap.get(x.dataId);const xId=xData.id;const xStridesBytes=new Uint8Array(new Int32Array(tfjs_core22.util.computeStrides(x.shape)).buffer);const outputShapeBytes=new Uint8Array(new Int32Array(outputShape).buffer);const outStridesBytes=new Uint8Array(new Int32Array(tfjs_core22.util.computeStrides(outputShape)).buffer);const outId=backend.dataIdMap.get(out.dataId).id;const channelsLast=dataFormat==="NHWC"?1:0;wasmDepthToSpace(xId,blockSize,channelsLast,xStridesBytes,x.shape.length-1,outputShapeBytes,outStridesBytes,outputShape.length,outId);return out}const depthToSpaceConfig={kernelName:tfjs_core22.DepthToSpace,backendName:"wasm",setupFunc:setup11,kernelFunc:depthToSpace};const tfjs_core23=__toModule(require_tf_core_node());let wasmDepthwiseConv2d;function setup12(backend){wasmDepthwiseConv2d=backend.wasm.cwrap(tfjs_core23.DepthwiseConv2dNative,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function depthwiseConv2d(args){const{inputs,attrs,backend}=args;const{x,filter}=inputs;const xId=backend.dataIdMap.get(x.dataId).id;const filterId=backend.dataIdMap.get(filter.dataId).id;const{strides,dilations,pad:pad2,dimRoundingMode}=attrs;const $dilations=dilations==null?[1,1]:dilations;const convInfo=tfjs_core23.backend_util.computeConv2DInfo(x.shape,filter.shape,strides,$dilations,pad2,dimRoundingMode,true);const filterHeight=convInfo.filterHeight;const filterWidth=convInfo.filterWidth;const padTop=convInfo.padInfo.top;const padRight=convInfo.padInfo.right;const padBottom=convInfo.padInfo.bottom;const padLeft=convInfo.padInfo.left;const dilationHeight=convInfo.dilationHeight;const dilationWidth=convInfo.dilationWidth;const strideHeight=convInfo.strideHeight;const strideWidth=convInfo.strideWidth;const inputChannels=convInfo.inChannels;const outputChannels=convInfo.outChannels;const isSamePad=convInfo.padInfo.type==="SAME"?1:0;if(convInfo.dataFormat!=="channelsLast"){throw new Error(`wasm backend DepthwiseConv2dNative does not support dataFormat:'${convInfo.dataFormat}'. Please use 'channelsLast'.`)}const out=backend.makeOutput(convInfo.outShape,"float32");const outId=backend.dataIdMap.get(out.dataId).id;wasmDepthwiseConv2d(xId,x.shape[0],x.shape[1],x.shape[2],filterId,filterHeight,filterWidth,padTop,padRight,padBottom,padLeft,isSamePad,dilationHeight,dilationWidth,strideHeight,strideWidth,inputChannels,outputChannels,outId);return out}const depthwiseConv2dNativeConfig={kernelName:tfjs_core23.DepthwiseConv2dNative,backendName:"wasm",setupFunc:setup12,kernelFunc:depthwiseConv2d};const tfjs_core24=__toModule(require_tf_core_node());const supportsFullBroadcast2=true;const divConfig=createBinaryKernelConfig(tfjs_core24.Div,supportsFullBroadcast2);const tfjs_core25=__toModule(require_tf_core_node());const supportsFullBroadcast3=false;const equalConfig=createBinaryKernelConfig(tfjs_core25.Equal,supportsFullBroadcast3,"bool");const tfjs_core26=__toModule(require_tf_core_node());const expConfig=createUnaryKernelConfig(tfjs_core26.Exp);const tfjs_core27=__toModule(require_tf_core_node());function fill(args){const{attrs:{shape,value,dtype},backend}=args;const out=backend.makeOutput(shape,dtype);const outVals=backend.typedArrayFromHeap(out);outVals.fill(value);return out}const fillConfig={kernelName:tfjs_core27.Fill,backendName:"wasm",kernelFunc:fill};const tfjs_core28=__toModule(require_tf_core_node());let wasmFlipLeftRight;function setup13(backend){wasmFlipLeftRight=backend.wasm.cwrap(tfjs_core28.FlipLeftRight,null,["number","number","number","number","number","number"])}function flipLeftRight(args){const{inputs,backend}=args;const{image:image2}=inputs;const out=backend.makeOutput(image2.shape,image2.dtype);const imageId=backend.dataIdMap.get(image2.dataId).id;const outId=backend.dataIdMap.get(out.dataId).id;const[batch,imageHeight,imageWidth,numChannels]=image2.shape;wasmFlipLeftRight(imageId,batch,imageHeight,imageWidth,numChannels,outId);return out}const flipLeftRightConfig={kernelName:tfjs_core28.FlipLeftRight,backendName:"wasm",kernelFunc:flipLeftRight,setupFunc:setup13};const tfjs_core29=__toModule(require_tf_core_node());const supportsFullBroadcast4=false;const floorDivConfig=createBinaryKernelConfig(tfjs_core29.FloorDiv,supportsFullBroadcast4);const tfjs_core30=__toModule(require_tf_core_node());let wasmBatchNorm;function setup14(backend){wasmBatchNorm=backend.wasm.cwrap(tfjs_core30.FusedBatchNorm,null,["number","number","number","number","number","number","number"])}function fusedBatchNorm(args){const{backend,inputs,attrs}=args;const{varianceEpsilon}=attrs;const{x,mean,variance,offset,scale}=inputs;const xId=backend.dataIdMap.get(x.dataId).id;const meanId=backend.dataIdMap.get(mean.dataId).id;const varianceId=backend.dataIdMap.get(variance.dataId).id;const offsetId=offset!=null?backend.dataIdMap.get(offset.dataId).id:0;const scaleId=scale!=null?backend.dataIdMap.get(scale.dataId).id:0;const out=backend.makeOutput(x.shape,x.dtype);if(tfjs_core30.util.sizeFromShape(x.shape)===0){return out}const outId=backend.dataIdMap.get(out.dataId).id;wasmBatchNorm(xId,meanId,varianceId,offsetId,scaleId,varianceEpsilon,outId);return out}const fusedBatchNormConfig={kernelName:tfjs_core30.FusedBatchNorm,backendName:"wasm",setupFunc:setup14,kernelFunc:fusedBatchNorm};const tfjs_core31=__toModule(require_tf_core_node());let wasmFusedConv2d;function setup15(backend){wasmFusedConv2d=backend.wasm.cwrap(tfjs_core31.FusedConv2D,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function fusedConv2d(args){const{inputs,attrs,backend}=args;const{x,filter,bias,preluActivationWeights}=inputs;const{strides,pad:pad2,dilations,dataFormat,dimRoundingMode,activation}=attrs;const convInfo=tfjs_core31.backend_util.computeConv2DInfo(x.shape,filter.shape,strides,dilations,pad2,dimRoundingMode);const fusedActivation=FusableActivation[activation];if(fusedActivation==null){throw new Error(`${activation} activation not yet supported for FusedConv2D in the wasm backend.`)}const xId=backend.dataIdMap.get(x.dataId).id;const filterId=backend.dataIdMap.get(filter.dataId).id;const outputChannels=convInfo.outChannels;let biasId=0;if(bias!=null){const biasData=backend.dataIdMap.get(bias.dataId);if(biasData.shape.length!==1){throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${biasData.shape.length}.`)}if(biasData.shape[0]!==outputChannels){throw new Error(`FusedConv2D bias shape (${biasData.shape}) does not match the number of output channels (${outputChannels})`)}biasId=biasData.id}const filterHeight=convInfo.filterHeight;const filterWidth=convInfo.filterWidth;const padTop=convInfo.padInfo.top;const padRight=convInfo.padInfo.right;const padBottom=convInfo.padInfo.bottom;const padLeft=convInfo.padInfo.left;const dilationHeight=convInfo.dilationHeight;const dilationWidth=convInfo.dilationWidth;const strideHeight=convInfo.strideHeight;const strideWidth=convInfo.strideWidth;const inputChannels=convInfo.inChannels;const isSamePad=convInfo.padInfo.type==="SAME"?1:0;const batchSize=convInfo.batchSize;const inHeight=convInfo.inHeight;const inWidth=convInfo.inWidth;if(dataFormat!=="NHWC"){throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${dataFormat}'. Please use 'NHWC'.`)}const out=backend.makeOutput(convInfo.outShape,"float32");const outId=backend.dataIdMap.get(out.dataId).id;const preluActivationWeightsId=preluActivationWeights==null?0:backend.dataIdMap.get(preluActivationWeights.dataId).id;wasmFusedConv2d(xId,batchSize,inHeight,inWidth,filterId,filterHeight,filterWidth,biasId,padTop,padRight,padBottom,padLeft,isSamePad,dilationHeight,dilationWidth,strideHeight,strideWidth,inputChannels,outputChannels,fusedActivation,preluActivationWeightsId,outId);return out}const fusedConv2DConfig={kernelName:tfjs_core31.FusedConv2D,backendName:"wasm",setupFunc:setup15,kernelFunc:fusedConv2d};const tfjs_core32=__toModule(require_tf_core_node());let wasmFusedDepthwiseConv2d;function setup16(backend){wasmFusedDepthwiseConv2d=backend.wasm.cwrap(tfjs_core32.FusedDepthwiseConv2D,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function fusedDepthwiseConv2d(args){const{inputs,attrs,backend}=args;const{x,filter,bias,preluActivationWeights}=inputs;const{strides,pad:pad2,dilations,dataFormat,dimRoundingMode,activation}=attrs;const convInfo=tfjs_core32.backend_util.computeConv2DInfo(x.shape,filter.shape,strides,dilations,pad2,dimRoundingMode,true);const fusedActivation=FusableActivation[activation];if(fusedActivation==null){throw new Error(`${activation} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`)}const xId=backend.dataIdMap.get(x.dataId).id;const filterId=backend.dataIdMap.get(filter.dataId).id;const outputChannels=convInfo.outChannels;let biasId=0;if(bias!=null){const biasData=backend.dataIdMap.get(bias.dataId);if(biasData.shape.length!==1){throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${biasData.shape.length}.`)}if(biasData.shape[0]!==outputChannels){throw new Error(`FusedDepthwiseConv2D bias shape (${biasData.shape}) does not match the number of output channels (${outputChannels})`)}biasId=biasData.id}const filterHeight=convInfo.filterHeight;const filterWidth=convInfo.filterWidth;const padTop=convInfo.padInfo.top;const padRight=convInfo.padInfo.right;const padBottom=convInfo.padInfo.bottom;const padLeft=convInfo.padInfo.left;const dilationHeight=convInfo.dilationHeight;const dilationWidth=convInfo.dilationWidth;const strideHeight=convInfo.strideHeight;const strideWidth=convInfo.strideWidth;const inputChannels=convInfo.inChannels;const isSamePad=convInfo.padInfo.type==="SAME"?1:0;const batchSize=convInfo.batchSize;const inHeight=convInfo.inHeight;const inWidth=convInfo.inWidth;if(dataFormat!=="NHWC"){throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${dataFormat}'. Please use 'NHWC'.`)}const out=backend.makeOutput(convInfo.outShape,"float32");const outId=backend.dataIdMap.get(out.dataId).id;const preluActivationWeightsId=preluActivationWeights==null?0:backend.dataIdMap.get(preluActivationWeights.dataId).id;wasmFusedDepthwiseConv2d(xId,batchSize,inHeight,inWidth,filterId,filterHeight,filterWidth,biasId,padTop,padRight,padBottom,padLeft,isSamePad,dilationHeight,dilationWidth,strideHeight,strideWidth,inputChannels,outputChannels,fusedActivation,preluActivationWeightsId,outId);return out}const fusedDepthwiseConv2DConfig={kernelName:tfjs_core32.FusedDepthwiseConv2D,backendName:"wasm",setupFunc:setup16,kernelFunc:fusedDepthwiseConv2d};const tfjs_core33=__toModule(require_tf_core_node());let wasmGatherNd;function setup17(backend){wasmGatherNd=backend.wasm.cwrap(tfjs_core33.GatherNd,null,["number","number","number","number","number","number","array","number"])}function gatherNd(args){const{backend,inputs}=args;const{params,indices}=inputs;const[resultShape,numSlices,sliceSize,strides]=tfjs_core33.gather_util.prepareAndValidate(params,indices);const out=backend.makeOutput(resultShape,params.dtype);if(numSlices===0){return out}const indicesShape=indices.shape;const sliceRank=indicesShape[indicesShape.length-1];const xData=backend.dataIdMap.get(params.dataId);const xId=xData.id;const indicesData=backend.dataIdMap.get(indices.dataId);const indicesId=indicesData.id;const stridesBytes=new Uint8Array(new Int32Array(strides).buffer);const outId=backend.dataIdMap.get(out.dataId).id;wasmGatherNd(xId,CppDType[params.dtype],indicesId,numSlices,sliceRank,sliceSize,stridesBytes,outId);return out}const gatherNdConfig={kernelName:tfjs_core33.GatherNd,backendName:"wasm",setupFunc:setup17,kernelFunc:gatherNd};const tfjs_core34=__toModule(require_tf_core_node());let wasmGather;function setup18(backend){wasmGather=backend.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])}function gatherV2(args){const{backend,inputs,attrs}=args;const{x,indices}=inputs;const{axis}=attrs;const newShape=x.shape.slice();newShape[axis]=tfjs_core34.util.sizeFromShape(indices.shape);const stridesSize=x.shape.length-1;const out=backend.makeOutput(newShape,x.dtype);if(tfjs_core34.util.sizeFromShape(x.shape)===0){return out}const xData=backend.dataIdMap.get(x.dataId);const xId=xData.id;const indicesData=backend.dataIdMap.get(indices.dataId);const indicesId=indicesData.id;const outId=backend.dataIdMap.get(out.dataId).id;const xStridesBytes=new Uint8Array(new Int32Array(tfjs_core34.util.computeStrides(x.shape)).buffer);const outStridesBytes=new Uint8Array(new Int32Array(tfjs_core34.util.computeStrides(newShape)).buffer);wasmGather(xId,CppDType[x.dtype],xStridesBytes,stridesSize,indicesId,axis,outStridesBytes,outId);const parsedAxis=tfjs_core34.util.parseAxisParam(axis,x.shape)[0];const shapeInfo=tfjs_core34.backend_util.segment_util.collectGatherOpShapeInfo(x,indices,parsedAxis);out.shape=shapeInfo.outputShape;return out}const gatherV2Config={kernelName:tfjs_core34.GatherV2,backendName:"wasm",setupFunc:setup18,kernelFunc:gatherV2};const tfjs_core35=__toModule(require_tf_core_node());const supportsFullBroadcast5=false;const greaterConfig=createBinaryKernelConfig(tfjs_core35.Greater,supportsFullBroadcast5,"bool");const tfjs_core36=__toModule(require_tf_core_node());const supportsFullBroadcast6=false;const greaterEqualConfig=createBinaryKernelConfig(tfjs_core36.GreaterEqual,supportsFullBroadcast6,"bool");const tfjs_core37=__toModule(require_tf_core_node());const supportsFullBroadcast7=false;const lessConfig=createBinaryKernelConfig(tfjs_core37.Less,supportsFullBroadcast7,"bool");const tfjs_core38=__toModule(require_tf_core_node());const supportsFullBroadcast8=false;const lessEqualConfig=createBinaryKernelConfig(tfjs_core38.LessEqual,supportsFullBroadcast8,"bool");const tfjs_core39=__toModule(require_tf_core_node());const logConfig=createUnaryKernelConfig(tfjs_core39.Log);const tfjs_core40=__toModule(require_tf_core_node());const supportsFullBroadcast9=false;const logicalAndConfig=createBinaryKernelConfig(tfjs_core40.LogicalAnd,supportsFullBroadcast9,"bool");const tfjs_core41=__toModule(require_tf_core_node());const tfjs_core42=__toModule(require_tf_core_node());let wasmMax;function setup19(backend){wasmMax=backend.wasm.cwrap(tfjs_core42.Max,null,["number, number, number"])}function max(args){const{backend,inputs,attrs}=args;const{reductionIndices:axis,keepDims}=attrs;const{x}=inputs;const xId=backend.dataIdMap.get(x.dataId).id;let inputId=xId;let input=x;const{transposed,axes,originalAxes,inputWasTransposed}=permuteAxesAndTranspose(x,axis,backend);if(inputWasTransposed){const transposedId=backend.dataIdMap.get(transposed.dataId).id;input=transposed;inputId=transposedId}const inputRank=input.shape.length;tfjs_core41.backend_util.assertAxesAreInnerMostDims("max",axes,inputRank);const[outShape,reduceShape]=tfjs_core41.backend_util.computeOutAndReduceShapes(input.shape,axes);const reduceSize=tfjs_core41.util.sizeFromShape(reduceShape);const out=backend.makeOutput(outShape,x.dtype);if(tfjs_core41.util.sizeFromShape(input.shape)!==0){const outId=backend.dataIdMap.get(out.dataId).id;wasmMax(inputId,reduceSize,outId)}if(inputWasTransposed){backend.disposeData(transposed.dataId)}if(keepDims){const newShape=tfjs_core41.backend_util.expandShapeToKeepDim(out.shape,originalAxes);out.shape=newShape}return out}const maxConfig={kernelName:tfjs_core42.Max,backendName:"wasm",setupFunc:setup19,kernelFunc:max};const tfjs_core43=__toModule(require_tf_core_node());const supportsFullBroadcast10=false;const maximumConfig=createBinaryKernelConfig(tfjs_core43.Maximum,supportsFullBroadcast10);const tfjs_core44=__toModule(require_tf_core_node());let wasmMaxPool;function setup20(backend){wasmMaxPool=backend.wasm.cwrap(tfjs_core44.MaxPool,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function maxPool(args){const{inputs,attrs,backend}=args;const x=inputs.x;const xId=backend.dataIdMap.get(x.dataId).id;const{filterSize,strides,pad:pad2,dimRoundingMode}=attrs;const convInfo=tfjs_core44.backend_util.computePool2DInfo(x.shape,filterSize,strides,1,pad2,dimRoundingMode);const filterHeight=convInfo.filterHeight;const filterWidth=convInfo.filterWidth;const padTop=convInfo.padInfo.top;const padRight=convInfo.padInfo.right;const padBottom=convInfo.padInfo.bottom;const padLeft=convInfo.padInfo.left;const dilationHeight=convInfo.dilationHeight;const dilationWidth=convInfo.dilationWidth;const strideHeight=convInfo.strideHeight;const strideWidth=convInfo.strideWidth;const inputChannels=convInfo.inChannels;const outputChannels=convInfo.outChannels;if(convInfo.dataFormat!=="channelsLast"){throw new Error(`wasm backend does not support dataFormat:'${convInfo.dataFormat}'. Please use 'channelsLast'.`)}const out=backend.makeOutput(convInfo.outShape,"float32");const outId=backend.dataIdMap.get(out.dataId).id;wasmMaxPool(xId,x.shape[0],x.shape[1],x.shape[2],filterHeight,filterWidth,padTop,padRight,padBottom,padLeft,dilationHeight,dilationWidth,strideHeight,strideWidth,inputChannels,outputChannels,outId);return out}const maxPoolConfig={kernelName:tfjs_core44.MaxPool,backendName:"wasm",setupFunc:setup20,kernelFunc:maxPool};const tfjs_core45=__toModule(require_tf_core_node());let wasmMin;function setup21(backend){wasmMin=backend.wasm.cwrap(tfjs_core45.Min,null,["number, number, number"])}function min(args){const{backend,inputs,attrs}=args;const{axis,keepDims}=attrs;const{x}=inputs;const xId=backend.dataIdMap.get(x.dataId).id;let inputId=xId;let input=x;const{transposed,axes,originalAxes,inputWasTransposed}=permuteAxesAndTranspose(x,axis,backend);if(inputWasTransposed){const transposedId=backend.dataIdMap.get(transposed.dataId).id;if(transposedId!==xId){input=transposed;inputId=transposedId}}const inputRank=input.shape.length;tfjs_core45.backend_util.assertAxesAreInnerMostDims("min",axes,inputRank);const[outShape,reduceShape]=tfjs_core45.backend_util.computeOutAndReduceShapes(input.shape,axes);const reduceSize=tfjs_core45.util.sizeFromShape(reduceShape);const out=backend.makeOutput(outShape,input.dtype);if(tfjs_core45.util.sizeFromShape(input.shape)!==0){const outId=backend.dataIdMap.get(out.dataId).id;wasmMin(inputId,reduceSize,outId)}if(inputWasTransposed){backend.disposeData(transposed.dataId)}if(keepDims){const newShape=tfjs_core45.backend_util.expandShapeToKeepDim(out.shape,originalAxes);out.shape=newShape}return out}const minConfig={kernelName:tfjs_core45.Min,backendName:"wasm",setupFunc:setup21,kernelFunc:min};const tfjs_core46=__toModule(require_tf_core_node());const supportsFullBroadcast11=false;const minimumConfig=createBinaryKernelConfig(tfjs_core46.Minimum,supportsFullBroadcast11);const tfjs_core47=__toModule(require_tf_core_node());const supportsFullBroadcast12=true;const multiplyConfig=createBinaryKernelConfig(tfjs_core47.Multiply,supportsFullBroadcast12);const tfjs_core48=__toModule(require_tf_core_node());const negateConfig=createUnaryKernelConfig(tfjs_core48.Negate);const tfjs_core49=__toModule(require_tf_core_node());function parseResultStruct(backend,resOffset){const result=new Int32Array(backend.wasm.HEAPU8.buffer,resOffset,4);const pSelectedIndices=result[0];const selectedSize=result[1];const pSelectedScores=result[2];const pValidOutputs=result[3];backend.wasm._free(resOffset);return{pSelectedIndices,selectedSize,pSelectedScores,pValidOutputs}}let wasmFunc3;function setup22(backend){wasmFunc3=backend.wasm.cwrap(tfjs_core49.NonMaxSuppressionV3,"number",["number","number","number","number","number"])}function kernelFunc(args){const{backend,inputs,attrs}=args;const{iouThreshold,maxOutputSize,scoreThreshold}=attrs;const{boxes,scores}=inputs;const boxesId=backend.dataIdMap.get(boxes.dataId).id;const scoresId=backend.dataIdMap.get(scores.dataId).id;const resOffset=wasmFunc3(boxesId,scoresId,maxOutputSize,iouThreshold,scoreThreshold);const{pSelectedIndices,selectedSize,pSelectedScores,pValidOutputs}=parseResultStruct(backend,resOffset);backend.wasm._free(pSelectedScores);backend.wasm._free(pValidOutputs);const selectedIndicesTensor=backend.makeOutput([selectedSize],"int32",pSelectedIndices);return selectedIndicesTensor}const nonMaxSuppressionV3Config={kernelName:tfjs_core49.NonMaxSuppressionV3,backendName:"wasm",setupFunc:setup22,kernelFunc};const tfjs_core50=__toModule(require_tf_core_node());let wasmFunc4;function setup23(backend){wasmFunc4=backend.wasm.cwrap(tfjs_core50.NonMaxSuppressionV4,"number",["number","number","number","number","number","bool"])}function nonMaxSuppressionV4(args){const{backend,inputs,attrs}=args;const{iouThreshold,maxOutputSize,scoreThreshold,padToMaxOutputSize}=attrs;const{boxes,scores}=inputs;const boxesId=backend.dataIdMap.get(boxes.dataId).id;const scoresId=backend.dataIdMap.get(scores.dataId).id;const resOffset=wasmFunc4(boxesId,scoresId,maxOutputSize,iouThreshold,scoreThreshold,padToMaxOutputSize);const{pSelectedIndices,selectedSize,pSelectedScores,pValidOutputs}=parseResultStruct(backend,resOffset);backend.wasm._free(pSelectedScores);const selectedIndicesTensor=backend.makeOutput([selectedSize],"int32",pSelectedIndices);const validOutputsTensor=backend.makeOutput([],"int32",pValidOutputs);return[selectedIndicesTensor,validOutputsTensor]}const nonMaxSuppressionV4Config={kernelName:tfjs_core50.NonMaxSuppressionV4,backendName:"wasm",setupFunc:setup23,kernelFunc:nonMaxSuppressionV4};const tfjs_core51=__toModule(require_tf_core_node());let wasmFunc5;function setup24(backend){wasmFunc5=backend.wasm.cwrap(tfjs_core51.NonMaxSuppressionV5,"number",["number","number","number","number","number","number"])}function kernelFunc2(args){const{backend,inputs,attrs}=args;const{iouThreshold,maxOutputSize,scoreThreshold,softNmsSigma}=attrs;const{boxes,scores}=inputs;const boxesId=backend.dataIdMap.get(boxes.dataId).id;const scoresId=backend.dataIdMap.get(scores.dataId).id;const resOffset=wasmFunc5(boxesId,scoresId,maxOutputSize,iouThreshold,scoreThreshold,softNmsSigma);const{pSelectedIndices,selectedSize,pSelectedScores,pValidOutputs}=parseResultStruct(backend,resOffset);backend.wasm._free(pValidOutputs);const selectedIndicesTensor=backend.makeOutput([selectedSize],"int32",pSelectedIndices);const selectedScoresTensor=backend.makeOutput([selectedSize],"float32",pSelectedScores);return[selectedIndicesTensor,selectedScoresTensor]}const nonMaxSuppressionV5Config={kernelName:tfjs_core51.NonMaxSuppressionV5,backendName:"wasm",setupFunc:setup24,kernelFunc:kernelFunc2};const tfjs_core52=__toModule(require_tf_core_node());const supportsFullBroadcast13=false;const notEqualConfig=createBinaryKernelConfig(tfjs_core52.NotEqual,supportsFullBroadcast13,"bool");const tfjs_core53=__toModule(require_tf_core_node());let wasmOneHot;function setup25(backend){wasmOneHot=backend.wasm.cwrap(tfjs_core53.OneHot,null,["number","number","number","number","number"])}function oneHot(args){const{inputs,backend,attrs}=args;const{indices}=inputs;const{depth,onValue,offValue}=attrs;const out=backend.makeOutput([...indices.shape,depth],"int32");const outId=backend.dataIdMap.get(out.dataId).id;const indicesData=backend.dataIdMap.get(indices.dataId);const indicesId=indicesData.id;wasmOneHot(indicesId,depth,onValue,offValue,outId);return out}const oneHotConfig={kernelName:tfjs_core53.OneHot,backendName:"wasm",setupFunc:setup25,kernelFunc:oneHot};const tfjs_core54=__toModule(require_tf_core_node());function onesLike(args){const{inputs:{x},backend}=args;const out=backend.makeOutput(x.shape,x.dtype);const outVals=backend.typedArrayFromHeap(out);outVals.fill(1);return out}const onesLikeConfig={kernelName:tfjs_core54.OnesLike,backendName:"wasm",kernelFunc:onesLike};const tfjs_core55=__toModule(require_tf_core_node());let wasmPadV2;function setup26(backend){wasmPadV2=backend.wasm.cwrap(tfjs_core55.PadV2,null,["number","array","number","number","array","array","number","number"])}function pad(args){const{inputs:{x},backend,attrs:{paddings,constantValue}}=args;const outShape=paddings.map((p,i)=>p[0]+x.shape[i]+p[1]);const xId=backend.dataIdMap.get(x.dataId).id;const out=backend.makeOutput(outShape,x.dtype);const outId=backend.dataIdMap.get(out.dataId).id;const xShapeBytes=new Uint8Array(new Int32Array(x.shape).buffer);const prePaddingsFlat=paddings.map(padTuple=>padTuple[0]);const postPaddingsFlat=paddings.map(padTuple=>padTuple[1]);const prePaddingsBytes=new Uint8Array(new Int32Array(prePaddingsFlat).buffer);const postPaddingsBytes=new Uint8Array(new Int32Array(postPaddingsFlat).buffer);wasmPadV2(xId,xShapeBytes,x.shape.length,CppDType[x.dtype],prePaddingsBytes,postPaddingsBytes,constantValue,outId);return out}const padV2Config={kernelName:tfjs_core55.PadV2,backendName:"wasm",kernelFunc:pad,setupFunc:setup26};const tfjs_core56=__toModule(require_tf_core_node());const supportsFullBroadcast14=false;const powConfig=createBinaryKernelConfig(tfjs_core56.Pow,supportsFullBroadcast14);const tfjs_core57=__toModule(require_tf_core_node());let wasmPrelu;function setup27(backend){wasmPrelu=backend.wasm.cwrap(tfjs_core57.Prelu,null,["number","number","number"])}function prelu(args){const{inputs,backend}=args;const{x,alpha}=inputs;const xId=backend.dataIdMap.get(x.dataId).id;const weightsId=backend.dataIdMap.get(alpha.dataId).id;const out=backend.makeOutput(x.shape,"float32");const outId=backend.dataIdMap.get(out.dataId).id;wasmPrelu(xId,weightsId,outId);return out}const preluConfig={kernelName:tfjs_core57.Prelu,backendName:"wasm",setupFunc:setup27,kernelFunc:prelu};const tfjs_core58=__toModule(require_tf_core_node());const reluConfig=createUnaryKernelConfig(tfjs_core58.Relu);const tfjs_core59=__toModule(require_tf_core_node());const relu6Config=createUnaryKernelConfig(tfjs_core59.Relu6);const tfjs_core60=__toModule(require_tf_core_node());let wasmResizeBilinear;function setup28(backend){wasmResizeBilinear=backend.wasm.cwrap(tfjs_core60.ResizeBilinear,null,["number","number","number","number","number","number","number","number","number"])}function resizeBilinear(args){const{backend,inputs,attrs}=args;const{images}=inputs;const{alignCorners,size}=attrs;const[newHeight,newWidth]=size;const[batch,oldHeight,oldWidth,numChannels]=images.shape;const outShape=[batch,newHeight,newWidth,numChannels];let xData=backend.dataIdMap.get(images.dataId);let castedData;if(xData.dtype!=="float32"){castedData=cast({backend,inputs:{x:images},attrs:{dtype:"float32"}});xData=backend.dataIdMap.get(castedData.dataId)}const xId=xData.id;const out=backend.makeOutput(outShape,"float32");if(tfjs_core60.util.sizeFromShape(images.shape)===0){return out}const outId=backend.dataIdMap.get(out.dataId).id;wasmResizeBilinear(xId,batch,oldHeight,oldWidth,numChannels,newHeight,newWidth,alignCorners?1:0,outId);if(castedData!=null){backend.disposeData(castedData.dataId)}return out}const resizeBilinearConfig={kernelName:tfjs_core60.ResizeBilinear,backendName:"wasm",setupFunc:setup28,kernelFunc:resizeBilinear};const tfjs_core61=__toModule(require_tf_core_node());let wasmReverse;function setup29(backend){wasmReverse=backend.wasm.cwrap(tfjs_core61.Reverse,null,["number","array","number","array","number","number"])}function reverse(args){const{inputs,backend,attrs}=args;const{x}=inputs;const{dims}=attrs;const axes=tfjs_core61.util.parseAxisParam(dims,x.shape);if(x.shape.length===0){return identity({inputs:{x},backend})}const out=backend.makeOutput(x.shape,x.dtype);const xId=backend.dataIdMap.get(x.dataId).id;const outId=backend.dataIdMap.get(out.dataId).id;const axesBytes=new Uint8Array(new Int32Array(axes).buffer);const outShapeBytes=new Uint8Array(new Int32Array(x.shape).buffer);wasmReverse(xId,axesBytes,axes.length,outShapeBytes,x.shape.length,outId);return reshape({inputs:{x:out},attrs:{shape:x.shape},backend})}const reverseConfig={kernelName:tfjs_core61.Reverse,backendName:"wasm",kernelFunc:reverse,setupFunc:setup29};const tfjs_core62=__toModule(require_tf_core_node());const tfjs_core63=__toModule(require_tf_core_node());let wasmRotate;function setup30(backend){wasmRotate=backend.wasm.cwrap(tfjs_core62.RotateWithOffset,null,["number","number","number","number","number","number","number","number","array","number","number"])}function rotateWithOffset(args){const{inputs,backend,attrs}=args;const{image:image2}=inputs;const{radians,fillValue,center}=attrs;const out=backend.makeOutput(image2.shape,image2.dtype);const imageId=backend.dataIdMap.get(image2.dataId).id;const outId=backend.dataIdMap.get(out.dataId).id;const[batch,imageHeight,imageWidth,numChannels]=image2.shape;const[centerX,centerY]=tfjs_core63.backend_util.getImageCenter(center,imageHeight,imageWidth);const fillIsBlack=fillValue===0;const fullOpacityValue=255;const fillValues=typeof fillValue==="number"?[fillValue,fillValue,fillValue,fillIsBlack?0:fullOpacityValue]:[...fillValue,fullOpacityValue];const fillBytes=new Uint8Array(new Int32Array(fillValues).buffer);wasmRotate(imageId,batch,imageHeight,imageWidth,numChannels,radians,centerX,centerY,fillBytes,fillValues.length,outId);return out}const rotateWithOffsetConfig={kernelName:tfjs_core62.RotateWithOffset,backendName:"wasm",kernelFunc:rotateWithOffset,setupFunc:setup30};const tfjs_core64=__toModule(require_tf_core_node());const rsqrtConfig=createUnaryKernelConfig(tfjs_core64.Rsqrt);const tfjs_core65=__toModule(require_tf_core_node());let wasmScatterNd;function setup31(backend){wasmScatterNd=backend.wasm.cwrap(tfjs_core65.ScatterNd,null,["number","number","number","number","number","number","array","number","number"])}function scatterNd(args){const{backend,inputs,attrs}=args;const{indices,updates}=inputs;const{shape}=attrs;const out=backend.makeOutput(shape,updates.dtype);if(tfjs_core65.util.sizeFromShape(shape)===0){return out}const{sliceRank,numUpdates,sliceSize,strides,outputSize}=tfjs_core65.scatter_util.calculateShapes(updates,indices,shape);const indicesData=backend.dataIdMap.get(indices.dataId);const indicesId=indicesData.id;const updatesData=backend.dataIdMap.get(updates.dataId);const updatesId=updatesData.id;const stridesBytes=new Uint8Array(new Int32Array(strides).buffer);const outId=backend.dataIdMap.get(out.dataId).id;wasmScatterNd(indicesId,updatesId,CppDType[updates.dtype],sliceRank,numUpdates,sliceSize,stridesBytes,outputSize,outId);return out}const scatterNdConfig={kernelName:tfjs_core65.ScatterNd,backendName:"wasm",setupFunc:setup31,kernelFunc:scatterNd};const tfjs_core66=__toModule(require_tf_core_node());let wasmSelect;function setup32(backend){wasmSelect=backend.wasm.cwrap(tfjs_core66.SelectV2,null,["number","number","number","number","number"])}function select(args){const{inputs,backend}=args;const{condition,t,e}=inputs;const conditionId=backend.dataIdMap.get(condition.dataId).id;const tId=backend.dataIdMap.get(t.dataId).id;const eId=backend.dataIdMap.get(e.dataId).id;const out=backend.makeOutput(t.shape,t.dtype);const outId=backend.dataIdMap.get(out.dataId).id;const cRank=condition.shape.length;const tRank=t.shape.length;const offset=cRank===0||cRank>1||tRank===1?1:tfjs_core66.util.sizeFromShape(t.shape.slice(1));wasmSelect(conditionId,tId,eId,offset,outId);return out}const selectV2Config={kernelName:tfjs_core66.SelectV2,backendName:"wasm",kernelFunc:select,setupFunc:setup32};const tfjs_core67=__toModule(require_tf_core_node());let wasmFunc6;function setup33(backend){wasmFunc6=backend.wasm.cwrap(tfjs_core67.Sigmoid,null,["number","number"])}function sigmoid(args){const{backend,inputs:{x}}=args;const xId=backend.dataIdMap.get(x.dataId).id;const out=backend.makeOutput(x.shape,x.dtype);const outId=backend.dataIdMap.get(out.dataId).id;if(tfjs_core67.util.sizeFromShape(out.shape)===0){return out}wasmFunc6(xId,outId);return out}const sigmoidConfig={kernelName:"Sigmoid",backendName:"wasm",setupFunc:setup33,kernelFunc:sigmoid};const tfjs_core68=__toModule(require_tf_core_node());const sinConfig=createUnaryKernelConfig(tfjs_core68.Sin);const tfjs_core69=__toModule(require_tf_core_node());function slice(args){const{inputs:{x},attrs:{begin,size},backend}=args;const[begin_,size_]=tfjs_core69.slice_util.parseSliceParams(x,begin,size);const isContinous=tfjs_core69.slice_util.isSliceContinous(x.shape,begin_,size_);const xVals=backend.typedArrayFromHeap(x);const out=backend.makeOutput(size_,x.dtype);const outVals=backend.typedArrayFromHeap(out);const xStrides=tfjs_core69.util.computeStrides(x.shape);if(isContinous){const flatOffset=tfjs_core69.slice_util.computeFlatOffset(begin_,xStrides);outVals.set(xVals.subarray(flatOffset,flatOffset+tfjs_core69.util.sizeFromShape(size_)));return out}const rank=x.shape.length;if(rank===2){slice2d(xVals,xStrides[0],outVals,begin_,size_)}else if(rank===3){slice3d(xVals,xStrides[0],xStrides[1],outVals,begin_,size_)}else if(rank===4){slice4d(xVals,xStrides[0],xStrides[1],xStrides[2],outVals,begin_,size_)}else{genericSliceSlow(xVals,x,outVals,begin_,size_)}return out}function slice2d(xVals,xStride,outVals,begin,size){let outOffset=0;const beginI=begin[0];const beginJ=begin[1];const endI=beginI+size[0];for(let i=beginI;iidx+begin[j]);outVals[i]=xBuf.get(...xLoc)}}const sliceConfig={kernelName:tfjs_core69.Slice,backendName:"wasm",kernelFunc:slice};const tfjs_core70=__toModule(require_tf_core_node());let wasmFunc7;function setup34(backend){wasmFunc7=backend.wasm.cwrap(tfjs_core70.Softmax,null,["number","number","number","number"])}function softmax(args){const{backend,inputs:{logits},attrs:{dim}}=args;const xId=backend.dataIdMap.get(logits.dataId).id;const out=backend.makeOutput(logits.shape,logits.dtype);const outId=backend.dataIdMap.get(out.dataId).id;const channels=logits.shape[dim];const batch=tfjs_core70.util.sizeFromShape(logits.shape)/channels;if(tfjs_core70.util.sizeFromShape(out.shape)===0){return out}wasmFunc7(xId,outId,channels,batch);return out}const softmaxConfig={kernelName:tfjs_core70.Softmax,backendName:"wasm",setupFunc:setup34,kernelFunc:softmax};const tfjs_core71=__toModule(require_tf_core_node());const tfjs_core72=__toModule(require_tf_core_node());function split(args){const{inputs,attrs,backend}=args;const{x}=inputs;const{numOrSizeSplits,axis}=attrs;const $axis=tfjs_core71.util.parseAxisParam(axis,x.shape)[0];const splitSizes=tfjs_core72.backend_util.prepareSplitSize(x,numOrSizeSplits,axis);const begin=new Array(x.shape.length).fill(0);const size=x.shape.slice();return splitSizes.map(s=>{const xSliceSize=[...size];xSliceSize[$axis]=s;const xSlice=slice({inputs:{x},attrs:{begin,size:xSliceSize},backend});begin[$axis]+=s;return xSlice})}const splitVConfig={kernelName:tfjs_core71.SplitV,backendName:"wasm",kernelFunc:split};const tfjs_core73=__toModule(require_tf_core_node());const sqrtConfig=createUnaryKernelConfig(tfjs_core73.Sqrt);const tfjs_core74=__toModule(require_tf_core_node());const squareConfig=createUnaryKernelConfig(tfjs_core74.Square);const tfjs_core75=__toModule(require_tf_core_node());const supportsFullBroadcast15=true;const squaredDifferenceConfig=createBinaryKernelConfig(tfjs_core75.SquaredDifference,supportsFullBroadcast15);const tfjs_core76=__toModule(require_tf_core_node());let wasmStridedSlice;function setup35(backend){wasmStridedSlice=backend.wasm.cwrap(tfjs_core76.StridedSlice,null,["number","array","number","array","array","array","array","array","number","number"])}function stridedSlice(args){const{backend,inputs,attrs}=args;const{x}=inputs;let{begin,end,strides}=attrs;if(strides==null){strides=new Array(begin.length)}const{beginMask,endMask,ellipsisMask,newAxisMask,shrinkAxisMask}=attrs;const ellipsisAxes=tfjs_core76.backend_util.slice_util.maskToAxes(ellipsisMask);if(ellipsisAxes.length>1){throw new Error("Multiple ellipses in slice is not allowed.")}if(ellipsisMask!==0&&newAxisMask!==0){throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.")}if(ellipsisMask!==0&&shrinkAxisMask!==0){throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.")}const numInterpolatedAxes=x.shape.length-begin.length;const expandAxes=tfjs_core76.backend_util.slice_util.maskToAxes(newAxisMask);const newShape=x.shape.slice();expandAxes.forEach(axis=>{begin[axis]=0;end[axis]=1;newShape.splice(axis,0,1)});const xReshaped=reshape({inputs:{x},attrs:{shape:newShape},backend});const{begin:normalizedBegin,end:normalizedEnd,strides:normalizedStrides}=tfjs_core76.backend_util.slice_util.getNormalizedAxes(xReshaped.shape,ellipsisAxes,numInterpolatedAxes,begin,end,strides,beginMask,endMask,ellipsisMask);begin=normalizedBegin;end=normalizedEnd;strides=normalizedStrides;const shrinkAxes=tfjs_core76.backend_util.slice_util.maskToAxes(shrinkAxisMask);shrinkAxes.forEach(axis=>{end[axis]=begin[axis]+1;strides[axis]=1});const size=tfjs_core76.backend_util.slice_util.computeOutShape(begin,end,strides);const outShape=size.filter((_,axis)=>shrinkAxes.indexOf(axis)===-1);const nonStrided=strides.every(v=>v===1);if(nonStrided){const xSliced=slice({inputs:{x},attrs:{begin,size},backend});return reshape({inputs:{x:xSliced},attrs:{shape:outShape},backend})}const out=backend.makeOutput(outShape,"float32");if(!outShape.some(axis=>axis===0)){const xId=backend.dataIdMap.get(xReshaped.dataId).id;const xStridesBytes=new Uint8Array(new Int32Array(tfjs_core76.util.computeStrides(xReshaped.shape)).buffer);const beginBytes=new Uint8Array(new Int32Array(begin).buffer);const endBytes=new Uint8Array(new Int32Array(end).buffer);const stridesBytes=new Uint8Array(new Int32Array(strides).buffer);const outputShapeBytes=new Uint8Array(new Int32Array(outShape).buffer);const outStridesBytes=new Uint8Array(new Int32Array(tfjs_core76.util.computeStrides(outShape)).buffer);const outId=backend.dataIdMap.get(out.dataId).id;wasmStridedSlice(xId,xStridesBytes,xReshaped.shape.length,beginBytes,endBytes,stridesBytes,outputShapeBytes,outStridesBytes,outShape.length,outId)}return reshape({inputs:{x:out},attrs:{shape:outShape},backend})}const stridedSliceConfig={kernelName:tfjs_core76.StridedSlice,backendName:"wasm",setupFunc:setup35,kernelFunc:stridedSlice};const tfjs_core77=__toModule(require_tf_core_node());const supportsFullBroadcast16=true;const subConfig=createBinaryKernelConfig(tfjs_core77.Sub,supportsFullBroadcast16);const tfjs_core78=__toModule(require_tf_core_node());let wasmSum;function setup36(backend){wasmSum=backend.wasm.cwrap(tfjs_core78.Sum,null,["number, number, number"])}function sum(args){const{backend,inputs,attrs}=args;const{axis,keepDims}=attrs;const{x}=inputs;const xId=backend.dataIdMap.get(x.dataId).id;let inputId=xId;let input=x;const{transposed,axes,originalAxes,inputWasTransposed}=permuteAxesAndTranspose(x,axis,backend);let reductionAxes=axes;if(inputWasTransposed){const transposedId=backend.dataIdMap.get(transposed.dataId).id;if(transposedId!==xId){input=transposed;inputId=transposedId;reductionAxes=tfjs_core78.backend_util.getInnerMostAxes(reductionAxes.length,input.shape.length)}}tfjs_core78.backend_util.assertAxesAreInnerMostDims("sum",reductionAxes,input.shape.length);const[outShape,reduceShape]=tfjs_core78.backend_util.computeOutAndReduceShapes(input.shape,reductionAxes);const reduceSize=tfjs_core78.util.sizeFromShape(reduceShape);const out=backend.makeOutput(outShape,input.dtype);if(tfjs_core78.util.sizeFromShape(input.shape)!==0){const outId=backend.dataIdMap.get(out.dataId).id;wasmSum(inputId,reduceSize,outId)}if(inputWasTransposed){backend.disposeData(transposed.dataId)}if(keepDims){const newShape=tfjs_core78.backend_util.expandShapeToKeepDim(out.shape,originalAxes);out.shape=newShape}return out}const sumConfig={kernelName:tfjs_core78.Sum,backendName:"wasm",setupFunc:setup36,kernelFunc:sum};const tfjs_core79=__toModule(require_tf_core_node());const tanhConfig=createUnaryKernelConfig(tfjs_core79.Tanh);const tfjs_core80=__toModule(require_tf_core_node());let wasmTile;function setup37(backend){wasmTile=backend.wasm.cwrap(tfjs_core80.Tile,null,["number","array","number","array","number","number"])}function tile(args){const{inputs,backend,attrs}=args;const{x}=inputs;const xId=backend.dataIdMap.get(x.dataId).id;const{reps}=attrs;const newShape=new Array(x.shape.length);for(let i=0;i({dataId,dtype,shape:outShape}))}const unpackConfig={kernelName:tfjs_core81.Unpack,backendName:"wasm",kernelFunc:unpack};const tfjs_core82=__toModule(require_tf_core_node());function zerosLike(args){const{inputs:{x},backend}=args;const out=backend.makeOutput(x.shape,x.dtype);const outVals=backend.typedArrayFromHeap(out);outVals.fill(0);return out}const zerosLikeConfig={kernelName:tfjs_core82.ZerosLike,backendName:"wasm",kernelFunc:zerosLike};const kernelConfigs=[absConfig,addConfig,addNConfig,argMaxConfig,avgPoolConfig,batchMatMulConfig,castConfig,clipByValueConfig,concatConfig,conv2DConfig,conv2DBackpropInputConfig,cosConfig,cropAndResizeConfig,cumsumConfig,depthToSpaceConfig,depthwiseConv2dNativeConfig,divConfig,equalConfig,expConfig,fillConfig,flipLeftRightConfig,floorDivConfig,fusedMatMulConfig,fusedBatchNormConfig,fusedConv2DConfig,fusedDepthwiseConv2DConfig,gatherNdConfig,gatherV2Config,greaterConfig,greaterEqualConfig,identityConfig,lessConfig,lessEqualConfig,logConfig,logicalAndConfig,maxConfig,maximumConfig,maxPoolConfig,minConfig,minimumConfig,multiplyConfig,negateConfig,nonMaxSuppressionV3Config,nonMaxSuppressionV4Config,nonMaxSuppressionV5Config,notEqualConfig,oneHotConfig,onesLikeConfig,padV2Config,powConfig,preluConfig,reluConfig,relu6Config,reshapeConfig,resizeBilinearConfig,reverseConfig,rotateWithOffsetConfig,rsqrtConfig,scatterNdConfig,selectV2Config,sigmoidConfig,sinConfig,sliceConfig,softmaxConfig,splitVConfig,sqrtConfig,squareConfig,squaredDifferenceConfig,stridedSliceConfig,subConfig,sumConfig,tanhConfig,tileConfig,transposeConfig,unpackConfig,zerosLikeConfig];for(const kernelConfig of kernelConfigs){tfjs_core83.registerKernel(kernelConfig)}const tfjs_core84=__toModule(require_tf_core_node());const ENV=tfjs_core84.env();ENV.registerFlag("WASM_HAS_SIMD_SUPPORT",async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,9,1,7,0,65,0,253,15,26,11])));ENV.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",async()=>{if(ENV.get("IS_NODE")){return false}try{new MessageChannel().port1.postMessage(new SharedArrayBuffer(1));return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch(e){return false}});const tfjs_core85=__toModule(require_tf_core_node());const tfjs_backend_wasm_threaded_simd=__toModule(require_tfjs_backend_wasm_threaded_simd());const wasmWorkerContents='var threadInfoStruct=0;var selfThreadId=0;var parentThreadId=0;var Module={};function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:selfThreadId})}var err=threadPrintErr;this.alert=threadAlert;Module["instantiateWasm"]=function(info,receiveInstance){var instance=new WebAssembly.Instance(Module["wasmModule"],info);Module["wasmModule"]=null;receiveInstance(instance);return instance.exports};this.onmessage=function(e){try{if(e.data.cmd==="load"){Module["DYNAMIC_BASE"]=e.data.DYNAMIC_BASE;Module["DYNAMICTOP_PTR"]=e.data.DYNAMICTOP_PTR;Module["wasmModule"]=e.data.wasmModule;Module["wasmMemory"]=e.data.wasmMemory;Module["buffer"]=Module["wasmMemory"].buffer;Module["ENVIRONMENT_IS_PTHREAD"]=true;if(typeof e.data.urlOrBlob==="string"){importScripts(e.data.urlOrBlob)}else{var objectUrl=URL.createObjectURL(e.data.urlOrBlob);importScripts(objectUrl);URL.revokeObjectURL(objectUrl)}Module=WasmBackendModuleThreadedSimd(Module);postMessage({"cmd":"loaded"})}else if(e.data.cmd==="objectTransfer"){Module["PThread"].receiveObjectTransfer(e.data)}else if(e.data.cmd==="run"){Module["__performance_now_clock_drift"]=performance.now()-e.data.time;threadInfoStruct=e.data.threadInfoStruct;Module["__register_pthread_ptr"](threadInfoStruct,0,0);selfThreadId=e.data.selfThreadId;parentThreadId=e.data.parentThreadId;var max=e.data.stackBase;var top=e.data.stackBase+e.data.stackSize;Module["establishStackSpace"](top,max);Module["_emscripten_tls_init"]();Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].setThreadStatus(Module["_pthread_self"](),1);try{var result=Module["dynCall_ii"](e.data.start_routine,e.data.arg);if(!Module["getNoExitRuntime"]())Module["PThread"].threadExit(result)}catch(ex){if(ex==="Canceled!"){Module["PThread"].threadCancel()}else if(ex!="unwind"){Atomics.store(Module["HEAPU32"],threadInfoStruct+4>>2,ex instanceof Module["ExitStatus"]?ex.status:-2);Atomics.store(Module["HEAPU32"],threadInfoStruct+0>>2,1);Module["_emscripten_futex_wake"](threadInfoStruct+0,2147483647);if(!(ex instanceof Module["ExitStatus"]))throw ex}}}else if(e.data.cmd==="cancel"){if(threadInfoStruct){Module["PThread"].threadCancel()}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processThreadQueue"){if(threadInfoStruct){Module["_emscripten_current_thread_process_queued_calls"]()}}else{err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){err("worker.js onmessage() captured an uncaught exception: "+ex);if(ex.stack)err(ex.stack);throw ex}};if(typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string"){self={location:{href:__filename}};var onmessage=this.onmessage;var nodeWorkerThreads=require("worker_threads");Worker=nodeWorkerThreads.Worker;var parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",function(data){onmessage({data:data})});var nodeFS=require("fs");var nodeRead=function(filename){return nodeFS.readFileSync(filename,"utf8")};function globalEval(x){global.require=require;global.Module=Module;eval.call(null,x)}importScripts=function(f){globalEval(nodeRead(f))};postMessage=function(msg){parentPort.postMessage(msg)};if(typeof performance==="undefined"){performance={now:function(){return Date.now()}}}}';const tfjs_backend_wasm=__toModule(require_tfjs_backend_wasm());const WASM_PRIORITY=2;class BackendWasm extends tfjs_core85.KernelBackend{constructor(wasm){super();this.wasm=wasm;this.dataIdNextNumber=1;this.wasm.tfjs.init();this.dataIdMap=new tfjs_core85.DataStorage(this,tfjs_core85.engine())}write(values,shape,dtype){const dataId={};this.move(dataId,values,shape,dtype);return dataId}numDataIds(){return this.dataIdMap.numDataIds()}async time(f){const start=tfjs_core85.util.now();f();const kernelMs=tfjs_core85.util.now()-start;return{kernelMs}}move(dataId,values,shape,dtype){const id=this.dataIdNextNumber++;if(dtype==="string"){const stringBytes=values;this.dataIdMap.set(dataId,{id,stringBytes,shape,dtype,memoryOffset:null});return}const size=tfjs_core85.util.sizeFromShape(shape);const numBytes=size*tfjs_core85.util.bytesPerElement(dtype);const memoryOffset=this.wasm._malloc(numBytes);this.dataIdMap.set(dataId,{id,memoryOffset,shape,dtype});this.wasm.tfjs.registerTensor(id,size,memoryOffset);if(values!=null){this.wasm.HEAPU8.set(new Uint8Array(values.buffer,values.byteOffset,numBytes),memoryOffset)}}async read(dataId){return this.readSync(dataId)}readSync(dataId){const{memoryOffset,dtype,shape,stringBytes}=this.dataIdMap.get(dataId);if(dtype==="string"){return stringBytes}const bytes=this.wasm.HEAPU8.slice(memoryOffset,memoryOffset+tfjs_core85.util.sizeFromShape(shape)*tfjs_core85.util.bytesPerElement(dtype));return typedArrayFromBuffer(bytes.buffer,dtype)}disposeData(dataId){const data2=this.dataIdMap.get(dataId);this.wasm._free(data2.memoryOffset);this.wasm.tfjs.disposeData(data2.id);this.dataIdMap.delete(dataId)}floatPrecision(){return 32}getMemoryOffset(dataId){return this.dataIdMap.get(dataId).memoryOffset}dispose(){this.wasm.tfjs.dispose();this.wasm=null}memory(){return{unreliable:false}}makeOutput(shape,dtype,memoryOffset){let dataId;if(memoryOffset==null){dataId=this.write(null,shape,dtype)}else{dataId={};const id=this.dataIdNextNumber++;this.dataIdMap.set(dataId,{id,memoryOffset,shape,dtype});const size=tfjs_core85.util.sizeFromShape(shape);this.wasm.tfjs.registerTensor(id,size,memoryOffset)}return{dataId,shape,dtype}}typedArrayFromHeap({shape,dtype,dataId}){const buffer2=this.wasm.HEAPU8.buffer;const{memoryOffset}=this.dataIdMap.get(dataId);const size=tfjs_core85.util.sizeFromShape(shape);switch(dtype){case"float32":return new Float32Array(buffer2,memoryOffset,size);case"int32":return new Int32Array(buffer2,memoryOffset,size);case"bool":return new Uint8Array(buffer2,memoryOffset,size);default:throw new Error(`Unknown dtype ${dtype}`)}}}tfjs_core85.registerBackend("wasm",async()=>{const{wasm}=await init();return new BackendWasm(wasm)},WASM_PRIORITY);function createInstantiateWasmFunc(path){return(imports,callback)=>{tfjs_core85.util.fetch(path,{credentials:"same-origin"}).then(response=>{if(!response["ok"]){imports.env.a(`failed to load wasm binary file at '${path}'`)}response.arrayBuffer().then(binary=>{WebAssembly.instantiate(binary,imports).then(output=>{callback(output.instance)})})});return{}}}function getPathToWasmBinary(simdSupported,threadsSupported,wasmModuleFolder){if(wasmPath!=null){return wasmPath}let path="tfjs-backend-wasm.wasm";if(simdSupported&&threadsSupported){path="tfjs-backend-wasm-threaded-simd.wasm"}else if(simdSupported){path="tfjs-backend-wasm-simd.wasm"}if(wasmFileMap!=null){if(wasmFileMap[path]!=null){return wasmFileMap[path]}}return wasmModuleFolder+path}async function init(){const[simdSupported,threadsSupported]=await Promise.all([tfjs_core85.env().getAsync("WASM_HAS_SIMD_SUPPORT"),tfjs_core85.env().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise((resolve,reject)=>{const factoryConfig={};factoryConfig.locateFile=(path,prefix)=>{if(path.endsWith(".worker.js")){const response=wasmWorkerContents;const blob=new Blob([response],{type:"application/javascript"});return URL.createObjectURL(blob)}if(path.endsWith(".wasm")){return getPathToWasmBinary(simdSupported,threadsSupported,wasmPathPrefix!=null?wasmPathPrefix:prefix)}return prefix+path};if(customFetch){factoryConfig.instantiateWasm=createInstantiateWasmFunc(getPathToWasmBinary(simdSupported,threadsSupported,wasmPathPrefix!=null?wasmPathPrefix:""))}let wasm;if(threadsSupported&&simdSupported&&wasmPath==null){wasm=tfjs_backend_wasm_threaded_simd.default(factoryConfig);wasm.mainScriptUrlOrBlob=new Blob([`var _scriptDir = undefined; var WasmBackendModuleThreadedSimd = `+tfjs_backend_wasm_threaded_simd.default.toString()],{type:"text/javascript"})}else{wasm=tfjs_backend_wasm.default(factoryConfig)}const voidReturnType=null;wasm.tfjs={init:wasm.cwrap("init",null,[]),registerTensor:wasm.cwrap("register_tensor",null,["number","number","number"]),disposeData:wasm.cwrap("dispose_data",voidReturnType,["number"]),dispose:wasm.cwrap("dispose",voidReturnType,[])};let initialized=false;wasm.onRuntimeInitialized=()=>{initialized=true;initAborted=false;resolve({wasm})};wasm.onAbort=()=>{if(initialized){return}if(initAborted){return}initAborted=true;const rejectMsg="Make sure the server can serve the `.wasm` file relative to the bundled js file. For more details see https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-wasm/README.md#using-bundlers";reject({message:rejectMsg})}})}function typedArrayFromBuffer(buffer2,dtype){switch(dtype){case"float32":return new Float32Array(buffer2);case"int32":return new Int32Array(buffer2);case"bool":return new Uint8Array(buffer2);default:throw new Error(`Unknown dtype ${dtype}`)}}const wasmBinaryNames=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"];let wasmPath=null;let wasmPathPrefix=null;let wasmFileMap={};let initAborted=false;let customFetch=false;function setWasmPath(path,usePlatformFetch=false){tfjs_core85.deprecationWarn("setWasmPath has been deprecated in favor of setWasmPaths and will be removed in a future release.");if(initAborted){throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPath()` before you call `tf.setBackend()` or `tf.ready()`")}wasmPath=path;customFetch=usePlatformFetch}function setWasmPaths(prefixOrFileMap,usePlatformFetch=false){if(initAborted){throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPaths()` before you call `tf.setBackend()` or `tf.ready()`")}if(typeof prefixOrFileMap==="string"){wasmPathPrefix=prefixOrFileMap}else{wasmFileMap=prefixOrFileMap;const missingPaths=wasmBinaryNames.filter(name=>wasmFileMap[name]==null);if(missingPaths.length>0){throw new Error(`There were no entries found for the following binaries: ${missingPaths.join(",")}. Please either call setWasmPaths with a map providing a path for each binary, or with a string indicating the directory where all the binaries can be found.`)}}customFetch=usePlatformFetch}const version2="2.7.0";const facemesh=__toModule(require_facemesh());const age=__toModule(require_age());const gender=__toModule(require_gender());const emotion=__toModule(require_emotion());const embedding=__toModule(require_embedding());const posenet=__toModule(require_posenet());function getBoxSize(box){return[Math.abs(box.endPoint[0]-box.startPoint[0]),Math.abs(box.endPoint[1]-box.startPoint[1])]}function getBoxCenter(box){return[box.startPoint[0]+(box.endPoint[0]-box.startPoint[0])/2,box.startPoint[1]+(box.endPoint[1]-box.startPoint[1])/2]}function cutBoxFromImageAndResize(box,image2,cropSize){const h=image2.shape[1];const w=image2.shape[2];const boxes=[[box.startPoint[1]/h,box.startPoint[0]/w,box.endPoint[1]/h,box.endPoint[0]/w]];return tf.image.cropAndResize(image2,boxes,[0],cropSize)}function scaleBoxCoordinates(box,factor){const startPoint=[box.startPoint[0]*factor[0],box.startPoint[1]*factor[1]];const endPoint=[box.endPoint[0]*factor[0],box.endPoint[1]*factor[1]];const palmLandmarks=box.palmLandmarks.map(coord=>{const scaledCoord=[coord[0]*factor[0],coord[1]*factor[1]];return scaledCoord});return{startPoint,endPoint,palmLandmarks,confidence:box.confidence}}function enlargeBox(box,factor=1.5){const center=getBoxCenter(box);const size=getBoxSize(box);const newHalfSize=[factor*size[0]/2,factor*size[1]/2];const startPoint=[center[0]-newHalfSize[0],center[1]-newHalfSize[1]];const endPoint=[center[0]+newHalfSize[0],center[1]+newHalfSize[1]];return{startPoint,endPoint,palmLandmarks:box.palmLandmarks}}function squarifyBox(box){const centers=getBoxCenter(box);const size=getBoxSize(box);const maxEdge=Math.max(...size);const halfSize=maxEdge/2;const startPoint=[centers[0]-halfSize,centers[1]-halfSize];const endPoint=[centers[0]+halfSize,centers[1]+halfSize];return{startPoint,endPoint,palmLandmarks:box.palmLandmarks}}function shiftBox(box,shiftFactor){const boxSize=[box.endPoint[0]-box.startPoint[0],box.endPoint[1]-box.startPoint[1]];const shiftVector=[boxSize[0]*shiftFactor[0],boxSize[1]*shiftFactor[1]];const startPoint=[box.startPoint[0]+shiftVector[0],box.startPoint[1]+shiftVector[1]];const endPoint=[box.endPoint[0]+shiftVector[0],box.endPoint[1]+shiftVector[1]];return{startPoint,endPoint,palmLandmarks:box.palmLandmarks}}function normalizeRadians(angle){return angle-2*Math.PI*Math.floor((angle+Math.PI)/(2*Math.PI))}function computeRotation(point1,point2){const radians=Math.PI/2-Math.atan2(-(point2[1]-point1[1]),point2[0]-point1[0]);return normalizeRadians(radians)}const buildTranslationMatrix=(x,y)=>[[1,0,x],[0,1,y],[0,0,1]];function dot(v1,v2){let product=0;for(let i=0;i{if(typeof performance!=="undefined")return performance.now();return parseInt(Number(process.hrtime.bigint())/1e3/1e3)};function mergeDeep(...objects){const isObject=obj=>obj&&typeof obj==="object";return objects.reduce((prev,obj)=>{Object.keys(obj||{}).forEach(key=>{const pVal=prev[key];const oVal=obj[key];if(Array.isArray(pVal)&&Array.isArray(oVal)){prev[key]=pVal.concat(...oVal)}else if(isObject(pVal)&&isObject(oVal)){prev[key]=mergeDeep(pVal,oVal)}else{prev[key]=oVal}});return prev},{})}class Human{constructor(userConfig={}){this.tf=tf;this.version=version4;this.config=mergeDeep(config_default,userConfig);this.fx=null;this.state="idle";this.numTensors=0;this.analyzeMemoryLeaks=false;this.checkSanity=false;this.firstRun=true;this.perf={};this.models={facemesh:null,posenet:null,handpose:null,iris:null,age:null,gender:null,emotion:null};this.facemesh=facemesh;this.age=age;this.gender=gender;this.emotion=emotion;this.body=posenet;this.hand=handpose}log(...msg){if(msg&&this.config.console)console.log("Human:",...msg)}profile(){if(this.config.profile)return profile.data;return{}}analyze(...msg){if(!this.analyzeMemoryLeaks)return;const current=tf.engine().state.numTensors;const previous=this.numTensors;this.numTensors=current;const leaked=current-previous;if(leaked!==0)this.log(...msg,leaked)}sanity(input){if(!this.checkSanity)return null;if(!input)return"input is not defined";if(tf.ENV.flags.IS_NODE&&!(input instanceof tf.Tensor)){return"input must be a tensor"}try{tf.getBackend()}catch(e){return"backend not loaded"}return null}simmilarity(embedding1,embedding2){if(this.config.face.embedding.enabled)return embedding.simmilarity(embedding1,embedding2);return 0}async load(userConfig){this.state="load";const timeStamp=now();if(userConfig)this.config=mergeDeep(this.config,userConfig);if(this.firstRun){this.checkBackend(true);this.log(`version: ${this.version} TensorFlow/JS version: ${tf.version_core}`);this.log("configuration:",this.config);this.log("flags:",tf.ENV.flags);this.firstRun=false}if(this.config.async){[this.models.facemesh,this.models.age,this.models.gender,this.models.emotion,this.models.embedding,this.models.posenet,this.models.handpose]=await Promise.all([this.models.facemesh||(this.config.face.enabled?facemesh.load(this.config.face):null),this.models.age||(this.config.face.enabled&&this.config.face.age.enabled?age.load(this.config):null),this.models.gender||(this.config.face.enabled&&this.config.face.gender.enabled?gender.load(this.config):null),this.models.emotion||(this.config.face.enabled&&this.config.face.emotion.enabled?emotion.load(this.config):null),this.models.embedding||(this.config.face.enabled&&this.config.face.embedding.enabled?embedding.load(this.config):null),this.models.posenet||(this.config.body.enabled?posenet.load(this.config):null),this.models.handpose||(this.config.hand.enabled?handpose.load(this.config.hand):null)])}else{if(this.config.face.enabled&&!this.models.facemesh)this.models.facemesh=await facemesh.load(this.config.face);if(this.config.face.enabled&&this.config.face.age.enabled&&!this.models.age)this.models.age=await age.load(this.config);if(this.config.face.enabled&&this.config.face.gender.enabled&&!this.models.gender)this.models.gender=await gender.load(this.config);if(this.config.face.enabled&&this.config.face.emotion.enabled&&!this.models.emotion)this.models.emotion=await emotion.load(this.config);if(this.config.face.enabled&&this.config.face.embedding.enabled&&!this.models.embedding)this.models.embedding=await embedding.load(this.config);if(this.config.body.enabled&&!this.models.posenet)this.models.posenet=await posenet.load(this.config);if(this.config.hand.enabled&&!this.models.handpose)this.models.handpose=await handpose.load(this.config.hand)}const current=Math.trunc(now()-timeStamp);if(current>(this.perf.load||0))this.perf.load=current}async checkBackend(force){const timeStamp=now();if(this.config.backend&&this.config.backend!==""&&force||tf.getBackend()!==this.config.backend){this.state="backend";this.log("setting backend:",this.config.backend);if(this.config.backend==="wasm"){this.log("settings wasm path:",this.config.wasmPath);dist_exports.setWasmPaths(this.config.wasmPath);const simd=await tf.env().getAsync("WASM_HAS_SIMD_SUPPORT");if(!simd)this.log("warning: wasm simd support is not enabled")}await tf.setBackend(this.config.backend);tf.enableProdMode();if(tf.getBackend()==="webgl"){if(this.config.deallocate){this.log("changing webgl: WEBGL_DELETE_TEXTURE_THRESHOLD:",this.config.deallocate);tf.ENV.set("WEBGL_DELETE_TEXTURE_THRESHOLD",this.config.deallocate?0:-1)}tf.ENV.set("WEBGL_PACK_DEPTHWISECONV",true)}await tf.ready()}const current=Math.trunc(now()-timeStamp);if(current>(this.perf.backend||0))this.perf.backend=current}async detectFace(input){let timeStamp;let ageRes;let genderRes;let emotionRes;let embeddingRes;const faceRes=[];this.state="run:face";timeStamp=now();const faces=await this.models.facemesh.estimateFaces(input,this.config.face);this.perf.face=Math.trunc(now()-timeStamp);for(const face2 of faces){this.analyze("Get Face");if(!face2.image||face2.image.isDisposedInternal){this.log("Face object is disposed:",face2.image);continue}this.analyze("Start Age:");if(this.config.async){ageRes=this.config.face.age.enabled?age.predict(face2.image,this.config):{}}else{this.state="run:age";timeStamp=now();ageRes=this.config.face.age.enabled?await age.predict(face2.image,this.config):{};this.perf.age=Math.trunc(now()-timeStamp)}this.analyze("Start Gender:");if(this.config.async){genderRes=this.config.face.gender.enabled?gender.predict(face2.image,this.config):{}}else{this.state="run:gender";timeStamp=now();genderRes=this.config.face.gender.enabled?await gender.predict(face2.image,this.config):{};this.perf.gender=Math.trunc(now()-timeStamp)}this.analyze("Start Emotion:");if(this.config.async){emotionRes=this.config.face.emotion.enabled?emotion.predict(face2.image,this.config):{}}else{this.state="run:emotion";timeStamp=now();emotionRes=this.config.face.emotion.enabled?await emotion.predict(face2.image,this.config):{};this.perf.emotion=Math.trunc(now()-timeStamp)}this.analyze("End Emotion:");this.analyze("Start Embedding:");if(this.config.async){embeddingRes=this.config.face.embedding.enabled?embedding.predict(face2.image,this.config):{}}else{this.state="run:embedding";timeStamp=now();embeddingRes=this.config.face.embedding.enabled?await embedding.predict(face2.image,this.config):{};this.perf.embedding=Math.trunc(now()-timeStamp)}this.analyze("End Emotion:");if(this.config.async){[ageRes,genderRes,emotionRes,embeddingRes]=await Promise.all([ageRes,genderRes,emotionRes,embeddingRes])}this.analyze("Finish Face:");face2.image.dispose();const irisSize=face2.annotations.leftEyeIris&&face2.annotations.rightEyeIris?11.7*Math.max(Math.abs(face2.annotations.leftEyeIris[3][0]-face2.annotations.leftEyeIris[1][0]),Math.abs(face2.annotations.rightEyeIris[4][1]-face2.annotations.rightEyeIris[2][1])):0;faceRes.push({confidence:face2.confidence,box:face2.box,mesh:face2.mesh,annotations:face2.annotations,age:ageRes.age,gender:genderRes.gender,genderConfidence:genderRes.confidence,emotion:emotionRes,embedding:embeddingRes,iris:irisSize!==0?Math.trunc(irisSize)/100:0});this.analyze("End Face")}this.analyze("End FaceMesh:");if(this.config.async){if(this.perf.face)delete this.perf.face;if(this.perf.age)delete this.perf.age;if(this.perf.gender)delete this.perf.gender;if(this.perf.emotion)delete this.perf.emotion}return faceRes}async image(input,userConfig={}){this.state="image";this.config=mergeDeep(this.config,userConfig);const process3=image.process(input,this.config);process3.tensor.dispose();return process3.canvas}async detect(input,userConfig={}){return new Promise(async resolve=>{this.state="config";let timeStamp;this.config=mergeDeep(this.config,userConfig);this.state="check";const error=this.sanity(input);if(error){this.log(error,input);resolve({error})}let poseRes;let handRes;let faceRes;const timeStart=now();await this.checkBackend();await this.load();if(this.config.scoped)tf.engine().startScope();this.analyze("Start Scope:");timeStamp=now();const process3=image.process(input,this.config);this.perf.image=Math.trunc(now()-timeStamp);this.analyze("Get Image:");if(this.config.async){faceRes=this.config.face.enabled?this.detectFace(process3.tensor):[];if(this.perf.face)delete this.perf.face}else{this.state="run:face";timeStamp=now();faceRes=this.config.face.enabled?await this.detectFace(process3.tensor):[];this.perf.face=Math.trunc(now()-timeStamp)}this.analyze("Start Body:");if(this.config.async){poseRes=this.config.body.enabled?this.models.posenet.estimatePoses(process3.tensor,this.config):[];if(this.perf.body)delete this.perf.body}else{this.state="run:body";timeStamp=now();poseRes=this.config.body.enabled?await this.models.posenet.estimatePoses(process3.tensor,this.config):[];this.perf.body=Math.trunc(now()-timeStamp)}this.analyze("End Body:");this.analyze("Start Hand:");if(this.config.async){handRes=this.config.hand.enabled?this.models.handpose.estimateHands(process3.tensor,this.config.hand):[];if(this.perf.hand)delete this.perf.hand}else{this.state="run:hand";timeStamp=now();handRes=this.config.hand.enabled?await this.models.handpose.estimateHands(process3.tensor,this.config.hand):[];this.perf.hand=Math.trunc(now()-timeStamp)}if(this.config.async){[faceRes,poseRes,handRes]=await Promise.all([faceRes,poseRes,handRes])}process3.tensor.dispose();if(this.config.scoped)tf.engine().endScope();this.analyze("End Scope:");let gestureRes=[];if(this.config.gesture.enabled){timeStamp=now();gestureRes={face:gesture.face(faceRes),body:gesture.body(poseRes),hand:gesture.hand(handRes)};if(!this.config.async)this.perf.gesture=Math.trunc(now()-timeStamp);else if(this.perf.gesture)delete this.perf.gesture}this.perf.total=Math.trunc(now()-timeStart);this.state="idle";resolve({face:faceRes,body:poseRes,hand:handRes,gesture:gestureRes,performance:this.perf,canvas:process3.canvas})})}async warmup(userConfig,sample){if(!sample)sample=new ImageData(255,255);const warmup=await this.detect(sample,userConfig);this.log("warmed up");return warmup}} /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /** * @license * Copyright 2017 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ /** * @license * Copyright 2018 Google LLC * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. * ============================================================================= */ /** * @license * Copyright 2018 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ============================================================================= */ /** * @license * Copyright 2018 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ /** * @license * Copyright 2019 Google LLC * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. * ============================================================================= */ /** * @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ============================================================================= */ /** * @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ /** * @license * Copyright 2020 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ /** * @license * Copyright 2020 Google LLC * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. * ============================================================================= */ /** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ /** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ /** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ /** * @license * Copyright 2018 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ /** @license See the LICENSE file. */ //# sourceMappingURL=human.node.js.map