You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
3839 lines
704 KiB
3839 lines
704 KiB
(window.webpackJsonp=window.webpackJsonp||[]).push([[58],{"2LEM":function(rn,ke,te){rn.exports=te.p+"static/checkPeople.d3191bb4.jpg"},"2U/9":function(rn,ke,te){"use strict";var Se=te("VTBJ"),ze=te("rePB"),at=te("Ff2n"),mt=te("1OyB"),Ke=te("vuIU"),ve=te("Ji7U"),ye=te("LK+K"),ne=te("q1tI"),kt=te.n(ne),ee=te("Zm9Q"),ot=te("TSYQ"),Mt=te.n(ot),tt=["className","prefixCls","style","active","status","iconPrefix","icon","wrapperStyle","stepNumber","disabled","description","title","subTitle","progressDot","stepIcon","tailContent","icons","stepIndex","onStepClick","onClick"];function Ve(Pt){return typeof Pt=="string"}var st=function(Pt){Object(ve.a)(Pe,Pt);var dn=Object(ye.a)(Pe);function Pe(){var Ge;return Object(mt.a)(this,Pe),Ge=dn.apply(this,arguments),Ge.onClick=function(){var ce=Ge.props,Ye=ce.onClick,ie=ce.onStepClick,D=ce.stepIndex;Ye&&Ye.apply(void 0,arguments),ie(D)},Ge}return Object(Ke.a)(Pe,[{key:"renderIconNode",value:function(){var ce,Ye=this.props,ie=Ye.prefixCls,D=Ye.progressDot,se=Ye.stepIcon,Te=Ye.stepNumber,Ae=Ye.status,ae=Ye.title,Oe=Ye.description,Be=Ye.icon,Qt=Ye.iconPrefix,k=Ye.icons,Qe,q=Mt()("".concat(ie,"-icon"),"".concat(Qt,"icon"),(ce={},Object(ze.a)(ce,"".concat(Qt,"icon-").concat(Be),Be&&Ve(Be)),Object(ze.a)(ce,"".concat(Qt,"icon-check"),!Be&&Ae==="finish"&&(k&&!k.finish||!k)),Object(ze.a)(ce,"".concat(Qt,"icon-cross"),!Be&&Ae==="error"&&(k&&!k.error||!k)),ce)),lt=ne.createElement("span",{className:"".concat(ie,"-icon-dot")});return D?typeof D=="function"?Qe=ne.createElement("span",{className:"".concat(ie,"-icon")},D(lt,{index:Te-1,status:Ae,title:ae,description:Oe})):Qe=ne.createElement("span",{className:"".concat(ie,"-icon")},lt):Be&&!Ve(Be)?Qe=ne.createElement("span",{className:"".concat(ie,"-icon")},Be):k&&k.finish&&Ae==="finish"?Qe=ne.createElement("span",{className:"".concat(ie,"-icon")},k.finish):k&&k.error&&Ae==="error"?Qe=ne.createElement("span",{className:"".concat(ie,"-icon")},k.error):Be||Ae==="finish"||Ae==="error"?Qe=ne.createElement("span",{className:q}):Qe=ne.createElement("span",{className:"".concat(ie,"-icon")},Te),se&&(Qe=se({index:Te-1,status:Ae,title:ae,description:Oe,node:Qe})),Qe}},{key:"render",value:function(){var ce,Ye=this.props,ie=Ye.className,D=Ye.prefixCls,se=Ye.style,Te=Ye.active,Ae=Ye.status,ae=Ae===void 0?"wait":Ae,Oe=Ye.iconPrefix,Be=Ye.icon,Qt=Ye.wrapperStyle,k=Ye.stepNumber,Qe=Ye.disabled,q=Ye.description,lt=Ye.title,je=Ye.subTitle,St=Ye.progressDot,Cn=Ye.stepIcon,bn=Ye.tailContent,On=Ye.icons,xr=Ye.stepIndex,tr=Ye.onStepClick,Xt=Ye.onClick,nr=Object(at.a)(Ye,tt),rr=Mt()("".concat(D,"-item"),"".concat(D,"-item-").concat(ae),ie,(ce={},Object(ze.a)(ce,"".concat(D,"-item-custom"),Be),Object(ze.a)(ce,"".concat(D,"-item-active"),Te),Object(ze.a)(ce,"".concat(D,"-item-disabled"),Qe===!0),ce)),wn=Object(Se.a)({},se),$t={};return tr&&!Qe&&($t.role="button",$t.tabIndex=0,$t.onClick=this.onClick),ne.createElement("div",Object.assign({},nr,{className:rr,style:wn}),ne.createElement("div",Object.assign({onClick:Xt},$t,{className:"".concat(D,"-item-container")}),ne.createElement("div",{className:"".concat(D,"-item-tail")},bn),ne.createElement("div",{className:"".concat(D,"-item-icon")},this.renderIconNode()),ne.createElement("div",{className:"".concat(D,"-item-content")},ne.createElement("div",{className:"".concat(D,"-item-title")},lt,je&&ne.createElement("div",{title:typeof je=="string"?je:void 0,className:"".concat(D,"-item-subtitle")},je)),q&&ne.createElement("div",{className:"".concat(D,"-item-description")},q))))}}]),Pe}(ne.Component),Ct=["prefixCls","style","className","children","direction","type","labelPlacement","iconPrefix","status","size","current","progressDot","stepIcon","initial","icons","onChange"],Ft=function(Pt){Object(ve.a)(Pe,Pt);var dn=Object(ye.a)(Pe);function Pe(){var Ge;return Object(mt.a)(this,Pe),Ge=dn.apply(this,arguments),Ge.onStepClick=function(ce){var Ye=Ge.props,ie=Ye.onChange,D=Ye.current;ie&&D!==ce&&ie(ce)},Ge}return Object(Ke.a)(Pe,[{key:"render",value:function(){var ce,Ye=this,ie=this.props,D=ie.prefixCls,se=ie.style,Te=se===void 0?{}:se,Ae=ie.className,ae=ie.children,Oe=ie.direction,Be=ie.type,Qt=ie.labelPlacement,k=ie.iconPrefix,Qe=ie.status,q=ie.size,lt=ie.current,je=ie.progressDot,St=ie.stepIcon,Cn=ie.initial,bn=ie.icons,On=ie.onChange,xr=Object(at.a)(ie,Ct),tr=Be==="navigation",Xt=je?"vertical":Qt,nr=Mt()(D,"".concat(D,"-").concat(Oe),Ae,(ce={},Object(ze.a)(ce,"".concat(D,"-").concat(q),q),Object(ze.a)(ce,"".concat(D,"-label-").concat(Xt),Oe==="horizontal"),Object(ze.a)(ce,"".concat(D,"-dot"),!!je),Object(ze.a)(ce,"".concat(D,"-navigation"),tr),ce));return kt.a.createElement("div",Object.assign({className:nr,style:Te},xr),Object(ee.a)(ae).map(function(rr,wn){var $t=Cn+wn,En=Object(Se.a)({stepNumber:"".concat($t+1),stepIndex:$t,key:$t,prefixCls:D,iconPrefix:k,wrapperStyle:Te,progressDot:je,stepIcon:St,icons:bn,onStepClick:On&&Ye.onStepClick},rr.props);return Qe==="error"&&wn===lt-1&&(En.className="".concat(D,"-next-error")),rr.props.status||($t===lt?En.status=Qe:$t<lt?En.status="finish":En.status="wait"),En.active=$t===lt,Object(ne.cloneElement)(rr,En)}))}}]),Pe}(kt.a.Component);Ft.Step=st,Ft.defaultProps={type:"default",prefixCls:"rc-steps",iconPrefix:"rc",direction:"horizontal",labelPlacement:"horizontal",initial:0,current:0,status:"process",size:"",progressDot:!1};var xn=ke.a=Ft},"49sm":function(rn,ke){var te={}.toString;rn.exports=Array.isArray||function(Se){return te.call(Se)=="[object Array]"}},5:function(rn,ke){},6:function(rn,ke){},7:function(rn,ke){},"8KZw":function(rn,ke,te){"use strict";(function(Se,ze){te.d(ke,"a",function(){return at});function at(){return typeof Se=="object"&&!0&&typeof rn!="undefined"&&typeof ze!="undefined"&&!!ze.version}}).call(this,te("IyRk"),te("Q2Ig"))},H7XF:function(rn,ke,te){"use strict";ke.byteLength=ne,ke.toByteArray=ee,ke.fromByteArray=tt;for(var Se=[],ze=[],at=typeof Uint8Array!="undefined"?Uint8Array:Array,mt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ke=0,ve=mt.length;Ke<ve;++Ke)Se[Ke]=mt[Ke],ze[mt.charCodeAt(Ke)]=Ke;ze["-".charCodeAt(0)]=62,ze["_".charCodeAt(0)]=63;function ye(Ve){var st=Ve.length;if(st%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var Ct=Ve.indexOf("=");Ct===-1&&(Ct=st);var Ft=Ct===st?0:4-Ct%4;return[Ct,Ft]}function ne(Ve){var st=ye(Ve),Ct=st[0],Ft=st[1];return(Ct+Ft)*3/4-Ft}function kt(Ve,st,Ct){return(st+Ct)*3/4-Ct}function ee(Ve){var st,Ct=ye(Ve),Ft=Ct[0],xn=Ct[1],Pt=new at(kt(Ve,Ft,xn)),dn=0,Pe=xn>0?Ft-4:Ft,Ge;for(Ge=0;Ge<Pe;Ge+=4)st=ze[Ve.charCodeAt(Ge)]<<18|ze[Ve.charCodeAt(Ge+1)]<<12|ze[Ve.charCodeAt(Ge+2)]<<6|ze[Ve.charCodeAt(Ge+3)],Pt[dn++]=st>>16&255,Pt[dn++]=st>>8&255,Pt[dn++]=st&255;return xn===2&&(st=ze[Ve.charCodeAt(Ge)]<<2|ze[Ve.charCodeAt(Ge+1)]>>4,Pt[dn++]=st&255),xn===1&&(st=ze[Ve.charCodeAt(Ge)]<<10|ze[Ve.charCodeAt(Ge+1)]<<4|ze[Ve.charCodeAt(Ge+2)]>>2,Pt[dn++]=st>>8&255,Pt[dn++]=st&255),Pt}function ot(Ve){return Se[Ve>>18&63]+Se[Ve>>12&63]+Se[Ve>>6&63]+Se[Ve&63]}function Mt(Ve,st,Ct){for(var Ft,xn=[],Pt=st;Pt<Ct;Pt+=3)Ft=(Ve[Pt]<<16&16711680)+(Ve[Pt+1]<<8&65280)+(Ve[Pt+2]&255),xn.push(ot(Ft));return xn.join("")}function tt(Ve){for(var st,Ct=Ve.length,Ft=Ct%3,xn=[],Pt=16383,dn=0,Pe=Ct-Ft;dn<Pe;dn+=Pt)xn.push(Mt(Ve,dn,dn+Pt>Pe?Pe:dn+Pt));return Ft===1?(st=Ve[Ct-1],xn.push(Se[st>>2]+Se[st<<4&63]+"==")):Ft===2&&(st=(Ve[Ct-2]<<8)+Ve[Ct-1],xn.push(Se[st>>10]+Se[st>>4&63]+Se[st<<2&63]+"=")),xn.join("")}},HDXh:function(rn,ke,te){"use strict";(function(Se){/*!
|
|
* The buffer module from node.js, for the browser.
|
|
*
|
|
* @author Feross Aboukhadijeh <http://feross.org>
|
|
* @license MIT
|
|
*/var ze=te("H7XF"),at=te("kVK+"),mt=te("49sm");ke.Buffer=ne,ke.SlowBuffer=xn,ke.INSPECT_MAX_BYTES=50,ne.TYPED_ARRAY_SUPPORT=Se.TYPED_ARRAY_SUPPORT!==void 0?Se.TYPED_ARRAY_SUPPORT:Ke(),ke.kMaxLength=ve();function Ke(){try{var L=new Uint8Array(1);return L.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},L.foo()===42&&typeof L.subarray=="function"&&L.subarray(1,1).byteLength===0}catch(_){return!1}}function ve(){return ne.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function ye(L,_){if(ve()<_)throw new RangeError("Invalid typed array length");return ne.TYPED_ARRAY_SUPPORT?(L=new Uint8Array(_),L.__proto__=ne.prototype):(L===null&&(L=new ne(_)),L.length=_),L}function ne(L,_,R){if(!ne.TYPED_ARRAY_SUPPORT&&!(this instanceof ne))return new ne(L,_,R);if(typeof L=="number"){if(typeof _=="string")throw new Error("If encoding is specified then the first argument must be a string");return Mt(this,L)}return kt(this,L,_,R)}ne.poolSize=8192,ne._augment=function(L){return L.__proto__=ne.prototype,L};function kt(L,_,R,U){if(typeof _=="number")throw new TypeError('"value" argument must not be a number');return typeof ArrayBuffer!="undefined"&&_ instanceof ArrayBuffer?st(L,_,R,U):typeof _=="string"?tt(L,_,R):Ct(L,_)}ne.from=function(L,_,R){return kt(null,L,_,R)},ne.TYPED_ARRAY_SUPPORT&&(ne.prototype.__proto__=Uint8Array.prototype,ne.__proto__=Uint8Array,typeof Symbol!="undefined"&&Symbol.species&&ne[Symbol.species]===ne&&Object.defineProperty(ne,Symbol.species,{value:null,configurable:!0}));function ee(L){if(typeof L!="number")throw new TypeError('"size" argument must be a number');if(L<0)throw new RangeError('"size" argument must not be negative')}function ot(L,_,R,U){return ee(_),_<=0?ye(L,_):R!==void 0?typeof U=="string"?ye(L,_).fill(R,U):ye(L,_).fill(R):ye(L,_)}ne.alloc=function(L,_,R){return ot(null,L,_,R)};function Mt(L,_){if(ee(_),L=ye(L,_<0?0:Ft(_)|0),!ne.TYPED_ARRAY_SUPPORT)for(var R=0;R<_;++R)L[R]=0;return L}ne.allocUnsafe=function(L){return Mt(null,L)},ne.allocUnsafeSlow=function(L){return Mt(null,L)};function tt(L,_,R){if((typeof R!="string"||R==="")&&(R="utf8"),!ne.isEncoding(R))throw new TypeError('"encoding" must be a valid string encoding');var U=Pt(_,R)|0;L=ye(L,U);var $=L.write(_,R);return $!==U&&(L=L.slice(0,$)),L}function Ve(L,_){var R=_.length<0?0:Ft(_.length)|0;L=ye(L,R);for(var U=0;U<R;U+=1)L[U]=_[U]&255;return L}function st(L,_,R,U){if(_.byteLength,R<0||_.byteLength<R)throw new RangeError("'offset' is out of bounds");if(_.byteLength<R+(U||0))throw new RangeError("'length' is out of bounds");return R===void 0&&U===void 0?_=new Uint8Array(_):U===void 0?_=new Uint8Array(_,R):_=new Uint8Array(_,R,U),ne.TYPED_ARRAY_SUPPORT?(L=_,L.__proto__=ne.prototype):L=Ve(L,_),L}function Ct(L,_){if(ne.isBuffer(_)){var R=Ft(_.length)|0;return L=ye(L,R),L.length===0||_.copy(L,0,0,R),L}if(_){if(typeof ArrayBuffer!="undefined"&&_.buffer instanceof ArrayBuffer||"length"in _)return typeof _.length!="number"||Rn(_.length)?ye(L,0):Ve(L,_);if(_.type==="Buffer"&&mt(_.data))return Ve(L,_.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function Ft(L){if(L>=ve())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+ve().toString(16)+" bytes");return L|0}function xn(L){return+L!=L&&(L=0),ne.alloc(+L)}ne.isBuffer=function(_){return!!(_!=null&&_._isBuffer)},ne.compare=function(_,R){if(!ne.isBuffer(_)||!ne.isBuffer(R))throw new TypeError("Arguments must be Buffers");if(_===R)return 0;for(var U=_.length,$=R.length,de=0,xe=Math.min(U,$);de<xe;++de)if(_[de]!==R[de]){U=_[de],$=R[de];break}return U<$?-1:$<U?1:0},ne.isEncoding=function(_){switch(String(_).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},ne.concat=function(_,R){if(!mt(_))throw new TypeError('"list" argument must be an Array of Buffers');if(_.length===0)return ne.alloc(0);var U;if(R===void 0)for(R=0,U=0;U<_.length;++U)R+=_[U].length;var $=ne.allocUnsafe(R),de=0;for(U=0;U<_.length;++U){var xe=_[U];if(!ne.isBuffer(xe))throw new TypeError('"list" argument must be an Array of Buffers');xe.copy($,de),de+=xe.length}return $};function Pt(L,_){if(ne.isBuffer(L))return L.length;if(typeof ArrayBuffer!="undefined"&&typeof ArrayBuffer.isView=="function"&&(ArrayBuffer.isView(L)||L instanceof ArrayBuffer))return L.byteLength;typeof L!="string"&&(L=""+L);var R=L.length;if(R===0)return 0;for(var U=!1;;)switch(_){case"ascii":case"latin1":case"binary":return R;case"utf8":case"utf-8":case void 0:return $t(L).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R*2;case"hex":return R>>>1;case"base64":return et(L).length;default:if(U)return $t(L).length;_=(""+_).toLowerCase(),U=!0}}ne.byteLength=Pt;function dn(L,_,R){var U=!1;if((_===void 0||_<0)&&(_=0),_>this.length)return"";if((R===void 0||R>this.length)&&(R=this.length),R<=0)return"";if(R>>>=0,_>>>=0,R<=_)return"";for(L||(L="utf8");;)switch(L){case"hex":return q(this,_,R);case"utf8":case"utf-8":return Oe(this,_,R);case"ascii":return k(this,_,R);case"latin1":case"binary":return Qe(this,_,R);case"base64":return ae(this,_,R);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return lt(this,_,R);default:if(U)throw new TypeError("Unknown encoding: "+L);L=(L+"").toLowerCase(),U=!0}}ne.prototype._isBuffer=!0;function Pe(L,_,R){var U=L[_];L[_]=L[R],L[R]=U}ne.prototype.swap16=function(){var _=this.length;if(_%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var R=0;R<_;R+=2)Pe(this,R,R+1);return this},ne.prototype.swap32=function(){var _=this.length;if(_%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var R=0;R<_;R+=4)Pe(this,R,R+3),Pe(this,R+1,R+2);return this},ne.prototype.swap64=function(){var _=this.length;if(_%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var R=0;R<_;R+=8)Pe(this,R,R+7),Pe(this,R+1,R+6),Pe(this,R+2,R+5),Pe(this,R+3,R+4);return this},ne.prototype.toString=function(){var _=this.length|0;return _===0?"":arguments.length===0?Oe(this,0,_):dn.apply(this,arguments)},ne.prototype.equals=function(_){if(!ne.isBuffer(_))throw new TypeError("Argument must be a Buffer");return this===_?!0:ne.compare(this,_)===0},ne.prototype.inspect=function(){var _="",R=ke.INSPECT_MAX_BYTES;return this.length>0&&(_=this.toString("hex",0,R).match(/.{2}/g).join(" "),this.length>R&&(_+=" ... ")),"<Buffer "+_+">"},ne.prototype.compare=function(_,R,U,$,de){if(!ne.isBuffer(_))throw new TypeError("Argument must be a Buffer");if(R===void 0&&(R=0),U===void 0&&(U=_?_.length:0),$===void 0&&($=0),de===void 0&&(de=this.length),R<0||U>_.length||$<0||de>this.length)throw new RangeError("out of range index");if($>=de&&R>=U)return 0;if($>=de)return-1;if(R>=U)return 1;if(R>>>=0,U>>>=0,$>>>=0,de>>>=0,this===_)return 0;for(var xe=de-$,ut=U-R,Rt=Math.min(xe,ut),Ut=this.slice($,de),pn=_.slice(R,U),qt=0;qt<Rt;++qt)if(Ut[qt]!==pn[qt]){xe=Ut[qt],ut=pn[qt];break}return xe<ut?-1:ut<xe?1:0};function Ge(L,_,R,U,$){if(L.length===0)return-1;if(typeof R=="string"?(U=R,R=0):R>2147483647?R=2147483647:R<-2147483648&&(R=-2147483648),R=+R,isNaN(R)&&(R=$?0:L.length-1),R<0&&(R=L.length+R),R>=L.length){if($)return-1;R=L.length-1}else if(R<0)if($)R=0;else return-1;if(typeof _=="string"&&(_=ne.from(_,U)),ne.isBuffer(_))return _.length===0?-1:ce(L,_,R,U,$);if(typeof _=="number")return _=_&255,ne.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf=="function"?$?Uint8Array.prototype.indexOf.call(L,_,R):Uint8Array.prototype.lastIndexOf.call(L,_,R):ce(L,[_],R,U,$);throw new TypeError("val must be string, number or Buffer")}function ce(L,_,R,U,$){var de=1,xe=L.length,ut=_.length;if(U!==void 0&&(U=String(U).toLowerCase(),U==="ucs2"||U==="ucs-2"||U==="utf16le"||U==="utf-16le")){if(L.length<2||_.length<2)return-1;de=2,xe/=2,ut/=2,R/=2}function Rt(ba,Un){return de===1?ba[Un]:ba.readUInt16BE(Un*de)}var Ut;if($){var pn=-1;for(Ut=R;Ut<xe;Ut++)if(Rt(L,Ut)===Rt(_,pn===-1?0:Ut-pn)){if(pn===-1&&(pn=Ut),Ut-pn+1===ut)return pn*de}else pn!==-1&&(Ut-=Ut-pn),pn=-1}else for(R+ut>xe&&(R=xe-ut),Ut=R;Ut>=0;Ut--){for(var qt=!0,Jr=0;Jr<ut;Jr++)if(Rt(L,Ut+Jr)!==Rt(_,Jr)){qt=!1;break}if(qt)return Ut}return-1}ne.prototype.includes=function(_,R,U){return this.indexOf(_,R,U)!==-1},ne.prototype.indexOf=function(_,R,U){return Ge(this,_,R,U,!0)},ne.prototype.lastIndexOf=function(_,R,U){return Ge(this,_,R,U,!1)};function Ye(L,_,R,U){R=Number(R)||0;var $=L.length-R;U?(U=Number(U),U>$&&(U=$)):U=$;var de=_.length;if(de%2!==0)throw new TypeError("Invalid hex string");U>de/2&&(U=de/2);for(var xe=0;xe<U;++xe){var ut=parseInt(_.substr(xe*2,2),16);if(isNaN(ut))return xe;L[R+xe]=ut}return xe}function ie(L,_,R,U){return gn($t(_,L.length-R),L,R,U)}function D(L,_,R,U){return gn(En(_),L,R,U)}function se(L,_,R,U){return D(L,_,R,U)}function Te(L,_,R,U){return gn(et(_),L,R,U)}function Ae(L,_,R,U){return gn(ar(_,L.length-R),L,R,U)}ne.prototype.write=function(_,R,U,$){if(R===void 0)$="utf8",U=this.length,R=0;else if(U===void 0&&typeof R=="string")$=R,U=this.length,R=0;else if(isFinite(R))R=R|0,isFinite(U)?(U=U|0,$===void 0&&($="utf8")):($=U,U=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var de=this.length-R;if((U===void 0||U>de)&&(U=de),_.length>0&&(U<0||R<0)||R>this.length)throw new RangeError("Attempt to write outside buffer bounds");$||($="utf8");for(var xe=!1;;)switch($){case"hex":return Ye(this,_,R,U);case"utf8":case"utf-8":return ie(this,_,R,U);case"ascii":return D(this,_,R,U);case"latin1":case"binary":return se(this,_,R,U);case"base64":return Te(this,_,R,U);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Ae(this,_,R,U);default:if(xe)throw new TypeError("Unknown encoding: "+$);$=(""+$).toLowerCase(),xe=!0}},ne.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function ae(L,_,R){return _===0&&R===L.length?ze.fromByteArray(L):ze.fromByteArray(L.slice(_,R))}function Oe(L,_,R){R=Math.min(L.length,R);for(var U=[],$=_;$<R;){var de=L[$],xe=null,ut=de>239?4:de>223?3:de>191?2:1;if($+ut<=R){var Rt,Ut,pn,qt;switch(ut){case 1:de<128&&(xe=de);break;case 2:Rt=L[$+1],(Rt&192)===128&&(qt=(de&31)<<6|Rt&63,qt>127&&(xe=qt));break;case 3:Rt=L[$+1],Ut=L[$+2],(Rt&192)===128&&(Ut&192)===128&&(qt=(de&15)<<12|(Rt&63)<<6|Ut&63,qt>2047&&(qt<55296||qt>57343)&&(xe=qt));break;case 4:Rt=L[$+1],Ut=L[$+2],pn=L[$+3],(Rt&192)===128&&(Ut&192)===128&&(pn&192)===128&&(qt=(de&15)<<18|(Rt&63)<<12|(Ut&63)<<6|pn&63,qt>65535&&qt<1114112&&(xe=qt))}}xe===null?(xe=65533,ut=1):xe>65535&&(xe-=65536,U.push(xe>>>10&1023|55296),xe=56320|xe&1023),U.push(xe),$+=ut}return Qt(U)}var Be=4096;function Qt(L){var _=L.length;if(_<=Be)return String.fromCharCode.apply(String,L);for(var R="",U=0;U<_;)R+=String.fromCharCode.apply(String,L.slice(U,U+=Be));return R}function k(L,_,R){var U="";R=Math.min(L.length,R);for(var $=_;$<R;++$)U+=String.fromCharCode(L[$]&127);return U}function Qe(L,_,R){var U="";R=Math.min(L.length,R);for(var $=_;$<R;++$)U+=String.fromCharCode(L[$]);return U}function q(L,_,R){var U=L.length;(!_||_<0)&&(_=0),(!R||R<0||R>U)&&(R=U);for(var $="",de=_;de<R;++de)$+=wn(L[de]);return $}function lt(L,_,R){for(var U=L.slice(_,R),$="",de=0;de<U.length;de+=2)$+=String.fromCharCode(U[de]+U[de+1]*256);return $}ne.prototype.slice=function(_,R){var U=this.length;_=~~_,R=R===void 0?U:~~R,_<0?(_+=U,_<0&&(_=0)):_>U&&(_=U),R<0?(R+=U,R<0&&(R=0)):R>U&&(R=U),R<_&&(R=_);var $;if(ne.TYPED_ARRAY_SUPPORT)$=this.subarray(_,R),$.__proto__=ne.prototype;else{var de=R-_;$=new ne(de,void 0);for(var xe=0;xe<de;++xe)$[xe]=this[xe+_]}return $};function je(L,_,R){if(L%1!==0||L<0)throw new RangeError("offset is not uint");if(L+_>R)throw new RangeError("Trying to access beyond buffer length")}ne.prototype.readUIntLE=function(_,R,U){_=_|0,R=R|0,U||je(_,R,this.length);for(var $=this[_],de=1,xe=0;++xe<R&&(de*=256);)$+=this[_+xe]*de;return $},ne.prototype.readUIntBE=function(_,R,U){_=_|0,R=R|0,U||je(_,R,this.length);for(var $=this[_+--R],de=1;R>0&&(de*=256);)$+=this[_+--R]*de;return $},ne.prototype.readUInt8=function(_,R){return R||je(_,1,this.length),this[_]},ne.prototype.readUInt16LE=function(_,R){return R||je(_,2,this.length),this[_]|this[_+1]<<8},ne.prototype.readUInt16BE=function(_,R){return R||je(_,2,this.length),this[_]<<8|this[_+1]},ne.prototype.readUInt32LE=function(_,R){return R||je(_,4,this.length),(this[_]|this[_+1]<<8|this[_+2]<<16)+this[_+3]*16777216},ne.prototype.readUInt32BE=function(_,R){return R||je(_,4,this.length),this[_]*16777216+(this[_+1]<<16|this[_+2]<<8|this[_+3])},ne.prototype.readIntLE=function(_,R,U){_=_|0,R=R|0,U||je(_,R,this.length);for(var $=this[_],de=1,xe=0;++xe<R&&(de*=256);)$+=this[_+xe]*de;return de*=128,$>=de&&($-=Math.pow(2,8*R)),$},ne.prototype.readIntBE=function(_,R,U){_=_|0,R=R|0,U||je(_,R,this.length);for(var $=R,de=1,xe=this[_+--$];$>0&&(de*=256);)xe+=this[_+--$]*de;return de*=128,xe>=de&&(xe-=Math.pow(2,8*R)),xe},ne.prototype.readInt8=function(_,R){return R||je(_,1,this.length),this[_]&128?(255-this[_]+1)*-1:this[_]},ne.prototype.readInt16LE=function(_,R){R||je(_,2,this.length);var U=this[_]|this[_+1]<<8;return U&32768?U|4294901760:U},ne.prototype.readInt16BE=function(_,R){R||je(_,2,this.length);var U=this[_+1]|this[_]<<8;return U&32768?U|4294901760:U},ne.prototype.readInt32LE=function(_,R){return R||je(_,4,this.length),this[_]|this[_+1]<<8|this[_+2]<<16|this[_+3]<<24},ne.prototype.readInt32BE=function(_,R){return R||je(_,4,this.length),this[_]<<24|this[_+1]<<16|this[_+2]<<8|this[_+3]},ne.prototype.readFloatLE=function(_,R){return R||je(_,4,this.length),at.read(this,_,!0,23,4)},ne.prototype.readFloatBE=function(_,R){return R||je(_,4,this.length),at.read(this,_,!1,23,4)},ne.prototype.readDoubleLE=function(_,R){return R||je(_,8,this.length),at.read(this,_,!0,52,8)},ne.prototype.readDoubleBE=function(_,R){return R||je(_,8,this.length),at.read(this,_,!1,52,8)};function St(L,_,R,U,$,de){if(!ne.isBuffer(L))throw new TypeError('"buffer" argument must be a Buffer instance');if(_>$||_<de)throw new RangeError('"value" argument is out of bounds');if(R+U>L.length)throw new RangeError("Index out of range")}ne.prototype.writeUIntLE=function(_,R,U,$){if(_=+_,R=R|0,U=U|0,!$){var de=Math.pow(2,8*U)-1;St(this,_,R,U,de,0)}var xe=1,ut=0;for(this[R]=_&255;++ut<U&&(xe*=256);)this[R+ut]=_/xe&255;return R+U},ne.prototype.writeUIntBE=function(_,R,U,$){if(_=+_,R=R|0,U=U|0,!$){var de=Math.pow(2,8*U)-1;St(this,_,R,U,de,0)}var xe=U-1,ut=1;for(this[R+xe]=_&255;--xe>=0&&(ut*=256);)this[R+xe]=_/ut&255;return R+U},ne.prototype.writeUInt8=function(_,R,U){return _=+_,R=R|0,U||St(this,_,R,1,255,0),ne.TYPED_ARRAY_SUPPORT||(_=Math.floor(_)),this[R]=_&255,R+1};function Cn(L,_,R,U){_<0&&(_=65535+_+1);for(var $=0,de=Math.min(L.length-R,2);$<de;++$)L[R+$]=(_&255<<8*(U?$:1-$))>>>(U?$:1-$)*8}ne.prototype.writeUInt16LE=function(_,R,U){return _=+_,R=R|0,U||St(this,_,R,2,65535,0),ne.TYPED_ARRAY_SUPPORT?(this[R]=_&255,this[R+1]=_>>>8):Cn(this,_,R,!0),R+2},ne.prototype.writeUInt16BE=function(_,R,U){return _=+_,R=R|0,U||St(this,_,R,2,65535,0),ne.TYPED_ARRAY_SUPPORT?(this[R]=_>>>8,this[R+1]=_&255):Cn(this,_,R,!1),R+2};function bn(L,_,R,U){_<0&&(_=4294967295+_+1);for(var $=0,de=Math.min(L.length-R,4);$<de;++$)L[R+$]=_>>>(U?$:3-$)*8&255}ne.prototype.writeUInt32LE=function(_,R,U){return _=+_,R=R|0,U||St(this,_,R,4,4294967295,0),ne.TYPED_ARRAY_SUPPORT?(this[R+3]=_>>>24,this[R+2]=_>>>16,this[R+1]=_>>>8,this[R]=_&255):bn(this,_,R,!0),R+4},ne.prototype.writeUInt32BE=function(_,R,U){return _=+_,R=R|0,U||St(this,_,R,4,4294967295,0),ne.TYPED_ARRAY_SUPPORT?(this[R]=_>>>24,this[R+1]=_>>>16,this[R+2]=_>>>8,this[R+3]=_&255):bn(this,_,R,!1),R+4},ne.prototype.writeIntLE=function(_,R,U,$){if(_=+_,R=R|0,!$){var de=Math.pow(2,8*U-1);St(this,_,R,U,de-1,-de)}var xe=0,ut=1,Rt=0;for(this[R]=_&255;++xe<U&&(ut*=256);)_<0&&Rt===0&&this[R+xe-1]!==0&&(Rt=1),this[R+xe]=(_/ut>>0)-Rt&255;return R+U},ne.prototype.writeIntBE=function(_,R,U,$){if(_=+_,R=R|0,!$){var de=Math.pow(2,8*U-1);St(this,_,R,U,de-1,-de)}var xe=U-1,ut=1,Rt=0;for(this[R+xe]=_&255;--xe>=0&&(ut*=256);)_<0&&Rt===0&&this[R+xe+1]!==0&&(Rt=1),this[R+xe]=(_/ut>>0)-Rt&255;return R+U},ne.prototype.writeInt8=function(_,R,U){return _=+_,R=R|0,U||St(this,_,R,1,127,-128),ne.TYPED_ARRAY_SUPPORT||(_=Math.floor(_)),_<0&&(_=255+_+1),this[R]=_&255,R+1},ne.prototype.writeInt16LE=function(_,R,U){return _=+_,R=R|0,U||St(this,_,R,2,32767,-32768),ne.TYPED_ARRAY_SUPPORT?(this[R]=_&255,this[R+1]=_>>>8):Cn(this,_,R,!0),R+2},ne.prototype.writeInt16BE=function(_,R,U){return _=+_,R=R|0,U||St(this,_,R,2,32767,-32768),ne.TYPED_ARRAY_SUPPORT?(this[R]=_>>>8,this[R+1]=_&255):Cn(this,_,R,!1),R+2},ne.prototype.writeInt32LE=function(_,R,U){return _=+_,R=R|0,U||St(this,_,R,4,2147483647,-2147483648),ne.TYPED_ARRAY_SUPPORT?(this[R]=_&255,this[R+1]=_>>>8,this[R+2]=_>>>16,this[R+3]=_>>>24):bn(this,_,R,!0),R+4},ne.prototype.writeInt32BE=function(_,R,U){return _=+_,R=R|0,U||St(this,_,R,4,2147483647,-2147483648),_<0&&(_=4294967295+_+1),ne.TYPED_ARRAY_SUPPORT?(this[R]=_>>>24,this[R+1]=_>>>16,this[R+2]=_>>>8,this[R+3]=_&255):bn(this,_,R,!1),R+4};function On(L,_,R,U,$,de){if(R+U>L.length)throw new RangeError("Index out of range");if(R<0)throw new RangeError("Index out of range")}function xr(L,_,R,U,$){return $||On(L,_,R,4,34028234663852886e22,-34028234663852886e22),at.write(L,_,R,U,23,4),R+4}ne.prototype.writeFloatLE=function(_,R,U){return xr(this,_,R,!0,U)},ne.prototype.writeFloatBE=function(_,R,U){return xr(this,_,R,!1,U)};function tr(L,_,R,U,$){return $||On(L,_,R,8,17976931348623157e292,-17976931348623157e292),at.write(L,_,R,U,52,8),R+8}ne.prototype.writeDoubleLE=function(_,R,U){return tr(this,_,R,!0,U)},ne.prototype.writeDoubleBE=function(_,R,U){return tr(this,_,R,!1,U)},ne.prototype.copy=function(_,R,U,$){if(U||(U=0),!$&&$!==0&&($=this.length),R>=_.length&&(R=_.length),R||(R=0),$>0&&$<U&&($=U),$===U)return 0;if(_.length===0||this.length===0)return 0;if(R<0)throw new RangeError("targetStart out of bounds");if(U<0||U>=this.length)throw new RangeError("sourceStart out of bounds");if($<0)throw new RangeError("sourceEnd out of bounds");$>this.length&&($=this.length),_.length-R<$-U&&($=_.length-R+U);var de=$-U,xe;if(this===_&&U<R&&R<$)for(xe=de-1;xe>=0;--xe)_[xe+R]=this[xe+U];else if(de<1e3||!ne.TYPED_ARRAY_SUPPORT)for(xe=0;xe<de;++xe)_[xe+R]=this[xe+U];else Uint8Array.prototype.set.call(_,this.subarray(U,U+de),R);return de},ne.prototype.fill=function(_,R,U,$){if(typeof _=="string"){if(typeof R=="string"?($=R,R=0,U=this.length):typeof U=="string"&&($=U,U=this.length),_.length===1){var de=_.charCodeAt(0);de<256&&(_=de)}if($!==void 0&&typeof $!="string")throw new TypeError("encoding must be a string");if(typeof $=="string"&&!ne.isEncoding($))throw new TypeError("Unknown encoding: "+$)}else typeof _=="number"&&(_=_&255);if(R<0||this.length<R||this.length<U)throw new RangeError("Out of range index");if(U<=R)return this;R=R>>>0,U=U===void 0?this.length:U>>>0,_||(_=0);var xe;if(typeof _=="number")for(xe=R;xe<U;++xe)this[xe]=_;else{var ut=ne.isBuffer(_)?_:$t(new ne(_,$).toString()),Rt=ut.length;for(xe=0;xe<U-R;++xe)this[xe+R]=ut[xe%Rt]}return this};var Xt=/[^+\/0-9A-Za-z-_]/g;function nr(L){if(L=rr(L).replace(Xt,""),L.length<2)return"";for(;L.length%4!==0;)L=L+"=";return L}function rr(L){return L.trim?L.trim():L.replace(/^\s+|\s+$/g,"")}function wn(L){return L<16?"0"+L.toString(16):L.toString(16)}function $t(L,_){_=_||Infinity;for(var R,U=L.length,$=null,de=[],xe=0;xe<U;++xe){if(R=L.charCodeAt(xe),R>55295&&R<57344){if(!$){if(R>56319){(_-=3)>-1&&de.push(239,191,189);continue}else if(xe+1===U){(_-=3)>-1&&de.push(239,191,189);continue}$=R;continue}if(R<56320){(_-=3)>-1&&de.push(239,191,189),$=R;continue}R=($-55296<<10|R-56320)+65536}else $&&((_-=3)>-1&&de.push(239,191,189));if($=null,R<128){if((_-=1)<0)break;de.push(R)}else if(R<2048){if((_-=2)<0)break;de.push(R>>6|192,R&63|128)}else if(R<65536){if((_-=3)<0)break;de.push(R>>12|224,R>>6&63|128,R&63|128)}else if(R<1114112){if((_-=4)<0)break;de.push(R>>18|240,R>>12&63|128,R>>6&63|128,R&63|128)}else throw new Error("Invalid code point")}return de}function En(L){for(var _=[],R=0;R<L.length;++R)_.push(L.charCodeAt(R)&255);return _}function ar(L,_){for(var R,U,$,de=[],xe=0;xe<L.length&&!((_-=2)<0);++xe)R=L.charCodeAt(xe),U=R>>8,$=R%256,de.push($),de.push(U);return de}function et(L){return ze.toByteArray(nr(L))}function gn(L,_,R,U){for(var $=0;$<U&&!($+R>=_.length||$>=L.length);++$)_[$+R]=L[$];return $}function Rn(L){return L!==L}}).call(this,te("IyRk"))},IO3U:function(rn,ke,te){rn.exports={wrp:"wrp___1U2de"}},Og1z:function(rn,ke){(function(te){rn.exports=function(){var Se={887:function(){}},ze={};function at(mt){if(ze[mt])return ze[mt].exports;var Ke=ze[mt]={exports:{}},ve=!0;try{Se[mt](Ke,Ke.exports,at),ve=!1}finally{ve&&delete ze[mt]}return Ke.exports}return at.ab=te+"/",at(887)}()}).call(this,"/")},"Re/O":function(rn,ke,te){"use strict";(function(Se,ze,at){te.d(ke,"a",function(){return fn}),te.d(ke,"b",function(){return Fr}),te.d(ke,"c",function(){return La}),te.d(ke,"d",function(){return dl}),te.d(ke,"e",function(){return Xc}),te.d(ke,"f",function(){return zf}),te.d(ke,"g",function(){return jc}),te.d(ke,"h",function(){return Qn}),te.d(ke,"i",function(){return xo}),te.d(ke,"j",function(){return os}),te.d(ke,"k",function(){return rs}),te.d(ke,"l",function(){return Uc}),te.d(ke,"m",function(){return gr}),te.d(ke,"n",function(){return qo}),te.d(ke,"o",function(){return Al}),te.d(ke,"p",function(){return jf}),te.d(ke,"q",function(){return uu}),te.d(ke,"r",function(){return fl}),te.d(ke,"s",function(){return ll}),te.d(ke,"t",function(){return Ba}),te.d(ke,"u",function(){return ru}),te.d(ke,"v",function(){return Rr}),te.d(ke,"w",function(){return cu}),te.d(ke,"x",function(){return uo}),te.d(ke,"y",function(){return We}),te.d(ke,"z",function(){return sl}),te.d(ke,"A",function(){return zc}),te.d(ke,"B",function(){return Hr}),te.d(ke,"C",function(){return hl}),te.d(ke,"D",function(){return Sa}),te.d(ke,"E",function(){return Ar}),te.d(ke,"F",function(){return va}),te.d(ke,"G",function(){return _n}),te.d(ke,"H",function(){return Ur}),te.d(ke,"I",function(){return Wr}),te.d(ke,"J",function(){return Ko}),te.d(ke,"K",function(){return Er}),te.d(ke,"L",function(){return en}),te.d(ke,"M",function(){return zr}),te.d(ke,"N",function(){return xl}),te.d(ke,"O",function(){return co}),te.d(ke,"P",function(){return Jt});/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/var mt=function(r,n){return(mt=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var a in t)t.hasOwnProperty(a)&&(e[a]=t[a])})(r,n)};function Ke(r,n){function e(){this.constructor=r}mt(r,n),r.prototype=n===null?Object.create(n):(e.prototype=n.prototype,new e)}function ve(r,n,e,t){return new(e||(e=Promise))(function(a,o){function i(c){try{u(t.next(c))}catch(d){o(d)}}function s(c){try{u(t.throw(c))}catch(d){o(d)}}function u(c){c.done?a(c.value):new e(function(d){d(c.value)}).then(i,s)}u((t=t.apply(r,n||[])).next())})}function ye(r,n){var e,t,a,o,i={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function s(u){return function(c){return function(d){if(e)throw new TypeError("Generator is already executing.");for(;i;)try{if(e=1,t&&(a=2&d[0]?t.return:d[0]?t.throw||((a=t.return)&&a.call(t),0):t.next)&&!(a=a.call(t,d[1])).done)return a;switch(t=0,a&&(d=[2&d[0],a.value]),d[0]){case 0:case 1:a=d;break;case 4:return i.label++,{value:d[1],done:!1};case 5:i.label++,t=d[1],d=[0];continue;case 7:d=i.ops.pop(),i.trys.pop();continue;default:if(!(a=(a=i.trys).length>0&&a[a.length-1])&&(d[0]===6||d[0]===2)){i=0;continue}if(d[0]===3&&(!a||d[1]>a[0]&&d[1]<a[3])){i.label=d[1];break}if(d[0]===6&&i.label<a[1]){i.label=a[1],a=d;break}if(a&&i.label<a[2]){i.label=a[2],i.ops.push(d);break}a[2]&&i.ops.pop(),i.trys.pop();continue}d=n.call(r,i)}catch(f){d=[6,f],t=0}finally{e=a=0}if(5&d[0])throw d[1];return{value:d[0]?d[1]:void 0,done:!0}}([u,c])}}}var ne=function(){function r(n){this.global=n,this.flags={},this.flagRegistry={},this.urlFlags={},this.populateURLFlags()}return r.prototype.setPlatform=function(n,e){this.platform!=null&&console.warn("Platform "+this.platformName+" has already been set. Overwriting the platform with "+e+"."),this.platformName=n,this.platform=e},r.prototype.registerFlag=function(n,e,t){if(this.flagRegistry[n]={evaluationFn:e,setHook:t},this.urlFlags[n]!=null){var a=this.urlFlags[n];console.warn("Setting feature override from URL "+n+": "+a+"."),this.set(n,a)}},r.prototype.get=function(n){return n in this.flags?this.flags[n]:(this.flags[n]=this.evaluateFlag(n),this.flags[n])},r.prototype.getNumber=function(n){return this.get(n)},r.prototype.getBool=function(n){return this.get(n)},r.prototype.getFlags=function(){return this.flags},Object.defineProperty(r.prototype,"features",{get:function(){return this.flags},enumerable:!0,configurable:!0}),r.prototype.set=function(n,e){if(this.flagRegistry[n]==null)throw new Error("Cannot set flag "+n+" as it has not been registered.");this.flags[n]=e,this.flagRegistry[n].setHook!=null&&this.flagRegistry[n].setHook(e)},r.prototype.evaluateFlag=function(n){if(this.flagRegistry[n]==null)throw new Error("Cannot evaluate flag '"+n+"': no evaluation function found.");return this.flagRegistry[n].evaluationFn()},r.prototype.setFlags=function(n){this.flags=Object.assign({},n)},r.prototype.reset=function(){this.flags={},this.urlFlags={},this.populateURLFlags()},r.prototype.populateURLFlags=function(){var n=this;if(this.global!==void 0&&this.global.location!==void 0&&this.global.location.search!==void 0){var e,t,a=(e=this.global.location.search,t={},e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,function(o){for(var i=[],s=1;s<arguments.length;s++)i[s-1]=arguments[s];return kt(t,i[0],i[1]),i.join("=")}),t);"tfjsflags"in a&&a.tfjsflags.split(",").forEach(function(o){var i=o.split(":"),s=i[0],u=i[1];n.urlFlags[s]=function(c,d){if((d=d.toLowerCase())==="true"||d==="false")return d==="true";if(""+ +d===d)return+d;throw new Error("Could not parse value flag value "+d+" for flag "+c+".")}(s,u)})}},r}();function kt(r,n,e){r[decodeURIComponent(n)]=decodeURIComponent(e||"")}function ee(){return ot}var ot=null,Mt=new Map,tt=new Map;function Ve(r,n){var e=Pe(r,n);return Mt.get(e)}function st(r){return tt.get(r)}function Ct(r){for(var n=Mt.entries(),e=[];;){var t=n.next(),a=t.done,o=t.value;if(a)break;var i=o[0],s=o[1];i.split("_")[0]===r&&e.push(s)}return e}function Ft(r){var n=r.kernelName,e=r.backendName,t=Pe(n,e);if(Mt.has(t))throw new Error("The kernel '"+n+"' for backend '"+e+"' is already registered");Mt.set(t,r)}function xn(r){var n=r.kernelName;tt.has(n)&&console.warn("Overriding the gradient for '"+n+"'"),tt.set(n,r)}function Pt(r,n){var e=Pe(r,n);if(!Mt.has(e))throw new Error("The kernel '"+r+"' for backend '"+n+"' is not registered");Mt.delete(e)}function dn(r){if(!tt.has(r))throw new Error("The gradient '"+r+"' for backend is not registered");tt.delete(r)}function Pe(r,n){return n+"_"+r}function Ge(r){for(var n=r.length,e=0,t=0;n>0;)t=Math.random()*n|0,e=r[--n],r[n]=r[t],r[t]=e}function ce(r,n,e){return Math.max(r,Math.min(n,e))}function Ye(r){return r%2==0?r:r+1}function ie(r){for(var n=0,e=0;e<r.length;e++)n+=r[e];return n}function D(r,n){if(!r)throw new Error(typeof n=="string"?n:n())}function se(r,n,e){e===void 0&&(e=""),D(Oe(r,n),function(){return e+" Shapes "+r+" and "+n+" must match"})}function Te(r){D(r!=null,function(){return"The input to the tensor constructor must be a non-null value."})}function Ae(r,n,e){if(n===void 0&&(n=[]),e===void 0&&(e=!1),n==null&&(n=[]),Array.isArray(r)||Xt(r)&&!e)for(var t=0;t<r.length;++t)Ae(r[t],n,e);else n.push(r);return n}function ae(r){if(r.length===0)return 1;for(var n=r[0],e=1;e<r.length;e++)n*=r[e];return n}function Oe(r,n){if(r===n)return!0;if(r==null||n==null)return!1;if(r.length!==n.length)return!1;for(var e=0;e<r.length;e++)if(r[e]!==n[e])return!1;return!0}function Be(r){return r%1==0}function Qt(r){if(Math.tanh!=null)return Math.tanh(r);if(r===1/0)return 1;if(r===-1/0)return-1;var n=Math.exp(2*r);return(n-1)/(n+1)}function k(r){var n=Math.ceil(Math.sqrt(r));return[n,Math.ceil(r/n)]}function Qe(r,n){return n<=r.length?r:r+" ".repeat(n-r.length)}function q(r,n,e){return n===void 0&&(n=function(t){return 0}),new Promise(function(t,a){var o=0,i=function(){if(r())t();else{o++;var s=n(o);e!=null&&o>=e?a():setTimeout(i,s)}};i()})}function lt(r,n){for(var e=1,t=-1,a=0;a<r.length;++a)if(r[a]>=0)e*=r[a];else if(r[a]===-1){if(t!==-1)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+t+" and dim "+a);t=a}else if(r[a]<0)throw Error("Shapes can not be < 0. Found "+r[a]+" at dim "+a);if(t===-1){if(n>0&&n!==e)throw Error("Size("+n+") must match the product of shape "+r);return r}if(e===0)throw Error("Cannot infer the missing size in ["+r+"] when there are 0 elements");if(n%e!=0)throw Error("The implicit shape can't be a fractional number. Got "+n+" / "+e);var o=r.slice();return o[t]=n/e,o}function je(r,n){var e=n.length;return D((r=r==null?n.map(function(t,a){return a}):[].concat(r)).every(function(t){return t>=-e&&t<e}),function(){return"All values in axis param must be in range [-"+e+", "+e+") but got axis "+r}),D(r.every(function(t){return Be(t)}),function(){return"All values in axis param must be integers but got axis "+r}),r.map(function(t){return t<0?e+t:t})}function St(r,n){for(var e=[],t=[],a=n!=null&&Array.isArray(n)&&n.length===0,o=n==null||a?null:je(n,r).sort(),i=0,s=0;s<r.length;++s){if(o!=null){if(o[i]===s&&r[s]!==1)throw new Error("Can't squeeze axis "+s+" since its dim '"+r[s]+"' is not 1");(o[i]==null||o[i]>s)&&r[s]===1&&(e.push(r[s]),t.push(s)),o[i]<=s&&i++}r[s]!==1&&(e.push(r[s]),t.push(s))}return{newShape:e,keptDims:t}}function Cn(r,n){var e=null;if(r==null||r==="float32")e=new Float32Array(n);else if(r==="int32")e=new Int32Array(n);else{if(r!=="bool")throw new Error("Unknown data type "+r);e=new Uint8Array(n)}return e}function bn(r,n){var e=null;if(r==null||r==="float32")e=new Float32Array(n);else if(r==="int32")e=new Int32Array(n);else if(r==="bool")e=new Uint8Array(n);else{if(r!=="string")throw new Error("Unknown data type "+r);e=new Array(n)}return e}function On(r,n){for(var e=0;e<r.length;e++){var t=r[e];if(isNaN(t)||!isFinite(t))throw Error("A tensor of type "+n+" being uploaded contains "+t+".")}}function xr(r){return r==="bool"||r==="complex64"||r==="float32"||r==="int32"||r==="string"}function tr(r,n){return n!=="complex64"&&((n!=="float32"||r==="complex64")&&(n!=="int32"||r==="float32"||r==="complex64"))&&(n!=="bool"||r!=="bool")}function Xt(r){return r instanceof Float32Array||r instanceof Int32Array||r instanceof Uint8Array}function nr(r){if(r==="float32"||r==="int32")return 4;if(r==="complex64")return 8;if(r==="bool")return 1;throw new Error("Unknown dtype "+r)}function rr(r){if(r==null)return 0;var n=0;return r.forEach(function(e){return n+=e.length}),n}function wn(r){return typeof r=="string"||r instanceof String}function $t(r){return typeof r=="boolean"}function En(r){return typeof r=="number"}function ar(r){return Array.isArray(r)?ar(r[0]):r instanceof Float32Array?"float32":r instanceof Int32Array||r instanceof Uint8Array?"int32":En(r)?"float32":wn(r)?"string":$t(r)?"bool":"float32"}function et(r){return!!(r&&r.constructor&&r.call&&r.apply)}function gn(r,n){for(var e=n;e<r;++e)if(r%e==0)return e;return r}function Rn(r){var n=r.length;if(n<2)return[];var e=new Array(n-1);e[n-2]=r[n-1];for(var t=n-3;t>=0;--t)e[t]=e[t+1]*r[t+1];return e}function L(r,n,e){if(n==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(r)&&(r=Ae(r)),e&&On(r,n),function(o,i){return o instanceof Float32Array&&i==="float32"||o instanceof Int32Array&&i==="int32"||o instanceof Uint8Array&&i==="bool"}(r,n))return r;if(n==null||n==="float32"||n==="complex64")return new Float32Array(r);if(n==="int32")return new Int32Array(r);if(n==="bool"){for(var t=new Uint8Array(r.length),a=0;a<t.length;++a)Math.round(r[a])!==0&&(t[a]=1);return t}throw new Error("Unknown data type "+n)}function _(r,n){if(r.length===0)return n[0];var e=r.reduce(function(t,a){return t*a});if(e===0)return[];if(e!==n.length)throw new Error("["+r+"] does not match the input size.");return function t(a,o,i){var s=new Array;if(o.length===1)for(var u=o[0],c=0;c<u;c++)s[c]=i[a+c];else{u=o[0];var d=o.slice(1),f=d.reduce(function(m,g){return m*g});for(c=0;c<u;c++)s[c]=t(a+c*f,d,i)}return s}(0,r,n)}function R(r,n){for(var e=U(r,n),t=0;t<e.length;t++)e[t]=1;return e}function U(r,n){if(n==null||n==="float32"||n==="complex64")return new Float32Array(r);if(n==="int32")return new Int32Array(r);if(n==="bool")return new Uint8Array(r);throw new Error("Unknown data type "+n)}function $(){return ee().platform.now()}function de(r){r.forEach(function(n){D(Number.isInteger(n)&&n>=0,function(){return"Tensor must have a shape comprised of positive integers but got shape ["+r+"]."})})}function xe(r,n){return n===void 0&&(n="utf-8"),n=n||"utf-8",ee().platform.encode(r,n)}function ut(r,n){return n===void 0&&(n="utf-8"),n=n||"utf-8",ee().platform.decode(r,n)}function Rt(r,n,e){if(n===0)return 0;if(n===1)return r[0];for(var t=r[r.length-1],a=0;a<r.length-1;++a)t+=e[a]*r[a];return t}function Ut(r,n,e){if(n===0)return[];if(n===1)return[r];for(var t=new Array(n),a=0;a<t.length-1;++a)t[a]=Math.floor(r/e[a]),r-=t[a]*e[a];return t[t.length-1]=r,t}var pn=Object.freeze({shuffle:Ge,clamp:ce,nearestLargerEven:Ye,sum:ie,randUniform:function(r,n){var e=Math.random();return n*e+(1-e)*r},distSquared:function(r,n){for(var e=0,t=0;t<r.length;t++){var a=Number(r[t])-Number(n[t]);e+=a*a}return e},assert:D,assertShapesMatch:se,assertNonNull:Te,flatten:Ae,sizeFromShape:ae,isScalarShape:function(r){return r.length===0},arraysEqual:Oe,isInt:Be,tanh:Qt,sizeToSquarishShape:k,createShuffledIndices:function(r){for(var n=new Uint32Array(r),e=0;e<r;++e)n[e]=e;return Ge(n),n},rightPad:Qe,repeatedTry:q,inferFromImplicitShape:lt,parseAxisParam:je,squeezeShape:St,getTypedArrayFromDType:Cn,getArrayFromDType:bn,checkConversionForErrors:On,isValidDtype:xr,hasEncodingLoss:tr,isTypedArray:Xt,bytesPerElement:nr,bytesFromStringArray:rr,isString:wn,isBoolean:$t,isNumber:En,inferDtype:ar,isFunction:et,nearestDivisor:gn,computeStrides:Rn,toTypedArray:L,toNestedArray:_,makeOnesTypedArray:R,makeZerosTypedArray:U,now:$,assertNonNegativeIntegerDimensions:de,fetch:function(r,n){return ee().platform.fetch(r,n)},encodeString:xe,decodeString:ut,locToIndex:Rt,indexToLoc:Ut}),qt=function(){function r(n,e){this.backendTimer=n,this.logger=e,e==null&&(this.logger=new Jr)}return r.prototype.profileKernel=function(n,e,t){var a,o=this,i=this.backendTimer.time(function(){a=t()});return a.forEach(function(s){s.data().then(function(u){!function(c,d,f){if(d!=="float32")return!1;for(var m=0;m<c.length;m++){var g=c[m];if(isNaN(g)||!isFinite(g))return console.warn("Found "+g+" in the result of '"+f+"'"),!0}}(u,s.dtype,n),i.then(function(c){var d="";c.getExtraProfileInfo!=null&&(d=c.getExtraProfileInfo()),o.logger.logKernelProfile(n,s,u,c.kernelMs,e,d)})})}),a},r}(),Jr=function(){function r(){}return r.prototype.logKernelProfile=function(n,e,t,a,o,i){var s=typeof a=="number"?Qe(a+"ms",9):a.error,u=Qe(n,25),c=e.rank,d=e.size,f=Qe(e.shape.toString(),14),m="";for(var g in o){var x=o[g].shape||e.shape,E=x.length;m+=g+": "+E+"D "+(E>0?x:"")+" "}console.log("%c"+u+" %c"+s+" %c"+c+"D "+f+" %c"+d+" %c"+m+" %c"+i,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")},r}(),ba=20,Un=3,No=7;function fi(r,n,e,t){var a=Rn(n),o=function(c,d,f,m){var g=ae(d),x=m[m.length-1],E=new Array(x).fill(0),w=d.length,C=f==="complex64"?br(c):c;if(w>1)for(var N=0;N<g/x;N++)for(var S=N*x,I=0;I<x;I++)E[I]=Math.max(E[I],Qr(C[S+I],0,f).length);return E}(r,n,e,a),i=n.length,s=function c(d,f,m,g,x,E){E===void 0&&(E=!0);var w=m==="complex64"?2:1,C=f[0],N=f.length;if(N===0)return m==="complex64"?[Qr(br(d)[0],0,m)]:m==="bool"?[ko(d[0])]:[d[0].toString()];if(N===1){if(C>ba){var S=Un*w,I=Array.from(d.slice(0,S)),M=Array.from(d.slice((C-Un)*w,C*w));return m==="complex64"&&(I=br(I),M=br(M)),["["+I.map(function(he,Ee){return Qr(he,x[Ee],m)}).join(", ")+", ..., "+M.map(function(he,Ee){return Qr(he,x[C-Un+Ee],m)}).join(", ")+"]"]}return["["+(m==="complex64"?br(d):Array.from(d)).map(function(he,Ee){return Qr(he,x[Ee],m)}).join(", ")+"]"]}var j=f.slice(1),G=g.slice(1),z=g[0]*w,W=[];if(C>ba){for(var V=0;V<Un;V++){var Z=(J=V*z)+z;W.push.apply(W,c(d.slice(J,Z),j,m,G,x,!1))}for(W.push("..."),V=C-Un;V<C;V++)Z=(J=V*z)+z,W.push.apply(W,c(d.slice(J,Z),j,m,G,x,V===C-1))}else for(V=0;V<C;V++){var J;Z=(J=V*z)+z,W.push.apply(W,c(d.slice(J,Z),j,m,G,x,V===C-1))}var me=N===2?",":"";for(W[0]="["+W[0]+me,V=1;V<W.length-1;V++)W[V]=" "+W[V]+me;var fe=`,
|
|
`;for(V=2;V<N;V++)fe+=`
|
|
`;return W[W.length-1]=" "+W[W.length-1]+"]"+(E?"":fe),W}(r,n,e,a,o),u=["Tensor"];return t&&(u.push(" dtype: "+e),u.push(" rank: "+i),u.push(" shape: ["+n+"]"),u.push(" values:")),u.push(s.map(function(c){return" "+c}).join(`
|
|
`)),u.join(`
|
|
`)}function Qr(r,n,e){return Qe(Array.isArray(r)?parseFloat(r[0].toFixed(No))+" + "+parseFloat(r[1].toFixed(No))+"j":wn(r)?"'"+r+"'":e==="bool"?ko(r):parseFloat(r.toFixed(No)).toString(),n)}function ko(r){return r===0?"false":"true"}function br(r){for(var n=[],e=0;e<r.length;e+=2)n.push([r[e],r[e+1]]);return n}var za=function(){function r(n,e,t){var a=this;if(this.dtype=e,this.shape=n.slice(),this.size=ae(n),t!=null){var o=t.length;D(o===this.size,function(){return"Length of values '"+o+"' does not match the size inferred by the shape '"+a.size+"'."})}if(e==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=t||bn(e,this.size),this.strides=Rn(n)}return r.prototype.set=function(n){for(var e=this,t=[],a=1;a<arguments.length;a++)t[a-1]=arguments[a];t.length===0&&(t=[0]),D(t.length===this.rank,function(){return"The number of provided coordinates ("+t.length+") must match the rank ("+e.rank+")"});var o=this.locToIndex(t);this.values[o]=n},r.prototype.get=function(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];n.length===0&&(n=[0]);for(var t=0,a=0,o=n;a<o.length;a++){var i=o[a];if(i<0||i>=this.shape[t]){var s="Requested out of range element at "+n+". Buffer shape="+this.shape;throw new Error(s)}t++}for(var u=n[n.length-1],c=0;c<n.length-1;++c)u+=this.strides[c]*n[c];return this.values[u]},r.prototype.locToIndex=function(n){if(this.rank===0)return 0;if(this.rank===1)return n[0];for(var e=n[n.length-1],t=0;t<n.length-1;++t)e+=this.strides[t]*n[t];return e},r.prototype.indexToLoc=function(n){if(this.rank===0)return[];if(this.rank===1)return[n];for(var e=new Array(this.shape.length),t=0;t<e.length-1;++t)e[t]=Math.floor(n/this.strides[t]),n-=e[t]*this.strides[t];return e[e.length-1]=n,e},Object.defineProperty(r.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),r.prototype.toTensor=function(){return In().makeTensor(this.values,this.shape,this.dtype)},r}(),In=null,oe=null,So=null,fn=function(){function r(n,e,t,a){this.kept=!1,this.isDisposedInternal=!1,this.shape=n.slice(),this.dtype=e||"float32",this.size=ae(n),this.strides=Rn(n),this.dataId=t,this.id=a,this.rankType=this.rank<5?this.rank.toString():"higher"}return r.prototype.flatten=function(){return this.throwIfDisposed(),this.as1D()},r.prototype.asScalar=function(){return this.throwIfDisposed(),D(this.size===1,function(){return"The array must have only 1 element."}),this.reshape([])},r.prototype.as1D=function(){return this.throwIfDisposed(),this.reshape([this.size])},r.prototype.as2D=function(n,e){return this.throwIfDisposed(),this.reshape([n,e])},r.prototype.as3D=function(n,e,t){return this.throwIfDisposed(),this.reshape([n,e,t])},r.prototype.as4D=function(n,e,t,a){return this.throwIfDisposed(),this.reshape([n,e,t,a])},r.prototype.as5D=function(n,e,t,a,o){return this.throwIfDisposed(),this.reshape([n,e,t,a,o])},r.prototype.asType=function(n){return this.throwIfDisposed(),oe.cast(this,n)},Object.defineProperty(r.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),r.prototype.buffer=function(){return ve(this,void 0,void 0,function(){var n;return ye(this,function(e){switch(e.label){case 0:return[4,this.data()];case 1:return n=e.sent(),[2,oe.buffer(this.shape,this.dtype,n)]}})})},r.prototype.bufferSync=function(){return oe.buffer(this.shape,this.dtype,this.dataSync())},r.prototype.array=function(){return ve(this,void 0,void 0,function(){var n;return ye(this,function(e){switch(e.label){case 0:return[4,this.data()];case 1:return n=e.sent(),[2,_(this.shape,n)]}})})},r.prototype.arraySync=function(){return _(this.shape,this.dataSync())},r.prototype.data=function(){return ve(this,void 0,void 0,function(){var n,e;return ye(this,function(t){switch(t.label){case 0:return this.throwIfDisposed(),n=In().read(this.dataId),this.dtype!=="string"?[3,2]:[4,n];case 1:e=t.sent();try{return[2,e.map(function(a){return ut(a)})]}catch(a){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}t.label=2;case 2:return[2,n]}})})},r.prototype.dataSync=function(){this.throwIfDisposed();var n=In().readSync(this.dataId);if(this.dtype==="string")try{return n.map(function(e){return ut(e)})}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return n},r.prototype.bytes=function(){return ve(this,void 0,void 0,function(){var n;return ye(this,function(e){switch(e.label){case 0:return this.throwIfDisposed(),[4,In().read(this.dataId)];case 1:return n=e.sent(),this.dtype==="string"?[2,n]:[2,new Uint8Array(n.buffer)]}})})},r.prototype.dispose=function(){this.isDisposed||(In().disposeTensor(this),this.isDisposedInternal=!0)},Object.defineProperty(r.prototype,"isDisposed",{get:function(){return this.isDisposedInternal},enumerable:!0,configurable:!0}),r.prototype.throwIfDisposed=function(){if(this.isDisposed)throw new Error("Tensor is disposed.")},r.prototype.toFloat=function(){return this.asType("float32")},r.prototype.toInt=function(){return this.asType("int32")},r.prototype.toBool=function(){return this.asType("bool")},r.prototype.print=function(n){return n===void 0&&(n=!1),oe.print(this,n)},r.prototype.reshape=function(n){return this.throwIfDisposed(),oe.reshape(this,n)},r.prototype.reshapeAs=function(n){return this.throwIfDisposed(),this.reshape(n.shape)},r.prototype.expandDims=function(n){return n===void 0&&(n=0),oe.expandDims(this,n)},r.prototype.cumsum=function(n,e,t){return n===void 0&&(n=0),e===void 0&&(e=!1),t===void 0&&(t=!1),oe.cumsum(this,n,e,t)},r.prototype.squeeze=function(n){return this.throwIfDisposed(),oe.squeeze(this,n)},r.prototype.clone=function(){return this.throwIfDisposed(),oe.clone(this)},r.prototype.oneHot=function(n,e,t){return this.throwIfDisposed(),oe.oneHot(this,n,e,t)},r.prototype.toString=function(n){return n===void 0&&(n=!1),fi(this.dataSync(),this.shape,this.dtype,n)},r.prototype.tile=function(n){return this.throwIfDisposed(),oe.tile(this,n)},r.prototype.gather=function(n,e){return e===void 0&&(e=0),this.throwIfDisposed(),oe.gather(this,n,e)},r.prototype.matMul=function(n,e,t){return e===void 0&&(e=!1),t===void 0&&(t=!1),this.throwIfDisposed(),oe.matMul(this,n,e,t)},r.prototype.dot=function(n){return this.throwIfDisposed(),oe.dot(this,n)},r.prototype.norm=function(n,e,t){return n===void 0&&(n="euclidean"),e===void 0&&(e=null),t===void 0&&(t=!1),this.throwIfDisposed(),oe.norm(this,n,e,t)},r.prototype.slice=function(n,e){return this.throwIfDisposed(),oe.slice(this,n,e)},r.prototype.reverse=function(n){return this.throwIfDisposed(),oe.reverse(this,n)},r.prototype.concat=function(n,e){return e===void 0&&(e=0),this.throwIfDisposed(),n instanceof r&&(n=[n]),oe.concat([this].concat(n),e)},r.prototype.split=function(n,e){return e===void 0&&(e=0),this.throwIfDisposed(),oe.split(this,n,e)},r.prototype.stack=function(n,e){return e===void 0&&(e=0),oe.stack([this,n],e)},r.prototype.unstack=function(n){return n===void 0&&(n=0),oe.unstack(this,n)},r.prototype.pad=function(n,e){return e===void 0&&(e=0),oe.pad(this,n,e)},r.prototype.batchNormalization=function(n,e,t,a,o){return t===void 0&&(t=.001),So("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon"),this.batchNorm(n,e,o,a,t)},r.prototype.batchNorm=function(n,e,t,a,o){return o===void 0&&(o=.001),this.throwIfDisposed(),oe.batchNorm(this,n,e,t,a,o)},r.prototype.all=function(n,e){return n===void 0&&(n=null),e===void 0&&(e=!1),this.throwIfDisposed(),oe.all(this,n,e)},r.prototype.any=function(n,e){return n===void 0&&(n=null),e===void 0&&(e=!1),this.throwIfDisposed(),oe.any(this,n,e)},r.prototype.logSumExp=function(n,e){return n===void 0&&(n=null),e===void 0&&(e=!1),this.throwIfDisposed(),oe.logSumExp(this,n,e)},r.prototype.sum=function(n,e){return n===void 0&&(n=null),e===void 0&&(e=!1),this.throwIfDisposed(),oe.sum(this,n,e)},r.prototype.prod=function(n,e){return n===void 0&&(n=null),e===void 0&&(e=!1),this.throwIfDisposed(),oe.prod(this,n,e)},r.prototype.mean=function(n,e){return n===void 0&&(n=null),e===void 0&&(e=!1),this.throwIfDisposed(),oe.mean(this,n,e)},r.prototype.min=function(n,e){return n===void 0&&(n=null),e===void 0&&(e=!1),this.throwIfDisposed(),oe.min(this,n,e)},r.prototype.max=function(n,e){return n===void 0&&(n=null),e===void 0&&(e=!1),this.throwIfDisposed(),oe.max(this,n,e)},r.prototype.argMin=function(n){return n===void 0&&(n=null),this.throwIfDisposed(),oe.argMin(this,n)},r.prototype.argMax=function(n){return n===void 0&&(n=null),this.throwIfDisposed(),oe.argMax(this,n)},r.prototype.cast=function(n){return this.throwIfDisposed(),oe.cast(this,n)},r.prototype.add=function(n){return this.throwIfDisposed(),oe.add(this,n)},r.prototype.addStrict=function(n){return this.throwIfDisposed(),oe.addStrict(this,n)},r.prototype.atan2=function(n){return this.throwIfDisposed(),oe.atan2(this,n)},r.prototype.sub=function(n){return this.throwIfDisposed(),oe.sub(this,n)},r.prototype.subStrict=function(n){return this.throwIfDisposed(),oe.subStrict(this,n)},r.prototype.pow=function(n){return this.throwIfDisposed(),oe.pow(this,n)},r.prototype.powStrict=function(n){return this.throwIfDisposed(),oe.powStrict(this,n)},r.prototype.mul=function(n){return this.throwIfDisposed(),oe.mul(this,n)},r.prototype.mulStrict=function(n){return this.throwIfDisposed(),oe.mulStrict(this,n)},r.prototype.div=function(n){return this.throwIfDisposed(),oe.div(this,n)},r.prototype.divNoNan=function(n){return this.throwIfDisposed(),oe.divNoNan(this,n)},r.prototype.floorDiv=function(n){return this.throwIfDisposed(),oe.floorDiv(this,n)},r.prototype.divStrict=function(n){return this.throwIfDisposed(),oe.divStrict(this,n)},r.prototype.minimum=function(n){return this.throwIfDisposed(),oe.minimum(this,n)},r.prototype.minimumStrict=function(n){return this.throwIfDisposed(),oe.minimumStrict(this,n)},r.prototype.maximum=function(n){return this.throwIfDisposed(),oe.maximum(this,n)},r.prototype.maximumStrict=function(n){return this.throwIfDisposed(),oe.maximumStrict(this,n)},r.prototype.mod=function(n){return this.throwIfDisposed(),oe.mod(this,n)},r.prototype.modStrict=function(n){return this.throwIfDisposed(),oe.modStrict(this,n)},r.prototype.squaredDifferenceStrict=function(n){return this.throwIfDisposed(),oe.squaredDifferenceStrict(this,n)},r.prototype.transpose=function(n){return this.throwIfDisposed(),oe.transpose(this,n)},r.prototype.notEqual=function(n){return this.throwIfDisposed(),oe.notEqual(this,n)},r.prototype.notEqualStrict=function(n){return this.throwIfDisposed(),oe.notEqualStrict(this,n)},r.prototype.less=function(n){return this.throwIfDisposed(),oe.less(this,n)},r.prototype.lessStrict=function(n){return this.throwIfDisposed(),oe.lessStrict(this,n)},r.prototype.equal=function(n){return this.throwIfDisposed(),oe.equal(this,n)},r.prototype.equalStrict=function(n){return this.throwIfDisposed(),oe.equalStrict(this,n)},r.prototype.lessEqual=function(n){return this.throwIfDisposed(),oe.lessEqual(this,n)},r.prototype.lessEqualStrict=function(n){return this.throwIfDisposed(),oe.lessEqualStrict(this,n)},r.prototype.greater=function(n){return this.throwIfDisposed(),oe.greater(this,n)},r.prototype.greaterStrict=function(n){return this.throwIfDisposed(),oe.greaterStrict(this,n)},r.prototype.greaterEqual=function(n){return this.throwIfDisposed(),oe.greaterEqual(this,n)},r.prototype.greaterEqualStrict=function(n){return this.throwIfDisposed(),oe.greaterEqualStrict(this,n)},r.prototype.logicalAnd=function(n){return this.throwIfDisposed(),oe.logicalAnd(this,n)},r.prototype.logicalOr=function(n){return this.throwIfDisposed(),oe.logicalOr(this,n)},r.prototype.logicalNot=function(){return this.throwIfDisposed(),oe.logicalNot(this)},r.prototype.logicalXor=function(n){return this.throwIfDisposed(),oe.logicalXor(this,n)},r.prototype.where=function(n,e){return this.throwIfDisposed(),oe.where(n,this,e)},r.prototype.neg=function(){return this.throwIfDisposed(),oe.neg(this)},r.prototype.ceil=function(){return this.throwIfDisposed(),oe.ceil(this)},r.prototype.floor=function(){return this.throwIfDisposed(),oe.floor(this)},r.prototype.sign=function(){return this.throwIfDisposed(),oe.sign(this)},r.prototype.isNaN=function(){return this.throwIfDisposed(),oe.isNaN(this)},r.prototype.isInf=function(){return this.throwIfDisposed(),oe.isInf(this)},r.prototype.isFinite=function(){return this.throwIfDisposed(),oe.isFinite(this)},r.prototype.exp=function(){return this.throwIfDisposed(),oe.exp(this)},r.prototype.expm1=function(){return this.throwIfDisposed(),oe.expm1(this)},r.prototype.log=function(){return this.throwIfDisposed(),oe.log(this)},r.prototype.log1p=function(){return this.throwIfDisposed(),oe.log1p(this)},r.prototype.sqrt=function(){return this.throwIfDisposed(),oe.sqrt(this)},r.prototype.rsqrt=function(){return this.throwIfDisposed(),oe.rsqrt(this)},r.prototype.square=function(){return this.throwIfDisposed(),oe.square(this)},r.prototype.reciprocal=function(){return this.throwIfDisposed(),oe.reciprocal(this)},r.prototype.abs=function(){return this.throwIfDisposed(),oe.abs(this)},r.prototype.clipByValue=function(n,e){return this.throwIfDisposed(),oe.clipByValue(this,n,e)},r.prototype.relu=function(){return this.throwIfDisposed(),oe.relu(this)},r.prototype.relu6=function(){return this.throwIfDisposed(),oe.relu6(this)},r.prototype.elu=function(){return this.throwIfDisposed(),oe.elu(this)},r.prototype.selu=function(){return this.throwIfDisposed(),oe.selu(this)},r.prototype.leakyRelu=function(n){return n===void 0&&(n=.2),this.throwIfDisposed(),oe.leakyRelu(this,n)},r.prototype.prelu=function(n){return this.throwIfDisposed(),oe.prelu(this,n)},r.prototype.sigmoid=function(){return this.throwIfDisposed(),oe.sigmoid(this)},r.prototype.logSigmoid=function(){return this.throwIfDisposed(),oe.logSigmoid(this)},r.prototype.softplus=function(){return this.throwIfDisposed(),oe.softplus(this)},r.prototype.zerosLike=function(){return this.throwIfDisposed(),oe.zerosLike(this)},r.prototype.onesLike=function(){return this.throwIfDisposed(),oe.onesLike(this)},r.prototype.sin=function(){return this.throwIfDisposed(),oe.sin(this)},r.prototype.cos=function(){return this.throwIfDisposed(),oe.cos(this)},r.prototype.tan=function(){return this.throwIfDisposed(),oe.tan(this)},r.prototype.asin=function(){return this.throwIfDisposed(),oe.asin(this)},r.prototype.acos=function(){return this.throwIfDisposed(),oe.acos(this)},r.prototype.atan=function(){return this.throwIfDisposed(),oe.atan(this)},r.prototype.sinh=function(){return this.throwIfDisposed(),oe.sinh(this)},r.prototype.cosh=function(){return this.throwIfDisposed(),oe.cosh(this)},r.prototype.tanh=function(){return this.throwIfDisposed(),oe.tanh(this)},r.prototype.asinh=function(){return this.throwIfDisposed(),oe.asinh(this)},r.prototype.acosh=function(){return this.throwIfDisposed(),oe.acosh(this)},r.prototype.atanh=function(){return this.throwIfDisposed(),oe.atanh(this)},r.prototype.erf=function(){return this.throwIfDisposed(),oe.erf(this)},r.prototype.round=function(){return this.throwIfDisposed(),oe.round(this)},r.prototype.step=function(n){return n===void 0&&(n=0),this.throwIfDisposed(),oe.step(this,n)},r.prototype.softmax=function(n){return n===void 0&&(n=-1),this.throwIfDisposed(),oe.softmax(this,n)},r.prototype.logSoftmax=function(n){return n===void 0&&(n=-1),this.throwIfDisposed(),oe.logSoftmax(this,n)},r.prototype.resizeBilinear=function(n,e){return e===void 0&&(e=!1),this.throwIfDisposed(),oe.image.resizeBilinear(this,n,e)},r.prototype.resizeNearestNeighbor=function(n,e){return e===void 0&&(e=!1),this.throwIfDisposed(),oe.image.resizeNearestNeighbor(this,n,e)},r.prototype.conv1d=function(n,e,t,a,o,i){return a===void 0&&(a="NWC"),o===void 0&&(o=1),this.throwIfDisposed(),oe.conv1d(this,n,e,t,a,o,i)},r.prototype.conv2d=function(n,e,t,a,o,i){return a===void 0&&(a="NHWC"),o===void 0&&(o=[1,1]),this.throwIfDisposed(),oe.conv2d(this,n,e,t,a,o,i)},r.prototype.conv2dTranspose=function(n,e,t,a,o){return this.throwIfDisposed(),oe.conv2dTranspose(this,n,e,t,a,o)},r.prototype.depthwiseConv2D=function(n,e,t,a,o,i){return a===void 0&&(a="NHWC"),o===void 0&&(o=[1,1]),this.throwIfDisposed(),oe.depthwiseConv2d(this,n,e,t,a,o,i)},r.prototype.separableConv2d=function(n,e,t,a,o,i){return o===void 0&&(o=[1,1]),i===void 0&&(i="NHWC"),this.throwIfDisposed(),oe.separableConv2d(this,n,e,t,a,o,i)},r.prototype.avgPool=function(n,e,t,a){return this.throwIfDisposed(),oe.avgPool(this,n,e,t,a)},r.prototype.maxPool=function(n,e,t,a){return this.throwIfDisposed(),oe.maxPool(this,n,e,t,a)},r.prototype.localResponseNormalization=function(n,e,t,a){return n===void 0&&(n=5),e===void 0&&(e=1),t===void 0&&(t=1),a===void 0&&(a=.5),oe.localResponseNormalization(this,n,e,t,a)},r.prototype.pool=function(n,e,t,a,o){return this.throwIfDisposed(),oe.pool(this,n,e,t,a,o)},r.prototype.variable=function(n,e,t){return n===void 0&&(n=!0),this.throwIfDisposed(),In().makeVariable(this,n,e,t)},r.prototype.unsortedSegmentSum=function(n,e){return this.throwIfDisposed(),oe.unsortedSegmentSum(this,n,e)},r.prototype.batchToSpaceND=function(n,e){return this.throwIfDisposed(),oe.batchToSpaceND(this,n,e)},r.prototype.spaceToBatchND=function(n,e){return this.throwIfDisposed(),oe.spaceToBatchND(this,n,e)},r.prototype.topk=function(n,e){return n===void 0&&(n=1),e===void 0&&(e=!0),this.throwIfDisposed(),oe.topk(this,n,e)},r.prototype.stridedSlice=function(n,e,t,a,o,i,s,u){return a===void 0&&(a=0),o===void 0&&(o=0),i===void 0&&(i=0),s===void 0&&(s=0),u===void 0&&(u=0),this.throwIfDisposed(),oe.stridedSlice(this,n,e,t,a,o,i,s,u)},r.prototype.depthToSpace=function(n,e){return this.throwIfDisposed(),oe.depthToSpace(this,n,e)},r.prototype.fft=function(){return this.throwIfDisposed(),oe.spectral.fft(this)},r.prototype.ifft=function(){return this.throwIfDisposed(),oe.spectral.ifft(this)},r.prototype.rfft=function(){return this.throwIfDisposed(),oe.spectral.rfft(this)},r.prototype.irfft=function(){return this.throwIfDisposed(),oe.spectral.irfft(this)},r}();Object.defineProperty(fn,Symbol.hasInstance,{value:function(r){return!!r&&r.dataId!=null&&r.shape!=null&&r.dtype!=null}});var Oo,Va,Ga,an,Io,Fr=function(r){function n(e,t,a,o){var i=r.call(this,e.shape,e.dtype,e.dataId,o)||this;return i.trainable=t,i.name=a,i}return Ke(n,r),n.prototype.assign=function(e){if(e.dtype!==this.dtype)throw new Error("dtype of the new value ("+e.dtype+") and previous value ("+this.dtype+") must match");if(!Oe(e.shape,this.shape))throw new Error("shape of the new value ("+e.shape+") and previous value ("+this.shape+") must match");In().disposeTensor(this),this.dataId=e.dataId,In().incRef(this,null)},n.prototype.dispose=function(){In().disposeVariable(this),this.isDisposedInternal=!0},n}(fn);Object.defineProperty(Fr,Symbol.hasInstance,{value:function(r){return r instanceof fn&&r.assign!=null&&r.assign instanceof Function}}),function(r){r.R0="R0",r.R1="R1",r.R2="R2",r.R3="R3",r.R4="R4",r.R5="R5",r.R6="R6"}(Oo||(Oo={})),function(r){r.float32="float32",r.int32="int32",r.bool="int32",r.complex64="complex64"}(Va||(Va={})),function(r){r.float32="float32",r.int32="int32",r.bool="bool",r.complex64="complex64"}(Ga||(Ga={})),function(r){r.float32="float32",r.int32="float32",r.bool="float32",r.complex64="complex64"}(an||(an={})),function(r){r.float32="complex64",r.int32="complex64",r.bool="complex64",r.complex64="complex64"}(Io||(Io={}));var Mo={float32:an,int32:Va,bool:Ga,complex64:Io};function yn(r,n){if(r==="string"||n==="string"){if(r==="string"&&n==="string")return"string";throw new Error("Can not upcast "+r+" with "+n)}return Mo[r][n]}function vn(r){return yn(r,"int32")}function Wt(r,n){if(r.dtype===n.dtype)return[r,n];var e=yn(r.dtype,n.dtype);return[r.cast(e),n.cast(e)]}function Kn(r,n){D(r.dtype===n.dtype,function(){return"The dtypes of the first("+r.dtype+") and second("+n.dtype+") input must match"})}function qn(r){var n=[];return function e(t,a,o){if(t==null)return;if(t instanceof fn)return void a.push(t);if(i=t,!Array.isArray(i)&&typeof i!="object")return;var i,s=t;for(var u in s){var c=s[u];o.has(c)||(o.add(c),e(c,a,o))}}(r,n,new Set),n}var wa,vi=Object.freeze({makeTypesMatch:Wt,assertTypesMatch:Kn,isTensorInList:function(r,n){return n.some(function(e){return e.id===r.id})},getTensorsInContainer:qn}),Fo=function(){function r(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null}}return r.prototype.dispose=function(){for(var n in this.registeredVariables)this.registeredVariables[n].dispose()},r}(),mi=function(){function r(n){this.ENV=n,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Fo}return r.prototype.ready=function(){return ve(this,void 0,void 0,function(){var n,e,t;return ye(this,function(a){switch(a.label){case 0:if(this.pendingBackendInit!=null)return[2,this.pendingBackendInit.then(function(){})];if(this.backendInstance!=null)return[2];n=this.getSortedBackends(),e=0,a.label=1;case 1:return e<n.length?(t=n[e],[4,this.initializeBackend(t).success]):[3,5];case 2:return a.sent()?[4,this.setBackend(t)]:[3,4];case 3:return a.sent(),[2];case 4:return e++,[3,1];case 5:throw new Error("Could not initialize any backends, all backend initializations failed.")}})})},Object.defineProperty(r.prototype,"backend",{get:function(){if(this.pendingBackendInit!=null)throw new Error("Backend '"+this.backendName+"' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods");if(this.backendInstance==null){var n=this.initializeBackendsAndReturnBest(),e=n.name;if(n.asyncInit)throw new Error("The highest priority backend '"+e+"' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods");this.setBackend(e)}return this.backendInstance},enumerable:!0,configurable:!0}),r.prototype.backendNames=function(){return Object.keys(this.registryFactory)},r.prototype.findBackend=function(n){if(!(n in this.registry)){if(!(n in this.registryFactory))return null;if(this.initializeBackend(n).asyncInit)return null}return this.registry[n]},r.prototype.findBackendFactory=function(n){return n in this.registryFactory?this.registryFactory[n].factory:null},r.prototype.registerBackend=function(n,e,t){return t===void 0&&(t=1),n in this.registryFactory?(console.warn(n+" backend was already registered. Reusing existing backend factory."),!1):(this.registryFactory[n]={factory:e,priority:t},!0)},r.prototype.setBackend=function(n){return ve(this,void 0,void 0,function(){var e,t,a;return ye(this,function(o){switch(o.label){case 0:if(this.registryFactory[n]==null)throw new Error("Backend name '"+n+"' not found in registry");return this.backendName=n,this.registry[n]!=null?[3,4]:(this.backendInstance=null,e=this.initializeBackend(n),t=e.success,e.asyncInit?[4,t]:[3,2]);case 1:return a=o.sent(),[3,3];case 2:a=t,o.label=3;case 3:if(!a)return[2,!1];o.label=4;case 4:return this.backendInstance=this.registry[n],this.setupRegisteredKernels(),this.profiler=new qt(this.backendInstance),[2,!0]}})})},r.prototype.setupRegisteredKernels=function(){var n=this;Ct(this.backendName).forEach(function(e){e.setupFunc!=null&&e.setupFunc(n.backendInstance)})},r.prototype.disposeRegisteredKernels=function(n){var e=this;Ct(n).forEach(function(t){t.disposeFunc!=null&&t.disposeFunc(e.registry[n])})},r.prototype.initializeBackend=function(n){var e=this,t=this.registryFactory[n];if(t==null)throw new Error("Cannot initialize backend "+n+", no registration found.");try{var a=t.factory();if(Promise.resolve(a)===a){var o=++this.pendingBackendInitId,i=a.then(function(s){return!(o<e.pendingBackendInitId)&&(e.registry[n]=s,e.pendingBackendInit=null,!0)}).catch(function(s){return!(o<e.pendingBackendInitId)&&(e.pendingBackendInit=null,console.warn("Initialization of backend "+n+" failed"),console.warn(s.stack||s.message),!1)});return this.pendingBackendInit=i,{success:i,asyncInit:!0}}return this.registry[n]=a,{success:!0,asyncInit:!1}}catch(s){return console.warn("Initialization of backend "+n+" failed"),console.warn(s.stack||s.message),{success:!1,asyncInit:!1}}},r.prototype.removeBackend=function(n){if(!(n in this.registryFactory))throw new Error(n+" backend not found in registry");this.backendName===n&&this.pendingBackendInit!=null&&this.pendingBackendInitId++,n in this.registry&&(this.disposeRegisteredKernels(n),this.registry[n].dispose(),delete this.registry[n]),delete this.registryFactory[n],this.backendName===n&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)},r.prototype.getSortedBackends=function(){var n=this;if(Object.keys(this.registryFactory).length===0)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort(function(e,t){return n.registryFactory[t].priority-n.registryFactory[e].priority})},r.prototype.initializeBackendsAndReturnBest=function(){for(var n=this.getSortedBackends(),e=0;e<n.length;e++){var t=n[e],a=this.initializeBackend(t),o=a.success,i=a.asyncInit;if(i||o)return{name:t,asyncInit:i}}throw new Error("Could not initialize any backends, all backend initializations failed.")},r.prototype.moveData=function(n,e){var t=this.state.tensorInfo.get(e),a=t.backend,o=this.readSync(e);a.disposeData(e),t.backend=n,n.move(e,o,t.shape,t.dtype),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++},r.prototype.tidy=function(n,e){var t,a=this,o=null;if(e==null){if(typeof n!="function")throw new Error("Please provide a function to tidy()");e=n}else{if(typeof n!="string"&&!(n instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if(typeof e!="function")throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");o=n}return this.scopedRun(function(){return a.startScope(o)},function(){return a.endScope(t)},function(){return(t=e())instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),t})},r.prototype.scopedRun=function(n,e,t){n();try{var a=t();return e(),a}catch(o){throw e(),o}},r.prototype.nextTensorId=function(){return r.nextTensorId++},r.prototype.nextVariableId=function(){return r.nextVariableId++},r.prototype.clone=function(n){var e=this.makeTensorFromDataId(n.dataId,n.shape,n.dtype),t={x:n};return this.addTapeNode(this.state.activeScope.name,t,[e],function(a){return{x:function(){return a.toFloat()}}},[]),e},r.prototype.runKernel=function(n,e,t,a,o){return this.runKernelFunc(null,e,null,n,t,a,o)},r.prototype.shouldCheckForMemLeaks=function(){return this.ENV.getBool("IS_TEST")},r.prototype.checkKernelForMemLeak=function(n,e,t){var a=this.backend.numDataIds(),o=0;t.forEach(function(u){o+=u.dtype==="complex64"?3:1});var i=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],s=a-e-o-i;if(s>0)throw new Error("Backend '"+this.backendName+"' has an internal memory leak ("+s+" data ids) after running '"+n+"'")},r.prototype.runKernelFunc=function(n,e,t,a,o,i,s){var u,c=this;i===void 0&&(i=[]),s===void 0&&(s=[]);var d=[],f=this.isTapeOn();a==null&&(a=this.state.activeScope!=null?this.state.activeScope.name:"");var m,g=function(N){f&&(d=N.map(function(S){return c.keep(c.clone(S))}))},x=this.state.numBytes,E=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);var w,C=Ve(a,this.backendName);return m=C!=null?function(){var N=c.backend.numDataIds();w=C.kernelFunc({inputs:e,attrs:o,backend:c.backend});var S=Array.isArray(w)?w:[w];c.shouldCheckForMemLeaks()&&c.checkKernelForMemLeak(a,N,S);var I=S.map(function(j){var G=j.dataId,z=j.shape,W=j.dtype;return c.makeTensorFromDataId(G,z,W)}),M=I.filter(function(j,G){return s[G]});return g((i||[]).slice().concat(M)),I}:function(){var N=c.backend.numDataIds();w=c.tidy(function(){return n(c.backend,g)});var S=Array.isArray(w)?w:[w];return c.shouldCheckForMemLeaks()&&c.checkKernelForMemLeak(a,N,S),S},this.scopedRun(function(){return c.state.kernelDepth++},function(){return c.state.kernelDepth--},function(){u=c.ENV.getBool("DEBUG")?c.profiler.profileKernel(a,e,function(){return m()}):m()}),f&&this.addTapeNode(a,e,u,t,d),this.state.profiling&&this.state.activeProfile.kernels.push({name:a,bytesAdded:this.state.numBytes-x,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-E,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(e).map(function(N){return e[N].shape}),outputShapes:u.map(function(N){return N.shape})}),Array.isArray(w)?u:u[0]},r.prototype.makeTensor=function(n,e,t,a){if(n==null)throw new Error("Values passed to engine.makeTensor() are null");t=t||"float32",a=a||this.backend;var o=n;t==="string"&&wn(n[0])&&(o=n.map(function(d){return xe(d)}));var i=a.write(o,e,t),s=new fn(e,t,i,this.nextTensorId());if(this.incRef(s,a),t==="string"){var u=this.state.tensorInfo.get(i),c=rr(o);this.state.numBytes+=c-u.bytes,u.bytes=c}return s},r.prototype.makeTensorFromDataId=function(n,e,t,a){var o=new fn(e,t=t||"float32",n,this.nextTensorId());return this.incRef(o,a),o},r.prototype.makeVariable=function(n,e,t,a){e===void 0&&(e=!0),t=t||this.nextVariableId().toString(),a!=null&&a!==n.dtype&&(n=n.asType(a));var o=new Fr(n,e,t,this.nextTensorId());if(this.state.registeredVariables[o.name]!=null)throw new Error("Variable with name "+o.name+" was already registered");return this.state.registeredVariables[o.name]=o,this.incRef(o,this.backend),o},r.prototype.incRef=function(n,e){var t=this.state.tensorInfo.has(n.dataId)?this.state.tensorInfo.get(n.dataId).refCount:0;if(this.state.numTensors++,n.dtype==="string"&&this.state.numStringTensors++,t===0){this.state.numDataBuffers++;var a=0;n.dtype!=="complex64"&&n.dtype!=="string"&&(a=n.size*nr(n.dtype)),this.state.tensorInfo.set(n.dataId,{backend:e||this.backend,dtype:n.dtype,shape:n.shape,bytes:a,refCount:0}),this.state.numBytes+=a}this.state.tensorInfo.get(n.dataId).refCount++,n instanceof Fr||this.track(n)},r.prototype.disposeTensor=function(n){if(this.state.tensorInfo.has(n.dataId)){this.state.numTensors--,n.dtype==="string"&&this.state.numStringTensors--;var e=this.state.tensorInfo.get(n.dataId);e.refCount<=1?(n.dtype!=="complex64"&&(this.state.numBytes-=e.bytes),this.state.numDataBuffers--,e.backend.disposeData(n.dataId),this.state.tensorInfo.delete(n.dataId)):this.state.tensorInfo.get(n.dataId).refCount--}},r.prototype.disposeVariables=function(){for(var n in this.state.registeredVariables){var e=this.state.registeredVariables[n];this.disposeVariable(e)}},r.prototype.disposeVariable=function(n){this.disposeTensor(n),this.state.registeredVariables[n.name]!=null&&delete this.state.registeredVariables[n.name]},r.prototype.memory=function(){var n=this.backend.memory();return n.numTensors=this.state.numTensors,n.numDataBuffers=this.state.numDataBuffers,n.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(n.unreliable=!0,n.reasons==null&&(n.reasons=[]),n.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),n},r.prototype.profile=function(n){return ve(this,void 0,void 0,function(){var e,t;return ye(this,function(a){return this.state.profiling=!0,e=this.state.numBytes,t=this.state.numTensors,this.state.activeProfile.kernels=[],this.state.activeProfile.result=n(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max.apply(Math,this.state.activeProfile.kernels.map(function(o){return o.totalBytesSnapshot})),this.state.activeProfile.newBytes=this.state.numBytes-e,this.state.activeProfile.newTensors=this.state.numTensors-t,[2,this.state.activeProfile]})})},r.prototype.isTapeOn=function(){return this.state.gradientDepth>0&&this.state.kernelDepth===0},r.prototype.addTapeNode=function(n,e,t,a,o){var i=this,s={id:this.state.nextTapeNodeId++,kernelName:n,inputs:e,outputs:t,saved:o},u=st(n);u!=null&&(a=u.gradFunc),a!=null&&(s.gradient=function(c){return c=c.map(function(d,f){if(d==null){var m=t[f],g=U(m.size,m.dtype);return i.makeTensor(g,m.shape,m.dtype)}return d}),a(c.length>1?c:c[0],o)}),this.state.activeTape.push(s)},r.prototype.keep=function(n){return n.kept=!0,n},r.prototype.startTape=function(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++},r.prototype.endTape=function(){this.state.gradientDepth--},r.prototype.startScope=function(n){var e={track:[],name:"unnamed scope",id:this.state.nextScopeId++};n&&(e.name=n),this.state.scopeStack.push(e),this.state.activeScope=e},r.prototype.endScope=function(n){for(var e=this,t=qn(n),a=new Set(t.map(function(u){return u.id})),o=0;o<this.state.activeScope.track.length;o++){var i=this.state.activeScope.track[o];i.kept||a.has(i.id)||i.dispose()}var s=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach(function(u){u.kept||u.scopeId!==s.id||e.track(u)})},r.prototype.gradients=function(n,e,t,a){var o=this;if(a===void 0&&(a=!1),D(e.length>0,function(){return"gradients() received an empty list of xs."}),t!=null&&t.dtype!=="float32")throw new Error("dy must have 'float32' dtype, but has '"+t.dtype+"'");var i=this.scopedRun(function(){return o.startTape()},function(){return o.endTape()},function(){return o.tidy("forward",n)});D(i instanceof fn,function(){return"The result y returned by f() must be a tensor."});var s=function(u,c,d){for(var f={},m={},g=0;g<c.length;g++)f[c[g].id]=!0;for(g=0;g<u.length;g++){var x=(j=u[g]).inputs;for(var E in x){for(var w=x[E],C=!1,N=0;N<c.length;N++)if(f[w.id]){j.outputs.forEach(function(V){return f[V.id]=!0}),C=!0,m[j.id]=!0;break}if(C)break}}var S={};S[d.id]=!0;var I={};for(g=u.length-1;g>=0;g--)for(x=(j=u[g]).inputs,N=0;N<j.outputs.length;N++)if(S[j.outputs[N].id]){for(var E in x)S[x[E].id]=!0,I[j.id]=!0;break}var M=[];for(g=0;g<u.length;g++){var j;if(m[(j=u[g]).id]&&I[j.id]){var G={};for(var E in j.inputs){var z=j.inputs[E];f[z.id]&&(G[E]=z)}var W=Object.assign({},j);W.inputs=G,W.outputs=j.outputs,M.push(W)}}return M}(this.state.activeTape,e,i);if(!a&&s.length===0&&e.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",function(){var u,c,d={};d[i.id]=t==null?(u=i.shape,c=R(ae(u),"float32"),X.makeTensor(c,u,"float32")):t,function(m,g,x){for(var E=function(C){var N=g[C],S=[];if(N.outputs.forEach(function(G){var z=m[G.id];z!=null?S.push(z):S.push(null)}),N.gradient==null)throw new Error("Cannot compute gradient: gradient function not found for "+N.kernelName+".");var I=N.gradient(S),M=function(G){if(!(G in I))throw new Error("Cannot backprop through input "+G+". Available gradients found: "+Object.keys(I)+".");var z=x(function(){return I[G]()});if(z.dtype!=="float32")throw new Error("Error in gradient for op "+N.kernelName+". The gradient of input "+G+" must have 'float32' dtype, but has '"+z.dtype+"'");var W=N.inputs[G];if(!Oe(z.shape,W.shape))throw new Error("Error in gradient for op "+N.kernelName+". The gradient of input '"+G+"' has shape '"+z.shape+"', which does not match the shape of the input '"+W.shape+"'");if(m[W.id]==null)m[W.id]=z;else{var V=m[W.id];m[W.id]=V.add(z),V.dispose()}};for(var j in N.inputs)M(j)},w=g.length-1;w>=0;w--)E(w)}(d,s,function(m){return o.tidy(m)});var f=e.map(function(m){return d[m.id]});return o.state.gradientDepth===0&&(o.state.activeTape.forEach(function(m){for(var g=0,x=m.saved;g<x.length;g++)x[g].dispose()}),o.state.activeTape=null),{value:i,grads:f}})},r.prototype.customGrad=function(n){var e=this;return D(et(n),function(){return"The f passed in customGrad(f) must be a function."}),function(){for(var t,a=[],o=0;o<arguments.length;o++)a[o]=arguments[o];D(a.every(function(s){return s instanceof fn}),function(){return"The args passed in customGrad(f)(x1, x2,...) must all be tensors"});var i={};return a.forEach(function(s,u){i[u]=s}),e.runKernelFunc(function(s,u){return D((t=n.apply(void 0,a.concat([u]))).value instanceof fn,function(){return"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"}),D(et(t.gradFunc),function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."}),t.value},i,function(s,u){var c=t.gradFunc(s,u),d=Array.isArray(c)?c:[c];D(d.length===a.length,function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."}),D(d.every(function(m){return m instanceof fn}),function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors."});var f={};return d.forEach(function(m,g){f[g]=function(){return m}}),f})}},r.prototype.readSync=function(n){return this.state.tensorInfo.get(n).backend.readSync(n)},r.prototype.read=function(n){return this.state.tensorInfo.get(n).backend.read(n)},r.prototype.time=function(n){return ve(this,void 0,void 0,function(){var e,t;return ye(this,function(a){switch(a.label){case 0:return e=$(),[4,this.backend.time(n)];case 1:return(t=a.sent()).wallMs=$()-e,[2,t]}})})},r.prototype.track=function(n){return this.state.activeScope!=null&&(n.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(n)),n},Object.defineProperty(r.prototype,"registeredVariables",{get:function(){return this.state.registeredVariables},enumerable:!0,configurable:!0}),r.prototype.reset=function(){for(var n in this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new Fo,this.registry)this.disposeRegisteredKernels(n),this.registry[n].dispose(),delete this.registry[n];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null},r.nextTensorId=0,r.nextVariableId=0,r}(),X=function(){var r=function(){if(wa==null){var e=void 0;if(typeof window!="undefined")e=window;else if(typeof Se!="undefined")e=Se;else if(typeof ze!="undefined")e=ze;else{if(typeof self=="undefined")throw new Error("Could not find a global object");e=self}wa=e}return wa}();if(r._tfengine==null){var n=new ne(r);r._tfengine=new mi(n)}return function(e){ot=e}(r._tfengine.ENV),In=function(){return r._tfengine},r._tfengine}();function Po(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var pr=ee();pr.registerFlag("DEBUG",function(){return!1},function(r){r&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")}),pr.registerFlag("IS_BROWSER",function(){return Po()}),pr.registerFlag("IS_NODE",function(){return typeof ze!="undefined"&&ze.versions!==void 0&&ze.versions.node!==void 0}),pr.registerFlag("IS_CHROME",function(){return typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)}),pr.registerFlag("PROD",function(){return!1}),pr.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",function(){return pr.getBool("DEBUG")}),pr.registerFlag("DEPRECATION_WARNINGS_ENABLED",function(){return!0}),pr.registerFlag("IS_TEST",function(){return!1});var Ea,An,Tn,fr={},Lo={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function Bo(r,n){fr[r]=n}function or(r){r in fr||(fr[r]=function(e){if(e!==1&&e!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");var t=function(a){if(typeof OffscreenCanvas!="undefined"&&a===2)return new OffscreenCanvas(300,150);if(typeof document!="undefined")return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}(e);return t.addEventListener("webglcontextlost",function(a){a.preventDefault(),delete fr[e]},!1),e===1?t.getContext("webgl",Lo)||t.getContext("experimental-webgl",Lo):t.getContext("webgl2",Lo)}(r));var n=fr[r];return n.isContextLost()?(delete fr[r],or(r)):(n.disable(n.DEPTH_TEST),n.disable(n.STENCIL_TEST),n.disable(n.BLEND),n.disable(n.DITHER),n.disable(n.POLYGON_OFFSET_FILL),n.disable(n.SAMPLE_COVERAGE),n.enable(n.SCISSOR_TEST),n.enable(n.CULL_FACE),n.cullFace(n.BACK),fr[r])}function Pr(r,n){return[n,r]}function Zt(r){var n=ae(r);return k(Math.ceil(n/4))}function Lr(r,n){return[Math.max(1,Math.ceil(n/2)),Math.max(1,Math.ceil(r/2))]}function _a(r,n){var e,t,a,o,i,s,u,c,d,f=r;return ee().getNumber("WEBGL_VERSION")===2?(e=f.R32F,t=f.R16F,a=f.RGBA16F,o=f.RGBA32F,i=f.RED,s=4,u=1,c=f.HALF_FLOAT,d=f.FLOAT):(e=r.RGBA,t=r.RGBA,a=r.RGBA,o=f.RGBA,i=r.RGBA,s=4,u=4,c=n!=null?n.HALF_FLOAT_OES:null,d=r.FLOAT),{internalFormatFloat:e,internalFormatHalfFloat:t,internalFormatPackedHalfFloat:a,internalFormatPackedFloat:o,textureFormatFloat:i,downloadTextureFormat:r.RGBA,downloadUnpackNumChannels:s,defaultNumChannels:u,textureTypeHalfFloat:c,textureTypeFloat:d}}function Me(r,n,e){var t=e();return n&&function(a){var o=a.getError();if(o!==a.NO_ERROR)throw new Error("WebGL Error: "+jo(a,o))}(r),t}!function(r){r[r.DENSE=0]="DENSE",r[r.SHARED_BATCH=1]="SHARED_BATCH"}(Ea||(Ea={})),function(r){r[r.RENDER=0]="RENDER",r[r.UPLOAD=1]="UPLOAD",r[r.PIXELS=2]="PIXELS",r[r.DOWNLOAD=3]="DOWNLOAD"}(An||(An={})),function(r){r[r.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",r[r.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",r[r.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",r[r.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",r[r.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"}(Tn||(Tn={}));var Uu=596e-10,ls=65504;function ds(r){return!!(ee().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||r===0||Uu<Math.abs(r)&&Math.abs(r)<ls)}function jo(r,n){switch(n){case r.NO_ERROR:return"NO_ERROR";case r.INVALID_ENUM:return"INVALID_ENUM";case r.INVALID_VALUE:return"INVALID_VALUE";case r.INVALID_OPERATION:return"INVALID_OPERATION";case r.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case r.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case r.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return"Unknown error code "+n}}function Ca(r,n,e){return mr(r,n,function(){return r.getExtension(e)},'Extension "'+e+'" not supported on this browser.')}function hs(r,n,e){var t=mr(r,n,function(){return r.createShader(r.VERTEX_SHADER)},"Unable to create vertex WebGLShader.");if(Me(r,n,function(){return r.shaderSource(t,e)}),Me(r,n,function(){return r.compileShader(t)}),r.getShaderParameter(t,r.COMPILE_STATUS)===!1)throw console.log(r.getShaderInfoLog(t)),new Error("Failed to compile vertex shader.");return t}function ir(r,n,e){var t=mr(r,n,function(){return r.createShader(r.FRAGMENT_SHADER)},"Unable to create fragment WebGLShader.");if(Me(r,n,function(){return r.shaderSource(t,e)}),Me(r,n,function(){return r.compileShader(t)}),r.getShaderParameter(t,r.COMPILE_STATUS)===!1)throw function(a,o){var i=Ha.exec(o);if(i==null)return console.log("Couldn't parse line number in error: "+o),void console.log(a);for(var s=+i[1],u=a.split(`
|
|
`),c=u.length.toString().length+2,d=u.map(function(w,C){return Qe((C+1).toString(),c)+w}),f=0,m=0;m<d.length;m++)f=Math.max(d[m].length,f);var g=d.slice(0,s-1),x=d.slice(s-1,s),E=d.slice(s);console.log(g.join(`
|
|
`)),console.log(o.split(`
|
|
`)[0]),console.log("%c "+Qe(x[0],f),"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(E.join(`
|
|
`))}(e,r.getShaderInfoLog(t)),new Error("Failed to compile fragment shader.");return t}var Dn,Zr,Ha=/ERROR: [0-9]+:([0-9]+):/g;function Vn(r,n){return mr(r,n,function(){return r.createProgram()},"Unable to create WebGLProgram.")}function sr(r,n,e){if(Me(r,n,function(){return r.linkProgram(e)}),r.getProgramParameter(e,r.LINK_STATUS)===!1)throw console.log(r.getProgramInfoLog(e)),new Error("Failed to link vertex and fragment shaders.")}function Br(r,n,e){if(Me(r,n,function(){return r.validateProgram(e)}),r.getProgramParameter(e,r.VALIDATE_STATUS)===!1)throw console.log(r.getProgramInfoLog(e)),new Error("Shader program validation failed.")}function Xa(r,n,e){var t=mr(r,n,function(){return r.createBuffer()},"Unable to create WebGLBuffer");return Me(r,n,function(){return r.bindBuffer(r.ARRAY_BUFFER,t)}),Me(r,n,function(){return r.bufferData(r.ARRAY_BUFFER,e,r.STATIC_DRAW)}),t}function Uo(r,n,e){var t=mr(r,n,function(){return r.createBuffer()},"Unable to create WebGLBuffer");return Me(r,n,function(){return r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,t)}),Me(r,n,function(){return r.bufferData(r.ELEMENT_ARRAY_BUFFER,e,r.STATIC_DRAW)}),t}function Ka(r,n){return mr(r,n,function(){return r.createTexture()},"Unable to create WebGLTexture.")}function qa(r,n){var e=ee().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(r<=0||n<=0){var t="["+r+"x"+n+"]";throw new Error("Requested texture size "+t+" is invalid.")}if(r>e||n>e)throw t="["+r+"x"+n+"]",new Error("Requested texture size "+t+" greater than WebGL maximum on this browser / GPU "+("["+e+"x"+e+"]")+".")}function vr(r,n){return mr(r,n,function(){return r.createFramebuffer()},"Unable to create WebGLFramebuffer.")}function Yn(r,n,e,t,a,o,i,s){var u=r.getAttribLocation(e,t);return u!==-1&&(Me(r,n,function(){return r.bindBuffer(r.ARRAY_BUFFER,a)}),Me(r,n,function(){return r.vertexAttribPointer(u,o,r.FLOAT,!1,i,s)}),Me(r,n,function(){return r.enableVertexAttribArray(u)}),!0)}function Wo(r,n,e,t){Go(r,t),Me(r,n,function(){return r.activeTexture(r.TEXTURE0+t)}),Me(r,n,function(){return r.bindTexture(r.TEXTURE_2D,e)})}function gi(r,n,e,t){return mr(r,n,function(){return r.getUniformLocation(e,t)},'uniform "'+t+'" not present in program.')}function zo(r,n,e){return r.getUniformLocation(n,e)}function Vo(r,n,e,t,a,o){Me(r,n,function(){return Wo(r,n,t,o)}),Me(r,n,function(){return r.uniform1i(a,o)})}function Ya(r,n,e,t){Me(r,n,function(){return r.bindFramebuffer(r.FRAMEBUFFER,t)}),Me(r,n,function(){return r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e,0)})}function $a(r,n,e){Me(r,n,function(){return r.bindFramebuffer(r.FRAMEBUFFER,e)}),Me(r,n,function(){return r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,null,0)})}function Mn(r){var n=r.checkFramebufferStatus(r.FRAMEBUFFER);if(n!==r.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+yi(r,n))}function yi(r,n){switch(n){case r.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case r.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case r.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case r.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return"unknown error "+n}}function mr(r,n,e,t){var a=Me(r,n,function(){return e()});if(a==null)throw new Error(t);return a}function Go(r,n){var e=r.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,t=n+r.TEXTURE0;if(t<r.TEXTURE0||t>e)throw new Error("textureUnit must be in "+("[gl.TEXTURE0, gl.TEXTURE"+e+"]")+".")}function ea(r,n){return n===void 0&&(n=2),ae(r.slice(0,r.length-n))}function ta(r){if(r.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[r.length>1?r[r.length-2]:1,r[r.length-1]]}function na(r){var n=[1,1,1];return r.length===0||r.length===1&&r[0]===1||(n=[ea(r)].concat(ta(r))),n}function xi(r,n){var e;n===void 0&&(n=!1);var t=ee().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(n&&(t*=2,(r=r.map(function(c,d){return d>=r.length-2?Ye(r[d]):r[d]})).length===1&&(r=[2,r[0]])),r.length!==2){var a=St(r);r=a.newShape}var o=ae(r);if(r.length<=1&&o<=t)return[1,o];if(r.length===2&&r[0]<=t&&r[1]<=t)return r;if(r.length===3&&r[0]*r[1]<=t&&r[2]<=t)return[r[0]*r[1],r[2]];if(r.length===3&&r[0]<=t&&r[1]*r[2]<=t)return[r[0],r[1]*r[2]];if(r.length===4&&r[0]*r[1]*r[2]<=t&&r[3]<=t)return[r[0]*r[1]*r[2],r[3]];if(r.length===4&&r[0]<=t&&r[1]*r[2]*r[3]<=t)return[r[0],r[1]*r[2]*r[3]];if(n){var i=ea(r),s=2,u=2;return r.length&&(s=(e=ta(r))[0],u=e[1]),k(o=i*(s/2)*(u/2)).map(function(c){return 2*c})}return k(o)}function Ja(r){return r%2==0}function ra(r,n){if(Oe(r=r.slice(-2),n=n.slice(-2)))return!0;if(!r.length||!n.length)return!0;if(r[0]===0||r[1]===0||n[0]===0||n[1]===0)return!0;if(r.length!==n.length){var e=r.slice(-1)[0],t=n.slice(-1)[0];if(e===t)return!0;if(Ja(e)&&Ja(t)&&(r[0]===1||n[0]===1))return!0}return r[1]===n[1]&&Ja(r[0])&&Ja(n[0])}function bi(r){if(Dn==null){var n=or(r);Dn=n.getParameter(n.MAX_TEXTURE_SIZE)}return Dn}function Qa(r){if(Zr==null){var n=or(r);Zr=n.getParameter(n.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,Zr)}function Ra(r){if(r===0)return 0;var n=or(r);return Fn(n,"EXT_disjoint_timer_query_webgl2")&&r===2?2:Fn(n,"EXT_disjoint_timer_query")?1:0}function Fn(r,n){return r.getExtension(n)!=null}function Za(r){try{if(or(r)!=null)return!0}catch(n){return!1}return!1}function wi(r){if(r===0)return!1;var n=or(r);if(r===1){if(!Fn(n,"OES_texture_float"))return!1}else if(!Fn(n,"EXT_color_buffer_float"))return!1;return Ho(n)}function Ei(r){if(r===0)return!1;var n=or(r);if(r!==1){if(Fn(n,"EXT_color_buffer_float"))return Ho(n);if(Fn(n,"EXT_color_buffer_half_float")){var e=n.getExtension("EXT_color_buffer_half_float");return function(t,a){var o=_a(t,a),i=t.createTexture();t.bindTexture(t.TEXTURE_2D,i),t.texImage2D(t.TEXTURE_2D,0,o.internalFormatHalfFloat,1,1,0,o.textureFormatFloat,o.textureTypeHalfFloat,null);var s=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i,0);var u=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE;return t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteTexture(i),t.deleteFramebuffer(s),u}(n,e)}return!1}return!!Fn(n,"OES_texture_float")&&!!Fn(n,"WEBGL_color_buffer_float")&&Ho(n)}function Ho(r){var n=_a(r),e=r.createTexture();r.bindTexture(r.TEXTURE_2D,e),r.texImage2D(r.TEXTURE_2D,0,n.internalFormatFloat,1,1,0,n.textureFormatFloat,n.textureTypeFloat,null);var t=r.createFramebuffer();r.bindFramebuffer(r.FRAMEBUFFER,t),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e,0);var a=r.checkFramebufferStatus(r.FRAMEBUFFER)===r.FRAMEBUFFER_COMPLETE;return r.bindTexture(r.TEXTURE_2D,null),r.bindFramebuffer(r.FRAMEBUFFER,null),r.deleteTexture(e),r.deleteFramebuffer(t),a}function _i(r){return r===2&&or(r).fenceSync!=null}var ps=Object.freeze({callAndCheck:Me,canBeRepresented:ds,getWebGLErrorMessage:jo,getExtensionOrThrow:Ca,createVertexShader:hs,createFragmentShader:ir,createProgram:Vn,linkProgram:sr,validateProgram:Br,createStaticVertexBuffer:Xa,createStaticIndexBuffer:Uo,getNumChannels:function(){return ee().getNumber("WEBGL_VERSION")===2?1:4},createTexture:Ka,validateTextureSize:qa,createFramebuffer:vr,bindVertexBufferToProgramAttribute:Yn,bindTextureUnit:Wo,unbindTextureUnit:function(r,n,e){Go(r,e),Me(r,n,function(){return r.activeTexture(r.TEXTURE0+e)}),Me(r,n,function(){return r.bindTexture(r.TEXTURE_2D,null)})},getProgramUniformLocationOrThrow:gi,getProgramUniformLocation:zo,bindTextureToProgramUniformSampler:Vo,bindCanvasToFramebuffer:function(r,n){Me(r,n,function(){return r.bindFramebuffer(r.FRAMEBUFFER,null)}),Me(r,n,function(){return r.viewport(0,0,r.canvas.width,r.canvas.height)}),Me(r,n,function(){return r.scissor(0,0,r.canvas.width,r.canvas.height)})},bindColorTextureToFramebuffer:Ya,unbindColorTextureFromFramebuffer:$a,validateFramebuffer:Mn,getFramebufferErrorMessage:yi,getBatchDim:ea,getRowsCols:ta,getShapeAs3D:na,getTextureShapeFromLogicalShape:xi,isReshapeFree:ra,getWebGLMaxTextureSize:bi,resetMaxTextureSize:function(){Dn=null},resetMaxTexturesInShader:function(){Zr=null},getMaxTexturesInShader:Qa,getWebGLDisjointQueryTimerVersion:Ra,hasExtension:Fn,isWebGLVersionEnabled:Za,isCapableOfRenderingToFloatTexture:wi,isDownloadFloatTextureEnabled:Ei,isWebGLFenceEnabled:_i}),$e=ee();function Ci(){ee().set("PROD",!0)}function Wu(){ee().set("DEBUG",!0)}function zu(){ee().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function Ri(r){ee().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(r+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function Vu(){X.disposeVariables()}function Aa(){return X}function Gu(){return X.memory()}function fs(r){return X.profile(r)}function en(r,n){return X.tidy(r,n)}function Pn(r){qn(r).forEach(function(n){return n.dispose()})}function vs(r){return X.keep(r)}function Hu(r){return X.time(r)}function Xu(r){return X.setBackend(r)}function ed(){return X.ready()}function Ku(){return X.backendName}function Ai(r){X.removeBackend(r)}function qu(r){return X.findBackend(r)}function ms(r){return X.findBackendFactory(r)}function gs(r,n,e){return e===void 0&&(e=1),X.registerBackend(r,n,e)}function Yu(){return X.backend}function $u(r,n){ee().setPlatform(r,n)}function eo(){for(var r=[],n=0;n<arguments.length;n++)r[n]=arguments[n];ee().getBool("IS_TEST")||console.warn.apply(console,r)}function ur(r,n){var e=r;if(Xt(r))return n==="string"?[]:[r.length];if(!Array.isArray(r))return[];for(var t=[];Array.isArray(e)||Xt(e)&&n!=="string";)t.push(e.length),e=e[0];return Array.isArray(r)&&ee().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&function a(o,i,s){if(s=s||[],!Array.isArray(o)&&!Xt(o))return void D(i.length===0,function(){return"Element arr["+s.join("][")+"] is a primitive, but should be an array/TypedArray of "+i[0]+" elements"});D(i.length>0,function(){return"Element arr["+s.join("][")+"] should be a primitive, but is an array of "+o.length+" elements"}),D(o.length===i[0],function(){return"Element arr["+s.join("][")+"] should have "+i[0]+" elements, but has "+o.length+" elements"});for(var u=i.slice(1),c=0;c<o.length;++c)a(o[c],u,s.concat(c))}(r,t,[]),t}function $n(r,n,e,t){if(r!=null&&(r!=="numeric"&&r!==n||r==="numeric"&&n==="string"))throw new Error("Argument '"+e+"' passed to '"+t+"' must be "+r+" tensor, but got "+n+" tensor")}function F(r,n,e,t){if(t===void 0&&(t="numeric"),r instanceof fn)return $n(t,r.dtype,n,e),r;var a=ar(r);if(a!=="string"&&["bool","int32","float32"].indexOf(t)>=0&&(a=t),$n(t,a,n,e),r==null||!Xt(r)&&!Array.isArray(r)&&typeof r!="number"&&typeof r!="boolean"&&typeof r!="string"){var o=r==null?"null":r.constructor.name;throw new Error("Argument '"+n+"' passed to '"+e+"' must be a Tensor or TensorLike, but got '"+o+"'")}var i=ur(r,a);Xt(r)||Array.isArray(r)||(r=[r]);var s=a!=="string"?L(r,a,ee().getBool("DEBUG")):Ae(r,[],!0);return X.makeTensor(s,i,a)}function aa(r,n,e,t){if(t===void 0&&(t="numeric"),!Array.isArray(r))throw new Error("Argument "+n+" passed to "+e+" must be a `Tensor[]` or `TensorLike[]`");return r.map(function(a,o){return F(a,n+"["+o+"]",e)},t)}function Ti(r,n){for(var e=0;e<r.length;++e)if(r[r.length-e-1]!==n-1-e)return!1;return!0}function Xo(r,n,e){for(var t=r.length+n.length,a=[],o=0,i=0,s=0;s<t;s++)e.indexOf(s)===-1?a.push(r[o++]):a.push(n[i++]);return a}function Nn(r,n){for(var e=[],t=r.length,a=0;a<t;a++)n.indexOf(a)===-1&&e.push(r[a]);return[e,n.map(function(o){return r[o]})]}function kn(r,n){return Xo(r,n.map(function(e){return 1}),n)}function Wn(r,n,e){D(Ti(n,e),function(){return r+" supports only inner-most axes for now. Got axes "+n+" and rank-"+e+" input."})}function Gn(r,n){if(Ti(r,n))return null;for(var e=[],t=0;t<n;++t)r.indexOf(t)===-1&&e.push(t);return r.forEach(function(a){return e.push(a)}),e}function oa(r){return r.map(function(n,e){return[e,n]}).sort(function(n,e){return n[1]-e[1]}).map(function(n){return n[0]})}function Jn(r,n){for(var e=[],t=n-r;t<n;++t)e.push(t);return e}function Di(r,n){var e=r[0].length;r.forEach(function(a,o){D(a.length===e,function(){return"Error in concat"+e+"D: rank of tensors["+o+"] must be the same as the rank of the rest ("+e+")"})}),D(n>=0&&n<e,function(){return"Error in concat"+e+"D: axis must be between 0 and "+(e-1)+"."});var t=r[0];r.forEach(function(a,o){for(var i=0;i<e;i++)D(i===n||a[i]===t[i],function(){return"Error in concat"+e+"D: Shape of tensors["+o+"] ("+a+") does not match the shape of the rest ("+t+") along the non-concatenated axis "+o+"."})})}function jr(r,n){for(var e=r[0].slice(),t=1;t<r.length;t++)e[n]+=r[t][n];return e}function K(r){var n=Object.keys(r);if(n.length!==1)throw new Error("Please provide an object with a single key (operation name) mapping to a function. Got an object with "+n.length+" keys.");var e=n[0],t=r[e];e.endsWith("_")&&(e=e.substring(0,e.length-1));var a=function(){for(var o=[],i=0;i<arguments.length;i++)o[i]=arguments[i];X.startScope(e);try{var s=t.apply(void 0,o);return s instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),X.endScope(s),s}catch(u){throw X.endScope(null),u}};return Object.defineProperty(a,"name",{value:e,configurable:!0}),a}$e.registerFlag("HAS_WEBGL",function(){return $e.getNumber("WEBGL_VERSION")>0}),$e.registerFlag("WEBGL_VERSION",function(){return Za(2)?2:Za(1)?1:0}),$e.registerFlag("WEBGL_BUFFER_SUPPORTED",function(){return $e.get("WEBGL_VERSION")===2}),$e.registerFlag("WEBGL_CPU_FORWARD",function(){return!0}),$e.registerFlag("WEBGL_FORCE_F16_TEXTURES",function(){return!1}),$e.registerFlag("WEBGL_PACK",function(){return $e.getBool("HAS_WEBGL")}),$e.registerFlag("WEBGL_PACK_NORMALIZATION",function(){return $e.getBool("WEBGL_PACK")}),$e.registerFlag("WEBGL_PACK_CLIP",function(){return $e.getBool("WEBGL_PACK")}),$e.registerFlag("WEBGL_PACK_DEPTHWISECONV",function(){return!1}),$e.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",function(){return $e.getBool("WEBGL_PACK")}),$e.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",function(){return $e.getBool("WEBGL_PACK")}),$e.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",function(){return $e.getBool("WEBGL_PACK")}),$e.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",function(){return $e.getBool("WEBGL_PACK")}),$e.registerFlag("WEBGL_PACK_REDUCE",function(){return $e.getBool("WEBGL_PACK")}),$e.registerFlag("WEBGL_LAZILY_UNPACK",function(){return $e.getBool("WEBGL_PACK")}),$e.registerFlag("WEBGL_CONV_IM2COL",function(){return $e.getBool("WEBGL_PACK")}),$e.registerFlag("WEBGL_MAX_TEXTURE_SIZE",function(){return bi($e.getNumber("WEBGL_VERSION"))}),$e.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",function(){return Qa($e.getNumber("WEBGL_VERSION"))}),$e.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",function(){var r=$e.getNumber("WEBGL_VERSION");return r===0?0:Ra(r)}),$e.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",function(){return $e.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&(r=navigator.userAgent||navigator.vendor||window.opera,!(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(r)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(r.substr(0,4))));var r}),$e.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",function(){return wi($e.getNumber("WEBGL_VERSION"))}),$e.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",function(){return!$e.getBool("WEBGL_FORCE_F16_TEXTURES")&&$e.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")}),$e.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",function(){return Ei($e.getNumber("WEBGL_VERSION"))}),$e.registerFlag("WEBGL_FENCE_API_ENABLED",function(){return _i($e.getNumber("WEBGL_VERSION"))}),$e.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",function(){return $e.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0}),So=Ri;var zt=K({complex_:function(r,n){var e=F(r,"real","complex"),t=F(n,"imag","complex");return se(e.shape,t.shape,"real and imag shapes, "+e.shape+" and "+t.shape+", must match in call to tf.complex()."),X.runKernelFunc(function(a){return a.complex(e,t)},{$real:e,$imag:t})}}),Hn=K({real_:function(r){var n=F(r,"input","real");return X.runKernelFunc(function(e){return e.real(n)},{$input:n})}}),cr=K({imag_:function(r){var n=F(r,"input","imag");return X.runKernelFunc(function(e){return e.imag(n)},{$input:n})}});function _n(r,n,e){return wr(r,n,ur(r,e),e)}function wr(r,n,e,t){if(t==null&&(t=ar(r)),t==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!Xt(r)&&!Array.isArray(r)&&typeof r!="number"&&typeof r!="boolean"&&typeof r!="string")throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(n!=null){de(n);var a=ae(n),o=ae(e);D(a===o,function(){return"Based on the provided shape, ["+n+"], the tensor should have "+a+" values but has "+o});for(var i=0;i<e.length;++i){var s=e[i],u=i!==e.length-1||s!==ae(n.slice(i));D(e[i]===n[i]||!u,function(){return"Error creating a new Tensor. Inferred shape ("+e+") does not match the provided shape ("+n+"). "})}}return Xt(r)||Array.isArray(r)||(r=[r]),n=n||e,r=t!=="string"?L(r,t,ee().getBool("DEBUG")):Ae(r,[],!0),X.makeTensor(r,n,t)}function We(r,n){if((Xt(r)&&n!=="string"||Array.isArray(r))&&n!=="complex64")throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if(n==="string"&&Xt(r)&&!(r instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return wr(r,[],[],n)}function Ur(r,n){Te(r);var e=ur(r,n);if(e.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return wr(r,null,e,n)}function Wr(r,n,e){if(Te(r),n!=null&&n.length!==2)throw new Error("tensor2d() requires shape to have two numbers");var t=ur(r,e);if(t.length!==2&&t.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(t.length===1&&n==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return wr(r,n,t,e)}function Ko(r,n,e){if(Te(r),n!=null&&n.length!==3)throw new Error("tensor3d() requires shape to have three numbers");var t=ur(r,e);if(t.length!==3&&t.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(t.length===1&&n==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return wr(r,n,t,e)}function Er(r,n,e){if(Te(r),n!=null&&n.length!==4)throw new Error("tensor4d() requires shape to have four numbers");var t=ur(r,e);if(t.length!==4&&t.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(t.length===1&&n==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return wr(r,n,t,e)}function ia(r,n,e){if(Te(r),n!=null&&n.length!==5)throw new Error("tensor5d() requires shape to have five numbers");var t=ur(r,e);if(t.length!==5&&t.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(t.length===1&&n==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return wr(r,n,t,e)}function ys(r,n,e){if(Te(r),n!=null&&n.length!==6)throw new Error("tensor6d() requires shape to have six numbers");var t=ur(r,e);if(t.length!==6&&t.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(t.length===1&&n==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return wr(r,n=n||t,t,e)}function sa(r,n,e,t){return n===void 0&&(n=!0),X.makeVariable(r,n,e,t)}function _r(r,n){if(n===void 0&&(n="float32"),n==="complex64"){var e=_r(r,"float32"),t=Jt(r,"float32");return zt(e,t)}var a=R(ae(r),n);return X.makeTensor(a,r,n)}function Jt(r,n){if(n===void 0&&(n="float32"),n==="complex64"){var e=Jt(r,"float32"),t=Jt(r,"float32");return zt(e,t)}var a=U(ae(r),n);return X.makeTensor(a,r,n)}function qo(r,n,e){return X.runKernelFunc(function(t){return t.fill(r,n,e)},{})}function Ju(r,n,e){if(e<=0)throw new Error("The number of values should be positive.");return X.runKernelFunc(function(t){return t.linspace(r,n,e)},{})}function to(r,n,e,t){if(e===void 0&&(e=1),t===void 0&&(t="float32"),e===0)throw new Error("Cannot have a step of zero");if(r===n||r<n&&e<0||n<r&&e>1)return Jt([0],t);var a=U(Math.abs(Math.ceil((n-r)/e)),t);n<r&&e===1&&(e=-1),a[0]=r;for(var o=1;o<a.length;o++)a[o]=a[o-1]+e;return Ur(a,t)}var Ni=K({onesLike_:function(r){var n=F(r,"x","onesLike");if(n.dtype==="complex64"){var e=Ni(Hn(n)),t=gt(cr(n));return zt(e,t)}return X.runKernelFunc(function(a){return a.onesLike(n)},{$x:n},function(a,o){return{$x:function(){return gt(a)}}})}}),gt=K({zerosLike_:function(r){var n=F(r,"x","zerosLike");return X.runKernelFunc(function(e){return e.zerosLike(n)},{$x:n},function(e,t){return{$x:function(){return gt(e)}}})}}),Qn=K({concat_:function(r,n){n===void 0&&(n=0),D(r.length>=1,function(){return"Pass at least one tensor to concat"});var e=aa(r,"tensors","concat");e[0].dtype==="complex64"&&e.forEach(function(s){if(s.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor
|
|
with dtype `+s.dtype+". ")}),n=je(n,e[0].shape)[0];var t=jr(e.map(function(s){return s.shape}),n);if(ae(t)===0)return _n([],t);if((e=e.filter(function(s){return s.size>0})).length===1)return e[0];var a=e.map(function(s){return s.shape});Di(a,n);var o=e,i={axis:n};return X.runKernelFunc(function(s){return s.concat(e,n)},o,function(s){var u=a.map(function(c){return c[n]});return Ta(s,u,n).map(function(c){return function(){return c}})},"Concat",i)}}),xs=K({concat1d_:function(r){return Qn(r,0)}}),bs=K({concat2d_:function(r,n){return Qn(r,n)}}),no=K({concat3d_:function(r,n){return Qn(r,n)}}),ws=K({concat4d_:function(r,n){return Qn(r,n)}}),Ta=K({split_:function(r,n,e){e===void 0&&(e=0);var t,a=F(r,"x","split");return e=je(e,a.shape)[0],typeof n=="number"?(D(a.shape[e]%n==0,function(){return"Number of splits must evenly divide the axis."}),t=new Array(n).fill(a.shape[e]/n)):(D(a.shape[e]===n.reduce(function(o,i){return o+i}),function(){return"The sum of sizes must match the size of the axis dimension."}),t=n),X.runKernelFunc(function(o){return o.split(a,t,e)},{$x:a},function(o){return{$x:function(){return Qn(o,e)}}})}});typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof Se!="undefined"||typeof self!="undefined"&&self;function Ln(r,n){return r(n={exports:{}},n.exports),n.exports}var Cr=Ln(function(r){!function(n,e,t){function a(s){var u,c=this,d=(u=4022871197,function(f){f=f.toString();for(var m=0;m<f.length;m++){var g=.02519603282416938*(u+=f.charCodeAt(m));g-=u=g>>>0,u=(g*=u)>>>0,u+=4294967296*(g-=u)}return 23283064365386963e-26*(u>>>0)});c.next=function(){var f=2091639*c.s0+23283064365386963e-26*c.c;return c.s0=c.s1,c.s1=c.s2,c.s2=f-(c.c=0|f)},c.c=1,c.s0=d(" "),c.s1=d(" "),c.s2=d(" "),c.s0-=d(s),c.s0<0&&(c.s0+=1),c.s1-=d(s),c.s1<0&&(c.s1+=1),c.s2-=d(s),c.s2<0&&(c.s2+=1),d=null}function o(s,u){return u.c=s.c,u.s0=s.s0,u.s1=s.s1,u.s2=s.s2,u}function i(s,u){var c=new a(s),d=u&&u.state,f=c.next;return f.int32=function(){return 4294967296*c.next()|0},f.double=function(){return f()+11102230246251565e-32*(2097152*f()|0)},f.quick=f,d&&(typeof d=="object"&&o(d,c),f.state=function(){return o(c,{})}),f}e&&e.exports?e.exports=i:t&&t.amd?t(function(){return i}):this.alea=i}(0,r,!1)}),Es=Ln(function(r){!function(n,e,t){function a(s){var u=this,c="";u.x=0,u.y=0,u.z=0,u.w=0,u.next=function(){var f=u.x^u.x<<11;return u.x=u.y,u.y=u.z,u.z=u.w,u.w^=u.w>>>19^f^f>>>8},s===(0|s)?u.x=s:c+=s;for(var d=0;d<c.length+64;d++)u.x^=0|c.charCodeAt(d),u.next()}function o(s,u){return u.x=s.x,u.y=s.y,u.z=s.z,u.w=s.w,u}function i(s,u){var c=new a(s),d=u&&u.state,f=function(){return(c.next()>>>0)/4294967296};return f.double=function(){do var m=((c.next()>>>11)+(c.next()>>>0)/4294967296)/(1<<21);while(m===0);return m},f.int32=c.next,f.quick=f,d&&(typeof d=="object"&&o(d,c),f.state=function(){return o(c,{})}),f}e&&e.exports?e.exports=i:t&&t.amd?t(function(){return i}):this.xor128=i}(0,r,!1)}),_s=Ln(function(r){!function(n,e,t){function a(s){var u=this,c="";u.next=function(){var f=u.x^u.x>>>2;return u.x=u.y,u.y=u.z,u.z=u.w,u.w=u.v,(u.d=u.d+362437|0)+(u.v=u.v^u.v<<4^f^f<<1)|0},u.x=0,u.y=0,u.z=0,u.w=0,u.v=0,s===(0|s)?u.x=s:c+=s;for(var d=0;d<c.length+64;d++)u.x^=0|c.charCodeAt(d),d==c.length&&(u.d=u.x<<10^u.x>>>4),u.next()}function o(s,u){return u.x=s.x,u.y=s.y,u.z=s.z,u.w=s.w,u.v=s.v,u.d=s.d,u}function i(s,u){var c=new a(s),d=u&&u.state,f=function(){return(c.next()>>>0)/4294967296};return f.double=function(){do var m=((c.next()>>>11)+(c.next()>>>0)/4294967296)/(1<<21);while(m===0);return m},f.int32=c.next,f.quick=f,d&&(typeof d=="object"&&o(d,c),f.state=function(){return o(c,{})}),f}e&&e.exports?e.exports=i:t&&t.amd?t(function(){return i}):this.xorwow=i}(0,r,!1)}),Cs=Ln(function(r){!function(n,e,t){function a(s){var u=this;u.next=function(){var c,d,f=u.x,m=u.i;return c=f[m],d=(c^=c>>>7)^c<<24,d^=(c=f[m+1&7])^c>>>10,d^=(c=f[m+3&7])^c>>>3,d^=(c=f[m+4&7])^c<<7,c=f[m+7&7],d^=(c^=c<<13)^c<<9,f[m]=d,u.i=m+1&7,d},function(c,d){var f,m=[];if(d===(0|d))m[0]=d;else for(d=""+d,f=0;f<d.length;++f)m[7&f]=m[7&f]<<15^d.charCodeAt(f)+m[f+1&7]<<13;for(;m.length<8;)m.push(0);for(f=0;f<8&&m[f]===0;++f);for(f==8?m[7]=-1:m[f],c.x=m,c.i=0,f=256;f>0;--f)c.next()}(u,s)}function o(s,u){return u.x=s.x.slice(),u.i=s.i,u}function i(s,u){s==null&&(s=+new Date);var c=new a(s),d=u&&u.state,f=function(){return(c.next()>>>0)/4294967296};return f.double=function(){do var m=((c.next()>>>11)+(c.next()>>>0)/4294967296)/(1<<21);while(m===0);return m},f.int32=c.next,f.quick=f,d&&(d.x&&o(d,c),f.state=function(){return o(c,{})}),f}e&&e.exports?e.exports=i:t&&t.amd?t(function(){return i}):this.xorshift7=i}(0,r,!1)}),Rs=Ln(function(r){!function(n,e,t){function a(s){var u=this;u.next=function(){var c,d,f=u.w,m=u.X,g=u.i;return u.w=f=f+1640531527|0,d=m[g+34&127],c=m[g=g+1&127],d^=d<<13,c^=c<<17,d^=d>>>15,c^=c>>>12,d=m[g]=d^c,u.i=g,d+(f^f>>>16)|0},function(c,d){var f,m,g,x,E,w=[],C=128;for(d===(0|d)?(m=d,d=null):(d+="\0",m=0,C=Math.max(C,d.length)),g=0,x=-32;x<C;++x)d&&(m^=d.charCodeAt((x+32)%d.length)),x===0&&(E=m),m^=m<<10,m^=m>>>15,m^=m<<4,m^=m>>>13,x>=0&&(E=E+1640531527|0,g=(f=w[127&x]^=m+E)==0?g+1:0);for(g>=128&&(w[127&(d&&d.length||0)]=-1),g=127,x=512;x>0;--x)m=w[g+34&127],f=w[g=g+1&127],m^=m<<13,f^=f<<17,m^=m>>>15,f^=f>>>12,w[g]=m^f;c.w=E,c.X=w,c.i=g}(u,s)}function o(s,u){return u.i=s.i,u.w=s.w,u.X=s.X.slice(),u}function i(s,u){s==null&&(s=+new Date);var c=new a(s),d=u&&u.state,f=function(){return(c.next()>>>0)/4294967296};return f.double=function(){do var m=((c.next()>>>11)+(c.next()>>>0)/4294967296)/(1<<21);while(m===0);return m},f.int32=c.next,f.quick=f,d&&(d.X&&o(d,c),f.state=function(){return o(c,{})}),f}e&&e.exports?e.exports=i:t&&t.amd?t(function(){return i}):this.xor4096=i}(0,r,!1)}),ki=Ln(function(r){!function(n,e,t){function a(s){var u=this,c="";u.next=function(){var f=u.b,m=u.c,g=u.d,x=u.a;return f=f<<25^f>>>7^m,m=m-g|0,g=g<<24^g>>>8^x,x=x-f|0,u.b=f=f<<20^f>>>12^m,u.c=m=m-g|0,u.d=g<<16^m>>>16^x,u.a=x-f|0},u.a=0,u.b=0,u.c=-1640531527,u.d=1367130551,s===Math.floor(s)?(u.a=s/4294967296|0,u.b=0|s):c+=s;for(var d=0;d<c.length+20;d++)u.b^=0|c.charCodeAt(d),u.next()}function o(s,u){return u.a=s.a,u.b=s.b,u.c=s.c,u.d=s.d,u}function i(s,u){var c=new a(s),d=u&&u.state,f=function(){return(c.next()>>>0)/4294967296};return f.double=function(){do var m=((c.next()>>>11)+(c.next()>>>0)/4294967296)/(1<<21);while(m===0);return m},f.int32=c.next,f.quick=f,d&&(typeof d=="object"&&o(d,c),f.state=function(){return o(c,{})}),f}e&&e.exports?e.exports=i:t&&t.amd?t(function(){return i}):this.tychei=i}(0,r,!1)}),lr=Ln(function(r){!function(n,e){var t,a=this,o=256,i=6,s="random",u=e.pow(o,i),c=e.pow(2,52),d=2*c,f=o-1;function m(C,N,S){var I=[],M=E(function z(W,V){var Z,J=[],me=typeof W;if(V&&me=="object")for(Z in W)try{J.push(z(W[Z],V-1))}catch(fe){}return J.length?J:me=="string"?W:W+"\0"}((N=N==1?{entropy:!0}:N||{}).entropy?[C,w(n)]:C==null?function(){try{var z;return t&&(z=t.randomBytes)?z=z(o):(z=new Uint8Array(o),(a.crypto||a.msCrypto).getRandomValues(z)),w(z)}catch(Z){var W=a.navigator,V=W&&W.plugins;return[+new Date,a,V,a.screen,w(n)]}}():C,3),I),j=new g(I),G=function(){for(var z=j.g(i),W=u,V=0;z<c;)z=(z+V)*o,W*=o,V=j.g(1);for(;z>=d;)z/=2,W/=2,V>>>=1;return(z+V)/W};return G.int32=function(){return 0|j.g(4)},G.quick=function(){return j.g(4)/4294967296},G.double=G,E(w(j.S),n),(N.pass||S||function(z,W,V,Z){return Z&&(Z.S&&x(Z,j),z.state=function(){return x(j,{})}),V?(e[s]=z,W):z})(G,M,"global"in N?N.global:this==e,N.state)}function g(C){var N,S=C.length,I=this,M=0,j=I.i=I.j=0,G=I.S=[];for(S||(C=[S++]);M<o;)G[M]=M++;for(M=0;M<o;M++)G[M]=G[j=f&j+C[M%S]+(N=G[M])],G[j]=N;(I.g=function(z){for(var W,V=0,Z=I.i,J=I.j,me=I.S;z--;)W=me[Z=f&Z+1],V=V*o+me[f&(me[Z]=me[J=f&J+W])+(me[J]=W)];return I.i=Z,I.j=J,V})(o)}function x(C,N){return N.i=C.i,N.j=C.j,N.S=C.S.slice(),N}function E(C,N){for(var S,I=C+"",M=0;M<I.length;)N[f&M]=f&(S^=19*N[f&M])+I.charCodeAt(M++);return w(N)}function w(C){return String.fromCharCode.apply(0,C)}if(e["seed"+s]=m,E(e.random(),n),r.exports){r.exports=m;try{t=te(5)}catch(C){}}}([],Math)});lr.alea=Cr,lr.xor128=Es,lr.xorwow=_s,lr.xorshift7=Cs,lr.xor4096=Rs,lr.tychei=ki;var Da=lr.alea,ro=function(){function r(n,e,t,a,o){this.mean=n,this.stdDev=e,this.dtype=t,this.nextVal=NaN,this.truncated=a,this.truncated&&(this.upper=this.mean+2*this.stdDev,this.lower=this.mean-2*this.stdDev);var i=o||Math.random();this.random=Da(i.toString())}return r.prototype.nextValue=function(){if(!isNaN(this.nextVal)){var n=this.nextVal;return this.nextVal=NaN,n}for(var e,t,a=!1;!a;){var o=void 0,i=void 0,s=void 0;do s=(o=2*this.random()-1)*o+(i=2*this.random()-1)*i;while(s>=1||s===0);var u=Math.sqrt(-2*Math.log(s)/s);e=this.mean+this.stdDev*o*u,t=this.mean+this.stdDev*i*u,this.truncated&&!this.isValidTruncated(e)||(a=!0)}return this.truncated&&!this.isValidTruncated(t)||(this.nextVal=this.convertValue(t)),this.convertValue(e)},r.prototype.convertValue=function(n){return this.dtype==null||this.dtype==="float32"?n:Math.round(n)},r.prototype.isValidTruncated=function(n){return n<=this.upper&&n>=this.lower},r}(),Qu=function(){function r(n,e,t,a){this.alpha=n,this.beta=1/e,this.dtype=t;var o=a||Math.random();this.randu=Da(o.toString()),this.randn=new ro(0,1,t,!1,this.randu()),this.d=n<1?n+2/3:n-1/3,this.c=1/Math.sqrt(9*this.d)}return r.prototype.nextValue=function(){for(var n,e,t,a,o,i;;){do a=this.randn.nextValue(),i=1+this.c*a;while(i<=0);if(i*=i*i,e=1-.331*(n=a*a)*n,t=.5*n+this.d*(1-i+Math.log(i)),(o=this.randu())<e||Math.log(o)<t)break}return i=1/this.beta*this.d*i,this.alpha<1&&(i*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(i)},r.prototype.convertValue=function(n){return this.dtype==="float32"?n:Math.round(n)},r}(),Si=function(){function r(n,e,t,a){var o=this;if(n===void 0&&(n=0),e===void 0&&(e=1),this.canReturnFloat=function(){return o.dtype==null||o.dtype==="float32"},this.min=n,this.range=e-n,this.dtype=t,a==null&&(a=Math.random()),typeof a=="number"&&(a=a.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error("The difference between "+n+" - "+e+" <= 1 and dtype is not float");this.random=Da(a)}return r.prototype.convertValue=function(n){return this.canReturnFloat()?n:Math.round(n)},r.prototype.nextValue=function(){return this.convertValue(this.min+this.range*this.random())},r}();function Je(r,n,e){return n===void 0&&(n="float32"),n=n||"float32",de(r),new za(r,n,e)}function ao(r,n){n===void 0&&(n=!1),console.log(r.toString(n))}var oo=K({batchToSpaceND_:function(r,n,e){var t=F(r,"x","batchToSpaceND"),a=n.reduce(function(o,i){return o*i});return D(t.rank>=1+n.length,function(){return"input rank is "+t.rank+" but should be > than blockShape.length "+n.length}),D(e.length===n.length,function(){return"crops.length is "+e.length+" but should be equal to blockShape.length "+n.length}),D(t.shape[0]%a==0,function(){return"input tensor batch is "+t.shape[0]+" but is not divisible by the product of the elements of blockShape "+n.join(" * ")+" === "+a}),X.runKernelFunc(function(o){return o.batchToSpaceND(t,n,e)},{$x:t},function(o){return{$x:function(){return o.spaceToBatchND(n,e)}}})}}),As=K({broadcastTo_:function(r,n){var e=F(r,"broadcastTo","x"),t=e.shape;if(n.some(function(u){return!(u>0)||u%1!=0}))throw new Error("broadcastTo(): Invalid broadcast shape ["+n+"].");if(n.length<e.rank)throw new Error("broadcastTo(): shape.length="+n.length+" < input.rank="+e.rank+".");if(n.length>e.rank){for(var a=e.shape.slice();a.length<n.length;)a.unshift(1);e=e.reshape(a)}for(var o=Array.from(n),i=n.length-1;i>=0;i--)if(e.shape[i]===n[i])o[i]=1;else if(e.shape[i]!==1)throw new Error("broadcastTo(): ["+t+"] cannot be broadcast to ["+n+"].");var s=o.map(function(u,c){return u>1?c:-1}).filter(function(u){return u>=0});return s.length===0?e.clone():X.runKernelFunc(function(u){return u.tile(e,o)},{input:e},function(u){return{input:function(){return u.sum(s,!0)}}})}}),io=K({cast_:function(r,n){var e=F(r,"x","cast");if(!xr(n))throw new Error("Failed to cast to unknown dtype "+n);if(n==="string"&&e.dtype!=="string"||n!=="string"&&e.dtype==="string")throw new Error("Only strings can be casted to strings");var t={dtype:n};return X.runKernelFunc(function(a){return a.cast(e,n)},{x:e},function(a){return{x:function(){return a.clone()}}},"Cast",t)}}),so=K({clone_:function(r){var n=F(r,"x","clone",null);return X.runKernelFunc(function(){return X.makeTensorFromDataId(n.dataId,n.shape,n.dtype)},{$x:n},function(e){return{$x:function(){return e.toFloat()}}})}}),Ts=K({cumsum_:function(r,n,e,t){n===void 0&&(n=0),e===void 0&&(e=!1),t===void 0&&(t=!1);var a=F(r,"x","cumsum"),o=Gn([n|=0],a.rank),i=a;o!=null&&(i=a.transpose(o));var s=Jn(1,a.rank)[0],u=X.runKernelFunc(function(c){return c.cumsum(i,s,e,t)},{permutedX:i},function(c){return{permutedX:function(){return c.cumsum(n,e,!t)}}});return o!=null&&(u=u.transpose(o)),u}}),Ds=K({depthToSpace_:function(r,n,e){e===void 0&&(e="NHWC");var t=F(r,"x","depthToSpace"),a=e==="NHWC"?t.shape[1]:t.shape[2],o=e==="NHWC"?t.shape[2]:t.shape[3],i=e==="NHWC"?t.shape[3]:t.shape[1];return D(a*n>=0,function(){return`Negative dimension size caused by overflow when multiplying
|
|
`+a+" and "+n+` for depthToSpace with input shape
|
|
`+t.shape}),D(o*n>=0,function(){return`Negative dimension size caused by overflow when multiplying
|
|
`+o+" and "+n+` for depthToSpace with input shape
|
|
`+t.shape}),D(i%(n*n)==0,function(){return"Dimension size must be evenly divisible by "+n*n+" but is "+i+" for depthToSpace with input shape "+t.shape}),X.runKernelFunc(function(s){return s.depthToSpace(t,n,e)},{$x:t})}}),gr=K({expandDims_:function(r,n){n===void 0&&(n=0);var e=F(r,"x","expandDims",null);D(n<=e.rank,function(){return"Axis must be <= rank of the tensor"});var t=e.shape.slice();return n<0&&(D(-(e.rank+1)<=n,function(){return"Axis must be in the interval ["+-(e.rank+1)+", "+e.rank+"]"}),n=e.rank+n+1),t.splice(n,0,1),uo(e,t)}}),Oi=K({eye_:function(r,n,e,t){t===void 0&&(t="float32"),n==null&&(n=r);for(var a=Je([r,n],t),o=r<=n?r:n,i=0;i<o;++i)a.set(1,i,i);var s=a.toTensor().as2D(r,n);if(e==null)return s;if(e.length===1)return zr(gr(s,0),[e[0],1,1]);if(e.length===2)return zr(gr(gr(s,0),0),[e[0],e[1],1,1]);if(e.length===3)return zr(gr(gr(gr(s,0),0),0),[e[0],e[1],e[2],1,1]);throw new Error("eye() currently supports only 1D and 2D batchShapes, but received "+e.length+"D.")}}),Yo=K({multinomial_:function(r,n,e,t){t===void 0&&(t=!1);var a=F(r,"logits","multinomial"),o=a.size,i=a.rank;if(o<2)throw new Error("Error in multinomial: you need at least 2 outcomes, but got "+o+".");if(i>2)throw new Error("Rank of probabilities must be 1 or 2, but is "+i);e=e||Math.random();var s=i===1?a.as2D(1,-1):a,u=X.runKernelFunc(function(c){return c.multinomial(s,t,n,e)},{logits2D:s});return i===1?u.as1D():u}}),$o=K({oneHot_:function(r,n,e,t){if(e===void 0&&(e=1),t===void 0&&(t=0),n<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+n);var a=F(r,"indices","oneHot","int32"),o=a.shape.concat([n]);return a=a.flatten(),X.runKernelFunc(function(i){return i.oneHot(a,n,e,t)},{$indices:a},function(i){return{$indices:function(){return Jt(a.shape,"float32")}}}).reshape(o)}}),Rr=K({pad_:function(r,n,e){e===void 0&&(e=0);var t=F(r,"x","pad");if(t.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var a={paddings:n,constantValue:e};return X.runKernelFunc(function(o){return o.pad(t,n,e)},{x:t},function(o){var i=n.map(function(s){return s[0]});return{x:function(){return o.slice(i,t.shape)}}},"PadV2",a)}}),Ii=K({pad1d_:function(r,n,e){return e===void 0&&(e=0),D(n.length===2,function(){return"Invalid number of paddings. Must be length of 2."}),Rr(r,[n],e)}}),ua=K({pad2d_:function(r,n,e){return e===void 0&&(e=0),D(n.length===2&&n[0].length===2&&n[1].length===2,function(){return"Invalid number of paddings. Must be length of 2 each."}),Rr(r,n,e)}}),Jo=K({pad3d_:function(r,n,e){return e===void 0&&(e=0),D(n.length===3&&n[0].length===2&&n[1].length===2&&n[2].length===2,function(){return"Invalid number of paddings. Must be length of 2 each."}),Rr(r,n,e)}}),Ns=K({pad4d_:function(r,n,e){return e===void 0&&(e=0),D(n.length===4&&n[0].length===2&&n[1].length===2&&n[2].length===2&&n[3].length===2,function(){return"Invalid number of paddings. Must be length of 2 each."}),Rr(r,n,e)}}),ks=K({rand_:function(r,n,e){var t=ae(r),a=null;if(e==null||e==="float32")a=new Float32Array(t);else if(e==="int32")a=new Int32Array(t);else{if(e!=="bool")throw new Error("Unknown data type "+e);a=new Uint8Array(t)}for(var o=0;o<t;o++)a[o]=n();return X.makeTensor(a,r,e)}}),Ss=K({randomNormal_:function(r,n,e,t,a){if(n===void 0&&(n=0),e===void 0&&(e=1),t!=null&&t==="bool")throw new Error("Unsupported data type "+t);for(var o=new ro(n,e,t,!1,a),i=Je(r,t),s=0;s<i.values.length;s++)i.values[s]=o.nextValue();return i.toTensor()}}),Os=K({randomGamma_:function(r,n,e,t,a){if(e===void 0&&(e=1),t===void 0&&(t="float32"),e==null&&(e=1),t==null&&(t="float32"),t!=="float32"&&t!=="int32")throw new Error("Unsupported data type "+t);for(var o=new Qu(n,e,t,a),i=Je(r,t),s=0;s<i.values.length;s++)i.values[s]=o.nextValue();return i.toTensor()}}),Qo=K({randomUniform_:function(r,n,e,t,a){n===void 0&&(n=0),e===void 0&&(e=1),t===void 0&&(t="float32");for(var o=Je(r,t),i=new Si(n,e,null,a),s=0;s<o.values.length;s++)o.values[s]=i.nextValue();return o.toTensor()}}),uo=K({reshape_:function(r,n){var e=F(r,"x","reshape",null);n=lt(n,e.size),D(e.size===ae(n),function(){return"new shape and old shape must have the same number of elements."});var t={shape:n};return X.runKernelFunc(function(a){return a.reshape(e,n)},{x:e},function(a){return{x:function(){return a.reshape(e.shape)}}},"Reshape",t)}}),Mi=K({spaceToBatchND_:function(r,n,e){var t=F(r,"x","spaceToBatchND");return D(t.rank>=1+n.length,function(){return"input rank "+t.rank+" should be > than [blockShape] "+n.length}),D(e.length===n.length,function(){return"paddings.shape[0] "+e.length+" must be equal to [blockShape] "+n.length}),D(t.shape.reduce(function(a,o,i){return i>0&&i<=n.length?a&&(o+e[i-1][0]+e[i-1][1])%n[i-1]==0:a},!0),function(){return"input spatial dimensions "+t.shape.slice(1)+" with paddings "+e.toString()+" must be divisible by blockShapes "+n.toString()}),X.runKernelFunc(function(a){return a.spaceToBatchND(t,n,e)},{$x:t},function(a){return{$x:function(){return a.batchToSpaceND(n,e)}}})}}),Fi=K({squeeze_:function(r,n){var e=F(r,"x","squeeze");return uo(e,St(e.shape,n).newShape)}}),Ar=K({stack_:function(r,n){n===void 0&&(n=0);var e=aa(r,"tensors","stack");if(D(e.length>=1,function(){return"Pass at least one tensor to tf.stack"}),e.length===1)return e[0].expandDims(n);var t=e[0].rank,a=e[0].shape,o=e[0].dtype;D(n<=t,function(){return"Axis must be <= rank of the tensor"}),e.forEach(function(s){se(a,s.shape,"All tensors passed to stack must have matching shapes")}),e.forEach(function(s){D(o===s.dtype,function(){return"All tensors passed to stack must have matching dtypes"})});var i=e.map(function(s){return s.expandDims(n)});return Qn(i,n)}}),zr=K({tile_:function(r,n){var e=F(r,"x","tile",null);D(e.rank===n.length,function(){return"Error in transpose: rank of input "+e.rank+" must match length of reps "+n+"."});var t=[e],a={reps:n};return X.runKernelFunc(function(o,i){var s=o.tile(e,n);return i([e]),s},{x:e},function(o,i){var s=i[0];return{x:function(){var u=gt(s);if(s.rank===1)for(var c=0;c<n[0];++c)u=u.add(o.slice([c*s.shape[0]],[s.shape[0]]));else if(s.rank===2)for(c=0;c<n[0];++c)for(var d=0;d<n[1];++d)u=u.add(o.slice([c*s.shape[0],d*s.shape[1]],[s.shape[0],s.shape[1]]));else if(s.rank===3)for(c=0;c<n[0];++c)for(d=0;d<n[1];++d)for(var f=0;f<n[2];++f)u=u.add(o.slice([c*s.shape[0],d*s.shape[1],f*s.shape[2]],[s.shape[0],s.shape[1],s.shape[2]]));else{if(s.rank!==4)throw new Error("Gradient for tile operation is not implemented for rank-"+s.rank+" tensors yet.");for(c=0;c<n[0];++c)for(d=0;d<n[1];++d)for(f=0;f<n[2];++f)for(var m=0;m<n[3];++m)u=u.add(o.slice([c*s.shape[0],d*s.shape[1],f*s.shape[2],m*s.shape[3]],[s.shape[0],s.shape[1],s.shape[2],s.shape[3]]))}return u}}},"Tile",a,t)}}),Is=K({truncatedNormal_:function(r,n,e,t,a){if(n===void 0&&(n=0),e===void 0&&(e=1),t!=null&&t==="bool")throw new Error("Unsupported data type "+t);for(var o=new ro(n,e,t,!0,a),i=Je(r,t),s=0;s<i.values.length;s++)i.values[s]=o.nextValue();return i.toTensor()}}),co=K({unstack_:function(r,n){n===void 0&&(n=0),n=n||0;var e=F(r,"x","unstack");D(n>=-e.shape.length&&n<e.shape.length,function(){return"Axis = "+n+" is not in [-"+e.shape.length+", "+e.shape.length+")"}),n<0&&(n+=e.shape.length);var t={axis:n};return X.runKernelFunc(function(a){return a.unstack(e,n)},{x:e},function(a){return{x:function(){return Ar(a,n)}}},"Unpack",t)}}),Ms=function(r,n){return ve(this,void 0,void 0,function(){var e,t,a,o,i,s,u,c,d,f;return ye(this,function(m){switch(m.label){case 0:return e=F(r,"x","setdiff1d"),t=F(n,"y","setdiff1d"),D(e.dtype===t.dtype,function(){return"x and y should have the same dtype, but got x ("+e.dtype+") and y ("+t.dtype+")."}),D(e.rank===1,function(){return"x should be 1D tensor, but got x ("+e.shape+")."}),D(t.rank===1,function(){return"y should be 1D tensor, but got y ("+t.shape+")."}),[4,e.data()];case 1:return a=m.sent(),[4,t.data()];case 2:for(o=m.sent(),i=new Set(o),s=0,d=0;d<a.length;d++)i.has(a[d])||s++;for(u=new za([s],e.dtype),c=new za([s],"int32"),d=0,f=0;d<a.length;d++)i.has(a[d])||(u.values[f]=a[d],c.values[f]=d,f++);return[2,[u.toTensor(),c.toTensor()]]}})})};function Na(r,n,e,t){t===void 0&&(t=!0);var a=[];if(t)(a=a.concat(n.slice(0))).push(r[0]/e),a=a.concat(r.slice(1));else{a=a.concat(r[0]);for(var o=n.length,i=0;i<o;++i)a=a.concat([r[i+1]/n[i],n[i]]);a=a.concat(r.slice(o+1))}return a}function xt(r,n,e){e===void 0&&(e=!0);var t=[];if(e){t.push(n);for(var a=n+1;a<r;++a)a<=2*n?(t.push(a),t.push(a-(n+1))):t.push(a)}else{var o=[],i=[];for(a=1;a<r;++a)a>=2*n+1||a%2==1?i.push(a):o.push(a);t.push.apply(t,o),t.push(0),t.push.apply(t,i)}return t}function lo(r,n,e,t){t===void 0&&(t=!0);var a=[];t?a.push(r[0]/e):a.push(r[0]*e);for(var o=1;o<r.length;++o)o<=n.length?t?a.push(n[o-1]*r[o]):a.push(r[o]/n[o-1]):a.push(r[o]);return a}function Fs(r,n){for(var e=[0],t=0;t<n;++t)e.push(r[t][0]);return e}function Ps(r,n,e){for(var t=r.slice(0,1),a=0;a<e;++a)t.push(r[a+1]-n[a][0]-n[a][1]);return t}function Pi(r,n){if(r.rank<1)throw new Error("tf.gatherND() expects the input to be rank 1 or higher, but the rank was "+r.rank+".");if(n.rank<1)throw new Error("tf.gatherND() expects the indices to be rank 1 or higher, but the rank was "+n.rank+".");if(n.dtype!=="int32")throw new Error("tf.gatherND() expects the indices to be int32 type, but the dtype was "+n.dtype+".");if(n.shape[n.rank-1]>r.rank)throw new Error("index innermost dimension length must be <= tensor rank; saw: "+n.shape[n.rank-1]+" vs. "+r.rank);if(r.size===0)throw new Error("Requested more than 0 entries, but input is empty. Input shape: "+r.shape+".");for(var e=n.shape,t=e[e.length-1],a=1,o=0;o<e.length-1;++o)a*=e[o];var i=r.shape,s=e.slice();s.pop();var u=1;for(o=t;o<r.rank;++o)u*=i[o],s.push(i[o]);var c=Rn(r.shape).map(function(d){return d/u}).concat([1]).slice(0,t);return[s,a,u,c]}var Zu=Object.freeze({prepareAndValidate:Pi}),Li=30;function Zo(r){return r<=Li?r:gn(r,Math.floor(Math.sqrt(r)))}function Ls(r,n,e){var t=n.rank>1?n.shape[n.rank-1]:1,a=n.rank>1?n.rank-1:1,o="Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: "+e.shape+", indices.shape: "+n.shape+", shape: "+r+", sliceDim: "+t+", and batchDim: "+a+".";if(e.rank<a)throw new Error(o+" update.rank < "+a+". ");if(r.length<t+(e.rank-a))throw new Error(o+" Output shape length < "+(t+(e.rank-a)));if(e.rank!==a+r.length-t)throw new Error(o+" update.rank != "+(a+r.length-t));for(var i=0;i<a;++i)if(e.shape[i]!==n.shape[i])throw new Error(o+" updates.shape["+i+"] ("+e.shape[i]+") != indices.shape["+i+"] ("+n.shape[i]+").");for(i=0;i<e.rank-a;++i)if(e.shape[i+a]!==r[i+t])throw new Error(o+" updates.shape["+(i+a)+"] ("+e.shape[i+a]+") != shape["+(i+a)+"] ("+r[i+a]+")")}function Bs(r,n,e){if(n.rank<1)throw new Error("tf.scatterND() expects the indices to be rank 1 or higher, but the rank was "+n.rank+".");if(r.rank<1)throw new Error("tf.scatterND() expects the updates to be rank 1 or higher, but the rank was "+r.rank+".");if(n.dtype!=="int32")throw new Error("The dtype of 'indices' should be int32, but got dtype: "+n.dtype);if(e.length<1)throw new Error("Output rank must be greater or equal to 1, but got shape: "+e);if(e.length===0){if(n.size===0)throw new Error("Indices specified for empty output. indices shape: "+n.shape);if(r.size===0)throw new Error("Updates specified for empty output. updates shape: "+r.shape)}Ls(e,n,r)}function ka(r,n,e){for(var t=n.shape.length,a=t>1?n.shape[t-1]:1,o=e.length,i=1,s=a;s<o;++s)i*=e[s];var u=a<1?1:a;return{sliceRank:a,numUpdates:ae(n.shape)/u,sliceSize:i,strides:Rn(e.slice(0,a)).concat([1]),outputSize:ae(e)}}var ec=Object.freeze({validateUpdateShape:Ls,validateInput:Bs,calculateShapes:ka});function js(r,n,e){D(r.rank===n.length,function(){return"Error in slice"+r.rank+"D: Length of begin "+n+" must match the rank of the array ("+r.rank+")."}),D(r.rank===e.length,function(){return"Error in slice"+r.rank+"D: Length of size "+e+" must match the rank of the array ("+r.rank+")."});for(var t=function(o){D(n[o]+e[o]<=r.shape[o],function(){return"Error in slice"+r.rank+"D: begin["+o+"] + size["+o+"] ("+(n[o]+e[o])+") would overflow input.shape["+o+"] ("+r.shape[o]+")"})},a=0;a<r.rank;++a)t(a)}function Bi(r){for(var n=[],e=0;r>0;)1&r&&n.push(e),r/=2,e++;return n}function ho(r,n,e){for(var t=[],a=0;a<r.length;a++)t[a]=Math.ceil((n[a]-r[a])/e[a]);return t}function Us(r,n,e,t,a){var o=n[a],i=e[a]||1;(r&1<<a||o==null)&&(o=i>0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var s=t[a];return o<0&&(o+=s),o=ce(0,o,s-1)}function ji(r,n,e,t,a){var o=n[a],i=e[a]||1;(r&1<<a||o==null)&&(o=i>0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var s=t[a];return o<0&&(o+=s),o=i>0?ce(0,o,s):ce(-1,o,s-1)}function Ui(r,n,e){for(var t=e.length,a=0;a<e.length;a++)if(e[a]>1){t=a;break}for(a=t+1;a<e.length;a++)if(n[a]>0||e[a]!==r[a])return!1;return!0}function Wi(r,n){for(var e=r.length>0?r[r.length-1]:1,t=0;t<r.length-1;t++)e+=r[t]*n[t];return e}var td=Object.freeze({assertParamsValid:js,maskToAxes:Bi,computeOutShape:ho,startForAxis:Us,stopForAxis:ji,isSliceContinous:Ui,computeFlatOffset:Wi});function nd(r){return D(et(r),function(){return"The f passed in grad(f) must be a function"}),function(n,e){var t=F(n,"x","tf.grad",null),a=e!=null?F(e,"dy","tf.grad"):null;return X.tidy(function(){var o=X.gradients(function(){return r(t)},[t],a),i=o.value,s=o.grads;return a!=null&&se(i.shape,a.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),la(s),s[0]})}}function rd(r){return D(et(r),function(){return"The f passed in grads(f) must be a function"}),function(n,e){D(Array.isArray(n),function(){return"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s"});var t=aa(n,"args","tf.grads",null),a=e!=null?F(e,"dy","tf.grads"):null;return X.tidy(function(){var o=X.gradients(function(){return r.apply(void 0,t)},t,a),i=o.value,s=o.grads;return a!=null&&se(i.shape,a.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),la(s),s})}}function Ws(r){return D(et(r),function(){return"The f passed in valueAndGrad(f) must be a function"}),function(n,e){D(n instanceof fn,function(){return"The x passed in valueAndGrad(f)(x) must be a tensor"}),D(e==null||e instanceof fn,function(){return"The dy passed in valueAndGrad(f)(x, dy) must be a tensor"});var t=X.gradients(function(){return r(n)},[n],e),a=t.grads,o=t.value;return la(a),{grad:a[0],value:o}}}function zi(r){return D(et(r),function(){return"The f passed in valueAndGrads(f) must be a function"}),function(n,e){D(Array.isArray(n)&&n.every(function(a){return a instanceof fn}),function(){return"The args passed in valueAndGrads(f)(args) must be array of tensors"}),D(e==null||e instanceof fn,function(){return"The dy passed in valueAndGrads(f)(args, dy) must be a tensor"});var t=X.gradients(function(){return r.apply(void 0,n)},n,e);return e!=null&&se(t.value.shape,e.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),la(t.grads),t}}function ei(r,n){D(et(r),function(){return"The f passed in variableGrads(f) must be a function"}),D(n==null||Array.isArray(n)&&n.every(function(d){return d instanceof Fr}),function(){return"The varList passed in variableGrads(f, varList) must be an array of variables"});var e=n!=null;if(!e)for(var t in n=[],X.registeredVariables)n.push(X.registeredVariables[t]);var a=e?n.filter(function(d){return!d.trainable}):null,o=n.length;D((n=n.filter(function(d){return d.trainable})).length>0,function(){return"variableGrads() expects at least one of the input variables to be trainable, but none of the "+o+" variables is trainable."});var i=X.gradients(r,n,null,!0),s=i.value,u=i.grads;D(u.some(function(d){return d!=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()."}),D(s.rank===0,function(){return"The f passed in variableGrads(f) must return a scalar, but it returned a rank-"+s.rank+" tensor"});var c={};return n.forEach(function(d,f){u[f]!=null&&(c[d.name]=u[f])}),a!=null&&a.forEach(function(d){return c[d.name]=null}),{value:s,grads:c}}function ca(r){return X.customGrad(r)}function la(r){if(r.filter(function(n){return n==null}).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.`)}var Sa=K({softmax_:function(r,n){n===void 0&&(n=-1);var e=F(r,"logits","softmax","float32");if(n===-1&&(n=e.rank-1),n!==e.rank-1)throw Error("Softmax along a non-last dimension is not yet supported. Logits was rank "+e.rank+" and dim was "+n);return X.runKernelFunc(function(t,a){var o=t.softmax(e,n);return a([o]),o},{logits:e},function(t,a){var o=a[0],i=t.mul(o);return{logits:function(){return i.sub(i.sum([n],!0).mul(o))}}},"Softmax",{dim:n},[],[!0])}}),ti=K({logSoftmax_:function(r,n){n===void 0&&(n=-1);var e=F(r,"logits","logSoftmax");if(n===-1&&(n=e.rank-1),n!==e.rank-1)throw Error("Log Softmax along a non-last dimension is not yet supported. Logits was rank "+e.rank+" and axis was "+n);return ca(function(t,a){var o=t.max(n,!0),i=t.sub(o),s=i.toFloat().sub(i.exp().sum(n,!0).log());return a([s]),{value:s,gradFunc:function(u,c){var d=c[0].exp();return u.sub(u.sum(n,!0).mul(d))}}})(e)}}),po=function(){function r(n,e){this.backend=n,this.dataMover=e,this.data=new WeakMap,this.dataIdsCount=0}return r.prototype.get=function(n){return this.data.has(n)||this.dataMover.moveData(this.backend,n),this.data.get(n)},r.prototype.set=function(n,e){this.dataIdsCount++,this.data.set(n,e)},r.prototype.has=function(n){return this.data.has(n)},r.prototype.delete=function(n){return this.dataIdsCount--,this.data.delete(n)},r.prototype.numDataIds=function(){return this.dataIdsCount},r}(),fo=function(){function r(){}return r.prototype.time=function(n){return re("time")},r.prototype.read=function(n){return re("read")},r.prototype.readSync=function(n){return re("readSync")},r.prototype.numDataIds=function(){return re("numDataIds")},r.prototype.disposeData=function(n){return re("disposeData")},r.prototype.write=function(n,e,t){return re("write")},r.prototype.move=function(n,e,t,a){return re("move")},r.prototype.memory=function(){return re("memory")},r.prototype.floatPrecision=function(){return re("floatPrecision")},r.prototype.epsilon=function(){return this.floatPrecision()===32?1e-7:1e-4},r.prototype.batchMatMul=function(n,e,t,a){return re("batchMatMul")},r.prototype.fusedBatchMatMul=function(n){return n.a,n.b,n.transposeA,n.transposeB,n.bias,n.activation,n.preluActivationWeights,re("fusedBatchMatMul")},r.prototype.slice=function(n,e,t){return re("slice")},r.prototype.stridedSlice=function(n,e,t,a){return re("stridedSlice")},r.prototype.unstack=function(n,e){return re("unstack")},r.prototype.reverse=function(n,e){return re("reverse")},r.prototype.concat=function(n,e){return re("concat")},r.prototype.neg=function(n){return re("neg")},r.prototype.add=function(n,e){return re("add")},r.prototype.addN=function(n){return re("addN")},r.prototype.subtract=function(n,e){return re("subtract")},r.prototype.multiply=function(n,e){return re("multiply")},r.prototype.realDivide=function(n,e){return re("realDivide")},r.prototype.floorDiv=function(n,e){return re("floorDiv")},r.prototype.sum=function(n,e){return re("sum")},r.prototype.prod=function(n,e){return re("prod")},r.prototype.unsortedSegmentSum=function(n,e,t){return re("unsortedSegmentSum")},r.prototype.argMin=function(n,e){return re("argMin")},r.prototype.argMax=function(n,e){return re("argMax")},r.prototype.equal=function(n,e){return re("equal")},r.prototype.notEqual=function(n,e){return re("notEqual")},r.prototype.less=function(n,e){return re("less")},r.prototype.lessEqual=function(n,e){return re("lessEqual")},r.prototype.greater=function(n,e){return re("greater")},r.prototype.greaterEqual=function(n,e){return re("greaterEqual")},r.prototype.logicalNot=function(n){return re("logicalNot")},r.prototype.logicalAnd=function(n,e){return re("logicalAnd")},r.prototype.logicalOr=function(n,e){return re("logicalOr")},r.prototype.where=function(n){return re("where")},r.prototype.select=function(n,e,t){return re("select")},r.prototype.topk=function(n,e,t){return re("topk")},r.prototype.min=function(n,e){return re("min")},r.prototype.minimum=function(n,e){return re("minimum")},r.prototype.mod=function(n,e){return re("mod")},r.prototype.max=function(n,e){return re("max")},r.prototype.maximum=function(n,e){return re("maximum")},r.prototype.all=function(n,e){return re("all")},r.prototype.any=function(n,e){return re("any")},r.prototype.squaredDifference=function(n,e){return re("squaredDifference")},r.prototype.ceil=function(n){return re("ceil")},r.prototype.floor=function(n){return re("floor")},r.prototype.round=function(n){return re("round")},r.prototype.sign=function(n){return re("sign")},r.prototype.isNaN=function(n){return re("isNaN")},r.prototype.isInf=function(n){return re("isInf")},r.prototype.isFinite=function(n){return re("isFinite")},r.prototype.pow=function(n,e){return re("pow")},r.prototype.exp=function(n){return re("exp")},r.prototype.expm1=function(n){return re("expm1")},r.prototype.softmax=function(n,e){return re("softmax")},r.prototype.log=function(n){return re("log")},r.prototype.log1p=function(n){return re("log1p")},r.prototype.sqrt=function(n){return re("sqrt")},r.prototype.rsqrt=function(n){return re("rsqrt")},r.prototype.square=function(n){return re("square")},r.prototype.reciprocal=function(n){return re("reciprocal")},r.prototype.relu=function(n){return re("relu")},r.prototype.relu6=function(n){return re("relu6")},r.prototype.prelu=function(n,e){return re("prelu")},r.prototype.elu=function(n){return re("elu")},r.prototype.eluDer=function(n,e){return re("eluDer")},r.prototype.selu=function(n){return re("selu")},r.prototype.int=function(n){return re("int")},r.prototype.clip=function(n,e,t){return re("clip")},r.prototype.abs=function(n){return re("abs")},r.prototype.complexAbs=function(n){return re("complexAbs")},r.prototype.sigmoid=function(n){return re("sigmoid")},r.prototype.softplus=function(n){return re("softplus")},r.prototype.sin=function(n){return re("sin")},r.prototype.cos=function(n){return re("cos")},r.prototype.tan=function(n){return re("tan")},r.prototype.asin=function(n){return re("asin")},r.prototype.acos=function(n){return re("acos")},r.prototype.atan=function(n){return re("atan")},r.prototype.atan2=function(n,e){return re("atan2")},r.prototype.sinh=function(n){return re("sinh")},r.prototype.cosh=function(n){return re("cosh")},r.prototype.tanh=function(n){return re("tanh")},r.prototype.asinh=function(n){return re("asinh")},r.prototype.acosh=function(n){return re("acosh")},r.prototype.atanh=function(n){return re("atanh")},r.prototype.erf=function(n){return re("erf")},r.prototype.step=function(n,e){return re("step")},r.prototype.fusedConv2d=function(n){return n.input,n.filter,n.convInfo,n.bias,n.activation,n.preluActivationWeights,re("fusedConv2d")},r.prototype.conv2d=function(n,e,t){return re("conv2d")},r.prototype.conv2dDerInput=function(n,e,t){return re("conv2dDerInput")},r.prototype.conv2dDerFilter=function(n,e,t){return re("conv2dDerFilter")},r.prototype.fusedDepthwiseConv2D=function(n){return n.input,n.filter,n.convInfo,n.bias,n.activation,n.preluActivationWeights,re("fusedDepthwiseConv2D")},r.prototype.depthwiseConv2D=function(n,e,t){return re("depthwiseConv2D")},r.prototype.depthwiseConv2DDerInput=function(n,e,t){return re("depthwiseConv2DDerInput")},r.prototype.depthwiseConv2DDerFilter=function(n,e,t){return re("depthwiseConv2DDerFilter")},r.prototype.conv3d=function(n,e,t){return re("conv3d")},r.prototype.conv3dDerInput=function(n,e,t){return re("conv3dDerInput")},r.prototype.conv3dDerFilter=function(n,e,t){return re("conv3dDerFilter")},r.prototype.maxPool=function(n,e){return re("maxPool")},r.prototype.maxPoolBackprop=function(n,e,t,a){return re("maxPoolBackprop")},r.prototype.avgPool=function(n,e){return re("avgPool")},r.prototype.avgPoolBackprop=function(n,e,t){return re("avgPoolBackprop")},r.prototype.avgPool3d=function(n,e){return re("avgPool3d")},r.prototype.avgPool3dBackprop=function(n,e,t){return re("avgPool3dBackprop")},r.prototype.maxPool3d=function(n,e){return re("maxPool3d")},r.prototype.maxPool3dBackprop=function(n,e,t,a){return re("maxPool3dBackprop")},r.prototype.reshape=function(n,e){return re("reshape")},r.prototype.cast=function(n,e){return re("cast")},r.prototype.tile=function(n,e){return re("tile")},r.prototype.pad=function(n,e,t){return re("pad")},r.prototype.transpose=function(n,e){return re("transpose")},r.prototype.gather=function(n,e,t){return re("gather")},r.prototype.gatherND=function(n,e){return re("gatherND")},r.prototype.scatterND=function(n,e,t){return re("scatterND")},r.prototype.batchToSpaceND=function(n,e,t){return re("batchToSpaceND")},r.prototype.spaceToBatchND=function(n,e,t){return re("spaceToBatchND")},r.prototype.resizeBilinear=function(n,e,t,a){return re("resizeBilinear")},r.prototype.resizeBilinearBackprop=function(n,e,t){return re("resizeBilinearBackprop")},r.prototype.resizeNearestNeighbor=function(n,e,t,a){return re("resizeNearestNeighbor")},r.prototype.resizeNearestNeighborBackprop=function(n,e,t){return re("resizeNearestNeighborBackprop")},r.prototype.batchNormalization=function(n,e,t,a,o,i){return re("batchNormalization")},r.prototype.localResponseNormalization4D=function(n,e,t,a,o){return re("localResponseNormalization4D")},r.prototype.LRNGrad=function(n,e,t,a,o,i,s){return re("LRNGrad")},r.prototype.multinomial=function(n,e,t,a){return re("multinomial")},r.prototype.oneHot=function(n,e,t,a){return re("oneHot")},r.prototype.cumsum=function(n,e,t,a){return re("cumsum")},r.prototype.nonMaxSuppression=function(n,e,t,a,o){return re("nonMaxSuppression")},r.prototype.fft=function(n){return re("fft")},r.prototype.ifft=function(n){return re("ifft")},r.prototype.complex=function(n,e){return re("complex")},r.prototype.real=function(n){return re("real")},r.prototype.imag=function(n){return re("imag")},r.prototype.cropAndResize=function(n,e,t,a,o,i){return re("cropAndResize")},r.prototype.depthToSpace=function(n,e,t){return re("depthToSpace")},r.prototype.split=function(n,e,t){return re("split")},r.prototype.sparseToDense=function(n,e,t,a){return re("sparseToDense")},r.prototype.diag=function(n){return re("diag")},r.prototype.fill=function(n,e,t){return re("fill")},r.prototype.onesLike=function(n){return re("onesLike")},r.prototype.zerosLike=function(n){return re("zerosLike")},r.prototype.linspace=function(n,e,t){return re("linspace")},r.prototype.dispose=function(){return re("dispose")},r}();function re(r){throw new Error("'"+r+"' not yet implemented or not found in the registry. Did you forget to import the kernel?")}function dr(r,n){for(var e=r.length,t=[],a=0;a<e;a++){var o=e-1-a,i=r[o]||1;(n[n.length-1-a]||1)>1&&i===1&&t.unshift(o)}return t}function tn(r,n){for(var e=[],t=0;t<n.length;t++){var a=r[r.length-t-1],o=n.length-t-1,i=n[o];(a==null||a===1&&i>1)&&e.unshift(o)}return e}function nt(r,n){for(var e=[],t=Math.max(r.length,n.length),a=0;a<t;a++){var o=r[r.length-a-1];o==null&&(o=1);var i=n[n.length-a-1];if(i==null&&(i=1),o===1)e.unshift(i);else if(i===1)e.unshift(o);else{if(o!==i)throw Error("Operands could not be broadcast together with shapes "+r+" and "+n+".");e.unshift(o)}}return e}function Vr(r,n,e,t,a,o,i){i===void 0&&(i="channelsLast");var s,u=mo(n),c=u[0],d=u[1];if(i==="channelsLast")s=[c,d,r[3],r[3]];else{if(i!=="channelsFirst")throw new Error("Unknown dataFormat "+i);s=[c,d,r[1],r[1]]}return Tr(r,s,e,t,a,o,!1,i)}function Oa(r,n,e,t,a,o,i){i===void 0&&(i="NDHWC");var s,u,c=Ia(n),d=c[0],f=c[1],m=c[2];if(i==="NDHWC")u="channelsLast",s=[d,f,m,r[4],r[4]];else{if(i!=="NCDHW")throw new Error("Unknown dataFormat "+i);u="channelsFirst",s=[d,f,m,r[1],r[1]]}return da(r,s,e,t,a,!1,u,o)}function Tr(r,n,e,t,a,o,i,s){i===void 0&&(i=!1),s===void 0&&(s="channelsLast");var u=[-1,-1,-1,-1],c=u[0],d=u[1],f=u[2],m=u[3];if(s==="channelsLast")c=r[0],d=r[1],f=r[2],m=r[3];else{if(s!=="channelsFirst")throw new Error("Unknown dataFormat "+s);c=r[0],m=r[1],d=r[2],f=r[3]}var g,x=n[0],E=n[1],w=n[3],C=mo(e),N=C[0],S=C[1],I=mo(t),M=I[0],j=I[1],G=Dr(x,M),z=Dr(E,j),W=function(fe,he,Ee,be,pe,Ce,Re,Le){var Xe,qe,ht;if(typeof fe=="number"){Xe={top:fe,bottom:fe,left:fe,right:fe,type:fe===0?"VALID":"NUMBER"};var pt=function(_t,Ht,It,hn,cn){hn==null&&(hn=vo(_t,Ht,It));var ln=_t[0],Or=_t[1],Ir=Ma((ln-Ht+2*hn)/It+1,cn);D(Be(Ir),function(){return"The output # of rows ("+Ir+") must be an integer. Change the stride and/or zero pad parameters"});var er=Ma((Or-Ht+2*hn)/It+1,cn);return D(Be(er),function(){return"The output # of columns ("+er+") must be an integer. Change the stride and/or zero pad parameters"}),[Ir,er]}([he,Ee],Ce,be,fe,Le);qe=pt[0],ht=pt[1]}else if(fe==="same"){qe=Math.ceil(he/be),ht=Math.ceil(Ee/pe);var vt=Math.max(0,(qe-1)*be+Ce-he),Dt=Math.max(0,(ht-1)*pe+Re-Ee),Et=Math.floor(vt/2),Nt=vt-Et,mn=Math.floor(Dt/2);Xe={top:Et,bottom:Nt,left:mn,right:Dt-mn,type:"SAME"}}else{if(fe!=="valid")throw Error("Unknown padding parameter: "+fe);Xe={top:0,bottom:0,left:0,right:0,type:"VALID"},qe=Math.ceil((he-Ce+1)/be),ht=Math.ceil((Ee-Re+1)/pe)}return{padInfo:Xe,outHeight:qe,outWidth:ht}}(a,d,f,N,S,G,z,o),V=W.padInfo,Z=W.outHeight,J=W.outWidth,me=i?w*m:w;return s==="channelsFirst"?g=[c,me,Z,J]:s==="channelsLast"&&(g=[c,Z,J,me]),{batchSize:c,dataFormat:s,inHeight:d,inWidth:f,inChannels:m,outHeight:Z,outWidth:J,outChannels:me,padInfo:V,strideHeight:N,strideWidth:S,filterHeight:x,filterWidth:E,effectiveFilterHeight:G,effectiveFilterWidth:z,dilationHeight:M,dilationWidth:j,inShape:r,outShape:g,filterShape:n}}function da(r,n,e,t,a,o,i,s){o===void 0&&(o=!1),i===void 0&&(i="channelsLast");var u=[-1,-1,-1,-1,-1],c=u[0],d=u[1],f=u[2],m=u[3],g=u[4];if(i==="channelsLast")c=r[0],d=r[1],f=r[2],m=r[3],g=r[4];else{if(i!=="channelsFirst")throw new Error("Unknown dataFormat "+i);c=r[0],g=r[1],d=r[2],f=r[3],m=r[4]}var x,E=n[0],w=n[1],C=n[2],N=n[4],S=Ia(e),I=S[0],M=S[1],j=S[2],G=Ia(t),z=G[0],W=G[1],V=G[2],Z=Dr(E,z),J=Dr(w,W),me=Dr(C,V),fe=function(Re,Le,Xe,qe,ht,pt,vt,Dt,Et,Nt,mn){var _t,Ht,It,hn;if(typeof Re=="number"){_t={top:Re,bottom:Re,left:Re,right:Re,front:Re,back:Re,type:Re===0?"VALID":"NUMBER"};var cn=function(To,$r,Fu,Do,Mr,Pu){Mr==null&&(Mr=vo(To,$r,Do));var Hf=To[0],Xf=To[1],Kf=To[2],Lu=Ma((Hf-$r+2*Mr)/Do+1,Pu);D(Be(Lu),function(){return"The output # of depths ("+Lu+") must be an integer. Change the stride and/or zero pad parameters"});var Bu=Ma((Xf-$r+2*Mr)/Do+1,Pu);D(Be(Bu),function(){return"The output # of rows ("+Bu+") must be an integer. Change the stride and/or zero pad parameters"});var ju=Ma((Kf-$r+2*Mr)/Do+1,Pu);return D(Be(ju),function(){return"The output # of columns ("+ju+") must be an integer. Change the stride and/or zero pad parameters"}),[Lu,Bu,ju,Fu]}([Le,Xe,qe,1],Dt,1,ht,Re,mn);Ht=cn[0],It=cn[1],hn=cn[2]}else if(Re==="same"){Ht=Math.ceil(Le/ht),It=Math.ceil(Xe/pt),hn=Math.ceil(qe/vt);var ln=(Ht-1)*ht+Dt-Le,Or=(It-1)*pt+Et-Xe,Ir=(hn-1)*vt+Nt-qe,er=Math.floor(ln/2),Ao=ln-er,qr=Math.floor(Or/2),xa=Or-qr,Yr=Math.floor(Ir/2);_t={top:qr,bottom:xa,left:Yr,right:Ir-Yr,front:er,back:Ao,type:"SAME"}}else{if(Re!=="valid")throw Error("Unknown padding parameter: "+Re);_t={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},Ht=Math.ceil((Le-Dt+1)/ht),It=Math.ceil((Xe-Et+1)/pt),hn=Math.ceil((qe-Nt+1)/vt)}return{padInfo:_t,outDepth:Ht,outHeight:It,outWidth:hn}}(a,d,f,m,I,M,j,Z,J,me,s),he=fe.padInfo,Ee=fe.outDepth,be=fe.outHeight,pe=fe.outWidth,Ce=o?N*g:N;return i==="channelsFirst"?x=[c,Ce,Ee,be,pe]:i==="channelsLast"&&(x=[c,Ee,be,pe,Ce]),{batchSize:c,dataFormat:i,inDepth:d,inHeight:f,inWidth:m,inChannels:g,outDepth:Ee,outHeight:be,outWidth:pe,outChannels:Ce,padInfo:he,strideDepth:I,strideHeight:M,strideWidth:j,filterDepth:E,filterHeight:w,filterWidth:C,effectiveFilterDepth:Z,effectiveFilterHeight:J,effectiveFilterWidth:me,dilationDepth:z,dilationHeight:W,dilationWidth:V,inShape:r,outShape:x,filterShape:n}}function vo(r,n,e,t){t===void 0&&(t=1);var a=Dr(n,t);return Math.floor((r[0]*(e-1)-e+a)/2)}function mo(r){return typeof r=="number"?[r,r,r]:r.length===2?[r[0],r[1],1]:r}function Ia(r){return typeof r=="number"?[r,r,r]:r}function Dr(r,n){return n<=1?r:r+(r-1)*(n-1)}function Ma(r,n){if(!n)return r;switch(n){case"round":return Math.round(r);case"ceil":return Math.ceil(r);case"floor":return Math.floor(r);default:throw new Error("Unknown roundingMode "+n)}}function ha(r){var n=mo(r),e=n[0],t=n[1],a=n[2];return e===1&&t===1&&a===1}function Bn(r,n){return ha(r)||ha(n)}function ni(r){if(r==="NHWC")return"channelsLast";if(r==="NCHW")return"channelsFirst";throw new Error("Unknown dataFormat "+r)}function ri(r,n,e){if(n==="complex64"){if(r.dtype==="complex64")return r.clone();var t=Jt(r.shape),a=r.toFloat(),o=e.complex(a,t);return t.dispose(),a.dispose(),o}if(!tr(r.dtype,n))return X.makeTensorFromDataId(r.dataId,r.shape,n);if(r.dtype==="complex64"){var i=e.real(r);return o=i.cast(n),i.dispose(),o}if(n==="int32")return e.int(r);if(n==="bool"){var s=We(0,r.dtype);return o=e.notEqual(r,s),s.dispose(),o}throw new Error("Error in Cast: failed to cast "+r.dtype+" to "+n)}function go(r,n){return X.makeTensorFromDataId(r.dataId,n,r.dtype)}function Vi(r,n,e){var t=(n-r)/(e-1),a=U(e,"float32");a[0]=r;for(var o=1;o<a.length;o++)a[o]=a[o-1]+t;return Ur(a,"float32")}var ad=Object.freeze({castTensor:ri,reshapeTensor:go,linspaceImpl:Vi,upcastType:yn,axesAreInnerMostDims:Ti,combineLocations:Xo,computeOutAndReduceShapes:Nn,expandShapeToKeepDim:kn,assertAxesAreInnerMostDims:Wn,getAxesPermutation:Gn,getUndoAxesPermutation:oa,getInnerMostAxes:Jn,getBroadcastDims:dr,getReductionAxes:tn,assertAndGetBroadcastShape:nt,assertParamsConsistent:Di,computeOutShape:jr,computePool2DInfo:Vr,computePool3DInfo:Oa,computeConv2DInfo:Tr,computeConv3DInfo:da,computeDefaultPad:vo,tupleValuesAreOne:ha,eitherStridesOrDilationsAreOne:Bn,convertConv2DDataFormat:ni,PARALLELIZE_THRESHOLD:Li,computeOptimalWindowSize:Zo});function yo(r,n){if(r.length!==n.length)throw new Error("Cannot merge real and imag arrays of different lengths. real:"+r.length+", imag: "+n.length+".");for(var e=new Float32Array(2*r.length),t=0;t<e.length;t+=2)e[t]=r[t/2],e[t+1]=n[t/2];return e}function Gi(r,n){return{real:r[2*n],imag:r[2*n+1]}}function zs(r,n,e,t){r[2*t]=n,r[2*t+1]=e}function Vs(r,n,e){var t=(e?2:-2)*Math.PI*(r/n);return{real:Math.cos(t),imag:Math.sin(t)}}function Gs(r,n,e){var t=function(o,i,s){return function(u,c,d){for(var f=0,m=u.length,g=0,x=!1;f<m;){var E=d(c,u[g=f+(m-f>>>1)]);E>0?f=g+1:(m=g,x=!E)}return x?f:-f-1}(o,i,s||Hs)}(r,n,e),a=t<0?-(t+1):t;r.splice(a,0,n)}function Hs(r,n){return r>n?1:r<n?-1:0}function ai(r,n,e,t,a){return Hi(r,n,e,t,a,0).selectedIndices}function oi(r,n,e,t,a,o){var i=Hi(r,n,e,t,a,o,!0);return i.numValidOutputs.dispose(),{selectedIndices:i.selectedIndices,selectedScores:i.selectedScores}}function Hi(r,n,e,t,a,o,i,s){i===void 0&&(i=!1),s===void 0&&(s=!1);for(var u=Array.from(n).map(function(I,M){return{score:I,boxIndex:M,suppressBeginIndex:0}}).filter(function(I){return I.score>a}).sort(Xi),c=o>0?-.5/o:0,d=[],f=[];d.length<e&&u.length>0;){var m=u.pop(),g=m.score,x=m.boxIndex,E=m.suppressBeginIndex;if(g<a)break;for(var w=!1,C=d.length-1;C>=E;--C){var N=Xs(r,x,d[C]);if(N>=t){w=!0;break}if(m.score=m.score*Ks(t,c,N),m.score<=a)break}m.suppressBeginIndex=d.length,w||(m.score===g?(d.push(x),f.push(m.score)):m.score>a&&Gs(u,m,Xi))}var S=d.length;return s&&(d.fill(0,S),f.fill(0,S)),{selectedIndices:Ur(d,"int32"),selectedScores:Ur(f,"float32"),numValidOutputs:We(S,"int32")}}function Xs(r,n,e){var t=r.subarray(4*n,4*n+4),a=r.subarray(4*e,4*e+4),o=Math.min(t[0],t[2]),i=Math.min(t[1],t[3]),s=Math.max(t[0],t[2]),u=Math.max(t[1],t[3]),c=Math.min(a[0],a[2]),d=Math.min(a[1],a[3]),f=Math.max(a[0],a[2]),m=Math.max(a[1],a[3]),g=(s-o)*(u-i),x=(f-c)*(m-d);if(g<=0||x<=0)return 0;var E=Math.max(o,c),w=Math.max(i,d),C=Math.min(s,f),N=Math.min(u,m),S=Math.max(C-E,0)*Math.max(N-w,0);return S/(g+x-S)}function Ks(r,n,e){var t=Math.exp(n*e*e);return e<=r?t:0}function Xi(r,n){return r.score-n.score||r.score===n.score&&n.boxIndex-r.boxIndex}function Ki(r,n,e){var t=new Array(r.rank).fill(0),a=r.shape.slice();return n.map(function(o){a[e]=o;var i=r.slice(t,a);return t[e]+=o,i})}function qi(r,n){for(var e=new Array(r.rank),t=0;t<e.length;t++)e[t]=r.shape[t]*n[t];var a=Je(e,r.dtype);for(t=0;t<a.values.length;++t){for(var o=a.indexToLoc(t),i=new Array(r.rank),s=0;s<i.length;s++)i[s]=o[s]%r.shape[s];var u=r.locToIndex(i);a.values[t]=r.values[u]}return a.toTensor()}function qs(r,n,e,t,a){for(var o=n[n.length-1],i=[r.length/o,o],s=i[0],u=i[1],c=Cn(e,s*t),d=Cn("int32",s*t),f=0;f<s;f++){for(var m=f*u,g=r.subarray(m,m+u),x=[],E=0;E<g.length;E++)x.push({value:g[E],index:E});x.sort(function(I,M){return M.value-I.value});var w=f*t,C=c.subarray(w,w+t),N=d.subarray(w,w+t);for(E=0;E<t;E++)C[E]=x[E].value,N[E]=x[E].index}var S=n.slice();return S[S.length-1]=t,[_n(c,S,e),_n(d,S,"int32")]}function Yi(r,n){for(var e=[],t=0;t<n.length;t++)n[t]&&e.push(t);var a=Je(r,"int32"),o=Je([e.length,r.length],"int32");for(t=0;t<e.length;t++){var i=a.indexToLoc(e[t]),s=t*r.length;o.values.set(i,s)}return o.toTensor()}var tc=function(r,n){this.outputShape=[],this.outputShape=r,this.variableNames=n.map(function(a,o){return"T"+o});var e=[];this.variableNames.forEach(function(a){e.push("float v"+a+" = get"+a+"AtOutCoords();")});var t=this.variableNames.map(function(a){return"v"+a}).join(" + ");this.userCode=`
|
|
void main() {
|
|
`+e.join(`
|
|
`)+`
|
|
|
|
float result = `+t+`;
|
|
setOutput(result);
|
|
}
|
|
`},Ys=function(r,n){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=r,this.variableNames=n.map(function(a,o){return"T"+o});var e=[];this.variableNames.forEach(function(a){e.push("vec4 v"+a+" = get"+a+"AtOutCoords();")});var t=this.variableNames.map(function(a){return"v"+a}).join(" + ");this.userCode=`
|
|
void main() {
|
|
`+e.join(`
|
|
`)+`
|
|
|
|
vec4 result = `+t+`;
|
|
setOutput(result);
|
|
}
|
|
`},nc=function(r,n,e){this.variableNames=["A"];var t=r.windowSize,a=r.batchSize,o=r.inSize,i=Math.ceil(o/t);e||this.variableNames.push("bestIndicesA"),this.outputShape=[a,i];var s=n==="max"?">":"<",u=e?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = outIdx * `+t+`;
|
|
|
|
int bestIndex = inOffset;
|
|
float bestValue = getA(batch, bestIndex);
|
|
|
|
for (int i = 0; i < `+t+`; i++) {
|
|
int inIdx = `+u+`;
|
|
float candidate = getA(batch, inIdx);
|
|
if (candidate `+s+` bestValue) {
|
|
bestValue = candidate;
|
|
bestIndex = inIdx;
|
|
}
|
|
}
|
|
setOutput(float(bestIndex));
|
|
}
|
|
`};function p(r,n){return["x","y","z","w","u","v"].slice(0,n).map(function(e){return r+"."+e})}function l(r,n){return n===1?[r]:p(r,n)}function h(){var r,n,e,t,a,o,i,s,u,c;return ee().getNumber("WEBGL_VERSION")===2?(r="#version 300 es",n="in",e="out",t="in",a="texture",o="outputColor",i="out vec4 outputColor;",s=`
|
|
bool isnan_custom(float val) {
|
|
return (val > 0.0 || val < 0.0) ? false : val != 0.0;
|
|
}
|
|
|
|
bvec4 isnan_custom(vec4 val) {
|
|
return bvec4(isnan_custom(val.x),
|
|
isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));
|
|
}
|
|
|
|
#define isnan(value) isnan_custom(value)
|
|
`,u="",c=`
|
|
#define round(value) newRound(value)
|
|
int newRound(float value) {
|
|
return int(floor(value + 0.5));
|
|
}
|
|
|
|
ivec4 newRound(vec4 value) {
|
|
return ivec4(floor(value + vec4(0.5)));
|
|
}
|
|
`):(r="",n="attribute",e="varying",t="varying",a="texture2D",o="gl_FragColor",i="",s=`
|
|
#define isnan(value) isnan_custom(value)
|
|
bool isnan_custom(float val) {
|
|
return (val > 0. || val < 1. || val == 0.) ? false : true;
|
|
}
|
|
bvec4 isnan_custom(vec4 val) {
|
|
return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));
|
|
}
|
|
`,u=`
|
|
uniform float INFINITY;
|
|
|
|
bool isinf(float val) {
|
|
return abs(val) == INFINITY;
|
|
}
|
|
bvec4 isinf(vec4 val) {
|
|
return equal(abs(val), vec4(INFINITY));
|
|
}
|
|
`,c=`
|
|
int round(float value) {
|
|
return int(floor(value + 0.5));
|
|
}
|
|
|
|
ivec4 round(vec4 value) {
|
|
return ivec4(floor(value + vec4(0.5)));
|
|
}
|
|
`),{version:r,attribute:n,varyingVs:e,varyingFs:t,texture2D:a,output:o,defineOutput:i,defineSpecialNaN:s,defineSpecialInf:u,defineRound:c}}function v(r,n,e){e===void 0&&(e="index");var t=Rn(n);return t.map(function(a,o){return"int "+r[o]+" = "+e+" / "+a+"; "+(o===t.length-1?"int "+r[o+1]+" = "+e+" - "+r[o]+" * "+a:"index -= "+r[o]+" * "+a)+";"}).join("")}function y(r){var n=Rn(r).map(function(e){return e.toString()});return`
|
|
int getFlatIndex(ivec3 coords) {
|
|
return coords.x * `+n[0]+" + coords.y * "+n[1]+` + coords.z;
|
|
}
|
|
`}var b=`
|
|
const float FLOAT_MAX = 1.70141184e38;
|
|
const float FLOAT_MIN = 1.17549435e-38;
|
|
|
|
lowp vec4 encode_float(highp float v) {
|
|
if (isnan(v)) {
|
|
return vec4(255, 255, 255, 255);
|
|
}
|
|
|
|
highp float av = abs(v);
|
|
|
|
if(av < FLOAT_MIN) {
|
|
return vec4(0.0, 0.0, 0.0, 0.0);
|
|
} else if(v > FLOAT_MAX) {
|
|
return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;
|
|
} else if(v < -FLOAT_MAX) {
|
|
return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;
|
|
}
|
|
|
|
highp vec4 c = vec4(0,0,0,0);
|
|
|
|
highp float e = floor(log2(av));
|
|
highp float m = exp2(fract(log2(av))) - 1.0;
|
|
|
|
c[2] = floor(128.0 * m);
|
|
m -= c[2] / 128.0;
|
|
c[1] = floor(32768.0 * m);
|
|
m -= c[1] / 32768.0;
|
|
c[0] = floor(8388608.0 * m);
|
|
|
|
highp float ebias = e + 127.0;
|
|
c[3] = floor(ebias / 2.0);
|
|
ebias -= c[3] * 2.0;
|
|
c[2] += floor(ebias) * 128.0;
|
|
|
|
c[3] += 128.0 * step(0.0, -v);
|
|
|
|
return c / 255.0;
|
|
}
|
|
`;function T(r,n,e,t){var a=[];r.forEach(function(g){var x=ae(g.shapeInfo.logicalShape);g.shapeInfo.isUniform?a.push("uniform float "+g.name+(x>1?"["+x+"]":"")+";"):(a.push("uniform sampler2D "+g.name+";"),a.push("uniform int offset"+g.name+";"))});var o,i,s=a.join(`
|
|
`),u=r.map(function(g){return function(x,E,w){w===void 0&&(w=!1);var C="";C+=w?O(x):A(x);var N=x.shapeInfo.logicalShape,S=E.logicalShape;return N.length<=S.length&&(C+=w?function(I,M){var j,G=I.name,z=G.charAt(0).toUpperCase()+G.slice(1),W="get"+z+"AtOutCoords",V=I.shapeInfo.logicalShape.length,Z=M.logicalShape.length,J=dr(I.shapeInfo.logicalShape,M.logicalShape),me=le(Z),fe=Z-V,he=["x","y","z","w","u","v"];j=V===0?"":Z<2&&J.length>=1?"coords = 0;":J.map(function(Xe){return"coords."+he[Xe+fe]+" = 0;"}).join(`
|
|
`);var Ee="";Ee=Z<2&&V>0?"coords":I.shapeInfo.logicalShape.map(function(Xe,qe){return"coords."+he[qe+fe]}).join(", ");var be="return outputValue;",pe=ae(I.shapeInfo.logicalShape)===1,Ce=ae(M.logicalShape)===1;if(V!==1||pe||Ce){if(pe&&!Ce)be=Z===1?`
|
|
return vec4(outputValue.x, outputValue.x, 0., 0.);
|
|
`:`
|
|
return vec4(outputValue.x);
|
|
`;else if(J.length){var Re=V-2,Le=V-1;J.indexOf(Re)>-1&&J.indexOf(Le)>-1?be="return vec4(outputValue.x);":J.indexOf(Re)>-1?be="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":J.indexOf(Le)>-1&&(be="return vec4(outputValue.xx, outputValue.zz);")}}else be=`
|
|
return vec4(outputValue.xy, outputValue.xy);
|
|
`;return`
|
|
vec4 `+W+`() {
|
|
`+me+` coords = getOutputCoords();
|
|
`+j+`
|
|
vec4 outputValue = get`+z+"("+Ee+`);
|
|
`+be+`
|
|
}
|
|
`}(x,E):function(I,M){var j=I.name,G=j.charAt(0).toUpperCase()+j.slice(1),z="get"+G+"AtOutCoords",W=M.texShape,V=I.shapeInfo.texShape,Z=I.shapeInfo.logicalShape.length,J=M.logicalShape.length;if(!I.shapeInfo.isUniform&&Z===J&&I.shapeInfo.flatOffset==null&&Oe(V,W))return`
|
|
float `+z+`() {
|
|
return sampleTexture(`+j+`, resultUV);
|
|
}
|
|
`;var me,fe=le(J),he=dr(I.shapeInfo.logicalShape,M.logicalShape),Ee=J-Z,be=["x","y","z","w","u","v"];me=Z===0?"":J<2&&he.length>=1?"coords = 0;":he.map(function(Ce){return"coords."+be[Ce+Ee]+" = 0;"}).join(`
|
|
`);var pe="";return pe=J<2&&Z>0?"coords":I.shapeInfo.logicalShape.map(function(Ce,Re){return"coords."+be[Re+Ee]}).join(", "),`
|
|
float `+z+`() {
|
|
`+fe+` coords = getOutputCoords();
|
|
`+me+`
|
|
return get`+G+"("+pe+`);
|
|
}
|
|
`}(x,E)),C}(g,n,t)}).join(`
|
|
`),c=n.texShape,d=h(),f=function(g){return`
|
|
float sampleTexture(sampler2D textureSampler, vec2 uv) {
|
|
return `+g.texture2D+`(textureSampler, uv).r;
|
|
}
|
|
`}(d),m=function(g){return g.version+`
|
|
precision highp float;
|
|
precision highp int;
|
|
precision highp sampler2D;
|
|
`+g.varyingFs+` vec2 resultUV;
|
|
`+g.defineOutput+`
|
|
const vec2 halfCR = vec2(0.5, 0.5);
|
|
|
|
struct ivec5
|
|
{
|
|
int x;
|
|
int y;
|
|
int z;
|
|
int w;
|
|
int u;
|
|
};
|
|
|
|
struct ivec6
|
|
{
|
|
int x;
|
|
int y;
|
|
int z;
|
|
int w;
|
|
int u;
|
|
int v;
|
|
};
|
|
|
|
uniform float NAN;
|
|
`+g.defineSpecialNaN+`
|
|
`+g.defineSpecialInf+`
|
|
`+g.defineRound+`
|
|
|
|
int imod(int x, int y) {
|
|
return x - y * (x / y);
|
|
}
|
|
|
|
int idiv(int a, int b, float sign) {
|
|
int res = a / b;
|
|
int mod = imod(a, b);
|
|
if (sign < 0. && mod != 0) {
|
|
res -= 1;
|
|
}
|
|
return res;
|
|
}
|
|
|
|
//Based on the work of Dave Hoskins
|
|
//https://www.shadertoy.com/view/4djSRW
|
|
#define HASHSCALE1 443.8975
|
|
float random(float seed){
|
|
vec2 p = resultUV * seed;
|
|
vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);
|
|
p3 += dot(p3, p3.yzx + 19.19);
|
|
return fract((p3.x + p3.y) * p3.z);
|
|
}
|
|
|
|
`+P+`
|
|
`+B+`
|
|
`+H+`
|
|
`}(d);return n.isPacked?(o=function(g,x){switch(g.length){case 0:return`
|
|
int getOutputCoords() {
|
|
return 0;
|
|
}
|
|
`;case 1:return function(I,M){var j=[Math.ceil(M[0]/2),Math.ceil(M[1]/2)];return j[0]===1?`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.x * `+j[1]+`.0);
|
|
}
|
|
`:j[1]===1?`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.y * `+j[0]+`.0);
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(`+j[0]+", "+j[1]+`));
|
|
return 2 * (resTexRC.x * `+j[1]+` + resTexRC.y);
|
|
}
|
|
`}(0,x);case 2:return function(I,M){var j=[Math.ceil(M[0]/2),Math.ceil(M[1]/2)];if(Oe(I,M))return`
|
|
ivec2 getOutputCoords() {
|
|
return 2 * ivec2(resultUV.yx * vec2(`+j[0]+", "+j[1]+`));
|
|
}
|
|
`;var G=Math.ceil(I[1]/2);return`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(`+j[0]+", "+j[1]+`));
|
|
|
|
int index = resTexRC.x * `+j[1]+` + resTexRC.y;
|
|
int r = 2 * (index / `+G+`);
|
|
int c = imod(index, `+G+`) * 2;
|
|
|
|
return ivec2(r, c);
|
|
}
|
|
`}(g,x);case 3:return E=g,w=x,C=[Math.ceil(w[0]/2),Math.ceil(w[1]/2)],N=Math.ceil(E[2]/2),S=N*Math.ceil(E[1]/2),`
|
|
ivec3 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(`+C[0]+", "+C[1]+`));
|
|
int index = resTexRC.x * `+C[1]+` + resTexRC.y;
|
|
|
|
int b = index / `+S+`;
|
|
index -= b * `+S+`;
|
|
|
|
int r = 2 * (index / `+N+`);
|
|
int c = imod(index, `+N+`) * 2;
|
|
|
|
return ivec3(b, r, c);
|
|
}
|
|
`;default:return function(I,M){for(var j=[Math.ceil(M[0]/2),Math.ceil(M[1]/2)],G=Math.ceil(I[I.length-1]/2),z=G*Math.ceil(I[I.length-2]/2),W=z,V="",Z="b, r, c",J=2;J<I.length-1;J++)W*=I[I.length-J-1],V=`
|
|
int b`+J+" = index / "+W+`;
|
|
index -= b`+J+" * "+W+`;
|
|
`+V,Z="b"+J+", "+Z;return`
|
|
ivec`+I.length+` getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(`+j[0]+", "+j[1]+`));
|
|
int index = resTexRC.x * `+j[1]+` + resTexRC.y;
|
|
|
|
`+V+`
|
|
|
|
int b = index / `+z+`;
|
|
index -= b * `+z+`;
|
|
|
|
int r = 2 * (index / `+G+`);
|
|
int c = imod(index, `+G+`) * 2;
|
|
|
|
return ivec`+I.length+"("+Z+`);
|
|
}
|
|
`}(g,x)}var E,w,C,N,S}(n.logicalShape,c),i=function(g){return`
|
|
void setOutput(vec4 val) {
|
|
`+g.output+` = val;
|
|
}
|
|
`}(d)):(o=function(g,x){switch(g.length){case 0:return`
|
|
int getOutputCoords() {
|
|
return 0;
|
|
}
|
|
`;case 1:return function(C,N){return N[0]===1?`
|
|
int getOutputCoords() {
|
|
return int(resultUV.x * `+N[1]+`.0);
|
|
}
|
|
`:N[1]===1?`
|
|
int getOutputCoords() {
|
|
return int(resultUV.y * `+N[0]+`.0);
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(`+N[0]+", "+N[1]+`));
|
|
return resTexRC.x * `+N[1]+` + resTexRC.y;
|
|
}
|
|
`}(0,x);case 2:return function(C,N){return Oe(C,N)?`
|
|
ivec2 getOutputCoords() {
|
|
return ivec2(resultUV.yx * vec2(`+N[0]+", "+N[1]+`));
|
|
}
|
|
`:C[1]===1?`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(`+N[0]+", "+N[1]+`));
|
|
int index = resTexRC.x * `+N[1]+` + resTexRC.y;
|
|
return ivec2(index, 0);
|
|
}
|
|
`:C[0]===1?`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(`+N[0]+", "+N[1]+`));
|
|
int index = resTexRC.x * `+N[1]+` + resTexRC.y;
|
|
return ivec2(0, index);
|
|
}
|
|
`:`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(`+N[0]+", "+N[1]+`));
|
|
int index = resTexRC.x * `+N[1]+` + resTexRC.y;
|
|
int r = index / `+C[1]+`;
|
|
int c = index - r * `+C[1]+`;
|
|
return ivec2(r, c);
|
|
}
|
|
`}(g,x);case 3:return E=x,w=v(["r","c","d"],g),`
|
|
ivec3 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(`+E[0]+", "+E[1]+`));
|
|
int index = resTexRC.x * `+E[1]+` + resTexRC.y;
|
|
`+w+`
|
|
return ivec3(r, c, d);
|
|
}
|
|
`;case 4:return function(C,N){var S=v(["r","c","d","d2"],C);return`
|
|
ivec4 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(`+N[0]+", "+N[1]+`));
|
|
int index = resTexRC.x * `+N[1]+` + resTexRC.y;
|
|
`+S+`
|
|
return ivec4(r, c, d, d2);
|
|
}
|
|
`}(g,x);case 5:return function(C,N){var S=v(["r","c","d","d2","d3"],C);return`
|
|
ivec5 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx * vec2(`+N[0]+`,
|
|
`+N[1]+`));
|
|
|
|
int index = resTexRC.x * `+N[1]+` + resTexRC.y;
|
|
|
|
`+S+`
|
|
|
|
ivec5 outShape = ivec5(r, c, d, d2, d3);
|
|
return outShape;
|
|
}
|
|
`}(g,x);case 6:return function(C,N){var S=v(["r","c","d","d2","d3","d4"],C);return`
|
|
ivec6 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(`+N[0]+", "+N[1]+`));
|
|
int index = resTexRC.x * `+N[1]+` + resTexRC.y;
|
|
|
|
`+S+`
|
|
|
|
ivec6 result = ivec6(r, c, d, d2, d3, d4);
|
|
return result;
|
|
}
|
|
`}(g,x);default:throw new Error(g.length+"-D output sampling is not yet supported")}var E,w}(n.logicalShape,c),i=function(g){return`
|
|
void setOutput(float val) {
|
|
`+g.output+` = vec4(val, 0, 0, 0);
|
|
}
|
|
`}(d)),t&&(m+=Y),[m,f,i,s,o,u,e].join(`
|
|
`)}function A(r){var n=r.shapeInfo.logicalShape;switch(n.length){case 0:return function(e){var t=e.name,a="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return"float "+a+"() {return "+t+";}";var o=e.shapeInfo.texShape,i=o[0],s=o[1];if(i===1&&s===1)return`
|
|
float `+a+`() {
|
|
return sampleTexture(`+t+`, halfCR);
|
|
}
|
|
`;var u=e.shapeInfo.texShape,c=u[0],d=u[1],f=Q(t);return`
|
|
float `+a+`() {
|
|
vec2 uv = uvFromFlat(`+c+", "+d+", "+f+`);
|
|
return sampleTexture(`+t+`, uv);
|
|
}
|
|
`}(r);case 1:return function(e){var t=e.name,a="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return`
|
|
float `+a+`(int index) {
|
|
`+ue(e)+`
|
|
}
|
|
`;var o=e.shapeInfo.texShape,i=o[0],s=o[1];if(s===1&&i===1)return`
|
|
float `+a+`(int index) {
|
|
return sampleTexture(`+t+`, halfCR);
|
|
}
|
|
`;var u=Q(t);return s===1?`
|
|
float `+a+`(int index) {
|
|
vec2 uv = vec2(0.5, (float(index + `+u+") + 0.5) / "+i+`.0);
|
|
return sampleTexture(`+t+`, uv);
|
|
}
|
|
`:i===1?`
|
|
float `+a+`(int index) {
|
|
vec2 uv = vec2((float(index + `+u+") + 0.5) / "+s+`.0, 0.5);
|
|
return sampleTexture(`+t+`, uv);
|
|
}
|
|
`:`
|
|
float `+a+`(int index) {
|
|
vec2 uv = uvFromFlat(`+i+", "+s+", index + "+u+`);
|
|
return sampleTexture(`+t+`, uv);
|
|
}
|
|
`}(r);case 2:return function(e){var t=e.shapeInfo.logicalShape,a=e.name,o="get"+a.charAt(0).toUpperCase()+a.slice(1),i=e.shapeInfo.texShape;if(i!=null&&Oe(t,i)){var s=i[0],u=i[1];return`
|
|
float `+o+`(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(`+u+".0, "+s+`.0);
|
|
return sampleTexture(`+a+`, uv);
|
|
}
|
|
`}var c=St(t),d=c.newShape,f=c.keptDims,m=d;if(m.length<t.length){var g=_e(e,m);return`
|
|
`+A(g)+`
|
|
float `+o+`(int row, int col) {
|
|
return `+o+"("+De(["row","col"],f)+`);
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float `+o+`(int row, int col) {
|
|
int index = round(dot(vec2(row, col), vec2(`+t[1]+`, 1)));
|
|
`+ue(e)+`
|
|
}
|
|
`;var x=i[0],E=i[1],w=Q(a);return E===1?`
|
|
float `+o+`(int row, int col) {
|
|
float index = dot(vec3(row, col, `+w+"), vec3("+t[1]+`, 1, 1));
|
|
vec2 uv = vec2(0.5, (index + 0.5) / `+x+`.0);
|
|
return sampleTexture(`+a+`, uv);
|
|
}
|
|
`:x===1?`
|
|
float `+o+`(int row, int col) {
|
|
float index = dot(vec3(row, col, `+w+"), vec3("+t[1]+`, 1, 1));
|
|
vec2 uv = vec2((index + 0.5) / `+E+`.0, 0.5);
|
|
return sampleTexture(`+a+`, uv);
|
|
}
|
|
`:`
|
|
float `+o+`(int row, int col) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * `+t[1]+" + col + "+w+`;
|
|
vec2 uv = uvFromFlat(`+x+", "+E+`, index);
|
|
return sampleTexture(`+a+`, uv);
|
|
}
|
|
`}(r);case 3:return function(e){var t=e.shapeInfo.logicalShape,a=e.name,o="get"+a.charAt(0).toUpperCase()+a.slice(1),i=t[1]*t[2],s=t[2],u=St(t),c=u.newShape,d=u.keptDims,f=c;if(f.length<t.length){var m=_e(e,f);return`
|
|
`+A(m)+`
|
|
float `+o+`(int row, int col, int depth) {
|
|
return `+o+"("+De(["row","col","depth"],d)+`);
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float `+o+`(int row, int col, int depth) {
|
|
int index = round(dot(vec3(row, col, depth),
|
|
vec3(`+i+", "+s+`, 1)));
|
|
`+ue(e)+`
|
|
}
|
|
`;var g=e.shapeInfo.texShape,x=g[0],E=g[1],w=e.shapeInfo.flatOffset;if(E===i&&w==null)return`
|
|
float `+o+`(int row, int col, int depth) {
|
|
float texR = float(row);
|
|
float texC = dot(vec2(col, depth), vec2(`+s+`, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(`+E+".0, "+x+`.0);
|
|
return sampleTexture(`+a+`, uv);
|
|
}
|
|
`;if(E===s&&w==null)return`
|
|
float `+o+`(int row, int col, int depth) {
|
|
float texR = dot(vec2(row, col), vec2(`+t[1]+`, 1));
|
|
float texC = float(depth);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(`+E+".0, "+x+`.0);
|
|
return sampleTexture(`+a+`, uv);
|
|
}
|
|
`;var C=Q(a);return`
|
|
float `+o+`(int row, int col, int depth) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * `+i+" + col * "+s+" + depth + "+C+`;
|
|
vec2 uv = uvFromFlat(`+x+", "+E+`, index);
|
|
return sampleTexture(`+a+`, uv);
|
|
}
|
|
`}(r);case 4:return function(e){var t=e.shapeInfo.logicalShape,a=e.name,o="get"+a.charAt(0).toUpperCase()+a.slice(1),i=t[3],s=t[2]*i,u=t[1]*s,c=St(t),d=c.newShape,f=c.keptDims;if(d.length<t.length){var m=_e(e,d);return`
|
|
`+A(m)+`
|
|
float `+o+`(int row, int col, int depth, int depth2) {
|
|
return `+o+"("+De(["row","col","depth","depth2"],f)+`);
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float `+o+`(int row, int col, int depth, int depth2) {
|
|
int index = round(dot(vec4(row, col, depth, depth2),
|
|
vec4(`+u+", "+s+", "+i+`, 1)));
|
|
`+ue(e)+`
|
|
}
|
|
`;var g=e.shapeInfo.flatOffset,x=e.shapeInfo.texShape,E=x[0],w=x[1];if(w===u&&g==null)return`
|
|
float `+o+`(int row, int col, int depth, int depth2) {
|
|
float texR = float(row);
|
|
float texC =
|
|
dot(vec3(col, depth, depth2),
|
|
vec3(`+s+", "+i+`, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(`+w+".0, "+E+`.0);
|
|
return sampleTexture(`+a+`, uv);
|
|
}
|
|
`;if(w===i&&g==null)return`
|
|
float `+o+`(int row, int col, int depth, int depth2) {
|
|
float texR = dot(vec3(row, col, depth),
|
|
vec3(`+t[1]*t[2]+", "+t[2]+`, 1));
|
|
float texC = float(depth2);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(`+w+".0, "+E+`.0);
|
|
return sampleTexture(`+a+`, uv);
|
|
}
|
|
`;var C=Q(a);return`
|
|
float `+o+`(int row, int col, int depth, int depth2) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * `+u+" + col * "+s+` +
|
|
depth * `+i+` + depth2;
|
|
vec2 uv = uvFromFlat(`+E+", "+w+", index + "+C+`);
|
|
return sampleTexture(`+a+`, uv);
|
|
}
|
|
`}(r);case 5:return function(e){var t=e.shapeInfo.logicalShape,a=e.name,o="get"+a.charAt(0).toUpperCase()+a.slice(1),i=t[4],s=t[3]*i,u=t[2]*s,c=t[1]*u,d=St(t),f=d.newShape,m=d.keptDims;if(f.length<t.length){var g=_e(e,f);return`
|
|
`+A(g)+`
|
|
float `+o+`(int row, int col, int depth, int depth2, int depth3) {
|
|
return `+o+"("+De(["row","col","depth","depth2","depth3"],m)+`);
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float `+o+`(int row, int col, int depth, int depth2, int depth3) {
|
|
float index = dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(`+c+", "+u+", "+s+", "+i+`)) +
|
|
depth3;
|
|
`+ue(e)+`
|
|
}
|
|
`;var x=e.shapeInfo.flatOffset,E=e.shapeInfo.texShape,w=E[0],C=E[1];if(C===c&&x==null)return`
|
|
float `+o+`(int row, int col, int depth, int depth2, int depth3) {
|
|
int texR = row;
|
|
float texC = dot(vec4(col, depth, depth2, depth3),
|
|
vec4(`+u+", "+s+", "+i+`, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(`+C+".0, "+w+`.0);
|
|
return sampleTexture(`+a+`, uv);
|
|
}
|
|
`;if(C===i&&x==null)return`
|
|
float `+o+`(int row, int col, int depth, int depth2, int depth3) {
|
|
float texR = dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(`+t[1]*t[2]*t[3]+`,
|
|
`+t[2]*t[3]+", "+t[3]+`, 1));
|
|
int texC = depth3;
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(`+C+".0, "+w+`.0);
|
|
return sampleTexture(`+a+`, uv);
|
|
}
|
|
`;var N=Q(a);return`
|
|
float `+o+`(int row, int col, int depth, int depth2, int depth3) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * `+c+" + col * "+u+" + depth * "+s+` +
|
|
depth2 * `+i+" + depth3 + "+N+`;
|
|
vec2 uv = uvFromFlat(`+w+", "+C+`, index);
|
|
return sampleTexture(`+a+`, uv);
|
|
}
|
|
`}(r);case 6:return function(e){var t=e.shapeInfo.logicalShape,a=e.name,o="get"+a.charAt(0).toUpperCase()+a.slice(1),i=St(t),s=i.newShape,u=i.keptDims;if(s.length<t.length){var c=_e(e,s);return`
|
|
`+A(c)+`
|
|
float `+o+`(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
return `+o+"("+De(["row","col","depth","depth2","depth3","depth4"],u)+`);
|
|
}
|
|
`}var d=t[5],f=t[4]*d,m=t[3]*f,g=t[2]*m,x=t[1]*g;if(e.shapeInfo.isUniform)return`
|
|
float `+o+`(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
int index = round(dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(`+x+", "+g+", "+m+", "+f+`)) +
|
|
dot(
|
|
vec2(depth3, depth4),
|
|
vec2(`+d+`, 1)));
|
|
`+ue(e)+`
|
|
}
|
|
`;var E=e.shapeInfo.flatOffset,w=e.shapeInfo.texShape,C=w[0],N=w[1];if(N===x&&E==null)return`
|
|
float `+o+`(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
int texR = row;
|
|
float texC = dot(vec4(col, depth, depth2, depth3),
|
|
vec4(`+g+", "+m+", "+f+", "+d+`)) +
|
|
float(depth4);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(`+N+".0, "+C+`.0);
|
|
return sampleTexture(`+a+`, uv);
|
|
}
|
|
`;if(N===d&&E==null)return`
|
|
float `+o+`(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
float texR = dot(vec4(row, col, depth, depth2),
|
|
vec4(`+t[1]*t[2]*t[3]*t[4]+`,
|
|
`+t[2]*t[3]*t[4]+`,
|
|
`+t[3]*t[4]+`,
|
|
`+t[4]+`)) + float(depth3);
|
|
int texC = depth4;
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(`+N+".0, "+C+`.0);
|
|
return sampleTexture(`+a+`, uv);
|
|
}
|
|
`;var S=Q(a);return`
|
|
float `+o+`(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * `+x+" + col * "+g+" + depth * "+m+` +
|
|
depth2 * `+f+" + depth3 * "+d+" + depth4 + "+S+`;
|
|
vec2 uv = uvFromFlat(`+C+", "+N+`, index);
|
|
return sampleTexture(`+a+`, uv);
|
|
}
|
|
`}(r);default:throw new Error(n.length+"-D input sampling is not yet supported")}}function O(r){var n,e,t;switch(r.shapeInfo.logicalShape.length){case 0:return n=r.name,e="get"+n.charAt(0).toUpperCase()+n.slice(1),t=h(),`
|
|
vec4 `+e+`() {
|
|
return `+t.texture2D+"("+n+`, halfCR);
|
|
}
|
|
`;case 1:return function(a){var o=a.name,i="get"+o.charAt(0).toUpperCase()+o.slice(1),s=a.shapeInfo.texShape,u=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)],c=h();return`
|
|
vec4 `+i+`(int index) {
|
|
vec2 uv = packedUVfrom1D(
|
|
`+u[0]+", "+u[1]+`, index);
|
|
return `+c.texture2D+"("+o+`, uv);
|
|
}
|
|
`}(r);case 2:return function(a){var o=a.shapeInfo.logicalShape,i=a.name,s="get"+i.charAt(0).toUpperCase()+i.slice(1),u=a.shapeInfo.texShape,c=u[0],d=u[1],f=h();if(u!=null&&Oe(o,u))return`
|
|
vec4 `+s+`(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(`+d+".0, "+c+`.0);
|
|
|
|
return `+f.texture2D+"("+i+`, uv);
|
|
}
|
|
`;var m=[Math.ceil(u[0]/2),Math.ceil(u[1]/2)],g=Math.ceil(o[1]/2);return`
|
|
vec4 `+s+`(int row, int col) {
|
|
vec2 uv = packedUVfrom2D(`+g+", "+m[0]+", "+m[1]+`, row, col);
|
|
return `+f.texture2D+"("+i+`, uv);
|
|
}
|
|
`}(r);case 3:return function(a){var o=a.shapeInfo.logicalShape,i=a.name,s="get"+i.charAt(0).toUpperCase()+i.slice(1),u=a.shapeInfo.texShape,c=[Math.ceil(u[0]/2),Math.ceil(u[1]/2)];if(o[0]===1){var d=o.slice(1),f=_e(a,d);return`
|
|
`+O(f)+`
|
|
vec4 `+s+`(int b, int row, int col) {
|
|
return `+s+"("+De(["b","row","col"],[1,2])+`);
|
|
}
|
|
`}var m=c[0],g=c[1],x=Math.ceil(o[2]/2),E=x*Math.ceil(o[1]/2),w=h();return`
|
|
vec4 `+s+`(int b, int row, int col) {
|
|
vec2 uv = packedUVfrom3D(
|
|
`+m+", "+g+", "+E+", "+x+`, b, row, col);
|
|
return `+w.texture2D+"("+i+`, uv);
|
|
}
|
|
`}(r);default:return function(a){for(var o=a.shapeInfo.logicalShape,i=o.length,s=a.name,u="get"+s.charAt(0).toUpperCase()+s.slice(1),c=a.shapeInfo.texShape,d=[Math.ceil(c[0]/2),Math.ceil(c[1]/2)],f=d[0],m=d[1],g=Math.ceil(o[i-1]/2),x=g*Math.ceil(o[i-2]/2),E="int b, int row, int col",w="b * "+x+" + (row / 2) * "+g+" + (col / 2)",C=2;C<i-1;C++)E="int b"+C+", "+E,x*=o[i-C-1],w="b"+C+" * "+x+" + "+w;var N=h();return`
|
|
vec4 `+u+"("+E+`) {
|
|
int index = `+w+`;
|
|
int texR = index / `+m+`;
|
|
int texC = index - texR * `+m+`;
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(`+m+", "+f+`);
|
|
return `+N.texture2D+"("+s+`, uv);
|
|
}
|
|
`}(r)}}var P=`
|
|
vec2 uvFromFlat(int texNumR, int texNumC, int index) {
|
|
int texR = index / texNumC;
|
|
int texC = index - texR * texNumC;
|
|
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
|
|
}
|
|
vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {
|
|
int texelIndex = index / 2;
|
|
int texR = texelIndex / texNumC;
|
|
int texC = texelIndex - texR * texNumC;
|
|
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
|
|
}
|
|
`,B=`
|
|
vec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,
|
|
int texNumC, int row, int col) {
|
|
int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);
|
|
int texR = texelIndex / texNumC;
|
|
int texC = texelIndex - texR * texNumC;
|
|
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
|
|
}
|
|
`,H=`
|
|
vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
int texelsInBatch, int texelsInLogicalRow, int b,
|
|
int row, int col) {
|
|
int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);
|
|
int texR = index / texNumC;
|
|
int texC = index - texR * texNumC;
|
|
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
|
|
}
|
|
`,Y=`
|
|
float getChannel(vec4 frag, vec2 innerDims) {
|
|
vec2 modCoord = mod(innerDims, 2.);
|
|
return modCoord.x == 0. ?
|
|
(modCoord.y == 0. ? frag.r : frag.g) :
|
|
(modCoord.y == 0. ? frag.b : frag.a);
|
|
}
|
|
float getChannel(vec4 frag, int dim) {
|
|
float modCoord = mod(float(dim), 2.);
|
|
return modCoord == 0. ? frag.r : frag.g;
|
|
}
|
|
`;function Q(r){return"offset"+r}function ue(r){var n=r.name,e=ae(r.shapeInfo.logicalShape);return e<2?"return "+n+";":`
|
|
for (int i = 0; i < `+e+`; i++) {
|
|
if (i == index) {
|
|
return `+n+`[i];
|
|
}
|
|
}
|
|
`}function le(r){if(r<=1)return"int";if(r===2)return"ivec2";if(r===3)return"ivec3";if(r===4)return"ivec4";if(r===5)return"ivec5";if(r===6)return"ivec6";throw Error("GPU for rank "+r+" is not yet supported")}function _e(r,n){var e=JSON.parse(JSON.stringify(r));return e.shapeInfo.logicalShape=n,e}function De(r,n){return n.map(function(e){return r[e]}).join(", ")}var Ue=function(r,n,e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,D(r.length>2,function(){return"Packed arg"+(e.charAt(0).toUpperCase()+e.slice(1))+" supports only inputs with rank above 2."});var a=r[r.length-1],o=Math.ceil(a/n);this.outputShape=r.slice(0,-1),o>1&&this.outputShape.push(o),t||this.variableNames.push("bestIndicesA");var i,s,u=this.outputShape,c=u.length,d=le(c),f=l("coords",c);if(o===1){var m=le(s=c+1);i=`
|
|
`+m+" sourceLocR = "+m+"("+f.join()+`, 0);
|
|
++`+f[c-1]+`;
|
|
`+m+" sourceLocG = "+m+"("+f.join()+`, 0);
|
|
++`+f[c-2]+`;
|
|
`+m+" sourceLocA = "+m+"("+f.join()+`, 0);
|
|
--`+f[c-1]+`;
|
|
`+m+" sourceLocB = "+m+"("+f.join()+`, 0);
|
|
--`+f[c-2]+";"}else s=c,i=`
|
|
`+d+` sourceLocR = coords;
|
|
++`+f[c-1]+`;
|
|
`+d+` sourceLocG = coords;
|
|
++`+f[c-2]+`;
|
|
`+d+` sourceLocA = coords;
|
|
--`+f[c-1]+`;
|
|
`+d+` sourceLocB = coords;
|
|
--`+f[c-2]+";";var g=["x","y","z","w","u","v"].slice(0,s),x="."+g[s-1],E=g.map(function(z){return"int "+z}),w=l("sourceLocR",s-1).concat("inIdx.r"),C=l("sourceLocG",s-1).concat("inIdx.g"),N=l("sourceLocB",s-1).concat("inIdx.b"),S=l("sourceLocA",s-1).concat("inIdx.a"),I=e==="max"?"greaterThan":"lessThan",M=t?"":`
|
|
inIdx = round(vec4(getBestIndicesAChannel(`+w.join()+`),
|
|
getBestIndicesAChannel(`+C.join()+`),
|
|
getBestIndicesAChannel(`+N.join()+`),
|
|
getBestIndicesAChannel(`+S.join()+")));",j=`vec4(
|
|
getAChannel(`+w.join()+`),
|
|
hasNextCol ? getAChannel(`+C.join()+`) : 0.,
|
|
hasNextRow ? getAChannel(`+N.join()+`) : 0.,
|
|
hasNextRow && hasNextCol ? getAChannel(`+S.join()+") : 0.)",G=t?"":`
|
|
float getBestIndicesAChannel(`+E.join()+`) {
|
|
return getChannel(getBestIndicesA(`+g.join()+`),
|
|
vec2(`+g.slice(-2).join()+`));
|
|
}`;this.userCode=`
|
|
float getAChannel(`+E.join()+`) {
|
|
return getChannel(getA(`+g.join()+`),
|
|
vec2(`+g.slice(-2).join()+`));
|
|
}
|
|
`+G+`
|
|
void main() {
|
|
`+d+` coords = getOutputCoords();
|
|
bool hasNextCol = `+f[c-1]+" < "+(u[c-1]-1)+`;
|
|
bool hasNextRow = `+f[c-2]+" < "+(u[c-2]-1)+`;
|
|
`+i+`
|
|
ivec4 srcIdx = ivec4(sourceLocR`+x+", sourceLocG"+x+`,
|
|
sourceLocB`+x+", sourceLocA"+x+") * "+n+`;
|
|
ivec4 inIdx = srcIdx;
|
|
vec4 bestIndex = vec4(inIdx);
|
|
vec4 bestValue = `+j+`;
|
|
|
|
for (int i = 0; i < `+n+`; i++) {
|
|
inIdx = srcIdx;
|
|
`+M+`
|
|
vec4 candidate = `+j+`;
|
|
bvec4 nan = isnan(candidate);
|
|
bvec4 replace = bvec4(
|
|
vec4(`+I+`(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
|
|
|
|
bestValue = vec4(replace.x ? candidate.x : bestValue.x,
|
|
replace.y ? candidate.y : bestValue.y,
|
|
replace.z ? candidate.z : bestValue.z,
|
|
replace.w ? candidate.w : bestValue.w);
|
|
bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
|
|
srcIdx++;
|
|
}
|
|
setOutput(bestIndex);
|
|
}
|
|
`},Fe=function(r){this.variableNames=["dy"],this.outputShape=r.inShape;var n=r.filterHeight,e=r.filterWidth,t=r.strideHeight,a=r.strideWidth,o=r.dilationHeight,i=r.dilationWidth,s=r.effectiveFilterHeight,u=r.effectiveFilterWidth,c=s-1-r.padInfo.top,d=u-1-r.padInfo.left,f=1/(n*e);this.userCode=`
|
|
const ivec2 pads = ivec2(`+c+", "+d+`);
|
|
const float avgMultiplier = float(`+f+`);
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
|
|
ivec2 dyRCCorner = coords.yz - pads;
|
|
int dyRCorner = dyRCCorner.x;
|
|
int dyCCorner = dyRCCorner.y;
|
|
|
|
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wR = 0; wR < `+s+`;
|
|
wR += `+o+`) {
|
|
float dyR = float(dyRCorner + wR) / `+t+`.0;
|
|
|
|
if (dyR < 0.0 || dyR >= `+r.outHeight+`.0 || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
for (int wC = 0; wC < `+u+`;
|
|
wC+= `+i+`) {
|
|
float dyC = float(dyCCorner + wC) / `+a+`.0;
|
|
|
|
if (dyC < 0.0 || dyC >= `+r.outWidth+`.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
float dyValue = getDy(b, idyR, idyC, d);
|
|
|
|
dotProd += dyValue * avgMultiplier;
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`},we=function(r){this.variableNames=["dy"],this.outputShape=r.inShape;var n=r.filterDepth,e=r.filterHeight,t=r.filterWidth,a=r.strideDepth,o=r.strideHeight,i=r.strideWidth,s=r.dilationDepth,u=r.dilationHeight,c=r.dilationWidth,d=r.effectiveFilterDepth,f=r.effectiveFilterHeight,m=r.effectiveFilterWidth,g=d-1-r.padInfo.front,x=f-1-r.padInfo.top,E=m-1-r.padInfo.left,w=1/(n*e*t);this.userCode=`
|
|
const ivec3 pads = ivec3(`+g+", "+x+", "+E+`);
|
|
const float avgMultiplier = float(`+w+`);
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
|
|
int dyDCorner = dyCorner.x;
|
|
int dyRCorner = dyCorner.y;
|
|
int dyCCorner = dyCorner.z;
|
|
|
|
// Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
|
|
// dx(xD, xR, xC, ch).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
|
|
for (int wD = 0; wD < `+d+`;
|
|
wD += `+s+`) {
|
|
float dyD = float(dyDCorner + wD) / `+a+`.0;
|
|
|
|
if (dyD < 0.0 || dyD >= `+r.outDepth+`.0 || fract(dyD) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyD = int(dyD);
|
|
|
|
for (int wR = 0; wR < `+f+`;
|
|
wR += `+u+`) {
|
|
float dyR = float(dyRCorner + wR) / `+o+`.0;
|
|
|
|
if (dyR < 0.0 || dyR >= `+r.outHeight+`.0 ||
|
|
fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
for (int wC = 0; wC < `+m+`;
|
|
wC += `+c+`) {
|
|
float dyC = float(dyCCorner + wC) / `+i+`.0;
|
|
|
|
if (dyC < 0.0 || dyC >= `+r.outWidth+`.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
|
|
|
|
dotProd += dyValue * avgMultiplier;
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`},Ne=function(r,n,e,t,a,o){this.outputShape=[],this.variableNames=["x","mean","variance"],nt(r,n),nt(r,e);var i="0.0";t!=null&&(nt(r,t),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");var s="1.0";a!=null&&(nt(r,a),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=r,this.userCode=`
|
|
void main() {
|
|
float x = getXAtOutCoords();
|
|
float mean = getMeanAtOutCoords();
|
|
float variance = getVarianceAtOutCoords();
|
|
float offset = `+i+`;
|
|
float scale = `+s+`;
|
|
float inv = scale * inversesqrt(variance + float(`+o+`));
|
|
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
|
|
}
|
|
`},Ze=function(r,n,e,t,a,o){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],nt(r,n),nt(r,e);var i="vec4(0.0)";t!=null&&(nt(r,t),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");var s="vec4(1.0)";a!=null&&(nt(r,a),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=r,this.userCode=`
|
|
void main() {
|
|
vec4 offset = `+i+`;
|
|
vec4 scale = `+s+`;
|
|
|
|
vec4 x = getXAtOutCoords();
|
|
vec4 mean = getMeanAtOutCoords();
|
|
vec4 variance = getVarianceAtOutCoords();
|
|
|
|
vec4 inv = scale * inversesqrt(variance + vec4(`+o+`));
|
|
|
|
setOutput((x - mean) * inv + offset);
|
|
}
|
|
`},Bt="return areal * breal - aimag * bimag;",Yt="return areal * bimag + aimag * breal;",At=function(r,n,e){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=nt(n,e),this.userCode=`
|
|
float binaryOpComplex(
|
|
float areal, float aimag, float breal, float bimag) {
|
|
`+r+`
|
|
}
|
|
|
|
void main() {
|
|
float areal = getARealAtOutCoords();
|
|
float aimag = getAImagAtOutCoords();
|
|
float breal = getBRealAtOutCoords();
|
|
float bimag = getBImagAtOutCoords();
|
|
setOutput(binaryOpComplex(areal, aimag, breal, bimag));
|
|
}
|
|
`},rt="return a + b;",Kt="return a - b;",on="return a * b;",nn="return (a < 0.) ? b * a : a;",dt=function(r,n,e){this.variableNames=["A","B"],this.outputShape=nt(n,e),this.userCode=`
|
|
float binaryOperation(float a, float b) {
|
|
`+r+`
|
|
}
|
|
|
|
void main() {
|
|
float a = getAAtOutCoords();
|
|
float b = getBAtOutCoords();
|
|
setOutput(binaryOperation(a, b));
|
|
}
|
|
`},zn=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`,Ie=function(r,n,e,t){t===void 0&&(t=!1),this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=nt(n,e);var a=this.outputShape.length,o="";if(t)if(a===0||ae(this.outputShape)===1)o=`
|
|
result.y = 0.;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`;else if(o=`
|
|
`+le(a)+` coords = getOutputCoords();
|
|
`,a===1)o+=`
|
|
result.y = (coords + 1) >= `+this.outputShape[0]+` ? 0. : result.y;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`;else{var i=l("coords",a);o+=`
|
|
bool nextRowOutOfBounds =
|
|
(`+i[a-2]+" + 1) >= "+this.outputShape[a-2]+`;
|
|
bool nextColOutOfBounds =
|
|
(`+i[a-1]+" + 1) >= "+this.outputShape[a-1]+`;
|
|
result.y = nextColOutOfBounds ? 0. : result.y;
|
|
result.z = nextRowOutOfBounds ? 0. : result.z;
|
|
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
|
|
`}this.userCode=`
|
|
vec4 binaryOperation(vec4 a, vec4 b) {
|
|
`+r+`
|
|
}
|
|
|
|
void main() {
|
|
vec4 a = getAAtOutCoords();
|
|
vec4 b = getBAtOutCoords();
|
|
|
|
vec4 result = binaryOperation(a, b);
|
|
`+o+`
|
|
|
|
setOutput(result);
|
|
}
|
|
`},Sn=function(){function r(n){this.variableNames=["A"],this.outputShape=n,this.userCode=`
|
|
uniform float minVal;
|
|
uniform float maxVal;
|
|
|
|
void main() {
|
|
float value = getAAtOutCoords();
|
|
if (isnan(value)) {
|
|
setOutput(value);
|
|
return;
|
|
}
|
|
|
|
setOutput(clamp(value, minVal, maxVal));
|
|
}
|
|
`}return r.prototype.getCustomSetupFunc=function(n,e){var t=this;return function(a,o){t.minLoc==null&&(t.minLoc=a.getUniformLocationNoThrow(o,"minVal"),t.maxLoc=a.getUniformLocationNoThrow(o,"maxVal")),a.gl.uniform1f(t.minLoc,n),a.gl.uniform1f(t.maxLoc,e)}},r}(),Ot=function(){function r(n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n,this.userCode=`
|
|
uniform float minVal;
|
|
uniform float maxVal;
|
|
|
|
void main() {
|
|
vec4 value = getAAtOutCoords();
|
|
|
|
if (any(isnan(value))) {
|
|
setOutput(value);
|
|
return;
|
|
}
|
|
|
|
setOutput(clamp(value, vec4(minVal), vec4(maxVal)));
|
|
}
|
|
`}return r.prototype.getCustomSetupFunc=function(n,e){var t=this;return function(a,o){t.minLoc==null&&(t.minLoc=a.getUniformLocationNoThrow(o,"minVal"),t.maxLoc=a.getUniformLocationNoThrow(o,"maxVal")),a.gl.uniform1f(t.minLoc,n),a.gl.uniform1f(t.maxLoc,e)}},r}(),sn=function(r){this.variableNames=["real","imag"],this.outputShape=r,this.userCode=`
|
|
void main() {
|
|
float re = abs(getRealAtOutCoords());
|
|
float im = abs(getImagAtOutCoords());
|
|
float mx = max(re, im);
|
|
|
|
// sadly the length function in glsl is not underflow-safe
|
|
// (at least not on Intel GPUs). So the safe solution is
|
|
// to ensure underflow-safety in all cases.
|
|
setOutput(
|
|
mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))
|
|
);
|
|
}
|
|
`},Nr=function(r){this.outputShape=[],this.outputShape=jr(r,1),this.variableNames=r.map(function(s,u){return"T"+u});var n=new Array(r.length-1);n[0]=r[0][1];for(var e=1;e<n.length;e++)n[e]=n[e-1]+r[e][1];var t=["if (yC < "+n[0]+") setOutput(getT0(yR, yC));"];for(e=1;e<n.length;e++){var a=n[e-1];t.push("else if (yC < "+n[e]+") setOutput(getT"+e+"(yR, yC-"+a+"));")}var o=n.length,i=n[n.length-1];t.push("else setOutput(getT"+o+"(yR, yC-"+i+"));"),this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int yR = coords.x;
|
|
int yC = coords.y;
|
|
|
|
`+t.join(`
|
|
`)+`
|
|
}
|
|
`},hr=function(r,n){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=jr(r,n);var e=this.outputShape,t=e.length,a=le(t),o=l("coords",t),i=["x","y","z","w","u","v"].slice(0,t);this.variableNames=r.map(function(w,C){return"T"+C});var s=new Array(r.length-1);s[0]=r[0][n];for(var u=1;u<s.length;u++)s[u]=s[u-1]+r[u][n];var c=i[n],d=i.slice(-2),f=i.join(),m="if ("+c+" < "+s[0]+`) {
|
|
return getChannel(
|
|
getT0(`+f+"), vec2("+d.join()+`));
|
|
}`;for(u=1;u<s.length;u++){var g=s[u-1];m+=`
|
|
if (`+c+" < "+s[u]+" && "+c+" >= "+s[u-1]+`) {
|
|
return getChannel(
|
|
getT`+u+"("+kr(i,c,g)+`),
|
|
vec2(`+kr(d,c,g)+`));
|
|
}`}var x=s.length,E=s[s.length-1];m+=`
|
|
return getChannel(
|
|
getT`+x+"("+kr(i,c,E)+`),
|
|
vec2(`+kr(d,c,E)+"));",this.userCode=`
|
|
float getValue(`+i.map(function(w){return"int "+w})+`) {
|
|
`+m+`
|
|
}
|
|
|
|
void main() {
|
|
`+a+` coords = getOutputCoords();
|
|
vec4 result = vec4(getValue(`+o+`), 0., 0., 0.);
|
|
|
|
`+o[t-1]+" = "+o[t-1]+` + 1;
|
|
if (`+o[t-1]+" < "+e[t-1]+`) {
|
|
result.g = getValue(`+o+`);
|
|
}
|
|
|
|
`+o[t-2]+" = "+o[t-2]+` + 1;
|
|
if (`+o[t-2]+" < "+e[t-2]+`) {
|
|
result.a = getValue(`+o+`);
|
|
}
|
|
|
|
`+o[t-1]+" = "+o[t-1]+` - 1;
|
|
if (`+o[t-2]+" < "+e[t-2]+` &&
|
|
`+o[t-1]+" < "+e[t-1]+`) {
|
|
result.b = getValue(`+o+`);
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`};function kr(r,n,e){var t=r.indexOf(n);return r.map(function(a,o){return o===t?a+" - "+e:a}).join()}var pa=function(r){this.variableNames=["x","dy"],this.outputShape=r.filterShape;var n=r.strideHeight,e=r.strideWidth,t=r.padInfo.top,a=r.padInfo.left,o=r.dataFormat==="channelsLast";this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int wR = coords.x;
|
|
int wC = coords.y;
|
|
int d1 = coords.z;
|
|
int d2 = coords.w;
|
|
|
|
// Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
|
|
for (int b = 0; b < `+r.batchSize+`; b++) {
|
|
for (int yR = 0; yR < `+r.outHeight+`; yR++) {
|
|
int xR = wR + yR * `+n+" - "+t+`;
|
|
|
|
if (xR < 0 || xR >= `+r.inHeight+`) {
|
|
continue;
|
|
}
|
|
|
|
for (int yC = 0; yC < `+r.outWidth+`; yC++) {
|
|
int xC = wC + yC * `+e+" - "+a+`;
|
|
|
|
if (xC < 0 || xC >= `+r.inWidth+`) {
|
|
continue;
|
|
}
|
|
|
|
if (`+o+`) {
|
|
float dyValue = getDy(b, yR, yC, d2);
|
|
float xValue = getX(b, xR, xC, d1);
|
|
dotProd += (xValue * dyValue);
|
|
} else {
|
|
float dyValue = getDy(b, d2, yR, yC);
|
|
float xValue = getX(b, d1, xR, xC);
|
|
dotProd += (xValue * dyValue);
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`},Fa=function(r){this.variableNames=["dy","W"],this.outputShape=r.inShape;var n=r.filterHeight,e=r.filterWidth,t=r.strideHeight,a=r.strideWidth,o=r.dataFormat==="channelsLast",i=n-1-r.padInfo.top,s=e-1-r.padInfo.left,u=o?1:2,c=o?2:3,d=o?3:1;this.userCode=`
|
|
const ivec2 pads = ivec2(`+i+", "+s+`);
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d1 = coords[`+d+`];
|
|
|
|
ivec2 dyCorner = ivec2(coords[`+u+"], coords["+c+`]) - pads;
|
|
int dyRCorner = dyCorner.x;
|
|
int dyCCorner = dyCorner.y;
|
|
|
|
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wR = 0; wR < `+n+`; wR++) {
|
|
float dyR = float(dyRCorner + wR) / `+t+`.0;
|
|
|
|
if (dyR < 0.0 || dyR >= `+r.outHeight+`.0 || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
int wRPerm = `+n+` - 1 - wR;
|
|
|
|
for (int wC = 0; wC < `+e+`; wC++) {
|
|
float dyC = float(dyCCorner + wC) / `+a+`.0;
|
|
|
|
if (dyC < 0.0 || dyC >= `+r.outWidth+`.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
int wCPerm = `+e+` - 1 - wC;
|
|
|
|
for (int d2 = 0; d2 < `+r.outChannels+`; d2++) {
|
|
|
|
if (`+o+`) {
|
|
float xValue = getDy(batch, idyR, idyC, d2);
|
|
float wValue = getW(wRPerm, wCPerm, d1, d2);
|
|
dotProd += xValue * wValue;
|
|
} else {
|
|
float xValue = getDy(batch, d2, idyR, idyC);
|
|
float wValue = getW(wRPerm, wCPerm, d1, d2);
|
|
dotProd += xValue * wValue;
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`},jt=function(r){this.variableNames=["x","dy"],this.outputShape=r.filterShape;var n=r.strideDepth,e=r.strideHeight,t=r.strideWidth,a=r.padInfo.front,o=r.padInfo.top,i=r.padInfo.left;this.userCode=`
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int wF = coords.x;
|
|
int wR = coords.y;
|
|
int wC = coords.z;
|
|
int d1 = coords.w;
|
|
int d2 = coords.u;
|
|
|
|
float dotProd = 0.0;
|
|
|
|
for (int b = 0; b < `+r.batchSize+`; b++) {
|
|
for (int yF = 0; yF < `+r.outDepth+`; yF++) {
|
|
int xF = wF + yF * `+n+" - "+a+`;
|
|
|
|
if (xF < 0 || xF >= `+r.inDepth+`) {
|
|
continue;
|
|
}
|
|
|
|
for (int yR = 0; yR < `+r.outHeight+`; yR++) {
|
|
int xR = wR + yR * `+e+" - "+o+`;
|
|
|
|
if (xR < 0 || xR >= `+r.inHeight+`) {
|
|
continue;
|
|
}
|
|
|
|
for (int yC = 0; yC < `+r.outWidth+`; yC++) {
|
|
int xC = wC + yC * `+t+" - "+i+`;
|
|
|
|
if (xC < 0 || xC >= `+r.inWidth+`) {
|
|
continue;
|
|
}
|
|
|
|
float dyValue = getDy(b, yF, yR, yC, d2);
|
|
float xValue = getX(b, xF, xR, xC, d1);
|
|
dotProd += (xValue * dyValue);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`},He=function(r){this.variableNames=["dy","W"],this.outputShape=r.inShape;var n=r.filterDepth,e=r.filterHeight,t=r.filterWidth,a=r.strideDepth,o=r.strideHeight,i=r.strideWidth,s=n-1-r.padInfo.front,u=e-1-r.padInfo.top,c=t-1-r.padInfo.left;this.userCode=`
|
|
const ivec3 pads = ivec3(`+s+", "+u+", "+c+`);
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int d1 = coords.u;
|
|
|
|
|
|
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
|
|
int dyFCorner = dyCorner.x;
|
|
int dyRCorner = dyCorner.y;
|
|
int dyCCorner = dyCorner.z;
|
|
|
|
float dotProd = 0.0;
|
|
for (int wF = 0; wF < `+n+`; wF++) {
|
|
float dyF = float(dyFCorner + wF) / `+a+`.0;
|
|
|
|
if (dyF < 0.0 || dyF >= `+r.outDepth+`.0 || fract(dyF) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyF = int(dyF);
|
|
|
|
int wFPerm = `+n+` - 1 - wF;
|
|
|
|
for (int wR = 0; wR < `+e+`; wR++) {
|
|
float dyR = float(dyRCorner + wR) / `+o+`.0;
|
|
|
|
if (dyR < 0.0 || dyR >= `+r.outHeight+`.0 ||
|
|
fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
int wRPerm = `+e+` - 1 - wR;
|
|
|
|
for (int wC = 0; wC < `+t+`; wC++) {
|
|
float dyC = float(dyCCorner + wC) / `+i+`.0;
|
|
|
|
if (dyC < 0.0 || dyC >= `+r.outWidth+`.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
int wCPerm = `+t+` - 1 - wC;
|
|
|
|
for (int d2 = 0; d2 < `+r.outChannels+`; d2++) {
|
|
float xValue = getDy(batch, idyF, idyR, idyC, d2);
|
|
float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
|
|
dotProd += xValue * wValue;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`},ct=function(r){this.variableNames=["x","dy"],this.outputShape=r.filterShape;var n=r.strideHeight,e=r.strideWidth,t=r.padInfo.top,a=r.padInfo.left,o=r.outChannels/r.inChannels;this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int wR = coords.x;
|
|
int wC = coords.y;
|
|
int d1 = coords.z;
|
|
int dm = coords.w;
|
|
int d2 = d1 * `+o+` + dm;
|
|
|
|
float dotProd = 0.0;
|
|
|
|
// TO DO: Vec4 over the batch size
|
|
for (int b = 0; b < `+r.batchSize+`; b++) {
|
|
for (int yR = 0; yR < `+r.outHeight+`; yR++) {
|
|
int xR = wR + yR * `+n+" - "+t+`;
|
|
|
|
if (xR < 0 || xR >= `+r.inHeight+`) {
|
|
continue;
|
|
}
|
|
|
|
for (int yC = 0; yC < `+r.outWidth+`; yC++) {
|
|
int xC = wC + yC * `+e+" - "+a+`;
|
|
|
|
if (xC < 0 || xC >= `+r.inWidth+`) {
|
|
continue;
|
|
}
|
|
|
|
float dyValue = getDy(b, yR, yC, d2);
|
|
float xValue = getX(b, xR, xC, d1);
|
|
dotProd += (xValue * dyValue);
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`},Vt=function(r){this.variableNames=["dy","W"],this.outputShape=r.inShape;var n=r.filterHeight,e=r.filterWidth,t=r.strideHeight,a=r.strideWidth,o=n-1-r.padInfo.top,i=e-1-r.padInfo.left,s=r.outChannels/r.inChannels;this.userCode=`
|
|
const ivec2 pads = ivec2(`+o+", "+i+`);
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d1 = coords[3];
|
|
ivec2 dyCorner = coords.yz - pads;
|
|
int dyRCorner = dyCorner.x;
|
|
int dyCCorner = dyCorner.y;
|
|
|
|
float dotProd = 0.0;
|
|
|
|
for (int wR = 0; wR < `+n+`; wR++) {
|
|
float dyR = float(dyRCorner + wR) / `+t+`.0;
|
|
|
|
if (dyR < 0.0 || dyR >= `+r.outHeight+`.0 || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
int wRPerm = `+n+` - 1 - wR;
|
|
|
|
for (int wC = 0; wC < `+e+`; wC++) {
|
|
float dyC = float(dyCCorner + wC) / `+a+`.0;
|
|
|
|
if (dyC < 0.0 || dyC >= `+r.outWidth+`.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
int wCPerm = `+e+` - 1 - wC;
|
|
|
|
// TO DO: Vec4 over the channelMul
|
|
for (int dm = 0; dm < `+s+`; dm++) {
|
|
int d2 = d1 * `+s+` + dm;
|
|
float xValue = getDy(batch, idyR, idyC, d2);
|
|
float wValue = getW(wRPerm, wCPerm, d1, dm);
|
|
dotProd += xValue * wValue;
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`},Xn=function(r,n,e,t){n===void 0&&(n=!1),e===void 0&&(e=null),t===void 0&&(t=!1),this.variableNames=["x","W"],this.outputShape=r.outShape;var a=r.padInfo.top,o=r.padInfo.left,i=r.strideHeight,s=r.strideWidth,u=r.dilationHeight,c=r.dilationWidth,d=r.filterHeight,f=r.filterWidth,m=4*Math.floor(r.inChannels/4),g=r.inChannels%4,x=r.dataFormat==="channelsLast",E=x?1:2,w=x?2:3,C=x?3:1,N="",S="";e&&(N=t?`float activation(float a) {
|
|
float b = getPreluActivationWeightsAtOutCoords();
|
|
`+e+`
|
|
}`:`
|
|
float activation(float x) {
|
|
`+e+`
|
|
}
|
|
`,S="result = activation(result);");var I=n?"result += getBiasAtOutCoords();":"";n&&this.variableNames.push("bias"),t&&this.variableNames.push("preluActivationWeights"),this.userCode=`
|
|
`+N+`
|
|
|
|
const ivec2 strides = ivec2(`+i+", "+s+`);
|
|
const ivec2 pads = ivec2(`+a+", "+o+`);
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d2 = coords[`+C+`];
|
|
|
|
ivec2 xRCCorner =
|
|
ivec2(coords[`+E+"], coords["+w+`]) * strides - pads;
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
// Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wR = 0; wR < `+d+`; wR++) {
|
|
int xR = xRCorner + wR * `+u+`;
|
|
|
|
if (xR < 0 || xR >= `+r.inHeight+`) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < `+f+`; wC++) {
|
|
int xC = xCCorner + wC * `+c+`;
|
|
|
|
if (xC < 0 || xC >= `+r.inWidth+`) {
|
|
continue;
|
|
}
|
|
|
|
for (int d1 = 0; d1 < `+m+`; d1 += 4) {
|
|
vec4 wValues = vec4(
|
|
getW(wR, wC, d1, d2),
|
|
getW(wR, wC, d1 + 1, d2),
|
|
getW(wR, wC, d1 + 2, d2),
|
|
getW(wR, wC, d1 + 3, d2)
|
|
);
|
|
|
|
if (`+x+`) {
|
|
vec4 xValues = vec4(
|
|
getX(batch, xR, xC, d1),
|
|
getX(batch, xR, xC, d1 + 1),
|
|
getX(batch, xR, xC, d1 + 2),
|
|
getX(batch, xR, xC, d1 + 3)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else {
|
|
vec4 xValues = vec4(
|
|
getX(batch, d1, xR, xC),
|
|
getX(batch, d1 + 1, xR, xC),
|
|
getX(batch, d1 + 2, xR, xC),
|
|
getX(batch, d1 + 3, xR, xC)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
}
|
|
|
|
if (`+(g===1)+`) {
|
|
|
|
if (`+x+`) {
|
|
dotProd +=
|
|
getX(batch, xR, xC, `+m+`) *
|
|
getW(wR, wC, `+m+`, d2);
|
|
} else {
|
|
dotProd +=
|
|
getX(batch, `+m+`, xR, xC) *
|
|
getW(wR, wC, `+m+`, d2);
|
|
}
|
|
|
|
} else if (`+(g===2)+`) {
|
|
vec2 wValues = vec2(
|
|
getW(wR, wC, `+m+`, d2),
|
|
getW(wR, wC, `+m+` + 1, d2)
|
|
);
|
|
|
|
if (`+x+`) {
|
|
vec2 xValues = vec2(
|
|
getX(batch, xR, xC, `+m+`),
|
|
getX(batch, xR, xC, `+m+` + 1)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else {
|
|
vec2 xValues = vec2(
|
|
getX(batch, `+m+`, xR, xC),
|
|
getX(batch, `+m+` + 1, xR, xC)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
|
|
} else if (`+(g===3)+`) {
|
|
vec3 wValues = vec3(
|
|
getW(wR, wC, `+m+`, d2),
|
|
getW(wR, wC, `+m+` + 1, d2),
|
|
getW(wR, wC, `+m+` + 2, d2)
|
|
);
|
|
|
|
if (`+x+`) {
|
|
vec3 xValues = vec3(
|
|
getX(batch, xR, xC, `+m+`),
|
|
getX(batch, xR, xC, `+m+` + 1),
|
|
getX(batch, xR, xC, `+m+` + 2)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else {
|
|
vec3 xValues = vec3(
|
|
getX(batch, `+m+`, xR, xC),
|
|
getX(batch, `+m+` + 1, xR, xC),
|
|
getX(batch, `+m+` + 2, xR, xC)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
|
|
float result = dotProd;
|
|
`+I+`
|
|
`+S+`
|
|
setOutput(result);
|
|
}
|
|
`},bt=function(r){this.variableNames=["x","W"],this.outputShape=r.outShape;var n=r.padInfo.front,e=r.padInfo.top,t=r.padInfo.left,a=r.strideDepth,o=r.strideHeight,i=r.strideWidth,s=r.dilationDepth,u=r.dilationHeight,c=r.dilationWidth,d=r.filterDepth,f=r.filterHeight,m=r.filterWidth,g=4*Math.floor(r.inChannels/4),x=r.inChannels%4;this.userCode=`
|
|
const ivec3 strides = ivec3(`+a+", "+o+", "+i+`);
|
|
const ivec3 pads = ivec3(`+n+", "+e+", "+t+`);
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int d2 = coords.u;
|
|
|
|
ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
|
|
int xFCorner = xFRCCorner.x;
|
|
int xRCorner = xFRCCorner.y;
|
|
int xCCorner = xFRCCorner.z;
|
|
|
|
// Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
|
|
// y(yF, yR, yC, d2). ? = to be determined. : = across all
|
|
// values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wF = 0; wF < `+d+`; wF++) {
|
|
int xF = xFCorner + wF * `+s+`;
|
|
|
|
if (xF < 0 || xF >= `+r.inDepth+`) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < `+f+`; wR++) {
|
|
int xR = xRCorner + wR * `+u+`;
|
|
|
|
if (xR < 0 || xR >= `+r.inHeight+`) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < `+m+`; wC++) {
|
|
int xC = xCCorner + wC * `+c+`;
|
|
|
|
if (xC < 0 || xC >= `+r.inWidth+`) {
|
|
continue;
|
|
}
|
|
|
|
for (int d1 = 0; d1 < `+g+`; d1 += 4) {
|
|
vec4 xValues = vec4(
|
|
getX(batch, xF, xR, xC, d1),
|
|
getX(batch, xF, xR, xC, d1 + 1),
|
|
getX(batch, xF, xR, xC, d1 + 2),
|
|
getX(batch, xF, xR, xC, d1 + 3)
|
|
);
|
|
vec4 wValues = vec4(
|
|
getW(wF, wR, wC, d1, d2),
|
|
getW(wF, wR, wC, d1 + 1, d2),
|
|
getW(wF, wR, wC, d1 + 2, d2),
|
|
getW(wF, wR, wC, d1 + 3, d2)
|
|
);
|
|
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
|
|
if (`+(x===1)+`) {
|
|
dotProd +=
|
|
getX(batch, xF, xR, xC, `+g+`) *
|
|
getW(wF, wR, wC, `+g+`, d2);
|
|
} else if (`+(x===2)+`) {
|
|
vec2 xValues = vec2(
|
|
getX(batch, xF, xR, xC, `+g+`),
|
|
getX(batch, xF, xR, xC, `+g+` + 1)
|
|
);
|
|
vec2 wValues = vec2(
|
|
getW(wF, wR, wC, `+g+`, d2),
|
|
getW(wF, wR, wC, `+g+` + 1, d2)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else if (`+(x===3)+`) {
|
|
vec3 xValues = vec3(
|
|
getX(batch, xF, xR, xC, `+g+`),
|
|
getX(batch, xF, xR, xC, `+g+` + 1),
|
|
getX(batch, xF, xR, xC, `+g+` + 2)
|
|
);
|
|
vec3 wValues = vec3(
|
|
getW(wF, wR, wC, `+g+`, d2),
|
|
getW(wF, wR, wC, `+g+` + 1, d2),
|
|
getW(wF, wR, wC, `+g+` + 2, d2)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`},yt=function(r,n,e,t){n===void 0&&(n=!1),e===void 0&&(e=null),t===void 0&&(t=!1),this.variableNames=["x","W"],this.outputShape=r.outShape;var a=r.inHeight,o=r.inWidth,i=r.padInfo.top,s=r.padInfo.left,u=r.strideHeight,c=r.strideWidth,d=r.dilationHeight,f=r.dilationWidth,m=r.filterHeight,g=r.filterWidth,x=r.outChannels/r.inChannels,E="",w="";e&&(E=t?`float activation(float a) {
|
|
float b = getPreluActivationWeightsAtOutCoords();
|
|
`+e+`
|
|
}`:`
|
|
float activation(float x) {
|
|
`+e+`
|
|
}
|
|
`,w="result = activation(result);");var C=n?"result += getBiasAtOutCoords();":"";n&&this.variableNames.push("bias"),t&&this.variableNames.push("preluActivationWeights"),this.userCode=`
|
|
`+E+`
|
|
|
|
const ivec2 strides = ivec2(`+u+", "+c+`);
|
|
const ivec2 pads = ivec2(`+i+", "+s+`);
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
|
int d2 = coords.w;
|
|
int d1 = d2 / `+x+`;
|
|
int q = d2 - d1 * `+x+`;
|
|
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
// Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
// TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.
|
|
for (int wR = 0; wR < `+m+`; wR++) {
|
|
int xR = xRCorner + wR * `+d+`;
|
|
|
|
if (xR < 0 || xR >= `+a+`) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < `+g+`; wC++) {
|
|
int xC = xCCorner + wC * `+f+`;
|
|
|
|
if (xC < 0 || xC >= `+o+`) {
|
|
continue;
|
|
}
|
|
|
|
float xVal = getX(batch, xR, xC, d1);
|
|
float wVal = getW(wR, wC, d1, q);
|
|
dotProd += xVal * wVal;
|
|
}
|
|
}
|
|
|
|
float result = dotProd;
|
|
`+C+`
|
|
`+w+`
|
|
setOutput(result);
|
|
}
|
|
`},ft=function(r,n,e,t){n===void 0&&(n=!1),e===void 0&&(e=null),t===void 0&&(t=!1),this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=r.outShape;for(var a=r.inHeight,o=r.inWidth,i=r.padInfo.top,s=r.padInfo.left,u=r.strideHeight,c=r.strideWidth,d=r.dilationHeight,f=r.dilationWidth,m=r.filterHeight,g=r.filterWidth,x=g,E="int xR; int xC; int xCOffset;",w=0;w<m;w++)for(var C=0;C<g;C++)E+=`
|
|
vec4 xTexelR`+w+"C"+2*C+` = vec4(0.);
|
|
vec4 wR`+w+"C"+C+` = vec4(0.);
|
|
vec4 xR`+w+"C"+C+" = vec4(0.);";for(w=0;w<m;w++)for(var N=0;N<x;N++){if(E+=`
|
|
xR = xRCorner + `+w*d+`;
|
|
xC = xCCorner + `+(C=2*N)*f+`;
|
|
`,c===1){if(C<g&&(E+=s%2==1?`
|
|
xCOffset = xC + 1;
|
|
if(xR >= 0 && xR < `+a+" && xCOffset >= 0 && xCOffset < "+o+`) {
|
|
xTexelR`+w+"C"+C+` = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if(xCOffset + 1 >= `+o+`) {
|
|
xTexelR`+w+"C"+C+`.zw = vec2(0.);
|
|
}
|
|
} else {
|
|
xTexelR`+w+"C"+C+` = vec4(0.);
|
|
}
|
|
|
|
xCOffset = xC + 1 - 2;
|
|
if(xR >= 0 && xR < `+a+" && xCOffset >= 0 && xCOffset < "+o+`) {
|
|
vec4 previous = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if(xCOffset + 1 >= `+o+`) {
|
|
previous.zw = vec2(0.);
|
|
}
|
|
|
|
xR`+w+"C"+C+" = vec4(previous.zw, xTexelR"+w+"C"+C+`.xy);
|
|
} else {
|
|
xR`+w+"C"+C+" = vec4(0, 0, xTexelR"+w+"C"+C+`.xy);
|
|
}
|
|
`:`
|
|
if(xR >= 0 && xR < `+a+" && xC >= 0 && xC < "+o+`) {
|
|
xTexelR`+w+"C"+C+` = getX(batch, xR, xC, d1);
|
|
} else {
|
|
xTexelR`+w+"C"+C+` = vec4(0.);
|
|
}
|
|
|
|
xR`+w+"C"+C+" = xTexelR"+w+"C"+C+`;
|
|
`,C+1<g)){var S=s%2==0?Ye(f):f;f%2==0&&s%2==1||f%2!=0&&s%2!=1?(E+=`
|
|
xCOffset = xC + `+s%2+" + "+S+`;
|
|
|
|
if(xR >= 0 && xR < `+a+` &&
|
|
xCOffset >= 0 && xCOffset < `+o+`) {
|
|
xTexelR`+w+"C"+(C+2)+` = getX(batch, xR, xCOffset, d1);
|
|
}
|
|
`,f>1&&(E+=`
|
|
xCOffset -= 2;
|
|
if(xR >= 0 && xR < `+a+` &&
|
|
xCOffset >= 0 && xCOffset < `+o+`) {
|
|
xTexelR`+w+"C"+C+` = getX(batch, xR, xCOffset, d1);
|
|
} else {
|
|
xTexelR`+w+"C"+C+` = vec4(0.);
|
|
}
|
|
`),E+=`
|
|
xR`+w+"C"+(C+1)+` = vec4(
|
|
xTexelR`+w+"C"+C+".zw, xTexelR"+w+"C"+(C+2)+`.xy);
|
|
`):E+=`
|
|
xCOffset = xC + `+S+`;
|
|
|
|
if(xR >= 0 && xR < `+a+` &&
|
|
xCOffset >= 0 && xCOffset < `+o+`) {
|
|
xTexelR`+w+"C"+(C+2)+` = getX(batch, xR, xCOffset, d1);
|
|
}
|
|
|
|
xR`+w+"C"+(C+1)+" = xTexelR"+w+"C"+(C+2)+`;
|
|
`}}else C<g&&(E+=`
|
|
if(xR >= 0 && xR < `+a+`) {
|
|
`,s%2==1?(E+=`
|
|
xCOffset = xC + 1 - `+c+`;
|
|
if(xCOffset >= 0 && xCOffset < `+o+`) {
|
|
xTexelR`+w+"C"+C+` = getX(batch, xR, xCOffset, d1);
|
|
} else {
|
|
xTexelR`+w+"C"+C+` = vec4(0.);
|
|
}
|
|
|
|
if(xC + 1 >= 0 && xC + 1 < `+o+`) {
|
|
xTexelR`+w+"C"+(C+2)+` = getX(batch, xR, xC + 1, d1);
|
|
} else {
|
|
xTexelR`+w+"C"+(C+2)+` = vec4(0.);
|
|
}
|
|
|
|
xR`+w+"C"+C+` = vec4(
|
|
xTexelR`+w+"C"+C+".zw, xTexelR"+w+"C"+(C+2)+`.zw);
|
|
`,C+1<g&&(E+=`
|
|
vec4 final = vec4(0.);
|
|
xCOffset = xC + 1 + `+c+`;
|
|
if(xCOffset >= 0 && xCOffset < `+o+`) {
|
|
final = getX(batch, xR, xCOffset, d1);
|
|
}
|
|
xR`+w+"C"+(C+1)+" = vec4(xTexelR"+w+"C"+(C+2)+`.xy, final.xy);
|
|
`)):(E+=`
|
|
if(xC >= 0 && xC < `+o+`) {
|
|
xTexelR`+w+"C"+C+` = getX(batch, xR, xC, d1);
|
|
} else {
|
|
xTexelR`+w+"C"+C+` = vec4(0.);
|
|
}
|
|
|
|
xCOffset = xC + `+c+`;
|
|
if(xCOffset >= 0 && xCOffset < `+o+`) {
|
|
xTexelR`+w+"C"+(C+2)+` = getX(batch, xR, xCOffset, d1);
|
|
} else {
|
|
xTexelR`+w+"C"+(C+2)+` = vec4(0.);
|
|
}
|
|
|
|
xR`+w+"C"+C+` = vec4(
|
|
xTexelR`+w+"C"+C+".xy, xTexelR"+w+"C"+(C+2)+`.xy);
|
|
`,C+1<g&&(E+=`
|
|
xR`+w+"C"+(C+1)+` = vec4(
|
|
xTexelR`+w+"C"+C+".zw, xTexelR"+w+"C"+(C+2)+`.zw);
|
|
`)),E+="}");C<g&&(E+=`
|
|
vec4 wTexelR`+w+"C"+C+" = getW("+w+", "+C+`, d1, q);
|
|
wR`+w+"C"+C+" = vec4(wTexelR"+w+"C"+C+".xz, wTexelR"+w+"C"+C+`.xz);
|
|
`,C+1<g&&(E+=`
|
|
vec4 wTexelR`+w+"C"+(C+1)+" = getW("+w+", "+(C+1)+`, d1, q);
|
|
wR`+w+"C"+(C+1)+` =
|
|
vec4(wTexelR`+w+"C"+(C+1)+".xz, wTexelR"+w+"C"+(C+1)+".xz);"))}for(w=0;w<m;w++)for(C=0;C<g;C++)E+="dotProd += xR"+w+"C"+C+" * wR"+w+"C"+C+";";var I="",M="";e&&(I=t?`vec4 activation(vec4 a) {
|
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
|
`+e+`
|
|
}`:`vec4 activation(vec4 x) {
|
|
`+e+`
|
|
}`,M="result = activation(result);");var j=n?"result += getBiasAtOutCoords();":"";n&&this.variableNames.push("bias"),t&&this.variableNames.push("preluActivationWeights"),this.userCode=`
|
|
`+I+`
|
|
|
|
const ivec2 strides = ivec2(`+u+", "+c+`);
|
|
const ivec2 pads = ivec2(`+i+", "+s+`);
|
|
|
|
void main() {
|
|
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
|
int d2 = coords.w;
|
|
int d1 = d2;
|
|
int q = 0;
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
vec4 dotProd = vec4(0.);
|
|
|
|
`+E+`
|
|
|
|
vec4 result = dotProd;
|
|
`+j+`
|
|
`+M+`
|
|
setOutput(result);
|
|
}
|
|
`},Lt=function(r,n,e,t,a){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];var o=r[0],i=r[1],s=r[2],u=r[3],c=n[0],d=e[0],f=e[1];this.outputShape=[c,d,f,u];var m=t==="bilinear"?1:0,g=[i-1+".0",s-1+".0"],x=g[0],E=g[1],w=d>1?[""+(i-1)/(d-1),"(y2-y1) * height_ratio","y1*"+x+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+x],C=w[0],N=w[1],S=w[2],I=f>1?[""+(s-1)/(f-1),"(x2-x1) * width_ratio","x1*"+E+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+E],M=I[0],j=I[1],G=I[2];this.userCode=`
|
|
const float height_ratio = float(`+C+`);
|
|
const float width_ratio = float(`+M+`);
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int y = coords[1];
|
|
int x = coords[2];
|
|
int d = coords[3];
|
|
|
|
// get box vals
|
|
float y1 = getBoxes(b,0);
|
|
float x1 = getBoxes(b,1);
|
|
float y2 = getBoxes(b,2);
|
|
float x2 = getBoxes(b,3);
|
|
|
|
// get image in batch index
|
|
int bInd = round(getBoxInd(b));
|
|
if(bInd < 0 || bInd >= `+o+`) {
|
|
return;
|
|
}
|
|
|
|
float height_scale = `+N+`;
|
|
float width_scale = `+j+`;
|
|
|
|
float in_y = `+S+`;
|
|
if( in_y < 0.0 || in_y > `+x+` ) {
|
|
setOutput(float(`+a+`));
|
|
return;
|
|
}
|
|
float in_x = `+G+`;
|
|
if( in_x < 0.0 || in_x > `+E+` ) {
|
|
setOutput(float(`+a+`));
|
|
return;
|
|
}
|
|
|
|
vec2 sourceFracIndexCR = vec2(in_x,in_y);
|
|
if(`+m+` == 1) {
|
|
// Compute the four integer indices.
|
|
ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);
|
|
ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));
|
|
|
|
float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);
|
|
float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);
|
|
float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);
|
|
float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);
|
|
|
|
vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);
|
|
|
|
float top = topLeft + (topRight - topLeft) * fracCR.x;
|
|
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
|
|
float newValue = top + (bottom - top) * fracCR.y;
|
|
setOutput(newValue);
|
|
} else {
|
|
// Compute the coordinators of nearest neighbor point.
|
|
ivec2 sourceNearestCR = ivec2(floor(
|
|
sourceFracIndexCR + vec2(0.5,0.5)));
|
|
float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);
|
|
setOutput(newValue);
|
|
}
|
|
}
|
|
`},wt=function(r,n,e){this.variableNames=["x"],this.outputShape=r;var t=r.length,a=r[r.length-1],o=e?"<":">";this.userCode=`
|
|
int getIndex(int i) {
|
|
`+(e?"return "+a+" -i - 1;":"return i;")+`
|
|
}
|
|
|
|
void main() {
|
|
`+le(t)+` coords = getOutputCoords();
|
|
int end = `+Tt(t,"coords")+`;
|
|
float val = 0.0;
|
|
for (int i = `+a+` - 1; i >= 0; i -= 1) {
|
|
int idx = getIndex(i);
|
|
if (idx `+o+` end) {
|
|
continue;
|
|
}
|
|
if (idx == end && `+n+`) {
|
|
continue;
|
|
}
|
|
`+Tt(t,"coords")+` = idx;
|
|
val += getX(`+function(i,s){if(i===1)return""+s;if(i===2)return s+".x, "+s+".y";if(i===3)return s+".x, "+s+".y, "+s+".z";if(i===4)return s+".x, "+s+".y, "+s+".z, "+s+".w";throw Error("Cumulative sum for rank "+i+" is not yet supported")}(t,"coords")+`);
|
|
}
|
|
setOutput(val);
|
|
}
|
|
`};function Tt(r,n){if(r===1)return""+n;if(r===2)return n+".y";if(r===3)return n+".z";if(r===4)return n+".w";throw Error("Cumulative sum for rank "+r+" is not yet supported")}var Gt=function(r){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=Ea.DENSE;var n=Zt(r),e=h();this.outputShape=r,this.userCode=`
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
`+v(["r","c","d"],r)+`
|
|
return ivec3(r, c, d);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(`+n[0]+", "+n[1]+`));
|
|
int index = 4 * (resTexRC.x * `+n[1]+` + resTexRC.y);
|
|
|
|
vec4 result = vec4(0.);
|
|
|
|
for (int i=0; i<4; i++) {
|
|
int flatIndex = index + i;
|
|
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
|
|
result[i] = getA(rc.x, rc.y, rc.z);
|
|
}
|
|
|
|
`+e.output+` = result;
|
|
}
|
|
`},Gr=function(r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=Ea.DENSE;var n=Zt(r),e=h();this.outputShape=r,this.userCode=`
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
`+v(["r","c","d"],r)+`
|
|
return ivec3(r, c, d);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(`+n[0]+", "+n[1]+`));
|
|
int index = 4 * (resTexRC.x * `+n[1]+` + resTexRC.y);
|
|
|
|
vec4 result = vec4(0.);
|
|
|
|
for (int i=0; i<4; i++) {
|
|
int flatIndex = index + i;
|
|
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
|
|
result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));
|
|
}
|
|
|
|
`+e.output+` = result;
|
|
}
|
|
`},Sr=function(){function r(n,e,t){this.variableNames=["x"],this.outputShape=[],this.outputShape=n,this.blockSize=e,this.dataFormat=t,this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int h = `+this.getHeightCoordString()+`;
|
|
int w = `+this.getWidthCoordString()+`;
|
|
int d = `+this.getDepthCoordString()+`;
|
|
|
|
int in_h = h / `+e+`;
|
|
int offset_h = imod(h, `+e+`);
|
|
int in_w = w / `+e+`;
|
|
int offset_w = imod(w, `+e+`);
|
|
int offset_d = (offset_h * `+e+` + offset_w) *
|
|
`+this.getOutputDepthSize()+`;
|
|
int in_d = d + offset_d;
|
|
|
|
float result = `+this.getInputSamplingString()+`;
|
|
setOutput(result);
|
|
}
|
|
`}return r.prototype.getHeightCoordString=function(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"},r.prototype.getWidthCoordString=function(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"},r.prototype.getDepthCoordString=function(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"},r.prototype.getOutputDepthSize=function(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]},r.prototype.getInputSamplingString=function(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"},r}(),fa=function(r){this.variableNames=["X"],this.outputShape=[r,r],this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;
|
|
setOutput(val);
|
|
}
|
|
`},un=function(r){this.variableNames=["A"],this.outTexUsage=An.DOWNLOAD;var n=h();this.outputShape=r,this.userCode=`
|
|
`+b+`
|
|
|
|
void main() {
|
|
float x = getAAtOutCoords();
|
|
`+n.output+` = encode_float(x);
|
|
}
|
|
`},$s=function(r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=An.DOWNLOAD;var n=h();this.outputShape=r,this.userCode=`
|
|
`+b+`
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
|
|
`+n.output+` = encode_float(x);
|
|
}
|
|
`},ii=function(r,n,e){e===void 0&&(e=!1),this.variableNames=["A"];var t=h(),a=n[0],o=n[1];this.outputShape=r;var i="result";e&&(i="floor(result * 255. + 0.5)"),this.userCode=`
|
|
`+y(r)+`
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
|
|
int flatIndex = getFlatIndex(coords);
|
|
int offset = imod(flatIndex, 4);
|
|
|
|
flatIndex = idiv(flatIndex, 4, 1.);
|
|
|
|
int r = flatIndex / `+o+`;
|
|
int c = imod(flatIndex, `+o+`);
|
|
vec2 uv = (vec2(c, r) + halfCR) / vec2(`+o+".0, "+a+`.0);
|
|
vec4 values = `+t.texture2D+`(A, uv);
|
|
|
|
float result;
|
|
|
|
if(offset == 0) {
|
|
result = values[0];
|
|
} else if(offset == 1) {
|
|
result = values[1];
|
|
} else if(offset == 2) {
|
|
result = values[2];
|
|
} else {
|
|
result = values[3];
|
|
}
|
|
|
|
`+t.output+" = vec4("+i+`, 0., 0., 0.);
|
|
}
|
|
`},si=function(r,n,e){e===void 0&&(e=!1),this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var t=h(),a=n[0],o=n[1];this.outputShape=r;var i="",s="result";e&&(s="floor(result * 255. + 0.5)");for(var u=0;u<=1;u++)for(var c=0;c<=1;c++){var d=2*u+c;i+=`
|
|
localCoords = coords;
|
|
if(localCoords[2] + `+c+" < "+r[2]+`) {
|
|
localCoords[2] += `+c+`;
|
|
if(localCoords[1] + `+u+" < "+r[1]+`) {
|
|
localCoords[1] += `+u+`;
|
|
|
|
flatIndex = getFlatIndex(localCoords);
|
|
offset = imod(flatIndex, 4);
|
|
|
|
flatIndex = idiv(flatIndex, 4, 1.);
|
|
|
|
r = flatIndex / `+o+`;
|
|
c = imod(flatIndex, `+o+`);
|
|
uv = (vec2(c, r) + halfCR) / vec2(`+o+".0, "+a+`.0);
|
|
values = `+t.texture2D+`(A, uv);
|
|
|
|
if(offset == 0) {
|
|
result[`+d+`] = values[0];
|
|
} else if(offset == 1) {
|
|
result[`+d+`] = values[1];
|
|
} else if(offset == 2) {
|
|
result[`+d+`] = values[2];
|
|
} else {
|
|
result[`+d+`] = values[3];
|
|
}
|
|
}
|
|
}
|
|
`}this.userCode=`
|
|
`+y(r)+`
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
|
|
vec4 result = vec4(0.);
|
|
int flatIndex, r, c, offset;
|
|
ivec3 localCoords;
|
|
vec2 uv;
|
|
vec4 values;
|
|
|
|
`+i+`
|
|
|
|
`+t.output+" = "+s+`;
|
|
}
|
|
`},$i="return real * expR - imag * expI;",od="return real * expI + imag * expR;",rc=function(r,n,e){this.variableNames=["real","imag"];var t=n[1];this.outputShape=n;var a=e?"2.0 * "+Math.PI:"-2.0 * "+Math.PI,o=e?t+".0":"1.0";this.userCode=`
|
|
const float exponentMultiplier = `+a+`;
|
|
|
|
float unaryOpComplex(float real, float expR, float imag, float expI) {
|
|
`+r+`
|
|
}
|
|
|
|
float mulMatDFT(int batch, int index) {
|
|
float indexRatio = float(index) / float(`+t+`);
|
|
float exponentMultiplierTimesIndexRatio =
|
|
exponentMultiplier * indexRatio;
|
|
|
|
float result = 0.0;
|
|
|
|
for (int i = 0; i < `+t+`; i++) {
|
|
// x = (-2|2 * PI / N) * index * i;
|
|
float x = exponentMultiplierTimesIndexRatio * float(i);
|
|
float expR = cos(x);
|
|
float expI = sin(x);
|
|
float real = getReal(batch, i);
|
|
float imag = getImag(batch, i);
|
|
|
|
result +=
|
|
unaryOpComplex(real, expR, imag, expI) / `+o+`;
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
setOutput(mulMatDFT(coords[0], coords[1]));
|
|
}
|
|
`},id=function(){function r(n,e){this.outputShape=[],this.variableNames=["x"],this.outputShape=n,this.userCode=`
|
|
uniform float value;
|
|
void main() {
|
|
// Input can be obtained from uniform value.
|
|
setOutput(value);
|
|
}
|
|
`}return r.prototype.getCustomSetupFunc=function(n){var e=this;return function(t,a){e.valueLoc==null&&(e.valueLoc=t.getUniformLocationNoThrow(a,"value")),t.gl.uniform1f(e.valueLoc,n)}},r}(),sd=function(r,n,e){this.variableNames=["A","indices"];var t=r.slice();t[e]=n,this.outputShape=t,this.rank=t.length;var a=le(this.rank),o=function(i,s){var u=i.length;if(u>4)throw Error("Gather for rank "+u+" is not yet supported");if(u===1)return"int(getIndices(resRC))";for(var c=["resRC.x","resRC.y","resRC.z","resRC.w"],d=[],f=0;f<i.length;f++)f===s?d.push("int(getIndices("+c[f]+"))"):d.push(""+c[f]);return d.join()}(r,e);this.userCode=`
|
|
void main() {
|
|
`+a+` resRC = getOutputCoords();
|
|
setOutput(getA(`+o+`));
|
|
}
|
|
`},ud=function(r,n,e){this.sliceDim=r,this.strides=n,this.variableNames=["x","indices"],this.outputShape=e;var t=le(n.length),a=le(e.length),o=this.sliceDim>1?"strides[j]":"strides";this.userCode=`
|
|
`+t+" strides = "+t+"("+this.strides+`);
|
|
void main() {
|
|
`+a+` coords = getOutputCoords();
|
|
int flattenIndex = 0;
|
|
for (int j = 0; j < `+this.sliceDim+`; j++) {
|
|
int index = round(getIndices(coords[0], j));
|
|
flattenIndex += index * `+o+`;
|
|
}
|
|
setOutput(getX(flattenIndex, coords[1]));
|
|
}
|
|
`};function ac(r,n){var e=h();return hs(r,n,e.version+`
|
|
precision highp float;
|
|
`+e.attribute+` vec3 clipSpacePos;
|
|
`+e.attribute+` vec2 uv;
|
|
`+e.varyingVs+` vec2 resultUV;
|
|
|
|
void main() {
|
|
gl_Position = vec4(clipSpacePos, 1);
|
|
resultUV = uv;
|
|
}`)}function oc(r,n){return Xa(r,n,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function ic(r,n){return Uo(r,n,new Uint16Array([0,1,2,2,1,3]))}function ui(r,n,e,t,a,o,i){qa(e,t);var s=Ka(r,n),u=r.TEXTURE_2D;return Me(r,n,function(){return r.bindTexture(u,s)}),Me(r,n,function(){return r.texParameteri(u,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE)}),Me(r,n,function(){return r.texParameteri(u,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE)}),Me(r,n,function(){return r.texParameteri(u,r.TEXTURE_MIN_FILTER,r.NEAREST)}),Me(r,n,function(){return r.texParameteri(u,r.TEXTURE_MAG_FILTER,r.NEAREST)}),Me(r,n,function(){return r.texImage2D(u,0,a,e,t,0,o,i,null)}),Me(r,n,function(){return r.bindTexture(r.TEXTURE_2D,null)}),s}function sc(r,n,e,t,a){var o=Pr(e,t);return ui(r,n,o[0],o[1],a.internalFormatFloat,a.textureFormatFloat,r.FLOAT)}function uc(r,n,e,t,a){var o=Pr(e,t);return ui(r,n,o[0],o[1],a.internalFormatHalfFloat,a.textureFormatFloat,a.textureTypeHalfFloat)}function cc(r,n,e,t,a){var o=Pr(e,t);return ui(r,n,o[0],o[1],r.RGBA,r.RGBA,r.UNSIGNED_BYTE)}function lc(r,n,e,t,a){var o=Lr(e,t);return ui(r,n,o[0],o[1],a.internalFormatPackedFloat,r.RGBA,r.FLOAT)}function dc(r,n,e,t,a){var o=Lr(e,t);return ui(r,n,o[0],o[1],a.internalFormatPackedHalfFloat,r.RGBA,a.textureTypeHalfFloat)}function hc(r,n,e,t){return Me(r,n,function(){return r.bindBuffer(r.ARRAY_BUFFER,t)}),Yn(r,n,e,"clipSpacePos",t,3,20,0)&&Yn(r,n,e,"uv",t,2,20,12)}function pc(r,n,e,t,a,o,i){var s,u,c;Me(r,n,function(){return r.bindTexture(r.TEXTURE_2D,e)}),o instanceof Uint8Array?(s=new Uint8Array(t*a*4),u=r.UNSIGNED_BYTE,c=r.RGBA):(s=new Float32Array(t*a*4),u=r.FLOAT,c=i.internalFormatPackedFloat),s.set(o),Me(r,n,function(){return r.texImage2D(r.TEXTURE_2D,0,c,t,a,0,r.RGBA,u,s)}),Me(r,n,function(){return r.bindTexture(r.TEXTURE_2D,null)})}function fc(r,n,e,t){Me(r,n,function(){return r.bindTexture(r.TEXTURE_2D,e)}),t.data instanceof Uint8Array?Me(r,n,function(){return r.texImage2D(r.TEXTURE_2D,0,r.RGBA,t.width,t.height,0,r.RGBA,r.UNSIGNED_BYTE,t.data)}):Me(r,n,function(){return r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,t)}),Me(r,n,function(){return r.bindTexture(r.TEXTURE_2D,null)})}function vc(r,n,e,t,a){var o=r.createBuffer();Me(r,n,function(){return r.bindBuffer(r.PIXEL_PACK_BUFFER,o)});var i=16*e*t;return Me(r,n,function(){return r.bufferData(r.PIXEL_PACK_BUFFER,i,r.STREAM_READ)}),Me(r,n,function(){return r.readPixels(0,0,t,e,r.RGBA,r.FLOAT,0)}),Me(r,n,function(){return r.bindBuffer(r.PIXEL_PACK_BUFFER,null)}),o}function mc(r,n,e){var t=r,a=new Float32Array(e);return t.bindBuffer(t.PIXEL_PACK_BUFFER,n),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),a}function gc(r,n,e,t,a){var o=Pr(e,t),i=o[0],s=o[1],u=new Uint8Array(e*t*4);return Me(r,n,function(){return r.readPixels(0,0,i,s,a.downloadTextureFormat,r.UNSIGNED_BYTE,u)}),new Float32Array(u.buffer)}function yc(r,n,e,t,a,o,i,s){var u=r,c=new Float32Array(function(d,f){var m=Lr(d,f);return m[0]*m[1]*4}(o,i));return u.bindBuffer(u.PIXEL_PACK_BUFFER,n),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,c),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),c}function xc(r,n,e,t){var a=new Float32Array(e*t*4);return Me(r,n,function(){return r.readPixels(0,0,t,e,r.RGBA,r.FLOAT,a)}),a}var cd=Object.freeze({createVertexShader:ac,createVertexBuffer:oc,createIndexBuffer:ic,createFloat32MatrixTexture:sc,createFloat16MatrixTexture:uc,createUnsignedBytesMatrixTexture:cc,createPackedMatrixTexture:lc,createFloat16PackedMatrixTexture:dc,bindVertexProgramAttributeStreams:hc,uploadDenseMatrixToTexture:pc,uploadPixelDataToTexture:fc,createBufferFromOutputTexture:vc,downloadFloat32MatrixFromBuffer:mc,downloadByteEncodedFloatMatrixFromOutputTexture:gc,downloadPackedMatrixFromBuffer:yc,downloadMatrixFromPackedOutputTexture:xc}),bc=function(){function r(n){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];var e=ee().getNumber("WEBGL_VERSION");n!=null?(this.gl=n,Bo(e,n)):this.gl=or(e);var t="WEBGL_color_buffer_float";if(ee().getNumber("WEBGL_VERSION")===1){if(this.textureFloatExtension=Ca(this.gl,this.debug,"OES_texture_float"),Fn(this.gl,"OES_texture_half_float"))this.textureHalfFloatExtension=Ca(this.gl,this.debug,"OES_texture_half_float");else if(ee().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.");if(this.colorBufferFloatExtension=this.gl.getExtension(t),Fn(this.gl,"EXT_color_buffer_half_float"))this.colorBufferHalfFloatExtension=Ca(this.gl,this.debug,"EXT_color_buffer_half_float");else if(ee().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 if(t="EXT_color_buffer_float",Fn(this.gl,t))this.colorBufferFloatExtension=this.gl.getExtension(t);else{if(!Fn(this.gl,"EXT_color_buffer_half_float"))throw new Error("GL context does not support color renderable floats");this.colorBufferHalfFloatExtension=this.gl.getExtension("EXT_color_buffer_half_float")}this.vertexBuffer=oc(this.gl,this.debug),this.indexBuffer=ic(this.gl,this.debug),this.framebuffer=vr(this.gl,this.debug),this.textureConfig=_a(this.gl,this.textureHalfFloatExtension)}return Object.defineProperty(r.prototype,"debug",{get:function(){return ee().getBool("DEBUG")},enumerable:!0,configurable:!0}),r.prototype.dispose=function(){var n=this;if(!this.disposed){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."),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 e=this.gl;Me(e,this.debug,function(){return e.finish()}),Me(e,this.debug,function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)}),Me(e,this.debug,function(){return e.deleteFramebuffer(n.framebuffer)}),Me(e,this.debug,function(){return e.bindBuffer(e.ARRAY_BUFFER,null)}),Me(e,this.debug,function(){return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)}),Me(e,this.debug,function(){return e.deleteBuffer(n.indexBuffer)}),this.disposed=!0}},r.prototype.createFloat32MatrixTexture=function(n,e){return this.throwIfDisposed(),sc(this.gl,this.debug,n,e,this.textureConfig)},r.prototype.createFloat16MatrixTexture=function(n,e){return this.throwIfDisposed(),uc(this.gl,this.debug,n,e,this.textureConfig)},r.prototype.createUnsignedBytesMatrixTexture=function(n,e){return this.throwIfDisposed(),cc(this.gl,this.debug,n,e,this.textureConfig)},r.prototype.uploadPixelDataToTexture=function(n,e){this.throwIfDisposed(),fc(this.gl,this.debug,n,e)},r.prototype.uploadDenseMatrixToTexture=function(n,e,t,a){this.throwIfDisposed(),pc(this.gl,this.debug,n,e,t,a,this.textureConfig)},r.prototype.createFloat16PackedMatrixTexture=function(n,e){return this.throwIfDisposed(),dc(this.gl,this.debug,n,e,this.textureConfig)},r.prototype.createPackedMatrixTexture=function(n,e){return this.throwIfDisposed(),lc(this.gl,this.debug,n,e,this.textureConfig)},r.prototype.deleteMatrixTexture=function(n){var e=this;this.throwIfDisposed(),this.outputTexture===n&&($a(this.gl,this.debug,this.framebuffer),this.outputTexture=null),Me(this.gl,this.debug,function(){return e.gl.deleteTexture(n)})},r.prototype.downloadByteEncodedFloatMatrixFromOutputTexture=function(n,e,t){var a=this;return this.downloadMatrixDriver(n,function(){return gc(a.gl,a.debug,e,t,a.textureConfig)})},r.prototype.downloadPackedMatrixFromBuffer=function(n,e,t,a,o,i){return yc(this.gl,n,0,0,0,o,i,this.textureConfig)},r.prototype.downloadFloat32MatrixFromBuffer=function(n,e){return mc(this.gl,n,e)},r.prototype.createBufferFromTexture=function(n,e,t){this.bindTextureToFrameBuffer(n);var a=vc(this.gl,this.debug,e,t,this.textureConfig);return this.unbindTextureToFrameBuffer(),a},r.prototype.createAndWaitForFence=function(){var n=this.createFence(this.gl);return this.pollFence(n)},r.prototype.createFence=function(n){var e,t,a=this;if(ee().getBool("WEBGL_FENCE_API_ENABLED")){var o=n,i=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);n.flush(),t=function(){var s=o.clientWaitSync(i,0,0);return s===o.ALREADY_SIGNALED||s===o.CONDITION_SATISFIED},e=i}else ee().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(e=this.beginQuery(),this.endQuery(),t=function(){return a.isQueryAvailable(e,ee().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}):t=function(){return!0};return{query:e,isFencePassed:t}},r.prototype.downloadMatrixFromPackedTexture=function(n,e,t){var a=this;return this.downloadMatrixDriver(n,function(){return xc(a.gl,a.debug,e,t)})},r.prototype.createProgram=function(n){this.throwIfDisposed();var e=this.gl,t=ir(e,this.debug,n),a=ac(e,this.debug),o=Vn(e,this.debug);return Me(e,this.debug,function(){return e.attachShader(o,a)}),Me(e,this.debug,function(){return e.attachShader(o,t)}),sr(e,this.debug,o),this.debug&&Br(e,this.debug,o),this.vertexAttrsAreBound||(this.setProgram(o),this.vertexAttrsAreBound=hc(e,this.debug,this.program,this.vertexBuffer)),o},r.prototype.deleteProgram=function(n){var e=this;this.throwIfDisposed(),n===this.program&&(this.program=null),n!=null&&Me(this.gl,this.debug,function(){return e.gl.deleteProgram(n)})},r.prototype.setProgram=function(n){var e=this;this.throwIfDisposed(),this.program=n,this.program!=null&&this.debug&&Br(this.gl,this.debug,this.program),Me(this.gl,this.debug,function(){return e.gl.useProgram(n)})},r.prototype.getUniformLocation=function(n,e,t){return t===void 0&&(t=!0),this.throwIfDisposed(),t?gi(this.gl,this.debug,n,e):zo(this.gl,n,e)},r.prototype.getAttributeLocation=function(n,e){var t=this;return this.throwIfDisposed(),Me(this.gl,this.debug,function(){return t.gl.getAttribLocation(n,e)})},r.prototype.getUniformLocationNoThrow=function(n,e){return this.throwIfDisposed(),this.gl.getUniformLocation(n,e)},r.prototype.setInputMatrixTexture=function(n,e,t){this.throwIfDisposed(),this.throwIfNoProgram(),Vo(this.gl,this.debug,this.program,n,e,t)},r.prototype.setOutputMatrixTexture=function(n,e,t){this.setOutputMatrixTextureDriver(n,t,e)},r.prototype.setOutputPackedMatrixTexture=function(n,e,t){this.throwIfDisposed();var a=Lr(e,t),o=a[0],i=a[1];this.setOutputMatrixTextureDriver(n,o,i)},r.prototype.setOutputMatrixWriteRegion=function(n,e,t,a){this.setOutputMatrixWriteRegionDriver(t,n,a,e)},r.prototype.setOutputPackedMatrixWriteRegion=function(n,e,t,a){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")},r.prototype.debugValidate=function(){this.program!=null&&Br(this.gl,this.debug,this.program),Mn(this.gl)},r.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var n=this.gl;this.debug&&this.debugValidate(),Me(n,this.debug,function(){return n.drawElements(n.TRIANGLES,6,n.UNSIGNED_SHORT,0)})},r.prototype.blockUntilAllProgramsCompleted=function(){var n=this;this.throwIfDisposed(),Me(this.gl,this.debug,function(){return n.gl.finish()})},r.prototype.getQueryTimerExtension=function(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=Ca(this.gl,this.debug,ee().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension},r.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension()},r.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension()},r.prototype.beginQuery=function(){if(ee().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){var n=this.gl,e=this.getQueryTimerExtensionWebGL2(),t=n.createQuery();return n.beginQuery(e.TIME_ELAPSED_EXT,t),t}var a=this.getQueryTimerExtensionWebGL1(),o=a.createQueryEXT();return a.beginQueryEXT(a.TIME_ELAPSED_EXT,o),o},r.prototype.endQuery=function(){if(ee().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")!==2){var n=this.getQueryTimerExtensionWebGL1();n.endQueryEXT(n.TIME_ELAPSED_EXT)}else{var e=this.gl,t=this.getQueryTimerExtensionWebGL2();e.endQuery(t.TIME_ELAPSED_EXT)}},r.prototype.waitForQueryAndGetTime=function(n){return ve(this,void 0,void 0,function(){var e=this;return ye(this,function(t){switch(t.label){case 0:return[4,q(function(){return e.disposed||e.isQueryAvailable(n,ee().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))})];case 1:return t.sent(),[2,this.getQueryTime(n,ee().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))]}})})},r.prototype.getQueryTime=function(n,e){if(e===0)return null;if(e===2){var t=this.gl;return t.getQueryParameter(n,t.QUERY_RESULT)/1e6}var a=this.getQueryTimerExtensionWebGL1();return a.getQueryObjectEXT(n,a.QUERY_RESULT_EXT)/1e6},r.prototype.isQueryAvailable=function(n,e){if(e===0)return!0;if(e===2){var t=this.gl,a=this.getQueryTimerExtensionWebGL2(),o=t.getQueryParameter(n,t.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(a.GPU_DISJOINT_EXT)),o&&!this.disjoint}return o=(a=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(n,a.QUERY_RESULT_AVAILABLE_EXT),this.disjoint==null&&(this.disjoint=this.gl.getParameter(a.GPU_DISJOINT_EXT)),o&&!this.disjoint},r.prototype.pollFence=function(n){var e=this;return new Promise(function(t){e.addItemToPoll(function(){return n.isFencePassed()},function(){return t()})})},r.prototype.pollItems=function(){for(var n=function(t){for(var a=0;a<t.length&&t[a]();++a);return a-1}(this.itemsToPoll.map(function(t){return t.isDoneFn})),e=0;e<=n;++e)(0,this.itemsToPoll[e].resolveFn)();this.itemsToPoll=this.itemsToPoll.slice(n+1)},r.prototype.addItemToPoll=function(n,e){var t=this;this.itemsToPoll.push({isDoneFn:n,resolveFn:e}),this.itemsToPoll.length>1||q(function(){return t.pollItems(),t.itemsToPoll.length===0})},r.prototype.bindTextureToFrameBuffer=function(n){this.throwIfDisposed(),Ya(this.gl,this.debug,n,this.framebuffer),this.debug&&Mn(this.gl)},r.prototype.unbindTextureToFrameBuffer=function(){this.outputTexture!=null?(Ya(this.gl,this.debug,this.outputTexture,this.framebuffer),this.debug&&Mn(this.gl)):$a(this.gl,this.debug,this.framebuffer)},r.prototype.downloadMatrixDriver=function(n,e){this.bindTextureToFrameBuffer(n);var t=e();return this.unbindTextureToFrameBuffer(),t},r.prototype.setOutputMatrixTextureDriver=function(n,e,t){this.throwIfDisposed();var a=this.gl;Ya(a,this.debug,n,this.framebuffer),this.debug&&Mn(a),this.outputTexture=n,Me(a,this.debug,function(){return a.viewport(0,0,e,t)}),Me(a,this.debug,function(){return a.scissor(0,0,e,t)})},r.prototype.setOutputMatrixWriteRegionDriver=function(n,e,t,a){var o=this;this.throwIfDisposed(),Me(this.gl,this.debug,function(){return o.gl.scissor(n,e,t,a)})},r.prototype.throwIfDisposed=function(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")},r.prototype.throwIfNoProgram=function(){if(this.program==null)throw new Error("No GPU program is currently set.")},r}();function wc(r,n){if(r.length!==n.length)throw Error("Binary was compiled with "+r.length+" inputs, but was executed with "+n.length+" inputs");r.forEach(function(e,t){var a=e.logicalShape,o=n[t],i=o.shape;if(!Oe(a,i))throw Error("Binary was compiled with different shapes than the current args. Shapes "+a+" and "+i+" must match");if(!e.isUniform||!o.isUniform){var s=e.texShape,u=o.isUniform?null:o.texData.texShape;if(!Oe(s,u))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+s+" and "+u+" must match")}})}var ld=function(r,n,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=r;for(var t=e.filterWidth,a=e.inChannels,o=e.strideWidth,i=e.strideHeight,s=e.padInfo,u=e.outWidth,c=e.dilationWidth,d=e.dilationHeight,f=e.dataFormat,m=s.left,g=s.top,x=a*t,E=h(),w=f==="channelsLast",C=w?0:1,N=w?1:2,S="",I=0;I<=1;I++)for(var M=0;M<=1;M++)S+=`
|
|
blockIndex = rc.y + `+M+`;
|
|
pos = rc.x + `+I+`;
|
|
|
|
if(blockIndex < `+r[1]+" && pos < "+r[0]+`) {
|
|
offsetY = int(blockIndex / (`+u+")) * "+i+" - "+g+`;
|
|
d0 = offsetY + `+d+" * (pos / "+x+`);
|
|
|
|
if(d0 < `+n[C]+` && d0 >= 0) {
|
|
|
|
offsetX = int(mod(float(blockIndex), `+u+".) * "+o+". - "+m+`.);
|
|
d1 = offsetX + `+c+" * (int(mod(float(pos), "+x+".) / "+a+`.));
|
|
|
|
if(d1 < `+n[N]+` && d1 >= 0) {
|
|
|
|
ch = int(mod(float(pos), `+a+`.));
|
|
|
|
if (`+w+`) {
|
|
innerDims = vec2(d1, ch);
|
|
result[`+(2*I+M)+`] = getChannel(
|
|
getA(d0, int(innerDims.x),
|
|
int(innerDims.y)), innerDims);
|
|
} else {
|
|
innerDims = vec2(d0, d1);
|
|
result[`+(2*I+M)+`] = getChannel(
|
|
getA(ch, int(innerDims.x),
|
|
int(innerDims.y)), innerDims);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
`;this.userCode=`
|
|
void main() {
|
|
ivec2 rc = getOutputCoords();
|
|
|
|
vec4 result = vec4(0);
|
|
|
|
int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
|
|
vec2 innerDims;
|
|
|
|
`+S+`
|
|
|
|
`+E.output+` = result;
|
|
}
|
|
`},dd=function(r,n,e,t,a){this.variableNames=["x"],this.outputShape=[];var o,i=n,s=r[3]-1;this.outputShape=r;var u="float("+e+") + float("+t+") * sum";o=a===.5?"inversesqrt("+u+")":a===1?"1.0/("+u+")":"exp(log("+u+") * float(-"+a+"));",this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int r = coords[1];
|
|
int c = coords[2];
|
|
int d = coords[3];
|
|
float x = getX(b, r, c, d);
|
|
float sum = 0.0;
|
|
for (int j = -`+i+"; j <= "+i+`; j++) {
|
|
int idx = d + j;
|
|
if (idx >= 0 && idx <= `+s+`) {
|
|
float z = getX(b, r, c, idx);
|
|
sum += z * z;
|
|
}
|
|
}
|
|
float val = x * `+o+`;
|
|
setOutput(val);
|
|
}
|
|
`},hd=function(r,n,e,t,a){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=r,this.depth=r[3],this.depthRadius=n,this.bias=e,this.alpha=t,this.beta=a,this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int r = coords[1];
|
|
int c = coords[2];
|
|
|
|
float result = 0.0;
|
|
for (int d = 0; d < `+this.depth+`; ++d) {
|
|
int depthBegin = int(max(0.0, float(d - `+n+`)));
|
|
int depthEnd = int(min(float(`+this.depth+`),
|
|
float(d + `+n+` + 1)));
|
|
|
|
const int MIN_DEPTH_BEGIN = 0;
|
|
const int MAX_DEPTH_END = `+this.depth+`;
|
|
|
|
float norm = 0.0;
|
|
for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {
|
|
if (k < depthBegin){
|
|
continue;
|
|
}
|
|
else if (k >= depthBegin && k < depthEnd) {
|
|
norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);
|
|
}
|
|
else {
|
|
break;
|
|
}
|
|
}
|
|
|
|
norm = float(`+t+") * norm + float("+e+`);
|
|
|
|
for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){
|
|
if (k < depthBegin){
|
|
continue;
|
|
}
|
|
else if (k >= depthBegin && k < depthEnd){
|
|
float dyi = -2.0 * float(`+t+`)
|
|
* float(`+a+`)
|
|
* getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)
|
|
/ norm;
|
|
if (k == d) {
|
|
dyi += pow(norm, -1.0 * `+a+`);
|
|
}
|
|
if (k == coords[3]) {
|
|
dyi *= getDy(b, r, c, d);
|
|
result += dyi;
|
|
}
|
|
}
|
|
else {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`},pd=function(r,n,e,t,a){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;var o,i=n,s=r[3]-1;this.outputShape=r;var u="float("+e+") + float("+t+") * sum";o=a===.5?"inversesqrt("+u+")":a===1?"1.0/("+u+")":"exp(log("+u+") * float(-"+a+"));",this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords.x;
|
|
int r = coords.y;
|
|
int c = coords.z;
|
|
int d = coords.w;
|
|
|
|
bool hasNextCol = d < `+this.outputShape[3]+`;
|
|
bool hasNextRow = c < `+this.outputShape[2]+`;
|
|
|
|
vec4 sum = vec4(0.);
|
|
vec4 xFragAtOutputCoords = getX(b, r, c, d);
|
|
|
|
vec4 xAtOutputCoords = vec4(
|
|
getChannel(xFragAtOutputCoords, vec2(c, d)),
|
|
hasNextCol ?
|
|
getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,
|
|
hasNextRow ?
|
|
getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,
|
|
(hasNextRow && hasNextCol) ?
|
|
getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0
|
|
);
|
|
|
|
int firstChannel = d - `+i+`;
|
|
vec2 cache = vec2(0.);
|
|
if(firstChannel >= 0){
|
|
vec4 firstChannelFrag = getX(b, r, c, firstChannel);
|
|
cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));
|
|
if(hasNextRow){
|
|
cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));
|
|
}
|
|
}
|
|
|
|
ivec2 depth = ivec2(d, d + 1);
|
|
for (int j = - `+i+"; j <= "+i+`; j++) {
|
|
ivec2 idx = depth + j;
|
|
bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
|
|
bvec2 belowUpperBound = lessThanEqual(idx, ivec2(`+s+`));
|
|
|
|
bool depthInRange = aboveLowerBound.x && belowUpperBound.x;
|
|
bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;
|
|
|
|
if(depthInRange || depthPlusOneInRange){
|
|
vec4 z = vec4(0.);
|
|
vec4 xFragAtCurrentDepth;
|
|
z.xz = cache.xy;
|
|
if(depthPlusOneInRange && hasNextCol){
|
|
xFragAtCurrentDepth = idx.y != d ?
|
|
getX(b, r, c, idx.y) : xFragAtOutputCoords;
|
|
z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));
|
|
if(hasNextRow){
|
|
z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));
|
|
}
|
|
}
|
|
cache.xy = z.yw;
|
|
sum += z * z;
|
|
}
|
|
}
|
|
vec4 result = xAtOutputCoords * `+o+`;
|
|
setOutput(result);
|
|
}
|
|
`},fd=function(r){this.variableNames=["dy","maxPos"],this.outputShape=r.inShape;var n=r.strideHeight,e=r.strideWidth,t=r.dilationHeight,a=r.effectiveFilterHeight,o=r.effectiveFilterWidth,i=a-1-r.padInfo.top,s=o-1-r.padInfo.left,u=a*o-1;this.userCode=`
|
|
const ivec2 pads = ivec2(`+i+", "+s+`);
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
|
|
ivec2 dyRCCorner = coords.yz - pads;
|
|
int dyRCorner = dyRCCorner.x;
|
|
int dyCCorner = dyRCCorner.y;
|
|
|
|
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wR = 0; wR < `+a+`;
|
|
wR += `+t+`) {
|
|
float dyR = float(dyRCorner + wR) / `+n+`.0;
|
|
|
|
if (dyR < 0.0 || dyR >= `+r.outHeight+`.0 || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
for (int wC = 0; wC < `+o+`; wC++) {
|
|
float dyC = float(dyCCorner + wC) / `+e+`.0;
|
|
|
|
if (dyC < 0.0 || dyC >= `+r.outWidth+`.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
float dyValue = getDy(b, idyR, idyC, d);
|
|
int maxPosValue = `+u+` - int(getMaxPos(b, idyR, idyC, d));
|
|
|
|
// Get the current value, check it against the value from the
|
|
// position matrix.
|
|
int curPosValue = wR * `+o+` + wC;
|
|
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
|
|
|
|
dotProd += dyValue * mask;
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`},vd=function(r){this.variableNames=["dy","maxPos"],this.outputShape=r.inShape;var n=r.strideDepth,e=r.strideHeight,t=r.strideWidth,a=r.dilationDepth,o=r.dilationHeight,i=r.dilationWidth,s=r.effectiveFilterDepth,u=r.effectiveFilterHeight,c=r.effectiveFilterWidth,d=s-1-r.padInfo.front,f=u-1-r.padInfo.top,m=c-1-r.padInfo.left,g=s*u*c-1;this.userCode=`
|
|
const ivec3 pads = ivec3(`+d+", "+f+", "+m+`);
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
|
|
int dyDCorner = dyCorner.x;
|
|
int dyRCorner = dyCorner.y;
|
|
int dyCCorner = dyCorner.z;
|
|
|
|
// Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get
|
|
// dx(xD, xR, xC, ch).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
|
|
for (int wD = 0; wD < `+s+`;
|
|
wD += `+a+`) {
|
|
float dyD = float(dyDCorner + wD) / `+n+`.0;
|
|
|
|
if (dyD < 0.0 || dyD >= `+r.outDepth+`.0 || fract(dyD) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyD = int(dyD);
|
|
|
|
for (int wR = 0; wR < `+u+`;
|
|
wR += `+o+`) {
|
|
float dyR = float(dyRCorner + wR) / `+e+`.0;
|
|
|
|
if (dyR < 0.0 || dyR >= `+r.outHeight+`.0 ||
|
|
fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
for (int wC = 0; wC < `+c+`;
|
|
wC += `+i+`) {
|
|
float dyC = float(dyCCorner + wC) / `+t+`.0;
|
|
|
|
if (dyC < 0.0 || dyC >= `+r.outWidth+`.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
|
|
int maxPosValue = `+g+` -
|
|
int(getMaxPos(batch, idyD, idyR, idyC, ch));
|
|
|
|
// Get the current value, check it against the value from the
|
|
// position matrix.
|
|
int curPosValue =
|
|
wD * `+u+" * "+c+` +
|
|
wR * `+c+` + wC;
|
|
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
|
|
|
|
dotProd += dyValue * mask;
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`},Js=function(r,n,e,t,a,o,i){e===void 0&&(e=!1),t===void 0&&(t=!1),a===void 0&&(a=!1),o===void 0&&(o=null),i===void 0&&(i=!1),this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n;var s=e?r[1]:r[2],u=Math.ceil(s/2),c=e?"i * 2, rc.y":"rc.y, i * 2",d=t?"rc.z, i * 2":"i * 2, rc.z",f=e?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],m=t?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],g="",x="";o&&(g=i?`vec4 activation(vec4 a) {
|
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
|
`+o+`
|
|
}`:`vec4 activation(vec4 x) {
|
|
`+o+`
|
|
}`,x="result = activation(result);");var E=a?"result += getBiasAtOutCoords();":"";a&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),this.userCode=`
|
|
`+g+`
|
|
|
|
const float sharedDimension = `+u+`.0;
|
|
|
|
vec4 dot2x2ARowBCol(ivec3 rc) {
|
|
vec4 result = vec4(0);
|
|
for (int i = 0; i < `+u+`; i++) {
|
|
vec4 a = getMatrixA(rc.x, `+c+`);
|
|
vec4 b = getMatrixB(rc.x, `+d+`);
|
|
|
|
// These swizzled products need to be separately added.
|
|
// See: https://github.com/tensorflow/tfjs/issues/1735
|
|
result += (`+f[0]+" * "+m[0]+`);
|
|
result += (`+f[1]+" * "+m[1]+`);
|
|
}
|
|
return result;
|
|
}
|
|
|
|
void main() {
|
|
ivec3 rc = getOutputCoords();
|
|
vec4 result = dot2x2ARowBCol(rc);
|
|
|
|
`+E+`
|
|
|
|
`+x+`
|
|
|
|
setOutput(result);
|
|
}
|
|
`},md=function(){function r(n,e,t){this.variableNames=["probs"],this.outputShape=[n,t],this.userCode=`
|
|
uniform float seed;
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
|
|
float r = random(seed);
|
|
float cdf = 0.0;
|
|
|
|
for (int i = 0; i < `+(e-1)+`; i++) {
|
|
cdf += getProbs(batch, i);
|
|
|
|
if (r < cdf) {
|
|
setOutput(float(i));
|
|
return;
|
|
}
|
|
}
|
|
|
|
// If no other event happened, last event happened.
|
|
setOutput(float(`+(e-1)+`));
|
|
}
|
|
`}return r.prototype.getCustomSetupFunc=function(n){var e=this;return function(t,a){e.seedLoc==null&&(e.seedLoc=t.getUniformLocation(a,"seed")),t.gl.uniform1f(e.seedLoc,n)}},r}(),gd=function(r,n,e,t){this.variableNames=["indices"],this.outputShape=[r,n],this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int index = round(getIndices(coords.x));
|
|
setOutput(mix(float(`+t+"), float("+e+`),
|
|
float(index == coords.y)));
|
|
}
|
|
`},yd=function(r){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=r;var n=r.length;if(n===0)this.userCode=`
|
|
void main() {
|
|
setOutput(vec4(getA(), 0., 0., 0.));
|
|
}
|
|
`;else{var e=l("rc",n),t=le(n),a=function(s,u,c){if(s===1)return"rc > "+u[0];for(var d="",f=s-2;f<s;f++)d+=c[f]+" >= "+u[f],f<s-1&&(d+="||");return d}(n,r,e),o=function(s,u,c,d){if(s===1)return"";var f=d.slice(-2);return`
|
|
int r = `+f[0]+`;
|
|
int c = `+f[1]+`;
|
|
int rp1 = r + 1;
|
|
int cp1 = c + 1;
|
|
|
|
bool cEdge = cp1 >= `+u+`;
|
|
bool rEdge = rp1 >= `+c+`;
|
|
`}(n,r[r.length-1],r[r.length-2],e),i=function(s,u){var c=s.length,d=function(f,m){for(var g=[],x=0;x<=1;x++)for(var E=0;E<=1;E++){for(var w=(x===0?"r":"rp1")+", "+(E===0?"c":"cp1"),C=2;C<f;C++)w=m[m.length-1-C]+","+w;g.push(w)}return g}(c,u);return c===1?`getA(rc),
|
|
rc + 1 >= `+s[0]+` ? 0. : getA(rc + 1),
|
|
0, 0`:"getA("+d[0]+`),
|
|
cEdge ? 0. : getA(`+d[1]+`),
|
|
rEdge ? 0. : getA(`+d[2]+`),
|
|
rEdge || cEdge ? 0. : getA(`+d[3]+")"}(r,e);this.userCode=`
|
|
void main() {
|
|
`+t+` rc = getOutputCoords();
|
|
|
|
if(`+a+`) {
|
|
setOutput(vec4(0));
|
|
} else {
|
|
`+o+`
|
|
|
|
setOutput(vec4(`+i+`));
|
|
}
|
|
}
|
|
`}},xd=function(r,n,e){this.variableNames=["x"],this.outputShape=n.map(function(u,c){return u[0]+r[c]+u[1]});var t=r.length,a=le(t),o=n.map(function(u){return u[0]}).join(","),i=n.map(function(u,c){return u[0]+r[c]}).join(","),s=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,t);this.userCode=t!==1?`
|
|
`+a+" start = "+a+"("+o+`);
|
|
`+a+" end = "+a+"("+i+`);
|
|
|
|
void main() {
|
|
`+a+` outC = getOutputCoords();
|
|
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
|
|
setOutput(float(`+e+`));
|
|
} else {
|
|
`+a+` coords = outC - start;
|
|
setOutput(getX(`+s+`));
|
|
}
|
|
}
|
|
`:`
|
|
int start = `+o+`;
|
|
int end = `+i+`;
|
|
|
|
void main() {
|
|
int outC = getOutputCoords();
|
|
if (outC < start || outC >= end) {
|
|
setOutput(float(`+e+`));
|
|
} else {
|
|
setOutput(getX(outC - start));
|
|
}
|
|
}
|
|
`},bd=function(r,n,e){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n.map(function(w,C){return w[0]+r[C]+w[1]});for(var t=r.length,a=le(t),o=n.map(function(w){return w[0]}).join(","),i=n.map(function(w,C){return w[0]+r[C]}).join(","),s=l("rc",t),u=l("source",t),c=s[t-1]+" < "+this.outputShape[t-1],d=t===1?"source":"vec2("+u.slice(-2).join()+")",f=[a+" rc = outputLoc;",s[t-1]+` += 1;
|
|
if(`+c+`) {
|
|
`,t===1?"":`}
|
|
rc = outputLoc;
|
|
`+s[t-2]+` += 1;
|
|
if(`+s[t-2]+" < "+this.outputShape[t-2]+") {",t===1?"":" "+s[t-1]+` += 1;
|
|
if(`+c+") {"],m=t===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",g="",x=0,E=t===1?2:4;x<E;x++)g+=`
|
|
`+f[x]+`
|
|
if (`+m+`) {
|
|
result[`+x+"] = float("+e+`);
|
|
} else {
|
|
`+a+` source = rc - start;
|
|
result[`+x+"] = getChannel(getX("+u.join()+"), "+d+`);
|
|
}
|
|
`;g+=t===1?"} ":"}}",this.userCode=`
|
|
const `+a+" start = "+a+"("+o+`);
|
|
const `+a+" end = "+a+"("+i+`);
|
|
|
|
void main() {
|
|
`+a+` outputLoc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
`+g+`
|
|
setOutput(result);
|
|
}
|
|
`},Qs=function(r,n,e){if(this.variableNames=["x"],n==="avg"&&e)throw new Error("Cannot compute positions for average pool.");var t=r.filterWidth,a=r.strideHeight,o=r.strideWidth,i=r.dilationHeight,s=r.dilationWidth,u=r.effectiveFilterHeight,c=r.effectiveFilterWidth,d=r.padInfo.top,f=r.padInfo.left;this.outputShape=r.outShape;var m=n==="avg",g="0.0";if(m||(g="-1.0 / 1e-20"),e)this.userCode=`
|
|
const ivec2 strides = ivec2(`+a+", "+o+`);
|
|
const ivec2 pads = ivec2(`+d+", "+f+`);
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d = coords[3];
|
|
|
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
// max/min x(?, ?, d) to get y(yR, yC, d).
|
|
// ? = to be determined
|
|
float minMaxValue = 0.0;
|
|
float minMaxValueFound = 0.0;
|
|
int minMaxPosition = 0;
|
|
float avgValue = 0.0;
|
|
|
|
for (int wR = 0; wR < `+u+`;
|
|
wR += `+i+`) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= `+r.inHeight+`) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < `+c+`;
|
|
wC += `+s+`) {
|
|
int xC = xCCorner + wC;
|
|
|
|
if (xC < 0 || xC >= `+r.inWidth+`) {
|
|
continue;
|
|
}
|
|
|
|
float value = getX(batch, xR, xC, d);
|
|
|
|
// If a min / max value has already been found, use it. If not,
|
|
// use the current value.
|
|
float currMinMaxValue = mix(
|
|
value, minMaxValue, minMaxValueFound);
|
|
if (value >= currMinMaxValue) {
|
|
minMaxValue = value;
|
|
minMaxValueFound = 1.0;
|
|
minMaxPosition = wR * `+c+` + wC;
|
|
}
|
|
}
|
|
}
|
|
setOutput(float(minMaxPosition));
|
|
}
|
|
`;else{var x=n+"("+n+"("+n+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";n==="avg"&&(x="avgValue / count");var E=4*Math.floor(t/4),w=t%4,C=`
|
|
if (`+m+`) {
|
|
avgValue += dot(values, ones);
|
|
} else {
|
|
minMaxValue = max(values, minMaxValue);
|
|
}
|
|
`;this.userCode=`
|
|
const ivec2 strides = ivec2(`+a+", "+o+`);
|
|
const ivec2 pads = ivec2(`+d+", "+f+`);
|
|
const float initializationValue = `+g+`;
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float count = 0.0;
|
|
|
|
float getValue(int batch, int xR, int xC, int d) {
|
|
if (xC < 0 || xC >= `+r.inWidth+`) {
|
|
return initializationValue;
|
|
}
|
|
count += 1.0;
|
|
return getX(batch, xR, xC, d);
|
|
}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d = coords[3];
|
|
|
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
// max/min x(?, ?, d) to get y(yR, yC, d).
|
|
// ? = to be determined
|
|
vec4 minMaxValue = vec4(`+g+`);
|
|
float avgValue = 0.0;
|
|
count = 0.0;
|
|
|
|
for (int wR = 0; wR < `+u+`;
|
|
wR += `+i+`) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= `+r.inHeight+`) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < `+E+`; wC += 4) {
|
|
int xC = xCCorner + wC * `+s+`;
|
|
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + `+s+`, d),
|
|
getValue(batch, xR, xC + 2 * `+s+`, d),
|
|
getValue(batch, xR, xC + 3 * `+s+`, d)
|
|
);
|
|
|
|
`+C+`
|
|
}
|
|
|
|
int xC = xCCorner + `+E+`;
|
|
if (`+(w===1)+`) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
`+C+`
|
|
} else if (`+(w===2)+`) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + `+s+`, d),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
`+C+`
|
|
} else if (`+(w===3)+`) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + `+s+`, d),
|
|
getValue(batch, xR, xC + 2 * `+s+`, d),
|
|
initializationValue
|
|
);
|
|
|
|
`+C+`
|
|
}
|
|
}
|
|
setOutput(`+x+`);
|
|
}
|
|
`}},Zs=function(r,n,e){if(this.variableNames=["x"],n==="avg"&&e)throw new Error("Cannot compute positions for average pool.");var t=r.filterWidth,a=r.strideDepth,o=r.strideHeight,i=r.strideWidth,s=r.dilationDepth,u=r.dilationHeight,c=r.dilationWidth,d=r.effectiveFilterDepth,f=r.effectiveFilterHeight,m=r.effectiveFilterWidth,g=r.padInfo.front,x=r.padInfo.top,E=r.padInfo.left;this.outputShape=r.outShape;var w=n==="avg",C="0.0";if(w||(C="-1.0 / 1e-20"),e)this.userCode=`
|
|
const ivec3 strides =
|
|
ivec3(`+a+", "+o+", "+i+`);
|
|
const ivec3 pads = ivec3(`+g+", "+x+", "+E+`);
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
|
|
int xDCorner = xCorner.x;
|
|
int xRCorner = xCorner.y;
|
|
int xCCorner = xCorner.z;
|
|
|
|
// max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
|
|
// ? = to be determined
|
|
float minMaxValue = 0.0;
|
|
float minMaxValueFound = 0.0;
|
|
int minMaxPosition = 0;
|
|
|
|
for (int wD = 0; wD < `+d+`;
|
|
wD += `+s+`) {
|
|
int xD = xDCorner + wD;
|
|
|
|
if (xD < 0 || xD >= `+r.inDepth+`) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < `+f+`;
|
|
wR += `+u+`) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= `+r.inHeight+`) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < `+m+`;
|
|
wC += `+c+`) {
|
|
int xC = xCCorner + wC;
|
|
|
|
if (xC < 0 || xC >= `+r.inWidth+`) {
|
|
continue;
|
|
}
|
|
|
|
float value = getX(batch, xD, xR, xC, ch);
|
|
|
|
// If a min / max value has already been found, use it. If not,
|
|
// use the current value.
|
|
float currMinMaxValue = mix(
|
|
value, minMaxValue, minMaxValueFound);
|
|
if (value >= currMinMaxValue) {
|
|
minMaxValue = value;
|
|
minMaxValueFound = 1.0;
|
|
minMaxPosition =
|
|
wD * `+f+" * "+m+` +
|
|
wR * `+m+` + wC;;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(float(minMaxPosition));
|
|
}
|
|
`;else{var N=n+"("+n+"("+n+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";n==="avg"&&(N="avgValue / count");var S=4*Math.floor(t/4),I=t%4,M=`
|
|
if (`+w+`) {
|
|
avgValue += dot(values, ones);
|
|
} else {
|
|
minMaxValue = max(values, minMaxValue);
|
|
}
|
|
`;this.userCode=`
|
|
const ivec3 strides =
|
|
ivec3(`+a+", "+o+", "+i+`);
|
|
const ivec3 pads = ivec3(`+g+", "+x+", "+E+`);
|
|
const float initializationValue = `+C+`;
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float count = 0.0;
|
|
|
|
float getValue(int batch, int xD, int xR, int xC, int ch) {
|
|
if (xC < 0 || xC >= `+r.inWidth+`) {
|
|
return initializationValue;
|
|
}
|
|
count += 1.0;
|
|
return getX(batch, xD, xR, xC, ch);
|
|
}
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
|
|
int xDCorner = xCorner.x;
|
|
int xRCorner = xCorner.y;
|
|
int xCCorner = xCorner.z;
|
|
|
|
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
|
|
// ? = to be determined
|
|
vec4 minMaxValue = vec4(`+C+`);
|
|
float avgValue = 0.0;
|
|
count = 0.0;
|
|
|
|
for (int wD = 0; wD < `+d+`;
|
|
wD += `+s+`) {
|
|
int xD = xDCorner + wD;
|
|
|
|
if (xD < 0 || xD >= `+r.inDepth+`) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < `+f+`;
|
|
wR += `+u+`) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= `+r.inHeight+`) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < `+S+`; wC += 4) {
|
|
int xC = xCCorner + wC * `+c+`;
|
|
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + `+c+`, ch),
|
|
getValue(batch, xD, xR, xC + 2 * `+c+`, ch),
|
|
getValue(batch, xD, xR, xC + 3 * `+c+`, ch)
|
|
);
|
|
|
|
`+M+`
|
|
}
|
|
|
|
int xC = xCCorner + `+S+`;
|
|
if (`+(I===1)+`) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
`+M+`
|
|
} else if (`+(I===2)+`) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + `+c+`, ch),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
`+M+`
|
|
} else if (`+(I===3)+`) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + `+c+`, ch),
|
|
getValue(batch, xD, xR, xC + 2 * `+c+`, ch),
|
|
initializationValue
|
|
);
|
|
|
|
`+M+`
|
|
}
|
|
}
|
|
setOutput(`+N+`);
|
|
}
|
|
}
|
|
`}},wd=function(r,n){this.variableNames=["x"];var e=r.windowSize,t=r.batchSize,a=r.inSize,o=Math.ceil(a/e);this.outputShape=[t,o];var i="0.0",s="";n==="prod"?i="1.0":n==="min"?(i="1.0 / 1e-20",s="min"):n==="max"&&(i="-1.0 / 1e-20",s="max");var u=n+"("+n+"("+n+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";n==="sum"?u="sumValue":n==="prod"?u="prodValue":n==="all"?u="allValue":n==="any"&&(u="anyValue");var c=4*Math.floor(e/4),d=e%4,f=`
|
|
if (`+(n==="sum")+`) {
|
|
sumValue += dot(values, ones);
|
|
} else if (`+(n==="prod")+`) {
|
|
vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);
|
|
prodValue *= tmp[0] * tmp[1];
|
|
} else {
|
|
minMaxValue = `+s+`(values, minMaxValue);
|
|
}
|
|
`,m="vec4";n==="all"?(i="1.0",f=`
|
|
bool reducedAllValue = all(values);
|
|
float floatedReducedAllValue = float(reducedAllValue);
|
|
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
|
|
`,m="bvec4"):n==="any"&&(i="0.0",f=`
|
|
bool reducedAnyValue = any(values);
|
|
float floatedReducedAnyValue = float(reducedAnyValue);
|
|
anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
|
|
`,m="bvec4");var g="";a%e>0&&(g=`
|
|
if (inIdx < 0 || inIdx >= `+a+`) {
|
|
return initializationValue;
|
|
}
|
|
`),this.userCode=`
|
|
const float initializationValue = `+i+`;
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float getValue(int batch, int inIdx) {
|
|
`+g+`
|
|
return getX(batch, inIdx);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = outIdx * `+e+`;
|
|
|
|
vec4 minMaxValue = vec4(`+i+`);
|
|
float prodValue = 1.0;
|
|
float sumValue = 0.0;
|
|
float allValue = 1.0;
|
|
float anyValue = 0.0;
|
|
|
|
for (int i = 0; i < `+c+`; i += 4) {
|
|
int inIdx = inOffset + i;
|
|
`+m+" values = "+m+`(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
getValue(batch, inIdx + 3)
|
|
);
|
|
|
|
`+f+`
|
|
}
|
|
|
|
int inIdx = inOffset + `+c+`;
|
|
if (`+(d===1)+`) {
|
|
`+m+" values = "+m+`(
|
|
getValue(batch, inIdx),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
`+f+`
|
|
} else if (`+(d===2)+`) {
|
|
`+m+" values = "+m+`(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
`+f+`
|
|
} else if (`+(d===3)+`) {
|
|
`+m+" values = "+m+`(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
initializationValue
|
|
);
|
|
|
|
`+f+`
|
|
}
|
|
setOutput(`+u+`);
|
|
}
|
|
`},Ed=function(r,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=r;for(var e="",t=0;t<4;t++){var a="thisRC = rc;";t%2==1&&(a+="thisRC.z += 1;"),t>1&&(a+="thisRC.y += 1;"),e+=`
|
|
`+a+`
|
|
`+(t>0?"if(thisRC.y < rows && thisRC.z < cols){":"")+`
|
|
int flatIndex = getFlatIndex(thisRC);
|
|
|
|
ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);
|
|
vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));
|
|
|
|
result[`+t+`] =
|
|
getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
|
|
`+(t>0?"}":"")+`
|
|
`}this.userCode=`
|
|
|
|
ivec3 inputCoordsFromReshapedOutCoords(int index) {
|
|
`+v(["r","c","d"],n)+`
|
|
return ivec3(r, c, d);
|
|
}
|
|
|
|
`+y(r)+`
|
|
|
|
void main() {
|
|
ivec3 rc = getOutputCoords();
|
|
|
|
vec4 result = vec4(0.);
|
|
|
|
ivec3 thisRC;
|
|
int rows = `+r[1]+`;
|
|
int cols = `+r[2]+`;
|
|
|
|
`+e+`
|
|
|
|
setOutput(result);
|
|
}
|
|
`},_d=function(r,n,e){this.variableNames=["dy"],this.outputShape=[],this.outputShape=n.shape;var t=n.shape,a=t[1],o=t[2],i=r.shape,s=i[1],u=i[2],c=[e&&s>1?a-1:a,e&&u>1?o-1:o],d=[e&&s>1?s-1:s,e&&u>1?u-1:u],f=c[0]/d[0],m=c[1]/d[1],g=1/f,x=1/m,E=2*Math.ceil(g)+2,w=2*Math.ceil(x)+2;this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
int r = coords[1];
|
|
int c = coords[2];
|
|
|
|
float accumulator = 0.0;
|
|
|
|
const float heightScale = float(`+f+`);
|
|
const float widthScale = float(`+m+`);
|
|
|
|
const float invHeightScale = float(`+g+`);
|
|
const float invWidthScale = float(`+x+`);
|
|
|
|
const int winHeight = int(`+E+`);
|
|
const int winWidth = int(`+w+`);
|
|
|
|
// Compute bounds for where in dy we will look
|
|
float startRLerp = floor(float(r) * invHeightScale);
|
|
int startDyR = int(startRLerp - float(winHeight / 2));
|
|
|
|
float startCLerp = floor(float(c) * invWidthScale);
|
|
int startDyC = int(startCLerp - float(winWidth / 2));
|
|
|
|
// Loop over dy
|
|
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
|
|
int dyR = dyROffset + startDyR;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyR < 0 || dyR >= `+s+`) {
|
|
continue;
|
|
}
|
|
|
|
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
|
|
int dyC = dyCOffset + startDyC;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyC < 0 || dyC >= `+u+`) {
|
|
continue;
|
|
}
|
|
|
|
float dxR = float(dyR) * heightScale;
|
|
int topDxRIndex = int(floor(dxR));
|
|
int bottomDxRIndex = int(min(ceil(dxR), `+(a-1)+`.0));
|
|
float dxRLerp = dxR - float(topDxRIndex);
|
|
float inverseDxRLerp = 1.0 - dxRLerp;
|
|
|
|
float dxC = float(dyC) * widthScale;
|
|
int leftDxCIndex = int(floor(dxC));
|
|
int rightDxCIndex = int(min(ceil(dxC), `+(o-1)+`.0));
|
|
float dxCLerp = dxC - float(leftDxCIndex);
|
|
float inverseDxCLerp = 1.0 - dxCLerp;
|
|
|
|
if (r == topDxRIndex && c == leftDxCIndex) {
|
|
// topLeft
|
|
accumulator +=
|
|
getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;
|
|
}
|
|
|
|
if (r == topDxRIndex && c == rightDxCIndex) {
|
|
// topRight
|
|
accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;
|
|
}
|
|
|
|
if (r == bottomDxRIndex && c == leftDxCIndex) {
|
|
// bottomLeft
|
|
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;
|
|
}
|
|
|
|
if (r == bottomDxRIndex && c == rightDxCIndex) {
|
|
// bottomRight
|
|
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;
|
|
}
|
|
}
|
|
}
|
|
// End loop over dy
|
|
|
|
setOutput(accumulator);
|
|
}
|
|
`},Cd=function(r,n,e,t){this.variableNames=["A"],this.outputShape=[];var a=r[0],o=r[1],i=r[2],s=r[3];this.outputShape=[a,n,e,s];var u=[t&&n>1?o-1:o,t&&e>1?i-1:i],c=[t&&n>1?n-1:n,t&&e>1?e-1:e];this.userCode=`
|
|
const vec2 effectiveInputOverOutputRatioRC = vec2(
|
|
`+u[0]/c[0]+`,
|
|
`+u[1]/c[1]+`);
|
|
const vec2 inputShapeRC = vec2(`+o+".0, "+i+`.0);
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
ivec2 yRC = coords.yz;
|
|
|
|
// Fractional source index.
|
|
vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;
|
|
|
|
// Compute the four integer indices.
|
|
ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);
|
|
ivec2 sourceCeilRC = ivec2(
|
|
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
|
|
|
|
float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);
|
|
float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);
|
|
float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);
|
|
float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);
|
|
|
|
vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);
|
|
|
|
float top = topLeft + (topRight - topLeft) * fracRC.y;
|
|
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;
|
|
float newValue = top + (bottom - top) * fracRC.x;
|
|
|
|
setOutput(newValue);
|
|
}
|
|
`},Rd=function(r,n,e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];var a=r[0],o=r[1],i=r[2],s=r[3];this.outputShape=[a,n,e,s];var u=[t&&n>1?o-1:o,t&&e>1?i-1:i],c=[t&&n>1?n-1:n,t&&e>1?e-1:e];this.userCode=`
|
|
const vec3 effectiveInputOverOutputRatioRC = vec3(
|
|
`+u[0]/c[0]+`,
|
|
`+u[1]/c[1]+`,
|
|
`+u[1]/c[1]+`);
|
|
const vec3 inputShapeRC = vec3(`+o+".0, "+i+`.0,
|
|
`+i+`.0);
|
|
|
|
float getAValue(int b, int r, int c, int d) {
|
|
return getChannel(getA(b, r, c, d), vec2(c, d));
|
|
}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
// Calculate values for next column in yRC.z.
|
|
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
|
|
|
|
// Fractional source index.
|
|
vec3 sourceFracIndexRC = vec3(yRC) * effectiveInputOverOutputRatioRC;
|
|
|
|
// Compute the four integer indices.
|
|
ivec3 sourceFloorRC = ivec3(sourceFracIndexRC);
|
|
ivec3 sourceCeilRC = ivec3(
|
|
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
|
|
|
|
// Should we calculate next column and row elements in 2x2 packed cell.
|
|
bool hasNextCol = d < `+(s-1)+`;
|
|
bool hasNextRow = coords.z < `+(e-1)+`;
|
|
|
|
// In parallel, construct four corners for all four components in
|
|
// packed 2x2 cell.
|
|
vec4 topLeft = vec4(
|
|
getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),
|
|
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)
|
|
: 0.0,
|
|
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)
|
|
: 0.0,
|
|
(hasNextRow && hasNextCol) ?
|
|
getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);
|
|
|
|
vec4 bottomLeft = vec4(
|
|
getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),
|
|
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)
|
|
: 0.0,
|
|
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)
|
|
: 0.0,
|
|
(hasNextRow && hasNextCol) ?
|
|
getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);
|
|
|
|
vec4 topRight = vec4(
|
|
getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),
|
|
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)
|
|
: 0.0,
|
|
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)
|
|
: 0.0,
|
|
(hasNextRow && hasNextCol) ?
|
|
getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);
|
|
|
|
vec4 bottomRight = vec4(
|
|
getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),
|
|
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)
|
|
: 0.0,
|
|
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)
|
|
: 0.0,
|
|
(hasNextRow && hasNextCol) ?
|
|
getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);
|
|
|
|
vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);
|
|
|
|
vec4 top = mix(topLeft, topRight, fracRC.yyzz);
|
|
vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);
|
|
vec4 newValue = mix(top, bottom, fracRC.x);
|
|
|
|
setOutput(newValue);
|
|
}
|
|
`},Ad=function(r,n,e){this.variableNames=["dy"],this.outputShape=[],this.outputShape=n.shape;var t=n.shape,a=t[1],o=t[2],i=r.shape,s=i[1],u=i[2],c=[e&&s>1?a-1:a,e&&u>1?o-1:o],d=[e&&s>1?s-1:s,e&&u>1?u-1:u],f=c[0]/d[0],m=c[1]/d[1],g=1/f,x=1/m,E=2*Math.ceil(g)+2,w=2*Math.ceil(x)+2;this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
int r = coords[1];
|
|
int c = coords[2];
|
|
|
|
float accumulator = 0.0;
|
|
|
|
const float heightScale = float(`+f+`);
|
|
const float widthScale = float(`+m+`);
|
|
|
|
const float invHeightScale = float(`+g+`);
|
|
const float invWidthScale = float(`+x+`);
|
|
|
|
const int winHeight = int(`+E+`);
|
|
const int winWidth = int(`+w+`);
|
|
|
|
// Compute bounds for where in dy we will look
|
|
float startRLerp = floor(float(r) * invHeightScale);
|
|
int startDyR = int(floor(startRLerp - float(winHeight / 2)));
|
|
|
|
float startCLerp = floor(float(c) * invWidthScale);
|
|
int startDyC = int(floor(startCLerp - float(winWidth / 2)));
|
|
|
|
// Loop over dy
|
|
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
|
|
int dyR = dyROffset + startDyR;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyR < 0 || dyR >= `+s+`) {
|
|
continue;
|
|
}
|
|
|
|
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
|
|
int dyC = dyCOffset + startDyC;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyC < 0 || dyC >= `+u+`) {
|
|
continue;
|
|
}
|
|
|
|
float sourceFracRow =
|
|
float(`+c[0]+`) *
|
|
(float(dyR) / float(`+d[0]+`));
|
|
|
|
float sourceFracCol =
|
|
float(`+c[1]+`) *
|
|
(float(dyC) / float(`+d[1]+`));
|
|
|
|
int sourceNearestRow = int(min(
|
|
float(int(`+a+`) - 1),
|
|
`+e+` ? float(round(sourceFracRow)) :
|
|
float(floor(sourceFracRow))));
|
|
|
|
int sourceNearestCol = int(min(
|
|
float(int(`+o+`) - 1),
|
|
`+e+` ? float(round(sourceFracCol)) :
|
|
float(floor(sourceFracCol))));
|
|
|
|
if (r == sourceNearestRow && c == sourceNearestCol) {
|
|
accumulator += getDy(b, dyR, dyC, d);
|
|
}
|
|
}
|
|
}
|
|
// End loop over dy
|
|
|
|
setOutput(accumulator);
|
|
}
|
|
`},Td=function(r,n,e,t){this.variableNames=["A"],this.outputShape=[];var a=r[0],o=r[1],i=r[2],s=r[3];this.outputShape=[a,n,e,s];var u=[t&&n>1?o-1:o,t&&e>1?i-1:i],c=[t&&n>1?n-1:n,t&&e>1?e-1:e],d=t?"0.5":"0.0";this.userCode=`
|
|
const vec2 effectiveInputOverOutputRatioRC = vec2(
|
|
`+u[0]/c[0]+`,
|
|
`+u[1]/c[1]+`);
|
|
const vec2 inputShapeRC = vec2(`+o+".0, "+i+`.0);
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
ivec2 yRC = coords.yz;
|
|
|
|
// Fractional source index.
|
|
vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;
|
|
|
|
// Compute the coordinators of nearest neighbor point.
|
|
ivec2 sourceNearestRC = ivec2(
|
|
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + `+d+`)));
|
|
|
|
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
|
|
|
|
setOutput(newValue);
|
|
}
|
|
`},Dd=function(r,n){this.variableNames=["x"];var e=r.length;if(e>4)throw new Error("WebGL backend: Reverse of rank-"+e+" tensor is not yet supported");if(this.outputShape=r,e!==1){var t=r.map(function(o,i){return function(s){return n.indexOf(s)!==-1&&r[s]!==1?r[s]+" - coords["+s+"] - 1":"coords["+s+"]"}(i)}).join(","),a=le(e);this.userCode=`
|
|
void main() {
|
|
`+a+` coords = getOutputCoords();
|
|
setOutput(getX(`+t+`));
|
|
}
|
|
`}else this.userCode=`
|
|
void main() {
|
|
int coord = getOutputCoords();
|
|
setOutput(getX(`+r[0]+` - coord - 1));
|
|
}
|
|
`},Nd=function(r,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;var e=r.length;if(e>4)throw new Error("WebGL backend: Reverse of rank-"+e+" tensor is not yet supported");this.outputShape=r;var t=l("rc",e),a=t[e-1]+" + 1 < "+this.outputShape[e-1],o=t[e-2]+" + 1 < "+this.outputShape[e-2],i=le(e);function s(u){var c=r.map(function(d,f){return function(m,g){return n.indexOf(m)!==-1&&r[m]!==1?r[m]+" - "+g[m]+" - 1":""+g[m]}(f,u)});return"getChannel(getX("+c.join(",")+"), vec2("+c.slice(-2).join(",")+"))"}this.userCode=e===1?`
|
|
void main(){
|
|
int rc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
result.r = getChannel(getX(`+r[0]+` - rc - 1),
|
|
`+r[0]+` - rc - 1);
|
|
if(`+a+`){
|
|
result.g = getChannel(getX(`+r[0]+` - (rc + 1) - 1),
|
|
`+r[0]+` - (rc + 1) - 1);
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`:`
|
|
void main() {
|
|
`+i+` rc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
result.r = `+function(u){return s(u)}(t.slice())+`;
|
|
if(`+a+`){
|
|
result.g = `+function(u){return u[e-1]="("+u[e-1]+" + 1)",s(u)}(t.slice())+`;
|
|
}
|
|
if(`+o+`) {
|
|
result.b = `+function(u){return u[e-2]="("+u[e-2]+" + 1)",s(u)}(t.slice())+`;
|
|
if(`+a+`) {
|
|
result.a = `+function(u){return u[e-1]="("+u[e-1]+" + 1)",u[e-2]="("+u[e-2]+" + 1)",s(u)}(t.slice())+`;
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`},Ec=function(r,n,e,t,a,o,i){i===void 0&&(i=!0),this.variableNames=["updates","indices","defaultValue"],this.outputShape=o;var s=le(a.length),u=le(o.length),c="";e===1?c="i":e===2&&(c="i, j");var d="getIndices("+c+")",f="";t===1?f="i":t===2&&(f="i, coords[1]");var m="getUpdates("+f+")",g=n>1?"strides[j]":"strides";this.userCode=`
|
|
`+s+" strides = "+s+"("+a+`);
|
|
|
|
void main() {
|
|
`+u+` coords = getOutputCoords();
|
|
float sum = 0.0;
|
|
bool found = false;
|
|
for (int i = 0; i < `+r+`; i++) {
|
|
int flattenedIndex = 0;
|
|
for (int j = 0; j < `+n+`; j++) {
|
|
int index = round(`+d+`);
|
|
flattenedIndex += index * `+g+`;
|
|
}
|
|
if (flattenedIndex == coords[0]) {
|
|
sum += `+m+`;
|
|
found = true;
|
|
}
|
|
}
|
|
setOutput(mix(getDefaultValue(), sum, float(found)));
|
|
}
|
|
`},kd=function(r,n){this.variableNames=["x","segmentIds"];var e=r.windowSize,t=r.batchSize,a=r.inSize,o=r.numSegments,i=o*Math.ceil(a/e);this.outputShape=[t,i];var s=4*Math.floor(e/4),u=e%4,c=`
|
|
sumValue += dot(values, segFilter);
|
|
`,d="";a%e>0&&(d=`
|
|
if (inIdx < 0 || inIdx >= `+a+`) {
|
|
return initializationValue;
|
|
}
|
|
`);var f="";a%e>0&&(f=`
|
|
if (inIdx < 0 || inIdx >= `+a+`) {
|
|
return -1.0;
|
|
}
|
|
`),this.userCode=`
|
|
const float initializationValue = 0.0;
|
|
|
|
float getValue(int batch, int inIdx) {
|
|
`+d+`
|
|
return getX(batch, inIdx);
|
|
}
|
|
|
|
float getSegmentIdAtIndex(int inIdx) {
|
|
`+f+`
|
|
return getSegmentIds(inIdx);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = int(floor(float(outIdx) / float(
|
|
`+o+")) * float("+e+`));
|
|
int currentSeg = int(mod(float(outIdx), float(`+o+`)));
|
|
|
|
float sumValue = 0.0;
|
|
|
|
for (int i = 0; i < `+s+`; i += 4) {
|
|
int inIdx = inOffset + i;
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
getValue(batch, inIdx + 3)
|
|
);
|
|
|
|
vec4 segFilter = vec4(
|
|
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0
|
|
);
|
|
|
|
`+c+`
|
|
}
|
|
|
|
int inIdx = inOffset + `+s+`;
|
|
if (`+(u===1)+`) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
int inIdxSeg = int(getSegmentIdAtIndex(inIdx));
|
|
|
|
vec4 segFilter = vec4(
|
|
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
|
|
0,
|
|
0,
|
|
0
|
|
);
|
|
|
|
`+c+`
|
|
} else if (`+(u===2)+`) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
vec4 segFilter = vec4(
|
|
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
|
|
0,
|
|
0
|
|
);
|
|
|
|
`+c+`
|
|
} else if (`+(u===3)+`) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
initializationValue
|
|
);
|
|
|
|
vec4 segFilter = vec4(
|
|
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
|
|
0
|
|
);
|
|
|
|
`+c+`
|
|
}
|
|
setOutput(sumValue);
|
|
}
|
|
`},Sd=function(r,n,e){var t,a;if(this.variableNames=["c","a","b"],this.outputShape=n,e>4)throw Error("Where for rank "+e+" is not yet supported");if(e===1)a="resRC",t="resRC";else{for(var o=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],s=[],u=0;u<n.length;u++)s.push(""+o[u]),u<r&&i.push(""+o[u]);t=i.join(),a=s.join()}var c=le(e);this.userCode=`
|
|
void main() {
|
|
`+c+` resRC = getOutputCoords();
|
|
float cVal = getC(`+t+`);
|
|
if (cVal >= 1.0) {
|
|
setOutput(getA(`+a+`));
|
|
} else {
|
|
setOutput(getB(`+a+`));
|
|
}
|
|
}
|
|
`},Od=function(){function r(n){this.variableNames=["source"],this.outputShape=n,this.rank=n.length;var e,t=le(this.rank),a="uniform int start["+this.rank+"];",o=function(i){if(i===1)return"sourceLoc";if(i<=6)return eu.slice(0,i).map(function(s){return"sourceLoc."+s}).join(",");throw Error("Slicing for rank "+i+" is not yet supported")}(this.rank);e=`
|
|
`+t+` sourceLoc;
|
|
`+t+` coords = getOutputCoords();
|
|
`+n.map(function(i,s){return"sourceLoc."+eu[s]+" = start["+s+"] + coords."+eu[s]+";"}).join(`
|
|
`)+`
|
|
`,this.userCode=`
|
|
`+a+`
|
|
void main() {
|
|
`+e+`
|
|
setOutput(getSource(`+o+`));
|
|
}
|
|
`}return r.prototype.getCustomSetupFunc=function(n){var e=this;if(n.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+n.length+")");return function(t,a){e.startLoc==null&&(e.startLoc=t.getUniformLocationNoThrow(a,"start"),e.startLoc==null)||t.gl.uniform1iv(e.startLoc,n)}},r}(),eu=["x","y","z","w","u","v"],Id=function(){function r(n){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n,this.rank=n.length;var e=le(this.rank),t=l("coords",this.rank),a=l("sourceLoc",this.rank),o=this.rank===1?"sourceLoc":"vec2("+a.slice(-2).join()+")",i="getChannel(getSource("+a.join()+"), "+o+")",s=`
|
|
result.x = `+i+`;
|
|
if (++`+t[this.rank-1]+" < "+n[this.rank-1]+`) {
|
|
++`+a[this.rank-1]+`;
|
|
result.y = `+i+`;
|
|
--`+a[this.rank-1]+`;
|
|
}
|
|
`,u=this.rank===1?"":`
|
|
--`+t[this.rank-1]+`;
|
|
if (++`+t[this.rank-2]+" < "+n[this.rank-2]+`) {
|
|
++`+a[this.rank-2]+`;
|
|
result.z = `+i+`;
|
|
if (++`+t[this.rank-1]+" < "+n[this.rank-1]+`) {
|
|
++`+a[this.rank-1]+`;
|
|
result.w = `+i+`;
|
|
}
|
|
}
|
|
`,c=this.rank<=4?`sourceLoc = coords +
|
|
`+e+"("+n.map(function(d,f){return"start["+f+"]"}).join()+");":n.map(function(d,f){return a[f]+" = "+t[f]+" + start["+f+"];"}).join(`
|
|
`);this.userCode=`
|
|
uniform int start[`+this.rank+`];
|
|
void main() {
|
|
`+e+` coords = getOutputCoords();
|
|
`+e+` sourceLoc;
|
|
`+c+`
|
|
vec4 result = vec4(0.);
|
|
`+s+`
|
|
`+u+`
|
|
setOutput(result);
|
|
}
|
|
`}return r.prototype.getCustomSetupFunc=function(n){var e=this;if(n.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+n.length+")");return function(t,a){e.startLoc==null&&(e.startLoc=t.getUniformLocationNoThrow(a,"start"),e.startLoc==null)||t.gl.uniform1iv(e.startLoc,n)}},r}(),Md=function(r,n,e){this.variableNames=["x"],this.outputShape=e;var t=e.length,a=le(e.length),o=le(e.length),i="";if(t===1)i="coords * strides + begin";else{var s=0;i=e.map(function(u,c){return s++,e.length===1?"coords * strides["+c+"] + begin["+c+"]":"coords["+(s-1)+"] * strides["+c+"] + begin["+c+"]"}).join(",")}this.userCode=`
|
|
`+a+" begin = "+a+"("+r+`);
|
|
`+a+" strides = "+a+"("+n+`);
|
|
|
|
void main() {
|
|
`+o+` coords = getOutputCoords();
|
|
setOutput(getX(`+i+`));
|
|
}
|
|
`},Fd=function(){function r(n){this.gpgpu=n,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}return r.prototype.acquireTexture=function(n,e,t){var a,o=_c(e,t),i=Cc(n,o,t);if(i in this.freeTextures||(this.freeTextures[i]=[]),i in this.usedTextures||(this.usedTextures[i]=[]),this.freeTextures[i].length>0){this.numFreeTextures--,this.numUsedTextures++,this.log();var s=this.freeTextures[i].shift();return this.usedTextures[i].push(s),s}return this.numUsedTextures++,this.log(),o===Tn.PACKED_2X2_FLOAT32?a=this.gpgpu.createPackedMatrixTexture(n[0],n[1]):o===Tn.PACKED_2X2_FLOAT16?a=this.gpgpu.createFloat16PackedMatrixTexture(n[0],n[1]):o===Tn.UNPACKED_FLOAT32?a=this.gpgpu.createFloat32MatrixTexture(n[0],n[1]):o===Tn.UNPACKED_FLOAT16?a=this.gpgpu.createFloat16MatrixTexture(n[0],n[1]):o===Tn.PACKED_4X1_UNSIGNED_BYTE&&(a=this.gpgpu.createUnsignedBytesMatrixTexture(n[0],n[1])),this.usedTextures[i].push(a),a},r.prototype.releaseTexture=function(n,e,t,a){if(this.freeTextures!=null){var o=Cc(e,_c(t,a),a);o in this.freeTextures||(this.freeTextures[o]=[]),this.freeTextures[o].push(n),this.numFreeTextures++,this.numUsedTextures--;var i=this.usedTextures[o],s=i.indexOf(n);if(s<0)throw new Error("Cannot release a texture that was never provided by this texture manager");i.splice(s,1),this.log()}},r.prototype.log=function(){if(this.logEnabled){var n=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+n+")")}},r.prototype.getNumUsedTextures=function(){return this.numUsedTextures},r.prototype.getNumFreeTextures=function(){return this.numFreeTextures},r.prototype.dispose=function(){var n=this;if(this.freeTextures!=null){for(var e in this.freeTextures)this.freeTextures[e].forEach(function(t){n.gpgpu.deleteMatrixTexture(t)});for(var e in this.usedTextures)this.usedTextures[e].forEach(function(a){n.gpgpu.deleteMatrixTexture(a)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0}},r}();function _c(r,n){if(r===An.UPLOAD)return Tn.PACKED_2X2_FLOAT32;if(r===An.RENDER||r==null)return function(e){return ee().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?Tn.PACKED_2X2_FLOAT32:Tn.UNPACKED_FLOAT32:e?Tn.PACKED_2X2_FLOAT16:Tn.UNPACKED_FLOAT16}(n);if(r===An.DOWNLOAD||r===An.PIXELS)return Tn.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+r)}function Cc(r,n,e){return r[0]+"_"+r[1]+"_"+n+"_"+e}var Pd=function(r,n){this.variableNames=["A"];for(var e=new Array(r.length),t=0;t<e.length;t++)e[t]=r[t]*n[t];this.outputShape=e,this.rank=e.length;var a=le(this.rank),o=function(i){var s=i.length;if(s>5)throw Error("Tile for rank "+s+" is not yet supported");if(s===1)return"imod(resRC, "+i[0]+")";for(var u=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],c=[],d=0;d<i.length;d++)c.push("imod("+u[d]+", "+i[d]+")");return c.join()}(r);this.userCode=`
|
|
void main() {
|
|
`+a+` resRC = getOutputCoords();
|
|
setOutput(getA(`+o+`));
|
|
}
|
|
`},Ld=function(r,n){this.variableNames=["A"];for(var e=new Array(r.length),t=0;t<e.length;t++)e[t]=r[n[t]];this.outputShape=e,this.rank=e.length;var a=le(this.rank),o=function(i){var s=i.length;if(s>6)throw Error("Transpose for rank "+s+" is not yet supported");for(var u=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],c=new Array(s),d=0;d<i.length;d++)c[i[d]]=u[d];return c.join()}(n);this.userCode=`
|
|
void main() {
|
|
`+a+` resRC = getOutputCoords();
|
|
setOutput(getA(`+o+`));
|
|
}
|
|
`},Bd=function(r,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;for(var e=new Array(r.length),t=0;t<e.length;t++)e[t]=r[n[t]];if(this.outputShape=e,this.rank=e.length,this.rank>6)throw Error("Packed transpose for rank "+this.rank+" is not yet supported.");var a=le(this.rank),o=p("rc",this.rank),i=new Array(this.rank);for(t=0;t<n.length;t++)i[n[t]]=o[t];var s="vec2("+i.slice(-2).join()+")",u="++"+o[this.rank-1]+" < "+e[this.rank-1],c="getChannel(getA("+i.join()+"), "+s+")";this.userCode=`
|
|
void main() {
|
|
`+a+` rc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
result[0] = `+c+`;
|
|
if(`+u+`) {
|
|
result[1] = `+c+`;
|
|
}
|
|
--`+o[this.rank-1]+`;
|
|
if(++`+o[this.rank-2]+" < "+e[this.rank-2]+`) {
|
|
result[2] = `+c+`;
|
|
if(`+u+`) {
|
|
result[3] = `+c+`;
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`},tu=1.7580993408473768,nu=1.0507009873554805,it=function(r,n){this.variableNames=["A"],this.outputShape=r,this.userCode=`
|
|
float unaryOperation(float x) {
|
|
`+n+`
|
|
}
|
|
|
|
void main() {
|
|
float x = getAAtOutCoords();
|
|
float y = unaryOperation(x);
|
|
|
|
setOutput(y);
|
|
}
|
|
`},yr="if (isnan(x)) return x;",jd="return x;",Rc="return abs(x);",Ac=yr+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,Tc=yr+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,Dc="return (x >= 0.0) ? x : (exp(x) - 1.0);",Ud=`
|
|
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
|
|
// see: https://arxiv.org/abs/1706.02515
|
|
float scaleAlpha = `+tu+`;
|
|
float scale = `+nu+`;
|
|
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
|
|
`,Nc="return -x;",kc="return ceil(x);",Sc="return floor(x);",Oc="return exp(x);",Ic="return exp(x) - 1.0;",Wd=yr+`
|
|
return sin(x);
|
|
`,zd=yr+`
|
|
return cos(x);
|
|
`,Vd=yr+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return asin(x);
|
|
`,Gd=yr+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return acos(x);
|
|
`,Hd=yr+`
|
|
return atan(x);
|
|
`,Xd=yr+"return log(x + sqrt(x * x + 1.0));",Kd=yr+`
|
|
if (x < 1.0) return NAN;
|
|
return log(x + sqrt(x * x - 1.0));`,qd=yr+`
|
|
if ((x < -1.0) || (x > 1.0)) return NAN;
|
|
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,Ji="return x;",Yd="return x;",Mc=`
|
|
vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
|
|
bvec4 isNaN = isnan(x);
|
|
|
|
result.r = isNaN.r ? x.r : result.r;
|
|
result.g = isNaN.g ? x.g : result.g;
|
|
result.b = isNaN.b ? x.b : result.b;
|
|
result.a = isNaN.a ? x.a : result.a;
|
|
|
|
return result;
|
|
`,Fc=`
|
|
vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));
|
|
bvec4 isNaN = isnan(x);
|
|
|
|
result.r = isNaN.r ? x.r : result.r;
|
|
result.g = isNaN.g ? x.g : result.g;
|
|
result.b = isNaN.b ? x.b : result.b;
|
|
result.a = isNaN.a ? x.a : result.a;
|
|
|
|
return result;
|
|
`,Pc=`
|
|
vec4 result;
|
|
|
|
result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);
|
|
result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);
|
|
result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);
|
|
result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);
|
|
|
|
return result;
|
|
`,ci=function(r,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=r,this.userCode=`
|
|
vec4 unaryOperation(vec4 x) {
|
|
`+n+`
|
|
}
|
|
|
|
void main() {
|
|
vec4 x = getAAtOutCoords();
|
|
vec4 y = unaryOperation(x);
|
|
|
|
setOutput(y);
|
|
}
|
|
`},$d=function(r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=r;var n=r.length,e=l("rc",n),t=le(n),a=function(s,u){if(s===1)return"rc";for(var c="",d=0;d<s;d++)c+=u[d],d<s-1&&(c+=",");return c}(n,e),o=e.slice(-2),i=n<=1?"rc":"vec2("+o.join(",")+")";this.userCode=`
|
|
void main() {
|
|
`+t+` rc = getOutputCoords();
|
|
vec4 packedInput = getA(`+a+`);
|
|
|
|
setOutput(getChannel(packedInput, `+i+`));
|
|
}
|
|
`},Qi={};function Zi(r,n){if(n===void 0&&(n=!1),r==="linear")return n?Yd:jd;if(r==="relu")return n?Mc:Ac;if(r==="elu")return n?Pc:Dc;if(r==="relu6")return n?Fc:Tc;if(r==="prelu")return n?zn:nn;throw new Error("Activation "+r+" has not been implemented for the WebGL backend.")}var Jd=600,Lc=function(r){function n(e){var t,a=r.call(this)||this;if(a.pendingRead=new WeakMap,a.pendingDisposal=new WeakSet,a.dataRefCount=new WeakMap,a.numBytesInGPU=0,a.uploadWaitMs=0,a.downloadWaitMs=0,a.warnedAboutMemory=!1,a.pendingDeletes=0,a.disposed=!1,!ee().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){var o=or(ee().getNumber("WEBGL_VERSION"));a.binaryCache=((t=ee().getNumber("WEBGL_VERSION"))in Qi||(Qi[t]={}),Qi[t]),a.gpgpu=new bc(o),a.canvas=o.canvas,a.gpgpuCreatedLocally=!0}else a.gpgpu=e,a.binaryCache={},a.gpgpuCreatedLocally=!1,a.canvas=e.gl.canvas;return a.textureManager=new Fd(a.gpgpu),a.numMBBeforeWarning=ee().global.screen==null?1024:ee().global.screen.height*ee().global.screen.width*window.devicePixelRatio*Jd/1024/1024,a.texData=new po(a,X),a}return Ke(n,r),n.prototype.numDataIds=function(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes},n.prototype.write=function(e,t,a){if(ee().getBool("DEBUG")&&this.checkNumericalProblems(e),a==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");var o={};return this.texData.set(o,{shape:t,dtype:a,values:e,usage:An.UPLOAD}),o},n.prototype.move=function(e,t,a,o){if(ee().getBool("DEBUG")&&this.checkNumericalProblems(t),o==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:a,dtype:o,values:t,usage:An.UPLOAD})},n.prototype.readSync=function(e){var t=this.texData.get(e),a=t.values,o=t.dtype,i=t.complexTensors,s=t.slice,u=t.shape,c=t.isPacked;if(s!=null){var d=void 0;d=c?new ci(u,Ji):new it(u,Ji);var f=this.runWebGLProgram(d,[{dataId:e,shape:u,dtype:o}],o),m=this.readSync(f.dataId);return this.disposeData(f.dataId),m}if(a!=null)return this.convertAndCacheOnCPU(e);if(o==="string")return a;var g,x,E=this.activeTimers!=null;return(E&&(g=$()),o==="complex64")?x=yo(i.real.dataSync(),i.imag.dataSync()):x=this.getValuesFromTexture(e),E&&(this.downloadWaitMs+=$()-g),this.convertAndCacheOnCPU(e,x)},n.prototype.read=function(e){return ve(this,void 0,void 0,function(){var t,a,o,i,s,u,c,d,f,m,g,x,E,w,C,N,S,I,M,j,G,z;return ye(this,function(W){switch(W.label){case 0:if(this.pendingRead.has(e))return t=this.pendingRead.get(e),[2,new Promise(function(V){return t.push(V)})];if(a=this.texData.get(e),o=a.values,i=a.shape,s=a.slice,u=a.dtype,c=a.complexTensors,d=a.isPacked,s!=null)return f=void 0,f=d?new ci(i,Ji):new it(i,Ji),m=this.runWebGLProgram(f,[{dataId:e,shape:i,dtype:u}],u),g=this.read(m.dataId),this.disposeData(m.dataId),[2,g];if(o!=null)return[2,this.convertAndCacheOnCPU(e)];if(!ee().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&ee().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");return x=null,u!=="complex64"&&ee().get("WEBGL_BUFFER_SUPPORTED")&&(E=this.decode(e),w=this.texData.get(E.dataId),x=(z=this.gpgpu).createBufferFromTexture.apply(z,[w.texture].concat(Zt(i)))),this.pendingRead.set(e,[]),u==="complex64"?[3,2]:[4,this.gpgpu.createAndWaitForFence()];case 1:W.sent(),W.label=2;case 2:return u!=="complex64"?[3,4]:[4,Promise.all([c.real.data(),c.imag.data()])];case 3:return N=W.sent(),S=N[0],I=N[1],C=yo(S,I),[3,5];case 4:x==null?C=this.getValuesFromTexture(e):(M=ae(i),C=this.gpgpu.downloadFloat32MatrixFromBuffer(x,M)),W.label=5;case 5:return E!=null&&this.disposeData(E.dataId),j=this.convertAndCacheOnCPU(e,C),G=this.pendingRead.get(e),this.pendingRead.delete(e),G.forEach(function(V){return V(j)}),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e),this.pendingDeletes--),[2,j]}})})},n.prototype.checkNumericalProblems=function(e){if(e!=null)for(var t=0;t<e.length;t++){var a=e[t];if(!ds(a))throw ee().getBool("WEBGL_RENDER_FLOAT32_CAPABLE")?Error("The value "+a+" cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'"):Error("The value "+a+" cannot be represented on this device.")}},n.prototype.getValuesFromTexture=function(e){var t,a=this.texData.get(e),o=a.shape,i=a.dtype,s=a.isPacked,u=ae(o);if(ee().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){var c=this.decode(e),d=this.texData.get(c.dataId),f=(t=this.gpgpu).downloadMatrixFromPackedTexture.apply(t,[d.texture].concat(Zt(o))).subarray(0,u);return this.disposeData(c.dataId),f}var m=ee().getBool("WEBGL_PACK")&&s===!0,g=m?na(o):o,x=m?new $s(g):new un(g),E=this.runWebGLProgram(x,[{shape:g,dtype:i,dataId:e}],"float32"),w=this.texData.get(E.dataId),C=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(w.texture,w.texShape[0],w.texShape[1]).subarray(0,u);return this.disposeData(E.dataId),C},n.prototype.time=function(e){return ve(this,void 0,void 0,function(){var t,a,o,i,s,u,c;return ye(this,function(d){switch(d.label){case 0:return t=this.activeTimers,a=[],o=!1,this.programTimersStack==null?(this.programTimersStack=a,o=!0):this.activeTimers.push(a),this.activeTimers=a,e(),i=Ae(this.activeTimers.map(function(f){return f.query})).filter(function(f){return f!=null}),s=Ae(this.activeTimers.map(function(f){return f.name})).filter(function(f){return f!=null}),this.activeTimers=t,o&&(this.programTimersStack=null),u={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null},ee().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?[4,Promise.all(i)]:[3,2];case 1:return c=d.sent(),u.kernelMs=ie(c),u.getExtraProfileInfo=function(){return c.map(function(f,m){return{name:s[m],ms:f}}).map(function(f){return f.name+": "+f.ms}).join(", ")},[3,3];case 2:u.kernelMs={error:"WebGL query timers are not supported in this environment."},d.label=3;case 3:return this.uploadWaitMs=0,this.downloadWaitMs=0,[2,u]}})})},n.prototype.memory=function(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU}},n.prototype.startTimer=function(){return ee().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:$(),endMs:null}},n.prototype.endTimer=function(e){return ee().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=$(),e)},n.prototype.getQueryTime=function(e){return ve(this,void 0,void 0,function(){var t;return ye(this,function(a){return ee().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?[2,this.gpgpu.waitForQueryAndGetTime(e)]:[2,(t=e).endMs-t.startMs]})})},n.prototype.disposeData=function(e){if(!this.pendingDisposal.has(e)){if(this.pendingRead.has(e))return this.pendingDisposal.add(e),void this.pendingDeletes++;if(this.texData.has(e)){this.releaseGPUData(e);var t=this.texData.get(e).complexTensors;t!=null&&(t.real.dispose(),t.imag.dispose()),this.texData.delete(e)}}},n.prototype.releaseGPUData=function(e){var t=this.texData.get(e),a=t.texture,o=t.dtype,i=t.texShape,s=t.usage,u=t.isPacked,c=t.slice,d=c&&c.origDataId||e,f=this.dataRefCount.get(d);f>1?this.dataRefCount.set(d,f-1):(this.dataRefCount.delete(d),a!=null&&(this.numBytesInGPU-=this.computeBytes(i,o),this.textureManager.releaseTexture(a,i,s,u)));var m=this.texData.get(e);m.texture=null,m.texShape=null,m.isPacked=!1,m.slice=null},n.prototype.getTexture=function(e){return this.uploadToGPU(e),this.texData.get(e).texture},n.prototype.getDataInfo=function(e){return this.texData.get(e)},n.prototype.getCPUBackend=function(){return ee().getBool("WEBGL_CPU_FORWARD")?(this.cpuBackend==null&&(this.cpuBackend=X.findBackend("cpu")),this.cpuBackend):null},n.prototype.shouldExecuteOnCPU=function(e,t){var a=this;return t===void 0&&(t=128),this.getCPUBackend()!=null&&e.every(function(o){return a.texData.get(o.dataId).texture==null&&o.size<t})},n.prototype.getGPGPUContext=function(){return this.gpgpu},n.prototype.complex=function(e,t){var a=this.makeOutput(e.shape,"complex64");return this.texData.get(a.dataId).complexTensors={real:X.keep(e.clone()),imag:X.keep(t.clone())},a},n.prototype.real=function(e){return this.texData.get(e.dataId).complexTensors.real.clone()},n.prototype.imag=function(e){return this.texData.get(e.dataId).complexTensors.imag.clone()},n.prototype.slice=function(e,t,a){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.slice(e,t,a);if(ae(a)===0)return _n([],a,e.dtype);var o=this.texData.get(e.dataId).isPacked,i=Ui(e.shape,t,a);if(o||!i){var s=ee().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Id(a):new Od(a),u=s.getCustomSetupFunc(t);return this.compileAndRun(s,[e],null,u)}return this.uploadToGPU(e.dataId),this.shallowSlice(e,t,a)},n.prototype.shallowSlice=function(e,t,a){var o=this.texData.get(e.dataId),i=this.makeOutput(a,e.dtype),s=this.texData.get(i.dataId);Object.assign(s,o),s.shape=a,s.dtype=e.dtype;var u=Wi(t,e.strides);o.slice&&(u+=o.slice.flatOffset),s.slice={flatOffset:u,origDataId:o.slice&&o.slice.origDataId||e.dataId};var c=this.dataRefCount.get(s.slice.origDataId)||1;return this.dataRefCount.set(s.slice.origDataId,c+1),i},n.prototype.stridedSlice=function(e,t,a,o){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.stridedSlice(e,t,a,o);var i=ho(t,a,o);if(i.some(function(u){return u===0}))return _n([],i);var s=new Md(t,o,i);return this.compileAndRun(s,[e])},n.prototype.reverse=function(e,t){var a=ee().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Nd(e.shape,t):new Dd(e.shape,t);return this.compileAndRun(a,[e])},n.prototype.concat=function(e,t){if(e[0].dtype==="complex64"){var a=e.map(function(g){return Hn(g)}),o=e.map(function(g){return cr(g)});return zt(this.concat(a,t),this.concat(o,t))}if(this.shouldExecuteOnCPU(e))return this.cpuBackend.concat(e,t);if(e.length===1)return e[0];if(e.length>ee().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){var i=Math.floor(e.length/2),s=this.concat(e.slice(0,i),t),u=this.concat(e.slice(i),t);return this.concat([s,u],t)}if(ee().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].rank>1){var c=new hr(e.map(function(g){return g.shape}),t);return this.compileAndRun(c,e)}var d=jr(e.map(function(g){return g.shape}),t),f=e.map(function(g){return g.as2D(-1,ae(g.shape.slice(t)))}),m=new Nr(f.map(function(g){return g.shape}));return this.compileAndRun(m,f).reshape(d)},n.prototype.neg=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.neg(e);if(ee().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Nc,e.dtype);var t=new it(e.shape,Nc);return this.compileAndRun(t,[e])},n.prototype.batchMatMul=function(e,t,a,o){var i=a?e.shape[2]:e.shape[1],s=o?t.shape[1]:t.shape[2],u=a?e.shape[1]:e.shape[2],c=e.shape[0];if((i===1||s===1)&&u>1e3){a&&(e=e.transpose([0,2,1])),o&&(t=t.transpose([0,2,1]));var d=s===1?e:e.as3D(c,u,1),f=s===1?2:1,m=s===1?t.as3D(c,1,u):t;return this.multiply(d,m).sum(f,!0)}var g=yn(e.dtype,t.dtype),x=new Js(e.shape,[c,i,s],a,o);return this.compileAndRun(x,[e,t],g)},n.prototype.fusedBatchMatMul=function(e){var t=e.a,a=e.b,o=e.transposeA,i=e.transposeB,s=e.bias,u=e.activation,c=e.preluActivationWeights,d=o?t.shape[2]:t.shape[1],f=i?a.shape[1]:a.shape[2],m=t.shape[0],g=yn(t.dtype,a.dtype),x=s!=null,E=c!=null,w=u?Zi(u,!0):null,C=new Js(t.shape,[m,d,f],o,i,x,w,E),N=[t,a];return s&&N.push(s),c&&N.push(c),this.compileAndRun(C,N,g)},n.prototype.multiply=function(e,t){if(e.dtype==="complex64"){var a=this.texData.get(e.dataId),o=this.texData.get(t.dataId),i=new At(Bt,e.shape,t.shape),s=new At(Yt,e.shape,t.shape),u=[this.makeComplexComponentTensorInfo(e,a.complexTensors.real),this.makeComplexComponentTensorInfo(e,a.complexTensors.imag),this.makeComplexComponentTensorInfo(t,o.complexTensors.real),this.makeComplexComponentTensorInfo(t,o.complexTensors.imag)],c=this.compileAndRun(i,u),d=this.compileAndRun(s,u),f=this.complex(c,d);return c.dispose(),d.dispose(),f}if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.multiply(e,t);if(ee().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,on,e.dtype);var m=new dt(on,e.shape,t.shape);return this.compileAndRun(m,[e,t],e.dtype)},n.prototype.batchNormalization=function(e,t,a,o,i,s){var u=[e,t,a],c=null;s!=null&&(c=s.shape,u.push(s));var d=null;if(i!=null&&(d=i.shape,u.push(i)),ee().getBool("WEBGL_PACK_NORMALIZATION")){var f=new Ze(e.shape,t.shape,a.shape,c,d,o);return this.compileAndRun(f,u)}var m=new Ne(e.shape,t.shape,a.shape,c,d,o);return this.compileAndRun(m,u)},n.prototype.localResponseNormalization4D=function(e,t,a,o,i){var s=ee().getBool("WEBGL_PACK_NORMALIZATION")?new pd(e.shape,t,a,o,i):new dd(e.shape,t,a,o,i);return this.compileAndRun(s,[e])},n.prototype.LRNGrad=function(e,t,a,o,i,s,u){var c=new hd(t.shape,o,i,s,u);return this.compileAndRun(c,[t,a,e])},n.prototype.tile=function(e,t){if(e.dtype==="string"){var a=this.readSync(e.dataId).map(function(i){return ut(i)});return qi(Je(e.shape,e.dtype,a),t)}var o=new Pd(e.shape,t);return this.compileAndRun(o,[e])},n.prototype.pad=function(e,t,a){var o=ee().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new bd(e.shape,t,a):new xd(e.shape,t,a);return this.compileAndRun(o,[e])},n.prototype.transpose=function(e,t){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.transpose(e,t);var a=ee().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Bd(e.shape,t):new Ld(e.shape,t);return this.compileAndRun(a,[e])},n.prototype.gather=function(e,t,a){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.gather(e,t,a);var o=new sd(e.shape,t.size,a);return this.compileAndRun(o,[e,t])},n.prototype.batchToSpaceND=function(e,t,a){D(e.rank<=4,function(){return"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"});var o=t.reduce(function(f,m){return f*m}),i=Na(e.shape,t,o),s=xt(i.length,t.length),u=lo(e.shape,t,o),c=Fs(a,t.length),d=Ps(u,a,t.length);return e.reshape(i).transpose(s).reshape(u).slice(c,d)},n.prototype.spaceToBatchND=function(e,t,a){D(e.rank<=4,function(){return"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"});var o=t.reduce(function(m,g){return m*g}),i=[[0,0]];i.push.apply(i,a);for(var s=1+t.length;s<e.shape.length;++s)i.push([0,0]);var u=e.pad(i),c=Na(u.shape,t,o,!1),d=xt(c.length,t.length,!1),f=lo(u.shape,t,o,!1);return u.reshape(c).transpose(d).reshape(f)},n.prototype.reduce=function(e,t,a){var o=e.shape[0],i=e.shape[1],s=Zo(i),u=new wd({windowSize:s,inSize:i,batchSize:o},t),c=this.compileAndRun(u,[e],a);return c.shape[1]===1?c:this.reduce(c,t,a)},n.prototype.argReduce=function(e,t,a){a===void 0&&(a=null);var o=e.shape[0],i=e.shape[1];a!=null&&(o=a.shape[0],i=a.shape[1]);var s=Zo(i),u=new nc({windowSize:s,inSize:i,batchSize:o},t,a==null),c=[e];a!=null&&c.push(a);var d=this.compileAndRun(u,c,"int32");return d.shape[1]===1?d:this.argReduce(e,t,d)},n.prototype.argReducePacked=function(e,t,a){a===void 0&&(a=null);var o=a!=null?a.shape:e.shape,i=Zo(o[o.length-1]),s=new Ue(o,i,t,a==null),u=a==null?[e]:[e,a],c=this.compileAndRun(s,u,"int32");return c.rank===e.rank?this.argReducePacked(e,t,c):c},n.prototype.sum=function(e,t){Wn("sum",t,e.rank);var a=Nn(e.shape,t),o=a[0],i=ae(a[1]),s=e.as2D(-1,i),u=vn(e.dtype);return this.reduce(s,"sum",u).reshape(o)},n.prototype.prod=function(e,t){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.prod(e,t);var a=Nn(e.shape,t),o=a[0],i=ae(a[1]),s=e.as2D(-1,i),u=vn(e.dtype);return this.reduce(s,"prod",u).reshape(o)},n.prototype.unsortedSegmentSum=function(e,t,a){var o=0,i=Gn([o],e.rank),s=e;i!=null&&(s=e.transpose(i),o=Jn(1,e.rank)[0]);var u=function(g,x,E){for(var w=[],C=g.length,N=0;N<C;N++)N!==x?w.push(g[N]):w.push(E);return w}(s.shape,o,a),c=ae([s.shape[o]]),d=s.as2D(-1,c),f=vn(e.dtype),m=this.segOpCompute(d,"unsortedSegmentSum",t,f,a).reshape(u);return i!=null&&(m=m.transpose(oa(i))),m},n.prototype.segOpCompute=function(e,t,a,o,i){var s=e.shape[0],u=e.shape[1],c=function(m,g){var x,E=!1;for(m<=Li?(x=m,E=!0):x=gn(m,Math.floor(Math.sqrt(m)));!E;)x>g||x===m?E=!0:x=gn(m,x+1);return x}(u,i),d=new kd({windowSize:c,inSize:u,batchSize:s,numSegments:i},t),f=this.compileAndRun(d,[e,a],o);return f.shape[1]===i?f:(a=to(0,i).tile([u/c]),this.segOpCompute(f,t,a,o,i))},n.prototype.argMinMaxReduce=function(e,t,a){var o=[t];if(Wn("arg"+a.charAt(0).toUpperCase()+a.slice(1),o,e.rank),!ee().getBool("WEBGL_PACK_REDUCE")||e.rank<=2){var i=Nn(e.shape,o),s=i[0],u=ae(i[1]),c=e.as2D(-1,u);return this.argReduce(c,a).reshape(s)}return this.argReducePacked(e,a)},n.prototype.argMin=function(e,t){return this.argMinMaxReduce(e,t,"min")},n.prototype.argMax=function(e,t){return this.argMinMaxReduce(e,t,"max")},n.prototype.cumsum=function(e,t,a,o){if(t!==e.rank-1)throw new Error("WebGL cumsum shader expects an inner-most axis="+(e.rank-1)+" but got axis="+t);var i=new wt(e.shape,a,o);return this.compileAndRun(i,[e])},n.prototype.equal=function(e,t){if(ee().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,`
|
|
return vec4(equal(a, b));
|
|
`,"bool");var a=new dt("return float(a == b);",e.shape,t.shape);return this.compileAndRun(a,[e,t],"bool")},n.prototype.notEqual=function(e,t){if(ee().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,`
|
|
return vec4(notEqual(a, b));
|
|
`,"bool");var a=new dt("return float(a != b);",e.shape,t.shape);return this.compileAndRun(a,[e,t],"bool")},n.prototype.less=function(e,t){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.less(e,t);if(ee().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,`
|
|
return vec4(lessThan(a, b));
|
|
`,"bool");var a=new dt("return float(a < b);",e.shape,t.shape);return this.compileAndRun(a,[e,t],"bool")},n.prototype.lessEqual=function(e,t){if(ee().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,`
|
|
return vec4(lessThanEqual(a, b));
|
|
`,"bool");var a=new dt("return float(a <= b);",e.shape,t.shape);return this.compileAndRun(a,[e,t],"bool")},n.prototype.greater=function(e,t){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.greater(e,t);if(ee().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,`
|
|
return vec4(greaterThan(a, b));
|
|
`,"bool");var a=new dt("return float(a > b);",e.shape,t.shape);return this.compileAndRun(a,[e,t],"bool")},n.prototype.greaterEqual=function(e,t){if(ee().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,`
|
|
return vec4(greaterThanEqual(a, b));
|
|
`,"bool");var a=new dt("return float(a >= b);",e.shape,t.shape);return this.compileAndRun(a,[e,t],"bool")},n.prototype.logicalNot=function(e){var t=new it(e.shape,"return float(!(x >= 1.0));");return this.compileAndRun(t,[e])},n.prototype.logicalAnd=function(e,t){if(ee().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,`
|
|
return vec4(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) *
|
|
vec4(greaterThanEqual(b, vec4(1.0))));
|
|
`,"bool");var a=new dt("return float(a >= 1.0 && b >= 1.0);",e.shape,t.shape);return this.compileAndRun(a,[e,t],"bool")},n.prototype.logicalOr=function(e,t){if(ee().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,`
|
|
return min(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) +
|
|
vec4(greaterThanEqual(b, vec4(1.0))),
|
|
vec4(1.0));
|
|
`,"bool");var a=new dt("return float(a >= 1.0 || b >= 1.0);",e.shape,t.shape);return this.compileAndRun(a,[e,t],"bool")},n.prototype.select=function(e,t,a){var o=new Sd(e.rank,t.shape,t.rank);return this.compileAndRun(o,[e,t,a],yn(t.dtype,a.dtype))},n.prototype.where=function(e){eo("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var t=e.dataSync();return Yi(e.shape,t)},n.prototype.topk=function(e,t,a){return qs(e.dataSync(),e.shape,e.dtype,t)},n.prototype.min=function(e,t){Wn("min",t,e.rank);var a=Nn(e.shape,t),o=a[0],i=ae(a[1]),s=e.as2D(-1,i);return this.reduce(s,"min",s.dtype).reshape(o)},n.prototype.minimum=function(e,t){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.minimum(e,t);var a=ee().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ie(`
|
|
vec4 result = vec4(min(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
|
|
result.r = isNaN.r > 0. ? NAN : result.r;
|
|
result.g = isNaN.g > 0. ? NAN : result.g;
|
|
result.b = isNaN.b > 0. ? NAN : result.b;
|
|
result.a = isNaN.a > 0. ? NAN : result.a;
|
|
|
|
return result;
|
|
`,e.shape,t.shape):new dt(`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
|
|
return min(a, b);
|
|
`,e.shape,t.shape);return this.compileAndRun(a,[e,t])},n.prototype.mod=function(e,t){var a=ee().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ie(`
|
|
vec4 result = mod(a, b);
|
|
vec4 isNaN = vec4(equal(b, vec4(0.0)));
|
|
|
|
result.r = isNaN.r > 0. ? NAN : result.r;
|
|
result.g = isNaN.g > 0. ? NAN : result.g;
|
|
result.b = isNaN.b > 0. ? NAN : result.b;
|
|
result.a = isNaN.a > 0. ? NAN : result.a;
|
|
|
|
return result;
|
|
`,e.shape,t.shape):new dt(`if (b == 0.0) return NAN;
|
|
return mod(a, b);`,e.shape,t.shape);return this.compileAndRun(a,[e,t])},n.prototype.max=function(e,t){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.max(e,t);Wn("max",t,e.rank);var a=Nn(e.shape,t),o=a[0],i=ae(a[1]),s=e.as2D(-1,i);return this.reduce(s,"max",s.dtype).reshape(o)},n.prototype.maximum=function(e,t){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.maximum(e,t);var a=ee().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ie(`
|
|
vec4 result = vec4(max(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
|
|
result.r = isNaN.r > 0. ? NAN : result.r;
|
|
result.g = isNaN.g > 0. ? NAN : result.g;
|
|
result.b = isNaN.b > 0. ? NAN : result.b;
|
|
result.a = isNaN.a > 0. ? NAN : result.a;
|
|
|
|
return result;
|
|
`,e.shape,t.shape):new dt(`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
|
|
return max(a, b);
|
|
`,e.shape,t.shape);return this.compileAndRun(a,[e,t])},n.prototype.all=function(e,t){Wn("all",t,e.rank);var a=Nn(e.shape,t),o=a[0],i=ae(a[1]),s=e.as2D(-1,i);return this.reduce(s,"all",s.dtype).reshape(o)},n.prototype.any=function(e,t){Wn("any",t,e.rank);var a=Nn(e.shape,t),o=a[0],i=ae(a[1]),s=e.as2D(-1,i);return this.reduce(s,"any",s.dtype).reshape(o)},n.prototype.realDivide=function(e,t){if(ee().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,`
|
|
// vec4 one = vec4(equal(a, b));
|
|
// return one + (vec4(1.0) - one) * a / b;
|
|
vec4 result = a / b;
|
|
if(a.x == b.x) {
|
|
result.x = 1.;
|
|
}
|
|
if(a.y == b.y) {
|
|
result.y = 1.;
|
|
}
|
|
if(a.z == b.z) {
|
|
result.z = 1.;
|
|
}
|
|
if(a.w == b.w) {
|
|
result.w = 1.;
|
|
}
|
|
|
|
return result;
|
|
`,"float32",!0);var a=new dt(`
|
|
if (a == b) {
|
|
return 1.0;
|
|
};
|
|
return a / b;`,e.shape,t.shape);return this.compileAndRun(a,[e,t],"float32")},n.prototype.floorDiv=function(e,t){if(ee().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,`
|
|
ivec4 ia = round(a);
|
|
ivec4 ib = round(b);
|
|
bvec4 cond = notEqual(ib, ivec4(0));
|
|
ivec4 result = ivec4(0);
|
|
vec4 s = sign(a) * sign(b);
|
|
|
|
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
|
|
if (cond[0]) {
|
|
result[0] = idiv(ia[0], ib[0], s[0]);
|
|
}
|
|
if (cond[1]) {
|
|
result[1] = idiv(ia[1], ib[1], s[1]);
|
|
}
|
|
if (cond[2]) {
|
|
result[2] = idiv(ia[2], ib[2], s[2]);
|
|
}
|
|
if (cond[3]) {
|
|
result[3] = idiv(ia[3], ib[3], s[3]);
|
|
}
|
|
return vec4(result);
|
|
`,"int32");var a=new dt(`
|
|
float s = sign(a) * sign(b);
|
|
int ia = round(a);
|
|
int ib = round(b);
|
|
if (ib != 0) {
|
|
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
|
|
return float(idiv(ia, ib, s));
|
|
} else {
|
|
return NAN;
|
|
}
|
|
`,e.shape,t.shape);return this.compileAndRun(a,[e,t],"int32")},n.prototype.add=function(e,t){if(e.dtype==="complex64"&&t.dtype==="complex64")return this.complexSeparableBinaryOp(e,t,rt);if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.add(e,t);var a=yn(e.dtype,t.dtype);if(ee().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,rt,a);var o=new dt(rt,e.shape,t.shape);return this.compileAndRun(o,[e,t],a)},n.prototype.packedUnaryOp=function(e,t,a){var o=new ci(e.shape,t);return this.compileAndRun(o,[e],a)},n.prototype.packedBinaryOp=function(e,t,a,o,i){i===void 0&&(i=!1);var s=new Ie(a,e.shape,t.shape,i);return this.compileAndRun(s,[e,t],o)},n.prototype.complexSeparableBinaryOp=function(e,t,a){var o=this,i=this.texData.get(e.dataId),s=this.texData.get(t.dataId),u=[[i.complexTensors.real,s.complexTensors.real],[i.complexTensors.imag,s.complexTensors.imag]].map(function(m){var g=m[0],x=m[1],E=o.makeComplexComponentTensorInfo(e,g),w=o.makeComplexComponentTensorInfo(t,x),C=new dt(a,e.shape,t.shape);return o.compileAndRun(C,[E,w],yn(g.dtype,x.dtype))}),c=u[0],d=u[1],f=this.complex(c,d);return c.dispose(),d.dispose(),f},n.prototype.makeComplexComponentTensorInfo=function(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}},n.prototype.addN=function(e){if(e.length===1)return e[0];if(e.length>ee().get("WEBGL_MAX_TEXTURES_IN_SHADER")){var t=Math.floor(e.length/2),a=this.addN(e.slice(0,t)),o=this.addN(e.slice(t));return this.addN([a,o])}var i=e.map(function(c){return c.dtype}).reduce(function(c,d){return yn(c,d)}),s=e.map(function(c){return c.shape}),u=ee().getBool("WEBGL_PACK")?new Ys(e[0].shape,s):new tc(e[0].shape,s);return this.compileAndRun(u,e,i)},n.prototype.subtract=function(e,t){if(e.dtype==="complex64"&&t.dtype==="complex64")return this.complexSeparableBinaryOp(e,t,Kt);if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.subtract(e,t);var a=yn(e.dtype,t.dtype);if(ee().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,Kt,e.dtype);var o=new dt(Kt,e.shape,t.shape);return this.compileAndRun(o,[e,t],a)},n.prototype.pow=function(e,t){var a=ee().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ie(`
|
|
// isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.
|
|
vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));
|
|
vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);
|
|
vec4 result = multiplier * pow(abs(a), b);
|
|
|
|
// Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS
|
|
bvec4 isExpZero = equal(b, vec4(0.0));
|
|
result.r = isExpZero.r ? 1.0 : result.r;
|
|
result.g = isExpZero.g ? 1.0 : result.g;
|
|
result.b = isExpZero.b ? 1.0 : result.b;
|
|
result.a = isExpZero.a ? 1.0 : result.a;
|
|
|
|
vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));
|
|
|
|
result.r = isNaN.r > 0. ? NAN : result.r;
|
|
result.g = isNaN.g > 0. ? NAN : result.g;
|
|
result.b = isNaN.b > 0. ? NAN : result.b;
|
|
result.a = isNaN.a > 0. ? NAN : result.a;
|
|
|
|
return result;
|
|
`,e.shape,t.shape):new dt(`
|
|
if(a < 0.0 && floor(b) < b){
|
|
return NAN;
|
|
}
|
|
if (b == 0.0) {
|
|
return 1.0;
|
|
}
|
|
return (round(mod(b, 2.0)) != 1) ?
|
|
pow(abs(a), b) : sign(a) * pow(abs(a), b);
|
|
`,e.shape,t.shape),o=yn(e.dtype,t.dtype);return this.compileAndRun(a,[e,t],o)},n.prototype.ceil=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.ceil(e);if(ee().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,kc,e.dtype);var t=new it(e.shape,kc);return this.compileAndRun(t,[e])},n.prototype.floor=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.floor(e);if(ee().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Sc,e.dtype);var t=new it(e.shape,Sc);return this.compileAndRun(t,[e])},n.prototype.sign=function(e){var t=new it(e.shape,`
|
|
if (isnan(x)) { return 0.0; }
|
|
return sign(x);
|
|
`);return this.compileAndRun(t,[e])},n.prototype.isNaN=function(e){var t=new it(e.shape,"return float(isnan(x));");return this.compileAndRun(t,[e],"bool")},n.prototype.isInf=function(e){var t=new it(e.shape,"return float(isinf(x));");return this.compileAndRun(t,[e],"bool")},n.prototype.isFinite=function(e){var t=new it(e.shape,"return float(!isnan(x) && !isinf(x));");return this.compileAndRun(t,[e],"bool")},n.prototype.round=function(e){var t=new it(e.shape,`
|
|
// OpenGL ES does not support round function.
|
|
// The algorithm is based on banker's rounding.
|
|
float base = floor(x);
|
|
if ((x - base) < 0.5) {
|
|
return floor(x);
|
|
} else if ((x - base) > 0.5) {
|
|
return ceil(x);
|
|
} else {
|
|
if (mod(base, 2.0) == 0.0) {
|
|
return base;
|
|
} else {
|
|
return base + 1.0;
|
|
}
|
|
}
|
|
`);return this.compileAndRun(t,[e])},n.prototype.exp=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.exp(e);if(ee().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Oc,e.dtype);var t=new it(e.shape,Oc);return this.compileAndRun(t,[e])},n.prototype.expm1=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.expm1(e);if(ee().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Ic,e.dtype);var t=new it(e.shape,Ic);return this.compileAndRun(t,[e])},n.prototype.softmax=function(e,t){var a=je([t],e.shape),o=this.max(e,a),i=kn(o.shape,a),s=this.subtract(e,o.reshape(i)),u=this.exp(s),c=this.sum(u,a).reshape(i);return this.realDivide(u,c)},n.prototype.log=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.log(e);if(ee().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,`
|
|
vec4 result = log(x);
|
|
vec4 isNaN = vec4(lessThan(x, vec4(0.0)));
|
|
result.r = isNaN.r == 1.0 ? NAN : result.r;
|
|
result.g = isNaN.g == 1.0 ? NAN : result.g;
|
|
result.b = isNaN.b == 1.0 ? NAN : result.b;
|
|
result.a = isNaN.a == 1.0 ? NAN : result.a;
|
|
|
|
return result;
|
|
`,e.dtype);var t=new it(e.shape,`if (x < 0.0) return NAN;
|
|
return log(x);`);return this.compileAndRun(t,[e])},n.prototype.log1p=function(e){var t=new it(e.shape,"return log(1.0 + x);");return this.compileAndRun(t,[e])},n.prototype.sqrt=function(e){var t=new it(e.shape,"return sqrt(x);");return this.compileAndRun(t,[e])},n.prototype.rsqrt=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.rsqrt(e);var t=new it(e.shape,"return inversesqrt(x);");return this.compileAndRun(t,[e])},n.prototype.reciprocal=function(e){var t=new it(e.shape,"return 1.0 / x;");return this.compileAndRun(t,[e])},n.prototype.relu=function(e){var t;return t=ee().getBool("WEBGL_PACK")?new ci(e.shape,Mc):new it(e.shape,Ac),this.compileAndRun(t,[e])},n.prototype.relu6=function(e){var t;return t=ee().getBool("WEBGL_PACK")?new ci(e.shape,Fc):new it(e.shape,Tc),this.compileAndRun(t,[e])},n.prototype.prelu=function(e,t){var a=ee().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ie(zn,e.shape,t.shape):new dt(nn,e.shape,t.shape);return this.compileAndRun(a,[e,t])},n.prototype.elu=function(e){if(ee().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Pc,e.dtype);var t=new it(e.shape,Dc);return this.compileAndRun(t,[e])},n.prototype.eluDer=function(e,t){var a=ee().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ie(`
|
|
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
|
|
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
|
|
`,e.shape,t.shape):new dt("return (b >= 1.0) ? a : a * (b + 1.0);",e.shape,t.shape);return this.compileAndRun(a,[e,t])},n.prototype.selu=function(e){var t=new it(e.shape,Ud);return this.compileAndRun(t,[e])},n.prototype.int=function(e){var t=new it(e.shape,"return float(int(x));");return this.compileAndRun(t,[e],"int32")},n.prototype.clip=function(e,t,a){var o,i=(o=ee().getBool("WEBGL_PACK_CLIP")?new Ot(e.shape):new Sn(e.shape)).getCustomSetupFunc(t,a);return this.compileAndRun(o,[e],null,i)},n.prototype.abs=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.abs(e);if(ee().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Rc,e.dtype);var t=new it(e.shape,Rc);return this.compileAndRun(t,[e])},n.prototype.complexAbs=function(e){var t=this.texData.get(e.dataId),a=new sn(e.shape),o=[this.makeComplexComponentTensorInfo(e,t.complexTensors.real),this.makeComplexComponentTensorInfo(e,t.complexTensors.imag)];return this.compileAndRun(a,o)},n.prototype.sigmoid=function(e){var t=new it(e.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(t,[e])},n.prototype.softplus=function(e){var t=new it(e.shape,`
|
|
float epsilon = 1.1920928955078125e-7;
|
|
float threshold = log(epsilon) + 2.0;
|
|
|
|
bool too_large = x > -threshold;
|
|
bool too_small = x < threshold;
|
|
|
|
float result;
|
|
float exp_x = exp(x);
|
|
|
|
if (too_large){
|
|
result = x;
|
|
}
|
|
else if (too_small){
|
|
result = exp_x;
|
|
}
|
|
else{
|
|
result = log(exp_x + 1.0);
|
|
}
|
|
return result;
|
|
`);return this.compileAndRun(t,[e])},n.prototype.sin=function(e){var t=new it(e.shape,Wd);return this.compileAndRun(t,[e])},n.prototype.cos=function(e){var t=new it(e.shape,zd);return this.compileAndRun(t,[e])},n.prototype.tan=function(e){var t=new it(e.shape,"return tan(x);");return this.compileAndRun(t,[e])},n.prototype.asin=function(e){var t=new it(e.shape,Vd);return this.compileAndRun(t,[e])},n.prototype.acos=function(e){var t=new it(e.shape,Gd);return this.compileAndRun(t,[e])},n.prototype.atan=function(e){var t=new it(e.shape,Hd);return this.compileAndRun(t,[e])},n.prototype.atan2=function(e,t){var a=ee().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ie(`
|
|
vec4 result = atan(a, b);
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
|
|
result.r = isNaN.r > 0. ? NAN : result.r;
|
|
result.g = isNaN.g > 0. ? NAN : result.g;
|
|
result.b = isNaN.b > 0. ? NAN : result.b;
|
|
result.a = isNaN.a > 0. ? NAN : result.a;
|
|
|
|
return result;
|
|
`,e.shape,t.shape):new dt(`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
|
|
return atan(a, b);
|
|
`,e.shape,t.shape);return this.compileAndRun(a,[e,t])},n.prototype.sinh=function(e){var t=new it(e.shape,`
|
|
float e2x = exp(x);
|
|
return (e2x - 1.0 / e2x) / 2.0;
|
|
`);return this.compileAndRun(t,[e])},n.prototype.cosh=function(e){var t=new it(e.shape,`
|
|
float e2x = exp(-x);
|
|
return (e2x + 1.0 / e2x) / 2.0;
|
|
`);return this.compileAndRun(t,[e])},n.prototype.tanh=function(e){var t=new it(e.shape,`
|
|
float e2x = exp(-2.0 * abs(x));
|
|
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
|
|
`);return this.compileAndRun(t,[e])},n.prototype.asinh=function(e){var t=new it(e.shape,Xd);return this.compileAndRun(t,[e])},n.prototype.acosh=function(e){var t=new it(e.shape,Kd);return this.compileAndRun(t,[e])},n.prototype.atanh=function(e){var t=new it(e.shape,qd);return this.compileAndRun(t,[e])},n.prototype.erf=function(e){var t=new it(e.shape,`
|
|
// Error function is calculated approximately with elementary function.
|
|
// See "Handbook of Mathematical Functions with Formulas,
|
|
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
|
|
float p = 0.3275911;
|
|
float a1 = 0.254829592;
|
|
float a2 = -0.284496736;
|
|
float a3 = 1.421413741;
|
|
float a4 = -1.453152027;
|
|
float a5 = 1.061405429;
|
|
|
|
float sign = sign(x);
|
|
x = abs(x);
|
|
float t = 1.0 / (1.0 + p * x);
|
|
return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));
|
|
`);return this.compileAndRun(t,[e])},n.prototype.step=function(e,t){var a=new it(e.shape,function(o){return o===void 0&&(o=0),yr+`
|
|
return x > 0.0 ? 1.0 : float(`+o+`);
|
|
`}(t));return this.compileAndRun(a,[e])},n.prototype.conv2dByMatMul=function(e,t,a,o,i,s){var u=e.shape,c=this.texData.get(e.dataId),d=a.inChannels,f=u[0]*u[1]*u[2],m=a.outChannels,g=a.dataFormat==="channelsLast",x=(f===1||m===1)&&d>1e3,E=u[2]%2!=0&&!!c.isPacked;if(x||!ee().getBool("WEBGL_LAZILY_UNPACK")||!ee().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!E){var w=g?u[0]*u[1]*u[2]:u[0]*u[2]*u[3],C=this.reshape(e,[1,w,a.inChannels]),N=this.reshape(t,[1,a.inChannels,a.outChannels]);return this.reshape(this.fusedBatchMatMul({a:C,b:N,transposeA:!1,transposeB:!1,bias:o,activation:i,preluActivationWeights:s}),a.outShape)}var S=g?u[0]*u[1]*(u[2]+1):u[0]*u[2]*(u[3]+1),I={dataId:e.dataId,shape:[1,S,a.inChannels],dtype:e.dtype},M=c.shape;c.shape=c.shape.slice(),c.shape[c.shape.length-2]++,D(ra(c.shape,I.shape),function(){return"packed reshape "+c.shape+" to "+I.shape+" isn't free"});var j=this.reshape(t,[1,a.inChannels,a.outChannels]),G=this.fusedBatchMatMul({a:I,b:j,transposeA:!1,transposeB:!1,bias:o,activation:i,preluActivationWeights:s}),z=this.texData.get(G.dataId);return D(z.isPacked,function(){return"batchMatMul result is expected to be packed"}),c.shape=M,z.shape=a.outShape,X.makeTensorFromDataId(G.dataId,a.outShape,G.dtype)},n.prototype.conv2dWithIm2Row=function(e,t,a,o,i,s){var u=a.filterWidth,c=a.filterHeight,d=a.inChannels,f=a.outWidth,m=a.outHeight,g=a.dataFormat==="channelsLast",x=u*c*d,E=m*f,w=[x,E],C=e.squeeze([0]),N=t.reshape([1,x,-1]),S=new ld(w,C.shape,a),I=this.compileAndRun(S,[C]).reshape([1,w[0],w[1]]),M=o!=null,j=s!=null,G=i?Zi(i,!0):null,z=new Js(I.shape,[1,E,a.outChannels],!0,!1,M,G,j),W=[I,N];o&&W.push(o),j&&W.push(s);var V=this.compileAndRun(z,W);return g?V.reshape([1,m,f,a.outChannels]):V.reshape([1,a.outChannels,m,f])},n.prototype.fusedConv2d=function(e){var t=e.input,a=e.filter,o=e.convInfo,i=e.bias,s=e.activation,u=e.preluActivationWeights;if(o.filterHeight===1&&o.filterWidth===1&&o.dilationHeight===1&&o.dilationWidth===1&&o.strideHeight===1&&o.strideWidth===1&&(o.padInfo.type==="SAME"||o.padInfo.type==="VALID"))return this.conv2dByMatMul(t,a,o,i,s,u);if(ee().getBool("WEBGL_CONV_IM2COL")&&t.shape[0]===1)return this.conv2dWithIm2Row(t,a,o,i,s,u);var c=i!=null,d=u!=null,f=s?Zi(s,!1):null,m=new Xn(o,c,f,d),g=[t,a];return i&&g.push(i),u&&g.push(u),this.compileAndRun(m,g)},n.prototype.conv2d=function(e,t,a){if(a.filterHeight===1&&a.filterWidth===1&&a.dilationHeight===1&&a.dilationWidth===1&&a.strideHeight===1&&a.strideWidth===1&&(a.padInfo.type==="SAME"||a.padInfo.type==="VALID"))return this.conv2dByMatMul(e,t,a);if(ee().getBool("WEBGL_CONV_IM2COL")&&e.shape[0]===1)return this.conv2dWithIm2Row(e,t,a);var o=new Xn(a);return this.compileAndRun(o,[e,t])},n.prototype.conv2dDerInput=function(e,t,a){var o=new Fa(a);return this.compileAndRun(o,[e,t])},n.prototype.conv2dDerFilter=function(e,t,a){var o=new pa(a);return this.compileAndRun(o,[e,t])},n.prototype.fusedDepthwiseConv2D=function(e){var t,a=e.input,o=e.filter,i=e.convInfo,s=e.bias,u=e.activation,c=e.preluActivationWeights,d=ee().getBool("WEBGL_PACK_DEPTHWISECONV")&&i.strideWidth<=2&&i.outChannels/i.inChannels==1,f=u?Zi(u,d):null,m=[a,o],g=s!=null,x=c!=null;return g&&m.push(s),x&&m.push(c),d?(t=new ft(i,g,f,x),this.compileAndRun(t,m)):(t=new yt(i,g,f,x),this.compileAndRun(t,m))},n.prototype.depthwiseConv2D=function(e,t,a){var o;return ee().getBool("WEBGL_PACK_DEPTHWISECONV")&&a.strideWidth<=2&&a.outChannels/a.inChannels==1?(o=new ft(a),this.compileAndRun(o,[e,t])):(o=new yt(a),this.compileAndRun(o,[e,t]))},n.prototype.depthwiseConv2DDerInput=function(e,t,a){var o=new Vt(a);return this.compileAndRun(o,[e,t])},n.prototype.depthwiseConv2DDerFilter=function(e,t,a){var o=new ct(a);return this.compileAndRun(o,[e,t])},n.prototype.conv3d=function(e,t,a){var o=new bt(a);return this.compileAndRun(o,[e,t])},n.prototype.conv3dDerInput=function(e,t,a){var o=new He(a);return this.compileAndRun(o,[e,t])},n.prototype.conv3dDerFilter=function(e,t,a){var o=new jt(a);return this.compileAndRun(o,[e,t])},n.prototype.maxPool=function(e,t){var a=new Qs(t,"max",!1);return this.compileAndRun(a,[e])},n.prototype.avgPool=function(e,t){var a=new Qs(t,"avg",!1);return this.compileAndRun(a,[e],"float32")},n.prototype.maxPoolBackprop=function(e,t,a,o){var i=new Qs(o,"max",!0),s=this.compileAndRun(i,[t]),u=new fd(o),c=this.compileAndRun(u,[e,s],t.dtype);return s.dispose(),c},n.prototype.avgPoolBackprop=function(e,t,a){var o=new Fe(a);return this.compileAndRun(o,[e],t.dtype)},n.prototype.cast=function(e,t){return ri(e,t,this)},n.prototype.unstack=function(e,t){for(var a=e.shape[t],o=new Array(e.rank-1),i=0,s=0;s<e.rank;s++)s!==t&&(o[i++]=e.shape[s]);var u=new Array(e.rank).fill(0),c=e.shape.slice();c[t]=1;var d=new Array(a);for(s=0;s<d.length;s++)u[t]=s,d[s]=this.slice(e,u,c).reshape(o);return d},n.prototype.avgPool3d=function(e,t){var a=new Zs(t,"avg",!1);return this.compileAndRun(a,[e],"float32")},n.prototype.avgPool3dBackprop=function(e,t,a){var o=new we(a);return this.compileAndRun(o,[e],t.dtype)},n.prototype.maxPool3d=function(e,t){var a=new Zs(t,"max",!1);return this.compileAndRun(a,[e],"float32")},n.prototype.maxPool3dBackprop=function(e,t,a,o){var i=new Zs(o,"max",!0),s=this.compileAndRun(i,[t]),u=new vd(o),c=this.compileAndRun(u,[e,s],t.dtype);return s.dispose(),c},n.prototype.reshape=function(e,t){var a=this.texData.get(e.dataId);if(a.isPacked&&!ra(e.shape,t)&&(a.texture===null||!ra(a.shape,t))){var o=this.packedReshape(e,t);return X.makeTensorFromDataId(o.dataId,o.shape,o.dtype)}return go(e,t)},n.prototype.resizeBilinear=function(e,t,a,o){var i=ee().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new Rd(e.shape,t,a,o):new Cd(e.shape,t,a,o);return this.compileAndRun(i,[e],"float32")},n.prototype.resizeBilinearBackprop=function(e,t,a){var o=new _d(e,t,a);return this.compileAndRun(o,[e])},n.prototype.resizeNearestNeighbor=function(e,t,a,o){var i=new Td(e.shape,t,a,o);return this.compileAndRun(i,[e])},n.prototype.resizeNearestNeighborBackprop=function(e,t,a){var o=new Ad(e,t,a);return this.compileAndRun(o,[e])},n.prototype.multinomial=function(e,t,a,o){var i=t?e:Sa(e),s=i.shape[0],u=i.shape[1],c=new md(s,u,a),d=c.getCustomSetupFunc(o);return this.compileAndRun(c,[i],"int32",d)},n.prototype.oneHot=function(e,t,a,o){var i=new gd(e.size,t,a,o);return this.compileAndRun(i,[e])},n.prototype.diag=function(e){var t=new fa(e.size);return this.compileAndRun(t,[e])},n.prototype.nonMaxSuppression=function(e,t,a,o,i){return eo("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead"),ai(e.dataSync(),t.dataSync(),a,o,i)},n.prototype.cropAndResize=function(e,t,a,o,i,s){var u=new Lt(e.shape,t.shape,o,i,s);return this.compileAndRun(u,[e,t,a],"float32")},n.prototype.depthToSpace=function(e,t,a){D(t>1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+t});var o=e.shape[0],i=a==="NHWC"?e.shape[1]:e.shape[2],s=a==="NHWC"?e.shape[2]:e.shape[3],u=a==="NHWC"?e.shape[3]:e.shape[1],c=i*t,d=s*t,f=u/(t*t),m=new Sr(a==="NHWC"?[o,c,d,f]:[o,f,c,d],t,a);return this.compileAndRun(m,[e])},n.prototype.split=function(e,t,a){return Ki(e,t,a)},n.prototype.scatterND=function(e,t,a){var o=ka(0,e,a),i=o.sliceRank,s=o.numUpdates,u=o.sliceSize,c=o.strides,d=o.outputSize,f=[d/u,u],m=e.reshape([s,i]),g=t.reshape([s,u]);if(d===0)return go(_n([]),a);var x=We(0),E=new Ec(s,i,m.rank,g.rank,c,f);return this.compileAndRun(E,[g,m,x]).reshape(a)},n.prototype.sparseToDense=function(e,t,a,o){var i=ka(0,e,a),s=i.sliceRank,u=i.numUpdates,c=i.strides,d=i.outputSize,f=new Ec(u,s,e.rank,t.rank,c,[d,1],!1);return this.compileAndRun(f,[t,e,o]).reshape(a)},n.prototype.fft=function(e){return this.fftImpl(e,!1)},n.prototype.ifft=function(e){return this.fftImpl(e,!0)},n.prototype.fftImpl=function(e,t){var a=this.texData.get(e.dataId),o=new rc($i,e.shape,t),i=new rc(od,e.shape,t),s=[this.makeComplexComponentTensorInfo(e,a.complexTensors.real),this.makeComplexComponentTensorInfo(e,a.complexTensors.imag)],u=this.compileAndRun(o,s),c=this.compileAndRun(i,s),d=this.complex(u,c).as2D(e.shape[0],e.shape[1]);return u.dispose(),c.dispose(),d},n.prototype.gatherND=function(e,t){var a=t.shape,o=a[a.length-1],i=Pi(e,t),s=i[0],u=i[1],c=i[2],d=i[3],f=t.reshape([u,o]),m=e.reshape([e.size/c,c]),g=new ud(o,d,[u,c]);return this.compileAndRun(g,[m,f]).reshape(s)},n.prototype.fill=function(e,t,a){if((a=a||ar(t))==="string"){var o=bn(a,ae(e));return o.fill(t),X.makeTensor(o,e,a,this)}var i=new id(e,t),s=i.getCustomSetupFunc(t);return this.compileAndRun(i,[],a,s)},n.prototype.onesLike=function(e){if(e.dtype==="string")throw new Error("onesLike is not supported under string dtype");return this.fill(e.shape,1,e.dtype)},n.prototype.zerosLike=function(e){return this.fill(e.shape,e.dtype==="string"?"":0,e.dtype)},n.prototype.linspace=function(e,t,a){return Vi(e,t,a)},n.prototype.makeTensorInfo=function(e,t){var a=this.write(null,e,t);return this.texData.get(a).usage=null,{dataId:a,shape:e,dtype:t}},n.prototype.makeOutput=function(e,t){var a=this.makeTensorInfo(e,t).dataId;return X.makeTensorFromDataId(a,e,t,this)},n.prototype.unpackTensor=function(e){var t=new $d(e.shape);return this.runWebGLProgram(t,[e],e.dtype)},n.prototype.packTensor=function(e){var t=new yd(e.shape);return this.runWebGLProgram(t,[e],e.dtype,null,!0)},n.prototype.packedReshape=function(e,t){var a=[ea(e.shape)].concat(ta(e.shape)),o={dtype:e.dtype,shape:a,dataId:e.dataId},i=[ea(t)].concat(ta(t)),s=new Ed(i,a),u=this.runWebGLProgram(s,[o],e.dtype,null,!0);return{dataId:u.dataId,shape:t,dtype:u.dtype}},n.prototype.decode=function(e){var t,a=this.texData.get(e),o=a.isPacked,i=a.shape,s=a.dtype,u=na(i);return t=o?new Gr(u):new Gt(u),{dtype:s,shape:i,dataId:this.runWebGLProgram(t,[{shape:u,dtype:s,dataId:e}],s,null,!0).dataId}},n.prototype.runWebGLProgram=function(e,t,a,o,i){var s=this;i===void 0&&(i=!1);var u=this.makeTensorInfo(e.outputShape,a),c=this.texData.get(u.dataId);if(e.packedOutput&&(c.isPacked=!0),e.outPackingScheme===Ea.DENSE){var d=Zt(e.outputShape);c.texShape=d.map(function(S){return 2*S})}if(e.outTexUsage!=null&&(c.usage=e.outTexUsage),ae(u.shape)===0)return c.values=Cn(u.dtype,0),u;var f=[],m=t.map(function(S){if(S.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");var I=s.texData.get(S.dataId);if(I.texture==null){if(!e.packedInputs&&ae(S.shape)<=ee().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:S.shape,texData:null,isUniform:!0,uniformValues:I.values};e.packedInputs&&(I.isPacked=!0,I.shape=S.shape)}else if(!!I.isPacked!=!!e.packedInputs)S=I.isPacked?s.unpackTensor(S):s.packTensor(S),f.push(S),I=s.texData.get(S.dataId);else if(I.isPacked&&!ra(I.shape,S.shape)){var M=S,j=S.shape;S.shape=I.shape,S=s.packedReshape(S,j),f.push(S),I=s.texData.get(S.dataId),M.shape=j}return s.uploadToGPU(S.dataId),{shape:S.shape,texData:I,isUniform:!1}});this.uploadToGPU(u.dataId);var g,x={shape:u.shape,texData:c,isUniform:!1},E=function(S,I,M){var j="";I.concat(M).forEach(function(W){var V=W.texData!=null&&W.texData.slice!=null&&W.texData.slice.flatOffset>0,Z=W.isUniform?"uniform":W.texData.texShape;j+=W.shape+"_"+Z+"_"+V});var G=S.userCode,z=S.constructor.name;return z+="_"+j+"_"+G}(e,m,x),w=this.getAndSaveBinary(E,function(){return function(S,I,M,j){var G=I.userCode,z=M.map(function(pe,Ce){var Re={logicalShape:pe.shape,texShape:pe.isUniform?null:pe.texData.texShape,isUniform:pe.isUniform,isPacked:!pe.isUniform&&pe.texData.isPacked,flatOffset:null};return pe.texData!=null&&pe.texData.slice!=null&&pe.texData.slice.flatOffset>0&&(Re.flatOffset=pe.texData.slice.flatOffset),{name:I.variableNames[Ce],shapeInfo:Re}}),W=z.map(function(pe){return pe.shapeInfo}),V={logicalShape:j.shape,texShape:j.texData.texShape,isUniform:!1,isPacked:j.texData.isPacked,flatOffset:null},Z=T(z,V,G,I.packedInputs),J=S.createProgram(Z),me=null,fe=S.getUniformLocation(J,"NAN",!1);ee().getNumber("WEBGL_VERSION")===1&&(me=S.getUniformLocation(J,"INFINITY",!1));for(var he={},Ee=0;Ee<I.variableNames.length;Ee++){var be=I.variableNames[Ee];he[be]=S.getUniformLocation(J,be,!1),he["offset"+be]=S.getUniformLocation(J,"offset"+be,!1)}return{program:I,source:Z,webGLProgram:J,uniformLocations:he,inShapeInfos:W,outShapeInfo:V,infLoc:me,nanLoc:fe}}(s.gpgpu,e,m,x)}),C=this.activeTimers!=null;if(C&&(g=this.startTimer()),function(S,I,M,j,G){wc(I.inShapeInfos,M),wc([I.outShapeInfo],[j]);var z=j.texData.texture,W=j.texData.texShape;j.texData.isPacked?S.setOutputPackedMatrixTexture(z,W[0],W[1]):S.setOutputMatrixTexture(z,W[0],W[1]),S.setProgram(I.webGLProgram),ee().getNumber("WEBGL_VERSION")===1&&I.infLoc!==null&&S.gl.uniform1f(I.infLoc,1/0),I.nanLoc!==null&&S.gl.uniform1f(I.nanLoc,NaN),M.forEach(function(V,Z){var J=I.program.variableNames[Z],me=I.uniformLocations[J],fe=I.uniformLocations["offset"+J];if(me!=null)if(V.isUniform)if(ae(V.shape)<2)S.gl.uniform1f(me,V.uniformValues[0]);else{var he=V.uniformValues;he instanceof Float32Array||(he=new Float32Array(he)),S.gl.uniform1fv(me,he)}else V.texData.slice!=null&&fe!=null&&S.gl.uniform1i(fe,V.texData.slice.flatOffset),S.setInputMatrixTexture(V.texData.texture,me,Z)}),G!=null&&G(S,I.webGLProgram),S.executeProgram()}(this.gpgpu,w,m,x,o),f.forEach(function(S){return s.disposeData(S.dataId)}),C&&(g=this.endTimer(g),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(g)})),!ee().getBool("WEBGL_LAZILY_UNPACK")&&c.isPacked&&i===!1){var N=this.unpackTensor(u);return this.disposeData(u.dataId),N}return u},n.prototype.compileAndRun=function(e,t,a,o,i){i===void 0&&(i=!1),a=a||t[0].dtype;var s=this.runWebGLProgram(e,t,a,o,i);return X.makeTensorFromDataId(s.dataId,s.shape,s.dtype)},n.prototype.getAndSaveBinary=function(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]},n.prototype.getTextureManager=function(){return this.textureManager},n.prototype.dispose=function(){var e=this;this.disposed||(ee().getBool("IS_TEST")||Object.keys(this.binaryCache).forEach(function(t){e.gpgpu.deleteProgram(e.binaryCache[t].webGLProgram),delete e.binaryCache[t]}),this.textureManager.dispose(),this.canvas!=null&&typeof HTMLCanvasElement!="undefined"&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)},n.prototype.floatPrecision=function(){var e=this;return this.floatPrecisionValue==null&&(this.floatPrecisionValue=en(function(){if(!ee().get("WEBGL_RENDER_FLOAT32_ENABLED")){var t=ee().getBool("DEBUG");ee().set("DEBUG",!1);var a=e.abs(We(1e-8)).dataSync()[0];if(ee().set("DEBUG",t),a>0)return 32}return 16})),this.floatPrecisionValue},n.prototype.epsilon=function(){return this.floatPrecision()===32?1e-7:1e-4},n.prototype.uploadToGPU=function(e){var t,a=this.texData.get(e),o=a.shape,i=a.dtype,s=a.values,u=a.texture,c=a.usage,d=a.isPacked;if(u==null){var f,m=this.activeTimers!=null;m&&(f=$());var g=a.texShape;if(g==null&&(g=xi(o,d),a.texShape=g),s!=null){var x=na(o),E=void 0,w=g[1],C=g[0],N=s instanceof Uint8Array;d?(w=(t=Lr(g[0],g[1]))[0],C=t[1],E=new si(x,[C,w],N)):E=new ii(x,[C,w],N);var S=this.makeTensorInfo([C,w],i);this.texData.get(S.dataId).usage=N?An.PIXELS:An.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(S.dataId),w,C,s);var I=this.runWebGLProgram(E,[S],i,null,!0),M=this.texData.get(I.dataId);a.texture=M.texture,a.texShape=M.texShape,a.isPacked=M.isPacked,a.usage=M.usage,this.disposeData(S.dataId),this.texData.delete(I.dataId),a.values=null,m&&(this.uploadWaitMs+=$()-f)}else{var j=this.acquireTexture(g,c,i,d);a.texture=j}}},n.prototype.convertAndCacheOnCPU=function(e,t){var a=this.texData.get(e),o=a.dtype;return this.releaseGPUData(e),t!=null&&(a.values=function(i,s){if(s==="float32"||s==="complex64")return i;if(s==="int32"||s==="bool"){for(var u=s==="int32"?new Int32Array(i.length):new Uint8Array(i.length),c=0;c<u.length;++c)u[c]=Math.round(i[c]);return u}throw new Error("Unknown dtype "+s)}(t,o)),a.values},n.prototype.acquireTexture=function(e,t,a,o){if(this.numBytesInGPU+=this.computeBytes(e,a),!this.warnedAboutMemory&&this.numBytesInGPU>1024*this.numMBBeforeWarning*1024){var i=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn("High memory usage in GPU: "+i+" MB, most likely due to a memory leak")}return this.textureManager.acquireTexture(e,t,o)},n.prototype.computeBytes=function(e,t){return e[0]*e[1]*nr(t)},n}(fo);Po()&&X.registerBackend("webgl",function(){return new Lc},2);var Qd=K({square_:function(r){var n=F(r,"x","square"),e=[n];return X.runKernelFunc(function(t,a){return a([n]),t.square(n)},{x:n},null,"Square",{},e,[])}}),li="SquaredDifference",Bc=K({squaredDifference_:function(r,n){var e,t=F(r,"a","squaredDifference"),a=F(n,"b","squaredDifference");e=Wt(t,a),t=e[0],a=e[1],nt(t.shape,a.shape);var o={a:t,b:a},i=[t,a];return X.runKernelFunc(function(s,u){var c=s.squaredDifference(t,a);return u([t,a]),c},o,function(s,u){var c=u[0],d=u[1],f=We(2);return{a:function(){return s.mul(c.sub(d).mul(f))},b:function(){return s.mul(d.sub(c).mul(f))}}},li,{},i,[])}}),Zd=K({abs_:function(r){var n=F(r,"x","abs");return n.dtype==="complex64"?X.runKernelFunc(function(e){return e.complexAbs(n)},{$x:n}):X.runKernelFunc(function(e,t){var a=e.abs(n);return t([n]),a},{x:n},function(e,t){var a=t[0];return{x:function(){return e.mul(a.toFloat().step(-1))}}},"Abs")}}),eh=K({acos_:function(r){var n=F(r,"x","acos");return X.runKernelFunc(function(e,t){var a=e.acos(n);return t([n]),a},{$x:n},function(e,t){var a=t[0];return{$x:function(){return e.divStrict(We(1).sub(a.toFloat().square()).sqrt()).neg()}}})}}),th=K({acosh_:function(r){var n=F(r,"x","acosh");return X.runKernelFunc(function(e,t){var a=e.acosh(n);return t([n]),a},{$x:n},function(e,t){var a=t[0];return{$x:function(){return e.divStrict(a.toFloat().square().sub(1).sqrt())}}})}}),nh=K({asin_:function(r){var n=F(r,"x","asin");return X.runKernelFunc(function(e,t){var a=e.asin(n);return t([n]),a},{$x:n},function(e,t){var a=t[0];return{$x:function(){return e.divStrict(We(1).sub(a.toFloat().square()).sqrt())}}})}}),rh=K({asinh_:function(r){var n=F(r,"x","asinh");return X.runKernelFunc(function(e,t){var a=e.asinh(n);return t([n]),a},{$x:n},function(e,t){var a=t[0];return{$x:function(){return e.divStrict(We(1).add(a.toFloat().square()).sqrt())}}})}}),ah=K({atan_:function(r){var n=F(r,"x","atan");return X.runKernelFunc(function(e,t){var a=e.atan(n);return t([n]),a},{$x:n},function(e,t){var a=t[0];return{$x:function(){return e.div(a.toFloat().square().add(1))}}})}}),oh=K({atanh_:function(r){var n=F(r,"x","atanh");return X.runKernelFunc(function(e,t){var a=e.atanh(n);return t([n]),a},{$x:n},function(e,t){var a=t[0];return{$x:function(){return e.div(We(1).sub(a.toFloat().square()))}}})}}),ih=K({ceil_:function(r){var n=F(r,"x","ceil");return X.runKernelFunc(function(e){return e.ceil(n)},{$x:n},function(e){return{$x:function(){return gt(e)}}})}}),jc=K({clipByValue_:function(r,n,e){var t=F(r,"x","clipByValue");D(n<=e,function(){return"Error in clip: min ("+n+") must be less than or equal to max ("+e+")."});var a=[t],o={min:n,max:e};return X.runKernelFunc(function(i,s){var u=i.clip(t,n,e);return s([t]),u},{x:t},function(i,s){var u=s[0];return{x:function(){return i.where(u.greaterEqual(n).logicalAnd(u.lessEqual(e)),gt(i))}}},"ClipByValue",o,a)}}),sh=K({cos_:function(r){var n=F(r,"x","cos"),e=[n];return X.runKernelFunc(function(t,a){var o=t.cos(n);return a([n]),o},{x:n},function(t,a){var o=a[0];return{x:function(){return o.toFloat().sin().neg().mul(t)}}},"Cos",{},e)}}),uh=K({cosh_:function(r){var n=F(r,"x","cosh");return X.runKernelFunc(function(e,t){var a=e.cosh(n);return t([n]),a},{$x:n},function(e,t){var a=t[0];return{$x:function(){return a.toFloat().sinh().mulStrict(e)}}})}}),ch=K({erf_:function(r){var n=F(r,"x","erf");return D(n.dtype==="int32"||n.dtype==="float32",function(){return"Input dtype must be `int32` or `float32`."}),n.dtype==="int32"&&(n=n.toFloat()),X.runKernelFunc(function(e,t){var a=e.erf(n);return t([n]),a},{$x:n},function(e,t){var a=t[0];return{$x:function(){return e.mul(a.square().neg().exp().mul(2/Math.sqrt(Math.PI)))}}})}}),Uc=K({exp_:function(r){var n=F(r,"x","exp");return X.runKernelFunc(function(e,t){var a=e.exp(n);return t([a]),a},{x:n},function(e,t){return{x:function(){return e.mulStrict(t[0])}}},"Exp",{},[],[!0])}}),lh=K({expm1_:function(r){var n=F(r,"x","expm1");return X.runKernelFunc(function(e,t){var a=e.expm1(n);return t([n]),a},{$x:n},function(e,t){var a=t[0];return{$x:function(){return e.mul(a.exp())}}})}}),dh=K({floor_:function(r){var n=F(r,"x","floor");return X.runKernelFunc(function(e){return e.floor(n)},{$x:n},function(e){return{$x:function(){return gt(e)}}})}}),hh=K({log_:function(r){var n=F(r,"x","log"),e=[n];return X.runKernelFunc(function(t,a){var o=t.log(n);return a([n]),o},{x:n},function(t,a){var o=a[0];return{x:function(){return t.div(o.toFloat())}}},"Log",{},e)}}),ph=K({log1p_:function(r){var n=F(r,"x","log1p");return X.runKernelFunc(function(e,t){var a=e.log1p(n);return t([n]),a},{$x:n},function(e,t){var a=t[0];return{$x:function(){return e.div(a.add(1))}}})}}),fh=K({logSigmoid_:function(r){var n=F(r,"x","logSigmoid");return X.runKernelFunc(function(e,t){var a=e.softplus(n.neg()).neg();return t([n]),a},{$x:n},function(e,t){var a=t[0];return{$x:function(){return e.mul(a.neg().sigmoid())}}})}}),ru=K({neg_:function(r){var n=F(r,"x","neg"),e=[n];return X.runKernelFunc(function(t){return t.neg(n)},{x:n},function(t){return{x:function(){return t.neg()}}},"Neg",{},e)}}),vh=K({reciprocal_:function(r){var n=F(r,"x","reciprocal");return X.runKernelFunc(function(e,t){var a=e.reciprocal(n);return t([n]),a},{$x:n},function(e,t){var a=t[0];return{$x:function(){return e.div(a.square().neg())}}})}}),mh=K({round_:function(r){var n=F(r,"x","round");return X.runKernelFunc(function(e){return e.round(n)},{$x:n},function(e){return{$x:function(){return gt(e)}}})}}),Wc=K({rsqrt_:function(r){var n=F(r,"x","rsqrt"),e=[n];return X.runKernelFunc(function(t,a){var o=t.rsqrt(n);return a([n]),o},{x:n},function(t,a){var o=a[0];return{x:function(){return t.div(o.pow(1.5).mul(2)).neg()}}},"Rsqrt",{},e)}}),zc=K({sigmoid_:function(r){var n=F(r,"x","sigmoid");return X.runKernelFunc(function(e,t){var a=e.sigmoid(n);return t([a]),a},{x:n},function(e,t){var a=t[0];return{x:function(){return e.mul(a.mul(We(1).sub(a)))}}},"Sigmoid")}}),gh=K({sign_:function(r){var n=F(r,"x","sign");return X.runKernelFunc(function(e){return e.sign(n)},{$x:n},function(e){return{$x:function(){return gt(e)}}})}}),yh=K({isNaN_:function(r){var n=F(r,"x","isNaN");return X.runKernelFunc(function(e){return e.isNaN(n)},{$x:n},function(e){return{$x:function(){return gt(e)}}})}}),xh=K({isInf_:function(r){var n=F(r,"x","isInf");return X.runKernelFunc(function(e){return e.isInf(n)},{$x:n},function(e){return{$x:function(){return gt(e)}}})}}),bh=K({isFinite_:function(r){var n=F(r,"x","isFinite");return X.runKernelFunc(function(e){return e.isFinite(n)},{$x:n},function(e){return{$x:function(){return gt(e)}}})}}),wh=K({sin_:function(r){var n=F(r,"x","sin"),e=[n];return X.runKernelFunc(function(t,a){var o=t.sin(n);return a([n]),o},{x:n},function(t,a){var o=a[0];return{x:function(){return o.toFloat().cos().mul(t)}}},"Sin",{},e)}}),Eh=K({sinh_:function(r){var n=F(r,"x","sinh");return X.runKernelFunc(function(e,t){var a=e.sinh(n);return t([n]),a},{$x:n},function(e,t){var a=t[0];return{$x:function(){return a.toFloat().cosh().mulStrict(e)}}})}}),_h=K({softplus_:function(r){var n=F(r,"x","softplus");return X.runKernelFunc(function(e,t){var a=e.softplus(n);return t([n]),a},{$x:n},function(e,t){var a=t[0];return{$x:function(){return e.mul(a.sigmoid())}}})}}),Ch=K({sqrt_:function(r){var n=F(r,"x","sqrt");return X.runKernelFunc(function(e,t){var a=e.sqrt(n);return t([n]),a},{$x:n},function(e,t){var a=t[0];return{$x:function(){return e.div(a.toFloat().sqrt().mul(2))}}})}}),Rh=K({step_:function(r,n){n===void 0&&(n=0);var e=F(r,"x","step");return X.runKernelFunc(function(t){return t.step(e,n)},{$x:e},function(t){return{$x:function(){return gt(t)}}})}}),Ah=K({tan_:function(r){var n=F(r,"x","tan");return X.runKernelFunc(function(e,t){var a=e.tan(n);return t([n]),a},{$x:n},function(e,t){var a=t[0];return{$x:function(){return e.div(a.cos().square())}}})}}),Th=K({tanh_:function(r){var n=F(r,"x","tanh");return X.runKernelFunc(function(e,t){var a=e.tanh(n);return t([a]),a},{x:n},function(e,t){var a=t[0];return{x:function(){return We(1).sub(a.square()).mulStrict(e)}}},"Tanh",{},null,[!0])}});function Vc(r,n,e,t,a,o){var i,s,u=F(r,"x","batchNorm"),c=F(n,"mean","batchNorm"),d=F(e,"variance","batchNorm");return a!=null&&(i=F(a,"scale","batchNorm")),t!=null&&(s=F(t,"offset","batchNorm")),D(u.rank===2,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."}),D(c.rank===2||c.rank===1,function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank "+c.rank+"."}),D(d.rank===2||d.rank===1,function(){return"Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank "+d.rank+"."}),i!=null&&D(i.rank===2||i.rank===1,function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank "+i.rank+"."}),s!=null&&D(s.rank===2||s.rank===1,function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank "+s.rank+"."}),di(u,c,d,s,i,o)}function Gc(r,n,e,t,a,o){var i,s,u=F(r,"x","batchNorm"),c=F(n,"mean","batchNorm"),d=F(e,"variance","batchNorm");return a!=null&&(i=F(a,"scale","batchNorm")),t!=null&&(s=F(t,"offset","batchNorm")),D(u.rank===3,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."}),D(c.rank===3||c.rank===1,function(){return"Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank "+c.rank+"."}),D(d.rank===3||d.rank===1,function(){return"Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank "+d.rank+"."}),i!=null&&D(i.rank===3||i.rank===1,function(){return"Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank "+i.rank+"."}),s!=null&&D(s.rank===3||s.rank===1,function(){return"Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank "+s.rank+"."}),di(u,c,d,s,i,o)}function Hc(r,n,e,t,a,o){var i,s,u=F(r,"x","batchNorm"),c=F(n,"mean","batchNorm"),d=F(e,"variance","batchNorm");return a!=null&&(i=F(a,"scale","batchNorm")),t!=null&&(s=F(t,"offset","batchNorm")),D(u.rank===4,function(){return"Error in batchNorm4D: x must be rank 4 but got rank "+u.rank+"."}),D(c.rank===4||c.rank===1,function(){return"Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank "+c.rank+"."}),D(d.rank===4||d.rank===1,function(){return"Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank "+d.rank+"."}),i!=null&&D(i.rank===4||i.rank===1,function(){return"Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank "+i.rank+"."}),s!=null&&D(s.rank===4||s.rank===1,function(){return"Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank "+s.rank+"."}),di(u,c,d,s,i,o)}function di(r,n,e,t,a,o){o==null&&(o=.001);var i,s,u,c=F(r,"x","batchNorm"),d=F(n,"mean","batchNorm"),f=F(e,"variance","batchNorm");a!=null&&(i=F(a,"scale","batchNorm")),t!=null&&(s=F(t,"offset","batchNorm")),D(d.rank===f.rank,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."}),D(s==null||d.rank===s.rank,function(){return"Batch normalization gradient requires mean and offset to have equal ranks."}),D(i==null||d.rank===i.rank,function(){return"Batch normalization gradient requires mean and scale to have equal ranks."}),u=c.rank===0||c.rank===1?c.as4D(1,1,1,c.size):c.rank===2?c.as4D(1,1,c.shape[0],c.shape[1]):c.rank===3?c.as4D(1,c.shape[0],c.shape[1],c.shape[2]):c;var m=[c,d,f,i];return X.runKernelFunc(function(g,x){var E=g.batchNormalization(u,es(d),es(f),o,es(i),es(s));return x([c,d,f,i]),E},{x:c,mean:d,variance:f,scale:i,offset:s},function(g,x){var E=x,w=E[0],C=E[1],N=E[2],S=E[3],I=S==null?We(1):S,M=tn(C.shape,u.shape),j=[];if(C.rank===1){for(var G=0;G<u.shape.length-1;++G)j.push(u.shape[G]);j.push(1)}var z=w.sub(C),W=g.mul(I),V=Wc(N.add(We(o))),Z=V.mul(V).mul(V).mul(We(-.5));return{x:function(){return C.rank===1?g.mul(zr(V.as4D(1,1,1,C.shape[0]),j)).mul(I).reshape(w.shape):g.mul(V).mul(I).reshape(w.shape)},mean:function(){var J=V.mul(We(-1)).mul(W);return C.rank===1&&(J=J.sum(M)),J.reshape(C.shape)},variance:function(){var J=Z.mul(z).mul(W);return C.rank===1&&(J=J.sum(M)),J.reshape(C.shape)},scale:function(){var J=z.mul(V),me=g.mul(J);return C.rank===1&&(me=me.sum(M)),me.reshape(C.shape)},offset:function(){var J=g;return C.rank===1&&(J=J.sum(M)),J.reshape(C.shape)}}},"BatchNormalization",{varianceEpsilon:o},m).reshape(c.shape)}function es(r){return r==null?null:r.rank===0?r.as1D():r.rank===1?r:r.rank===2?r.as4D(1,1,r.shape[0],r.shape[1]):r.rank===3?r.as4D(1,r.shape[0],r.shape[1],r.shape[2]):r}function ts(){Ri("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon")}var Dh=K({batchNormalization2d_:function(r,n,e,t,a,o){return t===void 0&&(t=.001),ts(),Vc(r,n,e,o,a,t)}}),Nh=K({batchNormalization3d_:function(r,n,e,t,a,o){return t===void 0&&(t=.001),ts(),Gc(r,n,e,o,a,t)}}),kh=K({batchNormalization4d_:function(r,n,e,t,a,o){return t===void 0&&(t=.001),ts(),Hc(r,n,e,o,a,t)}}),Sh=K({batchNormalization_:function(r,n,e,t,a,o){return t===void 0&&(t=.001),ts(),di(r,n,e,o,a,t)}}),Xc=K({batchNorm_:di}),Oh=K({batchNorm2d_:Vc}),Ih=K({batchNorm3d_:Gc}),Mh=K({batchNorm4d_:Hc}),ns=K({logicalAnd_:function(r,n){var e=F(r,"a","logicalAnd","bool"),t=F(n,"b","logicalAnd","bool");return nt(e.shape,t.shape),X.runKernelFunc(function(a){return a.logicalAnd(e,t)},{a:e,b:t},null,"LogicalAnd")}}),Fh=K({logicalNot_:function(r){var n=F(r,"x","logicalNot","bool");return X.runKernelFunc(function(e){return e.logicalNot(n)},{$x:n})}}),Kc=K({logicalOr_:function(r,n){var e=F(r,"a","logicalOr","bool"),t=F(n,"b","logicalOr","bool");return nt(e.shape,t.shape),X.runKernelFunc(function(a){return a.logicalOr(e,t)},{$a:e,$b:t})}}),Ph=K({logicalXor_:function(r,n){var e=F(r,"a","logicalXor","bool"),t=F(n,"b","logicalXor","bool");return nt(e.shape,t.shape),Kc(r,n).logicalAnd(ns(r,n).logicalNot())}}),Pa=K({where_:function(r,n,e){var t=F(n,"a","where"),a=F(e,"b","where"),o=F(r,"condition","where","bool");return se(t.shape,a.shape,"Error in where: "),o.rank===1?D(o.shape[0]===t.shape[0],function(){return"The first dimension of `a` must match the size of `condition`."}):se(o.shape,a.shape,"Error in where: "),X.runKernelFunc(function(i,s){var u=i.select(o,t,a);return s([o]),u},{$condition:o,$a:t,$b:a},function(i,s){var u=s[0];return{$condition:function(){return gt(u).toFloat()},$a:function(){return i.mul(u.cast(i.dtype))},$b:function(){return i.mul(u.logicalNot().cast(i.dtype))}}})}}),qc=function(r){return ve(this,void 0,void 0,function(){var n,e,t;return ye(this,function(a){switch(a.label){case 0:return[4,(n=F(r,"condition","whereAsync","bool")).data()];case 1:return e=a.sent(),t=Yi(n.shape,e),r!==n&&n.dispose(),[2,t]}})})},La=K({add_:function(r,n){var e,t=F(r,"a","add"),a=F(n,"b","add");e=Wt(t,a),t=e[0],a=e[1];var o=nt(t.shape,a.shape);return X.runKernelFunc(function(i){return i.add(t,a)},{a:t,b:a},function(i){return{a:function(){var s=i,u=tn(t.shape,o);return u.length>0&&(s=s.sum(u)),s.reshape(t.shape)},b:function(){var s=i,u=tn(a.shape,o);return u.length>0&&(s=s.sum(u)),s.reshape(a.shape)}}},"Add")}}),Lh=K({addN_:function(r){D(Array.isArray(r),function(){return"The argument passed to tf.addN() must be a list of tensors"}),D(r.length>=1,function(){return"Must pass at least one tensor to tf.addN(), but got "+r.length});var n=r.map(function(a,o){return F(a,"tensors"+o,"addN")}),e=n[0];n.forEach(function(a){if(a.dtype!==e.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),n.forEach(function(a){if(!Oe(a.shape,e.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});var t=n;return X.runKernelFunc(function(a){return a.addN(n)},t,function(a){var o={};return n.forEach(function(i,s){o[s]=function(){return a.clone()}}),o},"AddN")}}),Bh=K({addStrict_:function(r,n){var e=F(r,"a","addStrict"),t=F(n,"b","addStrict");return se(e.shape,t.shape,"Error in addStrict: "),e.add(t)}}),jh=K({atan2_:function(r,n){var e,t=F(r,"a","atan2"),a=F(n,"b","atan2");e=Wt(t,a),t=e[0],a=e[1];var o=nt(t.shape,a.shape);return X.runKernelFunc(function(i,s){var u=i.atan2(t,a);return s([t,a]),u},{$a:t,$b:a},function(i,s){var u=s[0],c=s[1];return{$a:function(){var d=La(u.square(),c.square()),f=i.mul(c.div(d)),m=tn(u.shape,o);return m.length>0&&(f=f.sum(m)),f.reshape(u.shape)},$b:function(){var d=La(u.square(),c.square()),f=ru(i.mul(u.div(d))),m=tn(c.shape,o);return m.length>0&&(f=f.sum(m)),f.reshape(c.shape)}}})}}),rs=K({div_:function(r,n){var e,t=F(r,"a","div"),a=F(n,"b","div");if(e=Wt(t,a),t=e[0],a=e[1],t.dtype==="int32"&&a.dtype==="int32")return Yc(t,a);var o=nt(t.shape,a.shape);return X.runKernelFunc(function(i,s){var u=i.realDivide(t,a);return s([t,a]),u},{a:t,b:a},function(i,s){var u=s[0],c=s[1];return{a:function(){var d=i.div(c.toFloat()),f=tn(u.shape,o);return f.length>0?d.sum(f).reshape(u.shape):d},b:function(){var d=i.mul(u.toFloat()),f=tn(c.shape,o);f.length>0&&(d=d.sum(f).reshape(c.shape));var m=c.square();return d.div(m.toFloat()).neg()}}},"Div")}}),Uh=K({divNoNan_:function(r,n){var e,t=F(r,"a","div"),a=F(n,"b","div");t=(e=Wt(t,a))[0],a=e[1];var o=rs(t,a),i=gt(o),s=a.equal(i);return Pa(s,i,o)}}),Wh=K({divStrict_:function(r,n){var e=F(r,"a","div"),t=F(n,"b","div");return se(e.shape,t.shape,"Error in divideStrict: "),e.div(t)}}),Yc=K({floorDiv_:function(r,n){var e,t=F(r,"a","floorDiv"),a=F(n,"b","floorDiv");e=Wt(t,a),t=e[0],a=e[1];var o=nt(t.shape,a.shape);return X.runKernelFunc(function(i,s){var u=i.floorDiv(t,a);return s([t,a]),u},{a:t,b:a},function(i,s){var u=s[0],c=s[1];return{a:function(){var d=i.div(c.toFloat()),f=tn(u.shape,o);return f.length>0?d.sum(f).reshape(u.shape):d},b:function(){var d=i.mul(u.toFloat()),f=tn(c.shape,o);f.length>0&&(d=d.sum(f).reshape(c.shape));var m=c.square();return d.div(m.toFloat()).neg()}}},"FloorDiv")}}),au=K({maximum_:function(r,n){var e,t=F(r,"a","maximum"),a=F(n,"b","maximum");return e=Wt(t,a),t=e[0],a=e[1],t.dtype==="bool"&&(t=t.toInt(),a=a.toInt()),nt(t.shape,a.shape),X.runKernelFunc(function(o,i){var s=o.maximum(t,a);return i([t,a]),s},{a:t,b:a},function(o,i){var s=i[0],u=i[1];return{a:function(){return o.mul(s.greaterEqual(u).toFloat())},b:function(){return o.mul(s.less(u).toFloat())}}},"Maximum")}}),zh=K({maximumStrict_:function(r,n){var e=F(r,"a","maximumStrict"),t=F(n,"b","maximumStrict");return se(e.shape,t.shape,"Error in maximumStrict: "),e.maximum(t)}}),$c=K({minimum_:function(r,n){var e,t=F(r,"a","minimum"),a=F(n,"b","minimum");return e=Wt(t,a),t=e[0],a=e[1],t.dtype==="bool"&&(t=t.toInt(),a=a.toInt()),nt(t.shape,a.shape),X.runKernelFunc(function(o,i){var s=o.minimum(t,a);return i([t,a]),s},{a:t,b:a},function(o,i){var s=i[0],u=i[1];return{a:function(){return o.mul(s.lessEqual(u).toFloat())},b:function(){return o.mul(s.greater(u).toFloat())}}},"Minimum")}}),Vh=K({minimumStrict_:function(r,n){var e=F(r,"a","minimumStrict"),t=F(n,"b","minimumStrict");return se(e.shape,t.shape,"Error in minimumStrict: "),e.minimum(t)}}),Gh=K({mod_:function(r,n){var e,t=F(r,"a","mod"),a=F(n,"b","mod");e=Wt(t,a),t=e[0],a=e[1];var o=nt(t.shape,a.shape);return X.runKernelFunc(function(i,s){var u=i.mod(t,a);return s([t,a]),u},{$a:t,$b:a},function(i,s){var u=s[0],c=s[1];return{$a:function(){var d=tn(u.shape,o);return d.length>0?i.sum(d).reshape(u.shape):i},$b:function(){var d=i.mul(u.div(c).floor().neg()),f=tn(c.shape,o);return f.length>0?d.sum(f).reshape(c.shape):d}}})}}),Hh=K({modStrict_:function(r,n){var e=F(r,"a","modStrict"),t=F(n,"b","modStrict");return se(e.shape,t.shape,"Error in modStrict: "),e.mod(t)}}),Ba=K({mul_:function(r,n){var e,t=F(r,"a","mul"),a=F(n,"b","mul");e=Wt(t,a),t=e[0],a=e[1];var o=nt(t.shape,a.shape);return X.runKernelFunc(function(i,s){var u=i.multiply(t,a);return s([t,a]),u},{a:t,b:a},function(i,s){var u=s[0],c=s[1];return{a:function(){var d=i.mul(c.toFloat()),f=tn(u.shape,o);return f.length>0?d.sum(f).reshape(u.shape):d},b:function(){var d=i.mul(u.toFloat()),f=tn(c.shape,o);return f.length>0?d.sum(f).reshape(c.shape):d}}},"Mul")}}),Xh=K({mulStrict_:function(r,n){var e=F(r,"a","mul"),t=F(n,"b","mul");return se(e.shape,t.shape,"Error in multiplyStrict: "),e.mul(t)}}),as=K({pow_:function(r,n){var e,t=F(r,"base","pow"),a=F(n,"exp","pow");e=Wt(t,a),t=e[0],a=e[1];var o=nt(t.shape,a.shape),i=[t,a];return X.runKernelFunc(function(s,u){var c=s.pow(t,a);return u([t,a,c]),c},{a:t,b:a},function(s,u){var c=u[0],d=u[1],f=u[2];return{a:function(){var m=d.toFloat(),g=s.mul(m.mul(c.pow(m.sub(We(1))))),x=tn(c.shape,o);return x.length>0&&(g=g.sum(x)),g.reshape(c.shape)},b:function(){var m=c.greater(0),g=c.log().where(m,gt(c)),x=s.mul(f.mul(g)),E=tn(d.shape,o);return E.length>0&&(x=x.sum(E)),x.reshape(d.shape)}}},"Pow",{},i,[!0])}}),Kh=K({powStrict_:function(r,n){return se(r.shape,n.shape,"Error in powStrict: "),r.pow(n)}}),qh=K({squaredDifferenceStrict_:function(r,n){var e=F(r,"a","squaredDifferenceStrict"),t=F(n,"b","squaredDifferenceStrict");return se(e.shape,t.shape,"Error in squaredDifferenceStrict: "),e.squaredDifference(t)}}),va=K({sub_:function(r,n){var e,t=F(r,"a","sub"),a=F(n,"b","sub");e=Wt(t,a),t=e[0],a=e[1];var o=nt(t.shape,a.shape);return X.runKernelFunc(function(i){return i.subtract(t,a)},{a:t,b:a},function(i){return{a:function(){var s=i,u=tn(t.shape,o);return u.length>0&&(s=s.sum(u)),s.reshape(t.shape)},b:function(){var s=i,u=tn(a.shape,o);return u.length>0&&(s=s.sum(u)),s.neg().reshape(a.shape)}}},"Sub")}}),Yh=K({subStrict_:function(r,n){var e=F(r,"a","subStrict"),t=F(n,"b","subStrict");return se(e.shape,t.shape,"Error in subStrict: "),e.sub(t)}}),Jc=K({equal_:function(r,n){var e,t=F(r,"a","equal"),a=F(n,"b","equal");return e=Wt(t,a),t=e[0],a=e[1],nt(t.shape,a.shape),X.runKernelFunc(function(o){return o.equal(t,a)},{$a:t,$b:a})}}),$h=K({equalStrict_:function(r,n){var e=F(r,"a","equalStrict"),t=F(n,"b","equalStrict");return se(e.shape,t.shape,"Error in equalStrict: "),e.equal(t)}}),Jh=K({greater_:function(r,n){var e,t=F(r,"a","greater"),a=F(n,"b","greater");return e=Wt(t,a),t=e[0],a=e[1],nt(t.shape,a.shape),X.runKernelFunc(function(o){return o.greater(t,a)},{a:t,b:a},null,"Greater")}}),Qc=K({greaterEqual_:function(r,n){var e,t=F(r,"a","greaterEqual"),a=F(n,"b","greaterEqual");return e=Wt(t,a),t=e[0],a=e[1],nt(t.shape,a.shape),X.runKernelFunc(function(o,i){var s=o.greaterEqual(t,a);return i([t,a]),s},{a:t,b:a},function(o,i){var s=i[0],u=i[1];return{a:function(){return gt(s)},b:function(){return gt(u)}}},"GreaterEqual")}}),Qh=K({greaterEqualStrict_:function(r,n){var e=F(r,"a","greaterEqualStrict"),t=F(n,"b","greaterEqualStrict");return se(e.shape,t.shape,"Error in greaterEqualStrict: "),e.greaterEqual(t)}}),Zh=K({greaterStrict_:function(r,n){var e=F(r,"a","greaterStrict"),t=F(n,"b","greaterStrict");return se(e.shape,t.shape,"Error in greaterStrict: "),e.greater(t)}}),ep=K({less_:function(r,n){var e,t=F(r,"a","less"),a=F(n,"b","less");return e=Wt(t,a),t=e[0],a=e[1],nt(t.shape,a.shape),X.runKernelFunc(function(o){return o.less(t,a)},{a:t,b:a},null,"Less")}}),tp=K({lessEqual_:function(r,n){var e,t=F(r,"a","lessEqual"),a=F(n,"b","lessEqual");return e=Wt(t,a),t=e[0],a=e[1],nt(t.shape,a.shape),X.runKernelFunc(function(o,i){var s=o.lessEqual(t,a);return i([t,a]),s},{a:t,b:a},null,"LessEqual")}}),np=K({lessEqualStrict_:function(r,n){var e=F(r,"a","lessEqualStrict"),t=F(n,"b","lessEqualStrict");return se(e.shape,t.shape,"Error in lessEqualStrict: "),e.lessEqual(t)}}),rp=K({lessStrict_:function(r,n){var e=F(r,"a","lessStrict"),t=F(n,"b","lessStrict");return se(e.shape,t.shape,"Error in lessStrict: "),e.less(t)}}),ap=K({notEqual_:function(r,n){var e,t=F(r,"a","notEqual"),a=F(n,"b","notEqual");return e=Wt(t,a),t=e[0],a=e[1],nt(t.shape,a.shape),X.runKernelFunc(function(o){return o.notEqual(t,a)},{a:t,b:a},null,"NotEqual")}}),op=K({notEqualStrict_:function(r,n){var e=F(r,"a","notEqualStrict"),t=F(n,"b","notEqualStrict");return se(e.shape,t.shape,"Error in notEqualStrict: "),e.notEqual(t)}});function Zc(r,n){for(var e=[],t=r;t<n;++t)e.push(t);return e}function el(r){for(var n=[],e=0;e<r.length;++e)for(var t=0;t<r[e].length;++t)n.push(r[e][t]);return n}var ou=K({gather_:function(r,n,e){e===void 0&&(e=0);var t=F(r,"x","gather"),a=F(n,"indices","gather","int32");e=je(e,t.shape)[0];var o=function(i,s,u){for(var c=i.shape[u],d=[],f=1,m=1,g=0;g<u;g++)d.push(i.shape[g]),f*=i.shape[g];for(g=0;g<s.rank;g++)d.push(s.shape[g]);for(g=u+1;g<i.rank;g++)d.push(i.shape[g]),m*=i.shape[g];return{batchSize:f,sliceSize:m,dimSize:c,outputShape:d}}(t,a,e);return X.runKernelFunc(function(i,s){var u=i.gather(t,a.flatten(),e);return s([a]),u},{x:t,indices:a},function(i,s){var u=s[0];return{x:function(){var c=t.shape,d=u.size,f=c.slice(0,e),m=f.length,g=c.slice(e,c.length).slice(1),x=g.length,E=Zc(0,m),w=Zc(m+1,m+1+x),C=el([f,[d],g]),N=i.reshape(C),S=u.reshape([d]),I=el([[m],E,w]),M=N.transpose(I),j=tl(M,S,t.shape[e]),G=oa(I);return j=j.transpose(G)},indices:function(){return u}}},"Gather",{axis:e}).reshape(o.outputShape)}}),tl=K({unsortedSegmentSum_:function(r,n,e){var t=F(r,"x","unsortedSegmentSum"),a=F(n,"segmentIds","unsortedSegmentSum","int32");return D(Be(e),function(){return"numSegments must be of dtype int"}),X.runKernelFunc(function(o,i){var s=o.unsortedSegmentSum(t,a,e);return i([a]),s},{$x:t},function(o,i){var s=i[0];return{$x:function(){return function(u,c){for(var d=au(c,gt(c)),f=ou(u,d),m=Qc(c,We(0,"int32")),g=f.rank-m.rank,x=0;x<g;++x)m=gr(m,x+1);m=ns(m,_r(f.shape,"bool"));var E=gt(f);return Pa(m,f,E)}(o,s)}}})}}),ip=function(r,n,e){return ve(this,void 0,void 0,function(){var t,a,o,i,s,u,c,d,f,m,g,x,E;return ye(this,function(w){switch(w.label){case 0:for(t=F(r,"tensor","boolMask"),a=F(n,"mask","boolMask","bool"),o=e==null?0:e,i=a.rank,s=t.shape,D(i>0,function(){return"mask cannot be scalar"}),se(s.slice(o,o+i),a.shape,"mask's shape must match the first K dimensions of tensor's shape,"),u=1,c=o;c<o+i;c++)u*=s[c];return d=s.slice(0,o).concat([u],s.slice(o+i)),f=t.reshape(d),m=a.reshape([-1]),[4,qc(m)];case 1:return g=w.sent(),x=g.squeeze([1]),E=ou(f,x,o),r!==t&&t.dispose(),n!==a&&a.dispose(),x.dispose(),f.dispose(),m.dispose(),g.dispose(),[2,E]}})})};function nl(r,n,e,t,a,o,i){o===void 0&&(o="NHWC"),D(r.length===n.rank,function(){return"Length of inShape ("+r.length+") and rank of dy ("+n.rank+") must match"});var s=r,u=n,c=!1;n.rank===3&&(c=!0,u=n.as4D(1,n.shape[0],n.shape[1],n.shape[2]),s=[1,r[0],r[1],r[2]]),D(s.length===4,function(){return"Error in conv2dDerInput: inShape must be length 4, but got length "+s.length+"."}),D(u.rank===4,function(){return"Error in conv2dDerInput: dy must be rank 4, but got rank "+u.rank}),D(e.rank===4,function(){return"Error in conv2dDerInput: filter must be rank 4, but got rank "+e.rank});var d=o==="NHWC"?s[3]:s[1],f=o==="NHWC"?u.shape[3]:u.shape[1];D(d===e.shape[2],function(){return"Error in conv2dDerInput: depth of input ("+d+") must match input depth for filter "+e.shape[2]+"."}),D(f===e.shape[3],function(){return"Error in conv2dDerInput: depth of output ("+f+") must match output depth for filter "+e.shape[3]+"."}),i!=null&&D(Be(a),function(){return"Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+a+"."});var m=ni(o),g=Tr(s,e.shape,t,1,a,i,!1,m),x=X.runKernelFunc(function(E,w){var C=E.conv2dDerInput(u,e,g);return w([e,u]),C},{dy4D:u,filter:e},function(E,w){var C=w[0],N=w[1];return{dy4D:function(){return xo(E,C,t,a,o,1,i)},filter:function(){return su(E,N,C.shape,t,a,o,i)}}});return c?x.as3D(x.shape[1],x.shape[2],x.shape[3]):x}function iu(r){var n=function(o){return typeof o=="number"?[o,o,o]:o.length===2?[o[0],o[1],1]:o}(r),e=n[0],t=n[1],a=n[2];return e===1&&t===1&&a===1}function rl(r,n,e,t,a){D(r.length===n.rank,function(){return"Length of inShape ("+r.length+") and rank of dy ("+n.rank+") must match"});var o=r,i=n,s=!1;n.rank===4&&(s=!0,i=n.as5D(1,n.shape[0],n.shape[1],n.shape[2],n.shape[3]),o=[1,r[0],r[1],r[2],r[3]]);var u=o[4],c=i.shape[4];D(o.length===5,function(){return"Error in conv3dDerInput: inShape must be length 5, but got length "+o.length+"."}),D(i.rank===5,function(){return"Error in conv3dDerInput: dy must be rank 5, but got rank "+i.rank}),D(e.rank===5,function(){return"Error in conv3dDerInput: filter must be rank 5, but got rank "+e.rank}),D(u===e.shape[3],function(){return"Error in conv3dDerInput: depth of input ("+u+") must match input depth for filter "+e.shape[3]+"."}),D(c===e.shape[4],function(){return"Error in conv3dDerInput: depth of output ("+c+") must match output depth for filter "+e.shape[4]+"."});var d=da(o,e.shape,t,1,a),f=X.runKernelFunc(function(m){return m.conv3dDerInput(i,e,d)},{dy5D:i});return s?f.as4D(f.shape[1],f.shape[2],f.shape[3],f.shape[4]):f}var sp=K({conv1d_:function(r,n,e,t,a,o,i){a===void 0&&(a="NWC"),o===void 0&&(o=1);var s=F(r,"x","conv1d"),u=F(n,"filter","conv1d"),c=s,d=!1;s.rank===2&&(d=!0,c=s.as3D(1,s.shape[0],s.shape[1])),D(c.rank===3,function(){return"Error in conv1d: input must be rank 3, but got rank "+c.rank+"."}),D(u.rank===3,function(){return"Error in conv1d: filter must be rank 3, but got rank "+u.rank+"."}),i!=null&&D(Be(t),function(){return"Error in conv1d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+t+"."}),D(c.shape[2]===u.shape[1],function(){return"Error in conv1d: depth of input ("+c.shape[2]+") must match input depth for filter "+u.shape[1]+"."}),D(Bn(e,o),function(){return"Error in conv1D: Either stride or dilation must be 1. Got stride "+e+" and dilation '"+o+"'"}),D(a==="NWC",function(){return"Error in conv1d: got dataFormat of "+a+" but only NWC is currently supported."});var f=u.as4D(1,u.shape[0],u.shape[1],u.shape[2]),m=c.as4D(c.shape[0],1,c.shape[1],c.shape[2]),g=xo(m,f,[1,e],t,"NHWC",[1,o],i);return d?g.as2D(g.shape[2],g.shape[3]):g.as3D(g.shape[0],g.shape[2],g.shape[3])}}),xo=K({conv2d_:function(r,n,e,t,a,o,i){a===void 0&&(a="NHWC"),o===void 0&&(o=[1,1]);var s=F(r,"x","conv2d"),u=F(n,"filter","conv2d"),c=s,d=!1;s.rank===3&&(d=!0,c=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),D(c.rank===4,function(){return"Error in conv2d: input must be rank 4, but got rank "+c.rank+"."}),D(u.rank===4,function(){return"Error in conv2d: filter must be rank 4, but got rank "+u.rank+"."}),i!=null&&D(Be(t),function(){return"Error in conv2d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+t+"."});var f=a==="NHWC"?c.shape[3]:c.shape[1];D(f===u.shape[2],function(){return"Error in conv2d: depth of input ("+f+") must match input depth for filter "+u.shape[2]+"."}),D(Bn(e,o),function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+o+"'"});var m=ni(a),g=Tr(c.shape,u.shape,e,o,t,i,!1,m),x=[u,c],E=X.runKernelFunc(function(w,C){var N=w.conv2d(c,u,g);return C([u,c]),N},{x:c,filter:u},function(w,C){var N=C,S=N[0],I=N[1];return D(ha(o),function(){return"Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+o+"'"}),{x:function(){return al(I.shape,w,S,e,t,a)},filter:function(){return su(I,w,S.shape,e,t,a)}}},"Conv2D",g,x);return d?E.as3D(E.shape[1],E.shape[2],E.shape[3]):E}}),up=K({conv3d_:function(r,n,e,t,a,o){a===void 0&&(a="NDHWC"),o===void 0&&(o=[1,1,1]);var i=F(r,"x","conv3d"),s=F(n,"filter","conv3d"),u=i,c=!1;i.rank===4&&(c=!0,u=i.as5D(1,i.shape[0],i.shape[1],i.shape[2],i.shape[3])),D(u.rank===5,function(){return"Error in conv3d: input must be rank 5, but got rank "+u.rank+"."}),D(s.rank===5,function(){return"Error in conv3d: filter must be rank 5, but got rank "+s.rank+"."}),D(u.shape[4]===s.shape[3],function(){return"Error in conv3d: depth of input ("+u.shape[4]+") must match input depth for filter "+s.shape[3]+"."}),D(function(m,g){return iu(m)||iu(g)}(e,o),function(){return"Error in conv3D: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+o+"'"}),D(a==="NDHWC",function(){return"Error in conv3d: got dataFormat of "+a+" but only NDHWC is currently supported."});var d=da(u.shape,s.shape,e,o,t),f=X.runKernelFunc(function(m,g){var x=m.conv3d(u,s,d);return g([u,s]),x},{x:u,$filter:s},function(m,g){D(iu(o),function(){return"Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+o+"'"});var x=g[0],E=g[1];return{x:function(){return rl(x.shape,m,E,e,t)},$filter:function(){return function(w,C,N,S,I){var M=w;w.rank===4&&(M=w.as5D(1,w.shape[0],w.shape[1],w.shape[2],w.shape[3]));var j=C;j.rank===4&&(j=C.as5D(1,C.shape[0],C.shape[1],C.shape[2],C.shape[3])),D(M.rank===5,function(){return"Error in conv3dDerFilter: input must be rank 5, but got shape "+M.shape+"."}),D(j.rank===5,function(){return"Error in conv3dDerFilter: dy must be rank 5, but got shape "+j.shape+"."}),D(N.length===5,function(){return"Error in conv3dDerFilter: filterShape must be length 5, but got "+N+"."}),D(M.shape[4]===N[3],function(){return"Error in conv3dDerFilter: depth of input "+M.shape[4]+") must match input depth in filter ("+N[3]+"."}),D(j.shape[4]===N[4],function(){return"Error in conv3dDerFilter: depth of dy ("+j.shape[4]+") must match output depth for filter ("+N[4]+")."});var G=da(M.shape,N,S,1,I);return X.runKernelFunc(function(z){return z.conv3dDerFilter(M,j,G)},{x5D:M,dy5D:j})}(x,m,E.shape,e,t)}}});return c?f.as4D(f.shape[1],f.shape[2],f.shape[3],f.shape[4]):f}}),su=K({conv2dDerFilter_:function(r,n,e,t,a,o,i){o===void 0&&(o="NHWC");var s=r;r.rank===3&&(s=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var u=n;u.rank===3&&(u=n.as4D(1,n.shape[0],n.shape[1],n.shape[2])),D(s.rank===4,function(){return"Error in conv2dDerFilter: input must be rank 4, but got shape "+s.shape+"."}),D(u.rank===4,function(){return"Error in conv2dDerFilter: dy must be rank 4, but got shape "+u.shape+"."}),D(e.length===4,function(){return"Error in conv2dDerFilter: filterShape must be length 4, but got "+e+"."});var c=o==="NHWC"?s.shape[3]:s.shape[1],d=o==="NHWC"?u.shape[3]:u.shape[1];D(c===e[2],function(){return"Error in conv2dDerFilter: depth of input "+c+") must match input depth in filter ("+e[2]+"."}),D(d===e[3],function(){return"Error in conv2dDerFilter: depth of dy ("+d+") must match output depth for filter ("+e[3]+")."}),i!=null&&D(Be(a),function(){return"Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+a+"."});var f=ni(o),m=Tr(s.shape,e,t,1,a,i,!1,f);return X.runKernelFunc(function(g){return g.conv2dDerFilter(s,u,m)},{x4D:s,dy4D:u})}}),al=K({conv2dDerInput_:nl}),os=K({depthwiseConv2d_:function(r,n,e,t,a,o,i){a===void 0&&(a="NHWC"),o===void 0&&(o=[1,1]);var s=F(r,"x","depthwiseConv2d"),u=F(n,"filter","depthwiseConv2d"),c=s,d=!1;s.rank===3&&(d=!0,c=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),D(c.rank===4,function(){return"Error in depthwiseConv2d: input must be rank 4, but got rank "+c.rank+"."}),D(u.rank===4,function(){return"Error in depthwiseConv2d: filter must be rank 4, but got rank "+u.rank+"."}),D(c.shape[3]===u.shape[2],function(){return"Error in depthwiseConv2d: number of input channels ("+c.shape[3]+") must match the inChannels dimension in filter "+u.shape[2]+"."}),o==null&&(o=[1,1]),D(Bn(e,o),function(){return"Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+o+"'"}),i!=null&&D(Be(t),function(){return"Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+t+"."});var f=Tr(c.shape,u.shape,e,o,t,i,!0),m=[c,u],g=X.runKernelFunc(function(x,E){var w=x.depthwiseConv2D(c,u,f);return E([c,u]),w},{x:c,filter:u},function(x,E){D(ha(o),function(){return"Error in gradient of depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+o+"'"});var w=E[0],C=E[1];return{x:function(){return ol(w.shape,x,C,f)},filter:function(){return il(w,x,C.shape,f)}}},"DepthwiseConv2dNative",f,m);return d?g.as3D(g.shape[1],g.shape[2],g.shape[3]):g}}),ol=K({depthwiseConv2dDerInput_:function(r,n,e,t){var a=n,o=!1;n.rank===3&&(o=!0,a=n.as4D(1,n.shape[0],n.shape[1],n.shape[2]));var i=X.runKernelFunc(function(s){return s.depthwiseConv2DDerInput(a,e,t)},{dy4D:a});return o?i.as3D(i.shape[1],i.shape[2],i.shape[3]):i}}),il=K({depthwiseConv2dDerFilter_:function(r,n,e,t){var a=r;r.rank===3&&(a=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var o=n;return o.rank===3&&(o=n.as4D(1,n.shape[0],n.shape[1],n.shape[2])),X.runKernelFunc(function(i){return i.depthwiseConv2DDerFilter(a,o,t)},{x4D:a,dy4D:o})}}),sl=K({separableConv2d_:function(r,n,e,t,a,o,i){o===void 0&&(o=[1,1]),i===void 0&&(i="NHWC");var s=F(r,"x","separableConv2d"),u=F(n,"depthwiseFilter","separableConv2d"),c=F(e,"pointwiseFilter","separableConv2d"),d=s,f=!1;if(s.rank===3&&(f=!0,d=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),i==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");D(d.rank===4,function(){return"Error in separableConv2d: input must be rank 4, but got rank "+d.rank+"."}),D(u.rank===4,function(){return"Error in separableConv2d: depthwise filter must be rank 4, but got rank "+u.rank+"."}),D(c.rank===4,function(){return"Error in separableConv2d: pointwise filter must be rank 4, but got rank "+u.rank+"."}),D(c.shape[0]===1,function(){return"Error in separableConv2d: the first dimension of pointwise filter must be 1, but got "+c.shape[0]+"."}),D(c.shape[1]===1,function(){return"Error in separableConv2d: the second dimension of pointwise filter must be 1, but got "+c.shape[1]+"."});var m=u.shape[2],g=u.shape[3];D(c.shape[2]===m*g,function(){return"Error in separableConv2d: the third dimension of pointwise filter must be "+m*g+", but got "+c.shape[2]+"."});var x=os(d,u,t,a,i,o),E=xo(x,c,1,"valid",i);return f?E.as3D(E.shape[1],E.shape[2],E.shape[3]):E}}),cp=K({conv2dTranspose_:function(r,n,e,t,a,o){return nl(e,F(r,"x","conv2dTranspose"),F(n,"filter","conv2dTranspose"),t,a,"NHWC",o)}}),lp=K({conv3dTranspose_:function(r,n,e,t,a){return rl(e,F(r,"x","conv3dTranspose"),F(n,"filter","conv3dTranspose"),t,a)}}),uu=K({matMul_:function(r,n,e,t){var a;e===void 0&&(e=!1),t===void 0&&(t=!1);var o=F(r,"a","matMul"),i=F(n,"b","matMul");a=Wt(o,i),o=a[0],i=a[1];var s=e?o.shape[o.rank-2]:o.shape[o.rank-1],u=t?i.shape[i.rank-1]:i.shape[i.rank-2],c=e?o.shape[o.rank-1]:o.shape[o.rank-2],d=t?i.shape[i.rank-2]:i.shape[i.rank-1],f=o.shape.slice(0,-2),m=i.shape.slice(0,-2),g=ae(f),x=ae(m);D(o.rank>=2&&i.rank>=2&&o.rank===i.rank,function(){return"Error in matMul: inputs must have the same rank of at least 2, got ranks "+o.rank+" and "+i.rank+"."}),D(Oe(f,m),function(){return"Error in matMul: outer dimensions ("+f+") and ("+m+") of Tensors with shapes "+o.shape+" and "+i.shape+" must match."}),D(s===u,function(){return"Error in matMul: inner shapes ("+s+") and ("+u+") of Tensors with shapes "+o.shape+" and "+i.shape+" and transposeA="+e+" and transposeB="+t+" must match."});var E=o.shape.slice(0,-2).concat([c,d]),w=e?o.as3D(g,s,c):o.as3D(g,c,s),C=t?i.as3D(x,d,u):i.as3D(x,u,d),N={transposeA:e,transposeB:t};return X.runKernelFunc(function(S,I){var M=S.batchMatMul(w,C,e,t);return I([w,C]),M},{a:w,b:C},function(S,I){var M=I,j=M[0],G=M[1];return e||t?!e&&t?{a:function(){return S.matMul(G,!1,!1)},b:function(){return S.matMul(j,!0,!1)}}:e&&!t?{a:function(){return G.matMul(S,!1,!0)},b:function(){return j.matMul(S,!1,!1)}}:{a:function(){return G.matMul(S,!0,!0)},b:function(){return S.matMul(j,!0,!0)}}:{a:function(){return S.matMul(G,!1,!0)},b:function(){return j.matMul(S,!0,!1)}}},"BatchMatMul",N).reshape(E)}}),dp=K({dot_:function(r,n){var e=F(r,"t1","dot"),t=F(n,"t2","dot");D(!(e.rank!==1&&e.rank!==2||t.rank!==1&&t.rank!==2),function(){return"Error in dot: inputs must all be rank 1 or 2, but got ranks "+e.rank+" and "+t.rank+"."});var a=e.rank===1?e.size:e.shape[1],o=t.rank===1?t.size:t.shape[0];return D(a===o,function(){return"Error in dot: inner dimensions of inputs must match, but got "+a+" and "+o+"."}),e.rank===1&&t.rank===1?e.as2D(1,-1).matMul(t.as2D(-1,1)).asScalar():e.rank===1&&t.rank===2?e.as2D(1,-1).matMul(t.as2D(t.shape[0],t.shape[1])).as1D():e.rank===2&&t.rank===1?e.matMul(t.as2D(-1,1)).as1D():e.matMul(t.as2D(t.shape[0],t.shape[1]))}}),hp=K({outerProduct_:function(r,n){var e=F(r,"v1","outerProduct"),t=F(n,"v2","outerProduct");return D(e.rank===1&&t.rank===1,function(){return"Error in outerProduct: inputs must be rank 1, but got ranks "+e.rank+" and "+t.rank+"."}),e.as2D(-1,1).matMul(t.as2D(1,-1))}}),hi=K({reverse_:function(r,n){var e=F(r,"x","reverse");if(e.rank===0)return e.clone();var t=je(n,e.shape);return X.runKernelFunc(function(a){return a.reverse(e,t)},{$x:e},function(a){return{$x:function(){return a.reverse(t)}}}).reshapeAs(e)}}),pp=K({reverse1d_:function(r){var n=F(r,"x","reverse");return D(n.rank===1,function(){return"Error in reverse1D: x must be rank 1 but got rank "+n.rank+"."}),hi(n,0)}}),fp=K({reverse2d_:function(r,n){var e=F(r,"x","reverse");return D(e.rank===2,function(){return"Error in reverse2D: x must be rank 2 but got rank "+e.rank+"."}),hi(e,n)}}),vp=K({reverse3d_:function(r,n){var e=F(r,"x","reverse");return D(e.rank===3,function(){return"Error in reverse3D: x must be rank 3 but got rank "+e.rank+"."}),hi(e,n)}}),mp=K({reverse4d_:function(r,n){var e=F(r,"x","reverse");return D(e.rank===4,function(){return"Error in reverse4D: x must be rank 4 but got rank "+e.rank+"."}),hi(e,n)}});function ul(r,n,e,t,a,o){var i=F(r,"x","maxPool"),s=i,u=!1;i.rank===3&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),t==null&&(t=[1,1]),D(s.rank===4,function(){return"Error in maxPool: input must be rank 4 but got rank "+s.rank+"."}),D(Bn(e,t),function(){return"Error in maxPool: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+t+"'"}),o!=null&&D(Be(a),function(){return"Error in maxPool: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+a+"."});var c=Vr(s.shape,n,e,t,a,o);if(c.filterWidth===1&&c.filterHeight===1&&Oe(c.inShape,c.outShape))return i.clone();var d=[s],f=X.runKernelFunc(function(m,g){var x=m.maxPool(s,c);return g([s,x]),x},{x:s},function(m,g){var x=g[0],E=g[1];return{x:function(){return function(w,C,N,S,I,M,j,G){var z=F(w,"dy","maxPoolBackprop"),W=F(C,"input","maxPoolBackprop"),V=F(N,"output","maxPoolBackprop");D(W.rank===z.rank,function(){return"Rank of input ("+W.rank+") does not match rank of dy ("+z.rank+")"}),M==null&&(M=[1,1]),D(Bn(I,M),function(){return"Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides "+I+" and dilations '"+M+"'"}),D(z.rank===4,function(){return"Error in maxPoolBackprop: dy must be rank 4 but got rank "+z.rank+"."}),D(W.rank===4,function(){return"Error in maxPoolBackprop: input must be rank 4 but got rank "+W.rank+"."}),G!=null&&D(Be(j),function(){return"Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode "+G+" but got pad "+j+"."});var Z=Vr(W.shape,S,I,M,j,G);return X.runKernelFunc(function(J){return J.maxPoolBackprop(z,W,V,Z)},{$dy:z,$input:W})}(m,x,E,n,e,t,a)}}},"MaxPool",c,d);return u?f.as3D(f.shape[1],f.shape[2],f.shape[3]):f}function cl(r,n,e,t,a,o){var i=F(r,"x","avgPool","float32");t==null&&(t=[1,1]),D(Bn(e,t),function(){return"Error in avgPool: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+t+"'"});var s=i,u=!1;i.rank===3&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),D(s.rank===4,function(){return"Error in avgPool: x must be rank 4 but got rank "+s.rank+"."}),o!=null&&D(Be(a),function(){return"Error in avgPool: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+a+"."});var c=Vr(s.shape,n,e,t,a,o);if(c.filterWidth===1&&c.filterHeight===1&&Oe(c.inShape,c.outShape))return i.clone();var d=X.runKernelFunc(function(f){return f.avgPool(s,c)},{x:s},function(f){return{x:function(){return function(m,g,x,E,w,C){var N=F(m,"dy","avgPoolBackprop"),S=F(g,"input","avgPoolBackprop");D(S.rank===N.rank,function(){return"Rank of input ("+S.rank+") does not match rank of dy ("+N.rank+")"}),w==null&&(w=[1,1]),D(Bn(E,w),function(){return"Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides "+E+" and dilations '"+w+"'"});var I=S,M=N,j=!1;S.rank===3&&(j=!0,I=S.as4D(1,S.shape[0],S.shape[1],S.shape[2]),M=N.as4D(1,N.shape[0],N.shape[1],N.shape[2])),D(M.rank===4,function(){return"Error in avgPoolBackprop: dy must be rank 4 but got rank "+M.rank+"."}),D(I.rank===4,function(){return"Error in avgPoolBackprop: input must be rank 4 but got rank "+I.rank+"."});var G=Vr(I.shape,x,E,w,C),z=X.runKernelFunc(function(W){return W.avgPoolBackprop(M,I,G)},{dy4D:M,input4D:I});return j?z.as3D(z.shape[1],z.shape[2],z.shape[3]):z}(f,s,n,e,t,a)}}},"AvgPool",c);return d=d.cast(i.dtype),u?d.as3D(d.shape[1],d.shape[2],d.shape[3]):d}var ll=K({maxPool_:function(r,n,e,t,a){return ul(r,n,e,1,t,a)}}),dl=K({avgPool_:function(r,n,e,t,a){return cl(r,n,e,1,t,a)}}),gp=K({pool_:function(r,n,e,t,a,o){a==null&&(a=[1,1]),o==null&&(o=1),t===0&&(t="valid");var i=F(r,"x","maxPool"),s=i,u=!1;i.rank===3&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),D(Bn(o,a),function(){return"Error in pool: Either strides or dilations must be 1. Got strides "+o+" and dilations '"+a+"'"});var c,d=Vr(s.shape,n,o,a,t),f=[d.dilationHeight,d.dilationWidth];c=t==="same"?function(I,M){var j=I.map(function(W,V){return W+(W-1)*(M[V]-1)}).map(function(W){return W-1}),G=j.map(function(W){return Math.floor(W/2)}),z=j.map(function(W,V){return W-G[V]});return j.map(function(W,V){return[G[V],z[V]]})}([d.filterHeight,d.filterWidth],f):[[0,0],[0,0]];var m=f[0]===1&&f[1]===1,g=function(I,M,j){var G=j.map(function(fe){return fe[0]}),z=j.map(function(fe){return fe[1]}),W=I.concat(G,z),V=M.map(function(fe,he){return(fe-W[he]%fe)%fe}),Z=z.map(function(fe,he){return fe+V[he]}),J=M.map(function(fe,he){return[G[he],Z[he]]}),me=M.map(function(fe,he){return[0,V[he]]});return[J,me]}([d.inHeight,d.inWidth],f,c),x=g[0],E=g[1],w=m?t:"valid",C=m?s:Mi(s,f,x),N=(e==="avg"?function(){return cl(C,n,o,1,w)}:function(){return ul(C,n,o,1,w)})(),S=m?N:oo(N,f,E);return u?S.as3D(S.shape[1],S.shape[2],S.shape[3]):S}}),yp=K({maxPool3d_:function(r,n,e,t,a,o,i){o===void 0&&(o="NDHWC");var s=F(r,"x","maxPool3d"),u=s,c=!1;s.rank===4&&(c=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),i==null&&(i=[1,1,1]),D(u.rank===5,function(){return"Error in maxPool3d: x must be rank 5 but got rank "+u.rank+"."}),D(o==="NDHWC",function(){return"Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of "+o}),D(Bn(e,i),function(){return"Error in maxPool3d: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+i+"'"}),a!=null&&D(Be(t),function(){return"Error in maxPool3d: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+t+"."});var d=Oa(u.shape,n,e,i,t,a,o),f=X.runKernelFunc(function(m,g){var x=m.maxPool3d(u,d);return g([u,x]),x},{x:u},function(m,g){var x=g[0],E=g[1];return{x:function(){return function(w,C,N,S,I,M,j,G){var z=F(w,"dy","maxPool3dBackprop"),W=F(C,"input","maxPool3dBackprop"),V=F(N,"output","maxPool3dBackprop"),Z=z,J=W,me=V,fe=!1;W.rank===4&&(fe=!0,Z=z.as5D(1,z.shape[0],z.shape[1],z.shape[2],z.shape[3]),J=W.as5D(1,W.shape[0],W.shape[1],W.shape[2],W.shape[3]),me=V.as5D(1,V.shape[0],V.shape[1],V.shape[2],V.shape[3])),D(Z.rank===5,function(){return"Error in maxPool3dBackprop: dy must be rank 5 but got rank "+Z.rank+"."}),D(J.rank===5,function(){return"Error in maxPool3dBackprop: input must be rank 5 but got rank "+J.rank+"."}),D(me.rank===5,function(){return"Error in maxPool3dBackprop: output must be rank 5 but got rank "+me.rank+"."}),M==null&&(M=[1,1,1]),D(Bn(I,M),function(){return"Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides "+I+" and dilations '"+M+"'"}),G!=null&&D(Be(j),function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+G+" but got pad "+j+"."});var he=Oa(J.shape,S,I,M,j,G),Ee=X.runKernelFunc(function(be){return be.maxPool3dBackprop(Z,J,me,he)},{dy5D:Z,input5D:J});return fe?Ee.as4D(Ee.shape[1],Ee.shape[2],Ee.shape[3],Ee.shape[4]):Ee}(m,x,E,n,e,i,t,a)}}});return c?f.as4D(f.shape[1],f.shape[2],f.shape[3],f.shape[4]):f}}),xp=K({avgPool3d_:function(r,n,e,t,a,o,i){o===void 0&&(o="NDHWC");var s=F(r,"x","avgPool3d","float32"),u=s,c=!1;s.rank===4&&(c=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),i==null&&(i=[1,1,1]),D(u.rank===5,function(){return"Error in avgPool3d: x must be rank 5 but got rank "+u.rank+"."}),D(o==="NDHWC",function(){return"Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of "+o}),D(Bn(e,i),function(){return"Error in avgPool3d: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+i+"'"}),a!=null&&D(Be(t),function(){return"Error in avgPool3d: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+t+"."});var d=Oa(u.shape,n,e,i,t,a,o),f=X.runKernelFunc(function(m){return m.avgPool3d(u,d)},{x:u},function(m){return{x:function(){return function(g,x,E,w,C,N,S){var I=F(g,"dy","avgPool3dBackprop"),M=F(x,"input","avgPool3dBackprop"),j=I,G=M,z=!1;M.rank===4&&(z=!0,j=I.as5D(1,I.shape[0],I.shape[1],I.shape[2],I.shape[3]),G=M.as5D(1,M.shape[0],M.shape[1],M.shape[2],M.shape[3])),D(j.rank===5,function(){return"Error in avgPool3dBackprop: dy must be rank 5 but got rank "+j.rank+"."}),D(G.rank===5,function(){return"Error in avgPool3dBackprop: input must be rank 5 but got rank "+G.rank+"."}),C==null&&(C=[1,1,1]),D(Bn(w,C),function(){return"Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides "+w+" and dilations '"+C+"'"}),S!=null&&D(Be(N),function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+S+" but got pad "+N+"."});var W=Oa(G.shape,E,w,C,N,S),V=X.runKernelFunc(function(Z){return Z.avgPool3dBackprop(j,G,W)},{dy5D:j,input5D:G});return z?V.as4D(V.shape[1],V.shape[2],V.shape[3],V.shape[4]):V}(m,u,n,e,i,t,a)}}});return f=f.cast(u.dtype),c?f.as4D(f.shape[1],f.shape[2],f.shape[3],f.shape[4]):f}}),Hr=K({slice_:function(r,n,e){var t,a,o=F(r,"x","slice");if(o.rank===0)throw new Error("Slicing scalar is not possible");(t=typeof n=="number"?[n].concat(new Array(o.rank-1).fill(0)):n.length<o.rank?n.concat(new Array(o.rank-n.length).fill(0)):n.slice()).forEach(function(u){D(u!==-1,function(){return"slice() does not support negative begin indexing."})}),a=(a=e==null?new Array(o.rank).fill(-1):typeof e=="number"?[e].concat(new Array(o.rank-1).fill(-1)):e.length<o.rank?e.concat(new Array(o.rank-e.length).fill(-1)):e).map(function(u,c){return u>=0?u:(D(u===-1,function(){return"Negative size values should be exactly -1 but got "+u+" for the slice() size at index "+c+"."}),o.shape[c]-t[c])}),js(o,t,a);var i=o.shape,s={begin:t,size:a};return X.runKernelFunc(function(u){return u.slice(o,t,a)},{x:o},function(u){for(var c=[],d=0;d<u.rank;d++)c.push([t[d],i[d]-t[d]-a[d]]);return{x:function(){return u.pad(c)}}},"Slice",s)}}),bp=K({slice1d_:function(r,n,e){var t=F(r,"x","slice1d");return D(t.rank===1,function(){return"slice1d expects a rank-1 tensor, but got a rank-"+t.rank+" tensor"}),Hr(t,[n],[e])}}),wp=K({slice2d_:function(r,n,e){var t=F(r,"x","slice2d");return D(t.rank===2,function(){return"slice2d expects a rank-2 tensor, but got a rank-"+t.rank+" tensor"}),Hr(t,n,e)}}),hl=K({slice3d_:function(r,n,e){var t=F(r,"x","slice3d");return D(t.rank===3,function(){return"slice3d expects a rank-3 tensor, but got a rank-"+t.rank+" tensor"}),Hr(t,n,e)}}),Ep=K({slice4d_:function(r,n,e){var t=F(r,"x","slice4d");return D(t.rank===4,function(){return"slice4d expects a rank-4 tensor, but got a rank-"+t.rank+" tensor"}),Hr(t,n,e)}});function pl(r,n,e,t,a){return n.rank<e.rank&&(n=n.reshape(kn(n.shape,t))),r.rank<e.rank&&(r=r.reshape(kn(r.shape,t))),{x:function(){var o=r.mul(e.equal(n).cast(r.dtype));return a==null?o:o.transpose(a)}}}var _p=K({all_:function(r,n,e){n===void 0&&(n=null),e===void 0&&(e=!1);var t=F(r,"x","all","bool"),a=je(n,t.shape),o=a,i=Gn(o,t.rank);i!=null&&(t=t.transpose(i),o=Jn(o.length,t.rank));var s=X.runKernelFunc(function(c){return c.all(t,o)},{$x:t});if(e){var u=kn(s.shape,a);return s.reshape(u)}return s}}),Cp=K({any_:function(r,n,e){n===void 0&&(n=null),e===void 0&&(e=!1);var t=F(r,"x","any","bool"),a=je(n,t.shape),o=a,i=Gn(o,t.rank);i!=null&&(t=t.transpose(i),o=Jn(o.length,t.rank));var s=X.runKernelFunc(function(c){return c.any(t,o)},{$x:t});if(e){var u=kn(s.shape,a);return s.reshape(u)}return s}}),Rp=K({argMax_:function(r,n){n===void 0&&(n=0);var e=F(r,"x","argMax");n==null&&(n=0);var t=je(n,e.shape),a=Gn(t,e.rank);a!=null&&(e=e.transpose(a),t=Jn(t.length,e.rank));var o={axis:t[0]},i=[e];return X.runKernelFunc(function(s,u){var c=s.argMax(e,t[0]);return u([e]),c},{x:e},function(s,u){var c=u[0];return{x:function(){return gt(c)}}},"ArgMax",o,i)}}),Ap=K({argMin_:function(r,n){n===void 0&&(n=0);var e=F(r,"x","argMin");n==null&&(n=0);var t=je(n,e.shape),a=Gn(t,e.rank);return a!=null&&(e=e.transpose(a),t=Jn(t.length,e.rank)),X.runKernelFunc(function(o,i){var s=o.argMin(e,t[0]);return i([e]),s},{$x:e},function(o,i){var s=i[0];return{$x:function(){return gt(s)}}})}}),Tp=K({logSumExp_:function(r,n,e){n===void 0&&(n=null),e===void 0&&(e=!1);var t=F(r,"x","logSumExp"),a=je(n,t.shape),o=t.max(a,!0),i=t.sub(o).exp().sum(a).log(),s=o.reshape(i.shape).add(i);if(e){var u=kn(s.shape,a);return s.reshape(u)}return s}}),fl=K({max_:function(r,n,e){n===void 0&&(n=null),e===void 0&&(e=!1);var t=F(r,"x","max"),a=t,o=je(n,t.shape),i=o,s=Gn(i,t.rank);s!=null&&(t=t.transpose(s),i=Jn(i.length,t.rank));var u=[t],c=X.runKernelFunc(function(f,m){var g=f.max(t,i);return m([a,g]),g},{x:t},function(f,m){return pl(f,m[1],m[0],o,s)},"Max",{axes:i},u,[!0]);if(e){var d=kn(c.shape,o);c=c.reshape(d)}return c}}),Dp=K({mean_:function(r,n,e){n===void 0&&(n=null),e===void 0&&(e=!1);var t=F(r,"x","mean"),a=je(n,t.shape),o=ae(Nn(t.shape,a)[1]);return ca(function(i){var s=We(o);return{value:(s.dtype===i.dtype?i:i.cast(s.dtype)).div(s).sum(n,e),gradFunc:function(u){var c=i.shape.slice();return a.forEach(function(d){c[d]=1}),u.reshape(c).mul(_r(i.shape,"float32")).div(o)}}})(t)}}),Np=K({min_:function(r,n,e){n===void 0&&(n=null),e===void 0&&(e=!1);var t=F(r,"x","min"),a=t,o=je(n,t.shape),i=o,s=Gn(i,t.rank);s!=null&&(t=t.transpose(s),i=Jn(i.length,t.rank));var u=[t],c=X.runKernelFunc(function(f,m){var g=f.min(t,i);return m([a,g]),g},{x:t},function(f,m){return pl(f,m[1],m[0],o,s)},"Min",{axes:i},u,[!0]);if(e){var d=kn(c.shape,o);c=c.reshape(d)}return c}}),kp=K({moments_:function(r,n,e){n===void 0&&(n=null),e===void 0&&(e=!1);var t=je(n,(r=F(r,"x","moments")).shape),a=r.mean(t,e),o=a.shape;e||(o=kn(a.shape,t));var i=r.toFloat().sub(a.reshape(o)).square();return{mean:a,variance:i.mean(t,e)}}}),vl=K({sum_:function(r,n,e){n===void 0&&(n=null),e===void 0&&(e=!1);var t=F(r,"x","sum");t.dtype==="bool"&&(t=t.toInt());var a=je(n,t.shape);return ca(function(o){var i=Gn(a,o.rank),s=a,u=o;i!=null&&(u=o.transpose(i),s=Jn(s.length,o.rank));var c=function(g){var x=o.shape.slice();return a.forEach(function(E){x[E]=1}),g.reshape(x).mul(_r(o.shape,"float32"))},d={axes:s},f=X.runKernelFunc(function(g){return g.sum(u,s)},{x:u},function(g){return{x:function(){return c(g)}}},"Sum",d);if(e){var m=kn(f.shape,a);f=f.reshape(m)}return{value:f,gradFunc:c}})(t)}}),Sp=K({prod_:function(r,n,e){n===void 0&&(n=null),e===void 0&&(e=!1);var t=F(r,"x","prod");t.dtype==="bool"&&(t=t.toInt());var a=je(n,t.shape),o=Gn(a,t.rank),i=a,s=t;o!=null&&(s=t.transpose(o),i=Jn(i.length,t.rank));var u=X.runKernelFunc(function(d){return d.prod(s,i)},{permutedX:s});if(e){var c=kn(u.shape,a);u=u.reshape(c)}return u}}),ml=K({elu_:function(r){var n=F(r,"x","elu");return X.runKernelFunc(function(e,t){var a=e.elu(n);return t([a]),a},{$x:n},function(e,t){var a=t[0];return{$x:function(){return X.runKernelFunc(function(o){return o.eluDer(e,a)},{dy:e,y:a})}}})}}),Op=K({leakyRelu_:function(r,n){n===void 0&&(n=.2);var e=F(r,"x","leakyRelu");return au(We(n).mul(e),e)}}),gl=K({prelu_:function(r,n){var e=F(r,"x","prelu"),t=F(n,"alpha","prelu");return X.runKernelFunc(function(a,o){var i=a.prelu(e,t);return o([e,t]),i},{x:e,alpha:t},function(a,o){var i=o[0],s=o[1],u=i.greater(0);return{x:function(){return Pa(u,a,a.mul(s))},alpha:function(){var c=Pa(u,gt(a),a.mul(i)),d=tn(s.shape,a.shape);return d.length>0&&(c=c.sum(d)),c.reshape(s.shape)}}},"Prelu")}}),cu=K({relu_:function(r){var n=F(r,"x","relu");return n.dtype==="bool"?n.toInt():X.runKernelFunc(function(e,t){var a=e.relu(n);return t([n]),a},{x:n},function(e,t){var a=t[0];return{x:function(){return e.mulStrict(a.step().toFloat())}}},"Relu")}}),yl=K({relu6_:function(r){var n=F(r,"x","relu6");return n.dtype==="bool"?n.toInt():X.runKernelFunc(function(e,t){var a=e.relu6(n);return t([n]),a},{x:n},function(e,t){var a=t[0],o=a.lessEqual(6).mul(a.step());return{x:function(){return e.mulStrict(o.toFloat())}}},"Relu6")}}),Ip=K({selu_:function(r){var n=F(r,"x","selu");return X.runKernelFunc(function(e,t){var a=e.selu(n);return t([n]),a},{$x:n},function(e,t){var a=t[0];return{$x:function(){var o=a.greater(We(0)),i=We(tu),s=We(nu),u=e.mul(s),c=e.mul(i).mul(a.toFloat().exp());return Pa(o,u,c)}}})}}),xl=K({transpose_:function(r,n){var e=F(r,"x","transpose");if(n==null&&(n=e.shape.map(function(a,o){return o}).reverse()),D(e.rank===n.length,function(){return"Error in transpose: rank of input "+e.rank+" must match length of perm "+n+"."}),n.forEach(function(a){D(a>=0&&a<e.rank,function(){return"All entries in 'perm' must be between 0 and "+(e.rank-1)+" but got "+n})}),e.rank<=1)return e.clone();var t={perm:n};return X.runKernelFunc(function(a){return a.transpose(e,n)},{x:e},function(a){var o=oa(n);return{x:function(){return a.transpose(o)}}},"Transpose",t)}}),Mp=K({localResponseNormalization_:function(r,n,e,t,a){n===void 0&&(n=5),e===void 0&&(e=1),t===void 0&&(t=1),a===void 0&&(a=.5);var o=F(r,"x","localResponseNormalization");D(o.rank===4||o.rank===3,function(){return`Error in localResponseNormalization: x must be rank 3 or 4 but got
|
|
rank `+o.rank+"."}),D(Be(n),function(){return"Error in localResponseNormalization: depthRadius must be an integer but got depthRadius "+n+"."});var i=o,s=!1;o.rank===3&&(s=!0,i=o.as4D(1,o.shape[0],o.shape[1],o.shape[2]));var u=X.runKernelFunc(function(c,d){var f=c.localResponseNormalization4D(i,n,e,t,a);return d([i,f]),f},{x4D:i},function(c,d){var f=d[0],m=d[1];return{x4D:function(){return X.runKernelFunc(function(g){return g.LRNGrad(c,f,m,n,e,t,a)},{})}}});return s?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),bl=K({norm_:function(r,n,e,t){n===void 0&&(n="euclidean"),e===void 0&&(e=null),t===void 0&&(t=!1);var a=function s(u,c,d){if(d===void 0&&(d=null),u.rank===0)return u.abs();if(u.rank!==1&&d===null)return s(u.reshape([-1]),c,d);if(u.rank===1||typeof d=="number"||Array.isArray(d)&&d.length===1){if(c===1)return u.abs().sum(d);if(c===1/0)return u.abs().max(d);if(c===-1/0)return u.abs().min(d);if(c==="euclidean"||c===2)return u.abs().pow(We(2,"int32")).sum(d).sqrt();throw new Error("Error in norm: invalid ord value: "+c)}if(Array.isArray(d)&&d.length===2){if(c===1)return u.abs().sum(d[0]).max(d[1]-1);if(c===1/0)return u.abs().sum(d[1]).max(d[0]);if(c===-1/0)return u.abs().sum(d[1]).min(d[0]);if(c==="fro"||c==="euclidean")return u.square().sum(d).sqrt();throw new Error("Error in norm: invalid ord value: "+c)}throw new Error("Error in norm: invalid axis: "+d)}(r=F(r,"x","norm"),n,e),o=a.shape;if(t){var i=je(e,r.shape);o=kn(a.shape,i)}return a.reshape(o)}}),Fp=K({basicLSTMCell_:function(r,n,e,t,a,o){var i=F(r,"forgetBias","basicLSTMCell"),s=F(n,"lstmKernel","basicLSTMCell"),u=F(e,"lstmBias","basicLSTMCell"),c=F(t,"data","basicLSTMCell"),d=F(a,"c","basicLSTMCell"),f=F(o,"h","basicLSTMCell"),m=c.concat(f,1).matMul(s).add(u),g=m.shape[0],x=m.shape[1]/4,E=[g,x],w=m.slice([0,0],E),C=m.slice([0,x],E),N=m.slice([0,2*x],E),S=m.slice([0,3*x],E),I=w.sigmoid().mulStrict(C.tanh()).addStrict(d.mulStrict(i.add(N).sigmoid())),M=I.tanh().mulStrict(S.sigmoid());return[I,M]}}),Pp=K({multiRNNCell_:function(r,n,e,t){for(var a=F(n,"data","multiRNNCell"),o=aa(e,"c","multiRNNCell"),i=aa(t,"h","multiRNNCell"),s=a,u=[],c=0;c<r.length;c++){var d=r[c](s,o[c],i[c]);u.push(d[0]),u.push(d[1]),s=d[1]}var f=[],m=[];for(c=0;c<u.length;c+=2)f.push(u[c]),m.push(u[c+1]);return[f,m]}}),Lp=K({movingAverage_:function(r,n,e,t,a){a===void 0&&(a=!0);var o=F(r,"v","movingAverage"),i=F(n,"x","movingAverage"),s=F(e,"decay","movingAverage");Kn(o,i),D(Oe(o.shape,i.shape),function(){return"Shape mismatch in v and x"});var u=We(1),c=u.sub(s),d=i.sub(o).mul(c);if(a){D(t!=null,function(){return"When using zeroDebias: true, step is required."});var f=F(t,"step","movingAverage");d=d.div(u.sub(as(s,f)))}return o.add(d)}}),Bp=K({stridedSlice_:function(r,n,e,t,a,o,i,s,u){if(a===void 0&&(a=0),o===void 0&&(o=0),i===void 0&&(i=0),s===void 0&&(s=0),u===void 0&&(u=0),t==null&&(t=new Array(n.length)),i!==0)throw new Error("ellipsis mask is not yet supported");var c=F(r,"x","stridedSlice"),d=Bi(s),f=c.shape.slice();d.forEach(function(w){n[w]=0,e[w]=1,f.splice(w,0,1)}),c=c.reshape(f);for(var m=0;m<c.rank;m++)n[m]=Us(a,n,t,c.shape,m),e[m]=ji(o,e,t,c.shape,m),t[m]=t[m]||1;var g=Bi(u);g.forEach(function(w){e[w]=n[w]+1,t[w]=1});var x=ho(n,e,t),E=x.filter(function(w,C){return g.indexOf(C)===-1});return t.every(function(w){return w===1})?Hr(c,n,x).reshape(E):X.runKernelFunc(function(w){return w.stridedSlice(c,n,e,t)},{$x:c}).reshape(E)}}),jp=K({topk_:function(r,n,e){n===void 0&&(n=1),e===void 0&&(e=!0);var t=F(r,"x","topk");if(t.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");var a=t.shape[t.shape.length-1];if(n>a)throw new Error("'k' passed to topk() must be <= the last dimension ("+a+") but got "+n);var o=X.runKernelFunc(function(i){return i.topk(t,n,e)},{$x:t});return{values:o[0],indices:o[1]}}}),Up=K({scatterND_:function(r,n,e){var t=F(r,"indices","scatterND","int32"),a=F(n,"updates","scatterND");return Bs(a,t,e),X.runKernelFunc(function(o){return o.scatterND(t,a,e)},{indices:t,updates:a},null,"ScatterNd",{shape:e})}}),lu=K({fft_:function(r){D(r.dtype==="complex64",function(){return"The dtype for tf.spectral.fft() must be complex64 but got "+r.dtype+"."});var n=r.shape[r.shape.length-1],e=r.size/n,t=r.as2D(e,n);return X.runKernelFunc(function(a){return a.fft(t)},{input:r}).reshape(r.shape)}}),is=K({ifft_:function(r){D(r.dtype==="complex64",function(){return"The dtype for tf.spectral.ifft() must be complex64 but got "+r.dtype+"."});var n=r.shape[r.shape.length-1],e=r.size/n,t=r.as2D(e,n);return X.runKernelFunc(function(a){return a.ifft(t)},{input:r}).reshape(r.shape)}}),du=K({rfft_:function(r,n){D(r.dtype==="float32",function(){return"The dtype for rfft() must be real value but got "+r.dtype});var e,t=r.shape[r.shape.length-1],a=r.size/t;if(n!=null&&n<t){var o=r.shape.map(function(C){return 0}),i=r.shape.map(function(C){return C});i[r.shape.length-1]=n,e=r.slice(o,i),t=n}else if(n!=null&&n>t){var s=r.shape.map(function(C){return C});s[r.shape.length-1]=n-t,e=r.concat(Jt(s),r.shape.length-1),t=n}else e=r;var u=e.zerosLike(),c=zt(e,u).as2D(a,t),d=lu(c),f=Math.floor(t/2)+1,m=Hn(d),g=cr(d),x=m.split([f,t-f],m.shape.length-1),E=g.split([f,t-f],g.shape.length-1),w=e.shape.slice();return w[e.shape.length-1]=f,zt(x[0],E[0]).reshape(w)}}),wl=K({irfft_:function(r){var n=r.shape[r.shape.length-1],e=r.size/n;if(n<=2){var t=r.as2D(e,n),a=is(t);return Hn(a)}var o=[e,2*(n-1)],i=Hn(r).as2D(e,n),s=cr(r).as2D(e,n),u=i.slice([0,1],[e,n-2]).reverse(1),c=s.slice([0,1],[e,n-2]).reverse(1).mul(We(-1)),d=i.concat(u,1),f=s.concat(c,1);return t=zt(d,f).as2D(o[0],o[1]),a=is(t),Hn(a)}}),Wp=Object.freeze({fft:lu,ifft:is,rfft:du,irfft:wl}),zp=K({sparseToDense_:function(r,n,e,t){t===void 0&&(t=0);var a=F(r,"sparseIndices","sparseToDense","int32"),o=F(n,"sparseValues","sparseToDense"),i=F(t,"defaultValue","sparseToDense",o.dtype);return function(s,u,c,d){if(s.dtype!=="int32")throw new Error("tf.sparseToDense() expects the indices to be int32 type, but the dtype was "+s.dtype+".");if(s.rank>2)throw new Error("sparseIndices should be a scalar, vector, or matrix, but got shape "+s.shape+".");var f=s.rank>0?s.shape[0]:1,m=s.rank>1?s.shape[1]:1;if(c.length!==m)throw new Error("outputShape has incorrect number of elements:, "+c.length+", should be: "+m+".");var g=u.size;if(u.rank!==0&&(u.rank!==1||g!==f))throw new Error("sparseValues has incorrect shape "+u.shape+", should be [] or ["+f+"]");if(u.dtype!==d.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(a,o,e,i),X.runKernelFunc(function(s){return s.sparseToDense(a,o,e,i)},{$sparseIndices:a,$sparseValues:o,$defaultValue:i})}}),Vp=K({gatherND_:function(r,n){var e=F(n,"indices","gatherND","int32"),t=F(r,"x","gatherND");return X.runKernelFunc(function(a){return a.gatherND(t,e)},{x:t,indices:e},null,"GatherNd")}}),Gp=K({diag_:function(r){var n=F(r,"x","diag").flatten(),e=r.shape.concat(r.shape);return X.runKernelFunc(function(t){return t.diag(n)},{$x:n}).reshape(e)}}),Hp=K({dropout_:function(r,n,e,t){var a=F(r,"x","dropout");if(D(a.dtype==="float32",function(){return"x has to be a floating point tensor since it's going to be scaled, but got a "+a.dtype+" tensor instead."}),D(n>=0&&n<1,function(){return"rate must be a float in the range [0, 1), but got "+n+"."}),n===0)return r instanceof fn?a.clone():a;var o=function(u,c){if(c==null)return u.shape.slice();if(Oe(u.shape,c))return c;if(u.shape.length===c.length){for(var d=[],f=0;f<u.shape.length;f++)c[f]==null&&u.shape[f]!=null?d.push(u.shape[f]):d.push(c[f]);return d}return c}(a,e),i=1-n,s=Qo(o,0,1,"float32",t).add(i).floor().div(i);return a.mul(s)}});function El(r,n,e){for(var t=1-r%2,a=new Float32Array(r),o=0;o<r;++o){var i=2*Math.PI*o/(r+t-1);a[o]=n-e*Math.cos(i)}return Ur(a,"float32")}var hu=K({hannWindow_:function(r){return El(r,.5,.5)}}),_l=K({hammingWindow_:function(r){return El(r,.54,.46)}}),pu=K({frame_:function(r,n,e,t,a){t===void 0&&(t=!1),a===void 0&&(a=0);for(var o=0,i=[];o+n<=r.size;)i.push(Hr(r,o,n)),o+=e;if(t)for(;o<r.size;){var s=o+n-r.size,u=Qn([Hr(r,o,n-s),qo([s],a)]);i.push(u),o+=e}return i.length===0?Wr([],[0,n]):Qn(i).as2D(i.length,n)}}),Cl=K({stft_:function(r,n,e,t,a){var o;a===void 0&&(a=hu),t==null&&(o=n,t=Math.floor(Math.pow(2,Math.ceil(Math.log(o)/Math.log(2)))));for(var i=pu(r,n,e),s=Ba(i,a(n)),u=[],c=0;c<i.shape[0];c++)u.push(du(s.slice([c,0],[1,n]),t));return Qn(u)}}),Xp=Object.freeze({hannWindow:hu,hammingWindow:_l,frame:pu,stft:Cl}),jn,Kp=function(r,n,e){return e===void 0&&(e=1),ve(this,void 0,void 0,function(){var t,a,o,i,s,u,c,d,f,m,g,x,E,w;return ye(this,function(C){switch(C.label){case 0:return t=F(r,"predictions","inTopK"),a=F(n,"targets","inTopK"),D(t.rank>1,function(){return"inTopK() expects the predictions to be of rank 2 or higher, but got "+t.rank}),D(t.rank-1===a.rank,function(){return"predictions rank should be 1 larger than targets rank, but got predictions rank "+t.rank+" and targets rank "+a.rank}),se(t.shape.slice(0,t.shape.length-1),a.shape,"predictions's shape should be align with the targets' shape, except the last dimension."),o=t.shape[t.shape.length-1],D(e>0&&e<=o,function(){return"'k' passed to inTopK() must be > 0 && <= the predictions last dimension ("+o+"), but got "+e}),[4,t.data()];case 1:return i=C.sent(),[4,a.data()];case 2:for(s=C.sent(),u=[i.length/o,o],d=u[1],f=Cn("bool",c=u[0]),m=0;m<c;m++){for(g=m*d,x=i.subarray(g,g+d),E=[],w=0;w<x.length;w++)E.push({value:x[w],index:w});for(E.sort(function(N,S){return S.value-N.value}),f[m]=0,w=0;w<e;w++)if(E[w].index===s[m]){f[m]=1;break}}return r!==t&&t.dispose(),n!==a&&a.dispose(),[2,_n(f,a.shape,"bool")]}})})};!function(r){r[r.NONE=0]="NONE",r[r.MEAN=1]="MEAN",r[r.SUM=2]="SUM",r[r.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"}(jn||(jn={}));var qp=K({absoluteDifference_:function(r,n,e,t){t===void 0&&(t=jn.SUM_BY_NONZERO_WEIGHTS);var a=F(r,"labels","absoluteDifference"),o=F(n,"predictions","absoluteDifference"),i=null;e!=null&&(i=F(e,"weights","absoluteDifference")),se(a.shape,o.shape,"Error in absoluteDifference: ");var s=a.sub(o).abs();return Xr(s,i,t)}}),Xr=K({computeWeightedLoss_:function(r,n,e){e===void 0&&(e=jn.SUM_BY_NONZERO_WEIGHTS);var t=F(r,"losses","computeWeightedLoss"),a=null;n!=null&&(a=F(n,"weights","computeWeightedLoss"));var o=a==null?t:t.mul(a);if(e===jn.NONE)return o;if(e===jn.SUM)return o.sum();if(e===jn.MEAN){if(a==null)return o.mean();var i=t.size/a.size,s=o.sum().div(a.sum());return i>1?s.div(We(i)):s}if(e===jn.SUM_BY_NONZERO_WEIGHTS){if(a==null)return o.sum().div(We(t.size));var u=a.mul(_r(t.shape)).notEqual(We(0)).sum().toFloat();return o.sum().div(u)}throw Error("Unknown reduction: "+e)}}),Yp=K({cosineDistance_:function(r,n,e,t,a){a===void 0&&(a=jn.SUM_BY_NONZERO_WEIGHTS);var o=F(r,"labels","cosineDistance"),i=F(n,"predictions","cosineDistance"),s=null;t!=null&&(s=F(t,"weights","cosineDistance")),se(o.shape,i.shape,"Error in cosineDistance: ");var u=We(1).sub(o.mul(i).sum(e,!0));return Xr(u,s,a)}}),$p=K({hingeLoss_:function(r,n,e,t){t===void 0&&(t=jn.SUM_BY_NONZERO_WEIGHTS);var a=F(r,"labels","hingeLoss"),o=F(n,"predictions","hingeLoss"),i=null;e!=null&&(i=F(e,"weights","hingeLoss")),se(a.shape,o.shape,"Error in hingeLoss: ");var s=We(1);a=We(2).mul(a).sub(s);var u=s.sub(a.mul(o)).relu();return Xr(u,i,t)}}),Jp=K({huberLoss_:function(r,n,e,t,a){t===void 0&&(t=1),a===void 0&&(a=jn.SUM_BY_NONZERO_WEIGHTS);var o=F(r,"labels","huberLoss"),i=F(n,"predictions","huberLoss"),s=null;e!=null&&(s=F(e,"weights","huberLoss")),se(o.shape,i.shape,"Error in huberLoss: ");var u=We(t),c=i.sub(o).abs(),d=$c(c,u),f=c.sub(d),m=We(.5).mul(d.square()).add(u.mul(f));return Xr(m,s,a)}}),Qp=K({logLoss_:function(r,n,e,t,a){t===void 0&&(t=1e-7),a===void 0&&(a=jn.SUM_BY_NONZERO_WEIGHTS);var o=F(r,"labels","logLoss"),i=F(n,"predictions","logLoss"),s=null;e!=null&&(s=F(e,"weights","logLoss")),se(o.shape,i.shape,"Error in logLoss: ");var u=We(1),c=We(t),d=o.mul(i.add(c).log()).neg().sub(u.sub(o).mul(u.sub(i).add(c).log()));return Xr(d,s,a)}}),Zp=K({meanSquaredError_:function(r,n,e,t){t===void 0&&(t=jn.SUM_BY_NONZERO_WEIGHTS);var a=F(r,"labels","meanSquaredError"),o=F(n,"predictions","meanSquaredError"),i=null;e!=null&&(i=F(e,"weights","meanSquaredError")),se(a.shape,o.shape,"Error in meanSquaredError: ");var s=a.squaredDifference(o);return Xr(s,i,t)}}),ef=K({sigmoidCrossEntropy_:function(r,n,e,t,a){t===void 0&&(t=0),a===void 0&&(a=jn.SUM_BY_NONZERO_WEIGHTS);var o=F(r,"multiClassLabels","sigmoidCrossEntropy"),i=F(n,"logits","sigmoidCrossEntropy"),s=null;if(e!=null&&(s=F(e,"weights","sigmoidCrossEntropy")),se(o.shape,i.shape,"Error in sigmoidCrossEntropy: "),t>0){var u=We(t),c=We(1),d=We(.5);o=o.mul(c.sub(u)).add(d.mul(u))}var f=function(m,g){var x=F(m,"labels","sigmoidCrossEntropyWithLogits"),E=F(g,"logits","sigmoidCrossEntropyWithLogits");se(x.shape,E.shape,"Error in sigmoidCrossEntropyWithLogits: ");var w=E.relu(),C=E.mul(x),N=E.abs().neg().exp().log1p();return w.sub(C).add(N)}(o,i);return Xr(f,s,a)}}),tf=K({softmaxCrossEntropy_:function(r,n,e,t,a){t===void 0&&(t=0),a===void 0&&(a=jn.SUM_BY_NONZERO_WEIGHTS);var o=F(r,"onehotLabels","softmaxCrossEntropy"),i=F(n,"logits","softmaxCrossEntropy"),s=null;if(e!=null&&(s=F(e,"weights","softmaxCrossEntropy")),se(o.shape,i.shape,"Error in softmaxCrossEntropy: "),t>0){var u=We(t),c=We(1),d=We(o.shape[1]);o=o.mul(c.sub(u)).add(u.div(d))}var f=function(m,g,x){if(x===void 0&&(x=-1),x===-1&&(x=g.rank-1),x!==g.rank-1)throw Error("Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank "+g.rank+" and dim was "+x);return ca(function(E,w,C){var N=w.logSumExp([x],!0),S=w.toFloat().sub(N);return C([E,S]),{value:S.mul(E).neg().sum([x]),gradFunc:function(I,M){var j=M[0],G=M[1],z=kn(I.shape,[x]);return[I.reshape(z).mul(j.toFloat().sub(G.exp())),I.reshape(z).mul(G.exp().sub(j.toFloat()))]}}})(m,g)}(o,i);return Xr(f,s,a)}}),nf=Object.freeze({get Reduction(){return jn},absoluteDifference:qp,computeWeightedLoss:Xr,cosineDistance:Yp,hingeLoss:$p,huberLoss:Jp,logLoss:Qp,meanSquaredError:Zp,sigmoidCrossEntropy:ef,softmaxCrossEntropy:tf});function Rl(r,n){return n===void 0&&(n=!1),X.tidy(function(){if(r.shape.length!==2)throw new Error("qr2d() requires a 2D Tensor, but got a "+r.shape.length+"D Tensor.");for(var e=r.shape[0],t=r.shape[1],a=Oi(e),o=r.clone(),i=Wr([[1]],[1,1]),s=i.clone(),u=e>=t?t:e,c=function(f){var m,g=o,x=s,E=a;m=X.tidy(function(){var w=o.slice([f,f],[e-f,1]),C=w.norm(),N=o.slice([f,f],[1,1]),S=Wr([[-1]]).where(N.greater(0),Wr([[1]])),I=N.sub(S.mul(C)),M=w.div(I);s=M.shape[0]===1?i.clone():i.concat(M.slice([1,0],[M.shape[0]-1,M.shape[1]]),0);var j=S.matMul(I).div(C).neg(),G=o.slice([f,0],[e-f,t]),z=j.mul(s);if(f===0)o=G.sub(z.matMul(s.transpose().matMul(G)));else{var W=G.sub(z.matMul(s.transpose().matMul(G)));o=o.slice([0,0],[f,t]).concat(W,0)}var V=a.slice([0,f],[e,a.shape[1]-f]);if(f===0)a=V.sub(V.matMul(s).matMul(z.transpose()));else{var Z=V.sub(V.matMul(s).matMul(z.transpose()));a=a.slice([0,0],[e,f]).concat(Z,1)}return[s,o,a]}),s=m[0],o=m[1],a=m[2],Pn([g,x,E])},d=0;d<u;++d)c(d);return!n&&e>t&&(a=a.slice([0,0],[e,t]),o=o.slice([0,0],[t,t])),[a,o]})}var rf=K({bandPart_:function(r,n,e){if(n%1!=0)throw new Error("bandPart(): numLower must be an integer, got "+n+".");if(e%1!=0)throw new Error("bandPart(): numUpper must be an integer, got "+e+".");var t=F(r,"a","bandPart");if(t.rank<2)throw new Error("bandPart(): Rank must be at least 2, got "+t.rank+".");var a=t.shape,o=t.shape.slice(-2),i=o[0],s=o[1];if(!(n<=i))throw new Error("bandPart(): numLower ("+n+") must not be greater than the number of rows ("+i+").");if(!(e<=s))throw new Error("bandPart(): numUpper ("+e+") must not be greater than the number of columns ("+s+").");n<0&&(n=i),e<0&&(e=s);var u=to(0,i,1,"int32").reshape([-1,1]),c=to(0,s,1,"int32"),d=va(u,c),f=ns(d.lessEqual(We(+n,"int32")),d.greaterEqual(We(-e,"int32"))),m=Jt([i,s],t.dtype);return Ar(co(t.reshape([-1,i,s])).map(function(g){return Pa(f,g,m)})).reshape(a)}}),af=K({gramSchmidt_:function(r){var n;if(Array.isArray(r)){n=!1,D(r!=null&&r.length>0,function(){return"Gram-Schmidt process: input must not be null, undefined, or empty"});for(var e=r[0].shape[0],t=function(u){D(r[u].shape[0]===e,function(){return"Gram-Schmidt: Non-unique lengths found in the input vectors: ("+r[u].shape[0]+" vs. "+e+")"})},a=1;a<r.length;++a)t(a)}else n=!0,r=Ta(r,r.shape[0],0).map(function(u){return Fi(u,[0])});D(r.length<=r[0].shape[0],function(){return"Gram-Schmidt: Number of vectors ("+r.length+") exceeds number of dimensions ("+r[0].shape[0]+")."});var o=[],i=r,s=function(u){o.push(X.tidy(function(){var c=i[u];if(u>0)for(var d=0;d<u;++d){var f=vl(o[d].mulStrict(c)).mul(o[d]);c=c.sub(f)}return c.div(bl(c,"euclidean"))}))};for(a=0;a<r.length;++a)s(a);return n?Ar(o,0):o}}),of=K({qr_:function(r,n){if(n===void 0&&(n=!1),r.rank<2)throw new Error("qr() requires input tensor to have a rank >= 2, but got rank "+r.rank);if(r.rank===2)return Rl(r,n);var e=r.shape.slice(0,r.shape.length-2).reduce(function(i,s){return i*s}),t=co(r.reshape([e,r.shape[r.shape.length-2],r.shape[r.shape.length-1]]),0),a=[],o=[];return t.forEach(function(i){var s=Rl(i,n),u=s[0],c=s[1];a.push(u),o.push(c)}),[Ar(a,0).reshape(r.shape),Ar(o,0).reshape(r.shape)]}}),sf=Object.freeze({bandPart:rf,gramSchmidt:af,qr:of});function ss(r,n,e,t,a,o){t==null&&(t=.5),a==null&&(a=Number.NEGATIVE_INFINITY),o==null&&(o=0);var i=r.shape[0];return e=Math.min(e,i),D(0<=t&&t<=1,function(){return"iouThreshold must be in [0, 1], but was '"+t+"'"}),D(r.rank===2,function(){return"boxes must be a 2D tensor, but was of rank '"+r.rank+"'"}),D(r.shape[1]===4,function(){return"boxes must have 4 columns, but 2nd dimension was "+r.shape[1]}),D(n.rank===1,function(){return"scores must be a 1D tensor"}),D(n.shape[0]===i,function(){return"scores has incompatible shape with boxes. Expected "+i+", but was "+n.shape[0]}),D(0<=o&&o<=1,function(){return"softNmsSigma must be in [0, 1], but was '"+o+"'"}),{maxOutputSize:e,iouThreshold:t,scoreThreshold:a,softNmsSigma:o}}var uf=K({resizeBilinear_:function(r,n,e){e===void 0&&(e=!1);var t=F(r,"images","resizeBilinear");D(t.rank===3||t.rank===4,function(){return"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+t.rank+"."}),D(n.length===2,function(){return"Error in resizeBilinear: new shape must 2D, but got shape "+n+"."});var a=t,o=!1;t.rank===3&&(o=!0,a=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var i=n[0],s=n[1],u=X.runKernelFunc(function(c,d){return d([a]),c.resizeBilinear(a,i,s,e)},{x:a},function(c,d){return{x:function(){return X.runKernelFunc(function(f){return f.resizeBilinearBackprop(c,d[0],e)},{})}}},"ResizeBilinear",{alignCorners:e,newHeight:i,newWidth:s});return o?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),cf=K({resizeNearestNeighbor_:function(r,n,e){e===void 0&&(e=!1);var t=F(r,"images","resizeNearestNeighbor");D(t.rank===3||t.rank===4,function(){return"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+t.rank+"."}),D(n.length===2,function(){return"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+n+"."}),D(t.dtype==="float32"||t.dtype==="int32",function(){return"`images` must have `int32` or `float32` as dtype"});var a=t,o=!1;t.rank===3&&(o=!0,a=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var i=n[0],s=n[1],u=X.runKernelFunc(function(c,d){return d([a]),c.resizeNearestNeighbor(a,i,s,e)},{batchImages:a},function(c,d){return{batchImages:function(){return X.runKernelFunc(function(f){return f.resizeNearestNeighborBackprop(c,d[0],e)},{})}}});return o?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),lf=K({nonMaxSuppression_:function(r,n,e,t,a){t===void 0&&(t=.5),a===void 0&&(a=Number.NEGATIVE_INFINITY);var o=F(r,"boxes","nonMaxSuppression"),i=F(n,"scores","nonMaxSuppression"),s=ss(o,i,e,t,a);e=s.maxOutputSize,t=s.iouThreshold,a=s.scoreThreshold;var u={maxOutputSize:e,iouThreshold:t,scoreThreshold:a};return X.runKernelFunc(function(c){return c.nonMaxSuppression(o,i,e,t,a)},{boxes:o,scores:i},null,"NonMaxSuppressionV3",u)}}),df=function(r,n,e,t,a){return t===void 0&&(t=.5),a===void 0&&(a=Number.NEGATIVE_INFINITY),ve(this,void 0,void 0,function(){var o,i,s,u,c,d,f;return ye(this,function(m){switch(m.label){case 0:return o=F(r,"boxes","nonMaxSuppressionAsync"),i=F(n,"scores","nonMaxSuppressionAsync"),s=ss(o,i,e,t,a),e=s.maxOutputSize,t=s.iouThreshold,a=s.scoreThreshold,[4,Promise.all([o.data(),i.data()])];case 1:return u=m.sent(),c=u[0],d=u[1],f=ai(c,d,e,t,a),o!==r&&o.dispose(),i!==n&&i.dispose(),[2,f]}})})},hf=K({nonMaxSuppressionWithScore_:function(r,n,e,t,a,o){t===void 0&&(t=.5),a===void 0&&(a=Number.NEGATIVE_INFINITY),o===void 0&&(o=0);var i=F(r,"boxes","nonMaxSuppression"),s=F(n,"scores","nonMaxSuppression"),u=ss(i,s,e,t,a,o),c={maxOutputSize:e=u.maxOutputSize,iouThreshold:t=u.iouThreshold,scoreThreshold:a=u.scoreThreshold,softNmsSigma:o=u.softNmsSigma},d=X.runKernel("NonMaxSuppressionV5",{boxes:i,scores:s},c);return{selectedIndices:d[0],selectedScores:d[1]}}}),pf=function(r,n,e,t,a,o){return t===void 0&&(t=.5),a===void 0&&(a=Number.NEGATIVE_INFINITY),o===void 0&&(o=0),ve(this,void 0,void 0,function(){var i,s,u,c,d,f,m;return ye(this,function(g){switch(g.label){case 0:return i=F(r,"boxes","nonMaxSuppressionAsync"),s=F(n,"scores","nonMaxSuppressionAsync"),u=ss(i,s,e,t,a,o),e=u.maxOutputSize,t=u.iouThreshold,a=u.scoreThreshold,o=u.softNmsSigma,[4,Promise.all([i.data(),s.data()])];case 1:return c=g.sent(),d=c[0],f=c[1],m=oi(d,f,e,t,a,o),i!==r&&i.dispose(),s!==n&&s.dispose(),[2,m]}})})},ff=K({cropAndResize_:function(r,n,e,t,a,o){var i=F(r,"image","cropAndResize"),s=F(n,"boxes","cropAndResize","float32"),u=F(e,"boxInd","cropAndResize","int32");a=a||"bilinear",o=o||0;var c=s.shape[0];return D(i.rank===4,function(){return"Error in cropAndResize: image must be rank 4,but got rank "+i.rank+"."}),D(s.rank===2&&s.shape[1]===4,function(){return"Error in cropAndResize: boxes must be have size ["+c+",4] but had shape "+s.shape+"."}),D(u.rank===1&&u.shape[0]===c,function(){return"Error in cropAndResize: boxInd must be have size ["+c+"] but had shape "+s.shape+"."}),D(t.length===2,function(){return"Error in cropAndResize: cropSize must be of length 2, but got length "+t.length+"."}),D(t[0]>=1&&t[1]>=1,function(){return"cropSize must be atleast [1,1], but was "+t}),D(a==="bilinear"||a==="nearest",function(){return"method must be bilinear or nearest, but was "+a}),X.runKernelFunc(function(d,f){return d.cropAndResize(i,s,u,t,a,o)},{images:i,boxes:s,boxInd:u},null,"CropAndResize",{method:a,extrapolationValue:o,cropSize:t})}}),Al=Object.freeze({resizeBilinear:uf,resizeNearestNeighbor:cf,nonMaxSuppression:lf,nonMaxSuppressionAsync:df,nonMaxSuppressionWithScore:hf,nonMaxSuppressionWithScoreAsync:pf,cropAndResize:ff}),fu=function(r,n){return!(r>0)||n==="linear"},vu=function(r,n,e){if(e==null||e==="linear")return r;if(e==="relu")return r.mul(n.step());throw new Error("Gradient for activation "+e+" has not been implemented yet.")},mu=function(r,n){var e=n,t=tn(r.shape,n.shape);return t.length>0&&(e=e.sum(t)),e.reshape(r.shape)},gu=function(r,n,e){if(n==="linear")return r;if(n==="relu")return cu(r);if(n==="elu")return ml(r);if(n==="relu6")return yl(r);if(n==="prelu")return gl(r,e);throw new Error("Unknown fused activation "+n+".")},vf=K({fusedMatMul_:function(r){var n,e=r.a,t=r.b,a=r.transposeA,o=a!==void 0&&a,i=r.transposeB,s=i!==void 0&&i,u=r.bias,c=r.activation,d=c===void 0?"linear":c,f=r.preluActivationWeights;if(fu(X.state.gradientDepth,d)===!1){var m=uu(e,t,o,s);return u!=null&&(m=La(m,u)),gu(m,d,f)}var g=F(e,"a","fused matMul"),x=F(t,"b","fused matMul");n=Wt(g,x),g=n[0],x=n[1];var E=o?g.shape[g.rank-2]:g.shape[g.rank-1],w=s?x.shape[x.rank-1]:x.shape[x.rank-2],C=o?g.shape[g.rank-1]:g.shape[g.rank-2],N=s?x.shape[x.rank-2]:x.shape[x.rank-1],S=g.shape.slice(0,-2),I=x.shape.slice(0,-2),M=ae(S),j=ae(I);D(g.rank>=2&&x.rank>=2&&g.rank===x.rank,function(){return"Error in fused matMul: inputs must have the same rank of at least 2, got ranks "+g.rank+" and "+x.rank+"."}),D(Oe(S,I),function(){return"Error in fused matMul: outer dimensions ("+S+") and ("+I+") of Tensors with shapes "+g.shape+" and "+x.shape+" must match."}),D(E===w,function(){return"Error in fused matMul: inner shapes ("+E+") and ("+w+") of Tensors with shapes "+g.shape+" and "+x.shape+" and transposeA="+o+" and transposeB="+s+" must match."});var G,z,W=g.shape.slice(0,-2).concat([C,N]),V=o?g.as3D(M,E,C):g.as3D(M,C,E),Z=s?x.as3D(j,N,w):x.as3D(j,w,N);u!=null&&nt(W,(G=Wt(G=F(u,"bias","fused matMul"),g)[0]).shape),f!=null&&(z=F(f,"prelu weights","fused matMul"));var J={a:V,b:Z};u!=null&&(J.bias=G),f!=null&&(J.preluActivationWeights=z);var me=[V,Z];return X.runKernelFunc(function(fe,he){var Ee=fe.fusedBatchMatMul({a:V,b:Z,transposeA:o,transposeB:s,bias:G,activation:d,preluActivationWeights:z});return he([V,Z,Ee]),Ee},J,function(fe,he){var Ee=he[0],be=he[1],pe=he[2],Ce=vu(fe,pe,d),Re={};return u!=null&&(Re={bias:function(){return mu(G,Ce)}}),o||s?!o&&s?Object.assign({a:function(){return Ce.matMul(be,!1,!1)},b:function(){return Ce.matMul(Ee,!0,!1)}},Re):o&&!s?Object.assign({a:function(){return be.matMul(Ce,!1,!0)},b:function(){return Ee.matMul(Ce,!1,!1)}},Re):Object.assign({a:function(){return be.matMul(Ce,!0,!0)},b:function(){return Ce.matMul(Ee,!0,!0)}},Re):Object.assign({a:function(){return Ce.matMul(be,!1,!0)},b:function(){return Ee.matMul(Ce,!0,!1)}},Re)},"_FusedMatMul",{transposeA:o,transposeB:s,activation:d},me,[!0]).reshape(W)}}),mf=K({fusedConv2d_:function(r){var n=r.x,e=r.filter,t=r.strides,a=r.pad,o=r.dataFormat,i=o===void 0?"NHWC":o,s=r.dilations,u=s===void 0?[1,1]:s,c=r.dimRoundingMode,d=r.bias,f=r.activation,m=f===void 0?"linear":f,g=r.preluActivationWeights;if(m=m||"linear",fu(X.state.gradientDepth,m)===!1){var x=xo(n,e,t,a,i,u,c);return d!=null&&(x=La(x,d)),gu(x,m,g)}var E=F(n,"x","conv2d"),w=F(e,"filter","conv2d"),C=E,N=!1;E.rank===3&&(N=!0,C=E.as4D(1,E.shape[0],E.shape[1],E.shape[2])),D(C.rank===4,function(){return"Error in fused conv2d: input must be rank 4, but got rank "+C.rank+"."}),D(w.rank===4,function(){return"Error in fused conv2d: filter must be rank 4, but got rank "+w.rank+"."}),c!=null&&D(Be(a),function(){return"Error in fused conv2d: pad must be an integer when using, dimRoundingMode "+c+" but got pad "+a+"."}),D(C.shape[3]===w.shape[2],function(){return"Error in conv2d: depth of input ("+C.shape[3]+") must match input depth for filter "+w.shape[2]+"."}),D(Bn(t,u),function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+t+" and dilations '"+u+"'"}),D(i==="NHWC",function(){return"Error in conv2d: got dataFormat of "+i+" but only NHWC is currently supported."});var S,I,M=Tr(C.shape,w.shape,t,u,a,c);d!=null&&(S=Wt(S=F(d,"bias","fused conv2d"),E)[0],nt(M.outShape,S.shape)),g!=null&&(I=F(g,"prelu weights","fused conv2d"));var j={x:C,filter:w};d!=null&&(j.bias=S),g!=null&&(j.preluActivationWeights=I);var G=[w,C],z=X.runKernelFunc(function(W,V){var Z=W.fusedConv2d({input:C,filter:w,convInfo:M,bias:S,activation:m,preluActivationWeights:I});return V([w,C,Z]),Z},j,function(W,V){var Z=V,J=Z[0],me=Z[1],fe=Z[2],he=vu(W,fe,m);D(ha(u),function(){return"Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+u+"'"});var Ee={};return d!=null&&(Ee={bias:function(){return mu(S,he)}}),Object.assign({x:function(){return al(me.shape,he,J,t,a)},filter:function(){return su(me,he,J.shape,t,a)}},Ee)},"FusedConv2D",{convInfo:M,activation:m},G,[!0]);return N?z.as3D(z.shape[1],z.shape[2],z.shape[3]):z}}),gf=K({fusedDepthwiseConv2d_:function(r){var n=r.x,e=r.filter,t=r.strides,a=r.pad,o=r.dataFormat,i=o===void 0?"NHWC":o,s=r.dilations,u=s===void 0?[1,1]:s,c=r.dimRoundingMode,d=r.bias,f=r.activation,m=f===void 0?"linear":f,g=r.preluActivationWeights;if(fu(X.state.gradientDepth,m)===!1){var x=os(n,e,t,a,i,u,c);return d!=null&&(x=La(x,d)),gu(x,m,g)}var E=F(n,"x","depthwiseConv2d"),w=F(e,"filter","depthwiseConv2d"),C=E,N=!1;E.rank===3&&(N=!0,C=E.as4D(1,E.shape[0],E.shape[1],E.shape[2])),D(C.rank===4,function(){return"Error in fused depthwiseConv2d: input must be rank 4, but got rank "+C.rank+"."}),D(w.rank===4,function(){return"Error in fused depthwiseConv2d: filter must be rank 4, but got rank "+w.rank+"."}),D(C.shape[3]===w.shape[2],function(){return"Error in fused depthwiseConv2d: number of input channels ("+C.shape[3]+") must match the inChannels dimension in filter "+w.shape[2]+"."}),u==null&&(u=[1,1]),D(Bn(t,u),function(){return"Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides "+t+" and dilations '"+u+"'"}),c!=null&&D(Be(a),function(){return"Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode "+c+" but got pad "+a+"."});var S,I,M=Tr(C.shape,w.shape,t,u,a,c,!0);d!=null&&(S=Wt(S=F(d,"bias","fused conv2d"),E)[0],nt(M.outShape,S.shape)),g!=null&&(I=F(g,"prelu weights","fused depthwiseConv2d"));var j={x:C,filter:w};d!=null&&(j.bias=S),g!=null&&(j.preluActivationWeights=I);var G=[w,C],z=X.runKernelFunc(function(W,V){var Z=W.fusedDepthwiseConv2D({input:C,filter:w,convInfo:M,bias:S,activation:m,preluActivationWeights:I});return V([w,C,Z]),Z},j,function(W,V){D(ha(u),function(){return"Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+u+"'"});var Z=V[0],J=V[1],me=V[2],fe=vu(W,me,m),he={};return d!=null&&(he={bias:function(){return mu(S,fe)}}),Object.assign({x:function(){return ol(J.shape,fe,Z,M)},filter:function(){return il(J,fe,Z.shape,M)}},he)},"FusedDepthwiseConv2D",{convInfo:M,activation:m},G,[!0]);return N?z.as3D(z.shape[1],z.shape[2],z.shape[3]):z}}),yf=Object.freeze({matMul:vf,conv2d:mf,depthwiseConv2d:gf}),xf=Object.freeze({image:Al,linalg:sf,losses:nf,spectral:Wp,fused:yf,signal:Xp,square:Qd,squaredDifference:Bc,conv1d:sp,conv2d:xo,conv3d:up,depthwiseConv2d:os,separableConv2d:sl,conv2dTranspose:cp,conv3dTranspose:lp,op:K,batchNormalization2d:Dh,batchNormalization3d:Nh,batchNormalization4d:kh,batchNormalization:Sh,batchNorm:Xc,batchNorm2d:Oh,batchNorm3d:Ih,batchNorm4d:Mh,booleanMaskAsync:ip,complex:zt,real:Hn,imag:cr,concat:Qn,concat1d:xs,concat2d:bs,concat3d:no,concat4d:ws,split:Ta,matMul:uu,dot:dp,outerProduct:hp,reverse:hi,reverse1d:pp,reverse2d:fp,reverse3d:vp,reverse4d:mp,maxPool:ll,avgPool:dl,pool:gp,maxPool3d:yp,avgPool3d:xp,slice:Hr,slice1d:bp,slice2d:wp,slice3d:hl,slice4d:Ep,abs:Zd,acos:eh,acosh:th,asin:nh,asinh:rh,atan:ah,atanh:oh,ceil:ih,clipByValue:jc,cos:sh,cosh:uh,erf:ch,exp:Uc,expm1:lh,floor:dh,log:hh,log1p:ph,logSigmoid:fh,neg:ru,reciprocal:vh,round:mh,rsqrt:Wc,sigmoid:zc,sign:gh,isNaN:yh,isInf:xh,isFinite:bh,sin:wh,sinh:Eh,softplus:_h,sqrt:Ch,step:Rh,tan:Ah,tanh:Th,all:_p,any:Cp,argMax:Rp,argMin:Ap,logSumExp:Tp,max:fl,mean:Dp,min:Np,moments:kp,sum:vl,prod:Sp,equal:Jc,equalStrict:$h,greater:Jh,greaterEqual:Qc,greaterEqualStrict:Qh,greaterStrict:Zh,less:ep,lessEqual:tp,lessEqualStrict:np,lessStrict:rp,notEqual:ap,notEqualStrict:op,add:La,addN:Lh,addStrict:Bh,atan2:jh,div:rs,divNoNan:Uh,divStrict:Wh,floorDiv:Yc,maximum:au,maximumStrict:zh,minimum:$c,minimumStrict:Vh,mod:Gh,modStrict:Hh,mul:Ba,mulStrict:Xh,pow:as,powStrict:Kh,squaredDifferenceStrict:qh,sub:va,subStrict:Yh,elu:ml,leakyRelu:Op,prelu:gl,relu:cu,relu6:yl,selu:Ip,logicalAnd:ns,logicalNot:Fh,logicalOr:Kc,logicalXor:Ph,where:Pa,whereAsync:qc,buffer:Je,print:ao,batchToSpaceND:oo,broadcastTo:As,cast:io,clone:so,cumsum:Ts,depthToSpace:Ds,expandDims:gr,eye:Oi,multinomial:Yo,oneHot:$o,pad:Rr,pad1d:Ii,pad2d:ua,pad3d:Jo,pad4d:Ns,rand:ks,randomNormal:Ss,randomGamma:Os,randomUniform:Qo,reshape:uo,spaceToBatchND:Mi,squeeze:Fi,stack:Ar,tile:zr,truncatedNormal:Is,unstack:co,setdiff1dAsync:Ms,fill:qo,linspace:Ju,ones:_r,range:to,scalar:We,tensor:_n,tensor1d:Ur,tensor2d:Wr,tensor3d:Ko,tensor4d:Er,tensor5d:ia,tensor6d:ys,variable:sa,zeros:Jt,onesLike:Ni,zerosLike:gt,transpose:xl,softmax:Sa,logSoftmax:ti,localResponseNormalization:Mp,norm:bl,gather:ou,unsortedSegmentSum:tl,basicLSTMCell:Fp,multiRNNCell:Pp,movingAverage:Lp,stridedSlice:Bp,topk:jp,scatterND:Up,fft:lu,ifft:is,rfft:du,irfft:wl,sparseToDense:zp,gatherND:Vp,diag:Gp,dropout:Hp,hannWindow:hu,hammingWindow:_l,frame:pu,stft:Cl,inTopKAsync:Kp});function ge(r,n){Array.isArray(r)||(r=[r]),r.forEach(function(e){e!=null&&D(e.dtype!=="complex64",function(){return n+" does not support complex64 tensors."})})}function yu(r,n,e,t){if(e==="linear")return r.linear(n);if(e==="relu")return r.relu(n);if(e==="elu")return r.elu(n);if(e==="relu6")return r.relu6(n);if(e==="prelu")return r.prelu(n,t);throw new Error("Activation "+e+" has not been implemented for the CPU backend.")}var bf=function(r){function n(){var e=r.call(this)||this;return e.blockSize=48,e.firstUse=!0,e.data=new po(e,X),e}return Ke(n,r),n.prototype.write=function(e,t,a){this.firstUse&&(this.firstUse=!1,ee().get("IS_NODE")&&eo(`
|
|
============================
|
|
Hi there \u{1F44B}. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.
|
|
============================`));var o={};return this.data.set(o,{values:e,dtype:a}),o},n.prototype.move=function(e,t,a,o){this.data.set(e,{values:t,dtype:o})},n.prototype.numDataIds=function(){return this.data.numDataIds()},n.prototype.read=function(e){return ve(this,void 0,void 0,function(){return ye(this,function(t){return[2,this.readSync(e)]})})},n.prototype.readSync=function(e){var t=this.data.get(e),a=t.dtype,o=t.complexTensors;return a==="complex64"?yo(this.readSync(o.real.dataId),this.readSync(o.imag.dataId)):this.data.get(e).values},n.prototype.bufferSync=function(e){var t=this.readSync(e.dataId),a=t;if(e.dtype==="string")try{a=t.map(function(o){return ut(o)})}catch(o){throw new Error("Failed to decode encoded string bytes into utf-8")}return Je(e.shape,e.dtype,a)},n.prototype.makeOutput=function(e,t,a){var o=this.write(e,t,a);return X.makeTensorFromDataId(o,t,a,this)},n.prototype.disposeData=function(e){if(this.data.has(e)){var t=this.data.get(e).complexTensors;t!=null&&(t.real.dispose(),t.imag.dispose()),this.data.delete(e)}},n.prototype.time=function(e){return ve(this,void 0,void 0,function(){var t;return ye(this,function(a){return t=$(),e(),[2,{kernelMs:$()-t}]})})},n.prototype.memory=function(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}},n.prototype.complex=function(e,t){var a=this.makeOutput(null,e.shape,"complex64");return this.data.get(a.dataId).complexTensors={real:X.keep(e.clone()),imag:X.keep(t.clone())},a},n.prototype.real=function(e){return this.data.get(e.dataId).complexTensors.real.clone()},n.prototype.imag=function(e){return this.data.get(e.dataId).complexTensors.imag.clone()},n.prototype.slice=function(e,t,a){if(ge(e,"slice"),Ui(e.shape,t,a)){var o=Wi(t,e.strides),i=ae(a);return _n(this.readSync(e.dataId).subarray(o,o+i),a,e.dtype)}for(var s=Je(a,e.dtype),u=this.bufferSync(e),c=0;c<s.size;++c){var d=s.indexToLoc(c).map(function(f,m){return f+t[m]});s.values[c]=u.get.apply(u,d)}return s.toTensor()},n.prototype.stridedSlice=function(e,t,a,o){ge(e,"stridedSlice");var i=ho(t,a,o);if(i.some(function(g){return g===0}))return _n([],i);for(var s=Je(i,e.dtype),u=this.bufferSync(e),c=0;c<s.size;c++){for(var d=s.indexToLoc(c),f=new Array(d.length),m=0;m<f.length;m++)f[m]=d[m]*o[m]+t[m];s.set.apply(s,[u.get.apply(u,f)].concat(d))}return s.toTensor()},n.prototype.diag=function(e){for(var t=this.readSync(e.dataId),a=Je([e.size,e.size],e.dtype),o=a.values,i=0;i<t.length;i++)o[i*e.size+i]=t[i];return a.toTensor()},n.prototype.unstack=function(e,t){for(var a=e.shape[t],o=new Array(e.rank-1),i=0,s=0;s<e.rank;s++)s!==t&&(o[i++]=e.shape[s]);var u=new Array(e.rank).fill(0),c=e.shape.slice();c[t]=1;var d=new Array(a);for(s=0;s<d.length;s++)u[t]=s,d[s]=this.slice(e,u,c).reshape(o);return d},n.prototype.reverse=function(e,t){ge(e,"reverse");for(var a=Je(e.shape,e.dtype),o=this.bufferSync(e),i=function(u){var c=a.indexToLoc(u),d=c.slice();t.forEach(function(f){return d[f]=e.shape[f]-1-d[f]}),a.set.apply(a,[o.get.apply(o,d)].concat(c))},s=0;s<a.size;s++)i(s);return a.toTensor()},n.prototype.concat=function(e,t){var a=this;if(e[0].dtype==="complex64"){var o=e.map(function(g){return Hn(g)}),i=e.map(function(g){return cr(g)});return zt(this.concat(o,t),this.concat(i,t))}var s=e.map(function(g){var x=ae(g.shape.slice(t));return g.as2D(-1,x)}),u=jr(s.map(function(g){return g.shape}),1),c=Je(u,e[0].dtype).values;if(s[0].shape[0]===1){var d=0;s.forEach(function(g){c.set(a.readSync(g.dataId),d),d+=g.size})}else{var f=0;s.forEach(function(g){for(var x=a.readSync(g.dataId),E=0,w=0;w<g.shape[0];++w)for(var C=w*u[1]+f,N=0;N<g.shape[1];++N)c[C+N]=x[E++];f+=g.shape[1]})}var m=jr(e.map(function(g){return g.shape}),t);return _n(c,m,e[0].dtype)},n.prototype.neg=function(e){return ge(e,"neg"),this.multiply(We(-1),e)},n.prototype.add=function(e,t){return e.dtype==="complex64"||t.dtype==="complex64"?this.broadcastedBinaryComplexOp(e.cast("complex64"),t.cast("complex64"),function(a,o,i,s){return{real:a+i,imag:o+s}}):this.broadcastedBinaryOp(e,t,yn(e.dtype,t.dtype),function(a,o){return a+o})},n.prototype.addN=function(e){var t=this;ge(e,"addN");for(var a=e.map(function(d){return t.readSync(d.dataId)}),o=Je(e[0].shape,e[0].dtype),i=o.values,s=0;s<e.length;s++)for(var u=a[s],c=0;c<i.length;c++)i[c]+=u[c];return o.toTensor()},n.prototype.softmax=function(e,t){var a=je([t],e.shape),o=this.max(e,a),i=kn(o.shape,a),s=this.subtract(e,o.reshape(i)),u=this.exp(s),c=this.sum(u,a).reshape(i);return this.realDivide(u,c)},n.prototype.subtract=function(e,t){return e.dtype==="complex64"||t.dtype==="complex64"?this.broadcastedBinaryComplexOp(e.cast("complex64"),t.cast("complex64"),function(a,o,i,s){return{real:a-i,imag:o-s}}):this.broadcastedBinaryOp(e,t,yn(e.dtype,t.dtype),function(a,o){return a-o})},n.prototype.pow=function(e,t){return ge([e,t],"pow"),this.broadcastedBinaryOp(e,t,e.dtype,function(a,o){return Math.pow(a,o)})},n.prototype.batchMatMul=function(e,t,a,o){ge([e,t],"matMul");for(var i=a?e.shape[1]:e.shape[2],s=a?e.shape[2]:e.shape[1],u=o?t.shape[1]:t.shape[2],c=e.shape[0],d=this.readSync(e.dataId),f=this.readSync(t.dataId),m=a?[e.strides[0],1,e.strides[1]]:[e.strides[0],e.strides[1],1],g=m[0],x=m[1],E=m[2],w=o?[1,t.strides[1],t.strides[0]]:[t.strides[1],1,t.strides[0]],C=w[0],N=w[1],S=w[2],I=s*u,M=Je([c,s,u],e.dtype),j=M.values,G=this.blockSize,z=0;z<c;z++)for(var W=0;W<s;W+=G)for(var V=0;V<u;V+=G)for(var Z=0;Z<i;Z+=G)for(var J=Math.min(W+G,s),me=Math.min(V+G,u),fe=Math.min(Z+G,i),he=W;he<J;he++)for(var Ee=V;Ee<me;Ee++){for(var be=0,pe=Z;pe<fe;pe++)be+=d[z*g+he*x+pe*E]*f[pe*C+Ee*N+z*S];j[z*I+(he*u+Ee)]+=be}return M.toTensor()},n.prototype.fusedBatchMatMul=function(e){var t=e.a,a=e.b,o=e.transposeA,i=e.transposeB,s=e.bias,u=e.activation,c=e.preluActivationWeights,d=this.batchMatMul(t,a,o,i);return s&&(d=this.add(d,s)),u&&(d=yu(this,d,u,c)),d},n.prototype.multiply=function(e,t){return e.dtype==="complex64"||t.dtype==="complex64"?this.broadcastedBinaryComplexOp(e.cast("complex64"),t.cast("complex64"),function(a,o,i,s){return{real:a*i-o*s,imag:a*s+o*i}}):this.broadcastedBinaryOp(e,t,yn(e.dtype,t.dtype),function(a,o){return a*o})},n.prototype.realDivide=function(e,t){return ge([e,t],"realDivide"),this.broadcastedBinaryOp(e,t,"float32",function(a,o){return a/o})},n.prototype.floorDiv=function(e,t){return ge([e,t],"floorDiv"),this.broadcastedBinaryOp(e,t,"int32",function(a,o){return Math.floor(a/o)})},n.prototype.sum=function(e,t){ge(e,"sum"),Wn("sum",t,e.rank);for(var a=Nn(e.shape,t),o=a[0],i=a[1],s=Jt(o,yn(e.dtype,"int32")),u=ae(i),c=this.readSync(s.dataId),d=this.readSync(e.dataId),f=0;f<c.length;++f){for(var m=f*u,g=0,x=0;x<u;++x)g+=d[m+x];c[f]=g}return s},n.prototype.prod=function(e,t){ge(e,"sum");for(var a=Nn(e.shape,t),o=a[0],i=a[1],s=Jt(o,yn(e.dtype,"int32")),u=ae(i),c=this.readSync(s.dataId),d=this.readSync(e.dataId),f=0;f<c.length;++f){for(var m=f*u,g=1,x=0;x<u;++x)g*=d[m+x];c[f]=g}return s},n.prototype.unsortedSegmentSum=function(e,t,a){ge(e,"unsortedSegmentSum");for(var o=[],i=e.rank-t.rank,s=0;s<i;++s)t=t.expandDims(s+1);for(s=0;s<a;++s){var u=We(s,"int32"),c=Jc(u,t).asType("float32").mul(e).sum(0);o.push(c)}return Ar(o)},n.prototype.argMin=function(e,t){ge(e,"argMin");var a=[t];Wn("argMin",a,e.rank);for(var o=Nn(e.shape,a),i=o[0],s=o[1],u=Jt(i,"int32"),c=ae(s),d=this.readSync(u.dataId),f=this.readSync(e.dataId),m=0;m<d.length;++m){for(var g=m*c,x=f[g],E=0,w=0;w<c;++w){var C=f[g+w];C<x&&(x=C,E=w)}d[m]=E}return u},n.prototype.argMax=function(e,t){ge(e,"argMax");var a=[t];Wn("argMax",a,e.rank);for(var o=Nn(e.shape,a),i=o[0],s=o[1],u=Jt(i,"int32"),c=ae(s),d=this.readSync(u.dataId),f=this.readSync(e.dataId),m=0;m<d.length;++m){for(var g=m*c,x=f[g],E=0,w=0;w<c;++w){var C=f[g+w];C>x&&(x=C,E=w)}d[m]=E}return u},n.prototype.cumsum=function(e,t,a,o){if(ge(e,"cumsum"),t!==e.rank-1)throw new Error("backend.cumsum in CPU expects an inner-most axis="+(e.rank-1)+" but got axis="+t);for(var i=yn(e.dtype,"int32"),s=Jt(e.shape,i),u=this.readSync(s.dataId),c=this.readSync(e.dataId),d=e.shape[e.rank-1],f=o?function(w,C){return w+d-C-1}:function(w,C){return w+C},m=0;m<c.length;m+=d)for(var g=0;g<d;g++){var x=f(m,g);if(g===0)u[x]=a?0:c[x];else{var E=f(m,g-1);u[x]=a?c[E]+u[E]:c[x]+u[E]}}return s},n.prototype.equal=function(e,t){return ge([e,t],"equal"),this.broadcastedBinaryOp(e,t,"bool",function(a,o){return a===o?1:0})},n.prototype.notEqual=function(e,t){return ge([e,t],"notEqual"),this.broadcastedBinaryOp(e,t,"bool",function(a,o){return a!==o?1:0})},n.prototype.less=function(e,t){return ge([e,t],"less"),this.broadcastedBinaryOp(e,t,"bool",function(a,o){return a<o?1:0})},n.prototype.lessEqual=function(e,t){return ge([e,t],"lessEqual"),this.broadcastedBinaryOp(e,t,"bool",function(a,o){return a<=o?1:0})},n.prototype.greater=function(e,t){return ge([e,t],"greater"),this.broadcastedBinaryOp(e,t,"bool",function(a,o){return a>o?1:0})},n.prototype.greaterEqual=function(e,t){return ge([e,t],"greaterEqual"),this.broadcastedBinaryOp(e,t,"bool",function(a,o){return a>=o?1:0})},n.prototype.logicalNot=function(e){ge(e,"logicalNot");for(var t=this.readSync(e.dataId),a=new Uint8Array(t.length),o=0;o<t.length;++o)a[o]=t[o]?0:1;return this.makeOutput(a,e.shape,"bool")},n.prototype.logicalAnd=function(e,t){return ge([e,t],"logicalAnd"),this.broadcastedBinaryOp(e,t,"bool",function(a,o){return a&&o})},n.prototype.logicalOr=function(e,t){return ge([e,t],"logicalOr"),this.broadcastedBinaryOp(e,t,"bool",function(a,o){return a||o})},n.prototype.select=function(e,t,a){ge([e,t,a],"select");for(var o=this.readSync(e.dataId),i=this.readSync(t.dataId),s=this.readSync(a.dataId),u=Jt(t.shape,yn(t.dtype,a.dtype)),c=this.readSync(u.dataId),d=0,f=e.rank===0||e.rank>1||t.rank===1?1:ae(t.shape.slice(1)),m=0;m<o.length;m++)for(var g=0;g<f;g++)o[m]===1?c[d++]=i[m]:c[d++]=s[m];return u},n.prototype.where=function(e){ge([e],"where");var t=this.readSync(e.dataId);return Yi(e.shape,t)},n.prototype.topk=function(e,t,a){return ge(e,"topk"),qs(this.readSync(e.dataId),e.shape,e.dtype,t)},n.prototype.min=function(e,t){ge(e,"min"),Wn("min",t,e.rank);for(var a=Nn(e.shape,t),o=a[0],i=a[1],s=Jt(o,e.dtype),u=ae(i),c=this.readSync(s.dataId),d=this.readSync(e.dataId),f=0;f<c.length;++f){for(var m=f*u,g=d[m],x=0;x<u;++x){var E=d[m+x];E<g&&(g=E)}c[f]=g}return s},n.prototype.minimum=function(e,t){return ge([e,t],"minimum"),this.broadcastedBinaryOp(e,t,e.dtype,function(a,o){return Math.min(a,o)})},n.prototype.mod=function(e,t){return ge([e,t],"mod"),this.broadcastedBinaryOp(e,t,e.dtype,function(a,o){var i=a%o;return a<0&&o<0||a>=0&&o>=0?i:(i+o)%o})},n.prototype.max=function(e,t){ge(e,"max"),Wn("max",t,e.rank);for(var a=Nn(e.shape,t),o=a[0],i=a[1],s=Jt(o,e.dtype),u=ae(i),c=this.readSync(s.dataId),d=this.readSync(e.dataId),f=0;f<c.length;++f){for(var m=f*u,g=d[m],x=0;x<u;++x){var E=d[m+x];E>g&&(g=E)}c[f]=g}return s},n.prototype.maximum=function(e,t){return ge([e,t],"maximum"),this.broadcastedBinaryOp(e,t,e.dtype,function(a,o){return Math.max(a,o)})},n.prototype.all=function(e,t){ge(e,"all"),Wn("all",t,e.rank);for(var a=Nn(e.shape,t),o=a[0],i=a[1],s=Jt(o,e.dtype),u=ae(i),c=this.readSync(s.dataId),d=this.readSync(e.dataId),f=0;f<c.length;++f){for(var m=f*u,g=d[m],x=0;x<u;++x){var E=d[m+x];g=g&&E}c[f]=g}return s},n.prototype.any=function(e,t){ge(e,"any"),Wn("any",t,e.rank);for(var a=Nn(e.shape,t),o=a[0],i=a[1],s=Jt(o,e.dtype),u=ae(i),c=this.readSync(s.dataId),d=this.readSync(e.dataId),f=0;f<c.length;++f){for(var m=f*u,g=d[m],x=0;x<u;++x){var E=d[m+x];g=g||E}c[f]=g}return s},n.prototype.squaredDifference=function(e,t){return ge([e,t],"squaredDifference"),this.broadcastedBinaryOp(e,t,e.dtype,function(a,o){var i=a-o;return i*i})},n.prototype.ceil=function(e){ge(e,"ceil");for(var t=this.readSync(e.dataId),a=new Float32Array(t.length),o=0;o<t.length;++o)a[o]=Math.ceil(t[o]);return this.makeOutput(a,e.shape,"float32")},n.prototype.floor=function(e){ge(e,"floor");for(var t=this.readSync(e.dataId),a=new Float32Array(t.length),o=0;o<t.length;++o)a[o]=Math.floor(t[o]);return this.makeOutput(a,e.shape,"float32")},n.prototype.sign=function(e){ge(e,"x");for(var t=this.readSync(e.dataId),a=new Float32Array(t.length),o=0;o<t.length;++o)t[o]<0?a[o]=-1:t[o]>0?a[o]=1:a[o]=0;return this.makeOutput(a,e.shape,"float32")},n.prototype.isNaN=function(e){ge(e,"x");for(var t=this.readSync(e.dataId),a=new Uint8Array(t.length),o=0;o<t.length;++o)Number.isNaN(t[o])&&(a[o]=1);return this.makeOutput(a,e.shape,"bool")},n.prototype.isInf=function(e){ge(e,"x");for(var t=this.readSync(e.dataId),a=new Uint8Array(t.length),o=0;o<t.length;++o)Math.abs(t[o])===1/0&&(a[o]=1);return this.makeOutput(a,e.shape,"bool")},n.prototype.isFinite=function(e){ge(e,"x");for(var t=this.readSync(e.dataId),a=new Uint8Array(t.length),o=0;o<t.length;++o)Number.isFinite(t[o])&&(a[o]=1);return this.makeOutput(a,e.shape,"bool")},n.prototype.round=function(e){ge(e,"round");for(var t=this.readSync(e.dataId),a=new Float32Array(t.length),o=0;o<t.length;++o){var i=Math.floor(t[o]);t[o]-i<.5?a[o]=Math.floor(t[o]):t[o]-i>.5?a[o]=Math.ceil(t[o]):a[o]=i%2==0?i:i+1}return this.makeOutput(a,e.shape,"float32")},n.prototype.exp=function(e){ge(e,"exp");for(var t=this.readSync(e.dataId),a=new Float32Array(t.length),o=0;o<t.length;++o)a[o]=Math.exp(t[o]);return this.makeOutput(a,e.shape,"float32")},n.prototype.expm1=function(e){ge(e,"expm1");for(var t=this.readSync(e.dataId),a=new Float32Array(t.length),o=0;o<t.length;++o)a[o]=Math.expm1(t[o]);return this.makeOutput(a,e.shape,"float32")},n.prototype.log=function(e){ge(e,"log");for(var t=this.readSync(e.dataId),a=new Float32Array(t.length),o=0;o<t.length;++o){var i=t[o];a[o]=Math.log(i)}return this.makeOutput(a,e.shape,"float32")},n.prototype.log1p=function(e){ge(e,"log1p");for(var t=this.readSync(e.dataId),a=new Float32Array(t.length),o=0;o<t.length;++o){var i=t[o];a[o]=Math.log1p(i)}return this.makeOutput(a,e.shape,"float32")},n.prototype.sqrt=function(e){ge(e,"sqrt");for(var t=this.readSync(e.dataId),a=new Float32Array(t.length),o=0;o<t.length;++o){var i=t[o];a[o]=Math.sqrt(i)}return this.makeOutput(a,e.shape,"float32")},n.prototype.rsqrt=function(e){ge(e,"rsqrt");for(var t=this.readSync(e.dataId),a=new Float32Array(t.length),o=0;o<t.length;++o){var i=t[o];a[o]=1/Math.sqrt(i)}return this.makeOutput(a,e.shape,"float32")},n.prototype.reciprocal=function(e){ge(e,"reciprocal");for(var t=this.readSync(e.dataId),a=new Float32Array(t.length),o=0;o<t.length;++o)a[o]=1/t[o];return this.makeOutput(a,e.shape,"float32")},n.prototype.linear=function(e){return e},n.prototype.relu=function(e){ge(e,"relu");for(var t=Jt(e.shape,e.dtype),a=this.readSync(t.dataId),o=this.readSync(e.dataId),i=0;i<o.length;++i)a[i]=Math.max(0,o[i]);return t},n.prototype.relu6=function(e){ge(e,"relu");for(var t=Jt(e.shape,e.dtype),a=this.readSync(t.dataId),o=this.readSync(e.dataId),i=0;i<o.length;++i)a[i]=Math.min(Math.max(0,o[i]),6);return t},n.prototype.prelu=function(e,t){return ge([e,t],"prelu"),this.broadcastedBinaryOp(e,t,e.dtype,function(a,o){return a<0?o*a:a})},n.prototype.elu=function(e){ge(e,"elu");for(var t=new Float32Array(e.size),a=this.readSync(e.dataId),o=0;o<a.length;++o){var i=a[o];t[o]=i>=0?i:Math.exp(i)-1}return this.makeOutput(t,e.shape,"float32")},n.prototype.eluDer=function(e,t){ge([e,t],"eluDer");for(var a=new Float32Array(t.size),o=this.readSync(t.dataId),i=this.readSync(e.dataId),s=0;s<o.length;++s){var u=o[s];a[s]=u>=1?i[s]:i[s]*(u+1)}return this.makeOutput(a,t.shape,"float32")},n.prototype.selu=function(e){ge(e,"selu");for(var t=tu,a=nu,o=new Float32Array(e.size),i=this.readSync(e.dataId),s=0;s<i.length;++s){var u=i[s];o[s]=u>=0?a*u:t*(Math.exp(u)-1)}return this.makeOutput(o,e.shape,"float32")},n.prototype.clip=function(e,t,a){ge(e,"clip");for(var o=new Float32Array(e.size),i=this.readSync(e.dataId),s=0;s<i.length;++s){var u=i[s];o[s]=u>a?a:u<t?t:u}return this.makeOutput(o,e.shape,"float32")},n.prototype.abs=function(e){for(var t=new Float32Array(e.size),a=this.readSync(e.dataId),o=0;o<a.length;++o)t[o]=Math.abs(a[o]);return this.makeOutput(t,e.shape,"float32")},n.prototype.complexAbs=function(e){for(var t=new Float32Array(e.size),a=this.readSync(e.dataId),o=0;o<e.size;++o){var i=a[2*o],s=a[2*o+1];t[o]=Math.hypot(i,s)}return this.makeOutput(t,e.shape,"float32")},n.prototype.int=function(e){ge(e,"int");for(var t=new Int32Array(e.size),a=this.readSync(e.dataId),o=0;o<a.length;++o)t[o]=a[o];return this.makeOutput(t,e.shape,"int32")},n.prototype.sigmoid=function(e){ge(e,"sigmoid");for(var t=new Float32Array(e.size),a=this.readSync(e.dataId),o=0;o<a.length;++o)t[o]=1/(1+Math.exp(-a[o]));return this.makeOutput(t,e.shape,"float32")},n.prototype.softplus=function(e){ge(e,"softplus");for(var t=Math.log(11920928955078125e-23)+2,a=new Float32Array(e.size),o=this.readSync(e.dataId),i=0;i<o.length;++i){var s=o[i]>-t,u=o[i]<t,c=Math.exp(o[i]),d=void 0;d=u?c:s?o[i]:Math.log(1+c),a[i]=d}return this.makeOutput(a,e.shape,"float32")},n.prototype.sin=function(e){ge(e,"sin");for(var t=new Float32Array(e.size),a=this.readSync(e.dataId),o=0;o<a.length;++o)t[o]=Math.sin(a[o]);return this.makeOutput(t,e.shape,"float32")},n.prototype.cos=function(e){ge(e,"cos");for(var t=new Float32Array(e.size),a=this.readSync(e.dataId),o=0;o<a.length;++o)t[o]=Math.cos(a[o]);return this.makeOutput(t,e.shape,"float32")},n.prototype.tan=function(e){ge(e,"tan");for(var t=new Float32Array(e.size),a=this.readSync(e.dataId),o=0;o<a.length;++o)t[o]=Math.tan(a[o]);return this.makeOutput(t,e.shape,"float32")},n.prototype.asin=function(e){ge(e,"asin");for(var t=new Float32Array(e.size),a=this.readSync(e.dataId),o=0;o<a.length;++o)t[o]=Math.asin(a[o]);return this.makeOutput(t,e.shape,"float32")},n.prototype.acos=function(e){ge(e,"acos");for(var t=new Float32Array(e.size),a=this.readSync(e.dataId),o=0;o<a.length;++o)t[o]=Math.acos(a[o]);return this.makeOutput(t,e.shape,"float32")},n.prototype.atan=function(e){ge(e,"atan");for(var t=new Float32Array(e.size),a=this.readSync(e.dataId),o=0;o<a.length;++o)t[o]=Math.atan(a[o]);return this.makeOutput(t,e.shape,"float32")},n.prototype.atan2=function(e,t){return ge([e,t],"atan2"),this.broadcastedBinaryOp(e,t,e.dtype,function(a,o){return Math.atan2(a,o)})},n.prototype.sinh=function(e){ge(e,"sinh");for(var t=new Float32Array(e.size),a=this.readSync(e.dataId),o=0;o<a.length;++o)t[o]=Math.sinh(a[o]);return this.makeOutput(t,e.shape,"float32")},n.prototype.cosh=function(e){ge(e,"cosh");for(var t=new Float32Array(e.size),a=this.readSync(e.dataId),o=0;o<a.length;++o)t[o]=Math.cosh(a[o]);return this.makeOutput(t,e.shape,"float32")},n.prototype.tanh=function(e){ge(e,"tanh");for(var t=new Float32Array(e.size),a=this.readSync(e.dataId),o=0;o<a.length;++o)t[o]=Qt(a[o]);return this.makeOutput(t,e.shape,"float32")},n.prototype.asinh=function(e){ge(e,"asinh");for(var t=new Float32Array(e.size),a=this.readSync(e.dataId),o=0;o<a.length;++o)t[o]=Math.asinh(a[o]);return this.makeOutput(t,e.shape,"float32")},n.prototype.acosh=function(e){ge(e,"acosh");for(var t=new Float32Array(e.size),a=this.readSync(e.dataId),o=0;o<a.length;++o)t[o]=Math.acosh(a[o]);return this.makeOutput(t,e.shape,"float32")},n.prototype.atanh=function(e){ge(e,"atanh");for(var t=new Float32Array(e.size),a=this.readSync(e.dataId),o=0;o<a.length;++o)t[o]=Math.atanh(a[o]);return this.makeOutput(t,e.shape,"float32")},n.prototype.erf=function(e){ge(e,"erf");for(var t=new Float32Array(e.size),a=this.readSync(e.dataId),o=0;o<a.length;++o){var i=Math.sign(a[o]),s=Math.abs(a[o]),u=1/(1+.3275911*s);t[o]=i*(1-((((1.061405429*u-1.453152027)*u+1.421413741)*u-.284496736)*u+.254829592)*u*Math.exp(-s*s))}return this.makeOutput(t,e.shape,"float32")},n.prototype.step=function(e,t){t===void 0&&(t=0),ge(e,"step");for(var a=new Float32Array(e.size),o=this.readSync(e.dataId),i=0;i<o.length;++i){var s=o[i];isNaN(s)?a[i]=NaN:a[i]=s>0?1:t}return this.makeOutput(a,e.shape,"float32")},n.prototype.fusedConv2d=function(e){var t=e.input,a=e.filter,o=e.convInfo,i=e.bias,s=e.activation,u=e.preluActivationWeights,c=this.conv2d(t,a,o);return i&&(c=this.add(c,i)),s&&(c=yu(this,c,s,u)),c},n.prototype.conv2d=function(e,t,a){ge([e,t],"conv2d");for(var o=a.filterHeight,i=a.filterWidth,s=a.dilationHeight,u=a.dilationWidth,c=a.padInfo.left,d=a.padInfo.top,f=a.dataFormat==="channelsLast",m=Je(a.outShape,e.dtype),g=e.strides[0],x=f?e.strides[1]:e.strides[2],E=f?e.strides[2]:1,w=f?1:e.strides[1],C=m.strides[0],N=f?m.strides[1]:m.strides[2],S=f?m.strides[2]:1,I=f?1:m.strides[1],M=this.readSync(e.dataId),j=this.readSync(t.dataId),G=m.values,z=0;z<a.batchSize;++z)for(var W=z*g,V=z*C,Z=0;Z<a.outHeight;++Z)for(var J=V+Z*N,me=Z*a.strideHeight-d,fe=0;fe<o;fe++){var he=me+fe*s;if(!(he<0||he>=a.inHeight))for(var Ee=fe*t.strides[0],be=W+he*x,pe=0;pe<a.outWidth;++pe)for(var Ce=J+pe*S,Re=pe*a.strideWidth-c,Le=0;Le<i;Le++){var Xe=Re+Le*u;if(!(Xe<0||Xe>=a.inWidth))for(var qe=be+Xe*E,ht=Ee+Le*t.strides[1],pt=0;pt<a.inChannels;++pt){for(var vt=M[qe+pt*w],Dt=0;Dt<a.outChannels;++Dt)G[Ce+Dt*I]+=vt*j[ht+Dt];ht+=a.outChannels}}}return m.toTensor()},n.prototype.conv3d=function(e,t,a){for(var o=a.filterDepth,i=a.filterHeight,s=a.filterWidth,u=a.dilationDepth,c=a.dilationHeight,d=a.dilationWidth,f=a.padInfo.front,m=a.padInfo.left,g=a.padInfo.top,x=Je(a.outShape,e.dtype),E=this.readSync(e.dataId),w=this.readSync(t.dataId),C=x.values,N=0;N<a.batchSize;++N)for(var S=N*e.strides[0],I=N*x.strides[0],M=0;M<a.outDepth;++M)for(var j=I+M*x.strides[1],G=M*a.strideDepth-f,z=0;z<o;z++){var W=G+z*u;if(!(W<0||W>=a.inDepth))for(var V=z*t.strides[0],Z=S+W*e.strides[1],J=0;J<a.outHeight;++J)for(var me=j+J*x.strides[2],fe=J*a.strideHeight-g,he=0;he<i;he++){var Ee=fe+he*c;if(!(Ee<0||Ee>=a.inHeight))for(var be=V+he*t.strides[1],pe=Z+Ee*e.strides[2],Ce=0;Ce<a.outWidth;++Ce)for(var Re=me+Ce*a.outChannels,Le=Ce*a.strideWidth-m,Xe=0;Xe<s;Xe++){var qe=Le+Xe*d;if(!(qe<0||qe>=a.inWidth))for(var ht=be+Xe*t.strides[2],pt=pe+qe*a.inChannels,vt=ht,Dt=0;Dt<a.inChannels;++Dt){for(var Et=E[pt+Dt],Nt=0;Nt<a.outChannels;++Nt)C[Re+Nt]+=Et*w[vt+Nt];vt+=a.outChannels}}}}return x.toTensor()},n.prototype.conv2dDerInput=function(e,t,a){ge([e,t],"conv2dDerInput");for(var o=Je(a.inShape,"float32"),i=o.values,s=this.readSync(e.dataId),u=this.readSync(t.dataId),c=t.strides,d=c[0],f=c[1],m=c[2],g=a.batchSize,x=a.filterHeight,E=a.filterWidth,w=a.inChannels,C=a.inHeight,N=a.inWidth,S=a.outChannels,I=a.outHeight,M=a.outWidth,j=a.strideHeight,G=a.strideWidth,z=a.dataFormat,W=x-1-a.padInfo.top,V=E-1-a.padInfo.left,Z=z==="channelsLast",J=o.strides[0],me=Z?o.strides[1]:o.strides[2],fe=Z?o.strides[2]:1,he=Z?1:o.strides[1],Ee=e.strides[0],be=Z?e.strides[1]:e.strides[2],pe=Z?e.strides[2]:1,Ce=Z?1:e.strides[1],Re=0;Re<g;++Re)for(var Le=0;Le<w;++Le)for(var Xe=0;Xe<C;++Xe)for(var qe=Xe-W,ht=Math.max(0,Math.ceil(qe/j)),pt=Math.min(I,(x+qe)/j),vt=0;vt<N;++vt){for(var Dt=vt-V,Et=Math.max(0,Math.ceil(Dt/G)),Nt=Math.min(M,(E+Dt)/G),mn=0,_t=ht;_t<pt;++_t)for(var Ht=_t*j-qe,It=Et;It<Nt;++It)for(var hn=Ee*Re+be*_t+pe*It,cn=d*(x-1-Ht)+f*(E-1-(It*G-Dt))+m*Le,ln=0;ln<S;++ln)mn+=s[hn+Ce*ln]*u[cn+ln];i[J*Re+me*Xe+fe*vt+he*Le]=mn}return o.toTensor()},n.prototype.conv3dDerInput=function(e,t,a){for(var o=Je(a.inShape,"float32"),i=o.values,s=o.strides,u=s[0],c=s[1],d=s[2],f=s[3],m=this.readSync(e.dataId),g=e.strides,x=g[0],E=g[1],w=g[2],C=g[3],N=this.readSync(t.dataId),S=t.strides,I=S[0],M=S[1],j=S[2],G=S[3],z=a.batchSize,W=a.filterDepth,V=a.filterHeight,Z=a.filterWidth,J=a.inChannels,me=a.inDepth,fe=a.inHeight,he=a.inWidth,Ee=a.outChannels,be=a.outDepth,pe=a.outHeight,Ce=a.outWidth,Re=a.strideDepth,Le=a.strideHeight,Xe=a.strideWidth,qe=W-1-a.padInfo.front,ht=V-1-a.padInfo.top,pt=Z-1-a.padInfo.left,vt=0;vt<z;++vt)for(var Dt=0;Dt<J;++Dt)for(var Et=0;Et<me;++Et)for(var Nt=Et-qe,mn=Math.max(0,Math.ceil(Nt/Re)),_t=Math.min(be,(W+Nt)/Re),Ht=0;Ht<fe;++Ht)for(var It=Ht-ht,hn=Math.max(0,Math.ceil(It/Le)),cn=Math.min(pe,(V+It)/Le),ln=0;ln<he;++ln){for(var Or=ln-pt,Ir=Math.max(0,Math.ceil(Or/Xe)),er=Math.min(Ce,(Z+Or)/Xe),Ao=0,qr=mn;qr<_t;++qr)for(var xa=qr*Re-Nt,Yr=hn;Yr<cn;++Yr)for(var To=Yr*Le-It,$r=Ir;$r<er;++$r)for(var Fu=x*vt+E*qr+w*Yr+C*$r,Do=I*(W-1-xa)+M*(V-1-To)+j*(Z-1-($r*Xe-Or))+G*Dt,Mr=0;Mr<Ee;++Mr)Ao+=m[Fu+Mr]*N[Do+Mr];i[u*vt+c*Et+d*Ht+f*ln+Dt]=Ao}return o.toTensor()},n.prototype.conv2dDerFilter=function(e,t,a){ge([e,t],"conv2dDerFilter");for(var o=a.strideHeight,i=a.strideWidth,s=a.filterHeight,u=a.filterWidth,c=a.dataFormat==="channelsLast",d=Je(a.filterShape,"float32"),f=a.padInfo.left,m=a.padInfo.top,g=this.bufferSync(e),x=this.bufferSync(t),E=0;E<s;++E)for(var w=Math.max(0,Math.ceil((m-E)/o)),C=Math.min(a.outHeight,(a.inHeight+m-E)/o),N=0;N<u;++N)for(var S=Math.max(0,Math.ceil((f-N)/i)),I=Math.min(a.outWidth,(a.inWidth+f-N)/i),M=0;M<a.inChannels;++M)for(var j=0;j<a.outChannels;++j){for(var G=0,z=0;z<a.batchSize;++z)for(var W=w;W<C;++W)for(var V=E+W*o-m,Z=S;Z<I;++Z){var J=N+Z*i-f;G+=c?g.get(z,V,J,M)*x.get(z,W,Z,j):g.get(z,M,V,J)*x.get(z,j,W,Z)}d.set(G,E,N,M,j)}return d.toTensor()},n.prototype.conv3dDerFilter=function(e,t,a){for(var o=a.strideDepth,i=a.strideHeight,s=a.strideWidth,u=a.filterDepth,c=a.filterHeight,d=a.filterWidth,f=Je(a.filterShape,"float32"),m=f.values,g=f.strides,x=g[0],E=g[1],w=g[2],C=g[3],N=this.readSync(t.dataId),S=t.strides,I=S[0],M=S[1],j=S[2],G=S[3],z=this.readSync(e.dataId),W=e.strides,V=W[0],Z=W[1],J=W[2],me=W[3],fe=a.padInfo.front,he=a.padInfo.left,Ee=a.padInfo.top,be=0;be<u;++be)for(var pe=Math.max(0,Math.ceil((fe-be)/o)),Ce=Math.min(a.outDepth,(a.inDepth+fe-be)/o),Re=be*x,Le=0;Le<c;++Le)for(var Xe=Math.max(0,Math.ceil((Ee-Le)/i)),qe=Math.min(a.outHeight,(a.inHeight+Ee-Le)/i),ht=Le*E+Re,pt=0;pt<d;++pt)for(var vt=Math.max(0,Math.ceil((he-pt)/s)),Dt=Math.min(a.outWidth,(a.inWidth+he-pt)/s),Et=pt*w+ht,Nt=0;Nt<a.inChannels;++Nt)for(var mn=Nt*C+Et,_t=0;_t<a.outChannels;++_t){for(var Ht=0,It=0;It<a.batchSize;++It)for(var hn=It*V,cn=It*I,ln=pe;ln<Ce;++ln)for(var Or=(be+ln*o-fe)*Z+hn,Ir=ln*M+cn,er=Xe;er<qe;++er)for(var Ao=(Le+er*i-Ee)*J+Or,qr=er*j+Ir,xa=vt;xa<Dt;++xa){var Yr=xa*G+qr;Ht+=z[(pt+xa*s-he)*me+Ao+Nt]*N[Yr+_t]}m[mn+_t]=Ht}return f.toTensor()},n.prototype.fusedDepthwiseConv2D=function(e){var t=e.input,a=e.filter,o=e.convInfo,i=e.bias,s=e.activation,u=e.preluActivationWeights,c=this.depthwiseConv2D(t,a,o);return i&&(c=this.add(c,i)),s&&(c=yu(this,c,s,u)),c},n.prototype.depthwiseConv2D=function(e,t,a){ge([e,t],"depthwiseConv2D");for(var o=a.filterHeight,i=a.filterWidth,s=a.dilationHeight,u=a.dilationWidth,c=a.padInfo.left,d=a.padInfo.top,f=a.outChannels/a.inChannels,m=Je(a.outShape,e.dtype),g=this.readSync(e.dataId),x=this.readSync(t.dataId),E=m.values,w=0;w<a.batchSize;++w)for(var C=w*e.strides[0],N=w*m.strides[0],S=0;S<a.outHeight;++S)for(var I=N+S*m.strides[1],M=S*a.strideHeight-c,j=0;j<o;++j){var G=M+j*s;if(!(G<0||G>=a.inHeight))for(var z=j*t.strides[0],W=C+G*e.strides[1],V=0;V<a.outWidth;++V)for(var Z=I+V*m.strides[2],J=V*a.strideWidth-d,me=0;me<i;++me){var fe=J+me*u;if(!(fe<0||fe>=a.inWidth))for(var he=z+me*t.strides[1],Ee=W+fe*a.inChannels,be=Z,pe=he,Ce=0;Ce<a.inChannels;++Ce){for(var Re=g[Ee+Ce],Le=0;Le<f;++Le)E[be+Le]+=Re*x[pe+Le];be+=f,pe+=f}}}return m.toTensor()},n.prototype.depthwiseConv2DDerInput=function(e,t,a){ge([e,t],"depthwiseConv2DDerInput");for(var o=Je(a.inShape,"float32"),i=o.values,s=o.strides,u=s[0],c=s[1],d=s[2],f=this.readSync(e.dataId),m=e.strides,g=m[0],x=m[1],E=m[2],w=this.readSync(t.dataId),C=t.strides,N=C[0],S=C[1],I=C[2],M=a.batchSize,j=a.filterHeight,G=a.filterWidth,z=a.inChannels,W=a.inHeight,V=a.inWidth,Z=a.outChannels,J=a.outHeight,me=a.outWidth,fe=a.strideHeight,he=a.strideWidth,Ee=j-1-a.padInfo.top,be=G-1-a.padInfo.left,pe=Z/z,Ce=0;Ce<M;++Ce)for(var Re=0;Re<z;++Re)for(var Le=0;Le<W;++Le)for(var Xe=Le-Ee,qe=Math.max(0,Math.ceil(Xe/fe)),ht=Math.min(J,(j+Xe)/fe),pt=0;pt<V;++pt){for(var vt=pt-be,Dt=Math.max(0,Math.ceil(vt/he)),Et=Math.min(me,(G+vt)/he),Nt=0,mn=qe;mn<ht;++mn)for(var _t=mn*fe-Xe,Ht=Dt;Ht<Et;++Ht)for(var It=g*Ce+x*mn+E*Ht,hn=N*(j-1-_t)+S*(G-1-(Ht*he-vt))+I*Re,cn=0;cn<pe;++cn)Nt+=f[It+(Re*pe+cn)]*w[hn+cn];i[u*Ce+c*Le+d*pt+Re]=Nt}return o.toTensor()},n.prototype.depthwiseConv2DDerFilter=function(e,t,a){ge([e,t],"depthwiseConv2DDerFilter");for(var o=a.strideHeight,i=a.strideWidth,s=a.filterHeight,u=a.filterWidth,c=Je(a.filterShape,"float32"),d=a.padInfo.left,f=a.padInfo.top,m=a.outChannels/a.inChannels,g=this.bufferSync(e),x=this.bufferSync(t),E=0;E<s;++E)for(var w=Math.max(0,Math.ceil((f-E)/o)),C=Math.min(a.outHeight,(a.inHeight+f-E)/o),N=0;N<u;++N)for(var S=Math.max(0,Math.ceil((d-N)/i)),I=Math.min(a.outWidth,(a.inWidth+d-N)/i),M=0;M<a.outChannels;++M){for(var j=Math.trunc(M/m),G=M%m,z=0,W=0;W<a.batchSize;++W)for(var V=w;V<C;++V)for(var Z=E+V*o-f,J=S;J<I;++J){var me=N+J*i-d;z+=g.get(W,Z,me,j)*x.get(W,V,J,M)}c.set(z,E,N,j,G)}return c.toTensor()},n.prototype.tile=function(e,t){return ge(e,"tile"),qi(this.bufferSync(e),t)},n.prototype.pad=function(e,t,a){ge(e,"pad");var o=t.map(function(m,g){return m[0]+e.shape[g]+m[1]}),i=t.map(function(m){return m[0]}),s=this.bufferSync(e),u=Je(o,e.dtype);a!==0&&u.values.fill(a);for(var c=0;c<e.size;c++){var d=s.indexToLoc(c),f=d.map(function(m,g){return m+i[g]});u.set.apply(u,[s.get.apply(s,d)].concat(f))}return u.toTensor()},n.prototype.transpose=function(e,t){ge(e,"transpose");for(var a=new Array(e.rank),o=0;o<a.length;o++)a[o]=e.shape[t[o]];var i=this.readSync(e.dataId),s=Je(a,e.dtype),u=this.bufferSync(e);for(o=0;o<e.size;++o){for(var c=u.indexToLoc(o),d=new Array(c.length),f=0;f<d.length;f++)d[f]=c[t[f]];var m=s.locToIndex(d);s.values[m]=i[o]}return s.toTensor()},n.prototype.gather=function(e,t,a){ge([e,t],"gather");var o=e.shape.slice(),i=this.readSync(t.dataId);o[a]=i.length;for(var s=Je(o,e.dtype),u=this.bufferSync(e),c=0;c<s.size;++c){var d=s.indexToLoc(c),f=d.slice();f[a]=i[d[a]];var m=u.locToIndex(f);s.values[c]=u.values[m]}return s.toTensor()},n.prototype.batchToSpaceND=function(e,t,a){ge([e],"batchToSpaceND");var o=t.reduce(function(f,m){return f*m}),i=Na(e.shape,t,o),s=xt(i.length,t.length),u=lo(e.shape,t,o),c=Fs(a,t.length),d=Ps(u,a,t.length);return e.reshape(i).transpose(s).reshape(u).slice(c,d)},n.prototype.spaceToBatchND=function(e,t,a){ge([e],"spaceToBatchND");var o=t.reduce(function(m,g){return m*g}),i=[[0,0]];i.push.apply(i,a);for(var s=1+t.length;s<e.shape.length;++s)i.push([0,0]);var u=e.pad(i),c=Na(u.shape,t,o,!1),d=xt(c.length,t.length,!1),f=lo(u.shape,t,o,!1);return u.reshape(c).transpose(d).reshape(f)},n.prototype.pool=function(e,t,a){ge(e,"pool");for(var o=t.strideHeight,i=t.strideWidth,s=t.dilationHeight,u=t.dilationWidth,c=t.effectiveFilterHeight,d=t.effectiveFilterWidth,f=t.padInfo.top,m=t.padInfo.left,g=a==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,x=this.readSync(e.dataId),E=Je(t.outShape,e.dtype),w=E.values,C=t.outShape[1]*t.outShape[2]*t.outShape[3],N=t.outShape[2]*t.outShape[3],S=t.outShape[3],I=0;I<t.batchSize;++I)for(var M=I*C,j=I*e.strides[0],G=0;G<t.inChannels;++G)for(var z=0;z<t.outHeight;++z)for(var W=z*o-f,V=Math.max(0,W),Z=Math.min(t.inHeight,c+W),J=M+z*N,me=0;me<t.outWidth;++me){for(var fe=me*i-m,he=Math.max(0,fe),Ee=Math.min(t.inWidth,d+fe),be=g,pe=0,Ce=0,Re=V;Re<Z;Re+=s){for(var Le=j+Re*e.strides[1],Xe=he;Xe<Ee;Xe+=u){var qe=x[Le+Xe*e.strides[2]+G];a==="max"&&qe>be?be=qe:a==="avg"&&(pe+=qe,Ce++)}if(isNaN(be))break}w[J+me*S+G]=a==="avg"?pe/Ce:be}return E.toTensor()},n.prototype.maxPool=function(e,t){return this.pool(e,t,"max")},n.prototype.maxPoolPositions=function(e,t){for(var a=Je(t.outShape,"int32"),o=t.strideHeight,i=t.strideWidth,s=t.dilationHeight,u=t.dilationWidth,c=t.effectiveFilterHeight,d=t.effectiveFilterWidth,f=t.padInfo.top,m=t.padInfo.left,g=this.bufferSync(e),x=0;x<t.batchSize;++x)for(var E=0;E<t.inChannels;++E)for(var w=0;w<t.outHeight;++w){for(var C=w*o-f,N=C;N<0;)N+=s;for(var S=Math.min(t.inHeight,c+C),I=0;I<t.outWidth;++I){for(var M=I*i-m,j=M;j<0;)j+=u;for(var G=Math.min(t.inWidth,d+M),z=Number.NEGATIVE_INFINITY,W=-1,V=N;V<S;V+=s)for(var Z=V-C,J=j;J<G;J+=u){var me=J-M,fe=g.get(x,V,J,E);fe>z&&(z=fe,W=Z*d+me)}a.set(W,x,w,I,E)}}return a.toTensor()},n.prototype.maxPoolBackprop=function(e,t,a,o){ge([t,a],"maxPoolBackprop");for(var i=this.maxPoolPositions(t,o),s=o.strideHeight,u=o.strideWidth,c=o.dilationHeight,d=o.dilationWidth,f=o.effectiveFilterHeight,m=o.effectiveFilterWidth,g=m-1-o.padInfo.left,x=f-1-o.padInfo.top,E=Je(t.shape,"float32"),w=this.bufferSync(i),C=this.bufferSync(e),N=0;N<o.batchSize;++N)for(var S=0;S<o.inChannels;++S)for(var I=0;I<o.inHeight;++I)for(var M=0;M<o.inWidth;++M){for(var j=I-x,G=M-g,z=0,W=0;W<f;W+=c){var V=(j+W)/s;if(!(V<0||V>=o.outHeight||Math.floor(V)!==V))for(var Z=0;Z<m;Z+=d){var J=(G+Z)/u;if(!(J<0||J>=o.outWidth||Math.floor(J)!==J)){var me=f*m-1-w.get(N,V,J,S)===W*m+Z?1:0;me!==0&&(z+=C.get(N,V,J,S)*me)}}}E.set(z,N,I,M,S)}return E.toTensor()},n.prototype.avgPoolBackprop=function(e,t,a){ge([e,t],"avgPoolBackprop");for(var o=a.strideHeight,i=a.strideWidth,s=a.filterHeight,u=a.filterWidth,c=a.dilationHeight,d=a.dilationWidth,f=a.effectiveFilterHeight,m=a.effectiveFilterWidth,g=m-1-a.padInfo.left,x=f-1-a.padInfo.top,E=Je(t.shape,"float32"),w=1/(s*u),C=this.bufferSync(e),N=0;N<a.batchSize;++N)for(var S=0;S<a.inChannels;++S)for(var I=0;I<a.inHeight;++I)for(var M=0;M<a.inWidth;++M){for(var j=I-x,G=M-g,z=0,W=0;W<f;W+=c){var V=(j+W)/o;if(!(V<0||V>=a.outHeight||Math.floor(V)!==V))for(var Z=0;Z<m;Z+=d){var J=(G+Z)/i;J<0||J>=a.outWidth||Math.floor(J)!==J||(z+=C.get(N,V,J,S))}}E.set(z*w,N,I,M,S)}return E.toTensor()},n.prototype.pool3d=function(e,t,a){ge(e,"pool3d");for(var o=t.strideDepth,i=t.strideHeight,s=t.strideWidth,u=t.dilationDepth,c=t.dilationHeight,d=t.dilationWidth,f=t.effectiveFilterDepth,m=t.effectiveFilterHeight,g=t.effectiveFilterWidth,x=t.padInfo.front,E=t.padInfo.top,w=t.padInfo.left,C=a==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,N=this.readSync(e.dataId),S=Je(t.outShape,e.dtype),I=S.values,M=t.outShape[1]*t.outShape[2]*t.outShape[3]*t.outShape[4],j=t.outShape[2]*t.outShape[3]*t.outShape[4],G=t.outShape[3]*t.outShape[4],z=t.outShape[4],W=0;W<t.batchSize;++W)for(var V=W*M,Z=W*e.strides[0],J=0;J<t.inChannels;++J)for(var me=0;me<t.outDepth;++me){for(var fe=me*o-x,he=fe;he<0;)he+=u;for(var Ee=Math.min(t.inDepth,f+fe),be=V+me*j,pe=0;pe<t.outHeight;++pe){for(var Ce=pe*i-E,Re=Ce;Re<0;)Re+=c;for(var Le=Math.min(t.inHeight,m+Ce),Xe=be+pe*G,qe=0;qe<t.outWidth;++qe){for(var ht=qe*s-w,pt=ht;pt<0;)pt+=d;for(var vt=Math.min(t.inWidth,g+ht),Dt=Xe+qe*z,Et=C,Nt=0,mn=0,_t=he;_t<Ee;_t+=u){for(var Ht=Z+_t*e.strides[1],It=Re;It<Le;It+=c){for(var hn=Ht+It*e.strides[2],cn=pt;cn<vt;cn+=d){var ln=N[hn+cn*e.strides[3]+J];if(a==="max"&&ln>Et?Et=ln:a==="avg"&&(Nt+=ln,mn++),isNaN(Et))break}if(isNaN(Et))break}if(isNaN(Et))break}I[Dt+J]=a==="avg"?Nt/mn:Et}}}return S.toTensor()},n.prototype.avgPool3d=function(e,t){return ge(e,"avgPool3d"),this.pool3d(e,t,"avg").toFloat()},n.prototype.avgPool3dBackprop=function(e,t,a){ge([e,t],"avgPool3dBackprop");for(var o=a.strideDepth,i=a.strideHeight,s=a.strideWidth,u=a.filterDepth,c=a.filterHeight,d=a.filterWidth,f=a.dilationDepth,m=a.dilationHeight,g=a.dilationWidth,x=a.effectiveFilterDepth,E=a.effectiveFilterHeight,w=a.effectiveFilterWidth,C=x-1-a.padInfo.front,N=w-1-a.padInfo.left,S=E-1-a.padInfo.top,I=Je(t.shape,"float32"),M=1/(u*c*d),j=this.bufferSync(e),G=0;G<a.batchSize;++G)for(var z=0;z<a.inChannels;++z)for(var W=0;W<a.inDepth;++W)for(var V=0;V<a.inHeight;++V)for(var Z=0;Z<a.inWidth;++Z){for(var J=W-C,me=V-S,fe=Z-N,he=0,Ee=0;Ee<x;Ee+=f){var be=(J+Ee)/o;if(!(be<0||be>=a.outDepth||Math.floor(be)!==be))for(var pe=0;pe<E;pe+=m){var Ce=(me+pe)/i;if(!(Ce<0||Ce>=a.outHeight||Math.floor(Ce)!==Ce))for(var Re=0;Re<w;Re+=g){var Le=(fe+Re)/s;Le<0||Le>=a.outWidth||Math.floor(Le)!==Le||(he+=j.get(G,be,Ce,Le,z))}}}I.set(he*M,G,W,V,Z,z)}return I.toTensor()},n.prototype.maxPool3d=function(e,t){return ge(e,"maxPool3d"),this.pool3d(e,t,"max").toFloat()},n.prototype.maxPool3dPositions=function(e,t){for(var a=Je(t.outShape,"int32"),o=t.strideDepth,i=t.strideHeight,s=t.strideWidth,u=t.dilationDepth,c=t.dilationHeight,d=t.dilationWidth,f=t.effectiveFilterDepth,m=t.effectiveFilterHeight,g=t.effectiveFilterWidth,x=t.padInfo.front,E=t.padInfo.top,w=t.padInfo.left,C=this.bufferSync(e),N=0;N<t.batchSize;++N)for(var S=0;S<t.inChannels;++S)for(var I=0;I<t.outDepth;++I){for(var M=I*o-x,j=M;j<0;)j+=u;for(var G=Math.min(t.inDepth,f+M),z=0;z<t.outHeight;++z){for(var W=z*i-E,V=W;V<0;)V+=c;for(var Z=Math.min(t.inHeight,m+W),J=0;J<t.outWidth;++J){for(var me=J*s-w,fe=me;fe<0;)fe+=d;for(var he=Math.min(t.inWidth,g+me),Ee=Number.NEGATIVE_INFINITY,be=-1,pe=j;pe<G;pe+=u)for(var Ce=pe-M,Re=V;Re<Z;Re+=c)for(var Le=Re-W,Xe=fe;Xe<he;Xe+=d){var qe=Xe-me,ht=C.get(N,pe,Re,Xe,S);ht>=Ee&&(Ee=ht,be=Ce*m*g+Le*m+qe)}a.set(be,N,I,z,J,S)}}}return a.toTensor()},n.prototype.maxPool3dBackprop=function(e,t,a,o){ge([t,a],"maxPool3dBackprop");for(var i=this.maxPool3dPositions(t,o),s=o.strideDepth,u=o.strideHeight,c=o.strideWidth,d=o.dilationDepth,f=o.dilationHeight,m=o.dilationWidth,g=o.effectiveFilterDepth,x=o.effectiveFilterHeight,E=o.effectiveFilterWidth,w=g-1-o.padInfo.front,C=E-1-o.padInfo.left,N=x-1-o.padInfo.top,S=Je(t.shape,"float32"),I=this.bufferSync(i),M=this.bufferSync(e),j=0;j<o.batchSize;++j)for(var G=0;G<o.inChannels;++G)for(var z=0;z<o.inDepth;++z)for(var W=0;W<o.inHeight;++W)for(var V=0;V<o.inWidth;++V){for(var Z=z-w,J=W-N,me=V-C,fe=0,he=0;he<g;he+=d){var Ee=(Z+he)/s;if(!(Ee<0||Ee>=o.outDepth||Math.floor(Ee)!==Ee))for(var be=0;be<x;be+=f){var pe=(J+be)/u;if(!(pe<0||pe>=o.outHeight||Math.floor(pe)!==pe))for(var Ce=0;Ce<E;Ce+=m){var Re=(me+Ce)/c;if(!(Re<0||Re>=o.outWidth||Math.floor(Re)!==Re)){var Le=g*x*E-1-I.get(j,Ee,pe,Re,G)===he*x*E+be*E+Ce?1:0;Le!==0&&(fe+=M.get(j,Ee,pe,Re,G)*Le)}}}}S.set(fe,j,z,W,V,G)}return S.toTensor()},n.prototype.cast=function(e,t){return ri(e,t,this)},n.prototype.reshape=function(e,t){return go(e,t)},n.prototype.avgPool=function(e,t){return ge(e,"avgPool"),this.pool(e,t,"avg").toFloat()},n.prototype.resizeBilinear=function(e,t,a,o){ge(e,"resizeBilinear");for(var i=e.shape,s=i[0],u=i[1],c=i[2],d=i[3],f=this.readSync(e.dataId),m=new Float32Array(ae([s,t,a,d])),g=[o&&t>1?u-1:u,o&&a>1?c-1:c],x=[o&&t>1?t-1:t,o&&a>1?a-1:a],E=0,w=g[0]/x[0],C=g[1]/x[1],N=0;N<s;N++)for(var S=0;S<t;S++)for(var I=w*S,M=Math.floor(I),j=I-M,G=Math.min(u-1,Math.ceil(I)),z=N*e.strides[0]+M*e.strides[1],W=N*e.strides[0]+G*e.strides[1],V=0;V<a;V++)for(var Z=C*V,J=Math.floor(Z),me=Z-J,fe=Math.min(c-1,Math.ceil(Z)),he=z+J*e.strides[2],Ee=W+J*e.strides[2],be=z+fe*e.strides[2],pe=W+fe*e.strides[2],Ce=0;Ce<d;Ce++){var Re=f[he+Ce],Le=f[Ee+Ce],Xe=Re+(f[be+Ce]-Re)*me,qe=Xe+(Le+(f[pe+Ce]-Le)*me-Xe)*j;m[E++]=qe}return _n(m,[s,t,a,d])},n.prototype.resizeBilinearBackprop=function(e,t,a){ge([e,t],"resizeBilinearBackprop");for(var o=t.shape,i=o[0],s=o[1],u=o[2],c=o[3],d=e.shape,f=d[1],m=d[2],g=new Float32Array(i*s*u*c),x=[a&&f>1?s-1:s,a&&m>1?u-1:u],E=[a&&f>1?f-1:f,a&&m>1?m-1:m],w=x[0]/E[0],C=x[1]/E[1],N=this.readSync(e.dataId),S=0,I=0;I<i;I++)for(var M=I*t.strides[0],j=0;j<f;j++)for(var G=j*w,z=Math.floor(G),W=Math.min(Math.ceil(G),s-1),V=M+z*t.strides[1],Z=M+W*t.strides[1],J=G-z,me=1-J,fe=0;fe<m;fe++)for(var he=fe*C,Ee=Math.floor(he),be=Math.min(Math.ceil(he),u-1),pe=he-Ee,Ce=1-pe,Re=V+Ee*t.strides[2],Le=V+be*t.strides[2],Xe=Z+Ee*t.strides[2],qe=Z+be*t.strides[2],ht=me*Ce,pt=me*pe,vt=J*Ce,Dt=J*pe,Et=0;Et<c;Et++){var Nt=N[S++];g[Re+Et]+=Nt*ht,g[Le+Et]+=Nt*pt,g[Xe+Et]+=Nt*vt,g[qe+Et]+=Nt*Dt}return Er(g,[i,u,s,c],t.dtype)},n.prototype.resizeNearestNeighbor=function(e,t,a,o){ge(e,"resizeNearestNeighbor");for(var i=e.shape,s=i[0],u=i[1],c=i[2],d=i[3],f=this.readSync(e.dataId),m=new Float32Array(s*t*a*d),g=[o&&t>1?u-1:u,o&&a>1?c-1:c],x=[o&&t>1?t-1:t,o&&a>1?a-1:a],E=g[0]/x[0],w=g[1]/x[1],C=0,N=0;N<s;N++)for(var S=N*e.strides[0],I=0;I<t;I++)for(var M=E*I,j=S+Math.min(u-1,o?Math.round(M):Math.floor(M))*e.strides[1],G=0;G<a;G++)for(var z=w*G,W=j+Math.min(c-1,o?Math.round(z):Math.floor(z))*e.strides[2],V=0;V<d;V++){var Z=f[W+V];m[C++]=Z}return _n(m,[s,t,a,d],e.dtype)},n.prototype.resizeNearestNeighborBackprop=function(e,t,a){ge([e,t],"resizeNearestNeighborBackprop");for(var o=t.shape,i=o[0],s=o[1],u=o[2],c=o[3],d=e.shape,f=d[1],m=d[2],g=new Float32Array(i*s*u*c),x=this.readSync(e.dataId),E=[a&&f>1?s-1:s,a&&m>1?u-1:u],w=[a&&f>1?f-1:f,a&&m>1?m-1:m],C=E[0]/w[0],N=E[1]/w[1],S=1/C,I=1/N,M=2*Math.ceil(S)+2,j=2*Math.ceil(I)+2,G=0;G<i;G++)for(var z=G*t.strides[0],W=0;W<s;W++)for(var V=z+W*t.strides[1],Z=Math.floor(W*S),J=Math.floor(Z-M/2),me=0;me<u;me++)for(var fe=V+me*t.strides[2],he=Math.floor(me*I),Ee=Math.floor(he-j/2),be=0;be<c;be++){for(var pe=0,Ce=0;Ce<M;Ce++){var Re=Ce+J;if(!(Re<0||Re>=f)){var Le=z+Re*e.strides[1],Xe=Re*C;if(W===Math.min(s-1,a?Math.round(Xe):Math.floor(Xe)))for(var qe=0;qe<j;qe++){var ht=qe+Ee;if(!(ht<0||ht>=m)){var pt=Le+ht*e.strides[2],vt=ht*N;me===Math.min(u-1,a?Math.round(vt):Math.floor(vt))&&(pe+=x[pt+be])}}}}g[fe+be]=pe}return Er(g,t.shape,t.dtype)},n.prototype.batchNormalization=function(e,t,a,o,i,s){ge([e,t,a,i,s],"batchNorm");for(var u=this.readSync(e.dataId),c=this.readSync(t.dataId),d=this.readSync(a.dataId),f=i?this.readSync(i.dataId):new Float32Array([1]),m=s?this.readSync(s.dataId):new Float32Array([0]),g=new Float32Array(u.length),x=m.length,E=f.length,w=d.length,C=c.length,N=0,S=0,I=0,M=0,j=0;j<u.length;++j)g[j]=m[N++]+(u[j]-c[S++])*f[I++]/Math.sqrt(d[M++]+o),N>=x&&(N=0),S>=C&&(S=0),I>=E&&(I=0),M>=w&&(M=0);return Er(g,e.shape)},n.prototype.localResponseNormalization4D=function(e,t,a,o,i){ge(e,"localResponseNormalization4D");var s=e.shape[3],u=s-1,c=this.readSync(e.dataId),d=e.size,f=new Float32Array(d);function m(w){for(var C=w%s,N=w-C+Math.max(0,C-t),S=w-C+Math.min(C+t,u),I=0;N<=S;N++){var M=c[N];I+=M*M}return I}for(var g=0;g<d;g++){var x=m(g),E=c[g]*Math.pow(a+o*x,-i);f[g]=E}return Er(f,e.shape)},n.prototype.LRNGrad=function(e,t,a,o,i,s,u){ge(e,"LRNGrad");for(var c=e.shape[3],d=this.readSync(e.dataId),f=this.readSync(t.dataId),m=this.readSync(a.dataId),g=new Float32Array(e.size),x=e.size,E=0;E<x;E++){for(var w=E%c,C=E-w+Math.max(0,w-o),N=E-w+Math.min(c,w+o+1),S=0,I=C;I<N;I++)S+=Math.pow(f[I],2);for(S=s*S+i,I=C;I<N;I++){var M=-2*s*u*f[I]*m[E]/S;E===I&&(M+=Math.pow(S,-u)),M*=d[E],g[I]+=M}}return Er(g,e.shape)},n.prototype.multinomial=function(e,t,a,o){ge(e,"multinomial");for(var i=t?e:Sa(e),s=i.shape[0],u=i.shape[1],c=Jt([s,a],"int32"),d=this.readSync(c.dataId),f=this.readSync(i.dataId),m=0;m<s;++m){var g=m*u,x=new Float32Array(u-1);x[0]=f[g];for(var E=1;E<x.length;++E)x[E]=x[E-1]+f[g+E];for(var w=Da(o.toString()),C=m*a,N=0;N<a;++N){var S=w();d[C+N]=x.length;for(var I=0;I<x.length;I++)if(S<x[I]){d[C+N]=I;break}}}return c},n.prototype.oneHot=function(e,t,a,o){ge(e,"oneHot");var i=new Float32Array(e.size*t);i.fill(o);for(var s=this.readSync(e.dataId),u=0;u<e.size;++u)s[u]>=0&&s[u]<t&&(i[u*t+s[u]]=a);return Wr(i,[e.size,t],"int32")},n.prototype.nonMaxSuppression=function(e,t,a,o,i){return ge(e,"nonMaxSuppression"),ai(this.readSync(e.dataId),this.readSync(t.dataId),a,o,i)},n.prototype.fft=function(e){return this.fftBatch(e,!1)},n.prototype.ifft=function(e){return this.fftBatch(e,!0)},n.prototype.fftBatch=function(e,t){for(var a=e.shape[0],o=e.shape[1],i=Je(e.shape,"float32"),s=Je(e.shape,"float32"),u=Hn(e).as2D(a,o),c=cr(e).as2D(a,o),d=0;d<a;d++)for(var f=u.slice([d,0],[1,o]),m=c.slice([d,0],[1,o]),g=zt(f,m),x=this.readSync(this.fftImpl(g,t).dataId),E=0;E<o;E++){var w=Gi(x,E);i.values[d*o+E]=w.real,s.values[d*o+E]=w.imag}return zt(i.toTensor(),s.toTensor()).as2D(a,o)},n.prototype.fftImpl=function(e,t){var a=e.as1D(),o=a.size;if(this.isExponentOf2(o)){var i=this.fftRadix2(a,o,t).as2D(e.shape[0],e.shape[1]);return t&&(i=zt(Hn(i).div(We(o)),cr(i).div(We(o)))),i}var s=this.readSync(e.dataId),u=function(c){for(var d=new Float32Array(c.length/2),f=new Float32Array(c.length/2),m=0;m<c.length;m+=2)d[m/2]=c[m],f[m/2]=c[m+1];return{real:d,imag:f}}(this.fourierTransformByMatmul(s,o,t));return zt(u.real,u.imag).as2D(e.shape[0],e.shape[1])},n.prototype.isExponentOf2=function(e){return(e&e-1)==0},n.prototype.fftRadix2=function(e,t,a){if(t===1)return e;var o=this.readSync(e.dataId),i=t/2,s=function(C){for(var N=Math.ceil(C.length/4),S=new Float32Array(N),I=new Float32Array(N),M=0;M<C.length;M+=4)S[Math.floor(M/4)]=C[M],I[Math.floor(M/4)]=C[M+1];return{real:S,imag:I}}(o),u=zt(s.real,s.imag).as1D(),c=function(C){for(var N=Math.floor(C.length/4),S=new Float32Array(N),I=new Float32Array(N),M=2;M<C.length;M+=4)S[Math.floor(M/4)]=C[M],I[Math.floor(M/4)]=C[M+1];return{real:S,imag:I}}(o),d=zt(c.real,c.imag).as1D();u=this.fftRadix2(u,i,a),d=this.fftRadix2(d,i,a);var f=function(C,N){for(var S=new Float32Array(C/2),I=new Float32Array(C/2),M=0;M<Math.ceil(C/2);M++){var j=(N?2:-2)*Math.PI*(M/C);S[M]=Math.cos(j),I[M]=Math.sin(j)}return{real:S,imag:I}}(t,a),m=zt(f.real,f.imag).mul(d),g=u.add(m),x=u.sub(m),E=Hn(g).concat(Hn(x)),w=cr(g).concat(cr(x));return zt(E,w).as1D()},n.prototype.fourierTransformByMatmul=function(e,t,a){for(var o=new Float32Array(2*t),i=0;i<t;i++){for(var s=0,u=0,c=0;c<t;c++){var d=Vs(i*c,t,a),f=Gi(e,c);s+=f.real*d.real-f.imag*d.imag,u+=f.real*d.imag+f.imag*d.real}a&&(s/=t,u/=t),zs(o,s,u,i)}return o},n.prototype.depthToSpace=function(e,t,a){D(a==="NHWC",function(){return"Only NHWC dataFormat supported on CPU for depthToSpace. Got "+a}),D(t>1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+t});for(var o=e.shape[0],i=e.shape[1],s=e.shape[2],u=e.shape[3],c=i*t,d=s*t,f=u/(t*t),m=this.readSync(e.dataId),g=new Float32Array(o*c*d*f),x=0,E=0;E<o;++E)for(var w=0;w<c;++w)for(var C=Math.floor(w/t),N=w%t,S=0;S<d;++S)for(var I=Math.floor(S/t),M=(N*t+S%t)*f,j=0;j<f;++j){var G=j+M+u*(I+s*(C+i*E));g[x++]=m[G]}return Er(g,[o,c,d,f])},n.prototype.broadcastedBinaryOp=function(e,t,a,o){var i=nt(e.shape,t.shape),s=Je(i,a),u=this.readSync(e.dataId),c=this.readSync(t.dataId),d=dr(e.shape,i),f=dr(t.shape,i),m=s.values;if(d.length+f.length===0)for(var g=0;g<m.length;++g)m[g]=o(u[g%u.length],c[g%c.length]);else{var x=this.bufferSync(e),E=this.bufferSync(t),w=function(C){var N=s.indexToLoc(C),S=N.slice(-e.rank);d.forEach(function(G){return S[G]=0});var I=x.locToIndex(S),M=N.slice(-t.rank);f.forEach(function(G){return M[G]=0});var j=E.locToIndex(M);m[C]=o(u[I],c[j])};for(g=0;g<m.length;++g)w(g)}return s.toTensor()},n.prototype.broadcastedBinaryComplexOp=function(e,t,a){var o=nt(e.shape,t.shape),i=Je(o,"float32"),s=Je(o,"float32"),u=this.readSync(e.dataId),c=this.readSync(t.dataId),d=dr(e.shape,o),f=dr(t.shape,o),m=i.values,g=s.values;if(d.length+f.length===0)for(var x=0;x<m.length;x++){var E=x%u.length,w=x%c.length,C=a(u[2*E],u[2*E+1],c[2*w],c[2*w+1]);m[x]=C.real,g[x]=C.imag}else{var N=this.bufferSync(this.data.get(e.dataId).complexTensors.real),S=this.bufferSync(this.data.get(t.dataId).complexTensors.real),I=function(M){var j=i.indexToLoc(M),G=j.slice(-e.rank);d.forEach(function(J){return G[J]=0});var z=N.locToIndex(G),W=j.slice(-t.rank);f.forEach(function(J){return W[J]=0});var V=S.locToIndex(W),Z=a(u[2*z],u[2*z+1],c[2*V],c[2*V+1]);m[M]=Z.real,g[M]=Z.imag};for(x=0;x<m.length;x++)I(x)}return this.complex(i.toTensor(),s.toTensor())},n.prototype.split=function(e,t,a){return Ki(e,t,a)},n.prototype.dispose=function(){},n.prototype.floatPrecision=function(){return 32},n.prototype.epsilon=function(){return 1e-7},n.prototype.cropAndResize=function(e,t,a,o,i,s){for(var u=e.shape,c=u[0],d=u[1],f=u[2],m=u[3],g=t.shape[0],x=o[0],E=o[1],w=Je([g,x,E,m],"float32"),C=this.readSync(t.dataId),N=this.readSync(a.dataId),S=this.readSync(e.dataId),I=e.strides,M=w.strides,j=0;j<g;j++){var G=4*j,z=C[G],W=C[G+1],V=C[G+2],Z=C[G+3],J=N[j];if(!(J>=c))for(var me=x>1?(V-z)*(d-1)/(x-1):0,fe=E>1?(Z-W)*(f-1)/(E-1):0,he=0;he<x;he++){var Ee=x>1?z*(d-1)+he*me:.5*(z+V)*(d-1);if(Ee<0||Ee>d-1)for(var be=0;be<E;be++)for(var pe=0;pe<m;pe++){var Ce=pe+be*M[2]+he*M[1]+j*M[0];w.values[Ce]=s}else if(i==="bilinear"){var Re=Math.floor(Ee),Le=Math.ceil(Ee),Xe=Ee-Re;for(be=0;be<E;be++)if((_t=E>1?W*(f-1)+be*fe:.5*(W+Z)*(f-1))<0||_t>f-1)for(pe=0;pe<m;pe++)Ce=pe+be*M[2]+he*M[1]+j*M[0],w.values[Ce]=s;else{var qe=Math.floor(_t),ht=Math.ceil(_t),pt=_t-qe;for(pe=0;pe<m;pe++){var vt=S[Ce=pe+qe*I[2]+Re*I[1]+J*I[0]],Dt=S[Ce=pe+ht*I[2]+Re*I[1]+J*I[0]],Et=S[Ce=pe+qe*I[2]+Le*I[1]+J*I[0]],Nt=vt+(Dt-vt)*pt,mn=Et+(S[Ce=pe+ht*I[2]+Le*I[1]+J*I[0]]-Et)*pt;Ce=pe+be*M[2]+he*M[1]+j*M[0],w.values[Ce]=Nt+(mn-Nt)*Xe}}}else for(be=0;be<E;++be){var _t;if((_t=E>1?W*(f-1)+be*fe:.5*(W+Z)*(f-1))<0||_t>f-1)for(pe=0;pe<m;pe++)Ce=pe+be*M[2]+he*M[1]+j*M[0],w.values[Ce]=s;else{var Ht=Math.round(_t),It=Math.round(Ee);for(pe=0;pe<m;pe++){var hn=pe+Ht*I[2]+It*I[1]+J*I[0],cn=pe+be*M[2]+he*M[1]+j*M[0];w.values[cn]=S[hn]}}}}}return w.toTensor()},n.prototype.sparseToDense=function(e,t,a,o){var i=ka(0,e,a),s=i.sliceRank,u=i.numUpdates,c=i.sliceSize,d=i.strides,f=i.outputSize;return this.scatter(e,t,a,f,c,u,s,d,o,!1)},n.prototype.gatherND=function(e,t){var a=t.shape,o=a[a.length-1],i=Pi(e,t),s=i[0],u=i[1],c=i[2],d=i[3];if(u===0)return _n([],s,e.dtype);for(var f=new za([u,c],e.dtype),m=this.readSync(t.dataId),g=this.readSync(e.dataId),x=0;x<u;x++){for(var E=[],w=0,C=0;C<o;C++){var N=m[x*o+C];w+=N*d[C],E.push(N)}if(w<0||w>=e.size/c)throw new Error("Invalid indices: "+E+" does not index into "+e.shape);for(var S=0;S<c;S++)f.values[x*c+S]=g[w*c+S]}return f.toTensor().reshape(s)},n.prototype.scatterND=function(e,t,a){var o=ka(0,e,a),i=o.sliceRank,s=o.numUpdates,u=o.sliceSize,c=o.strides,d=o.outputSize,f=We(0);return this.scatter(e,t,a,d,u,s,i,c,f,!0)},n.prototype.fill=function(e,t,a){var o=bn(a=a||ar(t),ae(e));return o.fill(t),X.makeTensor(o,e,a,this)},n.prototype.onesLike=function(e){if(e.dtype==="string")throw new Error("onesLike is not supported for string tensors");return this.fill(e.shape,1,e.dtype)},n.prototype.zerosLike=function(e){var t=bn(e.dtype,ae(e.shape));return this.makeOutput(t,e.shape,e.dtype)},n.prototype.linspace=function(e,t,a){return Vi(e,t,a)},n.prototype.scatter=function(e,t,a,o,i,s,u,c,d,f){var m=[o/i,i],g=this.readSync(e.dataId),x=this.readSync(t.dataId);if(o===0)return _n([],a,t.dtype);var E=new za(m,t.dtype);E.values.fill(this.readSync(d.dataId)[0]);for(var w=0;w<s;w++){for(var C=[],N=0,S=0;S<u;S++){var I=g[w*u+S];C.push(I),N+=I*c[S]}if(N<0||N>=o/i)throw new Error("Invalid indices: "+C+" does not index into "+a);for(var M=0;M<i;M++)f?E.values[N*i+M]+=x[w*i+M]:E.values[N*i+M]=t.rank===0?x[0]:x[w*i+M]}return E.toTensor().reshape(a)},n}(fo);X.registerBackend("cpu",function(){return new bf},1);for(var xu=0,Tl=[{kernelName:"NonMaxSuppressionV5",backendName:"cpu",kernelFunc:function(r){var n=r.inputs,e=r.backend,t=r.attrs,a=n,o=a.boxes,i=a.scores,s=t,u=s.maxOutputSize,c=s.iouThreshold,d=s.scoreThreshold,f=s.softNmsSigma,m=e;ge(o,"NonMaxSuppressionWithScore");var g=oi(m.data.get(o.dataId).values,m.data.get(i.dataId).values,u,c,d,f);return[g.selectedIndices,g.selectedScores]}},{kernelName:"Square",backendName:"cpu",kernelFunc:function(r){var n=r.inputs,e=r.backend,t=n.x,a=e;ge(t,"square");for(var o=a.data.get(t.dataId).values,i=new Float32Array(o.length),s=0;s<o.length;++s){var u=o[s];i[s]=u*u}return{dataId:a.write(i,t.shape,t.dtype),shape:t.shape,dtype:t.dtype}}},{kernelName:li,backendName:"cpu",kernelFunc:function(r){var n=r.inputs,e=r.backend,t=n,a=t.a,o=t.b,i=e;ge([a,o],li);var s=i.data.get(a.dataId).values,u=i.data.get(o.dataId).values,c=function(m,g,x,E,w,C){var N=nt(m,g),S=N.length,I=Rn(N),M=Cn(w,ae(N)),j=m.length,G=g.length,z=Rn(m),W=Rn(g),V=dr(m,N),Z=dr(g,N);if(V.length+Z.length===0)for(var J=0;J<M.length;++J)M[J]=C(x[J%x.length],E[J%E.length]);else{var me=function(fe){var he=Ut(fe,S,I),Ee=he.slice(-j);V.forEach(function(Re){return Ee[Re]=0});var be=Rt(Ee,j,z),pe=he.slice(-G);Z.forEach(function(Re){return pe[Re]=0});var Ce=Rt(pe,G,W);M[fe]=C(x[be],E[Ce])};for(J=0;J<M.length;++J)me(J)}return[M,N]}(a.shape,o.shape,s,u,a.dtype,function(m,g){var x=m-g;return x*x}),d=c[0],f=c[1];return{dataId:i.write(d,f,a.dtype),shape:f,dtype:a.dtype}}}];xu<Tl.length;xu++)Ft(Tl[xu]);for(var bo,wf=function(r){this.variableNames=["A"];var n=h(),e=r[0],t=r[1];this.outputShape=r,this.userCode=`
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
int texR = coords[0];
|
|
int texC = coords[1];
|
|
int depth = coords[2];
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(`+t+".0, "+e+`.0);
|
|
|
|
vec4 values = `+n.texture2D+`(A, uv);
|
|
float value;
|
|
if (depth == 0) {
|
|
value = values.r;
|
|
} else if (depth == 1) {
|
|
value = values.g;
|
|
} else if (depth == 2) {
|
|
value = values.b;
|
|
} else if (depth == 3) {
|
|
value = values.a;
|
|
}
|
|
|
|
setOutput(floor(value * 255.0 + 0.5));
|
|
}
|
|
`},Ef=function(r){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var n=h(),e=r[0],t=r[1];this.outputShape=r,this.userCode=`
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
int texR = coords[0];
|
|
int texC = coords[1];
|
|
int depth = coords[2];
|
|
|
|
vec4 result = vec4(0.);
|
|
|
|
for(int row=0; row<=1; row++) {
|
|
for(int col=0; col<=1; col++) {
|
|
texC = coords[1] + row;
|
|
depth = coords[2] + col;
|
|
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(`+t+".0, "+e+`.0);
|
|
vec4 values = `+n.texture2D+`(A, uv);
|
|
float value;
|
|
if (depth == 0) {
|
|
value = values.r;
|
|
} else if (depth == 1) {
|
|
value = values.g;
|
|
} else if (depth == 2) {
|
|
value = values.b;
|
|
} else if (depth == 3) {
|
|
value = values.a;
|
|
}
|
|
|
|
result[row * 2 + col] = floor(value * 255.0 + 0.5);
|
|
}
|
|
}
|
|
|
|
`+n.output+` = result;
|
|
}
|
|
`},bu=0,Dl=[{kernelName:"FromPixels",backendName:"webgl",kernelFunc:function(r){var n=r.inputs,e=r.backend,t=r.attrs,a=n.pixels,o=t.numChannels,i=typeof HTMLVideoElement!="undefined"&&a instanceof HTMLVideoElement,s=typeof HTMLImageElement!="undefined"&&a instanceof HTMLImageElement,u=i?[a.videoWidth,a.videoHeight]:[a.width,a.height],c=u[0],d=u[1],f=[d,c],m=[d,c,o];(s||i)&&(bo==null&&(bo=document.createElement("canvas").getContext("2d")),bo.canvas.width=c,bo.canvas.height=d,bo.drawImage(a,0,0,c,d),a=bo.canvas);var g=e.makeTensorInfo(f,"int32");e.texData.get(g.dataId).usage=An.PIXELS,e.gpgpu.uploadPixelDataToTexture(e.getTexture(g.dataId),a);var x=ee().getBool("WEBGL_PACK")?new Ef(m):new wf(m),E=e.runWebGLProgram(x,[g],"int32");return e.disposeData(g.dataId),E}},{kernelName:"NonMaxSuppressionV5",backendName:"webgl",kernelFunc:function(r){var n=r.inputs,e=r.backend,t=r.attrs;eo("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");var a=n,o=a.boxes,i=a.scores,s=t,u=s.maxOutputSize,c=s.iouThreshold,d=s.scoreThreshold,f=s.softNmsSigma,m=e,g=oi(m.readSync(o.dataId),m.readSync(i.dataId),u,c,d,f);return[g.selectedIndices,g.selectedScores]}},{kernelName:"Square",backendName:"webgl",kernelFunc:function(r){var n=r.inputs,e=r.backend,t=n.x,a=e,o=new it(t.shape,"return x * x;");return a.runWebGLProgram(o,[t],t.dtype)}},{kernelName:li,backendName:"webgl",kernelFunc:function(r){var n=r.inputs,e=r.backend,t=n,a=t.a,o=t.b,i=e,s=ee().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ie("return (a - b) * (a - b);",a.shape,o.shape):new dt("return (a - b) * (a - b);",a.shape,o.shape);return i.compileAndRun(s,[a,o])}}];bu<Dl.length;bu++)Ft(Dl[bu]);for(var wu=0,Nl=[{kernelName:"Square",gradFunc:function(r,n){var e=n[0];return{x:function(){return r.mul(e.toFloat().mul(2))}}}},{kernelName:li,gradFunc:function(r,n){var e=n[0],t=n[1],a=We(2);return{a:function(){return Ba(r,Ba(a,va(e,t)))},b:function(){return Ba(r,Ba(a,va(t,e)))}}}}];wu<Nl.length;wu++)xn(Nl[wu]);var _f=function(){function r(){}return r.prototype.fetch=function(n,e){return fetch(n,e)},r.prototype.now=function(){return performance.now()},r.prototype.encode=function(n,e){if(e!=="utf-8"&&e!=="utf8")throw new Error("Browser's encoder only supports utf-8, but got "+e);return this.textEncoder==null&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(n)},r.prototype.decode=function(n,e){return new TextDecoder(e).decode(n)},r}();ee().get("IS_BROWSER")&&ee().setPlatform("browser",new _f);var Eu,Cf=function(){return te(6)},Rf=function(){function r(){this.util=te(7),this.textEncoder=new this.util.TextEncoder}return r.prototype.fetch=function(n,e){return ee().global.fetch!=null?ee().global.fetch(n,e):(Eu==null&&(Eu=Cf()),Eu(n,e))},r.prototype.now=function(){var n=ze.hrtime();return 1e3*n[0]+n[1]/1e6},r.prototype.encode=function(n,e){if(e!=="utf-8"&&e!=="utf8")throw new Error("Node built-in encoder only supports utf-8, but got "+e);return this.textEncoder.encode(n)},r.prototype.decode=function(n,e){return n.length===0?"":new this.util.TextDecoder(e).decode(n)},r}();ee().get("IS_NODE")&&ee().setPlatform("node",new Rf);var _u={float32:4,int32:4,uint16:2,uint8:1,bool:1},us=4;function kl(r,n){for(var e={},t=0,a=function(s){var u=s.name,c=s.dtype,d=s.shape,f=ae(d),m=void 0;if("quantization"in s){var g=s.quantization;if(g.dtype!=="uint8"&&g.dtype!=="uint16")throw new Error("Weight "+s.name+" has unknown quantization dtype "+g.dtype+". Supported quantization dtypes are: 'uint8' and 'uint16'.");var x=_u[g.dtype],E=r.slice(t,t+f*x),w=g.dtype==="uint8"?new Uint8Array(E):new Uint16Array(E);if(c==="float32")m=Float32Array.from(w,function(j){return j*g.scale+g.min});else{if(c!=="int32")throw new Error("Unsupported dtype in weight '"+u+"': "+c);m=Int32Array.from(w,function(j){return Math.round(j*g.scale+g.min)})}t+=f*x}else if(c==="string"){var C=ae(s.shape);m=[];for(var N=0;N<C;N++){var S=new Uint32Array(r.slice(t,t+us))[0];t+=us;var I=new Uint8Array(r.slice(t,t+S));m.push(I),t+=S}}else{var M=_u[c];if(E=r.slice(t,t+f*M),c==="float32")m=new Float32Array(E);else if(c==="int32")m=new Int32Array(E);else{if(c!=="bool")throw new Error("Unsupported dtype in weight '"+u+"': "+c);m=new Uint8Array(E)}t+=f*M}e[u]=_n(m,d,c)},o=0,i=n;o<i.length;o++)a(i[o]);return e}function Af(r){if(r===null)throw new Error("Invalid input value: "+JSON.stringify(r));var n=0,e=[];r.forEach(function(o){if(n+=o.byteLength,e.push(o.byteLength===o.buffer.byteLength?o:new o.constructor(o)),!(o instanceof Float32Array||o instanceof Int32Array||o instanceof Uint8Array))throw new Error("Unsupported TypedArray subtype: "+o.constructor.name)});var t=new Uint8Array(n),a=0;return e.forEach(function(o){t.set(new Uint8Array(o.buffer),a),a+=o.byteLength}),t.buffer}var Cu=typeof at!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function Sl(r){return Cu?at.byteLength(r):new Blob([r]).size}function Ru(r){var n=0;r.forEach(function(a){n+=a.byteLength});var e=new Uint8Array(n),t=0;return r.forEach(function(a){e.set(new Uint8Array(a),t),t+=a.byteLength}),e.buffer}function Ol(r){for(r=r.trim();r.endsWith("/");)r=r.slice(0,r.length-1);var n=r.split("/");return n[n.length-1]}function pi(r){if(r.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:r.modelTopology==null?0:Sl(JSON.stringify(r.modelTopology)),weightSpecsBytes:r.weightSpecs==null?0:Sl(JSON.stringify(r.weightSpecs)),weightDataBytes:r.weightData==null?0:r.weightData.byteLength}}var Zn=function(){function r(){this.saveRouters=[],this.loadRouters=[]}return r.getInstance=function(){return r.instance==null&&(r.instance=new r),r.instance},r.registerSaveRouter=function(n){r.getInstance().saveRouters.push(n)},r.registerLoadRouter=function(n){r.getInstance().loadRouters.push(n)},r.getSaveHandlers=function(n){return r.getHandlers(n,"save")},r.getLoadHandlers=function(n,e){return r.getHandlers(n,"load",e)},r.getHandlers=function(n,e,t){var a=[];return(e==="load"?r.getInstance().loadRouters:r.getInstance().saveRouters).forEach(function(o){var i=o(n,t);i!==null&&a.push(i)}),a},r}(),wo="://",ma=function(){function r(){this.managers={}}return r.getInstance=function(){return r.instance==null&&(r.instance=new r),r.instance},r.registerManager=function(n,e){D(n!=null,function(){return"scheme must not be undefined or null."}),n.endsWith(wo)&&(n=n.slice(0,n.indexOf(wo))),D(n.length>0,function(){return"scheme must not be an empty string."});var t=r.getInstance();D(t.managers[n]==null,function(){return"A model store manager is already registered for scheme '"+n+"'."}),t.managers[n]=e},r.getManager=function(n){var e=this.getInstance().managers[n];if(e==null)throw new Error("Cannot find model manager for scheme '"+n+"'");return e},r.getSchemes=function(){return Object.keys(this.getInstance().managers)},r}();function cs(r){if(r.indexOf(wo)===-1)throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+ma.getSchemes().join(","));return{scheme:r.split(wo)[0],path:r.split(wo)[1]}}function Il(r,n,e){return e===void 0&&(e=!1),ve(this,void 0,void 0,function(){var t,a,o,i,s,u,c,d,f;return ye(this,function(m){switch(m.label){case 0:return D(r!==n,function(){return"Old path and new path are the same: '"+r+"'"}),D((t=Zn.getLoadHandlers(r)).length>0,function(){return"Copying failed because no load handler is found for source URL "+r+"."}),D(t.length<2,function(){return"Copying failed because more than one ("+t.length+") load handlers for source URL "+r+"."}),a=t[0],D((o=Zn.getSaveHandlers(n)).length>0,function(){return"Copying failed because no save handler is found for destination URL "+n+"."}),D(o.length<2,function(){return"Copying failed because more than one ("+t.length+") save handlers for destination URL "+n+"."}),i=o[0],s=cs(r).scheme,u=cs(r).path,c=s===cs(r).scheme,[4,a.load()];case 1:return d=m.sent(),e&&c?[4,ma.getManager(s).removeModel(u)]:[3,3];case 2:m.sent(),m.label=3;case 3:return[4,i.save(d)];case 4:return f=m.sent(),!e||c?[3,6]:[4,ma.getManager(s).removeModel(u)];case 5:m.sent(),m.label=6;case 6:return[2,f.modelArtifactsInfo]}})})}var ja="models_store",ga="model_info_store";function Ml(){if(!ee().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var r=window||self,n=r.indexedDB||r.mozIndexedDB||r.webkitIndexedDB||r.msIndexedDB||r.shimIndexedDB;if(n==null)throw new Error("The current browser does not appear to support IndexedDB.");return n}function Au(r){var n=r.result;n.createObjectStore(ja,{keyPath:"modelPath"}),n.createObjectStore(ga,{keyPath:"modelPath"})}var Eo=function(){function r(n){if(this.indexedDB=Ml(),n==null||!n)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=n}return r.prototype.save=function(n){return ve(this,void 0,void 0,function(){return ye(this,function(e){if(n.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return[2,this.databaseAction(this.modelPath,n)]})})},r.prototype.load=function(){return ve(this,void 0,void 0,function(){return ye(this,function(n){return[2,this.databaseAction(this.modelPath)]})})},r.prototype.databaseAction=function(n,e){var t=this;return new Promise(function(a,o){var i=t.indexedDB.open("tensorflowjs",1);i.onupgradeneeded=function(){return Au(i)},i.onsuccess=function(){var s=i.result;if(e==null){var u=s.transaction(ja,"readonly"),c=u.objectStore(ja).get(t.modelPath);c.onsuccess=function(){if(c.result==null)return s.close(),o(new Error("Cannot find model with path '"+t.modelPath+"' in IndexedDB."));a(c.result.modelArtifacts)},c.onerror=function(E){return s.close(),o(c.error)},u.oncomplete=function(){return s.close()}}else{var d,f=pi(e),m=s.transaction(ga,"readwrite"),g=m.objectStore(ga),x=g.put({modelPath:t.modelPath,modelArtifactsInfo:f});x.onsuccess=function(){var E=(d=s.transaction(ja,"readwrite")).objectStore(ja).put({modelPath:t.modelPath,modelArtifacts:e,modelArtifactsInfo:f});E.onsuccess=function(){return a({modelArtifactsInfo:f})},E.onerror=function(w){var C=(g=m.objectStore(ga)).delete(t.modelPath);C.onsuccess=function(){return s.close(),o(E.error)},C.onerror=function(N){return s.close(),o(E.error)}}},x.onerror=function(E){return s.close(),o(x.error)},m.oncomplete=function(){d==null?s.close():d.oncomplete=function(){return s.close()}}}},i.onerror=function(s){return o(i.error)}})},r.URL_SCHEME="indexeddb://",r}(),Fl=function(r){return ee().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(Eo.URL_SCHEME)?(n=r.slice(Eo.URL_SCHEME.length),new Eo(n)):null;var n};Zn.registerSaveRouter(Fl),Zn.registerLoadRouter(Fl);var Tf=function(){function r(){this.indexedDB=Ml()}return r.prototype.listModels=function(){return ve(this,void 0,void 0,function(){var n=this;return ye(this,function(e){return[2,new Promise(function(t,a){var o=n.indexedDB.open("tensorflowjs",1);o.onupgradeneeded=function(){return Au(o)},o.onsuccess=function(){var i=o.result,s=i.transaction(ga,"readonly"),u=s.objectStore(ga).getAll();u.onsuccess=function(){for(var c={},d=0,f=u.result;d<f.length;d++){var m=f[d];c[m.modelPath]=m.modelArtifactsInfo}t(c)},u.onerror=function(c){return i.close(),a(u.error)},s.oncomplete=function(){return i.close()}},o.onerror=function(i){return a(o.error)}})]})})},r.prototype.removeModel=function(n){return ve(this,void 0,void 0,function(){var e=this;return ye(this,function(t){var a;return n=(a=n).startsWith(Eo.URL_SCHEME)?a.slice(Eo.URL_SCHEME.length):a,[2,new Promise(function(o,i){var s=e.indexedDB.open("tensorflowjs",1);s.onupgradeneeded=function(){return Au(s)},s.onsuccess=function(){var u,c=s.result,d=c.transaction(ga,"readwrite"),f=d.objectStore(ga),m=f.get(n);m.onsuccess=function(){if(m.result==null)return c.close(),i(new Error("Cannot find model with path '"+n+"' in IndexedDB."));var g=f.delete(n),x=function(){var E=(u=c.transaction(ja,"readwrite")).objectStore(ja).delete(n);E.onsuccess=function(){return o(m.result.modelArtifactsInfo)},E.onerror=function(w){return i(m.error)}};g.onsuccess=x,g.onerror=function(E){return x(),c.close(),i(m.error)}},m.onerror=function(g){return c.close(),i(m.error)},d.oncomplete=function(){u==null?c.close():u.oncomplete=function(){return c.close()}}},s.onerror=function(u){return i(s.error)}})]})})},r}();if(ee().getBool("IS_BROWSER"))try{ma.registerManager(Eo.URL_SCHEME,new Tf)}catch(r){}var Kr="/",_o="tensorflowjs_models",Pl="info",Df="model_topology",Nf="weight_specs",kf="weight_data",Sf="model_metadata";function Ll(r){return{info:[_o,r,Pl].join(Kr),topology:[_o,r,Df].join(Kr),weightSpecs:[_o,r,Nf].join(Kr),weightData:[_o,r,kf].join(Kr),modelMetadata:[_o,r,Sf].join(Kr)}}function Of(r){var n=r.split(Kr);if(n.length<3)throw new Error("Invalid key format: "+r);return n.slice(1,n.length-1).join(Kr)}var Co=function(){function r(n){if(!ee().getBool("IS_BROWSER")||typeof window=="undefined"||window.localStorage===void 0)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,n==null||!n)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=n,this.keys=Ll(this.modelPath)}return r.prototype.save=function(n){return ve(this,void 0,void 0,function(){var e,t,a;return ye(this,function(o){if(n.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");e=JSON.stringify(n.modelTopology),t=JSON.stringify(n.weightSpecs),a=pi(n);try{return this.LS.setItem(this.keys.info,JSON.stringify(a)),this.LS.setItem(this.keys.topology,e),this.LS.setItem(this.keys.weightSpecs,t),this.LS.setItem(this.keys.weightData,function(i){if(Cu)return at.from(i).toString("base64");for(var s=new Uint8Array(i),u="",c=0,d=s.length;c<d;c++)u+=String.fromCharCode(s[c]);return btoa(u)}(n.weightData)),this.LS.setItem(this.keys.modelMetadata,JSON.stringify({format:n.format,generatedBy:n.generatedBy,convertedBy:n.convertedBy,userDefinedMetadata:n.userDefinedMetadata})),[2,{modelArtifactsInfo:a}]}catch(i){throw this.LS.removeItem(this.keys.info),this.LS.removeItem(this.keys.topology),this.LS.removeItem(this.keys.weightSpecs),this.LS.removeItem(this.keys.weightData),this.LS.removeItem(this.keys.modelMetadata),new Error("Failed to save model '"+this.modelPath+"' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes="+a.modelTopologyBytes+", weightSpecsBytes="+a.weightSpecsBytes+", weightDataBytes="+a.weightDataBytes+".")}return[2]})})},r.prototype.load=function(){return ve(this,void 0,void 0,function(){var n,e,t,a,o,i,s;return ye(this,function(u){if((n=JSON.parse(this.LS.getItem(this.keys.info)))==null)throw new Error("In local storage, there is no model with name '"+this.modelPath+"'");if(n.modelTopologyType!=="JSON")throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");if(e={},(t=JSON.parse(this.LS.getItem(this.keys.topology)))==null)throw new Error("In local storage, the topology of model '"+this.modelPath+"' is missing.");if(e.modelTopology=t,(a=JSON.parse(this.LS.getItem(this.keys.weightSpecs)))==null)throw new Error("In local storage, the weight specs of model '"+this.modelPath+"' are missing.");if(e.weightSpecs=a,(o=this.LS.getItem(this.keys.modelMetadata))!=null&&(i=JSON.parse(o),e.format=i.format,e.generatedBy=i.generatedBy,e.convertedBy=i.convertedBy,e.userDefinedMetadata=i.userDefinedMetadata),(s=this.LS.getItem(this.keys.weightData))==null)throw new Error("In local storage, the binary weight values of model '"+this.modelPath+"' are missing.");return e.weightData=function(c){if(Cu){var d=at.from(c,"base64");return d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength)}for(var f=atob(c),m=new Uint8Array(f.length),g=0;g<f.length;++g)m.set([f.charCodeAt(g)],g);return m.buffer}(s),[2,e]})})},r.URL_SCHEME="localstorage://",r}(),Bl=function(r){return ee().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(Co.URL_SCHEME)?(n=r.slice(Co.URL_SCHEME.length),new Co(n)):null;var n};Zn.registerSaveRouter(Bl),Zn.registerLoadRouter(Bl);var If=function(){function r(){D(ee().getBool("IS_BROWSER"),function(){return"Current environment is not a web browser"}),D(typeof window=="undefined"||window.localStorage!==void 0,function(){return"Current browser does not appear to support localStorage"}),this.LS=window.localStorage}return r.prototype.listModels=function(){return ve(this,void 0,void 0,function(){var n,e,t,a,o,i;return ye(this,function(s){for(n={},e=_o+Kr,t=Kr+Pl,a=0;a<this.LS.length;++a)(o=this.LS.key(a)).startsWith(e)&&o.endsWith(t)&&(i=Of(o),n[i]=JSON.parse(this.LS.getItem(o)));return[2,n]})})},r.prototype.removeModel=function(n){return ve(this,void 0,void 0,function(){var e,t;return ye(this,function(a){var o;if(n=(o=n).startsWith(Co.URL_SCHEME)?o.slice(Co.URL_SCHEME.length):o,e=Ll(n),this.LS.getItem(e.info)==null)throw new Error("Cannot find model at path '"+n+"'");return t=JSON.parse(this.LS.getItem(e.info)),this.LS.removeItem(e.info),this.LS.removeItem(e.topology),this.LS.removeItem(e.weightSpecs),this.LS.removeItem(e.weightData),[2,t]})})},r}();if(ee().getBool("IS_BROWSER"))try{ma.registerManager(Co.URL_SCHEME,new If)}catch(r){}var Mf="model",Ff=".json",Pf=".weights.bin";function jl(r){return new Promise(function(n){return setTimeout(n)}).then(r)}var Tu=function(){function r(n){if(!ee().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");n.startsWith(r.URL_SCHEME)&&(n=n.slice(r.URL_SCHEME.length)),n!=null&&n.length!==0||(n=Mf),this.modelTopologyFileName=n+Ff,this.weightDataFileName=n+Pf}return r.prototype.save=function(n){return ve(this,void 0,void 0,function(){var e,t,a,o,i,s;return ye(this,function(u){switch(u.label){case 0:if(typeof document=="undefined")throw new Error("Browser downloads are not supported in this environment since `document` is not present");if(e=window.URL.createObjectURL(new Blob([n.weightData],{type:"application/octet-stream"})),!(n.modelTopology instanceof ArrayBuffer))return[3,1];throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");case 1:return t=[{paths:["./"+this.weightDataFileName],weights:n.weightSpecs}],a={modelTopology:n.modelTopology,format:n.format,generatedBy:n.generatedBy,convertedBy:n.convertedBy,weightsManifest:t},o=window.URL.createObjectURL(new Blob([JSON.stringify(a)],{type:"application/json"})),(i=this.jsonAnchor==null?document.createElement("a"):this.jsonAnchor).download=this.modelTopologyFileName,i.href=o,[4,jl(function(){return i.dispatchEvent(new MouseEvent("click"))})];case 2:return u.sent(),n.weightData==null?[3,4]:((s=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor).download=this.weightDataFileName,s.href=e,[4,jl(function(){return s.dispatchEvent(new MouseEvent("click"))})]);case 3:u.sent(),u.label=4;case 4:return[2,{modelArtifactsInfo:pi(n)}]}})})},r.URL_SCHEME="downloads://",r}(),Lf=function(){function r(n){if(n==null||n.length<1)throw new Error("When calling browserFiles, at least 1 file is required, but received "+n);this.files=n}return r.prototype.load=function(){return ve(this,void 0,void 0,function(){var n,e,t=this;return ye(this,function(a){return n=this.files[0],e=this.files.slice(1),[2,new Promise(function(o,i){var s=new FileReader;s.onload=function(u){var c=JSON.parse(u.target.result),d=c.modelTopology;if(d!=null){e.length===0&&o({modelTopology:d});var f=c.weightsManifest;if(f!=null){var m;try{m=t.checkManifestAndWeightFiles(f,e)}catch(w){return void i(w)}var g=[],x=[],E=[];f.forEach(function(w){w.paths.forEach(function(C){x.push(C),E.push(null)}),g.push.apply(g,w.weights)}),f.forEach(function(w){w.paths.forEach(function(C){var N=new FileReader;N.onload=function(S){var I=S.target.result,M=x.indexOf(C);E[M]=I,E.indexOf(null)===-1&&o({modelTopology:d,weightSpecs:g,weightData:Ru(E),format:c.format,generatedBy:c.generatedBy,convertedBy:c.convertedBy,userDefinedMetadata:c.userDefinedMetadata})},N.onerror=function(S){return i("Failed to weights data from file of path '"+C+"'.")},N.readAsArrayBuffer(m[C])})})}else i(new Error("weightManifest field is missing from file "+n.name))}else i(new Error("modelTopology field is missing from file "+n.name))},s.onerror=function(u){return i("Failed to read model topology and weights manifest JSON from file '"+n.name+"'. BrowserFiles supports loading Keras-style tf.Model artifacts only.")},s.readAsText(n)})]})})},r.prototype.checkManifestAndWeightFiles=function(n,e){for(var t=[],a=e.map(function(u){return Ol(u.name)}),o={},i=0,s=n;i<s.length;i++)s[i].paths.forEach(function(u){var c=Ol(u);if(t.indexOf(c)!==-1)throw new Error("Duplicate file basename found in weights manifest: '"+c+"'");if(t.push(c),a.indexOf(c)===-1)throw new Error("Weight file with basename '"+c+"' is not provided.");o[u]=e[a.indexOf(c)]});if(t.length!==e.length)throw new Error("Mismatch in the number of files in weights manifest ("+t.length+") and the number of weight files provided ("+e.length+").");return o},r}();function Ul(r,n,e,t){!function(o){D(o!=null&&Array.isArray(o)&&o.length>0,function(){return"promises must be a none empty array"})}(r),function(o,i){D(o>=0&&o<=1,function(){return"Progress fraction must be in range [0, 1], but got startFraction "+o}),D(i>=0&&i<=1,function(){return"Progress fraction must be in range [0, 1], but got endFraction "+i}),D(i>=o,function(){return"startFraction must be no more than endFraction, but got startFraction "+o+" and endFraction "+i})}(e=e==null?0:e,t=t==null?1:t);var a=0;return Promise.all(r.map(function(o){return o.then(function(i){var s=e+ ++a/r.length*(t-e);return n(s),i}),o}))}function Wl(r,n){return ve(this,void 0,void 0,function(){var e,t,a,o,i,s,u,c,d;return ye(this,function(f){switch(f.label){case 0:return n==null&&(n={}),e=n.fetchFunc==null?ee().platform.fetch:n.fetchFunc,t=r.map(function(m){return e(m,n.requestInit,{isBinary:!0})}),a=0,o=.5,n.onProgress!=null?[3,2]:[4,Promise.all(t)];case 1:return i=f.sent(),[3,4];case 2:return[4,Ul(t,n.onProgress,a,o)];case 3:i=f.sent(),f.label=4;case 4:return s=i.map(function(m){return m.arrayBuffer()}),u=.5,c=1,n.onProgress!=null?[3,6]:[4,Promise.all(s)];case 5:return d=f.sent(),[3,8];case 6:return[4,Ul(s,n.onProgress,u,c)];case 7:d=f.sent(),f.label=8;case 8:return[2,d]}})})}function zl(r){var n=this;return function(e,t,a){return t===void 0&&(t=""),ve(n,void 0,void 0,function(){var o,i,s,u,c,d,f,m,g,x;return ye(this,function(E){switch(E.label){case 0:if(o=e.map(function(){return!1}),i={},s=a!=null?a.map(function(){return!1}):[],u=[],e.forEach(function(w,C){var N=0;w.weights.forEach(function(S){var I="quantization"in S?S.quantization.dtype:S.dtype,M=_u[I]*ae(S.shape),j=function(){o[C]=!0,i[C]==null&&(i[C]=[]),i[C].push({manifestEntry:S,groupOffset:N,sizeBytes:M})};a!=null?a.forEach(function(G,z){G===S.name&&(j(),s[z]=!0)}):j(),u.push(S.name),N+=M})}),!s.every(function(w){return w}))throw c=a.filter(function(w,C){return!s[C]}),new Error("Could not find weights in manifest with names: "+c.join(", ")+`.
|
|
Manifest JSON has weights with names: `+u.join(", ")+".");return d=o.reduce(function(w,C,N){return C&&w.push(N),w},[]),f=[],d.forEach(function(w){e[w].paths.forEach(function(C){var N=t+(t.endsWith("/")?"":"/")+C;f.push(N)})}),[4,r(f)];case 1:return m=E.sent(),g={},x=0,d.forEach(function(w){for(var C=e[w].paths.length,N=0,S=0;S<C;S++)N+=m[x+S].byteLength;for(var I=new ArrayBuffer(N),M=new Uint8Array(I),j=0,G=0;G<C;G++){var z=new Uint8Array(m[x+G]);M.set(z,j),j+=z.byteLength}i[w].forEach(function(W){var V=kl(I.slice(W.groupOffset,W.groupOffset+W.sizeBytes),[W.manifestEntry]);for(var Z in V)g[Z]=V[Z]}),x+=C}),[2,g]}})})}}Zn.registerSaveRouter(function(r){return ee().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(Tu.URL_SCHEME)?function(n){return n===void 0&&(n="model"),new Tu(n)}(r.slice(Tu.URL_SCHEME.length)):null});var Vl=function(){function r(n,e){if(this.DEFAULT_METHOD="POST",e==null&&(e={}),this.weightPathPrefix=e.weightPathPrefix,this.onProgress=e.onProgress,e.fetchFunc!=null?(D(typeof e.fetchFunc=="function",function(){return"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"}),this.fetch=e.fetchFunc):this.fetch=ee().platform.fetch,D(n!=null&&n.length>0,function(){return"URL path for http must not be null, undefined or empty."}),Array.isArray(n)&&D(n.length===2,function(){return"URL paths for http must have a length of 2, (actual length is "+n.length+")."}),this.path=n,e.requestInit!=null&&e.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=e.requestInit||{}}return r.prototype.save=function(n){return ve(this,void 0,void 0,function(){var e,t,a,o;return ye(this,function(i){switch(i.label){case 0:if(n.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");return(e=Object.assign({method:this.DEFAULT_METHOD},this.requestInit)).body=new FormData,t=[{paths:["./model.weights.bin"],weights:n.weightSpecs}],a={modelTopology:n.modelTopology,format:n.format,generatedBy:n.generatedBy,convertedBy:n.convertedBy,userDefinedMetadata:n.userDefinedMetadata,weightsManifest:t},e.body.append("model.json",new Blob([JSON.stringify(a)],{type:"application/json"}),"model.json"),n.weightData!=null&&e.body.append("model.weights.bin",new Blob([n.weightData],{type:"application/octet-stream"}),"model.weights.bin"),[4,this.fetch(this.path,e)];case 1:if((o=i.sent()).ok)return[2,{modelArtifactsInfo:pi(n),responses:[o]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+o.status+".")}})})},r.prototype.load=function(){return ve(this,void 0,void 0,function(){var n,e,t,a,o,i,s,u,c,d,f,m;return ye(this,function(g){switch(g.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(!(n=g.sent()).ok)throw new Error("Request to "+this.path+" failed with status code "+n.status+". Please verify this URL points to the model JSON of the model to load.");g.label=2;case 2:return g.trys.push([2,4,,5]),[4,n.json()];case 3:return e=g.sent(),[3,5];case 4:throw g.sent(),t="Failed to parse model JSON of response from "+this.path+".",this.path.endsWith(".pb")?t+=" 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.":t+=" Please make sure the server is serving valid JSON for this request.",new Error(t);case 5:if(a=e.modelTopology,o=e.weightsManifest,i=e.generatedBy,s=e.convertedBy,u=e.format,c=e.userDefinedMetadata,a==null&&o==null)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return o==null?[3,7]:[4,this.loadWeights(o)];case 6:m=g.sent(),d=m[0],f=m[1],g.label=7;case 7:return[2,{modelTopology:a,weightSpecs:d,weightData:f,userDefinedMetadata:c,generatedBy:i,convertedBy:s,format:u}]}})})},r.prototype.loadWeights=function(n){return ve(this,void 0,void 0,function(){var e,t,a,o,i,s,u,c,d,f,m;return ye(this,function(g){switch(g.label){case 0:for(e=Array.isArray(this.path)?this.path[1]:this.path,t=function(x){var E=x.lastIndexOf("/"),w=x.lastIndexOf("?"),C=x.substring(0,E),N=w>E?x.substring(w):"";return[C+"/",N]}(e),a=t[0],o=t[1],i=this.weightPathPrefix||a,s=[],u=0,c=n;u<c.length;u++)d=c[u],s.push.apply(s,d.weights);return f=[],n.forEach(function(x){x.paths.forEach(function(E){f.push(i+E+o)})}),[4,Wl(f,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress})];case 1:return m=g.sent(),[2,[s,Ru(m)]]}})})},r.URL_SCHEME_REGEX=/^https?:\/\//,r}();function Du(r){return r.match(Vl.URL_SCHEME_REGEX)!=null}var Gl=function(r,n){return typeof fetch=="undefined"?null:(Array.isArray(r)?r.every(function(e){return Du(e)}):Du(r))?Nu(r,{onProgress:n}):null};function Nu(r,n){return new Vl(r,n)}Zn.registerSaveRouter(Gl),Zn.registerLoadRouter(Gl);var ku=function(){function r(n){this.modelArtifacts=n}return r.prototype.load=function(){return ve(this,void 0,void 0,function(){return ye(this,function(n){return[2,this.modelArtifacts]})})},r}(),Bf=function(){function r(n){this.saveHandler=n}return r.prototype.save=function(n){return ve(this,void 0,void 0,function(){return ye(this,function(e){return[2,this.saveHandler(n)]})})},r}(),jf=Object.freeze({browserFiles:function(r){return new Lf(r)},browserHTTPRequest:function(r,n){return Nu(r,n)},concatenateArrayBuffers:Ru,decodeWeights:kl,encodeWeights:function(r,n){return ve(this,void 0,void 0,function(){var e,t,a,o,i,s=this;return ye(this,function(u){switch(u.label){case 0:for(e=[],t=[],a=Array.isArray(r)?r.map(function(c){return c.name}):Object.keys(r),o=function(c){var d=a[c],f=Array.isArray(r)?r[c].tensor:r[d];if(f.dtype!=="float32"&&f.dtype!=="int32"&&f.dtype!=="bool"&&f.dtype!=="string")throw new Error("Unsupported dtype in weight '"+d+"': "+f.dtype);var m={name:d,shape:f.shape,dtype:f.dtype};if(f.dtype==="string"){var g=new Promise(function(x){return ve(s,void 0,void 0,function(){var E,w,C,N,S,I,M;return ye(this,function(j){switch(j.label){case 0:return[4,f.bytes()];case 1:for(E=j.sent(),w=E.reduce(function(G,z){return G+z.length},0)+us*E.length,C=new Uint8Array(w),N=0,S=0;S<E.length;S++)I=E[S],M=new Uint8Array(new Uint32Array([I.length]).buffer),C.set(M,N),N+=us,C.set(I,N),N+=I.length;return x(C),[2]}})})});t.push(g)}else t.push(f.data());n!=null&&(m.group=n),e.push(m)},i=0;i<a.length;++i)o(i);return[4,Promise.all(t)];case 1:return[2,{data:Af(u.sent()),specs:e}]}})})},fromMemory:function(r,n,e,t){return arguments.length===1?r.modelTopology!=null||r.weightSpecs!=null?new ku(r):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new ku({modelTopology:r})):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new ku({modelTopology:r,weightSpecs:n,weightData:e,trainingConfig:t}))},getLoadHandlers:function(r,n){return Zn.getLoadHandlers(r,n)},getModelArtifactsInfoForJSON:pi,getSaveHandlers:function(r){return Zn.getSaveHandlers(r)},http:Nu,isHTTPScheme:Du,loadWeights:function(r,n,e,t){return n===void 0&&(n=""),ve(this,void 0,void 0,function(){return ye(this,function(a){return[2,zl(function(o){return Wl(o,{requestInit:t})})(r,n,e)]})})},registerLoadRouter:function(r){return Zn.registerLoadRouter(r)},registerSaveRouter:function(r){return Zn.registerSaveRouter(r)},weightsLoaderFactory:zl,withSaveHandler:function(r){return new Bf(r)},copyModel:function(r,n){return ve(this,void 0,void 0,function(){return ye(this,function(e){return[2,Il(r,n,!1)]})})},listModels:function(){return ve(this,void 0,void 0,function(){var r,n,e,t,a,o,i;return ye(this,function(s){switch(s.label){case 0:r=ma.getSchemes(),n={},e=0,t=r,s.label=1;case 1:return e<t.length?(a=t[e],[4,ma.getManager(a).listModels()]):[3,4];case 2:for(i in o=s.sent())n[a+wo+i]=o[i];s.label=3;case 3:return e++,[3,1];case 4:return[2,n]}})})},moveModel:function(r,n){return ve(this,void 0,void 0,function(){return ye(this,function(e){return[2,Il(r,n,!0)]})})},removeModel:function(r){return ve(this,void 0,void 0,function(){var n;return ye(this,function(e){return n=cs(r),[2,ma.getManager(n.scheme).removeModel(n.path)]})})}}),Ro,Uf=K({confusionMatrix_:function(r,n,e){var t=F(r,"labels","confusionMatrix"),a=F(n,"predictions","confusionMatrix");D(e==null||e>0&&Number.isInteger(e),function(){return"If provided, numClasses must be a positive integer, but got "+e}),D(t.rank===1,function(){return"Expected the rank of labels to be 1, but got "+t.rank}),D(a.rank===1,function(){return"Expected the rank of predictions to be 1, but got "+a.rank}),D(t.shape[0]===a.shape[0],function(){return"Mismatch in the number of examples: "+t.shape[0]+" vs. "+a.shape[0]+". Labels and predictions should have the same number of elements."}),D(e>0&&Number.isInteger(e),function(){return"numClasses is required to be a positive integer, but got "+e});var o=$o(t.asType("int32"),e),i=$o(a.asType("int32"),e);return o.transpose().matMul(i).asType("int32")}}),qf=Object.freeze({confusionMatrix:Uf}),Wf=K({fromPixels_:function(r,n){if(n===void 0&&(n=3),n>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(r==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var e=!1,t=!1,a=!1,o=!1,i=!1;if(r.data instanceof Uint8Array)e=!0;else if(typeof ImageData!="undefined"&&r instanceof ImageData)t=!0;else if(typeof HTMLVideoElement!="undefined"&&r instanceof HTMLVideoElement)a=!0;else if(typeof HTMLImageElement!="undefined"&&r instanceof HTMLImageElement)o=!0;else{if(r.getContext==null)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 "+r.constructor.name);i=!0}if(a&&(a&&r.readyState<2))throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.");if(Ve("FromPixels",X.backendName)!=null)return X.runKernel("FromPixels",{pixels:r},{numChannels:n});var s,u,c=a?[r.videoWidth,r.videoHeight]:[r.width,r.height],d=c[0],f=c[1];if(i?s=r.getContext("2d").getImageData(0,0,d,f).data:t||e?s=r.data:(o||a)&&(Ro==null&&(Ro=document.createElement("canvas").getContext("2d")),Ro.canvas.width=d,Ro.canvas.height=f,Ro.drawImage(r,0,0,d,f),s=Ro.getImageData(0,0,d,f).data),n===4)u=new Int32Array(s);else{var m=d*f;u=new Int32Array(m*n);for(var g=0;g<m;g++)for(var x=0;x<n;++x)u[g*n+x]=s[4*g+x]}return Ko(u,[f,d,n],"int32")}}),zf=Object.freeze({toPixels:function(r,n){return ve(this,void 0,void 0,function(){var e,t,a,o,i,s,u,c,d,f,m,g,x,E,w,C,N,S,I,M,j,G,z;return ye(this,function(W){switch(W.label){case 0:if(e=F(r,"img","toPixels"),r instanceof fn||(e=e.toInt()),e.rank!==2&&e.rank!==3)throw new Error("toPixels only supports rank 2 or 3 tensors, got rank "+e.rank+".");if(t=e.shape.slice(0,2),a=t[0],o=t[1],(i=e.rank===2?1:e.shape[2])>4||i===2)throw new Error("toPixels only supports depth of size 1, 3 or 4 but got "+i);return[4,e.data()];case 1:return s=W.sent(),u=e.min(),c=e.max(),[4,Promise.all([u.data(),c.data()])];case 2:if(d=W.sent(),f=d[0],m=d[1],g=f[0],x=m[0],u.dispose(),c.dispose(),e.dtype==="float32"){if(g<0||x>1)throw new Error("Tensor values for a float32 Tensor must be in the range [0 - 1] but got range ["+g+" - "+x+"].")}else{if(e.dtype!=="int32")throw new Error("Unsupported type for toPixels: "+e.dtype+". Please use float32 or int32 tensors.");if(g<0||x>255)throw new Error("Tensor values for a int32 Tensor must be in the range [0 - 255] but got range ["+g+" - "+x+"].")}for(E=e.dtype==="float32"?255:1,w=new Uint8ClampedArray(o*a*4),C=0;C<a*o;++C)N=void 0,S=void 0,I=void 0,M=void 0,i===1?(N=s[C]*E,S=s[C]*E,I=s[C]*E,M=255):i===3?(N=s[3*C]*E,S=s[3*C+1]*E,I=s[3*C+2]*E,M=255):i===4&&(N=s[4*C]*E,S=s[4*C+1]*E,I=s[4*C+2]*E,M=s[4*C+3]*E),w[(j=4*C)+0]=Math.round(N),w[j+1]=Math.round(S),w[j+2]=Math.round(I),w[j+3]=Math.round(M);return n!=null&&(n.width=o,n.height=a,G=n.getContext("2d"),z=new ImageData(w,o,a),G.putImageData(z,0,0)),e!==r&&e.dispose(),[2,w]}})})},fromPixels:Wf}),Hl=function(){function r(){}return r.prototype.getClassName=function(){return this.constructor.className},r.fromConfig=function(n,e){return new n(e)},r}(),Xl=function(){function r(){this.classNameMap={}}return r.getMap=function(){return r.instance==null&&(r.instance=new r),r.instance},r.register=function(n){r.getMap().classNameMap[n.className]=[n,n.fromConfig]},r}();function ya(r){D(r.className!=null,function(){return"Class being registered does not have the static className property defined."}),D(typeof r.className=="string",function(){return"className is required to be a string, but got type "+typeof r.className}),D(r.className.length>0,function(){return"Class being registered has an empty-string as its className, which is disallowed."}),Xl.register(r)}var Yf=Object.freeze({Serializable:Hl,SerializationMap:Xl,registerClass:ya}),Vf=.001,Kl=.1;function Su(){return X.backend.floatPrecision()===32?Vf:Kl}function Ou(r,n,e){var t=!0;if((Xt(r)||Xt(n))&&(t=!1),Xt(r)&&Xt(n)&&(t=!0),t){var a=r.constructor.name,o=n.constructor.name;if(a!==o)throw new Error("Arrays are of different type. Actual: "+a+". Expected: "+o)}if(Array.isArray(r)&&Array.isArray(n)){var i=ur(r),s=ur(n);if(!Oe(i,s))throw new Error("Arrays have different shapes. Actual: ["+i+"]. Expected: ["+s+"]")}var u=Xt(r)?r:Ae(r),c=Xt(n)?n:Ae(n);if(u.length!==c.length)throw new Error("Arrays have different lengths actual: "+u.length+" vs expected: "+c.length+`.
|
|
Actual: `+u+`.
|
|
Expected: `+c+".");for(var d=0;d<c.length;++d){var f=u[d],m=c[d];if(!e(f,m))throw new Error("Arrays differ: actual["+d+"] = "+f+", expected["+d+"] = "+m+`.
|
|
Actual: `+u+`.
|
|
Expected: `+c+".")}}function Iu(r,n,e){return!isFinite(r)&&!isFinite(n)||!(isNaN(r)||isNaN(n)||Math.abs(r-n)>e)}var $f=Object.freeze({TEST_EPSILON_FLOAT16:Kl,expectArraysClose:function(r,n,e){return e==null&&(e=Su()),Ou(r,n,function(t,a){return Iu(t,a,e)})},testEpsilon:Su,expectPromiseToFail:function(r,n){r().then(function(){return n.fail()},function(){return n()})},expectArraysEqual:function(r,n){var e=typeof n=="string"||typeof n=="number"||typeof n=="boolean"?[n]:n;return wn(r)||wn(r[0])||wn(n)||wn(n[0])?Ou(r,e,function(t,a){return t==a}):Ou(r,n,function(t,a){return Iu(t,a,0)})},expectNumbersClose:function(r,n,e){if(e==null&&(e=Su()),!Iu(r,n,e))throw new Error("Numbers differ: actual === "+r+", expected === "+n)},expectValuesInRange:function(r,n,e){for(var t=0;t<r.length;t++)if(r[t]<n||r[t]>e)throw new Error("Value out of range:"+r[t]+" low: "+n+", high: "+e)},expectArrayBuffersEqual:function(r,n){expect(new Float32Array(r)).toEqual(new Float32Array(n))}}),Jf="1.7.0",Qf=Object.freeze({gpgpu_util:cd,webgl_util:ps,forceHalfFloat:function(){ee().set("WEBGL_FORCE_F16_TEXTURES",!0)},MathBackendWebGL:Lc,setWebGLContext:Bo,GPGPUContext:bc}),Ua=function(r){function n(){return r!==null&&r.apply(this,arguments)||this}return Ke(n,r),n.prototype.minimize=function(e,t,a){t===void 0&&(t=!1);var o=this.computeGradients(e,a),i=o.value,s=o.grads;if(a!=null){var u=a.map(function(c){return{name:c.name,tensor:s[c.name]}});this.applyGradients(u)}else this.applyGradients(s);return Pn(s),t?i:(i.dispose(),null)},Object.defineProperty(n.prototype,"iterations",{get:function(){return this.iterations_==null&&(this.iterations_=0),this.iterations_},enumerable:!0,configurable:!0}),n.prototype.incrementIterations=function(){this.iterations_=this.iterations+1},n.prototype.computeGradients=function(e,t){return ei(e,t)},n.prototype.dispose=function(){this.iterations_!=null&&Pn(this.iterations_)},n.prototype.saveIterations=function(){return ve(this,void 0,void 0,function(){return ye(this,function(e){return this.iterations_==null&&(this.iterations_=0),[2,{name:"iter",tensor:We(this.iterations_,"int32")}]})})},n.prototype.getWeights=function(){return ve(this,void 0,void 0,function(){return ye(this,function(e){throw new Error("getWeights() is not implemented for this optimizer yet.")})})},n.prototype.setWeights=function(e){return ve(this,void 0,void 0,function(){return ye(this,function(t){throw new Error("setWeights() is not implemented for this optimizer class "+this.getClassName())})})},n.prototype.extractIterations=function(e){return ve(this,void 0,void 0,function(){var t;return ye(this,function(a){switch(a.label){case 0:return t=this,[4,e[0].tensor.data()];case 1:return t.iterations_=a.sent()[0],[2,e.slice(1)]}})})},n}(Hl);Object.defineProperty(Ua,Symbol.hasInstance,{value:function(r){return r.minimize!=null&&r.computeGradients!=null&&r.applyGradients!=null}});var ql=function(r){function n(e,t,a){a===void 0&&(a=null);var o=r.call(this)||this;return o.learningRate=e,o.rho=t,o.epsilon=a,o.accumulatedGrads=[],o.accumulatedUpdates=[],a==null&&(o.epsilon=X.backend.epsilon()),o}return Ke(n,r),n.prototype.applyGradients=function(e){var t=this;(Array.isArray(e)?e.map(function(a){return a.name}):Object.keys(e)).forEach(function(a,o){var i=X.registeredVariables[a];t.accumulatedGrads[o]==null&&(t.accumulatedGrads[o]={originalName:a+"/accum_grad",variable:en(function(){return gt(i).variable(!1)})}),t.accumulatedUpdates[o]==null&&(t.accumulatedUpdates[o]={originalName:a+"/accum_var",variable:en(function(){return gt(i).variable(!1)})});var s=Array.isArray(e)?e[o].tensor:e[a];if(s!=null){var u=t.accumulatedGrads[o].variable,c=t.accumulatedUpdates[o].variable;en(function(){var d=u.mul(t.rho).add(s.square().mul(1-t.rho)),f=c.add(t.epsilon).sqrt().div(u.add(t.epsilon).sqrt()).mul(s),m=c.mul(t.rho).add(f.square().mul(1-t.rho));u.assign(d),c.assign(m);var g=f.mul(-t.learningRate).add(i);i.assign(g)})}}),this.incrementIterations()},n.prototype.dispose=function(){this.accumulatedUpdates!=null&&(Pn(this.accumulatedGrads.map(function(e){return e.variable})),Pn(this.accumulatedUpdates.map(function(e){return e.variable})))},n.prototype.getWeights=function(){return ve(this,void 0,void 0,function(){var e;return ye(this,function(t){switch(t.label){case 0:return e=this.accumulatedGrads.concat(this.accumulatedUpdates),[4,this.saveIterations()];case 1:return[2,[t.sent()].concat(e.map(function(a){return{name:a.originalName,tensor:a.variable}}))]}})})},n.prototype.setWeights=function(e){return ve(this,void 0,void 0,function(){var t;return ye(this,function(a){switch(a.label){case 0:return[4,this.extractIterations(e)];case 1:return e=a.sent(),t=e.length/2,this.accumulatedGrads=e.slice(0,t).map(function(o){return{originalName:o.name,variable:o.tensor.variable(!1)}}),this.accumulatedUpdates=e.slice(t,2*t).map(function(o){return{originalName:o.name,variable:o.tensor.variable(!1)}}),[2]}})})},n.prototype.getConfig=function(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}},n.fromConfig=function(e,t){return new e(t.learningRate,t.rho,t.epsilon)},n.className="Adadelta",n}(Ua);ya(ql);var Yl=function(r){function n(e,t){t===void 0&&(t=.1);var a=r.call(this)||this;return a.learningRate=e,a.initialAccumulatorValue=t,a.accumulatedGrads=[],a}return Ke(n,r),n.prototype.applyGradients=function(e){var t=this;(Array.isArray(e)?e.map(function(a){return a.name}):Object.keys(e)).forEach(function(a,o){var i=X.registeredVariables[a];t.accumulatedGrads[o]==null&&(t.accumulatedGrads[o]={originalName:a+"/accumulator",variable:en(function(){return qo(i.shape,t.initialAccumulatorValue).variable(!1)})});var s=Array.isArray(e)?e[o].tensor:e[a];if(s!=null){var u=t.accumulatedGrads[o].variable;en(function(){var c=u.add(s.square());u.assign(c);var d=s.div(c.add(X.backend.epsilon()).sqrt()).mul(-t.learningRate).add(i);i.assign(d)})}}),this.incrementIterations()},n.prototype.dispose=function(){this.accumulatedGrads!=null&&Pn(this.accumulatedGrads.map(function(e){return e.variable}))},n.prototype.getWeights=function(){return ve(this,void 0,void 0,function(){return ye(this,function(e){switch(e.label){case 0:return[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(this.accumulatedGrads.map(function(t){return{name:t.originalName,tensor:t.variable}}))]}})})},n.prototype.setWeights=function(e){return ve(this,void 0,void 0,function(){return ye(this,function(t){switch(t.label){case 0:return[4,this.extractIterations(e)];case 1:return e=t.sent(),this.accumulatedGrads=e.map(function(a){return{originalName:a.name,variable:a.tensor.variable(!1)}}),[2]}})})},n.prototype.getConfig=function(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}},n.fromConfig=function(e,t){return new e(t.learningRate,t.initialAccumulatorValue)},n.className="Adagrad",n}(Ua);ya(Yl);var $l=function(r){function n(e,t,a,o){o===void 0&&(o=null);var i=r.call(this)||this;return i.learningRate=e,i.beta1=t,i.beta2=a,i.epsilon=o,i.accumulatedFirstMoment=[],i.accumulatedSecondMoment=[],en(function(){i.accBeta1=We(t).variable(),i.accBeta2=We(a).variable()}),o==null&&(i.epsilon=X.backend.epsilon()),i}return Ke(n,r),n.prototype.applyGradients=function(e){var t=this,a=Array.isArray(e)?e.map(function(o){return o.name}):Object.keys(e);en(function(){var o=va(1,t.accBeta1),i=va(1,t.accBeta2);a.forEach(function(s,u){var c=X.registeredVariables[s];t.accumulatedFirstMoment[u]==null&&(t.accumulatedFirstMoment[u]={originalName:s+"/m",variable:en(function(){return gt(c).variable(!1)})}),t.accumulatedSecondMoment[u]==null&&(t.accumulatedSecondMoment[u]={originalName:s+"/v",variable:en(function(){return gt(c).variable(!1)})});var d=Array.isArray(e)?e[u].tensor:e[s];if(d!=null){var f=t.accumulatedFirstMoment[u].variable,m=t.accumulatedSecondMoment[u].variable,g=f.mul(t.beta1).add(d.mul(1-t.beta1)),x=m.mul(t.beta2).add(d.square().mul(1-t.beta2)),E=g.div(o),w=x.div(i);f.assign(g),m.assign(x);var C=E.div(w.sqrt().add(t.epsilon)).mul(-t.learningRate).add(c);c.assign(C)}}),t.accBeta1.assign(t.accBeta1.mul(t.beta1)),t.accBeta2.assign(t.accBeta2.mul(t.beta2))}),this.incrementIterations()},n.prototype.dispose=function(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&Pn(this.accumulatedFirstMoment.map(function(e){return e.variable})),this.accumulatedSecondMoment!=null&&Pn(this.accumulatedSecondMoment.map(function(e){return e.variable}))},n.prototype.getWeights=function(){return ve(this,void 0,void 0,function(){var e;return ye(this,function(t){switch(t.label){case 0:return e=this.accumulatedFirstMoment.concat(this.accumulatedSecondMoment),[4,this.saveIterations()];case 1:return[2,[t.sent()].concat(e.map(function(a){return{name:a.originalName,tensor:a.variable}}))]}})})},n.prototype.setWeights=function(e){return ve(this,void 0,void 0,function(){var t,a=this;return ye(this,function(o){switch(o.label){case 0:return[4,this.extractIterations(e)];case 1:return e=o.sent(),en(function(){a.accBeta1.assign(as(a.beta1,a.iterations_+1)),a.accBeta2.assign(as(a.beta2,a.iterations_+1))}),t=e.length/2,this.accumulatedFirstMoment=e.slice(0,t).map(function(i){return{originalName:i.name,variable:i.tensor.variable(!1)}}),this.accumulatedSecondMoment=e.slice(t,2*t).map(function(i){return{originalName:i.name,variable:i.tensor.variable(!1)}}),[2]}})})},n.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}},n.fromConfig=function(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)},n.className="Adam",n}(Ua);ya($l);var Jl=function(r){function n(e,t,a,o,i){o===void 0&&(o=null),i===void 0&&(i=0);var s=r.call(this)||this;return s.learningRate=e,s.beta1=t,s.beta2=a,s.epsilon=o,s.decay=i,s.accumulatedFirstMoment=[],s.accumulatedWeightedInfNorm=[],en(function(){s.iteration=We(0).variable(),s.accBeta1=We(t).variable()}),o==null&&(s.epsilon=X.backend.epsilon()),s}return Ke(n,r),n.prototype.applyGradients=function(e){var t=this,a=Array.isArray(e)?e.map(function(o){return o.name}):Object.keys(e);en(function(){var o=va(1,t.accBeta1),i=rs(-t.learningRate,t.iteration.mul(t.decay).add(1));a.forEach(function(s,u){var c=X.registeredVariables[s];t.accumulatedFirstMoment[u]==null&&(t.accumulatedFirstMoment[u]={originalName:s+"/m",variable:gt(c).variable(!1)}),t.accumulatedWeightedInfNorm[u]==null&&(t.accumulatedWeightedInfNorm[u]={originalName:s+"/v",variable:gt(c).variable(!1)});var d=Array.isArray(e)?e[u].tensor:e[s];if(d!=null){var f=t.accumulatedFirstMoment[u].variable,m=t.accumulatedWeightedInfNorm[u].variable,g=f.mul(t.beta1).add(d.mul(1-t.beta1)),x=m.mul(t.beta2),E=d.abs(),w=x.maximum(E);f.assign(g),m.assign(w);var C=i.div(o).mul(g.div(w.add(t.epsilon))).add(c);c.assign(C)}}),t.iteration.assign(t.iteration.add(1)),t.accBeta1.assign(t.accBeta1.mul(t.beta1))}),this.incrementIterations()},n.prototype.dispose=function(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&Pn(this.accumulatedFirstMoment.map(function(e){return e.variable})),this.accumulatedWeightedInfNorm!=null&&Pn(this.accumulatedWeightedInfNorm.map(function(e){return e.variable}))},n.prototype.getWeights=function(){return ve(this,void 0,void 0,function(){return ye(this,function(e){throw new Error("getWeights() is not implemented for Adamax yet.")})})},n.prototype.setWeights=function(e){return ve(this,void 0,void 0,function(){return ye(this,function(t){throw new Error("setWeights() is not implemented for Adamax yet.")})})},n.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}},n.fromConfig=function(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay)},n.className="Adamax",n}(Ua);ya(Jl);var Mu=function(r){function n(e){var t=r.call(this)||this;return t.learningRate=e,t.setLearningRate(e),t}return Ke(n,r),n.prototype.applyGradients=function(e){var t=this;(Array.isArray(e)?e.map(function(a){return a.name}):Object.keys(e)).forEach(function(a,o){var i=Array.isArray(e)?e[o].tensor:e[a];if(i!=null){var s=X.registeredVariables[a];en(function(){var u=t.c.mul(i).add(s);s.assign(u)})}}),this.incrementIterations()},n.prototype.setLearningRate=function(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=vs(We(-e))},n.prototype.dispose=function(){this.c.dispose()},n.prototype.getWeights=function(){return ve(this,void 0,void 0,function(){return ye(this,function(e){switch(e.label){case 0:return[4,this.saveIterations()];case 1:return[2,[e.sent()]]}})})},n.prototype.setWeights=function(e){return ve(this,void 0,void 0,function(){return ye(this,function(t){switch(t.label){case 0:return[4,this.extractIterations(e)];case 1:if((e=t.sent()).length!==0)throw new Error("SGD optimizer does not have settable weights.");return[2]}})})},n.prototype.getConfig=function(){return{learningRate:this.learningRate}},n.fromConfig=function(e,t){return new e(t.learningRate)},n.className="SGD",n}(Ua);ya(Mu);var Ql=function(r){function n(e,t,a){a===void 0&&(a=!1);var o=r.call(this,e)||this;return o.learningRate=e,o.momentum=t,o.useNesterov=a,o.accumulations=[],o.m=We(o.momentum),o}return Ke(n,r),n.prototype.applyGradients=function(e){var t=this;(Array.isArray(e)?e.map(function(a){return a.name}):Object.keys(e)).forEach(function(a,o){var i=X.registeredVariables[a];t.accumulations[o]==null&&(t.accumulations[o]={originalName:a+"/momentum",variable:en(function(){return gt(i).variable(!1)})});var s=t.accumulations[o].variable,u=Array.isArray(e)?e[o].tensor:e[a];u!=null&&en(function(){var c,d=t.m.mul(s).add(u);c=t.useNesterov?t.c.mul(u.add(d.mul(t.m))).add(i):t.c.mul(d).add(i),s.assign(d),i.assign(c)})}),this.incrementIterations()},n.prototype.dispose=function(){this.m.dispose(),this.accumulations!=null&&Pn(this.accumulations.map(function(e){return e.variable}))},n.prototype.setMomentum=function(e){this.momentum=e},n.prototype.getWeights=function(){return ve(this,void 0,void 0,function(){return ye(this,function(e){switch(e.label){case 0:return[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(this.accumulations.map(function(t){return{name:t.originalName,tensor:t.variable}}))]}})})},n.prototype.setWeights=function(e){return ve(this,void 0,void 0,function(){return ye(this,function(t){switch(t.label){case 0:return[4,this.extractIterations(e)];case 1:return e=t.sent(),this.accumulations=e.map(function(a){return{originalName:a.name,variable:a.tensor.variable(!1)}}),[2]}})})},n.prototype.getConfig=function(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}},n.fromConfig=function(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)},n.className="Momentum",n}(Mu);ya(Ql);var Zl=function(r){function n(e,t,a,o,i){t===void 0&&(t=.9),a===void 0&&(a=0),o===void 0&&(o=null),i===void 0&&(i=!1);var s=r.call(this)||this;if(s.learningRate=e,s.decay=t,s.momentum=a,s.epsilon=o,s.accumulatedMeanSquares=[],s.accumulatedMoments=[],s.accumulatedMeanGrads=[],s.centered=i,o==null&&(s.epsilon=X.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.");return s}return Ke(n,r),n.prototype.applyGradients=function(e){var t=this;(Array.isArray(e)?e.map(function(a){return a.name}):Object.keys(e)).forEach(function(a,o){var i=X.registeredVariables[a];t.accumulatedMeanSquares[o]==null&&(t.accumulatedMeanSquares[o]={originalName:a+"/rms",variable:en(function(){return gt(i).variable(!1)})}),t.accumulatedMoments[o]==null&&(t.accumulatedMoments[o]={originalName:a+"/momentum",variable:en(function(){return gt(i).variable(!1)})}),t.accumulatedMeanGrads[o]==null&&t.centered&&(t.accumulatedMeanGrads[o]={originalName:a+"/mg",variable:en(function(){return gt(i).variable(!1)})});var s=Array.isArray(e)?e[o].tensor:e[a];if(s!=null){var u=t.accumulatedMeanSquares[o].variable,c=t.accumulatedMoments[o].variable;en(function(){var d=u.mul(t.decay).add(s.square().mul(1-t.decay));if(t.centered){var f=t.accumulatedMeanGrads[o].variable,m=f.mul(t.decay).add(s.mul(1-t.decay)),g=c.mul(t.momentum).add(s.mul(t.learningRate).div(d.sub(m.square().add(t.epsilon)).sqrt()));u.assign(d),f.assign(m),c.assign(g);var x=i.sub(g);i.assign(x)}else{var E=u.mul(t.decay).add(s.square().mul(1-t.decay));g=c.mul(t.momentum).add(s.mul(t.learningRate).div(E.add(t.epsilon).sqrt())),u.assign(E),c.assign(g),x=i.sub(g),i.assign(x)}})}}),this.incrementIterations()},n.prototype.dispose=function(){this.accumulatedMeanSquares!=null&&Pn(this.accumulatedMeanSquares.map(function(e){return e.variable})),this.accumulatedMeanGrads!=null&&this.centered&&Pn(this.accumulatedMeanGrads.map(function(e){return e.variable})),this.accumulatedMoments!=null&&Pn(this.accumulatedMoments.map(function(e){return e.variable}))},n.prototype.getWeights=function(){return ve(this,void 0,void 0,function(){var e;return ye(this,function(t){switch(t.label){case 0:return e=this.accumulatedMeanSquares.concat(this.accumulatedMoments),this.centered&&e.push.apply(e,this.accumulatedMeanGrads),[4,this.saveIterations()];case 1:return[2,[t.sent()].concat(e.map(function(a){return{name:a.originalName,tensor:a.variable}}))]}})})},n.prototype.setWeights=function(e){return ve(this,void 0,void 0,function(){var t;return ye(this,function(a){switch(a.label){case 0:return[4,this.extractIterations(e)];case 1:return e=a.sent(),t=this.centered?e.length/3:e.length/2,this.accumulatedMeanSquares=e.slice(0,t).map(function(o){return{originalName:o.name,variable:o.tensor.variable(!1)}}),this.accumulatedMoments=e.slice(t,2*t).map(function(o){return{originalName:o.name,variable:o.tensor.variable(!1)}}),this.centered&&(this.accumulatedMeanGrads=e.slice(2*t,3*t).map(function(o){return{originalName:o.name,variable:o.tensor.variable(!1)}})),[2]}})})},n.prototype.getConfig=function(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}},n.fromConfig=function(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)},n.className="RMSProp",n}(Ua);ya(Zl);var Wa=function(){function r(){}return r.sgd=function(n){return new Mu(n)},r.momentum=function(n,e,t){return t===void 0&&(t=!1),new Ql(n,e,t)},r.rmsprop=function(n,e,t,a,o){return e===void 0&&(e=.9),t===void 0&&(t=0),a===void 0&&(a=null),o===void 0&&(o=!1),new Zl(n,e,t,a,o)},r.adam=function(n,e,t,a){return n===void 0&&(n=.001),e===void 0&&(e=.9),t===void 0&&(t=.999),a===void 0&&(a=null),new $l(n,e,t,a)},r.adadelta=function(n,e,t){return n===void 0&&(n=.001),e===void 0&&(e=.95),t===void 0&&(t=null),new ql(n,e,t)},r.adamax=function(n,e,t,a,o){return n===void 0&&(n=.002),e===void 0&&(e=.9),t===void 0&&(t=.999),a===void 0&&(a=null),o===void 0&&(o=0),new Jl(n,e,t,a,o)},r.adagrad=function(n,e){return e===void 0&&(e=.1),new Yl(n,e)},r}(),Zf={sgd:Wa.sgd,momentum:Wa.momentum,adadelta:Wa.adadelta,adagrad:Wa.adagrad,rmsprop:Wa.rmsprop,adamax:Wa.adamax,adam:Wa.adam},Gf=typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:function(r){return r()};function ev(){return new Promise(function(r){return Gf(function(){return r()})})}fn.prototype.squaredDifference=function(r){return Bc(this,r)},oe=xf}).call(this,te("IyRk"),te("Q2Ig"),te("HDXh").Buffer)},gctT:function(rn,ke,te){"use strict";te.r(ke);var Se={};te.r(Se),te.d(Se,"drawContour",function(){return Qe}),te.d(Se,"drawDetections",function(){return X}),te.d(Se,"drawFaceExpressions",function(){return bi}),te.d(Se,"DrawBoxOptions",function(){return Fo}),te.d(Se,"DrawBox",function(){return mi}),te.d(Se,"DrawFaceLandmarksOptions",function(){return Fn}),te.d(Se,"DrawFaceLandmarks",function(){return Za}),te.d(Se,"drawFaceLandmarks",function(){return wi}),te.d(Se,"AnchorPosition",function(){return qn}),te.d(Se,"DrawTextFieldOptions",function(){return wa}),te.d(Se,"DrawTextField",function(){return vi});var ze=te("2qtc"),at=te("kLXV"),mt=te("14J3"),Ke=te("BMrR"),ve=te("jCWc"),ye=te("kPKH"),ne=te("+L6B"),kt=te("2/Rp"),ee=te("miYZ"),ot=te("tsqr"),Mt=te("k1fw"),tt=te("9og8"),Ve=te("tJVT"),st=te("PpiC"),Ct=te("FJo9"),Ft=te("L41K"),xn=te("aHsQ"),Pt=te("sGsY"),dn=te("WmNS"),Pe=te.n(dn),Ge=te("q1tI"),ce=te.n(Ge),Ye=te("Ty5D"),ie=te("9kvl"),D=te("yPBj"),se=te.n(D),Te=te("1vsH"),Ae=te("V0Rq"),ae=te("D1Df"),Oe=te.n(ae),Be=te("T2oS"),Qt=te("W9HT"),k=te("Re/O");function Qe(p,l,h){if(h===void 0&&(h=!1),p.beginPath(),l.slice(1).forEach(function(b,T){var A=b.x,O=b.y,P=l[T];p.moveTo(P.x,P.y),p.lineTo(A,O)}),h){var v=l[l.length-1],y=l[0];if(!v||!y)return;p.moveTo(v.x,v.y),p.lineTo(y.x,y.y)}p.stroke()}var q=te("mrSG"),lt=function(){function p(l,h){if(!En(l)||!En(h))throw new Error("Dimensions.constructor - expected width and height to be valid numbers, instead have "+JSON.stringify({width:l,height:h}));this._width=l,this._height=h}return Object.defineProperty(p.prototype,"width",{get:function(){return this._width},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"height",{get:function(){return this._height},enumerable:!0,configurable:!0}),p.prototype.reverse=function(){return new p(1/this.width,1/this.height)},p}();function je(p,l){return p instanceof k.a&&p.shape.length===l}function St(p){return je(p,1)}function Cn(p){return je(p,2)}function bn(p){return je(p,3)}function On(p){return je(p,4)}function xr(p){return p%1!==0}function tr(p){return p%2===0}function Xt(p,l){l===void 0&&(l=2);var h=Math.pow(10,l);return Math.floor(p*h)/h}function nr(p){return p&&p.width&&p.height}function rr(p,l){var h=p.width,v=p.height,y=l/Math.max(v,h);return new lt(Math.round(h*y),Math.round(v*y))}function wn(p){return p.reduce(function(l,h){return l.add(h)},new et(0,0)).div(new et(p.length,p.length))}function $t(p,l,h){return Array(p).fill(0).map(function(v,y){return l+y*h})}function En(p){return!!p&&p!==Infinity&&p!==-Infinity&&!isNaN(p)||p===0}function ar(p){return En(p)&&0<=p&&p<=1}var et=function(){function p(l,h){this._x=l,this._y=h}return Object.defineProperty(p.prototype,"x",{get:function(){return this._x},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"y",{get:function(){return this._y},enumerable:!0,configurable:!0}),p.prototype.add=function(l){return new p(this.x+l.x,this.y+l.y)},p.prototype.sub=function(l){return new p(this.x-l.x,this.y-l.y)},p.prototype.mul=function(l){return new p(this.x*l.x,this.y*l.y)},p.prototype.div=function(l){return new p(this.x/l.x,this.y/l.y)},p.prototype.abs=function(){return new p(Math.abs(this.x),Math.abs(this.y))},p.prototype.magnitude=function(){return Math.sqrt(Math.pow(this.x,2)+Math.pow(this.y,2))},p.prototype.floor=function(){return new p(Math.floor(this.x),Math.floor(this.y))},p}(),gn=function(){function p(l,h){h===void 0&&(h=!0);var v=l||{},y=[v.left,v.top,v.right,v.bottom].every(En),b=[v.x,v.y,v.width,v.height].every(En);if(!b&&!y)throw new Error("Box.constructor - expected box to be IBoundingBox | IRect, instead have "+JSON.stringify(v));var T=b?[v.x,v.y,v.width,v.height]:[v.left,v.top,v.right-v.left,v.bottom-v.top],A=T[0],O=T[1],P=T[2],B=T[3];p.assertIsValidBox({x:A,y:O,width:P,height:B},"Box.constructor",h),this._x=A,this._y=O,this._width=P,this._height=B}return p.isRect=function(l){return!!l&&[l.x,l.y,l.width,l.height].every(En)},p.assertIsValidBox=function(l,h,v){if(v===void 0&&(v=!1),!p.isRect(l))throw new Error(h+" - invalid box: "+JSON.stringify(l)+", expected object with properties x, y, width, height");if(!v&&(l.width<0||l.height<0))throw new Error(h+" - width ("+l.width+") and height ("+l.height+") must be positive numbers")},Object.defineProperty(p.prototype,"x",{get:function(){return this._x},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"y",{get:function(){return this._y},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"width",{get:function(){return this._width},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"height",{get:function(){return this._height},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"left",{get:function(){return this.x},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"top",{get:function(){return this.y},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"right",{get:function(){return this.x+this.width},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"bottom",{get:function(){return this.y+this.height},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"area",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"topLeft",{get:function(){return new et(this.left,this.top)},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"topRight",{get:function(){return new et(this.right,this.top)},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"bottomLeft",{get:function(){return new et(this.left,this.bottom)},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"bottomRight",{get:function(){return new et(this.right,this.bottom)},enumerable:!0,configurable:!0}),p.prototype.round=function(){var l=[this.x,this.y,this.width,this.height].map(function(T){return Math.round(T)}),h=l[0],v=l[1],y=l[2],b=l[3];return new p({x:h,y:v,width:y,height:b})},p.prototype.floor=function(){var l=[this.x,this.y,this.width,this.height].map(function(T){return Math.floor(T)}),h=l[0],v=l[1],y=l[2],b=l[3];return new p({x:h,y:v,width:y,height:b})},p.prototype.toSquare=function(){var l=this,h=l.x,v=l.y,y=l.width,b=l.height,T=Math.abs(y-b);return y<b&&(h-=T/2,y+=T),b<y&&(v-=T/2,b+=T),new p({x:h,y:v,width:y,height:b})},p.prototype.rescale=function(l){var h=nr(l)?l.width:l,v=nr(l)?l.height:l;return new p({x:this.x*h,y:this.y*v,width:this.width*h,height:this.height*v})},p.prototype.pad=function(l,h){var v=[this.x-l/2,this.y-h/2,this.width+l,this.height+h],y=v[0],b=v[1],T=v[2],A=v[3];return new p({x:y,y:b,width:T,height:A})},p.prototype.clipAtImageBorders=function(l,h){var v=this,y=v.x,b=v.y,T=v.right,A=v.bottom,O=Math.max(y,0),P=Math.max(b,0),B=T-O,H=A-P,Y=Math.min(B,l-O),Q=Math.min(H,h-P);return new p({x:O,y:P,width:Y,height:Q}).floor()},p.prototype.shift=function(l,h){var v=this,y=v.width,b=v.height,T=this.x+l,A=this.y+h;return new p({x:T,y:A,width:y,height:b})},p.prototype.padAtBorders=function(l,h){var v=this.width+1,y=this.height+1,b=1,T=1,A=v,O=y,P=this.left,B=this.top,H=this.right,Y=this.bottom;return H>h&&(A=-H+h+v,H=h),Y>l&&(O=-Y+l+y,Y=l),P<1&&(O=2-P,P=1),B<1&&(O=2-B,B=1),{dy:T,edy:O,dx:b,edx:A,y:B,ey:Y,x:P,ex:H,w:v,h:y}},p.prototype.calibrate=function(l){return new p({left:this.left+l.left*this.width,top:this.top+l.top*this.height,right:this.right+l.right*this.width,bottom:this.bottom+l.bottom*this.height}).toSquare().round()},p}(),Rn=function(p){Object(q.c)(l,p);function l(h,v,y,b,T){return T===void 0&&(T=!1),p.call(this,{left:h,top:v,right:y,bottom:b},T)||this}return l}(gn),L=function(){function p(l,h,v,y,b){this._imageDims=new lt(b.width,b.height),this._score=l,this._classScore=h,this._className=v,this._box=new gn(y).rescale(this._imageDims)}return Object.defineProperty(p.prototype,"score",{get:function(){return this._score},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"classScore",{get:function(){return this._classScore},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"className",{get:function(){return this._className},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"box",{get:function(){return this._box},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"imageDims",{get:function(){return this._imageDims},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"imageWidth",{get:function(){return this.imageDims.width},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"imageHeight",{get:function(){return this.imageDims.height},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"relativeBox",{get:function(){return new gn(this._box).rescale(this.imageDims.reverse())},enumerable:!0,configurable:!0}),p.prototype.forSize=function(l,h){return new p(this.score,this.classScore,this.className,this.relativeBox,{width:l,height:h})},p}(),_=function(p){Object(q.c)(l,p);function l(h,v,y){return p.call(this,h,h,"",v,y)||this}return l.prototype.forSize=function(h,v){var y=p.prototype.forSize.call(this,h,v),b=y.score,T=y.relativeBox,A=y.imageDims;return new l(b,T,A)},l}(L);function R(p,l,h){h===void 0&&(h=!0);var v=Math.max(0,Math.min(p.right,l.right)-Math.max(p.left,l.left)),y=Math.max(0,Math.min(p.bottom,l.bottom)-Math.max(p.top,l.top)),b=v*y;return h?b/(p.area+l.area-b):b/Math.min(p.area,l.area)}function U(p){var l=p.map(function(A){return A.x}),h=p.map(function(A){return A.y}),v=l.reduce(function(A,O){return O<A?O:A},Infinity),y=h.reduce(function(A,O){return O<A?O:A},Infinity),b=l.reduce(function(A,O){return A<O?O:A},0),T=h.reduce(function(A,O){return A<O?O:A},0);return new Rn(v,y,b,T)}function $(p,l,h,v){v===void 0&&(v=!0);for(var y=l.map(function(A,O){return{score:A,boxIndex:O}}).sort(function(A,O){return A.score-O.score}).map(function(A){return A.boxIndex}),b=[],T=function(){var A=y.pop();b.push(A);for(var O=y,P=[],B=0;B<O.length;B++){var H=O[B],Y=p[A],Q=p[H];P.push(R(Y,Q,v))}y=y.filter(function(ue,le){return P[le]<=h})};y.length>0;)T();return b}function de(p,l){return k.L(function(){var h=l[0],v=l[1],y=l[2],b=k.n(Object(q.e)(p.shape.slice(0,3),[1]),h),T=k.n(Object(q.e)(p.shape.slice(0,3),[1]),v),A=k.n(Object(q.e)(p.shape.slice(0,3),[1]),y),O=k.h([b,T,A],3);return k.F(p,O)})}function xe(p,l){return l===void 0&&(l=!1),k.L(function(){var h=p.shape.slice(1),v=h[0],y=h[1];if(v===y)return p;var b=Math.abs(v-y),T=Math.round(b*(l?.5:1)),A=v>y?2:1,O=function(Q){var ue=p.shape.slice();return ue[A]=Q,k.n(ue,0)},P=O(T),B=b-P.shape[A],H=l&&B?O(B):null,Y=[H,p,P].filter(function(Q){return!!Q}).map(function(Q){return Q.toFloat()});return k.h(Y,A)})}function ut(p){for(var l=p.slice(),h=l.length-1;h>0;h--){var v=Math.floor(Math.random()*(h+1)),y=l[h];l[h]=l[v],l[v]=y}return l}function Rt(p){return 1/(1+Math.exp(-p))}function Ut(p){return Math.log(p/(1-p))}var pn=function(p){Object(q.c)(l,p);function l(h,v,y,b,T){return T===void 0&&(T=!1),p.call(this,{x:h,y:v,width:y,height:b},T)||this}return l}(gn),qt=.5,Jr=.43,ba=.45,Un=function(){function p(l,h,v){v===void 0&&(v=new et(0,0));var y=h.width,b=h.height;this._imgDims=new lt(y,b),this._shift=v,this._positions=l.map(function(T){return T.mul(new et(y,b)).add(v)})}return Object.defineProperty(p.prototype,"shift",{get:function(){return new et(this._shift.x,this._shift.y)},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"imageWidth",{get:function(){return this._imgDims.width},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"imageHeight",{get:function(){return this._imgDims.height},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"positions",{get:function(){return this._positions},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"relativePositions",{get:function(){var l=this;return this._positions.map(function(h){return h.sub(l._shift).div(new et(l.imageWidth,l.imageHeight))})},enumerable:!0,configurable:!0}),p.prototype.forSize=function(l,h){return new this.constructor(this.relativePositions,{width:l,height:h})},p.prototype.shiftBy=function(l,h){return new this.constructor(this.relativePositions,this._imgDims,new et(l,h))},p.prototype.shiftByPoint=function(l){return this.shiftBy(l.x,l.y)},p.prototype.align=function(l,h){if(h===void 0&&(h={}),l){var v=l instanceof _?l.box.floor():new gn(l);return this.shiftBy(v.x,v.y).align(null,h)}var y=Object.assign({},{useDlibAlignment:!1,minBoxPadding:.2},h),b=y.useDlibAlignment,T=y.minBoxPadding;return b?this.alignDlib():this.alignMinBbox(T)},p.prototype.alignDlib=function(){var l=this.getRefPointsForAlignment(),h=l[0],v=l[1],y=l[2],b=function(H){return y.sub(H).magnitude()},T=(b(h)+b(v))/2,A=Math.floor(T/ba),O=wn(l),P=Math.floor(Math.max(0,O.x-qt*A)),B=Math.floor(Math.max(0,O.y-Jr*A));return new pn(P,B,Math.min(A,this.imageWidth+P),Math.min(A,this.imageHeight+B))},p.prototype.alignMinBbox=function(l){var h=U(this.positions);return h.pad(h.width*l,h.height*l)},p.prototype.getRefPointsForAlignment=function(){throw new Error("getRefPointsForAlignment not implemented by base class")},p}(),No=function(p){Object(q.c)(l,p);function l(){return p!==null&&p.apply(this,arguments)||this}return l.prototype.getRefPointsForAlignment=function(){var h=this.positions;return[h[0],h[1],wn([h[3],h[4]])]},l}(Un),fi=function(p){Object(q.c)(l,p);function l(){return p!==null&&p.apply(this,arguments)||this}return l.prototype.getJawOutline=function(){return this.positions.slice(0,17)},l.prototype.getLeftEyeBrow=function(){return this.positions.slice(17,22)},l.prototype.getRightEyeBrow=function(){return this.positions.slice(22,27)},l.prototype.getNose=function(){return this.positions.slice(27,36)},l.prototype.getLeftEye=function(){return this.positions.slice(36,42)},l.prototype.getRightEye=function(){return this.positions.slice(42,48)},l.prototype.getMouth=function(){return this.positions.slice(48,68)},l.prototype.getRefPointsForAlignment=function(){return[this.getLeftEye(),this.getRightEye(),this.getMouth()].map(wn)},l}(Un),Qr=function(){function p(l,h){this._label=l,this._distance=h}return Object.defineProperty(p.prototype,"label",{get:function(){return this._label},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"distance",{get:function(){return this._distance},enumerable:!0,configurable:!0}),p.prototype.toString=function(l){return l===void 0&&(l=!0),""+this.label+(l?" ("+Xt(this.distance)+")":"")},p}(),ko=function(p){Object(q.c)(l,p);function l(h,v){var y=p.call(this,h)||this;return y._label=v,y}return l.assertIsValidLabeledBox=function(h,v){if(gn.assertIsValidBox(h,v),!En(h.label))throw new Error(v+" - expected property label ("+h.label+") to be a number")},Object.defineProperty(l.prototype,"label",{get:function(){return this._label},enumerable:!0,configurable:!0}),l}(gn),br=function(){function p(l,h){if(!(typeof l=="string"))throw new Error("LabeledFaceDescriptors - constructor expected label to be a string");if(!Array.isArray(h)||h.some(function(v){return!(v instanceof Float32Array)}))throw new Error("LabeledFaceDescriptors - constructor expected descriptors to be an array of Float32Array");this._label=l,this._descriptors=h}return Object.defineProperty(p.prototype,"label",{get:function(){return this._label},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"descriptors",{get:function(){return this._descriptors},enumerable:!0,configurable:!0}),p.prototype.toJSON=function(){return{label:this.label,descriptors:this.descriptors.map(function(l){return Array.from(l)})}},p.fromJSON=function(l){var h=l.descriptors.map(function(v){return new Float32Array(v)});return new p(l.label,h)},p}(),za=function(p){Object(q.c)(l,p);function l(h,v,y,b){var T=p.call(this,h,v)||this;return T._score=y,T._classScore=b,T}return l.assertIsValidPredictedBox=function(h,v){if(ko.assertIsValidLabeledBox(h,v),!ar(h.score)||!ar(h.classScore))throw new Error(v+" - expected properties score ("+h.score+") and ("+h.classScore+") to be a number between [0, 1]")},Object.defineProperty(l.prototype,"score",{get:function(){return this._score},enumerable:!0,configurable:!0}),Object.defineProperty(l.prototype,"classScore",{get:function(){return this._classScore},enumerable:!0,configurable:!0}),l}(ko);function In(p){return p.detection instanceof _}function oe(p,l){var h={detection:l};return Object.assign({},p,h)}function So(){var p=window.fetch||function(){throw new Error("fetch - missing fetch implementation for browser environment")},l=function(){throw new Error("readFile - filesystem not available for browser environment")};return{Canvas:HTMLCanvasElement,CanvasRenderingContext2D,Image:HTMLImageElement,ImageData,Video:HTMLVideoElement,createCanvasElement:function(){return document.createElement("canvas")},createImageElement:function(){return document.createElement("img")},fetch:p,readFile:l}}var fn=te("rOjP"),Oo=te("oX8U");function Va(){return typeof window=="object"&&typeof document!="undefined"&&typeof HTMLImageElement!="undefined"&&typeof HTMLCanvasElement!="undefined"&&typeof HTMLVideoElement!="undefined"&&typeof ImageData!="undefined"&&typeof CanvasRenderingContext2D!="undefined"}var Ga=te("8KZw"),an;function Io(){if(!an)throw new Error("getEnv - environment is not defined, check isNodejs() and isBrowser()");return an}function Fr(p){an=p}function Mo(){Va()&&Fr(So()),Object(Ga.a)()&&Fr(Object(Oo.a)())}function yn(p){if(an||Mo(),!an)throw new Error("monkeyPatch - environment is not defined, check isNodejs() and isBrowser()");var l=p.Canvas,h=l===void 0?an.Canvas:l,v=p.Image,y=v===void 0?an.Image:v;an.Canvas=h,an.Image=y,an.createCanvasElement=p.createCanvasElement||function(){return new h},an.createImageElement=p.createImageElement||function(){return new y},an.ImageData=p.ImageData||an.ImageData,an.Video=p.Video||an.Video,an.fetch=p.fetch||an.fetch,an.readFile=p.readFile||an.readFile}var vn={getEnv:Io,setEnv:Fr,initialize:Mo,createBrowserEnv:So,createFileSystem:fn.a,createNodejsEnv:Oo.a,monkeyPatch:yn,isBrowser:Va,isNodejs:Ga.a};Mo();function Wt(p){return!vn.isNodejs()&&typeof p=="string"?document.getElementById(p):p}function Kn(p){var l=vn.getEnv(),h=l.Canvas,v=l.CanvasRenderingContext2D;if(p instanceof v)return p;var y=Wt(p);if(!(y instanceof h))throw new Error("resolveContext2d - expected canvas to be of instance of Canvas");var b=y.getContext("2d");if(!b)throw new Error("resolveContext2d - canvas 2d context is null");return b}var qn;(function(p){p.TOP_LEFT="TOP_LEFT",p.TOP_RIGHT="TOP_RIGHT",p.BOTTOM_LEFT="BOTTOM_LEFT",p.BOTTOM_RIGHT="BOTTOM_RIGHT"})(qn||(qn={}));var wa=function(){function p(l){l===void 0&&(l={});var h=l.anchorPosition,v=l.backgroundColor,y=l.fontColor,b=l.fontSize,T=l.fontStyle,A=l.padding;this.anchorPosition=h||qn.TOP_LEFT,this.backgroundColor=v||"rgba(0, 0, 0, 0.5)",this.fontColor=y||"rgba(255, 255, 255, 1)",this.fontSize=b||14,this.fontStyle=T||"Georgia",this.padding=A||4}return p}(),vi=function(){function p(l,h,v){v===void 0&&(v={}),this.text=typeof l=="string"?[l]:l instanceof p?l.text:l,this.anchor=h,this.options=new wa(v)}return p.prototype.measureWidth=function(l){var h=this.options.padding;return this.text.map(function(v){return l.measureText(v).width}).reduce(function(v,y){return v<y?y:v},0)+2*h},p.prototype.measureHeight=function(){var l=this.options,h=l.fontSize,v=l.padding;return this.text.length*h+2*v},p.prototype.getUpperLeft=function(l,h){var v=this.options.anchorPosition,y=v===qn.BOTTOM_RIGHT||v===qn.TOP_RIGHT,b=v===qn.BOTTOM_LEFT||v===qn.BOTTOM_RIGHT,T=this.measureWidth(l),A=this.measureHeight(),O=y?this.anchor.x-T:this.anchor.x,P=b?this.anchor.y-A:this.anchor.y;if(h){var B=h.width,H=h.height,Y=Math.max(Math.min(O,B-T),0),Q=Math.max(Math.min(P,H-A),0);return{x:Y,y:Q}}return{x:O,y:P}},p.prototype.draw=function(l){var h=Wt(l),v=Kn(h),y=this.options,b=y.backgroundColor,T=y.fontColor,A=y.fontSize,O=y.fontStyle,P=y.padding;v.font=A+"px "+O;var B=this.measureWidth(v),H=this.measureHeight();v.fillStyle=b;var Y=this.getUpperLeft(v,h);v.fillRect(Y.x,Y.y,B,H),v.fillStyle=T,this.text.forEach(function(Q,ue){var le=P+Y.x,_e=P+Y.y+(ue+1)*A;v.fillText(Q,le,_e)})},p}(),Fo=function(){function p(l){l===void 0&&(l={});var h=l.boxColor,v=l.lineWidth,y=l.label,b=l.drawLabelOptions;this.boxColor=h||"rgba(0, 0, 255, 1)",this.lineWidth=v||2,this.label=y;var T={anchorPosition:qn.BOTTOM_LEFT,backgroundColor:this.boxColor};this.drawLabelOptions=new wa(Object.assign({},T,b))}return p}(),mi=function(){function p(l,h){h===void 0&&(h={}),this.box=new gn(l),this.options=new Fo(h)}return p.prototype.draw=function(l){var h=Kn(l),v=this.options,y=v.boxColor,b=v.lineWidth,T=this.box,A=T.x,O=T.y,P=T.width,B=T.height;h.strokeStyle=y,h.lineWidth=b,h.strokeRect(A,O,P,B);var H=this.options.label;H&&new vi([H],{x:A-b/2,y:O},this.options.drawLabelOptions).draw(l)},p}();function X(p,l){var h=Array.isArray(l)?l:[l];h.forEach(function(v){var y=v instanceof _?v.score:In(v)?v.detection.score:void 0,b=v instanceof _?v.box:In(v)?v.detection.box:new gn(v),T=y?""+Xt(y):void 0;new mi(b,{label:T}).draw(p)})}function Po(p){var l=vn.getEnv(),h=l.Image,v=l.Video;return p instanceof h&&p.complete||p instanceof v&&p.readyState>=3}function pr(p){return new Promise(function(l,h){if(p instanceof vn.getEnv().Canvas||Po(p))return l();function v(b){if(!b.currentTarget)return;b.currentTarget.removeEventListener("load",v),b.currentTarget.removeEventListener("error",y),l(b)}function y(b){if(!b.currentTarget)return;b.currentTarget.removeEventListener("load",v),b.currentTarget.removeEventListener("error",y),h(b)}p.addEventListener("load",v),p.addEventListener("error",y)})}function Ea(p){return new Promise(function(l,h){if(!(p instanceof Blob))return h("bufferToImage - expected buf to be of type: Blob");var v=new FileReader;v.onload=function(){if(typeof v.result!="string")return h("bufferToImage - expected reader.result to be a string, in onload");var y=vn.getEnv().createImageElement();y.onload=function(){return l(y)},y.onerror=h,y.src=v.result},v.onerror=h,v.readAsDataURL(p)})}function An(p){var l=vn.getEnv(),h=l.Image,v=l.Video;return p instanceof h?new lt(p.naturalWidth,p.naturalHeight):p instanceof v?new lt(p.videoWidth,p.videoHeight):new lt(p.width,p.height)}function Tn(p){var l=p.width,h=p.height,v=vn.getEnv().createCanvasElement,y=v();return y.width=l,y.height=h,y}function fr(p,l){var h=vn.getEnv().ImageData;if(!(p instanceof h)&&!Po(p))throw new Error("createCanvasFromMedia - media has not finished loading yet");var v=l||An(p),y=v.width,b=v.height,T=Tn({width:y,height:b});return p instanceof h?Kn(T).putImageData(p,0,0):Kn(T).drawImage(p,0,0,y,b),T}function Lo(p,l){return Object(q.b)(this,void 0,void 0,function(){var h,v,y,b,T,A;return Object(q.d)(this,function(O){switch(O.label){case 0:return h=l||vn.getEnv().createCanvasElement(),v=p.shape.slice(On(p)?1:0),y=v[0],b=v[1],T=v[2],A=k.L(function(){return p.as3D(y,b,T).toInt()}),[4,k.f.toPixels(A,h)];case 1:return O.sent(),A.dispose(),[2,h]}})})}function Bo(p){var l=vn.getEnv(),h=l.Image,v=l.Canvas,y=l.Video;return p instanceof h||p instanceof v||p instanceof y}function or(p,l,h){h===void 0&&(h=!1);var v=vn.getEnv(),y=v.Image,b=v.Canvas;if(!(p instanceof y||p instanceof b))throw new Error("imageToSquare - expected arg0 to be HTMLImageElement | HTMLCanvasElement");var T=An(p),A=l/Math.max(T.height,T.width),O=A*T.width,P=A*T.height,B=Tn({width:l,height:l}),H=p instanceof b?p:fr(p),Y=Math.abs(O-P)/2,Q=h&&O<P?Y:0,ue=h&&P<O?Y:0;return Kn(B).drawImage(H,Q,ue,O,P),B}var Pr=function(){function p(l,h){var v=this;if(h===void 0&&(h=!1),this._imageTensors=[],this._canvases=[],this._treatAsBatchInput=!1,this._inputDimensions=[],!Array.isArray(l))throw new Error("NetInput.constructor - expected inputs to be an Array of TResolvedNetInput or to be instanceof tf.Tensor4D, instead have "+l);this._treatAsBatchInput=h,this._batchSize=l.length,l.forEach(function(y,b){if(bn(y)){v._imageTensors[b]=y,v._inputDimensions[b]=y.shape;return}if(On(y)){var T=y.shape[0];if(T!==1)throw new Error("NetInput - tf.Tensor4D with batchSize "+T+" passed, but not supported in input array");v._imageTensors[b]=y,v._inputDimensions[b]=y.shape.slice(1);return}var A=y instanceof vn.getEnv().Canvas?y:fr(y);v._canvases[b]=A,v._inputDimensions[b]=[A.height,A.width,3]})}return Object.defineProperty(p.prototype,"imageTensors",{get:function(){return this._imageTensors},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"canvases",{get:function(){return this._canvases},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"isBatchInput",{get:function(){return this.batchSize>1||this._treatAsBatchInput},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"batchSize",{get:function(){return this._batchSize},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"inputDimensions",{get:function(){return this._inputDimensions},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"inputSize",{get:function(){return this._inputSize},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"reshapedInputDimensions",{get:function(){var l=this;return $t(this.batchSize,0,1).map(function(h,v){return l.getReshapedInputDimensions(v)})},enumerable:!0,configurable:!0}),p.prototype.getInput=function(l){return this.canvases[l]||this.imageTensors[l]},p.prototype.getInputDimensions=function(l){return this._inputDimensions[l]},p.prototype.getInputHeight=function(l){return this._inputDimensions[l][0]},p.prototype.getInputWidth=function(l){return this._inputDimensions[l][1]},p.prototype.getReshapedInputDimensions=function(l){if(typeof this.inputSize!="number")throw new Error("getReshapedInputDimensions - inputSize not set, toBatchTensor has not been called yet");var h=this.getInputWidth(l),v=this.getInputHeight(l);return rr({width:h,height:v},this.inputSize)},p.prototype.toBatchTensor=function(l,h){var v=this;return h===void 0&&(h=!0),this._inputSize=l,k.L(function(){var y=$t(v.batchSize,0,1).map(function(T){var A=v.getInput(T);if(A instanceof k.a){var O=On(A)?A:A.expandDims();return O=xe(O,h),(O.shape[1]!==l||O.shape[2]!==l)&&(O=k.o.resizeBilinear(O,[l,l])),O.as3D(l,l,3)}if(A instanceof vn.getEnv().Canvas)return k.f.fromPixels(or(A,l,h));throw new Error("toBatchTensor - at batchIdx "+T+", expected input to be instanceof tf.Tensor or instanceof HTMLCanvasElement, instead have "+A)}),b=k.E(y.map(function(T){return T.toFloat()})).as4D(v.batchSize,l,l,3);return b})},p}();function Zt(p){return Object(q.b)(this,void 0,void 0,function(){var l,h,v;return Object(q.d)(this,function(y){switch(y.label){case 0:if(p instanceof Pr)return[2,p];if(l=Array.isArray(p)?p:[p],!l.length)throw new Error("toNetInput - empty array passed as input");return h=function(b){return Array.isArray(p)?" at input index "+b+":":""},v=l.map(Wt),v.forEach(function(b,T){if(!Bo(b)&&!bn(b)&&!On(b))throw typeof l[T]=="string"?new Error("toNetInput -"+h(T)+" string passed, but could not resolve HTMLElement for element id "+l[T]):new Error("toNetInput -"+h(T)+" expected media to be of type HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | tf.Tensor3D, or to be an element id");if(On(b)){var A=b.shape[0];if(A!==1)throw new Error("toNetInput -"+h(T)+" tf.Tensor4D with batchSize "+A+" passed, but not supported in input array")}}),[4,Promise.all(v.map(function(b){return Bo(b)&&pr(b)}))];case 1:return y.sent(),[2,new Pr(v,Array.isArray(p))]}})})}function Lr(p,l){return Object(q.b)(this,void 0,void 0,function(){var h,v,y,b,T,A,O;return Object(q.d)(this,function(P){switch(P.label){case 0:return h=vn.getEnv().Canvas,v=p,p instanceof h?[3,5]:[4,Zt(p)];case 1:if(y=P.sent(),y.batchSize>1)throw new Error("extractFaces - batchSize > 1 not supported");return b=y.getInput(0),b instanceof h?(T=b,[3,4]):[3,2];case 2:return[4,Lo(b)];case 3:T=P.sent(),P.label=4;case 4:v=T,P.label=5;case 5:return A=Kn(v),O=l.map(function(B){return B instanceof _?B.forSize(v.width,v.height).box.floor():B}).map(function(B){return B.clipAtImageBorders(v.width,v.height)}),[2,O.map(function(B){var H=B.x,Y=B.y,Q=B.width,ue=B.height,le=Tn({width:Q,height:ue});return Kn(le).putImageData(A.getImageData(H,Y,Q,ue),0,0),le})]}})})}function _a(p,l){return Object(q.b)(this,void 0,void 0,function(){return Object(q.d)(this,function(h){if(!bn(p)&&!On(p))throw new Error("extractFaceTensors - expected image tensor to be 3D or 4D");if(On(p)&&p.shape[0]>1)throw new Error("extractFaceTensors - batchSize > 1 not supported");return[2,k.L(function(){var v=p.shape.slice(On(p)?1:0),y=v[0],b=v[1],T=v[2],A=l.map(function(P){return P instanceof _?P.forSize(b,y).box:P}).map(function(P){return P.clipAtImageBorders(b,y)}),O=A.map(function(P){var B=P.x,H=P.y,Y=P.width,Q=P.height;return k.C(p.as3D(y,b,T),[H,B,0],[Q,Y,T])});return O})]})})}function Me(p,l){return Object(q.b)(this,void 0,void 0,function(){var h,v;return Object(q.d)(this,function(y){switch(y.label){case 0:return h=vn.getEnv().fetch,[4,h(p,l)];case 1:if(v=y.sent(),!(v.status<400))throw new Error("failed to fetch: ("+v.status+") "+v.statusText+", from url: "+v.url);return[2,v]}})})}function Uu(p){return Object(q.b)(this,void 0,void 0,function(){var l,h;return Object(q.d)(this,function(v){switch(v.label){case 0:return[4,Me(p)];case 1:return l=v.sent(),[4,l.blob()];case 2:if(h=v.sent(),!h.type.startsWith("image/"))throw new Error("fetchImage - expected blob type to be of type image/*, instead have: "+h.type+", for url: "+l.url);return[2,Ea(h)]}})})}function ls(p){return Object(q.b)(this,void 0,void 0,function(){return Object(q.d)(this,function(l){switch(l.label){case 0:return[4,Me(p)];case 1:return[2,l.sent().json()]}})})}function ds(p){return Object(q.b)(this,void 0,void 0,function(){var l;return Object(q.d)(this,function(h){switch(h.label){case 0:return l=Float32Array.bind,[4,Me(p)];case 1:return[4,h.sent().arrayBuffer()];case 2:return[2,new(l.apply(Float32Array,[void 0,h.sent()]))]}})})}function jo(p,l){var h=l+"-weights_manifest.json";if(!p)return{modelBaseUri:"",manifestUri:h};if(p==="/")return{modelBaseUri:"/",manifestUri:"/"+h};var v=p.startsWith("http://")?"http://":p.startsWith("https://")?"https://":"";p=p.replace(v,"");var y=p.split("/").filter(function(A){return A}),b=p.endsWith(".json")?y[y.length-1]:h,T=v+(p.endsWith(".json")?y.slice(0,y.length-1):y).join("/");return T=p.startsWith("/")?"/"+T:T,{modelBaseUri:T,manifestUri:T==="/"?"/"+b:T+"/"+b}}function Ca(p,l){return Object(q.b)(this,void 0,void 0,function(){var h,v,y,b;return Object(q.d)(this,function(T){switch(T.label){case 0:return h=jo(p,l),v=h.manifestUri,y=h.modelBaseUri,[4,ls(v)];case 1:return b=T.sent(),[2,k.p.loadWeights(b,y)]}})})}function hs(p,l,h){h===void 0&&(h=!1);var v=h?An(l):l,y=v.width,b=v.height;return p.width=y,p.height=b,{width:y,height:b}}var ir=function(){function p(l){this._name=l,this._params=void 0,this._paramMappings=[]}return Object.defineProperty(p.prototype,"params",{get:function(){return this._params},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"paramMappings",{get:function(){return this._paramMappings},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"isLoaded",{get:function(){return!!this.params},enumerable:!0,configurable:!0}),p.prototype.getParamFromPath=function(l){var h=this.traversePropertyPath(l),v=h.obj,y=h.objProp;return v[y]},p.prototype.reassignParamFromPath=function(l,h){var v=this.traversePropertyPath(l),y=v.obj,b=v.objProp;y[b].dispose(),y[b]=h},p.prototype.getParamList=function(){var l=this;return this._paramMappings.map(function(h){var v=h.paramPath;return{path:v,tensor:l.getParamFromPath(v)}})},p.prototype.getTrainableParams=function(){return this.getParamList().filter(function(l){return l.tensor instanceof k.b})},p.prototype.getFrozenParams=function(){return this.getParamList().filter(function(l){return!(l.tensor instanceof k.b)})},p.prototype.variable=function(){var l=this;this.getFrozenParams().forEach(function(h){var v=h.path,y=h.tensor;l.reassignParamFromPath(v,y.variable())})},p.prototype.freeze=function(){var l=this;this.getTrainableParams().forEach(function(h){var v=h.path,y=h.tensor,b=k.G(y.dataSync());y.dispose(),l.reassignParamFromPath(v,b)})},p.prototype.dispose=function(l){l===void 0&&(l=!0),this.getParamList().forEach(function(h){if(l&&h.tensor.isDisposed)throw new Error("param tensor has already been disposed for path "+h.path);h.tensor.dispose()}),this._params=void 0},p.prototype.serializeParams=function(){return new Float32Array(this.getParamList().map(function(l){var h=l.tensor;return Array.from(h.dataSync())}).reduce(function(l,h){return l.concat(h)}))},p.prototype.load=function(l){return Object(q.b)(this,void 0,void 0,function(){return Object(q.d)(this,function(h){switch(h.label){case 0:return l instanceof Float32Array?(this.extractWeights(l),[2]):[4,this.loadFromUri(l)];case 1:return h.sent(),[2]}})})},p.prototype.loadFromUri=function(l){return Object(q.b)(this,void 0,void 0,function(){var h;return Object(q.d)(this,function(v){switch(v.label){case 0:if(l&&typeof l!="string")throw new Error(this._name+".loadFromUri - expected model uri");return[4,Ca(l,this.getDefaultModelName())];case 1:return h=v.sent(),this.loadFromWeightMap(h),[2]}})})},p.prototype.loadFromDisk=function(l){return Object(q.b)(this,void 0,void 0,function(){var h,v,y,b,T,A,O,P,B,H;return Object(q.d)(this,function(Y){switch(Y.label){case 0:if(l&&typeof l!="string")throw new Error(this._name+".loadFromDisk - expected model file path");return h=vn.getEnv().readFile,v=jo(l,this.getDefaultModelName()),y=v.manifestUri,b=v.modelBaseUri,T=function(Q){return Promise.all(Q.map(function(ue){return h(ue).then(function(le){return le.buffer})}))},A=k.p.weightsLoaderFactory(T),B=(P=JSON).parse,[4,h(y)];case 1:return O=B.apply(P,[Y.sent().toString()]),[4,A(O,b)];case 2:return H=Y.sent(),this.loadFromWeightMap(H),[2]}})})},p.prototype.loadFromWeightMap=function(l){var h=this.extractParamsFromWeigthMap(l),v=h.paramMappings,y=h.params;this._paramMappings=v,this._params=y},p.prototype.extractWeights=function(l){var h=this.extractParams(l),v=h.paramMappings,y=h.params;this._paramMappings=v,this._params=y},p.prototype.traversePropertyPath=function(l){if(!this.params)throw new Error("traversePropertyPath - model has no loaded params");var h=l.split("/").reduce(function(b,T){if(!b.nextObj.hasOwnProperty(T))throw new Error("traversePropertyPath - object does not have property "+T+", for path "+l);return{obj:b.nextObj,objProp:T,nextObj:b.nextObj[T]}},{nextObj:this.params}),v=h.obj,y=h.objProp;if(!v||!y||!(v[y]instanceof k.a))throw new Error("traversePropertyPath - parameter is not a tensor, for path "+l);return{obj:v,objProp:y}},p}();function Dn(p,l,h){return k.L(function(){var v=k.z(p,l.depthwise_filter,l.pointwise_filter,h,"same");return v=k.c(v,l.bias),v})}function Zr(p,l,h){return h===void 0&&(h=!1),k.L(function(){var v=k.w(h?k.c(k.i(p,l.conv0.filters,[2,2],"same"),l.conv0.bias):Dn(p,l.conv0,[2,2])),y=Dn(v,l.conv1,[1,1]),b=k.w(k.c(v,y)),T=Dn(b,l.conv2,[1,1]);return k.w(k.c(v,k.c(y,T)))})}function Ha(p,l,h,v){return h===void 0&&(h=!1),v===void 0&&(v=!0),k.L(function(){var y=k.w(h?k.c(k.i(p,l.conv0.filters,v?[2,2]:[1,1],"same"),l.conv0.bias):Dn(p,l.conv0,v?[2,2]:[1,1])),b=Dn(y,l.conv1,[1,1]),T=k.w(k.c(y,b)),A=Dn(T,l.conv2,[1,1]),O=k.w(k.c(y,k.c(b,A))),P=Dn(O,l.conv3,[1,1]);return k.w(k.c(y,k.c(b,k.c(A,P))))})}function Vn(p,l,h,v){return h===void 0&&(h="same"),v===void 0&&(v=!1),k.L(function(){var y=k.c(k.i(p,l.filters,[1,1],h),l.bias);return v?k.w(y):y})}function sr(p,l){Object.keys(p).forEach(function(h){l.some(function(v){return v.originalPath===h})||p[h].dispose()})}function Br(p,l){return function(h,v,y,b){var T=k.K(p(h*v*y*y),[y,y,h,v]),A=k.H(p(v));return l.push({paramPath:b+"/filters"},{paramPath:b+"/bias"}),{filters:T,bias:A}}}function Xa(p,l){return function(h,v,y){var b=k.I(p(h*v),[h,v]),T=k.H(p(v));return l.push({paramPath:y+"/weights"},{paramPath:y+"/bias"}),{weights:b,bias:T}}}var Uo=function(){function p(l,h,v){this.depthwise_filter=l,this.pointwise_filter=h,this.bias=v}return p}();function Ka(p,l){return function(h,v,y){var b=k.K(p(3*3*h),[3,3,h,1]),T=k.K(p(h*v),[1,1,h,v]),A=k.H(p(v));return l.push({paramPath:y+"/depthwise_filter"},{paramPath:y+"/pointwise_filter"},{paramPath:y+"/bias"}),new Uo(b,T,A)}}function qa(p){return function(l){var h=p(l+"/depthwise_filter",4),v=p(l+"/pointwise_filter",4),y=p(l+"/bias",1);return new Uo(h,v,y)}}function vr(p,l){return function(h,v,y){var b=p[h];if(!je(b,v))throw new Error("expected weightMap["+h+"] to be a Tensor"+v+"D, instead have "+b);return l.push({originalPath:h,paramPath:y||h}),b}}function Yn(p){var l=p;function h(y){var b=l.slice(0,y);return l=l.slice(y),b}function v(){return l}return{extractWeights:h,getRemainingWeights:v}}function Wo(p,l){var h=Br(p,l),v=Ka(p,l);function y(T,A,O,P){P===void 0&&(P=!1);var B=P?h(T,A,3,O+"/conv0"):v(T,A,O+"/conv0"),H=v(A,A,O+"/conv1"),Y=v(A,A,O+"/conv2");return{conv0:B,conv1:H,conv2:Y}}function b(T,A,O,P){P===void 0&&(P=!1);var B=y(T,A,O,P),H=B.conv0,Y=B.conv1,Q=B.conv2,ue=v(A,A,O+"/conv3");return{conv0:H,conv1:Y,conv2:Q,conv3:ue}}return{extractDenseBlock3Params:y,extractDenseBlock4Params:b}}function gi(p){var l=[],h=Yn(p),v=h.extractWeights,y=h.getRemainingWeights,b=Wo(v,l).extractDenseBlock4Params,T=b(3,32,"dense0",!0),A=b(32,64,"dense1"),O=b(64,128,"dense2"),P=b(128,256,"dense3");if(y().length!==0)throw new Error("weights remaing after extract: "+y().length);return{paramMappings:l,params:{dense0:T,dense1:A,dense2:O,dense3:P}}}function zo(p){return function(l){var h=p(l+"/filters",4),v=p(l+"/bias",1);return{filters:h,bias:v}}}function Vo(p,l){var h=vr(p,l),v=zo(h),y=qa(h);function b(A,O){O===void 0&&(O=!1);var P=O?v(A+"/conv0"):y(A+"/conv0"),B=y(A+"/conv1"),H=y(A+"/conv2");return{conv0:P,conv1:B,conv2:H}}function T(A,O){O===void 0&&(O=!1);var P=O?v(A+"/conv0"):y(A+"/conv0"),B=y(A+"/conv1"),H=y(A+"/conv2"),Y=y(A+"/conv3");return{conv0:P,conv1:B,conv2:H,conv3:Y}}return{extractDenseBlock3Params:b,extractDenseBlock4Params:T}}function Ya(p){var l=[],h=Vo(p,l).extractDenseBlock4Params,v={dense0:h("dense0",!0),dense1:h("dense1"),dense2:h("dense2"),dense3:h("dense3")};return sr(p,l),{params:v,paramMappings:l}}var $a=function(p){Object(q.c)(l,p);function l(){return p.call(this,"FaceFeatureExtractor")||this}return l.prototype.forwardInput=function(h){var v=this.params;if(!v)throw new Error("FaceFeatureExtractor - load model before inference");return k.L(function(){var y=h.toBatchTensor(112,!0),b=[122.782,117.001,104.298],T=de(y,b).div(k.y(255)),A=Ha(T,v.dense0,!0);return A=Ha(A,v.dense1),A=Ha(A,v.dense2),A=Ha(A,v.dense3),A=k.d(A,[7,7],[2,2],"valid"),A})},l.prototype.forward=function(h){return Object(q.b)(this,void 0,void 0,function(){var v;return Object(q.d)(this,function(y){switch(y.label){case 0:return v=this.forwardInput,[4,Zt(h)];case 1:return[2,v.apply(this,[y.sent()])]}})})},l.prototype.getDefaultModelName=function(){return"face_feature_extractor_model"},l.prototype.extractParamsFromWeigthMap=function(h){return Ya(h)},l.prototype.extractParams=function(h){return gi(h)},l}(ir);function Mn(p,l){return k.L(function(){return k.c(k.q(p,l.weights),l.bias)})}function yi(p,l,h){var v=[],y=Yn(p),b=y.extractWeights,T=y.getRemainingWeights,A=Xa(b,v),O=A(l,h,"fc");if(T().length!==0)throw new Error("weights remaing after extract: "+T().length);return{paramMappings:v,params:{fc:O}}}function mr(p){var l=[],h=vr(p,l);function v(b){var T=h(b+"/weights",2),A=h(b+"/bias",1);return{weights:T,bias:A}}var y={fc:v("fc")};return sr(p,l),{params:y,paramMappings:l}}function Go(p){var l={},h={};return Object.keys(p).forEach(function(v){var y=v.startsWith("fc")?h:l;y[v]=p[v]}),{featureExtractorMap:l,classifierMap:h}}var ea=function(p){Object(q.c)(l,p);function l(h,v){var y=p.call(this,h)||this;return y._faceFeatureExtractor=v,y}return Object.defineProperty(l.prototype,"faceFeatureExtractor",{get:function(){return this._faceFeatureExtractor},enumerable:!0,configurable:!0}),l.prototype.runNet=function(h){var v=this,y=this.params;if(!y)throw new Error(this._name+" - load model before inference");return k.L(function(){var b=h instanceof Pr?v.faceFeatureExtractor.forwardInput(h):h;return Mn(b.as2D(b.shape[0],-1),y.fc)})},l.prototype.dispose=function(h){h===void 0&&(h=!0),this.faceFeatureExtractor.dispose(h),p.prototype.dispose.call(this,h)},l.prototype.loadClassifierParams=function(h){var v=this.extractClassifierParams(h),y=v.params,b=v.paramMappings;this._params=y,this._paramMappings=b},l.prototype.extractClassifierParams=function(h){return yi(h,this.getClassifierChannelsIn(),this.getClassifierChannelsOut())},l.prototype.extractParamsFromWeigthMap=function(h){var v=Go(h),y=v.featureExtractorMap,b=v.classifierMap;return this.faceFeatureExtractor.loadFromWeightMap(y),mr(b)},l.prototype.extractParams=function(h){var v=this.getClassifierChannelsIn(),y=this.getClassifierChannelsOut(),b=y*v+y,T=h.slice(0,h.length-b),A=h.slice(h.length-b);return this.faceFeatureExtractor.extractWeights(T),this.extractClassifierParams(A)},l}(ir),ta=["neutral","happy","sad","angry","fearful","disgusted","surprised"],na=function(){function p(l){var h=this;if(l.length!==7)throw new Error("FaceExpressions.constructor - expected probabilities.length to be 7, have: "+l.length);ta.forEach(function(v,y){h[v]=l[y]})}return p.prototype.asSortedArray=function(){var l=this;return ta.map(function(h){return{expression:h,probability:l[h]}}).sort(function(h,v){return v.probability-h.probability})},p}(),xi=function(p){Object(q.c)(l,p);function l(h){return h===void 0&&(h=new $a),p.call(this,"FaceExpressionNet",h)||this}return l.prototype.forwardInput=function(h){var v=this;return k.L(function(){return k.D(v.runNet(h))})},l.prototype.forward=function(h){return Object(q.b)(this,void 0,void 0,function(){var v;return Object(q.d)(this,function(y){switch(y.label){case 0:return v=this.forwardInput,[4,Zt(h)];case 1:return[2,v.apply(this,[y.sent()])]}})})},l.prototype.predictExpressions=function(h){return Object(q.b)(this,void 0,void 0,function(){var v,y,b,T,A=this;return Object(q.d)(this,function(O){switch(O.label){case 0:return[4,Zt(h)];case 1:return v=O.sent(),[4,this.forwardInput(v)];case 2:return y=O.sent(),[4,Promise.all(k.O(y).map(function(P){return Object(q.b)(A,void 0,void 0,function(){var B;return Object(q.d)(this,function(H){switch(H.label){case 0:return[4,P.data()];case 1:return B=H.sent(),P.dispose(),[2,B]}})})}))];case 3:return b=O.sent(),y.dispose(),T=b.map(function(P){return new na(P)}),[2,v.isBatchInput?T:T[0]]}})})},l.prototype.getDefaultModelName=function(){return"face_expression_model"},l.prototype.getClassifierChannelsIn=function(){return 256},l.prototype.getClassifierChannelsOut=function(){return 7},l}(ea);function Ja(p){return p.expressions instanceof na}function ra(p,l){var h={expressions:l};return Object.assign({},p,h)}function bi(p,l,h,v){h===void 0&&(h=.1);var y=Array.isArray(l)?l:[l];y.forEach(function(b){var T=b instanceof na?b:Ja(b)?b.expressions:void 0;if(!T)throw new Error("drawFaceExpressions - expected faceExpressions to be FaceExpressions | WithFaceExpressions<{}> or array thereof");var A=T.asSortedArray(),O=A.filter(function(H){return H.probability>h}),P=In(b)?b.detection.box.bottomLeft:v||new et(0,0),B=new vi(O.map(function(H){return H.expression+" ("+Xt(H.probability)+")"}),P);B.draw(p)})}function Qa(p){return In(p)&&p.landmarks instanceof Un&&p.unshiftedLandmarks instanceof Un&&p.alignedRect instanceof _}function Ra(p,l){var h=p.detection.box,v=l.shiftBy(h.x,h.y),y=v.align(),b=p.detection.imageDims,T=new _(p.detection.score,y.rescale(b.reverse()),b),A={landmarks:v,unshiftedLandmarks:l,alignedRect:T};return Object.assign({},p,A)}var Fn=function(){function p(l){l===void 0&&(l={});var h=l.drawLines,v=h===void 0?!0:h,y=l.drawPoints,b=y===void 0?!0:y,T=l.lineWidth,A=l.lineColor,O=l.pointSize,P=l.pointColor;this.drawLines=v,this.drawPoints=b,this.lineWidth=T||1,this.pointSize=O||2,this.lineColor=A||"rgba(0, 255, 255, 1)",this.pointColor=P||"rgba(255, 0, 255, 1)"}return p}(),Za=function(){function p(l,h){h===void 0&&(h={}),this.faceLandmarks=l,this.options=new Fn(h)}return p.prototype.draw=function(l){var h=Kn(l),v=this.options,y=v.drawLines,b=v.drawPoints,T=v.lineWidth,A=v.lineColor,O=v.pointSize,P=v.pointColor;if(y&&this.faceLandmarks instanceof fi&&(h.strokeStyle=A,h.lineWidth=T,Qe(h,this.faceLandmarks.getJawOutline()),Qe(h,this.faceLandmarks.getLeftEyeBrow()),Qe(h,this.faceLandmarks.getRightEyeBrow()),Qe(h,this.faceLandmarks.getNose()),Qe(h,this.faceLandmarks.getLeftEye(),!0),Qe(h,this.faceLandmarks.getRightEye(),!0),Qe(h,this.faceLandmarks.getMouth(),!0)),b){h.strokeStyle=P,h.fillStyle=P;var B=function(H){h.beginPath(),h.arc(H.x,H.y,O,0,2*Math.PI),h.fill()};this.faceLandmarks.positions.forEach(B)}},p}();function wi(p,l){var h=Array.isArray(l)?l:[l];h.forEach(function(v){var y=v instanceof Un?v:Qa(v)?v.landmarks:void 0;if(!y)throw new Error("drawFaceLandmarks - expected faceExpressions to be FaceLandmarks | WithFaceLandmarks<WithFaceDetection<{}>> or array thereof");new Za(y).draw(p)})}function Ei(p,l){var h=Br(p,l),v=Ka(p,l);function y(T,A,O){var P=v(T,A,O+"/separable_conv0"),B=v(A,A,O+"/separable_conv1"),H=h(T,A,1,O+"/expansion_conv");return{separable_conv0:P,separable_conv1:B,expansion_conv:H}}function b(T,A){var O=v(T,T,A+"/separable_conv0"),P=v(T,T,A+"/separable_conv1"),B=v(T,T,A+"/separable_conv2");return{separable_conv0:O,separable_conv1:P,separable_conv2:B}}return{extractConvParams:h,extractSeparableConvParams:v,extractReductionBlockParams:y,extractMainBlockParams:b}}function Ho(p,l){var h=[],v=Yn(p),y=v.extractWeights,b=v.getRemainingWeights,T=Ei(y,h),A=T.extractConvParams,O=T.extractSeparableConvParams,P=T.extractReductionBlockParams,B=T.extractMainBlockParams,H=A(3,32,3,"entry_flow/conv_in"),Y=P(32,64,"entry_flow/reduction_block_0"),Q=P(64,128,"entry_flow/reduction_block_1"),ue={conv_in:H,reduction_block_0:Y,reduction_block_1:Q},le={};$t(l,0,1).forEach(function(Fe){le["main_block_"+Fe]=B(128,"middle_flow/main_block_"+Fe)});var _e=P(128,256,"exit_flow/reduction_block"),De=O(256,512,"exit_flow/separable_conv"),Ue={reduction_block:_e,separable_conv:De};if(b().length!==0)throw new Error("weights remaing after extract: "+b().length);return{paramMappings:h,params:{entry_flow:ue,middle_flow:le,exit_flow:Ue}}}function _i(p,l){var h=vr(p,l),v=zo(h),y=qa(h);function b(A){var O=y(A+"/separable_conv0"),P=y(A+"/separable_conv1"),B=v(A+"/expansion_conv");return{separable_conv0:O,separable_conv1:P,expansion_conv:B}}function T(A){var O=y(A+"/separable_conv0"),P=y(A+"/separable_conv1"),B=y(A+"/separable_conv2");return{separable_conv0:O,separable_conv1:P,separable_conv2:B}}return{extractConvParams:v,extractSeparableConvParams:y,extractReductionBlockParams:b,extractMainBlockParams:T}}function ps(p,l){var h=[],v=_i(p,h),y=v.extractConvParams,b=v.extractSeparableConvParams,T=v.extractReductionBlockParams,A=v.extractMainBlockParams,O=y("entry_flow/conv_in"),P=T("entry_flow/reduction_block_0"),B=T("entry_flow/reduction_block_1"),H={conv_in:O,reduction_block_0:P,reduction_block_1:B},Y={};$t(l,0,1).forEach(function(_e){Y["main_block_"+_e]=A("middle_flow/main_block_"+_e)});var Q=T("exit_flow/reduction_block"),ue=b("exit_flow/separable_conv"),le={reduction_block:Q,separable_conv:ue};return sr(p,h),{params:{entry_flow:H,middle_flow:Y,exit_flow:le},paramMappings:h}}function $e(p,l,h){return k.c(k.i(p,l.filters,h,"same"),l.bias)}function Ci(p,l,h){h===void 0&&(h=!0);var v=h?k.w(p):p;return v=Dn(v,l.separable_conv0,[1,1]),v=Dn(k.w(v),l.separable_conv1,[1,1]),v=k.s(v,[3,3],[2,2],"same"),v=k.c(v,$e(p,l.expansion_conv,[2,2])),v}function Wu(p,l){var h=Dn(k.w(p),l.separable_conv0,[1,1]);return h=Dn(k.w(h),l.separable_conv1,[1,1]),h=Dn(k.w(h),l.separable_conv2,[1,1]),h=k.c(h,p),h}var zu=function(p){Object(q.c)(l,p);function l(h){var v=p.call(this,"TinyXception")||this;return v._numMainBlocks=h,v}return l.prototype.forwardInput=function(h){var v=this,y=this.params;if(!y)throw new Error("TinyXception - load model before inference");return k.L(function(){var b=h.toBatchTensor(112,!0),T=[122.782,117.001,104.298],A=de(b,T).div(k.y(256)),O=k.w($e(A,y.entry_flow.conv_in,[2,2]));return O=Ci(O,y.entry_flow.reduction_block_0,!1),O=Ci(O,y.entry_flow.reduction_block_1),$t(v._numMainBlocks,0,1).forEach(function(P){O=Wu(O,y.middle_flow["main_block_"+P])}),O=Ci(O,y.exit_flow.reduction_block),O=k.w(Dn(O,y.exit_flow.separable_conv,[1,1])),O})},l.prototype.forward=function(h){return Object(q.b)(this,void 0,void 0,function(){var v;return Object(q.d)(this,function(y){switch(y.label){case 0:return v=this.forwardInput,[4,Zt(h)];case 1:return[2,v.apply(this,[y.sent()])]}})})},l.prototype.getDefaultModelName=function(){return"tiny_xception_model"},l.prototype.extractParamsFromWeigthMap=function(h){return ps(h,this._numMainBlocks)},l.prototype.extractParams=function(h){return Ho(h,this._numMainBlocks)},l}(ir);function Ri(p){var l=[],h=Yn(p),v=h.extractWeights,y=h.getRemainingWeights,b=Xa(v,l),T=b(512,1,"fc/age"),A=b(512,2,"fc/gender");if(y().length!==0)throw new Error("weights remaing after extract: "+y().length);return{paramMappings:l,params:{fc:{age:T,gender:A}}}}function Vu(p){var l=[],h=vr(p,l);function v(b){var T=h(b+"/weights",2),A=h(b+"/bias",1);return{weights:T,bias:A}}var y={fc:{age:v("fc/age"),gender:v("fc/gender")}};return sr(p,l),{params:y,paramMappings:l}}var Aa;(function(p){p.FEMALE="female",p.MALE="male"})(Aa||(Aa={}));var Gu=function(p){Object(q.c)(l,p);function l(h){h===void 0&&(h=new zu(2));var v=p.call(this,"AgeGenderNet")||this;return v._faceFeatureExtractor=h,v}return Object.defineProperty(l.prototype,"faceFeatureExtractor",{get:function(){return this._faceFeatureExtractor},enumerable:!0,configurable:!0}),l.prototype.runNet=function(h){var v=this,y=this.params;if(!y)throw new Error(this._name+" - load model before inference");return k.L(function(){var b=h instanceof Pr?v.faceFeatureExtractor.forwardInput(h):h,T=k.d(b,[7,7],[2,2],"valid").as2D(b.shape[0],-1),A=Mn(T,y.fc.age).as1D(),O=Mn(T,y.fc.gender);return{age:A,gender:O}})},l.prototype.forwardInput=function(h){var v=this;return k.L(function(){var y=v.runNet(h),b=y.age,T=y.gender;return{age:b,gender:k.D(T)}})},l.prototype.forward=function(h){return Object(q.b)(this,void 0,void 0,function(){var v;return Object(q.d)(this,function(y){switch(y.label){case 0:return v=this.forwardInput,[4,Zt(h)];case 1:return[2,v.apply(this,[y.sent()])]}})})},l.prototype.predictAgeAndGender=function(h){return Object(q.b)(this,void 0,void 0,function(){var v,y,b,T,A,O,P=this;return Object(q.d)(this,function(B){switch(B.label){case 0:return[4,Zt(h)];case 1:return v=B.sent(),[4,this.forwardInput(v)];case 2:return y=B.sent(),b=k.O(y.age),T=k.O(y.gender),A=b.map(function(H,Y){return{ageTensor:H,genderTensor:T[Y]}}),[4,Promise.all(A.map(function(H){var Y=H.ageTensor,Q=H.genderTensor;return Object(q.b)(P,void 0,void 0,function(){var ue,le,_e,De,Ue;return Object(q.d)(this,function(Fe){switch(Fe.label){case 0:return[4,Y.data()];case 1:return ue=Fe.sent()[0],[4,Q.data()];case 2:return le=Fe.sent()[0],_e=le>.5,De=_e?Aa.MALE:Aa.FEMALE,Ue=_e?le:1-le,Y.dispose(),Q.dispose(),[2,{age:ue,gender:De,genderProbability:Ue}]}})})}))];case 3:return O=B.sent(),y.age.dispose(),y.gender.dispose(),[2,v.isBatchInput?O:O[0]]}})})},l.prototype.getDefaultModelName=function(){return"age_gender_model"},l.prototype.dispose=function(h){h===void 0&&(h=!0),this.faceFeatureExtractor.dispose(h),p.prototype.dispose.call(this,h)},l.prototype.loadClassifierParams=function(h){var v=this.extractClassifierParams(h),y=v.params,b=v.paramMappings;this._params=y,this._paramMappings=b},l.prototype.extractClassifierParams=function(h){return Ri(h)},l.prototype.extractParamsFromWeigthMap=function(h){var v=Go(h),y=v.featureExtractorMap,b=v.classifierMap;return this.faceFeatureExtractor.loadFromWeightMap(y),Vu(b)},l.prototype.extractParams=function(h){var v=512*1+1+(512*2+2),y=h.slice(0,h.length-v),b=h.slice(h.length-v);return this.faceFeatureExtractor.extractWeights(y),this.extractClassifierParams(b)},l}(ir),fs=function(p){Object(q.c)(l,p);function l(){return p!==null&&p.apply(this,arguments)||this}return l.prototype.postProcess=function(h,v,y){var b=y.map(function(A){var O=A.width,P=A.height,B=v/Math.max(P,O);return{width:O*B,height:P*B}}),T=b.length;return k.L(function(){var A=function(Y,Q){return k.E([k.n([68],Y),k.n([68],Q)],1).as2D(1,136).as1D()},O=function(Y,Q){var ue=b[Y],le=ue.width,_e=ue.height;return Q(le,_e)?Math.abs(le-_e)/2:0},P=function(Y){return O(Y,function(Q,ue){return Q<ue})},B=function(Y){return O(Y,function(Q,ue){return ue<Q})},H=h.mul(k.n([T,136],v)).sub(k.E(Array.from(Array(T),function(Y,Q){return A(P(Q),B(Q))}))).div(k.E(Array.from(Array(T),function(Y,Q){return A(b[Q].width,b[Q].height)})));return H})},l.prototype.forwardInput=function(h){var v=this;return k.L(function(){var y=v.runNet(h);return v.postProcess(y,h.inputSize,h.inputDimensions.map(function(b){var T=b[0],A=b[1];return{height:T,width:A}}))})},l.prototype.forward=function(h){return Object(q.b)(this,void 0,void 0,function(){var v;return Object(q.d)(this,function(y){switch(y.label){case 0:return v=this.forwardInput,[4,Zt(h)];case 1:return[2,v.apply(this,[y.sent()])]}})})},l.prototype.detectLandmarks=function(h){return Object(q.b)(this,void 0,void 0,function(){var v,y,b,T=this;return Object(q.d)(this,function(A){switch(A.label){case 0:return[4,Zt(h)];case 1:return v=A.sent(),y=k.L(function(){return k.O(T.forwardInput(v))}),[4,Promise.all(y.map(function(O,P){return Object(q.b)(T,void 0,void 0,function(){var B,H,Y,Q,ue;return Object(q.d)(this,function(le){switch(le.label){case 0:return Y=(H=Array).from,[4,O.data()];case 1:return B=Y.apply(H,[le.sent()]),Q=B.filter(function(_e,De){return tr(De)}),ue=B.filter(function(_e,De){return!tr(De)}),[2,new fi(Array(68).fill(0).map(function(_e,De){return new et(Q[De],ue[De])}),{height:v.getInputHeight(P),width:v.getInputWidth(P)})]}})})}))];case 2:return b=A.sent(),y.forEach(function(O){return O.dispose()}),[2,v.isBatchInput?b:b[0]]}})})},l.prototype.getClassifierChannelsOut=function(){return 136},l}(ea),en=function(p){Object(q.c)(l,p);function l(h){return h===void 0&&(h=new $a),p.call(this,"FaceLandmark68Net",h)||this}return l.prototype.getDefaultModelName=function(){return"face_landmark_68_model"},l.prototype.getClassifierChannelsIn=function(){return 256},l}(fs);function Pn(p){var l=[],h=Vo(p,l).extractDenseBlock3Params,v={dense0:h("dense0",!0),dense1:h("dense1"),dense2:h("dense2")};return sr(p,l),{params:v,paramMappings:l}}function vs(p){var l=[],h=Yn(p),v=h.extractWeights,y=h.getRemainingWeights,b=Wo(v,l).extractDenseBlock3Params,T=b(3,32,"dense0",!0),A=b(32,64,"dense1"),O=b(64,128,"dense2");if(y().length!==0)throw new Error("weights remaing after extract: "+y().length);return{paramMappings:l,params:{dense0:T,dense1:A,dense2:O}}}var Hu=function(p){Object(q.c)(l,p);function l(){return p.call(this,"TinyFaceFeatureExtractor")||this}return l.prototype.forwardInput=function(h){var v=this.params;if(!v)throw new Error("TinyFaceFeatureExtractor - load model before inference");return k.L(function(){var y=h.toBatchTensor(112,!0),b=[122.782,117.001,104.298],T=de(y,b).div(k.y(255)),A=Zr(T,v.dense0,!0);return A=Zr(A,v.dense1),A=Zr(A,v.dense2),A=k.d(A,[14,14],[2,2],"valid"),A})},l.prototype.forward=function(h){return Object(q.b)(this,void 0,void 0,function(){var v;return Object(q.d)(this,function(y){switch(y.label){case 0:return v=this.forwardInput,[4,Zt(h)];case 1:return[2,v.apply(this,[y.sent()])]}})})},l.prototype.getDefaultModelName=function(){return"face_feature_extractor_tiny_model"},l.prototype.extractParamsFromWeigthMap=function(h){return Pn(h)},l.prototype.extractParams=function(h){return vs(h)},l}(ir),Xu=function(p){Object(q.c)(l,p);function l(h){return h===void 0&&(h=new Hu),p.call(this,"FaceLandmark68TinyNet",h)||this}return l.prototype.getDefaultModelName=function(){return"face_landmark_68_tiny_model"},l.prototype.getClassifierChannelsIn=function(){return 128},l}(fs),ed=function(p){Object(q.c)(l,p);function l(){return p!==null&&p.apply(this,arguments)||this}return l}(en);function Ku(p,l){return k.c(k.t(p,l.weights),l.biases)}function Ai(p,l,h,v,y){y===void 0&&(y="same");var b=l.conv,T=b.filters,A=b.bias,O=k.i(p,T,h,y);return O=k.c(O,A),O=Ku(O,l.scale),v?k.w(O):O}function qu(p,l){return Ai(p,l,[1,1],!0)}function ms(p,l){return Ai(p,l,[1,1],!1)}function gs(p,l){return Ai(p,l,[2,2],!0,"valid")}function Yu(p,l){function h(A,O,P){var B=p(A),H=B.length/(O*P*P);if(xr(H))throw new Error("depth has to be an integer: "+H+", weights.length: "+B.length+", numFilters: "+O+", filterSize: "+P);return k.L(function(){return k.N(k.K(B,[O,H,P,P]),[2,3,1,0])})}function v(A,O,P,B){var H=h(A,O,P),Y=k.H(p(O));return l.push({paramPath:B+"/filters"},{paramPath:B+"/bias"}),{filters:H,bias:Y}}function y(A,O){var P=k.H(p(A)),B=k.H(p(A));return l.push({paramPath:O+"/weights"},{paramPath:O+"/biases"}),{weights:P,biases:B}}function b(A,O,P,B){var H=v(A,O,P,B+"/conv"),Y=y(O,B+"/scale");return{conv:H,scale:Y}}function T(A,O,P,B,H){H===void 0&&(H=!1);var Y=b((H?.5:1)*A,O,P,B+"/conv1"),Q=b(A,O,P,B+"/conv2");return{conv1:Y,conv2:Q}}return{extractConvLayerParams:b,extractResidualLayerParams:T}}function $u(p){var l=Yn(p),h=l.extractWeights,v=l.getRemainingWeights,y=[],b=Yu(h,y),T=b.extractConvLayerParams,A=b.extractResidualLayerParams,O=T(4704,32,7,"conv32_down"),P=A(9216,32,3,"conv32_1"),B=A(9216,32,3,"conv32_2"),H=A(9216,32,3,"conv32_3"),Y=A(36864,64,3,"conv64_down",!0),Q=A(36864,64,3,"conv64_1"),ue=A(36864,64,3,"conv64_2"),le=A(36864,64,3,"conv64_3"),_e=A(147456,128,3,"conv128_down",!0),De=A(147456,128,3,"conv128_1"),Ue=A(147456,128,3,"conv128_2"),Fe=A(589824,256,3,"conv256_down",!0),we=A(589824,256,3,"conv256_1"),Ne=A(589824,256,3,"conv256_2"),Ze=A(589824,256,3,"conv256_down_out"),Bt=k.L(function(){return k.N(k.I(h(256*128),[128,256]),[1,0])});if(y.push({paramPath:"fc"}),v().length!==0)throw new Error("weights remaing after extract: "+v().length);var Yt={conv32_down:O,conv32_1:P,conv32_2:B,conv32_3:H,conv64_down:Y,conv64_1:Q,conv64_2:ue,conv64_3:le,conv128_down:_e,conv128_1:De,conv128_2:Ue,conv256_down:Fe,conv256_1:we,conv256_2:Ne,conv256_down_out:Ze,fc:Bt};return{params:Yt,paramMappings:y}}function eo(p,l){var h=vr(p,l);function v(T){var A=h(T+"/scale/weights",1),O=h(T+"/scale/biases",1);return{weights:A,biases:O}}function y(T){var A=h(T+"/conv/filters",4),O=h(T+"/conv/bias",1),P=v(T);return{conv:{filters:A,bias:O},scale:P}}function b(T){return{conv1:y(T+"/conv1"),conv2:y(T+"/conv2")}}return{extractConvLayerParams:y,extractResidualLayerParams:b}}function ur(p){var l=[],h=eo(p,l),v=h.extractConvLayerParams,y=h.extractResidualLayerParams,b=v("conv32_down"),T=y("conv32_1"),A=y("conv32_2"),O=y("conv32_3"),P=y("conv64_down"),B=y("conv64_1"),H=y("conv64_2"),Y=y("conv64_3"),Q=y("conv128_down"),ue=y("conv128_1"),le=y("conv128_2"),_e=y("conv256_down"),De=y("conv256_1"),Ue=y("conv256_2"),Fe=y("conv256_down_out"),we=p.fc;if(l.push({originalPath:"fc",paramPath:"fc"}),!Cn(we))throw new Error("expected weightMap[fc] to be a Tensor2D, instead have "+we);var Ne={conv32_down:b,conv32_1:T,conv32_2:A,conv32_3:O,conv64_down:P,conv64_1:B,conv64_2:H,conv64_3:Y,conv128_down:Q,conv128_1:ue,conv128_2:le,conv256_down:_e,conv256_1:De,conv256_2:Ue,conv256_down_out:Fe,fc:we};return sr(p,l),{params:Ne,paramMappings:l}}function $n(p,l){var h=qu(p,l.conv1);return h=ms(h,l.conv2),h=k.c(h,p),h=k.w(h),h}function F(p,l){var h=gs(p,l.conv1);h=ms(h,l.conv2);var v=k.d(p,2,2,"valid"),y=k.P(v.shape),b=v.shape[3]!==h.shape[3],T=v.shape[1]!==h.shape[1]||v.shape[2]!==h.shape[2];if(T){var A=Object(q.e)(h.shape);A[1]=1;var O=k.P(A);h=k.h([h,O],1);var P=Object(q.e)(h.shape);P[2]=1;var B=k.P(P);h=k.h([h,B],2)}return v=b?k.h([v,y],3):v,h=k.c(v,h),h=k.w(h),h}var aa=function(p){Object(q.c)(l,p);function l(){return p.call(this,"FaceRecognitionNet")||this}return l.prototype.forwardInput=function(h){var v=this.params;if(!v)throw new Error("FaceRecognitionNet - load model before inference");return k.L(function(){var y=h.toBatchTensor(150,!0).toFloat(),b=[122.782,117.001,104.298],T=de(y,b).div(k.y(256)),A=gs(T,v.conv32_down);A=k.s(A,3,2,"valid"),A=$n(A,v.conv32_1),A=$n(A,v.conv32_2),A=$n(A,v.conv32_3),A=F(A,v.conv64_down),A=$n(A,v.conv64_1),A=$n(A,v.conv64_2),A=$n(A,v.conv64_3),A=F(A,v.conv128_down),A=$n(A,v.conv128_1),A=$n(A,v.conv128_2),A=F(A,v.conv256_down),A=$n(A,v.conv256_1),A=$n(A,v.conv256_2),A=F(A,v.conv256_down_out);var O=A.mean([1,2]),P=k.q(O,v.fc);return P})},l.prototype.forward=function(h){return Object(q.b)(this,void 0,void 0,function(){var v;return Object(q.d)(this,function(y){switch(y.label){case 0:return v=this.forwardInput,[4,Zt(h)];case 1:return[2,v.apply(this,[y.sent()])]}})})},l.prototype.computeFaceDescriptor=function(h){return Object(q.b)(this,void 0,void 0,function(){var v,y,b,T=this;return Object(q.d)(this,function(A){switch(A.label){case 0:return[4,Zt(h)];case 1:return v=A.sent(),y=k.L(function(){return k.O(T.forwardInput(v))}),[4,Promise.all(y.map(function(O){return O.data()}))];case 2:return b=A.sent(),y.forEach(function(O){return O.dispose()}),[2,v.isBatchInput?b:b[0]]}})})},l.prototype.getDefaultModelName=function(){return"face_recognition_model"},l.prototype.extractParamsFromWeigthMap=function(h){return ur(h)},l.prototype.extractParams=function(h){return $u(h)},l}(ir);function Ti(p){var l=new aa;return l.extractWeights(p),l}function Xo(p,l){var h={descriptor:l};return Object.assign({},p,h)}function Nn(p){return typeof p.age=="number"}function kn(p,l){var h={age:l};return Object.assign({},p,h)}function Wn(p){return(p.gender===Aa.MALE||p.gender===Aa.FEMALE)&&ar(p.genderProbability)}function Gn(p,l,h){var v={gender:l,genderProbability:h};return Object.assign({},p,v)}var oa=function(){function p(l){var h=l===void 0?{}:l,v=h.minFaceSize,y=h.scaleFactor,b=h.maxNumScales,T=h.scoreThresholds,A=h.scaleSteps;if(this._name="MtcnnOptions",this._minFaceSize=v||20,this._scaleFactor=y||.709,this._maxNumScales=b||10,this._scoreThresholds=T||[.6,.7,.7],this._scaleSteps=A,typeof this._minFaceSize!="number"||this._minFaceSize<0)throw new Error(this._name+" - expected minFaceSize to be a number > 0");if(typeof this._scaleFactor!="number"||this._scaleFactor<=0||this._scaleFactor>=1)throw new Error(this._name+" - expected scaleFactor to be a number between 0 and 1");if(typeof this._maxNumScales!="number"||this._maxNumScales<0)throw new Error(this._name+" - expected maxNumScales to be a number > 0");if(!Array.isArray(this._scoreThresholds)||this._scoreThresholds.length!==3||this._scoreThresholds.some(function(O){return typeof O!="number"}))throw new Error(this._name+" - expected scoreThresholds to be an array of numbers of length 3");if(this._scaleSteps&&(!Array.isArray(this._scaleSteps)||this._scaleSteps.some(function(O){return typeof O!="number"})))throw new Error(this._name+" - expected scaleSteps to be an array of numbers")}return Object.defineProperty(p.prototype,"minFaceSize",{get:function(){return this._minFaceSize},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"scaleFactor",{get:function(){return this._scaleFactor},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"maxNumScales",{get:function(){return this._maxNumScales},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"scoreThresholds",{get:function(){return this._scoreThresholds},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"scaleSteps",{get:function(){return this._scaleSteps},enumerable:!0,configurable:!0}),p}();function Jn(p,l){function h(O,P){var B=k.K(p(3*3*O),[3,3,O,1]),H=k.H(p(O)),Y=k.H(p(O)),Q=k.H(p(O)),ue=k.H(p(O));return l.push({paramPath:P+"/filters"},{paramPath:P+"/batch_norm_scale"},{paramPath:P+"/batch_norm_offset"},{paramPath:P+"/batch_norm_mean"},{paramPath:P+"/batch_norm_variance"}),{filters:B,batch_norm_scale:H,batch_norm_offset:Y,batch_norm_mean:Q,batch_norm_variance:ue}}function v(O,P,B,H,Y){var Q=k.K(p(O*P*B*B),[B,B,O,P]),ue=k.H(p(P));return l.push({paramPath:H+"/filters"},{paramPath:H+"/"+(Y?"batch_norm_offset":"bias")}),{filters:Q,bias:ue}}function y(O,P,B,H){var Y=v(O,P,B,H,!0),Q=Y.filters,ue=Y.bias;return{filters:Q,batch_norm_offset:ue}}function b(O,P,B){var H=h(O,B+"/depthwise_conv"),Y=y(O,P,1,B+"/pointwise_conv");return{depthwise_conv:H,pointwise_conv:Y}}function T(){var O=y(3,32,3,"mobilenetv1/conv_0"),P=b(32,64,"mobilenetv1/conv_1"),B=b(64,128,"mobilenetv1/conv_2"),H=b(128,128,"mobilenetv1/conv_3"),Y=b(128,256,"mobilenetv1/conv_4"),Q=b(256,256,"mobilenetv1/conv_5"),ue=b(256,512,"mobilenetv1/conv_6"),le=b(512,512,"mobilenetv1/conv_7"),_e=b(512,512,"mobilenetv1/conv_8"),De=b(512,512,"mobilenetv1/conv_9"),Ue=b(512,512,"mobilenetv1/conv_10"),Fe=b(512,512,"mobilenetv1/conv_11"),we=b(512,1024,"mobilenetv1/conv_12"),Ne=b(1024,1024,"mobilenetv1/conv_13");return{conv_0:O,conv_1:P,conv_2:B,conv_3:H,conv_4:Y,conv_5:Q,conv_6:ue,conv_7:le,conv_8:_e,conv_9:De,conv_10:Ue,conv_11:Fe,conv_12:we,conv_13:Ne}}function A(){var O=y(1024,256,1,"prediction_layer/conv_0"),P=y(256,512,3,"prediction_layer/conv_1"),B=y(512,128,1,"prediction_layer/conv_2"),H=y(128,256,3,"prediction_layer/conv_3"),Y=y(256,128,1,"prediction_layer/conv_4"),Q=y(128,256,3,"prediction_layer/conv_5"),ue=y(256,64,1,"prediction_layer/conv_6"),le=y(64,128,3,"prediction_layer/conv_7"),_e=v(512,12,1,"prediction_layer/box_predictor_0/box_encoding_predictor"),De=v(512,9,1,"prediction_layer/box_predictor_0/class_predictor"),Ue=v(1024,24,1,"prediction_layer/box_predictor_1/box_encoding_predictor"),Fe=v(1024,18,1,"prediction_layer/box_predictor_1/class_predictor"),we=v(512,24,1,"prediction_layer/box_predictor_2/box_encoding_predictor"),Ne=v(512,18,1,"prediction_layer/box_predictor_2/class_predictor"),Ze=v(256,24,1,"prediction_layer/box_predictor_3/box_encoding_predictor"),Bt=v(256,18,1,"prediction_layer/box_predictor_3/class_predictor"),Yt=v(256,24,1,"prediction_layer/box_predictor_4/box_encoding_predictor"),At=v(256,18,1,"prediction_layer/box_predictor_4/class_predictor"),rt=v(128,24,1,"prediction_layer/box_predictor_5/box_encoding_predictor"),Kt=v(128,18,1,"prediction_layer/box_predictor_5/class_predictor"),on={box_encoding_predictor:_e,class_predictor:De},nn={box_encoding_predictor:Ue,class_predictor:Fe},dt={box_encoding_predictor:we,class_predictor:Ne},zn={box_encoding_predictor:Ze,class_predictor:Bt},Ie={box_encoding_predictor:Yt,class_predictor:At},Sn={box_encoding_predictor:rt,class_predictor:Kt};return{conv_0:O,conv_1:P,conv_2:B,conv_3:H,conv_4:Y,conv_5:Q,conv_6:ue,conv_7:le,box_predictor_0:on,box_predictor_1:nn,box_predictor_2:dt,box_predictor_3:zn,box_predictor_4:Ie,box_predictor_5:Sn}}return{extractMobilenetV1Params:T,extractPredictionLayerParams:A}}function Di(p){var l=[],h=Yn(p),v=h.extractWeights,y=h.getRemainingWeights,b=Jn(v,l),T=b.extractMobilenetV1Params,A=b.extractPredictionLayerParams,O=T(),P=A(),B=k.J(v(5118*4),[1,5118,4]),H={extra_dim:B};if(l.push({paramPath:"output_layer/extra_dim"}),y().length!==0)throw new Error("weights remaing after extract: "+y().length);return{params:{mobilenetv1:O,prediction_layer:P,output_layer:H},paramMappings:l}}function jr(p,l){var h=vr(p,l);function v(P,B,H){var Y=h(P+"/Conv2d_"+B+"_pointwise/weights",4,H+"/filters"),Q=h(P+"/Conv2d_"+B+"_pointwise/convolution_bn_offset",1,H+"/batch_norm_offset");return{filters:Y,batch_norm_offset:Q}}function y(P){var B="mobilenetv1/conv_"+P,H="MobilenetV1/Conv2d_"+P+"_depthwise",Y=B+"/depthwise_conv",Q=B+"/pointwise_conv",ue=h(H+"/depthwise_weights",4,Y+"/filters"),le=h(H+"/BatchNorm/gamma",1,Y+"/batch_norm_scale"),_e=h(H+"/BatchNorm/beta",1,Y+"/batch_norm_offset"),De=h(H+"/BatchNorm/moving_mean",1,Y+"/batch_norm_mean"),Ue=h(H+"/BatchNorm/moving_variance",1,Y+"/batch_norm_variance");return{depthwise_conv:{filters:ue,batch_norm_scale:le,batch_norm_offset:_e,batch_norm_mean:De,batch_norm_variance:Ue},pointwise_conv:v("MobilenetV1",P,Q)}}function b(){return{conv_0:v("MobilenetV1",0,"mobilenetv1/conv_0"),conv_1:y(1),conv_2:y(2),conv_3:y(3),conv_4:y(4),conv_5:y(5),conv_6:y(6),conv_7:y(7),conv_8:y(8),conv_9:y(9),conv_10:y(10),conv_11:y(11),conv_12:y(12),conv_13:y(13)}}function T(P,B){var H=h(P+"/weights",4,B+"/filters"),Y=h(P+"/biases",1,B+"/bias");return{filters:H,bias:Y}}function A(P){var B=T("Prediction/BoxPredictor_"+P+"/BoxEncodingPredictor","prediction_layer/box_predictor_"+P+"/box_encoding_predictor"),H=T("Prediction/BoxPredictor_"+P+"/ClassPredictor","prediction_layer/box_predictor_"+P+"/class_predictor");return{box_encoding_predictor:B,class_predictor:H}}function O(){return{conv_0:v("Prediction",0,"prediction_layer/conv_0"),conv_1:v("Prediction",1,"prediction_layer/conv_1"),conv_2:v("Prediction",2,"prediction_layer/conv_2"),conv_3:v("Prediction",3,"prediction_layer/conv_3"),conv_4:v("Prediction",4,"prediction_layer/conv_4"),conv_5:v("Prediction",5,"prediction_layer/conv_5"),conv_6:v("Prediction",6,"prediction_layer/conv_6"),conv_7:v("Prediction",7,"prediction_layer/conv_7"),box_predictor_0:A(0),box_predictor_1:A(1),box_predictor_2:A(2),box_predictor_3:A(3),box_predictor_4:A(4),box_predictor_5:A(5)}}return{extractMobilenetV1Params:b,extractPredictionLayerParams:O}}function K(p){var l=[],h=jr(p,l),v=h.extractMobilenetV1Params,y=h.extractPredictionLayerParams,b=p["Output/extra_dim"];if(l.push({originalPath:"Output/extra_dim",paramPath:"output_layer/extra_dim"}),!bn(b))throw new Error("expected weightMap['Output/extra_dim'] to be a Tensor3D, instead have "+b);var T={mobilenetv1:v(),prediction_layer:y(),output_layer:{extra_dim:b}};return sr(p,l),{params:T,paramMappings:l}}function zt(p,l,h){return k.L(function(){var v=k.i(p,l.filters,h,"same");return v=k.c(v,l.batch_norm_offset),k.g(v,0,6)})}var Hn=.0010000000474974513;function cr(p,l,h){return k.L(function(){var v=k.j(p,l.filters,h,"same");return v=k.e(v,l.batch_norm_mean,l.batch_norm_variance,l.batch_norm_offset,l.batch_norm_scale,Hn),k.g(v,0,6)})}function _n(p){return[2,4,6,12].some(function(l){return l===p})?[2,2]:[1,1]}function wr(p,l){return k.L(function(){var h=null,v=zt(p,l.conv_0,[2,2]),y=[l.conv_1,l.conv_2,l.conv_3,l.conv_4,l.conv_5,l.conv_6,l.conv_7,l.conv_8,l.conv_9,l.conv_10,l.conv_11,l.conv_12,l.conv_13];if(y.forEach(function(b,T){var A=T+1,O=_n(A);v=cr(v,b.depthwise_conv,O),v=zt(v,b.pointwise_conv,[1,1]),A===11&&(h=v)}),h===null)throw new Error("mobileNetV1 - output of conv layer 11 is null");return{out:v,conv11:h}})}function We(p,l,h,v,y){var b=p.shape[0],T=Math.min(h,b),A=l.map(function(B,H){return{score:B,boxIndex:H}}).filter(function(B){return B.score>y}).sort(function(B,H){return H.score-B.score}),O=function(B){return B<=v?1:0},P=[];return A.forEach(function(B){if(P.length>=T)return;for(var H=B.score,Y=P.length-1;Y>=0;--Y){var Q=Ur(p,B.boxIndex,P[Y]);if(Q===0)continue;if(B.score*=O(Q),B.score<=y)break}H===B.score&&P.push(B.boxIndex)}),P}function Ur(p,l,h){var v=p.arraySync(),y=Math.min(v[l][0],v[l][2]),b=Math.min(v[l][1],v[l][3]),T=Math.max(v[l][0],v[l][2]),A=Math.max(v[l][1],v[l][3]),O=Math.min(v[h][0],v[h][2]),P=Math.min(v[h][1],v[h][3]),B=Math.max(v[h][0],v[h][2]),H=Math.max(v[h][1],v[h][3]),Y=(T-y)*(A-b),Q=(B-O)*(H-P);if(Y<=0||Q<=0)return 0;var ue=Math.max(y,O),le=Math.max(b,P),_e=Math.min(T,B),De=Math.min(A,H),Ue=Math.max(_e-ue,0)*Math.max(De-le,0);return Ue/(Y+Q-Ue)}function Wr(p){var l=k.O(k.N(p,[1,0])),h=[k.F(l[2],l[0]),k.F(l[3],l[1])],v=[k.c(l[0],k.k(h[0],k.y(2))),k.c(l[1],k.k(h[1],k.y(2)))];return{sizes:h,centers:v}}function Ko(p,l){var h=Wr(p),v=h.sizes,y=h.centers,b=k.O(k.N(l,[1,0])),T=k.k(k.t(k.l(k.k(b[2],k.y(5))),v[0]),k.y(2)),A=k.c(k.t(k.k(b[0],k.y(10)),v[0]),y[0]),O=k.k(k.t(k.l(k.k(b[3],k.y(5))),v[1]),k.y(2)),P=k.c(k.t(k.k(b[1],k.y(10)),v[1]),y[1]);return k.N(k.E([k.F(A,T),k.F(P,O),k.c(A,T),k.c(P,O)]),[1,0])}function Er(p,l,h){return k.L(function(){var v=p.shape[0],y=Ko(k.x(k.M(h.extra_dim,[v,1,1]),[-1,4]),k.x(p,[-1,4]));y=k.x(y,[v,y.shape[0]/v,4]);var b=k.A(k.B(l,[0,0,1],[-1,-1,-1])),T=k.B(b,[0,0,0],[-1,-1,1]);T=k.x(T,[v,T.shape[1]]);var A=k.O(y),O=k.O(T);return{boxes:A,scores:O}})}function ia(p,l){return k.L(function(){var h=p.shape[0],v=k.x(Vn(p,l.box_encoding_predictor),[h,-1,1,4]),y=k.x(Vn(p,l.class_predictor),[h,-1,3]);return{boxPredictionEncoding:v,classPrediction:y}})}function ys(p,l,h){return k.L(function(){var v=zt(p,h.conv_0,[1,1]),y=zt(v,h.conv_1,[2,2]),b=zt(y,h.conv_2,[1,1]),T=zt(b,h.conv_3,[2,2]),A=zt(T,h.conv_4,[1,1]),O=zt(A,h.conv_5,[2,2]),P=zt(O,h.conv_6,[1,1]),B=zt(P,h.conv_7,[2,2]),H=ia(l,h.box_predictor_0),Y=ia(p,h.box_predictor_1),Q=ia(y,h.box_predictor_2),ue=ia(T,h.box_predictor_3),le=ia(O,h.box_predictor_4),_e=ia(B,h.box_predictor_5),De=k.h([H.boxPredictionEncoding,Y.boxPredictionEncoding,Q.boxPredictionEncoding,ue.boxPredictionEncoding,le.boxPredictionEncoding,_e.boxPredictionEncoding],1),Ue=k.h([H.classPrediction,Y.classPrediction,Q.classPrediction,ue.classPrediction,le.classPrediction,_e.classPrediction],1);return{boxPredictions:De,classPredictions:Ue}})}var sa=function(){function p(l){var h=l===void 0?{}:l,v=h.minConfidence,y=h.maxResults;if(this._name="SsdMobilenetv1Options",this._minConfidence=v||.5,this._maxResults=y||100,typeof this._minConfidence!="number"||this._minConfidence<=0||this._minConfidence>=1)throw new Error(this._name+" - expected minConfidence to be a number between 0 and 1");if(typeof this._maxResults!="number")throw new Error(this._name+" - expected maxResults to be a number")}return Object.defineProperty(p.prototype,"minConfidence",{get:function(){return this._minConfidence},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"maxResults",{get:function(){return this._maxResults},enumerable:!0,configurable:!0}),p}(),_r=function(p){Object(q.c)(l,p);function l(){return p.call(this,"SsdMobilenetv1")||this}return l.prototype.forwardInput=function(h){var v=this.params;if(!v)throw new Error("SsdMobilenetv1 - load model before inference");return k.L(function(){var y=h.toBatchTensor(512,!1).toFloat(),b=k.F(k.t(y,k.y(.007843137718737125)),k.y(1)),T=wr(b,v.mobilenetv1),A=ys(T.out,T.conv11,v.prediction_layer),O=A.boxPredictions,P=A.classPredictions;return Er(O,P,v.output_layer)})},l.prototype.forward=function(h){return Object(q.b)(this,void 0,void 0,function(){var v;return Object(q.d)(this,function(y){switch(y.label){case 0:return v=this.forwardInput,[4,Zt(h)];case 1:return[2,v.apply(this,[y.sent()])]}})})},l.prototype.locateFaces=function(h,v){return v===void 0&&(v={}),Object(q.b)(this,void 0,void 0,function(){var y,b,T,A,O,P,B,H,Y,Q,ue,le,_e,De,Ue,Fe,we,Ne,Ze,Bt,Yt;return Object(q.d)(this,function(At){switch(At.label){case 0:return y=new sa(v),b=y.maxResults,T=y.minConfidence,[4,Zt(h)];case 1:for(A=At.sent(),O=this.forwardInput(A),P=O.boxes,B=O.scores,H=P[0],Y=B[0],Q=1;Q<P.length;Q++)P[Q].dispose(),B[Q].dispose();return _e=(le=Array).from,[4,Y.data()];case 2:return ue=_e.apply(le,[At.sent()]),De=.5,Ue=We(H,ue,b,De,T),Fe=A.getReshapedInputDimensions(0),we=A.inputSize,Ne=we/Fe.width,Ze=we/Fe.height,Bt=H.arraySync(),Yt=Ue.map(function(rt){var Kt=[Math.max(0,Bt[rt][0]),Math.min(1,Bt[rt][2])].map(function(Sn){return Sn*Ze}),on=Kt[0],nn=Kt[1],dt=[Math.max(0,Bt[rt][1]),Math.min(1,Bt[rt][3])].map(function(Sn){return Sn*Ne}),zn=dt[0],Ie=dt[1];return new _(ue[rt],new pn(zn,on,Ie-zn,nn-on),{height:A.getInputHeight(0),width:A.getInputWidth(0)})}),H.dispose(),Y.dispose(),[2,Yt]}})})},l.prototype.getDefaultModelName=function(){return"ssd_mobilenetv1_model"},l.prototype.extractParamsFromWeigthMap=function(h){return K(h)},l.prototype.extractParams=function(h){return Di(h)},l}(ir);function Jt(p){var l=new _r;return l.extractWeights(p),l}function qo(p){return Jt(p)}var Ju=function(p){Object(q.c)(l,p);function l(){return p!==null&&p.apply(this,arguments)||this}return l}(_r),to=.4,Ni=[new et(.738768,.874946),new et(2.42204,2.65704),new et(4.30971,7.04493),new et(10.246,4.59428),new et(12.6868,11.8741)],gt=[new et(1.603231,2.094468),new et(6.041143,7.080126),new et(2.882459,3.518061),new et(4.266906,5.178857),new et(9.041765,10.66308)],Qn=[117.001,114.697,97.404],xs="tiny_yolov2_model",bs="tiny_yolov2_separable_conv_model",no=function(p){return typeof p=="number"};function ws(p){if(!p)throw new Error("invalid config: "+p);if(typeof p.withSeparableConvs!="boolean")throw new Error("config.withSeparableConvs has to be a boolean, have: "+p.withSeparableConvs);if(!no(p.iouThreshold)||p.iouThreshold<0||p.iouThreshold>1)throw new Error("config.iouThreshold has to be a number between [0, 1], have: "+p.iouThreshold);if(!Array.isArray(p.classes)||!p.classes.length||!p.classes.every(function(l){return typeof l=="string"}))throw new Error("config.classes has to be an array class names: string[], have: "+JSON.stringify(p.classes));if(!Array.isArray(p.anchors)||!p.anchors.length||!p.anchors.map(function(l){return l||{}}).every(function(l){return no(l.x)&&no(l.y)}))throw new Error("config.anchors has to be an array of { x: number, y: number }, have: "+JSON.stringify(p.anchors));if(p.meanRgb&&(!Array.isArray(p.meanRgb)||p.meanRgb.length!==3||!p.meanRgb.every(no)))throw new Error("config.meanRgb has to be an array of shape [number, number, number], have: "+JSON.stringify(p.meanRgb))}function Ta(p){return k.L(function(){var l=k.t(p,k.y(.10000000149011612));return k.c(k.w(k.F(p,l)),l)})}function Ln(p,l){return k.L(function(){var h=k.v(p,[[0,0],[1,1],[1,1],[0,0]]);return h=k.i(h,l.conv.filters,[1,1],"valid"),h=k.F(h,l.bn.sub),h=k.t(h,l.bn.truediv),h=k.c(h,l.conv.bias),Ta(h)})}function Cr(p,l){return k.L(function(){var h=k.v(p,[[0,0],[1,1],[1,1],[0,0]]);return h=k.z(h,l.depthwise_filter,l.pointwise_filter,[1,1],"valid"),h=k.c(h,l.bias),Ta(h)})}function Es(p,l){var h=Br(p,l);function v(T,A){var O=k.H(p(T)),P=k.H(p(T));return l.push({paramPath:A+"/sub"},{paramPath:A+"/truediv"}),{sub:O,truediv:P}}function y(T,A,O){var P=h(T,A,3,O+"/conv"),B=v(A,O+"/bn");return{conv:P,bn:B}}var b=Ka(p,l);return{extractConvParams:h,extractConvWithBatchNormParams:y,extractSeparableConvParams:b}}function _s(p,l,h,v){var y=Yn(p),b=y.extractWeights,T=y.getRemainingWeights,A=[],O=Es(b,A),P=O.extractConvParams,B=O.extractConvWithBatchNormParams,H=O.extractSeparableConvParams,Y;if(l.withSeparableConvs){var Q=v[0],ue=v[1],le=v[2],_e=v[3],De=v[4],Ue=v[5],Fe=v[6],we=v[7],Ne=v[8],Ze=l.isFirstLayerConv2d?P(Q,ue,3,"conv0"):H(Q,ue,"conv0"),Bt=H(ue,le,"conv1"),Yt=H(le,_e,"conv2"),At=H(_e,De,"conv3"),rt=H(De,Ue,"conv4"),Kt=H(Ue,Fe,"conv5"),on=we?H(Fe,we,"conv6"):void 0,nn=Ne?H(we,Ne,"conv7"):void 0,dt=P(Ne||we||Fe,5*h,1,"conv8");Y={conv0:Ze,conv1:Bt,conv2:Yt,conv3:At,conv4:rt,conv5:Kt,conv6:on,conv7:nn,conv8:dt}}else{var Q=v[0],ue=v[1],le=v[2],_e=v[3],De=v[4],Ue=v[5],Fe=v[6],we=v[7],Ne=v[8],Ze=B(Q,ue,"conv0"),Bt=B(ue,le,"conv1"),Yt=B(le,_e,"conv2"),At=B(_e,De,"conv3"),rt=B(De,Ue,"conv4"),Kt=B(Ue,Fe,"conv5"),on=B(Fe,we,"conv6"),nn=B(we,Ne,"conv7"),dt=P(Ne,5*h,1,"conv8");Y={conv0:Ze,conv1:Bt,conv2:Yt,conv3:At,conv4:rt,conv5:Kt,conv6:on,conv7:nn,conv8:dt}}if(T().length!==0)throw new Error("weights remaing after extract: "+T().length);return{params:Y,paramMappings:A}}function Cs(p,l){var h=vr(p,l);function v(A){var O=h(A+"/sub",1),P=h(A+"/truediv",1);return{sub:O,truediv:P}}function y(A){var O=h(A+"/filters",4),P=h(A+"/bias",1);return{filters:O,bias:P}}function b(A){var O=y(A+"/conv"),P=v(A+"/bn");return{conv:O,bn:P}}var T=qa(h);return{extractConvParams:y,extractConvWithBatchNormParams:b,extractSeparableConvParams:T}}function Rs(p,l){var h=[],v=Cs(p,h),y=v.extractConvParams,b=v.extractConvWithBatchNormParams,T=v.extractSeparableConvParams,A;if(l.withSeparableConvs){var O=l.filterSizes&&l.filterSizes.length||9;A={conv0:l.isFirstLayerConv2d?y("conv0"):T("conv0"),conv1:T("conv1"),conv2:T("conv2"),conv3:T("conv3"),conv4:T("conv4"),conv5:T("conv5"),conv6:O>7?T("conv6"):void 0,conv7:O>8?T("conv7"):void 0,conv8:y("conv8")}}else A={conv0:b("conv0"),conv1:b("conv1"),conv2:b("conv2"),conv3:b("conv3"),conv4:b("conv4"),conv5:b("conv5"),conv6:b("conv6"),conv7:b("conv7"),conv8:y("conv8")};return sr(p,h),{params:A,paramMappings:h}}var ki;(function(p){p[p.XS=224]="XS",p[p.SM=320]="SM",p[p.MD=416]="MD",p[p.LG=608]="LG"})(ki||(ki={}));var lr=function(){function p(l){var h=l===void 0?{}:l,v=h.inputSize,y=h.scoreThreshold;if(this._name="TinyYolov2Options",this._inputSize=v||416,this._scoreThreshold=y||.5,typeof this._inputSize!="number"||this._inputSize%32!==0)throw new Error(this._name+" - expected inputSize to be a number divisible by 32");if(typeof this._scoreThreshold!="number"||this._scoreThreshold<=0||this._scoreThreshold>=1)throw new Error(this._name+" - expected scoreThreshold to be a number between 0 and 1")}return Object.defineProperty(p.prototype,"inputSize",{get:function(){return this._inputSize},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"scoreThreshold",{get:function(){return this._scoreThreshold},enumerable:!0,configurable:!0}),p}(),Da=function(p){Object(q.c)(l,p);function l(h){var v=p.call(this,"TinyYolov2")||this;return ws(h),v._config=h,v}return Object.defineProperty(l.prototype,"config",{get:function(){return this._config},enumerable:!0,configurable:!0}),Object.defineProperty(l.prototype,"withClassScores",{get:function(){return this.config.withClassScores||this.config.classes.length>1},enumerable:!0,configurable:!0}),Object.defineProperty(l.prototype,"boxEncodingSize",{get:function(){return 5+(this.withClassScores?this.config.classes.length:0)},enumerable:!0,configurable:!0}),l.prototype.runTinyYolov2=function(h,v){var y=Ln(h,v.conv0);return y=k.s(y,[2,2],[2,2],"same"),y=Ln(y,v.conv1),y=k.s(y,[2,2],[2,2],"same"),y=Ln(y,v.conv2),y=k.s(y,[2,2],[2,2],"same"),y=Ln(y,v.conv3),y=k.s(y,[2,2],[2,2],"same"),y=Ln(y,v.conv4),y=k.s(y,[2,2],[2,2],"same"),y=Ln(y,v.conv5),y=k.s(y,[2,2],[1,1],"same"),y=Ln(y,v.conv6),y=Ln(y,v.conv7),Vn(y,v.conv8,"valid",!1)},l.prototype.runMobilenet=function(h,v){var y=this.config.isFirstLayerConv2d?Ta(Vn(h,v.conv0,"valid",!1)):Cr(h,v.conv0);return y=k.s(y,[2,2],[2,2],"same"),y=Cr(y,v.conv1),y=k.s(y,[2,2],[2,2],"same"),y=Cr(y,v.conv2),y=k.s(y,[2,2],[2,2],"same"),y=Cr(y,v.conv3),y=k.s(y,[2,2],[2,2],"same"),y=Cr(y,v.conv4),y=k.s(y,[2,2],[2,2],"same"),y=Cr(y,v.conv5),y=k.s(y,[2,2],[1,1],"same"),y=v.conv6?Cr(y,v.conv6):y,y=v.conv7?Cr(y,v.conv7):y,Vn(y,v.conv8,"valid",!1)},l.prototype.forwardInput=function(h,v){var y=this,b=this.params;if(!b)throw new Error("TinyYolov2 - load model before inference");return k.L(function(){var T=h.toBatchTensor(v,!1).toFloat();return T=y.config.meanRgb?de(T,y.config.meanRgb):T,T=T.div(k.y(256)),y.config.withSeparableConvs?y.runMobilenet(T,b):y.runTinyYolov2(T,b)})},l.prototype.forward=function(h,v){return Object(q.b)(this,void 0,void 0,function(){var y;return Object(q.d)(this,function(b){switch(b.label){case 0:return y=this.forwardInput,[4,Zt(h)];case 1:return[4,y.apply(this,[b.sent(),v])];case 2:return[2,b.sent()]}})})},l.prototype.detect=function(h,v){return v===void 0&&(v={}),Object(q.b)(this,void 0,void 0,function(){var y,b,T,A,O,P,B,H,Y,Q,ue,le,_e,De,Ue=this;return Object(q.d)(this,function(Fe){switch(Fe.label){case 0:return y=new lr(v),b=y.inputSize,T=y.scoreThreshold,[4,Zt(h)];case 1:return A=Fe.sent(),[4,this.forwardInput(A,b)];case 2:return O=Fe.sent(),P=k.L(function(){return k.O(O)[0].expandDims()}),B={width:A.getInputWidth(0),height:A.getInputHeight(0)},[4,this.extractBoxes(P,A.getReshapedInputDimensions(0),T)];case 3:return H=Fe.sent(),O.dispose(),P.dispose(),Y=H.map(function(we){return we.box}),Q=H.map(function(we){return we.score}),ue=H.map(function(we){return we.classScore}),le=H.map(function(we){return Ue.config.classes[we.label]}),_e=$(Y.map(function(we){return we.rescale(b)}),Q,this.config.iouThreshold,!0),De=_e.map(function(we){return new L(Q[we],ue[we],le[we],Y[we],B)}),[2,De]}})})},l.prototype.getDefaultModelName=function(){return""},l.prototype.extractParamsFromWeigthMap=function(h){return Rs(h,this.config)},l.prototype.extractParams=function(h){var v=this.config.filterSizes||l.DEFAULT_FILTER_SIZES,y=v?v.length:void 0;if(y!==7&&y!==8&&y!==9)throw new Error("TinyYolov2 - expected 7 | 8 | 9 convolutional filters, but found "+y+" filterSizes in config");return _s(h,this.config,this.boxEncodingSize,v)},l.prototype.extractBoxes=function(h,v,y){return Object(q.b)(this,void 0,void 0,function(){var b,T,A,O,P,B,H,Y,Q,ue,le,_e,De,Ue,Fe,we,Ne,Ze,Bt,Yt,At,rt,Kt,on,nn,dt,zn,Ie,Sn,Ot=this;return Object(q.d)(this,function(sn){switch(sn.label){case 0:return b=v.width,T=v.height,A=Math.max(b,T),O=A/b,P=A/T,B=h.shape[1],H=this.config.anchors.length,Y=k.L(function(){var Nr=h.reshape([B,B,H,Ot.boxEncodingSize]),hr=Nr.slice([0,0,0,0],[B,B,H,4]),kr=Nr.slice([0,0,0,4],[B,B,H,1]),pa=Ot.withClassScores?k.D(Nr.slice([0,0,0,5],[B,B,H,Ot.config.classes.length]),3):k.y(0);return[hr,kr,pa]}),Q=Y[0],ue=Y[1],le=Y[2],_e=[],[4,ue.array()];case 1:return De=sn.sent(),[4,Q.array()];case 2:Ue=sn.sent(),Fe=0,sn.label=3;case 3:if(!(Fe<B))return[3,12];we=0,sn.label=4;case 4:if(!(we<B))return[3,11];Ne=0,sn.label=5;case 5:return Ne<H?(Ze=Rt(De[Fe][we][Ne][0]),!y||Ze>y?(Bt=(we+Rt(Ue[Fe][we][Ne][0]))/B*O,Yt=(Fe+Rt(Ue[Fe][we][Ne][1]))/B*P,At=Math.exp(Ue[Fe][we][Ne][2])*this.config.anchors[Ne].x/B*O,rt=Math.exp(Ue[Fe][we][Ne][3])*this.config.anchors[Ne].y/B*P,Kt=Bt-At/2,on=Yt-rt/2,nn={row:Fe,col:we,anchor:Ne},this.withClassScores?[4,this.extractPredictedClass(le,nn)]:[3,7]):[3,9]):[3,10];case 6:return Sn=sn.sent(),[3,8];case 7:Sn={classScore:1,label:0},sn.label=8;case 8:dt=Sn,zn=dt.classScore,Ie=dt.label,_e.push(Object(q.a)({box:new Rn(Kt,on,Kt+At,on+rt),score:Ze,classScore:Ze*zn,label:Ie},nn)),sn.label=9;case 9:return Ne++,[3,5];case 10:return we++,[3,4];case 11:return Fe++,[3,3];case 12:return Q.dispose(),ue.dispose(),le.dispose(),[2,_e]}})})},l.prototype.extractPredictedClass=function(h,v){return Object(q.b)(this,void 0,void 0,function(){var y,b,T,A;return Object(q.d)(this,function(O){switch(O.label){case 0:return y=v.row,b=v.col,T=v.anchor,[4,h.array()];case 1:return A=O.sent(),[2,Array(this.config.classes.length).fill(0).map(function(P,B){return A[y][b][T][B]}).map(function(P,B){return{classScore:P,label:B}}).reduce(function(P,B){return P.classScore>B.classScore?P:B})]}})})},l.DEFAULT_FILTER_SIZES=[3,16,32,64,128,256,512,1024,1024],l}(ir),ro=function(p){Object(q.c)(l,p);function l(h){h===void 0&&(h=!0);var v=this,y=Object.assign({},{withSeparableConvs:h,iouThreshold:to,classes:["face"]},h?{anchors:gt,meanRgb:Qn}:{anchors:Ni,withClassScores:!0});return v=p.call(this,y)||this,v}return Object.defineProperty(l.prototype,"withSeparableConvs",{get:function(){return this.config.withSeparableConvs},enumerable:!0,configurable:!0}),Object.defineProperty(l.prototype,"anchors",{get:function(){return this.config.anchors},enumerable:!0,configurable:!0}),l.prototype.locateFaces=function(h,v){return Object(q.b)(this,void 0,void 0,function(){var y;return Object(q.d)(this,function(b){switch(b.label){case 0:return[4,this.detect(h,v)];case 1:return y=b.sent(),[2,y.map(function(T){return new _(T.score,T.relativeBox,{width:T.imageWidth,height:T.imageHeight})})]}})})},l.prototype.getDefaultModelName=function(){return this.withSeparableConvs?bs:xs},l.prototype.extractParamsFromWeigthMap=function(h){return p.prototype.extractParamsFromWeigthMap.call(this,h)},l}(Da);function Qu(p,l){l===void 0&&(l=!0);var h=new ro(l);return h.extractWeights(p),h}var Si=function(p){Object(q.c)(l,p);function l(){var h=p!==null&&p.apply(this,arguments)||this;return h._name="TinyFaceDetectorOptions",h}return l}(lr),Je=function(){function p(){}return p.prototype.then=function(l){return Object(q.b)(this,void 0,void 0,function(){var h;return Object(q.d)(this,function(v){switch(v.label){case 0:return h=l,[4,this.run()];case 1:return[2,h.apply(void 0,[v.sent()])]}})})},p.prototype.run=function(){return Object(q.b)(this,void 0,void 0,function(){return Object(q.d)(this,function(l){throw new Error("ComposableTask - run is not implemented")})})},p}();function ao(p,l,h,v,y){return y===void 0&&(y=function(b){var T=b.alignedRect;return T}),Object(q.b)(this,void 0,void 0,function(){var b,T,A,O,P;return Object(q.d)(this,function(B){switch(B.label){case 0:return b=p.map(function(H){return Qa(H)?y(H):H.detection}),A=v,A?[3,5]:l instanceof k.a?[4,_a(l,b)]:[3,2];case 1:return O=B.sent(),[3,4];case 2:return[4,Lr(l,b)];case 3:O=B.sent(),B.label=4;case 4:A=O,B.label=5;case 5:return T=A,[4,h(T)];case 6:return P=B.sent(),T.forEach(function(H){return H instanceof k.a&&H.dispose()}),[2,P]}})})}function oo(p,l,h,v,y){return Object(q.b)(this,void 0,void 0,function(){var b=this;return Object(q.d)(this,function(T){return[2,ao([p],l,function(A){return Object(q.b)(b,void 0,void 0,function(){return Object(q.d)(this,function(O){return[2,h(A[0])]})})},v,y)]})})}function As(p){return k.L(function(){return k.E(k.O(p,3).reverse(),3)})}var io=2,so=12;function Ts(p,l){var h=Br(p,l),v=Xa(p,l);function y(P,B){var H=k.H(p(P));return l.push({paramPath:B}),H}function b(P,B,H){H===void 0&&(H=!1);var Y=h(P[0],P[1],3,B+"/conv1"),Q=y(P[1],B+"/prelu1_alpha"),ue=h(P[1],P[2],3,B+"/conv2"),le=y(P[2],B+"/prelu2_alpha"),_e=h(P[2],P[3],H?2:3,B+"/conv3"),De=y(P[3],B+"/prelu3_alpha");return{conv1:Y,prelu1_alpha:Q,conv2:ue,prelu2_alpha:le,conv3:_e,prelu3_alpha:De}}function T(){var P=b([3,10,16,32],"pnet"),B=h(32,2,1,"pnet/conv4_1"),H=h(32,4,1,"pnet/conv4_2");return Object(q.a)(Object(q.a)({},P),{conv4_1:B,conv4_2:H})}function A(){var P=b([3,28,48,64],"rnet",!0),B=v(576,128,"rnet/fc1"),H=y(128,"rnet/prelu4_alpha"),Y=v(128,2,"rnet/fc2_1"),Q=v(128,4,"rnet/fc2_2");return Object(q.a)(Object(q.a)({},P),{fc1:B,prelu4_alpha:H,fc2_1:Y,fc2_2:Q})}function O(){var P=b([3,32,64,64],"onet"),B=h(64,128,2,"onet/conv4"),H=y(128,"onet/prelu4_alpha"),Y=v(1152,256,"onet/fc1"),Q=y(256,"onet/prelu5_alpha"),ue=v(256,2,"onet/fc2_1"),le=v(256,4,"onet/fc2_2"),_e=v(256,10,"onet/fc2_3");return Object(q.a)(Object(q.a)({},P),{conv4:B,prelu4_alpha:H,fc1:Y,prelu5_alpha:Q,fc2_1:ue,fc2_2:le,fc2_3:_e})}return{extractPNetParams:T,extractRNetParams:A,extractONetParams:O}}function Ds(p){var l=Yn(p),h=l.extractWeights,v=l.getRemainingWeights,y=[],b=Ts(h,y),T=b.extractPNetParams,A=b.extractRNetParams,O=b.extractONetParams,P=T(),B=A(),H=O();if(v().length!==0)throw new Error("weights remaing after extract: "+v().length);return{params:{pnet:P,rnet:B,onet:H},paramMappings:y}}function gr(p,l){var h=vr(p,l);function v(B){var H=h(B+"/weights",4,B+"/filters"),Y=h(B+"/bias",1);return{filters:H,bias:Y}}function y(B){var H=h(B+"/weights",2),Y=h(B+"/bias",1);return{weights:H,bias:Y}}function b(B){return h(B,1)}function T(B){var H=v(B+"/conv1"),Y=b(B+"/prelu1_alpha"),Q=v(B+"/conv2"),ue=b(B+"/prelu2_alpha"),le=v(B+"/conv3"),_e=b(B+"/prelu3_alpha");return{conv1:H,prelu1_alpha:Y,conv2:Q,prelu2_alpha:ue,conv3:le,prelu3_alpha:_e}}function A(){var B=T("pnet"),H=v("pnet/conv4_1"),Y=v("pnet/conv4_2");return Object(q.a)(Object(q.a)({},B),{conv4_1:H,conv4_2:Y})}function O(){var B=T("rnet"),H=y("rnet/fc1"),Y=b("rnet/prelu4_alpha"),Q=y("rnet/fc2_1"),ue=y("rnet/fc2_2");return Object(q.a)(Object(q.a)({},B),{fc1:H,prelu4_alpha:Y,fc2_1:Q,fc2_2:ue})}function P(){var B=T("onet"),H=v("onet/conv4"),Y=b("onet/prelu4_alpha"),Q=y("onet/fc1"),ue=b("onet/prelu5_alpha"),le=y("onet/fc2_1"),_e=y("onet/fc2_2"),De=y("onet/fc2_3");return Object(q.a)(Object(q.a)({},B),{conv4:H,prelu4_alpha:Y,fc1:Q,prelu5_alpha:ue,fc2_1:le,fc2_2:_e,fc2_3:De})}return{extractPNetParams:A,extractRNetParams:O,extractONetParams:P}}function Oi(p){var l=[],h=gr(p,l),v=h.extractPNetParams,y=h.extractRNetParams,b=h.extractONetParams,T=v(),A=y(),O=b();return sr(p,l),{params:{pnet:T,rnet:A,onet:O},paramMappings:l}}function Yo(p,l){var h=l[0],v=l[1];return{height:Math.floor(h*p),width:Math.floor(v*p)}}function $o(p,l,h){for(var v=h[0],y=h[1],b=so/p,T=[],A=Math.min(v,y)*b,O=0;A>=12;)T.push(b*Math.pow(l,O)),A=A*l,O+=1;return T}var Rr=function(p){Object(q.c)(l,p);function l(h,v,y,b){return p.call(this,{left:h,top:v,right:y,bottom:b},!0)||this}return l}(gn);function Ii(p){return k.L(function(){return k.t(k.F(p,k.y(127.5)),k.y(.0078125))})}function ua(p,l){return k.L(function(){return k.c(k.w(p),k.t(l,k.u(k.w(k.u(p)))))})}function Jo(p,l,h){return h===void 0&&(h=!1),k.L(function(){var v=Vn(p,l.conv1,"valid");return v=ua(v,l.prelu1_alpha),v=k.s(v,h?[2,2]:[3,3],[2,2],"same"),v=Vn(v,l.conv2,"valid"),v=ua(v,l.prelu2_alpha),v=h?v:k.s(v,[3,3],[2,2],"valid"),v=Vn(v,l.conv3,"valid"),v=ua(v,l.prelu3_alpha),v})}function Ns(p,l){return k.L(function(){var h=Jo(p,l,!0),v=Vn(h,l.conv4_1,"valid"),y=k.m(k.r(v,3),3),b=k.D(k.F(v,y),3),T=Vn(h,l.conv4_2,"valid");return{prob:b,regions:T}})}function ks(p,l){return k.L(function(){var h=Yo(l,p.shape.slice(1)),v=h.height,y=h.width,b=k.o.resizeBilinear(p,[v,y]),T=Ii(b);return k.N(T,[0,2,1,3])})}function Ss(p,l,h,v){for(var y=[],b=p.arraySync(),T=0;T<p.shape[0];T++)for(var A=0;A<p.shape[1];A++)b[T][A]>=v&&y.push(new et(A,T));var O=y.map(function(P){var B=new Rn(Math.round((P.y*io+1)/h),Math.round((P.x*io+1)/h),Math.round((P.y*io+so)/h),Math.round((P.x*io+so)/h)),H=b[P.y][P.x],Y=l.arraySync(),Q=new Rr(Y[P.y][P.x][0],Y[P.y][P.x][1],Y[P.y][P.x][2],Y[P.y][P.x][3]);return{cell:B,score:H,region:Q}});return O}function Os(p,l,h,v,y){y.stage1=[];var b=l.map(function(Y){return k.L(function(){var Q={scale:Y},ue=ks(p,Y),le=Date.now(),_e=Ns(ue,v),De=_e.prob,Ue=_e.regions;Q.pnet=Date.now()-le;var Fe=k.O(k.O(De,3)[1])[0],we=k.O(Ue)[0];return{scoresTensor:Fe,regionsTensor:we,scale:Y,statsForScale:Q}})}),T=b.map(function(Y){var Q=Y.scoresTensor,ue=Y.regionsTensor,le=Y.scale,_e=Y.statsForScale,De=Ss(Q,ue,le,h);if(Q.dispose(),ue.dispose(),!De.length)return y.stage1.push(_e),[];var Ue=Date.now(),Fe=$(De.map(function(we){return we.cell}),De.map(function(we){return we.score}),.5);return _e.nms=Date.now()-Ue,_e.numBoxes=Fe.length,y.stage1.push(_e),Fe.map(function(we){return De[we]})}),A=T.reduce(function(Y,Q){return Y.concat(Q)},[]),O=[],P=[];if(A.length>0){var B=Date.now(),H=$(A.map(function(Y){return Y.cell}),A.map(function(Y){return Y.score}),.7);y.stage1_nms=Date.now()-B,P=H.map(function(Y){return A[Y].score}),O=H.map(function(Y){return A[Y]}).map(function(Y){var Q=Y.cell,ue=Y.region;return new Rn(Q.left+ue.left*Q.width,Q.top+ue.top*Q.height,Q.right+ue.right*Q.width,Q.bottom+ue.bottom*Q.height).toSquare().round()})}return{boxes:O,scores:P}}function Qo(p,l,h){var v=h.width,y=h.height;return Object(q.b)(this,void 0,void 0,function(){var b,T,A,O=this;return Object(q.d)(this,function(P){switch(P.label){case 0:return b=Kn(p),[4,Promise.all(l.map(function(B){return Object(q.b)(O,void 0,void 0,function(){var H,Y,Q,ue,le,_e,De,Ue;return Object(q.d)(this,function(Fe){return H=B.padAtBorders(p.height,p.width),Y=H.y,Q=H.ey,ue=H.x,le=H.ex,_e=ue-1,De=Y-1,Ue=b.getImageData(_e,De,le-_e,Q-De),[2,vn.isNodejs()?fr(Ue):createImageBitmap(Ue)]})})}))];case 1:return T=P.sent(),A=[],T.forEach(function(B){var H=Tn({width:v,height:y}),Y=Kn(H);Y.drawImage(B,0,0,v,y);for(var Q=Y.getImageData(0,0,v,y).data,ue=[],le=0;le<Q.length;le+=4)ue.push(Q[le+2]),ue.push(Q[le+1]),ue.push(Q[le]);A.push(ue)}),[2,A.map(function(B){var H=k.L(function(){var Y=k.N(k.K(B,[1,v,y,3]),[0,2,1,3]).toFloat();return Ii(Y)});return H})]}})})}function uo(p,l){return k.L(function(){var h=Jo(p,l),v=k.x(h,[h.shape[0],l.fc1.weights.shape[0]]),y=Mn(v,l.fc1),b=ua(y,l.prelu4_alpha),T=Mn(b,l.fc2_1),A=k.m(k.r(T,1),1),O=k.D(k.F(T,A),1),P=Mn(b,l.fc2_2),B=k.O(O,1)[1];return{scores:B,regions:P}})}function Mi(p,l,h,v,y){return Object(q.b)(this,void 0,void 0,function(){var b,T,A,O,P,B,H,Y,Q,ue,le,_e,De,Ue;return Object(q.d)(this,function(Fe){switch(Fe.label){case 0:return b=Date.now(),[4,Qo(p,l,{width:24,height:24})];case 1:return T=Fe.sent(),y.stage2_extractImagePatches=Date.now()-b,b=Date.now(),A=T.map(function(we){var Ne=uo(we,v);return we.dispose(),Ne}),y.stage2_rnet=Date.now()-b,O=A.length>1?k.h(A.map(function(we){return we.scores})):A[0].scores,H=(B=Array).from,[4,O.data()];case 2:return P=H.apply(B,[Fe.sent()]),O.dispose(),Y=P.map(function(we,Ne){return{score:we,idx:Ne}}).filter(function(we){return we.score>h}).map(function(we){var Ne=we.idx;return Ne}),Q=Y.map(function(we){return l[we]}),ue=Y.map(function(we){return P[we]}),le=[],_e=[],Q.length>0&&(b=Date.now(),De=$(Q,ue,.7),y.stage2_nms=Date.now()-b,Ue=De.map(function(we){var Ne=A[Y[we]].regions.arraySync();return new Rr(Ne[0][0],Ne[0][1],Ne[0][2],Ne[0][3])}),_e=De.map(function(we){return ue[we]}),le=De.map(function(we,Ne){return Q[we].calibrate(Ue[Ne])})),A.forEach(function(we){we.regions.dispose(),we.scores.dispose()}),[2,{boxes:le,scores:_e}]}})})}function Fi(p,l){return k.L(function(){var h=Jo(p,l);h=k.s(h,[2,2],[2,2],"same"),h=Vn(h,l.conv4,"valid"),h=ua(h,l.prelu4_alpha);var v=k.x(h,[h.shape[0],l.fc1.weights.shape[0]]),y=Mn(v,l.fc1),b=ua(y,l.prelu5_alpha),T=Mn(b,l.fc2_1),A=k.m(k.r(T,1),1),O=k.D(k.F(T,A),1),P=Mn(b,l.fc2_2),B=Mn(b,l.fc2_3),H=k.O(O,1)[1];return{scores:H,regions:P,points:B}})}function Ar(p,l,h,v,y){return Object(q.b)(this,void 0,void 0,function(){var b,T,A,O,P,B,H,Y,Q,ue,le,_e,De,Ue,Fe;return Object(q.d)(this,function(we){switch(we.label){case 0:return b=Date.now(),[4,Qo(p,l,{width:48,height:48})];case 1:return T=we.sent(),y.stage3_extractImagePatches=Date.now()-b,b=Date.now(),A=T.map(function(Ne){var Ze=Fi(Ne,v);return Ne.dispose(),Ze}),y.stage3_onet=Date.now()-b,O=A.length>1?k.h(A.map(function(Ne){return Ne.scores})):A[0].scores,H=(B=Array).from,[4,O.data()];case 2:return P=H.apply(B,[we.sent()]),O.dispose(),Y=P.map(function(Ne,Ze){return{score:Ne,idx:Ze}}).filter(function(Ne){return Ne.score>h}).map(function(Ne){var Ze=Ne.idx;return Ze}),Q=Y.map(function(Ne){var Ze=A[Ne].regions.arraySync();return new Rr(Ze[0][0],Ze[0][1],Ze[0][2],Ze[0][3])}),ue=Y.map(function(Ne,Ze){return l[Ne].calibrate(Q[Ze])}),le=Y.map(function(Ne){return P[Ne]}),_e=[],De=[],Ue=[],ue.length>0&&(b=Date.now(),Fe=$(ue,le,.7,!1),y.stage3_nms=Date.now()-b,_e=Fe.map(function(Ne){return ue[Ne]}),De=Fe.map(function(Ne){return le[Ne]}),Ue=Fe.map(function(Ne,Ze){return Array(5).fill(0).map(function(Bt,Yt){var At=A[Ne].points.arraySync();return new et(At[0][Yt]*(_e[Ze].width+1)+_e[Ze].left,At[0][Yt+5]*(_e[Ze].height+1)+_e[Ze].top)})})),A.forEach(function(Ne){Ne.regions.dispose(),Ne.scores.dispose(),Ne.points.dispose()}),[2,{boxes:_e,scores:De,points:Ue}]}})})}var zr=function(p){Object(q.c)(l,p);function l(){return p.call(this,"Mtcnn")||this}return l.prototype.load=function(h){return Object(q.b)(this,void 0,void 0,function(){return Object(q.d)(this,function(v){return console.warn("mtcnn is deprecated and will be removed soon"),[2,p.prototype.load.call(this,h)]})})},l.prototype.loadFromDisk=function(h){return Object(q.b)(this,void 0,void 0,function(){return Object(q.d)(this,function(v){return console.warn("mtcnn is deprecated and will be removed soon"),[2,p.prototype.loadFromDisk.call(this,h)]})})},l.prototype.forwardInput=function(h,v){return v===void 0&&(v={}),Object(q.b)(this,void 0,void 0,function(){var y,b,T,A,O,P,B,H,Y,Q,ue,le,_e,De,Ue,Fe,we,Ne,Ze,Bt,Yt;return Object(q.d)(this,function(At){switch(At.label){case 0:if(y=this.params,!y)throw new Error("Mtcnn - load model before inference");if(b=h.canvases[0],!b)throw new Error("Mtcnn - inputCanvas is not defined, note that passing tensors into Mtcnn.forwardInput is not supported yet.");return T={},A=Date.now(),O=k.L(function(){return As(k.m(k.f.fromPixels(b)).toFloat())}),P=function(rt){return O.dispose(),T.total=Date.now()-A,rt},B=O.shape.slice(1),H=B[0],Y=B[1],Q=new oa(v),ue=Q.minFaceSize,le=Q.scaleFactor,_e=Q.maxNumScales,De=Q.scoreThresholds,Ue=Q.scaleSteps,Fe=(Ue||$o(ue,le,[H,Y])).filter(function(rt){var Kt=Yo(rt,[H,Y]);return Math.min(Kt.width,Kt.height)>so}).slice(0,_e),T.scales=Fe,T.pyramid=Fe.map(function(rt){return Yo(rt,[H,Y])}),we=Date.now(),[4,Os(O,Fe,De[0],y.pnet,T)];case 1:return Ne=At.sent(),T.total_stage1=Date.now()-we,Ne.boxes.length?(T.stage2_numInputBoxes=Ne.boxes.length,we=Date.now(),[4,Mi(b,Ne.boxes,De[1],y.rnet,T)]):[2,P({results:[],stats:T})];case 2:return Ze=At.sent(),T.total_stage2=Date.now()-we,Ze.boxes.length?(T.stage3_numInputBoxes=Ze.boxes.length,we=Date.now(),[4,Ar(b,Ze.boxes,De[2],y.onet,T)]):[2,P({results:[],stats:T})];case 3:return Bt=At.sent(),T.total_stage3=Date.now()-we,Yt=Bt.boxes.map(function(rt,Kt){return Ra(oe({},new _(Bt.scores[Kt],new pn(rt.left/Y,rt.top/H,rt.width/Y,rt.height/H),{height:H,width:Y})),new No(Bt.points[Kt].map(function(on){return on.sub(new et(rt.left,rt.top)).div(new et(rt.width,rt.height))}),{width:rt.width,height:rt.height}))}),[2,P({results:Yt,stats:T})]}})})},l.prototype.forward=function(h,v){return v===void 0&&(v={}),Object(q.b)(this,void 0,void 0,function(){var y;return Object(q.d)(this,function(b){switch(b.label){case 0:return y=this.forwardInput,[4,Zt(h)];case 1:return[4,y.apply(this,[b.sent(),v])];case 2:return[2,b.sent().results]}})})},l.prototype.forwardWithStats=function(h,v){return v===void 0&&(v={}),Object(q.b)(this,void 0,void 0,function(){var y;return Object(q.d)(this,function(b){switch(b.label){case 0:return y=this.forwardInput,[4,Zt(h)];case 1:return[2,y.apply(this,[b.sent(),v])]}})})},l.prototype.getDefaultModelName=function(){return"mtcnn_model"},l.prototype.extractParamsFromWeigthMap=function(h){return Oi(h)},l.prototype.extractParams=function(h){return Ds(h)},l}(ir),Is=.4,co=[new et(1.603231,2.094468),new et(6.041143,7.080126),new et(2.882459,3.518061),new et(4.266906,5.178857),new et(9.041765,10.66308)],Ms=[117.001,114.697,97.404],Na=function(p){Object(q.c)(l,p);function l(){var h=this,v={withSeparableConvs:!0,iouThreshold:Is,classes:["face"],anchors:co,meanRgb:Ms,isFirstLayerConv2d:!0,filterSizes:[3,16,32,64,128,256,512]};return h=p.call(this,v)||this,h}return Object.defineProperty(l.prototype,"anchors",{get:function(){return this.config.anchors},enumerable:!0,configurable:!0}),l.prototype.locateFaces=function(h,v){return Object(q.b)(this,void 0,void 0,function(){var y;return Object(q.d)(this,function(b){switch(b.label){case 0:return[4,this.detect(h,v)];case 1:return y=b.sent(),[2,y.map(function(T){return new _(T.score,T.relativeBox,{width:T.imageWidth,height:T.imageHeight})})]}})})},l.prototype.getDefaultModelName=function(){return"tiny_face_detector_model"},l.prototype.extractParamsFromWeigthMap=function(h){return p.prototype.extractParamsFromWeigthMap.call(this,h)},l}(Da),xt={ssdMobilenetv1:new _r,tinyFaceDetector:new Na,tinyYolov2:new ro,mtcnn:new zr,faceLandmark68Net:new en,faceLandmark68TinyNet:new Xu,faceRecognitionNet:new aa,faceExpressionNet:new xi,ageGenderNet:new Gu},lo=function(p,l){return xt.ssdMobilenetv1.locateFaces(p,l)},Fs=function(p,l){return xt.tinyFaceDetector.locateFaces(p,l)},Ps=function(p,l){return xt.tinyYolov2.locateFaces(p,l)},Pi=function(p,l){return xt.mtcnn.forward(p,l)},Zu=function(p){return xt.faceLandmark68Net.detectLandmarks(p)},Li=function(p){return xt.faceLandmark68TinyNet.detectLandmarks(p)},Zo=function(p){return xt.faceRecognitionNet.computeFaceDescriptor(p)},Ls=function(p){return xt.faceExpressionNet.predictExpressions(p)},Bs=function(p){return xt.ageGenderNet.predictAgeAndGender(p)},ka=function(p){return xt.ssdMobilenetv1.load(p)},ec=function(p){return xt.tinyFaceDetector.load(p)},js=function(p){return xt.mtcnn.load(p)},Bi=function(p){return xt.tinyYolov2.load(p)},ho=function(p){return xt.faceLandmark68Net.load(p)},Us=function(p){return xt.faceLandmark68TinyNet.load(p)},ji=function(p){return xt.faceRecognitionNet.load(p)},Ui=function(p){return xt.faceExpressionNet.load(p)},Wi=function(p){return xt.ageGenderNet.load(p)},td=ka,nd=lo,rd=Zu,Ws=function(p){Object(q.c)(l,p);function l(h,v,y){var b=p.call(this)||this;return b.parentTask=h,b.input=v,b.extractedFaces=y,b}return l}(Je),zi=function(p){Object(q.c)(l,p);function l(){return p!==null&&p.apply(this,arguments)||this}return l.prototype.run=function(){return Object(q.b)(this,void 0,void 0,function(){var h,v,y=this;return Object(q.d)(this,function(b){switch(b.label){case 0:return[4,this.parentTask];case 1:return h=b.sent(),[4,ao(h,this.input,function(T){return Object(q.b)(y,void 0,void 0,function(){return Object(q.d)(this,function(A){switch(A.label){case 0:return[4,Promise.all(T.map(function(O){return xt.faceExpressionNet.predictExpressions(O)}))];case 1:return[2,A.sent()]}})})},this.extractedFaces)];case 2:return v=b.sent(),[2,h.map(function(T,A){return ra(T,v[A])})]}})})},l.prototype.withAgeAndGender=function(){return new ti(this,this.input)},l}(Ws),ei=function(p){Object(q.c)(l,p);function l(){return p!==null&&p.apply(this,arguments)||this}return l.prototype.run=function(){return Object(q.b)(this,void 0,void 0,function(){var h,v;return Object(q.d)(this,function(y){switch(y.label){case 0:return[4,this.parentTask];case 1:return h=y.sent(),h?[4,oo(h,this.input,function(b){return xt.faceExpressionNet.predictExpressions(b)},this.extractedFaces)]:[2];case 2:return v=y.sent(),[2,ra(h,v)]}})})},l.prototype.withAgeAndGender=function(){return new po(this,this.input)},l}(Ws),ca=function(p){Object(q.c)(l,p);function l(){return p!==null&&p.apply(this,arguments)||this}return l.prototype.withAgeAndGender=function(){return new fo(this,this.input)},l.prototype.withFaceDescriptors=function(){return new tn(this,this.input)},l}(zi),la=function(p){Object(q.c)(l,p);function l(){return p!==null&&p.apply(this,arguments)||this}return l.prototype.withAgeAndGender=function(){return new re(this,this.input)},l.prototype.withFaceDescriptor=function(){return new nt(this,this.input)},l}(ei),Sa=function(p){Object(q.c)(l,p);function l(h,v,y){var b=p.call(this)||this;return b.parentTask=h,b.input=v,b.extractedFaces=y,b}return l}(Je),ti=function(p){Object(q.c)(l,p);function l(){return p!==null&&p.apply(this,arguments)||this}return l.prototype.run=function(){return Object(q.b)(this,void 0,void 0,function(){var h,v,y=this;return Object(q.d)(this,function(b){switch(b.label){case 0:return[4,this.parentTask];case 1:return h=b.sent(),[4,ao(h,this.input,function(T){return Object(q.b)(y,void 0,void 0,function(){return Object(q.d)(this,function(A){switch(A.label){case 0:return[4,Promise.all(T.map(function(O){return xt.ageGenderNet.predictAgeAndGender(O)}))];case 1:return[2,A.sent()]}})})},this.extractedFaces)];case 2:return v=b.sent(),[2,h.map(function(T,A){var O=v[A],P=O.age,B=O.gender,H=O.genderProbability;return kn(Gn(T,B,H),P)})]}})})},l.prototype.withFaceExpressions=function(){return new zi(this,this.input)},l}(Sa),po=function(p){Object(q.c)(l,p);function l(){return p!==null&&p.apply(this,arguments)||this}return l.prototype.run=function(){return Object(q.b)(this,void 0,void 0,function(){var h,v,y,b,T;return Object(q.d)(this,function(A){switch(A.label){case 0:return[4,this.parentTask];case 1:return h=A.sent(),h?[4,oo(h,this.input,function(O){return xt.ageGenderNet.predictAgeAndGender(O)},this.extractedFaces)]:[2];case 2:return v=A.sent(),y=v.age,b=v.gender,T=v.genderProbability,[2,kn(Gn(h,b,T),y)]}})})},l.prototype.withFaceExpressions=function(){return new ei(this,this.input)},l}(Sa),fo=function(p){Object(q.c)(l,p);function l(){return p!==null&&p.apply(this,arguments)||this}return l.prototype.withFaceExpressions=function(){return new ca(this,this.input)},l.prototype.withFaceDescriptors=function(){return new tn(this,this.input)},l}(ti),re=function(p){Object(q.c)(l,p);function l(){return p!==null&&p.apply(this,arguments)||this}return l.prototype.withFaceExpressions=function(){return new la(this,this.input)},l.prototype.withFaceDescriptor=function(){return new nt(this,this.input)},l}(po),dr=function(p){Object(q.c)(l,p);function l(h,v){var y=p.call(this)||this;return y.parentTask=h,y.input=v,y}return l}(Je),tn=function(p){Object(q.c)(l,p);function l(){return p!==null&&p.apply(this,arguments)||this}return l.prototype.run=function(){return Object(q.b)(this,void 0,void 0,function(){var h,v;return Object(q.d)(this,function(y){switch(y.label){case 0:return[4,this.parentTask];case 1:return h=y.sent(),[4,ao(h,this.input,function(b){return Promise.all(b.map(function(T){return xt.faceRecognitionNet.computeFaceDescriptor(T)}))},null,function(b){return b.landmarks.align(null,{useDlibAlignment:!0})})];case 2:return v=y.sent(),[2,v.map(function(b,T){return Xo(h[T],b)})]}})})},l.prototype.withFaceExpressions=function(){return new ca(this,this.input)},l.prototype.withAgeAndGender=function(){return new fo(this,this.input)},l}(dr),nt=function(p){Object(q.c)(l,p);function l(){return p!==null&&p.apply(this,arguments)||this}return l.prototype.run=function(){return Object(q.b)(this,void 0,void 0,function(){var h,v;return Object(q.d)(this,function(y){switch(y.label){case 0:return[4,this.parentTask];case 1:return h=y.sent(),h?[4,oo(h,this.input,function(b){return xt.faceRecognitionNet.computeFaceDescriptor(b)},null,function(b){return b.landmarks.align(null,{useDlibAlignment:!0})})]:[2];case 2:return v=y.sent(),[2,Xo(h,v)]}})})},l.prototype.withFaceExpressions=function(){return new la(this,this.input)},l.prototype.withAgeAndGender=function(){return new re(this,this.input)},l}(dr),Vr=function(p){Object(q.c)(l,p);function l(h,v,y){var b=p.call(this)||this;return b.parentTask=h,b.input=v,b.useTinyLandmarkNet=y,b}return Object.defineProperty(l.prototype,"landmarkNet",{get:function(){return this.useTinyLandmarkNet?xt.faceLandmark68TinyNet:xt.faceLandmark68Net},enumerable:!0,configurable:!0}),l}(Je),Oa=function(p){Object(q.c)(l,p);function l(){return p!==null&&p.apply(this,arguments)||this}return l.prototype.run=function(){return Object(q.b)(this,void 0,void 0,function(){var h,v,y,b,T,A=this;return Object(q.d)(this,function(O){switch(O.label){case 0:return[4,this.parentTask];case 1:return h=O.sent(),v=h.map(function(P){return P.detection}),this.input instanceof k.a?[4,_a(this.input,v)]:[3,3];case 2:return b=O.sent(),[3,5];case 3:return[4,Lr(this.input,v)];case 4:b=O.sent(),O.label=5;case 5:return y=b,[4,Promise.all(y.map(function(P){return A.landmarkNet.detectLandmarks(P)}))];case 6:return T=O.sent(),y.forEach(function(P){return P instanceof k.a&&P.dispose()}),[2,h.map(function(P,B){return Ra(P,T[B])})]}})})},l.prototype.withFaceExpressions=function(){return new ca(this,this.input)},l.prototype.withAgeAndGender=function(){return new fo(this,this.input)},l.prototype.withFaceDescriptors=function(){return new tn(this,this.input)},l}(Vr),Tr=function(p){Object(q.c)(l,p);function l(){return p!==null&&p.apply(this,arguments)||this}return l.prototype.run=function(){return Object(q.b)(this,void 0,void 0,function(){var h,v,y,b,T;return Object(q.d)(this,function(A){switch(A.label){case 0:return[4,this.parentTask];case 1:return h=A.sent(),h?(v=h.detection,this.input instanceof k.a?[4,_a(this.input,[v])]:[3,3]):[2];case 2:return b=A.sent(),[3,5];case 3:return[4,Lr(this.input,[v])];case 4:b=A.sent(),A.label=5;case 5:return y=b,[4,this.landmarkNet.detectLandmarks(y[0])];case 6:return T=A.sent(),y.forEach(function(O){return O instanceof k.a&&O.dispose()}),[2,Ra(h,T)]}})})},l.prototype.withFaceExpressions=function(){return new la(this,this.input)},l.prototype.withAgeAndGender=function(){return new re(this,this.input)},l.prototype.withFaceDescriptor=function(){return new nt(this,this.input)},l}(Vr),da=function(p){Object(q.c)(l,p);function l(h,v){v===void 0&&(v=new sa);var y=p.call(this)||this;return y.input=h,y.options=v,y}return l}(Je),vo=function(p){Object(q.c)(l,p);function l(){return p!==null&&p.apply(this,arguments)||this}return l.prototype.run=function(){return Object(q.b)(this,void 0,void 0,function(){var h,v,y,b;return Object(q.d)(this,function(T){switch(T.label){case 0:return h=this,v=h.input,y=h.options,y instanceof oa?[4,xt.mtcnn.forward(v,y)]:[3,2];case 1:return[2,T.sent().map(function(A){return A.detection})];case 2:if(b=y instanceof Si?function(A){return xt.tinyFaceDetector.locateFaces(A,y)}:y instanceof sa?function(A){return xt.ssdMobilenetv1.locateFaces(A,y)}:y instanceof lr?function(A){return xt.tinyYolov2.locateFaces(A,y)}:null,!b)throw new Error("detectFaces - expected options to be instance of TinyFaceDetectorOptions | SsdMobilenetv1Options | MtcnnOptions | TinyYolov2Options");return[2,b(v)]}})})},l.prototype.runAndExtendWithFaceDetections=function(){var h=this;return new Promise(function(v){return Object(q.b)(h,void 0,void 0,function(){var y;return Object(q.d)(this,function(b){switch(b.label){case 0:return[4,this.run()];case 1:return y=b.sent(),[2,v(y.map(function(T){return oe({},T)}))]}})})})},l.prototype.withFaceLandmarks=function(h){return h===void 0&&(h=!1),new Oa(this.runAndExtendWithFaceDetections(),this.input,h)},l.prototype.withFaceExpressions=function(){return new zi(this.runAndExtendWithFaceDetections(),this.input)},l.prototype.withAgeAndGender=function(){return new ti(this.runAndExtendWithFaceDetections(),this.input)},l}(da),mo=function(p){Object(q.c)(l,p);function l(){return p!==null&&p.apply(this,arguments)||this}return l.prototype.run=function(){return Object(q.b)(this,void 0,void 0,function(){var h,v;return Object(q.d)(this,function(y){switch(y.label){case 0:return[4,new vo(this.input,this.options)];case 1:return h=y.sent(),v=h[0],h.forEach(function(b){b.score>v.score&&(v=b)}),[2,v]}})})},l.prototype.runAndExtendWithFaceDetection=function(){var h=this;return new Promise(function(v){return Object(q.b)(h,void 0,void 0,function(){var y;return Object(q.d)(this,function(b){switch(b.label){case 0:return[4,this.run()];case 1:return y=b.sent(),[2,v(y?oe({},y):void 0)]}})})})},l.prototype.withFaceLandmarks=function(h){return h===void 0&&(h=!1),new Tr(this.runAndExtendWithFaceDetection(),this.input,h)},l.prototype.withFaceExpressions=function(){return new ei(this.runAndExtendWithFaceDetection(),this.input)},l.prototype.withAgeAndGender=function(){return new po(this.runAndExtendWithFaceDetection(),this.input)},l}(da);function Ia(p,l){return l===void 0&&(l=new sa),new mo(p,l)}function Dr(p,l){return l===void 0&&(l=new sa),new vo(p,l)}function Ma(p,l){return Object(q.b)(this,void 0,void 0,function(){return Object(q.d)(this,function(h){switch(h.label){case 0:return console.warn("allFacesSsdMobilenetv1 is deprecated and will be removed soon, use the high level api instead"),[4,Dr(p,new sa(l?{minConfidence:l}:{})).withFaceLandmarks().withFaceDescriptors()];case 1:return[2,h.sent()]}})})}function ha(p,l){return l===void 0&&(l={}),Object(q.b)(this,void 0,void 0,function(){return Object(q.d)(this,function(h){switch(h.label){case 0:return console.warn("allFacesTinyYolov2 is deprecated and will be removed soon, use the high level api instead"),[4,Dr(p,new lr(l)).withFaceLandmarks().withFaceDescriptors()];case 1:return[2,h.sent()]}})})}function Bn(p,l){return l===void 0&&(l={}),Object(q.b)(this,void 0,void 0,function(){return Object(q.d)(this,function(h){switch(h.label){case 0:return console.warn("allFacesMtcnn is deprecated and will be removed soon, use the high level api instead"),[4,Dr(p,new oa(l)).withFaceLandmarks().withFaceDescriptors()];case 1:return[2,h.sent()]}})})}var ni=Ma;function ri(p,l){if(p.length!==l.length)throw new Error("euclideanDistance: arr1.length !== arr2.length");var h=Array.from(p),v=Array.from(l);return Math.sqrt(h.map(function(y,b){return y-v[b]}).reduce(function(y,b){return y+Math.pow(b,2)},0))}var go=function(){function p(l,h){h===void 0&&(h=.6),this._distanceThreshold=h;var v=Array.isArray(l)?l:[l];if(!v.length)throw new Error("FaceRecognizer.constructor - expected atleast one input");var y=1,b=function(){return"person "+y++};this._labeledDescriptors=v.map(function(T){if(T instanceof br)return T;if(T instanceof Float32Array)return new br(b(),[T]);if(T.descriptor&&T.descriptor instanceof Float32Array)return new br(b(),[T.descriptor]);throw new Error("FaceRecognizer.constructor - expected inputs to be of type LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array | Array<LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array>")})}return Object.defineProperty(p.prototype,"labeledDescriptors",{get:function(){return this._labeledDescriptors},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"distanceThreshold",{get:function(){return this._distanceThreshold},enumerable:!0,configurable:!0}),p.prototype.computeMeanDistance=function(l,h){return h.map(function(v){return ri(v,l)}).reduce(function(v,y){return v+y},0)/(h.length||1)},p.prototype.matchDescriptor=function(l){var h=this;return this.labeledDescriptors.map(function(v){var y=v.descriptors,b=v.label;return new Qr(b,h.computeMeanDistance(l,y))}).reduce(function(v,y){return v.distance<y.distance?v:y})},p.prototype.findBestMatch=function(l){var h=this.matchDescriptor(l);return h.distance<this.distanceThreshold?h:new Qr("unknown",h.distance)},p.prototype.toJSON=function(){return{distanceThreshold:this.distanceThreshold,labeledDescriptors:this.labeledDescriptors.map(function(l){return l.toJSON()})}},p.fromJSON=function(l){var h=l.labeledDescriptors.map(function(v){return br.fromJSON(v)});return new p(h,l.distanceThreshold)},p}();function Vi(p){var l=new zr;return l.extractWeights(p),l}function ad(p){var l=new Na;return l.extractWeights(p),l}function yo(p,l){var h=new lt(l.width,l.height),v=h.width,y=h.height;if(v<=0||y<=0)throw new Error("resizeResults - invalid dimensions: "+JSON.stringify({width:v,height:y}));if(Array.isArray(p))return p.map(function(A){return yo(A,{width:v,height:y})});if(Qa(p)){var b=p.detection.forSize(v,y),T=p.unshiftedLandmarks.forSize(b.box.width,b.box.height);return Ra(oe(p,b),T)}return In(p)?oe(p,p.detection.forSize(v,y)):p instanceof Un||p instanceof _?p.forSize(v,y):p}var Gi=te("ErOA"),zs=te("IO3U"),Vs=te.n(zs),Gs=te("m3rI"),Hs=function(l,h){for(var v=l.split(","),y=v[0].match(/:(.*?);/)[1],b=atob(v[1]),T=b.length,A=new Uint8Array(T);T--;)A[T]=b.charCodeAt(T);return new Blob([A],{type:y})},ai=function(){var p=Object(tt.a)(Pe.a.mark(function l(h){return Pe.a.wrap(function(y){for(;;)switch(y.prev=y.next){case 0:return y.abrupt("return",new Promise(function(b,T){var A=new Image;(h==null?void 0:h.indexOf("educoder.net"))>-1?A.setAttribute("crossOrigin","educoder.net"):A.setAttribute("crossOrigin","aliyuncs.com"),A.onload=function(){var O=document.createElement("canvas");O.width=this.naturalWidth,O.height=this.naturalHeight,O.getContext("2d").drawImage(A,0,0);var P=O.toDataURL("image/png");b(P)},A.src=h,A.onerror=function(){T(new Error("\u56FE\u7247\u6D41\u5F02\u5E38")),ot.b.error("\u60A8\u7684\u8EAB\u4EFD\u7167\u7247\u5F02\u5E38\uFF0C\u8BF7\u62CD\u7167\u540E\u63D0\u4EA4\u81F3\u4EBA\u5DE5\u5BA1\u6838")}}));case 1:case"end":return y.stop()}},l)}));return function(h){return p.apply(this,arguments)}}(),oi=Object(Ge.forwardRef)(function(p,l){var h=p.outputResult,v=p.identity_url,y=p.onCameraReady,b=p.defaultOpen,T=Object(Ye.i)(),A=window.ENV==="build"?"/react/build/weights":"/weights",O=Object(Ge.useRef)(),P=Object(Ge.useRef)(),B=Object(Ge.useRef)(),H=Object(Ge.useRef)(!1),Y=Object(Ge.useRef)(),Q=Object(Ge.useState)(!0),ue=Object(Ve.a)(Q,2),le=ue[0],_e=ue[1],De=Object(Ge.useState)(""),Ue=Object(Ve.a)(De,2),Fe=Ue[0],we=Ue[1],Ne=Object(Ge.useState)(""),Ze=Object(Ve.a)(Ne,2),Bt=Ze[0],Yt=Ze[1],At=Object(Ge.useRef)(!1),rt=Object(Ge.useRef)(""),Kt=Object(Ge.useState)(!0),on=Object(Ve.a)(Kt,1),nn=on[0],dt=.5,zn=224,Ie="\u5BA1\u6838\u5931\u8D25",Sn=Object(Ge.useMemo)(function(){return new Si({inputSize:zn,scoreThreshold:dt})},[]),Ot=function(){var bt=Object(tt.a)(Pe.a.mark(function yt(){return Pe.a.wrap(function(Lt){for(;;)switch(Lt.prev=Lt.next){case 0:return Lt.next=2,ec(A);case 2:return Lt.next=4,ho(A);case 4:return Lt.next=6,ji(A);case 6:ct(!0);case 7:case"end":return Lt.stop()}},yt)}));return function(){return bt.apply(this,arguments)}}();Object(Ge.useEffect)(function(){b&&Ot()},[b]),Object(Ge.useImperativeHandle)(l,function(){return{handleStop:He,handleRemove:jt,handlePlay:ct,startDiscern:pa,handleUploadImage:kr}});var sn=function(){var bt=Object(tt.a)(Pe.a.mark(function yt(ft){return Pe.a.wrap(function(wt){for(;;)switch(wt.prev=wt.next){case 0:if(O.current){wt.next=3;break}return setTimeout(function(){return sn(ft)}),wt.abrupt("return");case 3:navigator.mediaDevices.getUserMedia({video:{width:640,height:360}}).then(function(){var Tt=Object(tt.a)(Pe.a.mark(function Gt(Gr){var Sr;return Pe.a.wrap(function(un){for(;;)switch(un.prev=un.next){case 0:if("srcObject"in O.current?O.current.srcObject=Gr:O.current.src=window.URL.createObjectURL(Gr),O.current.onloadedmetadata=function($s){_e(!1),O.current.play()},!ft){un.next=10;break}return Sr=document.createElement("img"),un.next=6,ai(v+"?t="+new Date().getTime());case 6:return Sr.src=un.sent,un.next=9,Ia(Sr,Sn).withFaceLandmarks().withFaceDescriptor();case 9:Y.current=un.sent;case 10:case"end":return un.stop()}},Gt)}));return function(Gt){return Tt.apply(this,arguments)}}()).catch(function(Tt){console.log("err:",Tt,Tt.message),Tt.message==="Permission denied"||Tt.name==="NotAllowedError"?ot.b.error("\u60A8\u5DF2\u62D2\u7EDD\u4E86\u83B7\u53D6\u6444\u50CF\u5934"):Tt.message!="\u56FE\u7247\u6D41\u5F02\u5E38"&&ot.b.error("\u6444\u50CF\u5934\u83B7\u53D6\u5931\u8D25\uFF0C\u6216\u60A8\u5DF2\u62D2\u7EDD\u4E86\u83B7\u53D6\u6444\u50CF\u5934")});case 4:case"end":return wt.stop()}},yt)}));return function(ft){return bt.apply(this,arguments)}}(),Nr=function(){var bt=Object(tt.a)(Pe.a.mark(function yt(ft,Lt){return Pe.a.wrap(function(Tt){for(;;)switch(Tt.prev=Tt.next){case 0:return Tt.abrupt("return",new Promise(function(){var Gt=Object(tt.a)(Pe.a.mark(function Gr(Sr){var fa,un;return Pe.a.wrap(function(ii){for(;;)switch(ii.prev=ii.next){case 0:fa=new FormData,fa.append("file",Hs(ft,"1")),fa.append("1","123"),un=new window.XMLHttpRequest,un.withCredentials=!0,un.addEventListener("load",function(si){var $i=JSON.parse(si.target.responseText);Object(Gi.a)("/api/exercises/".concat(T.categoryId,"/upload_identify_photo.json"),{method:"post",body:{attachment_id:$i.id}}),Sr($i)},!1),un.addEventListener("error",function(si){console.error(si)},!1),un.open("POST","".concat(Gs.a.API_SERVER,"/api/attachments.json")),un.send(fa);case 9:case"end":return ii.stop()}},Gr)}));return function(Gr){return Gt.apply(this,arguments)}}()));case 1:case"end":return Tt.stop()}},yt)}));return function(ft,Lt){return bt.apply(this,arguments)}}(),hr=function(){var bt=Object(tt.a)(Pe.a.mark(function yt(ft){var Lt;return Pe.a.wrap(function(Tt){for(;;)switch(Tt.prev=Tt.next){case 0:return Tt.prev=0,P.current.width=O.current.videoWidth,P.current.height=360,Lt=P.current.getContext("2d"),Tt.next=6,Lt.drawImage(O.current,0,0,P.current.width,P.current.height);case 6:rt.current=P.current.toDataURL("image/png"),ft===1&&Nr(rt.current,ft),Tt.next=12;break;case 10:Tt.prev=10,Tt.t0=Tt.catch(0);case 12:case"end":return Tt.stop()}},yt,null,[[0,10]])}));return function(ft){return bt.apply(this,arguments)}}(),kr=function(){var bt=Object(tt.a)(Pe.a.mark(function yt(ft){return Pe.a.wrap(function(wt){for(;;)switch(wt.prev=wt.next){case 0:return wt.abrupt("return",new Promise(function(){var Tt=Object(tt.a)(Pe.a.mark(function Gt(Gr){var Sr;return Pe.a.wrap(function(un){for(;;)switch(un.prev=un.next){case 0:return Sr=P.current.getContext("2d"),un.next=3,Sr.drawImage(O.current,0,0,P.current.width,P.current.height);case 3:return un.next=5,Nr(rt.current,ft);case 5:Gr();case 6:case"end":return un.stop()}},Gt)}));return function(Gt){return Tt.apply(this,arguments)}}()));case 1:case"end":return wt.stop()}},yt)}));return function(ft){return bt.apply(this,arguments)}}(),pa=function(){var bt=Object(tt.a)(Pe.a.mark(function yt(){var ft,Lt,wt;return Pe.a.wrap(function(Gt){for(;;)switch(Gt.prev=Gt.next){case 0:return H.current=!0,Gt.next=3,Ia(O.current,Sn).withFaceLandmarks().withFaceDescriptor();case 3:ft=Gt.sent,ft&&Y.current?(Lt=new go(ft),wt=Lt.findBestMatch(Y.current.descriptor),we(wt._distance<.4?"\u8BC6\u522B\u6210\u529F":Ie),hr(wt._distance<.4?1:0),setTimeout(function(){h==null||h({content:wt._distance<.4?"\u8BC6\u522B\u6210\u529F":Ie,success:wt._distance<.4})},1e3),At.current=!0):(hr(0),we(Ie),setTimeout(function(){h==null||h({content:Ie,success:!1})},1e3)),setTimeout(function(){O.current.pause()},600);case 6:case"end":return Gt.stop()}},yt)}));return function(){return bt.apply(this,arguments)}}(),Fa=function(){var bt=Object(tt.a)(Pe.a.mark(function yt(){var ft,Lt,wt;return Pe.a.wrap(function(Gt){for(;;)switch(Gt.prev=Gt.next){case 0:if(!((ft=O.current)!==null&&ft!==void 0&&ft.paused||(Lt=O.current)!==null&&Lt!==void 0&&Lt.ended)){Gt.next=2;break}return Gt.abrupt("return",setTimeout(function(){return Fa()}));case 2:return Gt.next=4,Ia(O.current,Sn).withFaceLandmarks().withFaceDescriptor();case 4:wt=Gt.sent,H.current||(H.current=!0,y(!0)),wt&&O.current?(Yt(""),Vt(O.current,B.current,[wt],nn)):Yt("\u8BF7\u5C06\u8138\u90E8\u79FB\u52A8\u81F3\u53D6\u666F\u6846\u5185"),At.current||setTimeout(function(){return Fa()});case 8:case"end":return Gt.stop()}},yt)}));return function(){return bt.apply(this,arguments)}}(),jt=function(){try{var yt=O.current.srcObject,ft=yt.getTracks();ft.forEach(function(Lt){Lt.stop()}),H.current=!1}catch(Lt){}},He=function(){_e(!1);try{H.current=!1}catch(yt){}},ct=function(yt){H.current=!1,At.current=!1,P.current.getContext("2d").clearRect(0,0,640,480),we(""),_e(!0);try{sn(yt||!1)}catch(ft){}},Vt=function(yt,ft,Lt){var wt=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!0,Tt=Xn(yt,ft,Lt);wt&&Se.drawDetections(ft,Tt.map(function(Gt){return Gt.detection}))},Xn=function(yt,ft,Lt){var wt=yt instanceof HTMLVideoElement?An(yt):yt,Tt=wt.width,Gt=wt.height;return ft.width=Tt,ft.height=Gt,yo(Lt,{width:Tt,height:Gt})};return ce.a.createElement("div",{className:Vs.a.wrp},ce.a.createElement(Qt.a,{spinning:le,tip:"\u6B63\u5728\u542F\u52A8\u6444\u50CF\u5934\uFF0C\u8BF7\u7A0D\u540E..."},ce.a.createElement("video",{onPlay:Fa,ref:O,id:"inputVideo",autoPlay:!0,muted:!0}),ce.a.createElement("canvas",{style:{zIndex:2},ref:B}),ce.a.createElement("canvas",{ref:P}),ce.a.createElement("div",{className:"c-red mt5 tc",style:{height:22}},Fe," ",Bt)))}),Hi=oi,Xs=te("2LEM"),Ks=te.n(Xs),Xi=te("LvDl"),Ki=Pt.a.Countdown,qi=Ft.a.Step,qs=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"],Yi={0:"c-red-ee4",1:"c-green"},tc=["\u5355\u9009\u9898","\u591A\u9009\u9898","\u5224\u65AD\u9898","\u586B\u7A7A\u9898","\u7B80\u7B54\u9898","\u5B9E\u8BAD\u9898","\u7F16\u7A0B\u9898"],Ys=function(l){var h,v=l.globalSetting,y=l.loading,b=l.user,T=l.exercise,A=l.dispatch,O=Object(st.a)(l,["globalSetting","loading","user","exercise","dispatch"]),P=Object(Ye.i)(),B=Object(Ge.useState)(0),H=Object(Ve.a)(B,2),Y=H[0],Q=H[1],ue=Object(Ge.useState)(!1),le=Object(Ve.a)(ue,2),_e=le[0],De=le[1],Ue=Object(Ge.useState)(!1),Fe=Object(Ve.a)(Ue,2),we=Fe[0],Ne=Fe[1],Ze=Object(Ge.useState)(!1),Bt=Object(Ve.a)(Ze,2),Yt=Bt[0],At=Bt[1],rt=Object(Ge.useState)(0),Kt=Object(Ve.a)(rt,2),on=Kt[0],nn=Kt[1],dt=Object(Ge.useState)({}),zn=Object(Ve.a)(dt,2),Ie=zn[0],Sn=zn[1],Ot=Object(Ge.useRef)(),sn=Object(Ge.useRef)(!0),Nr=[{title:"\u91C7\u96C6\u7167\u7247",content:"First-content"},{title:"\u5BA1\u6838\u7ED3\u679C",content:"Second-content"},{title:"\u5F00\u542F\u624B\u673A\u5F55\u5236",content:"Last-content"}].filter(function(jt){return Ie!=null&&Ie.open_phone_video_recording?!0:jt.content!=="Last-content"}),hr=function(){var jt=Object(tt.a)(Pe.a.mark(function He(){return Pe.a.wrap(function(Vt){for(;;)switch(Vt.prev=Vt.next){case 0:return Vt.abrupt("return",new Promise(function(){var Xn=Object(tt.a)(Pe.a.mark(function bt(yt){var ft;return Pe.a.wrap(function(wt){for(;;)switch(wt.prev=wt.next){case 0:return wt.next=2,Object(Ae.P)(Object(Mt.a)({},P));case 2:ft=wt.sent,Sn(Object(Mt.a)({},ft)),yt(ft);case 5:case"end":return wt.stop()}},bt)}));return function(bt){return Xn.apply(this,arguments)}}()));case 1:case"end":return Vt.stop()}},He)}));return function(){return jt.apply(this,arguments)}}(),kr=function(){var jt=Object(tt.a)(Pe.a.mark(function He(){var ct,Vt;return Pe.a.wrap(function(bt){for(;;)switch(bt.prev=bt.next){case 0:return bt.next=2,hr();case 2:ct=bt.sent,ct!=null&&ct.identity_verify||Q(2),ct!=null&&ct.can_start&&ct.countdown_time===0?Q(2):(ct==null?void 0:ct.identity_photo_state)==="rejected"?(sn.current=!1,nn(1)):(ct==null?void 0:ct.identity_photo_state)==="passed"&&(sn.current=!1,Ot==null||((Vt=Ot.current)===null||Vt===void 0)||Vt.handleStop(),Ie!=null&&Ie.open_phone_video_recording||Q(2));case 5:case"end":return bt.stop()}},He)}));return function(){return jt.apply(this,arguments)}}(),pa=function(){var jt=Object(tt.a)(Pe.a.mark(function He(){var ct,Vt;return Pe.a.wrap(function(bt){for(;;)switch(bt.prev=bt.next){case 0:return bt.next=2,hr();case 2:ct=bt.sent,(ct==null?void 0:ct.identity_photo_state)==="submitted"||((ct==null?void 0:ct.identity_photo_state)==="rejected"?(sn.current=!1,nn(2)):(ct==null?void 0:ct.identity_photo_state)==="passed"&&(sn.current=!1,Ot==null||((Vt=Ot.current)===null||Vt===void 0)||Vt.handleStop(),nn(1),Ie!=null&&Ie.open_phone_video_recording||Q(2))),(ct==null?void 0:ct.identity_photo_state)!=="passed"&&sn.current&&setTimeout(function(){pa()},30*1e3);case 5:case"end":return bt.stop()}},He)}));return function(){return jt.apply(this,arguments)}}(),Fa=function(){var He;De(!1),Ot==null||((He=Ot.current)===null||He===void 0)||He.startDiscern()};return Object(Ge.useEffect)(function(){return kr(),console.log("captureRef:",Ot),function(){nn(0),At(!1),Ne(!1),Q(0)}},[]),ce.a.createElement("div",{className:"p30 bg-white minHb100 edu-container mt20"},(Ie==null?void 0:Ie.identity_verify)&&ce.a.createElement(ce.a.Fragment,null,ce.a.createElement("div",{className:"tc font16 blod"},"\u8EAB\u4EFD\u9A8C\u8BC1"),ce.a.createElement("div",{className:se.a.steps},ce.a.createElement(Ft.a,{current:Y},Nr.map(function(jt){return ce.a.createElement(qi,{key:jt.title,title:jt.title})})))),ce.a.createElement("div",{className:Y===0?"":"hide"},ce.a.createElement("div",{className:"tc mt50"},"\u8BF7\u4FDD\u8BC1\u5468\u56F4\u5149\u7EBF\u5145\u8DB3\uFF0C\u4E94\u5B98\u6E05\u6670\u53EF\u89C1\uFF01"),!we&&ce.a.createElement("div",{className:"tc"},ce.a.createElement("img",{width:536,src:Ks.a,className:"mt30"})),ce.a.createElement("div",{className:we?"":"hide"},ce.a.createElement(Hi,{ref:Ot,onCameraReady:function(He){De(He)},defaultOpen:Ie==null?void 0:Ie.identity_verify,identity_url:Object(Te.g)(b==null||((h=b.userInfo)===null||h===void 0)?void 0:h.identity_url),outputResult:function(He){He.success?(ot.b.success({content:"\u4EBA\u8138\u8BC6\u522B\u6210\u529F",key:"checkapi"}),Q(2)):At(!0),De(!1)}})),we&&ce.a.createElement(ce.a.Fragment,null,Yt?ce.a.createElement("div",{className:"tc mb30 mt15"},ce.a.createElement(kt.a,{type:"primary",onClick:function(){var He;Ot==null||((He=Ot.current)===null||He===void 0)||He.handlePlay(),Sn(Object(Mt.a)({},{})),At(!1)}},"\u91CD\u65B0\u8BC6\u522B"),ce.a.createElement(kt.a,{type:"primary",className:"ml90",onClick:Object(tt.a)(Pe.a.mark(function jt(){var He;return Pe.a.wrap(function(Vt){for(;;)switch(Vt.prev=Vt.next){case 0:return Vt.next=2,Ot==null||((He=Ot.current)===null||He===void 0)?void 0:He.handleUploadImage(0);case 2:sn.current=!0,Q(1),nn(0),At(!1),pa();case 7:case"end":return Vt.stop()}},jt)}))},"\u4EBA\u5DE5\u5BA1\u6838")):_e&&ce.a.createElement("div",{className:"tc mb30 mt15"},ce.a.createElement(kt.a,{type:"primary",onClick:Object(Xi.throttle)(Fa,2e3)},"\u5F00\u59CB\u8BC6\u522B"))),!we&&ce.a.createElement("div",{className:"tc mb30 mt15"},ce.a.createElement(kt.a,{type:"primary",onClick:function(){Ne(!0)}},"\u5F00\u59CB\u91C7\u96C6"))),Y===1&&ce.a.createElement("div",{className:"tc"},on===0&&ce.a.createElement(ce.a.Fragment,null,ce.a.createElement("div",{className:"tc mt50"},ce.a.createElement("span",{className:"c-blue font50 iconfont icon-dengdaishenhe"}),ce.a.createElement("br",null),"\u4EBA\u5DE5\u5BA1\u6838\u4E2D...",ce.a.createElement("br",null),"\u7533\u8BF7\u5DF2\u63D0\u4EA4\uFF0C\u76D1\u63A7\u8001\u5E08\u5BA1\u6838\u4E2D\uFF0C\u8BF7\u8010\u5FC3\u7B49\u5F85\uFF01"),ce.a.createElement(kt.a,{type:"primary",className:"mt50",onClick:Object(tt.a)(Pe.a.mark(function jt(){var He;return Pe.a.wrap(function(Vt){for(;;)switch(Vt.prev=Vt.next){case 0:return Vt.next=2,hr();case 2:He=Vt.sent,(He==null?void 0:He.identity_photo_state)==="submitted"?ot.b.warn({content:"\u6B63\u5728\u7B49\u5F85\u8001\u5E08\u5BA1\u6838\u4E2D\uFF0C\u8BF7\u7A0D\u540E...",key:"sh1"}):(He==null?void 0:He.identity_photo_state)==="rejected"?(nn(2),sn.current=!1):(He==null?void 0:He.identity_photo_state)==="passed"&&(sn.current=!1,nn(1),Ie!=null&&Ie.open_phone_video_recording||Q(2));case 4:case"end":return Vt.stop()}},jt)}))},"\u67E5\u770B\u5BA1\u6838\u7ED3\u679C")),on===1&&ce.a.createElement(ce.a.Fragment,null,ce.a.createElement("div",{className:"tc mt50"},ce.a.createElement("span",{className:"c-green font50 iconfont icon-tongguo"}),ce.a.createElement("br",null),"\u8EAB\u4EFD\u9A8C\u8BC1\u5BA1\u6838\u901A\u8FC7\u3002"),(Ie==null?void 0:Ie.open_phone_video_recording)&&ce.a.createElement(kt.a,{type:"primary",className:"mt50",onClick:function(){return Q(2)}},"\u4E0B\u4E00\u6B65")),on===2&&ce.a.createElement(ce.a.Fragment,null,ce.a.createElement("div",{className:"tc mt50"},ce.a.createElement("span",{className:"c-red font50 iconfont icon-hongsejingshi"}),ce.a.createElement("br",null),"\u8EAB\u4EFD\u9A8C\u8BC1\u5BA1\u6838\u4E0D\u901A\u8FC7\u3002\u8BF7\u91CD\u65B0\u62CD\u7167\u9A8C\u8BC1\u3002"),ce.a.createElement("div",{className:"mt20"},ce.a.createElement(Ke.a,null,ce.a.createElement(ye.a,{className:"tr",flex:"430px"},"\u5931\u8D25\u539F\u56E0\uFF1A"),ce.a.createElement(ye.a,null,Ie==null?void 0:Ie.identity_photo_comment)),ce.a.createElement(Ke.a,{className:"mt30"},ce.a.createElement(ye.a,{className:"tr",flex:"430px"},"\u91C7\u96C6\u7167\u7247\uFF1A"),ce.a.createElement(ye.a,null,ce.a.createElement("img",{src:Object(Te.g)(Ie==null?void 0:Ie.identity_photo_url),width:200}))),ce.a.createElement(Ke.a,null,ce.a.createElement(ye.a,{className:"tr",flex:"430px"}),ce.a.createElement(ye.a,null,ce.a.createElement(kt.a,{type:"primary",className:"mt50",onClick:function(){var He;Q(0),De(!1),At(!1),Ne(!1),Ot==null||((He=Ot.current)===null||He===void 0)||He.handlePlay()}},"\u91CD\u65B0\u8BA4\u8BC1")))))),Y===2&&ce.a.createElement(ce.a.Fragment,null,ce.a.createElement("div",{className:"tc mt50"},!(Ie!=null&&Ie.open_phone_video_recording)&&ce.a.createElement(ce.a.Fragment,null,(Ie==null?void 0:Ie.countdown_time)<=0?ce.a.createElement(ce.a.Fragment,null,ce.a.createElement("div",{className:"tc mt50"},ce.a.createElement("span",{className:"c-green font50 iconfont icon-tongguo"}),ce.a.createElement("br",null),"\u8EAB\u4EFD\u9A8C\u8BC1\u5BA1\u6838\u901A\u8FC7\u3002")):"\u8003\u8BD5\u5373\u5C06\u5F00\u59CB\uFF0C\u8BF7\u8010\u5FC3\u7B49\u5F85..."),(Ie==null?void 0:Ie.open_phone_video_recording)&&ce.a.createElement(ce.a.Fragment,null,(Ie==null?void 0:Ie.countdown_time)<=0?ce.a.createElement("div",{className:"tc"},"\u6839\u636E\u8003\u8BD5\u89C4\u5B9A\uFF0C\u8BF7\u6253\u5F00\u5FAE\u4FE1\u626B\u4E00\u626B\uFF0C\u626B\u7801\u4E0B\u9762\u7684\u4E8C\u7EF4\u7801\u5F00\u542F\u624B\u673A\u5F55\u5236\u89C6\u9891",ce.a.createElement("br",null),ce.a.createElement("span",{className:"c-blue",style:{cursor:"default"},onClick:function(){at.a.info({icon:null,title:"\u67E5\u770B\u64CD\u4F5C\u6307\u5F15",className:"custom-modal-divider",width:540,content:ce.a.createElement(Ke.a,null,ce.a.createElement(ye.a,{flex:"178px"},ce.a.createElement("img",{width:148,src:"/images/operation_guidance.png"})),ce.a.createElement(ye.a,{flex:"1"},"\u8BF7\u70B9\u51FB\u53F3\u4E0A\u89D2\u201C\u2026\u201D\uFF0C\u9009\u62E9",ce.a.createElement("span",{className:"c-orange"},"Safari\u4E2D\u6253\u5F00"),"\u6216\u8005",ce.a.createElement("span",{className:"c-orange"},"\u201C\u5728\u9ED8\u8BA4\u6D4F\u89C8\u5668\u4E2D\u6253\u5F00\u201D"),"\u540E\uFF0C\u6D4F\u89C8\u5668\u6253\u5F00\u540E\u8BF7\u70B9\u51FB\u5F00\u59CB\u5F55\u5236\u6309\u94AE\uFF0C\u53EF\u4EE5\u5F00\u542F\u624B\u673A\u5F55\u5236\u89C6\u9891\u3002"))})}},"\u5982\u82F9\u679C\u624B\u673A\u5FAE\u4FE1\u626B\u63CF\u4E8C\u7EF4\u7801\u540E\uFF0C\u51FA\u73B0\u70B9\u51FB\u5F00\u59CB\u5F55\u5236\u65E0\u54CD\u5E94\uFF0C\u8BF7\u67E5\u770B\u64CD\u4F5C\u6307\u5F15\u3002")):"\u8003\u8BD5\u5373\u5C06\u5F00\u59CB\uFF0C\u8BF7\u8010\u5FC3\u7B49\u5F85...")),(Ie==null?void 0:Ie.open_phone_video_recording)&&ce.a.createElement("div",{className:se.a.qrcode},ce.a.createElement(Oe.a,{value:"https://".concat(document.domain,"/live-push.html?id=").concat(P.categoryId,"&login=").concat(P.login,"&cookie=").concat(Object(Te.E)("_educoder_session"))})),(Ie==null?void 0:Ie.countdown_time)>0&&ce.a.createElement("div",{className:"tc mt20"},ce.a.createElement(Ki,{value:Date.now()+(Ie==null?void 0:Ie.countdown_time)*1e3,valueStyle:{color:"#cf1322",fontSize:40},onFinish:function(){hr()}})),ce.a.createElement("div",{className:"tc mb30 mt50"},ce.a.createElement(kt.a,{type:"primary",onClick:Object(tt.a)(Pe.a.mark(function jt(){var He,ct;return Pe.a.wrap(function(Xn){for(;;)switch(Xn.prev=Xn.next){case 0:return Xn.next=2,hr();case 2:He=Xn.sent,He!=null&&He.can_start&&(He==null?void 0:He.countdown_time)<=0?(Ot==null||((ct=Ot.current)===null||ct===void 0)||ct.handleRemove(),Ie!=null&&Ie.open_phone_video_recording?He!=null&&He.video_url&&setTimeout(function(){location.href="/classrooms/".concat(P.coursesId,"/exercise/").concat(P.categoryId,"/users/").concat(P.login)},300):setTimeout(function(){location.href="/classrooms/".concat(P.coursesId,"/exercise/").concat(P.categoryId,"/users/").concat(P.login)},300)):(He==null?void 0:He.countdown_time)>0?ot.b.warn({content:"\u8003\u8BD5\u6682\u672A\u5F00\u59CB\uFF0C\u8BF7\u7A0D\u540E..."}):ot.b.warn({content:"\u8BF7\u6253\u5F00\u5FAE\u4FE1\u626B\u4E00\u626B\uFF0C\u5F00\u542F\u624B\u673A\u89C6\u9891\u5F55\u5236"});case 4:case"end":return Xn.stop()}},jt)}))},"\u5F00\u59CB\u8003\u8BD5"))))},nc=ke.default=Object(ie.a)(function(p){var l=p.loading,h=p.user,v=p.exercise,y=p.globalSetting;return{globalSetting:y,user:h,exercise:v,loading:l.effects}})(Ys)},"kVK+":function(rn,ke){/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */ke.read=function(te,Se,ze,at,mt){var Ke,ve,ye=mt*8-at-1,ne=(1<<ye)-1,kt=ne>>1,ee=-7,ot=ze?mt-1:0,Mt=ze?-1:1,tt=te[Se+ot];for(ot+=Mt,Ke=tt&(1<<-ee)-1,tt>>=-ee,ee+=ye;ee>0;Ke=Ke*256+te[Se+ot],ot+=Mt,ee-=8);for(ve=Ke&(1<<-ee)-1,Ke>>=-ee,ee+=at;ee>0;ve=ve*256+te[Se+ot],ot+=Mt,ee-=8);if(Ke===0)Ke=1-kt;else{if(Ke===ne)return ve?NaN:(tt?-1:1)*Infinity;ve=ve+Math.pow(2,at),Ke=Ke-kt}return(tt?-1:1)*ve*Math.pow(2,Ke-at)},ke.write=function(te,Se,ze,at,mt,Ke){var ve,ye,ne,kt=Ke*8-mt-1,ee=(1<<kt)-1,ot=ee>>1,Mt=mt===23?Math.pow(2,-24)-Math.pow(2,-77):0,tt=at?0:Ke-1,Ve=at?1:-1,st=Se<0||Se===0&&1/Se<0?1:0;for(Se=Math.abs(Se),isNaN(Se)||Se===Infinity?(ye=isNaN(Se)?1:0,ve=ee):(ve=Math.floor(Math.log(Se)/Math.LN2),Se*(ne=Math.pow(2,-ve))<1&&(ve--,ne*=2),ve+ot>=1?Se+=Mt/ne:Se+=Mt*Math.pow(2,1-ot),Se*ne>=2&&(ve++,ne/=2),ve+ot>=ee?(ye=0,ve=ee):ve+ot>=1?(ye=(Se*ne-1)*Math.pow(2,mt),ve=ve+ot):(ye=Se*Math.pow(2,ot-1)*Math.pow(2,mt),ve=0));mt>=8;te[ze+tt]=ye&255,tt+=Ve,ye/=256,mt-=8);for(ve=ve<<mt|ye,kt+=mt;kt>0;te[ze+tt]=ve&255,tt+=Ve,ve/=256,kt-=8);te[ze+tt-Ve]|=st*128}},mrSG:function(rn,ke,te){"use strict";te.d(ke,"c",function(){return ze}),te.d(ke,"a",function(){return at}),te.d(ke,"b",function(){return ne}),te.d(ke,"d",function(){return kt}),te.d(ke,"e",function(){return st});/*! *****************************************************************************
|
|
Copyright (c) Microsoft Corporation.
|
|
|
|
Permission to use, copy, modify, and/or distribute this software for any
|
|
purpose with or without fee is hereby granted.
|
|
|
|
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
PERFORMANCE OF THIS SOFTWARE.
|
|
***************************************************************************** */var Se=function(D,se){return Se=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(Te,Ae){Te.__proto__=Ae}||function(Te,Ae){for(var ae in Ae)Ae.hasOwnProperty(ae)&&(Te[ae]=Ae[ae])},Se(D,se)};function ze(ie,D){Se(ie,D);function se(){this.constructor=ie}ie.prototype=D===null?Object.create(D):(se.prototype=D.prototype,new se)}var at=function(){return at=Object.assign||function(se){for(var Te,Ae=1,ae=arguments.length;Ae<ae;Ae++){Te=arguments[Ae];for(var Oe in Te)Object.prototype.hasOwnProperty.call(Te,Oe)&&(se[Oe]=Te[Oe])}return se},at.apply(this,arguments)};function mt(ie,D){var se={};for(var Te in ie)Object.prototype.hasOwnProperty.call(ie,Te)&&D.indexOf(Te)<0&&(se[Te]=ie[Te]);if(ie!=null&&typeof Object.getOwnPropertySymbols=="function")for(var Ae=0,Te=Object.getOwnPropertySymbols(ie);Ae<Te.length;Ae++)D.indexOf(Te[Ae])<0&&Object.prototype.propertyIsEnumerable.call(ie,Te[Ae])&&(se[Te[Ae]]=ie[Te[Ae]]);return se}function Ke(ie,D,se,Te){var Ae=arguments.length,ae=Ae<3?D:Te===null?Te=Object.getOwnPropertyDescriptor(D,se):Te,Oe;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")ae=Reflect.decorate(ie,D,se,Te);else for(var Be=ie.length-1;Be>=0;Be--)(Oe=ie[Be])&&(ae=(Ae<3?Oe(ae):Ae>3?Oe(D,se,ae):Oe(D,se))||ae);return Ae>3&&ae&&Object.defineProperty(D,se,ae),ae}function ve(ie,D){return function(se,Te){D(se,Te,ie)}}function ye(ie,D){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(ie,D)}function ne(ie,D,se,Te){function Ae(ae){return ae instanceof se?ae:new se(function(Oe){Oe(ae)})}return new(se||(se=Promise))(function(ae,Oe){function Be(Qe){try{k(Te.next(Qe))}catch(q){Oe(q)}}function Qt(Qe){try{k(Te.throw(Qe))}catch(q){Oe(q)}}function k(Qe){Qe.done?ae(Qe.value):Ae(Qe.value).then(Be,Qt)}k((Te=Te.apply(ie,D||[])).next())})}function kt(ie,D){var se={label:0,sent:function(){if(ae[0]&1)throw ae[1];return ae[1]},trys:[],ops:[]},Te,Ae,ae,Oe;return Oe={next:Be(0),throw:Be(1),return:Be(2)},typeof Symbol=="function"&&(Oe[Symbol.iterator]=function(){return this}),Oe;function Be(k){return function(Qe){return Qt([k,Qe])}}function Qt(k){if(Te)throw new TypeError("Generator is already executing.");for(;se;)try{if(Te=1,Ae&&(ae=k[0]&2?Ae.return:k[0]?Ae.throw||((ae=Ae.return)&&ae.call(Ae),0):Ae.next)&&!(ae=ae.call(Ae,k[1])).done)return ae;(Ae=0,ae)&&(k=[k[0]&2,ae.value]);switch(k[0]){case 0:case 1:ae=k;break;case 4:return se.label++,{value:k[1],done:!1};case 5:se.label++,Ae=k[1],k=[0];continue;case 7:k=se.ops.pop(),se.trys.pop();continue;default:if(!(ae=se.trys,ae=ae.length>0&&ae[ae.length-1])&&(k[0]===6||k[0]===2)){se=0;continue}if(k[0]===3&&(!ae||k[1]>ae[0]&&k[1]<ae[3])){se.label=k[1];break}if(k[0]===6&&se.label<ae[1]){se.label=ae[1],ae=k;break}if(ae&&se.label<ae[2]){se.label=ae[2],se.ops.push(k);break}ae[2]&&se.ops.pop(),se.trys.pop();continue}k=D.call(ie,se)}catch(Qe){k=[6,Qe],Ae=0}finally{Te=ae=0}if(k[0]&5)throw k[1];return{value:k[0]?k[1]:void 0,done:!0}}}function ee(ie,D,se,Te){Te===void 0&&(Te=se),ie[Te]=D[se]}function ot(ie,D){for(var se in ie)se!=="default"&&!D.hasOwnProperty(se)&&(D[se]=ie[se])}function Mt(ie){var D=typeof Symbol=="function"&&Symbol.iterator,se=D&&ie[D],Te=0;if(se)return se.call(ie);if(ie&&typeof ie.length=="number")return{next:function(){return ie&&Te>=ie.length&&(ie=void 0),{value:ie&&ie[Te++],done:!ie}}};throw new TypeError(D?"Object is not iterable.":"Symbol.iterator is not defined.")}function tt(ie,D){var se=typeof Symbol=="function"&&ie[Symbol.iterator];if(!se)return ie;var Te=se.call(ie),Ae,ae=[],Oe;try{for(;(D===void 0||D-- >0)&&!(Ae=Te.next()).done;)ae.push(Ae.value)}catch(Be){Oe={error:Be}}finally{try{Ae&&!Ae.done&&(se=Te.return)&&se.call(Te)}finally{if(Oe)throw Oe.error}}return ae}function Ve(){for(var ie=[],D=0;D<arguments.length;D++)ie=ie.concat(tt(arguments[D]));return ie}function st(){for(var ie=0,D=0,se=arguments.length;D<se;D++)ie+=arguments[D].length;for(var Te=Array(ie),Ae=0,D=0;D<se;D++)for(var ae=arguments[D],Oe=0,Be=ae.length;Oe<Be;Oe++,Ae++)Te[Ae]=ae[Oe];return Te}function Ct(ie){return this instanceof Ct?(this.v=ie,this):new Ct(ie)}function Ft(ie,D,se){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var Te=se.apply(ie,D||[]),Ae,ae=[];return Ae={},Oe("next"),Oe("throw"),Oe("return"),Ae[Symbol.asyncIterator]=function(){return this},Ae;function Oe(lt){Te[lt]&&(Ae[lt]=function(je){return new Promise(function(St,Cn){ae.push([lt,je,St,Cn])>1||Be(lt,je)})})}function Be(lt,je){try{Qt(Te[lt](je))}catch(St){q(ae[0][3],St)}}function Qt(lt){lt.value instanceof Ct?Promise.resolve(lt.value.v).then(k,Qe):q(ae[0][2],lt)}function k(lt){Be("next",lt)}function Qe(lt){Be("throw",lt)}function q(lt,je){(lt(je),ae.shift(),ae.length)&&Be(ae[0][0],ae[0][1])}}function xn(ie){var D,se;return D={},Te("next"),Te("throw",function(Ae){throw Ae}),Te("return"),D[Symbol.iterator]=function(){return this},D;function Te(Ae,ae){D[Ae]=ie[Ae]?function(Oe){return(se=!se)?{value:Ct(ie[Ae](Oe)),done:Ae==="return"}:ae?ae(Oe):Oe}:ae}}function Pt(ie){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var D=ie[Symbol.asyncIterator],se;return D?D.call(ie):(ie=typeof Mt=="function"?Mt(ie):ie[Symbol.iterator](),se={},Te("next"),Te("throw"),Te("return"),se[Symbol.asyncIterator]=function(){return this},se);function Te(ae){se[ae]=ie[ae]&&function(Oe){return new Promise(function(Be,Qt){Oe=ie[ae](Oe),Ae(Be,Qt,Oe.done,Oe.value)})}}function Ae(ae,Oe,Be,Qt){Promise.resolve(Qt).then(function(k){ae({value:k,done:Be})},Oe)}}function dn(ie,D){return Object.defineProperty?Object.defineProperty(ie,"raw",{value:D}):ie.raw=D,ie}function Pe(ie){if(ie&&ie.__esModule)return ie;var D={};if(ie!=null)for(var se in ie)Object.hasOwnProperty.call(ie,se)&&(D[se]=ie[se]);return D.default=ie,D}function Ge(ie){return ie&&ie.__esModule?ie:{default:ie}}function ce(ie,D){if(!D.has(ie))throw new TypeError("attempted to get private field on non-instance");return D.get(ie)}function Ye(ie,D,se){if(!D.has(ie))throw new TypeError("attempted to set private field on non-instance");return D.set(ie,se),se}},oX8U:function(rn,ke,te){"use strict";(function(Se){te.d(ke,"a",function(){return mt});var ze=te("mrSG"),at=te("rOjP");function mt(){var Ke=Se.Canvas||Se.HTMLCanvasElement,ve=Se.Image||Se.HTMLImageElement,ye=function(){if(Ke)return new Ke;throw new Error("createCanvasElement - missing Canvas implementation for nodejs environment")},ne=function(){if(ve)return new ve;throw new Error("createImageElement - missing Image implementation for nodejs environment")},kt=Se.fetch||function(){throw new Error("fetch - missing fetch implementation for nodejs environment")},ee=Object(at.a)();return Object(ze.a)({Canvas:Ke||function(){function ot(){}return ot}(),CanvasRenderingContext2D:Se.CanvasRenderingContext2D||function(){function ot(){}return ot}(),Image:ve||function(){function ot(){}return ot}(),ImageData:Se.ImageData||function(){function ot(){}return ot}(),Video:Se.HTMLVideoElement||function(){function ot(){}return ot}(),createCanvasElement:ye,createImageElement:ne,fetch:kt},ee)}}).call(this,te("IyRk"))},rOjP:function(rn,ke,te){"use strict";te.d(ke,"a",function(){return Se});function Se(ze){var at="";if(!ze)try{ze=te("Og1z")}catch(Ke){at=Ke.toString()}var mt=ze?function(Ke){return new Promise(function(ve,ye){ze.readFile(Ke,function(ne,kt){return ne?ye(ne):ve(kt)})})}:function(){throw new Error("readFile - failed to require fs in nodejs environment with error: "+at)};return{readFile:mt}}},yPBj:function(rn,ke,te){rn.exports={flex_box_center:"flex_box_center___3-ehW",flex_space_between:"flex_space_between___1gePc",flex_box_vertical_center:"flex_box_vertical_center___2IxJA",flex_box_center_end:"flex_box_center_end___2Bh1H",flex_box_column:"flex_box_column___35awp",bg:"bg___CQ173",steps:"steps___upu0k",qrcode:"qrcode___25DP3"}}}]);
|