diff --git "a/static/assets/pose.worker-BBF_KKBj.js" "b/static/assets/pose.worker-BBF_KKBj.js" new file mode 100644--- /dev/null +++ "b/static/assets/pose.worker-BBF_KKBj.js" @@ -0,0 +1,16077 @@ +function qh(n,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(r){if(r!=="default"&&!(r in n)){var s=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(n,r,s.get?s:{enumerable:!0,get:function(){return t[r]}})}})}),Object.freeze(n)}/** + * @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. + * ============================================================================= + */const gw=1e-7,yw=1e-4;class Kh{constructor(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}}class Gl{refCount(e){return jt("refCount")}incRef(e){return jt("incRef")}timerAvailable(){return!0}time(e){return jt("time")}read(e){return jt("read")}readSync(e){return jt("readSync")}readToGPU(e,t){return jt("readToGPU")}numDataIds(){return jt("numDataIds")}disposeData(e,t){return jt("disposeData")}write(e,t,r){return jt("write")}move(e,t,r,s,a){return jt("move")}createTensorFromGPUData(e,t,r){return jt("createTensorFromGPUData")}memory(){return jt("memory")}floatPrecision(){return jt("floatPrecision")}epsilon(){return this.floatPrecision()===32?gw:yw}dispose(){return jt("dispose")}}function jt(n){throw new Error(`'${n}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}/** + * @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. + * ============================================================================= + */function Pa(n,e,t){const r=n[e];n[e]=n[t],n[t]=r}function bw(n){let e=0;for(let t=0;tt+` Shapes ${n} and ${e} must match`)}function ca(n){$(n!=null,()=>"The input to the tensor constructor must be a non-null value.")}function q(n){if(n.length===0)return 1;let e=n[0];for(let t=1;t=0)t*=n[a];else if(n[a]===-1){if(r!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${r} and dim ${a}`);r=a}else if(n[a]<0)throw Error(`Shapes can not be < 0. Found ${n[a]} at dim ${a}`);if(r===-1){if(e>0&&e!==t)throw Error(`Size(${e}) must match the product of shape ${n}`);return n}if(t===0)throw Error(`Cannot infer the missing size in [${n}] when there are 0 elements`);if(e%t!==0)throw Error(`The implicit shape can't be a fractional number. Got ${e} / ${t}`);const s=n.slice();return s[r]=e/t,s}function $t(n,e){const t=e.length;return n=n==null?e.map((r,s)=>s):[].concat(n),$(n.every(r=>r>=-t&&r`All values in axis param must be in range [-${t}, ${t}) but got axis ${n}`),$(n.every(r=>ja(r)),()=>`All values in axis param must be integers but got axis ${n}`),n.map(r=>r<0?t+r:r)}function xw(n,e){const t=[],r=[],s=e!=null&&Array.isArray(e)&&e.length===0,a=e==null||s?null:$t(e,n).sort();let o=0;for(let i=0;ii)&&n[i]===1&&(t.push(n[i]),r.push(i)),a[o]<=i&&o++}n[i]!==1&&(t.push(n[i]),r.push(i))}return{newShape:t,keptDims:r}}function kr(n,e){return Ar(n,e)}function Ar(n,e){let t=null;if(n==null||n==="float32")t=new Float32Array(e);else if(n==="int32")t=new Int32Array(e);else if(n==="bool")t=new Uint8Array(e);else if(n==="string")t=new Array(e);else throw new Error(`Unknown data type ${n}`);return t}function vw(n,e){for(let t=0;te+=t.length),e}function ci(n){return typeof n=="string"||n instanceof String}function _w(n){return typeof n=="boolean"}function Cw(n){return typeof n=="number"}function da(n){return Array.isArray(n)?da(n[0]):n instanceof Float32Array?"float32":n instanceof Int32Array||n instanceof Uint8Array||n instanceof Uint8ClampedArray?"int32":Cw(n)?"float32":ci(n)?"string":_w(n)?"bool":"float32"}function nl(n){return!!(n&&n.constructor&&n.call&&n.apply)}function et(n){const e=n.length;if(e<2)return[];const t=new Array(e-1);t[e-2]=n[e-1];for(let r=e-3;r>=0;--r)t[r]=t[r+1]*n[r+1];return t}function Yh(n,e,t,r=!1){const s=new Array;if(e.length===1){const a=e[0]*(r?2:1);for(let o=0;ol*c)*(r?2:1);for(let l=0;ls*a)*(t?2:1);if(r===0)return[];if(r!==e.length)throw new Error(`[${n}] does not match the input size ${e.length}${t?" for a complex tensor":""}.`);return Yh(0,n,e,t)}function Au(n,e){if(Array.isArray(n))return n;if(e==="float32")return n instanceof Float32Array?n:new Float32Array(n);if(e==="int32")return n instanceof Int32Array?n:new Int32Array(n);if(e==="bool"||e==="string")return Uint8Array.from(new Int32Array(n));throw new Error(`Unknown dtype ${e}`)}function Qh(n,e){const t=ps(n,e);for(let r=0;r{$(Number.isInteger(e)&&e>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${n}].`)})}function sl(n,e,t){if(e===0)return 0;if(e===1)return n[0];let r=n[n.length-1];for(let s=0;s"u"||typeof this.global.location>"u"||typeof this.global.location.search>"u")return;const e=this.getQueryParams(this.global.location.search);cp in e&&e[cp].split(",").forEach(r=>{const[s,a]=r.split(":");this.urlFlags[s]=Ew(s,a)})}}function $w(n){const e={};return n.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(t,...r)=>(Tw(e,r[0],r[1]),r.join("="))),e}function Tw(n,e,t){n[decodeURIComponent(e)]=decodeURIComponent(t||"")}function Ew(n,e){const t=e.toLowerCase();return t==="true"||t==="false"?t==="true":`${+t}`===t?+t:e}function fe(){return Jh}let Jh=null;function Aw(n){Jh=n}/** + * @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. + * ============================================================================= + */let Ru;function ef(){if(Ru==null){let n;if(typeof window<"u")n=window;else if(typeof global<"u")n=global;else if(typeof process<"u")n=process;else if(typeof self<"u")n=self;else throw new Error("Could not find a global object");Ru=n}return Ru}function Rw(){const n=ef();return n._tfGlobals==null&&(n._tfGlobals=new Map),n._tfGlobals}function jl(n,e){const t=Rw();if(t.has(n))return t.get(n);{const r=e();return t.set(n,r),t.get(n)}}const ql="Abs",Kl="Acos",Xl="Acosh",di="Add",pi="AddN",hi="All",fi="Any",Yl="ArgMax",Ql="ArgMin",Zl="Asin",Jl="Asinh",ec="Atan",tc="Atanh",nc="Atan2",mi="AvgPool",tf="AvgPoolGrad",rc="AvgPool3D",nf="AvgPool3DGrad",gi="BatchMatMul",sc="BatchToSpaceND",yi="Bincount",rf="BitwiseAnd",ac="BroadcastArgs",bi="Cast",oc="Ceil",wi="ClipByValue",sf="Complex",af="ComplexAbs",ic="Concat",xi="Conv2D",of="Conv2DBackpropFilter",vi="Conv2DBackpropInput",Si="Conv3D",uc="Conv3DBackpropFilterV2",Ii="Conv3DBackpropInputV2",lc="Cos",cc="Cosh",ki="Cumprod",_i="Cumsum",Ci="CropAndResize",dc="DenseBincount",Ni="DepthToSpace",$i="DepthwiseConv2dNative",uf="DepthwiseConv2dNativeBackpropFilter",lf="DepthwiseConv2dNativeBackpropInput",pc="Diag",Ti="Dilation2D",hc="Dilation2DBackpropInput",fc="Dilation2DBackpropFilter",cf="Draw",mc="RealDiv",df="Einsum",gc="Elu",yc="EluGrad",bc="Erf",wc="Equal",xc="Exp",vc="ExpandDims",Sc="Expm1",pf="FFT",Ic="Fill",Ei="FlipLeftRight",kc="Floor",_c="FloorDiv",Ai="FusedBatchNorm",Cc="GatherV2",Ri="GatherNd",Nc="Greater",$c="GreaterEqual",Di="Identity",hf="IFFT",ff="Imag",Tc="IsFinite",Ec="IsInf",Ac="IsNan",Pi="LeakyRelu",Rc="Less",Dc="LessEqual",Fi="LinSpace",Pc="Log",Fc="Log1p",Oc="LogicalAnd",Mc="LogicalNot",Lc="LogicalOr",Dw="LogicalXor",Oi="LRN",zc="LRNGrad",Mi="Max",Bc="Maximum",Li="MaxPool",mf="MaxPoolGrad",Wc="MaxPool3D",gf="MaxPool3DGrad",Vc="MaxPoolWithArgmax",zi="Mean",Bi="Min",Uc="Minimum",Wi="MirrorPad",Hc="Mod",Vi="Multinomial",Gc="Multiply",jc="Neg",qc="NotEqual",Ui="NonMaxSuppressionV3",Kc="NonMaxSuppressionV4",Hi="NonMaxSuppressionV5",Xc="OnesLike",Gi="OneHot",Yc="Pack",ji="PadV2",Qc="Pow",qi="Prelu",Ki="Prod",Pw="RaggedGather",Fw="RaggedRange",Ow="RaggedTensorToTensor",Zc="Range",yf="Real",Jc="Reciprocal",ed="Relu",td="Reshape",Xi="ResizeNearestNeighbor",nd="ResizeNearestNeighborGrad",Yi="ResizeBilinear",rd="ResizeBilinearGrad",sd="Relu6",Qi="Reverse",ad="Round",od="Rsqrt",Zi="ScatterNd",Ji="TensorScatterUpdate",eu="SearchSorted",id="Select",ud="Selu",ld="Slice",cd="Sin",dd="Sinh",pd="Sign",hd="Sigmoid",fd="Softplus",md="Sqrt",tu="Sum",gd="SpaceToBatchND",yd="SplitV",nu="Softmax",bf="SparseFillEmptyRows",bd="SparseReshape",wd="SparseSegmentMean",xd="SparseSegmentSum",ru="SparseToDense",vd="SquaredDifference",wf="Square",Mw="StaticRegexReplace",su="StridedSlice",Sd="StringNGrams",xf="StringSplit",vf="StringToHashBucketFast",Id="Sub",kd="Tan",_d="Tanh",co="Tile",au="TopK",ou="Transform",Qs="Transpose",Sf="Unique",Cd="Unpack",If="UnsortedSegmentSum",Nd="ZerosLike",iu="Step",al="FromPixels",uu="RotateWithOffset",Ka="_FusedMatMul",Xa="FusedConv2D",Ya="FusedDepthwiseConv2D";/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function qs(...n){fe().getBool("IS_TEST")||fe().getBool("PROD")||console.warn(...n)}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const qo=jl("kernelRegistry",()=>new Map),Lw=jl("gradRegistry",()=>new Map);function Ko(n,e){const t=_f(n,e);return qo.get(t)}function dp(n){return Lw.get(n)}function pp(n){const e=qo.entries(),t=[];for(;;){const{done:r,value:s}=e.next();if(r)break;const[a,o]=s,[i]=a.split("_");i===n&&t.push(o)}return t}function kf(n){const{kernelName:e,backendName:t}=n,r=_f(e,t);qo.has(r)&&qs(`The kernel '${e}' for backend '${t}' is already registered`),qo.set(r,n)}function _f(n,e){return`${e}_${n}`}/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */function Cf(n){return n instanceof Float32Array||n instanceof Int32Array||n instanceof Uint8Array||n instanceof Uint8ClampedArray}var Xo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function $d(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}function zw(n){if(Object.prototype.hasOwnProperty.call(n,"__esModule"))return n;var e=n.default;if(typeof e=="function"){var t=function r(){return this instanceof r?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(n).forEach(function(r){var s=Object.getOwnPropertyDescriptor(n,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:function(){return n[r]}})}),t}var Du,hp;function Bw(){if(hp)return Du;hp=1,Du=e;var n=null;try{n=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function e(D,_,V){this.low=D|0,this.high=_|0,this.unsigned=!!V}e.prototype.__isLong__,Object.defineProperty(e.prototype,"__isLong__",{value:!0});function t(D){return(D&&D.__isLong__)===!0}e.isLong=t;var r={},s={};function a(D,_){var V,H,Y;return _?(D>>>=0,(Y=0<=D&&D<256)&&(H=s[D],H)?H:(V=i(D,(D|0)<0?-1:0,!0),Y&&(s[D]=V),V)):(D|=0,(Y=-128<=D&&D<128)&&(H=r[D],H)?H:(V=i(D,D<0?-1:0,!1),Y&&(r[D]=V),V))}e.fromInt=a;function o(D,_){if(isNaN(D))return _?I:v;if(_){if(D<0)return I;if(D>=m)return L}else{if(D<=-g)return B;if(D+1>=g)return O}return D<0?o(-D,_).neg():i(D%f|0,D/f|0,_)}e.fromNumber=o;function i(D,_,V){return new e(D,_,V)}e.fromBits=i;var l=Math.pow;function c(D,_,V){if(D.length===0)throw Error("empty string");if(D==="NaN"||D==="Infinity"||D==="+Infinity"||D==="-Infinity")return v;if(typeof _=="number"?(V=_,_=!1):_=!!_,V=V||10,V<2||360)throw Error("interior hyphen");if(H===0)return c(D.substring(1),_,V).neg();for(var Y=o(l(V,8)),X=v,ee=0;ee>>0:this.low},A.toNumber=function(){return this.unsigned?(this.high>>>0)*f+(this.low>>>0):this.high*f+(this.low>>>0)},A.toString=function(_){if(_=_||10,_<2||36<_)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative())if(this.eq(B)){var V=o(_),H=this.div(V),Y=H.mul(V).sub(this);return H.toString(_)+Y.toInt().toString(_)}else return"-"+this.neg().toString(_);for(var X=o(l(_,6),this.unsigned),ee=this,ye="";;){var ce=ee.div(X),be=ee.sub(ce.mul(X)).toInt()>>>0,Se=be.toString(_);if(ee=ce,ee.isZero())return Se+ye;for(;Se.length<6;)Se="0"+Se;ye=""+Se+ye}},A.getHighBits=function(){return this.high},A.getHighBitsUnsigned=function(){return this.high>>>0},A.getLowBits=function(){return this.low},A.getLowBitsUnsigned=function(){return this.low>>>0},A.getNumBitsAbs=function(){if(this.isNegative())return this.eq(B)?64:this.neg().getNumBitsAbs();for(var _=this.high!=0?this.high:this.low,V=31;V>0&&(_&1<=0},A.isOdd=function(){return(this.low&1)===1},A.isEven=function(){return(this.low&1)===0},A.equals=function(_){return t(_)||(_=u(_)),this.unsigned!==_.unsigned&&this.high>>>31===1&&_.high>>>31===1?!1:this.high===_.high&&this.low===_.low},A.eq=A.equals,A.notEquals=function(_){return!this.eq(_)},A.neq=A.notEquals,A.ne=A.notEquals,A.lessThan=function(_){return this.comp(_)<0},A.lt=A.lessThan,A.lessThanOrEqual=function(_){return this.comp(_)<=0},A.lte=A.lessThanOrEqual,A.le=A.lessThanOrEqual,A.greaterThan=function(_){return this.comp(_)>0},A.gt=A.greaterThan,A.greaterThanOrEqual=function(_){return this.comp(_)>=0},A.gte=A.greaterThanOrEqual,A.ge=A.greaterThanOrEqual,A.compare=function(_){if(t(_)||(_=u(_)),this.eq(_))return 0;var V=this.isNegative(),H=_.isNegative();return V&&!H?-1:!V&&H?1:this.unsigned?_.high>>>0>this.high>>>0||_.high===this.high&&_.low>>>0>this.low>>>0?-1:1:this.sub(_).isNegative()?-1:1},A.comp=A.compare,A.negate=function(){return!this.unsigned&&this.eq(B)?B:this.not().add(S)},A.neg=A.negate,A.add=function(_){t(_)||(_=u(_));var V=this.high>>>16,H=this.high&65535,Y=this.low>>>16,X=this.low&65535,ee=_.high>>>16,ye=_.high&65535,ce=_.low>>>16,be=_.low&65535,Se=0,Pe=0,Ve=0,Oe=0;return Oe+=X+be,Ve+=Oe>>>16,Oe&=65535,Ve+=Y+ce,Pe+=Ve>>>16,Ve&=65535,Pe+=H+ye,Se+=Pe>>>16,Pe&=65535,Se+=V+ee,Se&=65535,i(Ve<<16|Oe,Se<<16|Pe,this.unsigned)},A.subtract=function(_){return t(_)||(_=u(_)),this.add(_.neg())},A.sub=A.subtract,A.multiply=function(_){if(this.isZero())return v;if(t(_)||(_=u(_)),n){var V=n.mul(this.low,this.high,_.low,_.high);return i(V,n.get_high(),this.unsigned)}if(_.isZero())return v;if(this.eq(B))return _.isOdd()?B:v;if(_.eq(B))return this.isOdd()?B:v;if(this.isNegative())return _.isNegative()?this.neg().mul(_.neg()):this.neg().mul(_).neg();if(_.isNegative())return this.mul(_.neg()).neg();if(this.lt(b)&&_.lt(b))return o(this.toNumber()*_.toNumber(),this.unsigned);var H=this.high>>>16,Y=this.high&65535,X=this.low>>>16,ee=this.low&65535,ye=_.high>>>16,ce=_.high&65535,be=_.low>>>16,Se=_.low&65535,Pe=0,Ve=0,Oe=0,Et=0;return Et+=ee*Se,Oe+=Et>>>16,Et&=65535,Oe+=X*Se,Ve+=Oe>>>16,Oe&=65535,Oe+=ee*be,Ve+=Oe>>>16,Oe&=65535,Ve+=Y*Se,Pe+=Ve>>>16,Ve&=65535,Ve+=X*be,Pe+=Ve>>>16,Ve&=65535,Ve+=ee*ce,Pe+=Ve>>>16,Ve&=65535,Pe+=H*Se+Y*be+X*ce+ee*ye,Pe&=65535,i(Oe<<16|Et,Pe<<16|Ve,this.unsigned)},A.mul=A.multiply,A.divide=function(_){if(t(_)||(_=u(_)),_.isZero())throw Error("division by zero");if(n){if(!this.unsigned&&this.high===-2147483648&&_.low===-1&&_.high===-1)return this;var V=(this.unsigned?n.div_u:n.div_s)(this.low,this.high,_.low,_.high);return i(V,n.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?I:v;var H,Y,X;if(this.unsigned){if(_.unsigned||(_=_.toUnsigned()),_.gt(this))return I;if(_.gt(this.shru(1)))return C;X=I}else{if(this.eq(B)){if(_.eq(S)||_.eq(T))return B;if(_.eq(B))return S;var ee=this.shr(1);return H=ee.div(_).shl(1),H.eq(v)?_.isNegative()?S:T:(Y=this.sub(_.mul(H)),X=H.add(Y.div(_)),X)}else if(_.eq(B))return this.unsigned?I:v;if(this.isNegative())return _.isNegative()?this.neg().div(_.neg()):this.neg().div(_).neg();if(_.isNegative())return this.div(_.neg()).neg();X=v}for(Y=this;Y.gte(_);){H=Math.max(1,Math.floor(Y.toNumber()/_.toNumber()));for(var ye=Math.ceil(Math.log(H)/Math.LN2),ce=ye<=48?1:l(2,ye-48),be=o(H),Se=be.mul(_);Se.isNegative()||Se.gt(Y);)H-=ce,be=o(H,this.unsigned),Se=be.mul(_);be.isZero()&&(be=S),X=X.add(be),Y=Y.sub(Se)}return X},A.div=A.divide,A.modulo=function(_){if(t(_)||(_=u(_)),n){var V=(this.unsigned?n.rem_u:n.rem_s)(this.low,this.high,_.low,_.high);return i(V,n.get_high(),this.unsigned)}return this.sub(this.div(_).mul(_))},A.mod=A.modulo,A.rem=A.modulo,A.not=function(){return i(~this.low,~this.high,this.unsigned)},A.and=function(_){return t(_)||(_=u(_)),i(this.low&_.low,this.high&_.high,this.unsigned)},A.or=function(_){return t(_)||(_=u(_)),i(this.low|_.low,this.high|_.high,this.unsigned)},A.xor=function(_){return t(_)||(_=u(_)),i(this.low^_.low,this.high^_.high,this.unsigned)},A.shiftLeft=function(_){return t(_)&&(_=_.toInt()),(_&=63)===0?this:_<32?i(this.low<<_,this.high<<_|this.low>>>32-_,this.unsigned):i(0,this.low<<_-32,this.unsigned)},A.shl=A.shiftLeft,A.shiftRight=function(_){return t(_)&&(_=_.toInt()),(_&=63)===0?this:_<32?i(this.low>>>_|this.high<<32-_,this.high>>_,this.unsigned):i(this.high>>_-32,this.high>=0?0:-1,this.unsigned)},A.shr=A.shiftRight,A.shiftRightUnsigned=function(_){if(t(_)&&(_=_.toInt()),_&=63,_===0)return this;var V=this.high;if(_<32){var H=this.low;return i(H>>>_|V<<32-_,V>>>_,this.unsigned)}else return _===32?i(V,0,this.unsigned):i(V>>>_-32,0,this.unsigned)},A.shru=A.shiftRightUnsigned,A.shr_u=A.shiftRightUnsigned,A.toSigned=function(){return this.unsigned?i(this.low,this.high,!1):this},A.toUnsigned=function(){return this.unsigned?this:i(this.low,this.high,!0)},A.toBytes=function(_){return _?this.toBytesLE():this.toBytesBE()},A.toBytesLE=function(){var _=this.high,V=this.low;return[V&255,V>>>8&255,V>>>16&255,V>>>24,_&255,_>>>8&255,_>>>16&255,_>>>24]},A.toBytesBE=function(){var _=this.high,V=this.low;return[_>>>24,_>>>16&255,_>>>8&255,_&255,V>>>24,V>>>16&255,V>>>8&255,V&255]},e.fromBytes=function(_,V,H){return H?e.fromBytesLE(_,V):e.fromBytesBE(_,V)},e.fromBytesLE=function(_,V){return new e(_[0]|_[1]<<8|_[2]<<16|_[3]<<24,_[4]|_[5]<<8|_[6]<<16|_[7]<<24,V)},e.fromBytesBE=function(_,V){return new e(_[4]<<24|_[5]<<16|_[6]<<8|_[7],_[0]<<24|_[1]<<16|_[2]<<8|_[3],V)},Du}var Nf=Bw(),$f=$d(Nf),Ww=qh({__proto__:null,default:$f},[Nf]);/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const es=$f||Ww;function lu(n){return es.fromString(n,!0,16)}const Tf=lu("c3a5c85c97cb3127"),Zr=lu("b492b66fbe98f273"),Ft=lu("9ae16a3b2f90404f");function ol(n){return n.xor(n.shru(47))}function Ef(n,e,t){const r=n.slice(e,e+t);return es.fromBytes(Array.from(r),!0,!0)}function nt(n,e){return Ef(n,e,8)}function fp(n,e){return Ef(n,e,4)}function bt(n,e){return e===0?n:n.shru(e).or(n.shl(64-e))}function xr(n,e,t=lu("9ddfea08eb382d69")){let r=n.xor(e).mul(t);r=r.xor(r.shru(47));let s=e.xor(r).mul(t);return s=s.xor(s.shru(47)),s=s.mul(t),s}function Vw(n,e,t,r,s,a){s=s.add(n),a=bt(a.add(s).add(r),21);const o=s;return s=s.add(e),s=s.add(t),a=a.add(bt(s,44)),[s.add(r),a.add(o)]}function Eo(n,e,t,r){return Vw(nt(n,e),nt(n,e+8),nt(n,e+16),nt(n,e+24),t,r)}function Uw(n,e=n.length){if(e>=8){const t=Ft.add(e*2),r=nt(n,0).add(Ft),s=nt(n,e-8),a=bt(s,37).mul(t).add(r),o=bt(r,25).add(s).mul(t);return xr(a,o,t)}if(e>=4){const t=Ft.add(e*2),r=fp(n,0);return xr(r.shl(3).add(e),fp(n,e-4),t)}if(e>0){const t=n[0],r=n[e>>1],s=n[e-1],a=t+(r<<8),o=e+(s<<2);return ol(Ft.mul(a).xor(Tf.mul(o))).mul(Ft)}return Ft}function Hw(n,e=n.length){const t=Ft.add(e*2),r=nt(n,0).mul(Zr),s=nt(n,8),a=nt(n,e-8).mul(t),o=nt(n,e-16).mul(Ft);return xr(bt(r.add(s),43).add(bt(a,30)).add(o),r.add(bt(s.add(Ft),18)).add(a),t)}function Gw(n,e=n.length){const t=Ft.add(e*2),r=nt(n,0).mul(Ft),s=nt(n,8),a=nt(n,e-8).mul(t),o=nt(n,e-16).mul(Ft),i=bt(r.add(s),43).add(bt(a,30)).add(o),l=xr(i,r.add(bt(s.add(Ft),18)).add(a),t),c=nt(n,16).mul(t),u=nt(n,24),d=i.add(nt(n,e-32)).mul(t),p=l.add(nt(n,e-24)).mul(t);return xr(bt(c.add(u),43).add(bt(d,30)).add(p),c.add(bt(u.add(r),18)).add(d),t)}function jw(n,e=n.length){const t=es.fromNumber(81,!0);if(e<=32)return e<=16?Uw(n,e):Hw(n,e);if(e<=64)return Gw(n,e);let r=t,s=t.mul(Zr).add(113),a=ol(s.mul(Ft).add(113)).mul(Ft),o=[es.UZERO,es.UZERO],i=[es.UZERO,es.UZERO];r=r.mul(Ft).add(nt(n,0));let l=0;const c=(e-1>>6)*64,u=c+(e-1&63)-63;do r=bt(r.add(s).add(o[0]).add(nt(n,l+8)),37).mul(Zr),s=bt(s.add(o[1]).add(nt(n,l+48)),42).mul(Zr),r=r.xor(i[1]),s=s.add(o[0]).add(nt(n,l+40)),a=bt(a.add(i[0]),33).mul(Zr),o=Eo(n,l,o[1].mul(Zr),r.add(i[0])),i=Eo(n,l+32,a.add(i[1]),s.add(nt(n,l+16))),[a,r]=[r,a],l+=64;while(l!==c);const d=Zr.add(a.and(255).shl(1));return l=u,i[0]=i[0].add(e-1&63),o[0]=o[0].add(i[0]),i[0]=i[0].add(o[0]),r=bt(r.add(s).add(o[0]).add(nt(n,l+8)),37).mul(d),s=bt(s.add(o[1]).add(nt(n,l+48)),42).mul(d),r=r.xor(i[1].mul(9)),s=s.add(o[0].mul(9).add(nt(n,l+40))),a=bt(a.add(i[0]),33).mul(d),o=Eo(n,l,o[1].mul(d),r.add(i[0])),i=Eo(n,l+32,a.add(i[1]),s.add(nt(n,l+16))),[a,r]=[r,a],xr(xr(o[0],i[0],d).add(ol(s).mul(Tf)).add(a),xr(o[1],i[1],d).add(r),d)}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function qw(n,e){return e==="string"?is(n):cu([n],e)}function Kw(n,e){return n instanceof Float32Array&&e==="float32"||n instanceof Int32Array&&e==="int32"||n instanceof Uint8Array&&e==="bool"}function cu(n,e){if(e==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(n)&&(n=fs(n)),fe().getBool("DEBUG")&&vw(n,e),Kw(n,e))return n;if(e==null||e==="float32"||e==="complex64")return new Float32Array(n);if(e==="int32")return new Int32Array(n);if(e==="bool"){const t=new Uint8Array(n.length);for(let r=0;r{s=r()};let o;const i=ta();if(this.backendTimer.timerAvailable())o=this.backendTimer.time(a);else{a();for(const c of s)c.dataSync();o=Promise.resolve({kernelMs:ta()-i})}if(fe().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let c=0;c{Qw(d,u.dtype,e)})}return{kernelName:e,outputs:s,inputs:t,timeMs:o.then(c=>c.kernelMs),extraInfo:o.then(c=>c.getExtraProfileInfo!=null?c.getExtraProfileInfo():"")}}logKernelProfile(e){const{kernelName:t,outputs:r,timeMs:s,inputs:a,extraInfo:o}=e;r.forEach(i=>{Promise.all([i.data(),s,o]).then(l=>{this.logger.logKernelProfile(t,i,l[0],l[1],a,l[2])})})}}function Qw(n,e,t){if(e!=="float32")return!1;for(let r=0;r0?g:""} `}}console.log(`%c${l} %c${i} %c${c}D ${d} %c${u} %c${p} %c${o}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Jw(n,e,t){const r={},s={};for(let l=0;lr[g.id]=!0),f=!0,s[c.id]=!0;break}if(f)break}}const a={};a[t.id]=!0;const o={};for(let l=n.length-1;l>=0;l--){const c=n[l],u=c.inputs;for(let d=0;d=0;s--){const a=e[s],o=[];if(a.outputs.forEach(l=>{const c=n[l.id];c!=null?o.push(c):o.push(null)}),a.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${a.kernelName}.`);const i=a.gradient(o);for(const l in a.inputs){if(!(l in i))throw new Error(`Cannot backprop through input ${l}. Available gradients found: ${Object.keys(i)}.`);const c=t(()=>i[l]());if(c.dtype!=="float32")throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${c.dtype}'`);const u=a.inputs[l];if(!Vt(c.shape,u.shape))throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input '${l}' has shape '${c.shape}', which does not match the shape of the input '${u.shape}'`);if(n[u.id]==null)n[u.id]=c;else{const d=n[u.id];n[u.id]=r(d,c),d.dispose()}}}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const mp=20,Fa=3,Pu=7;function t0(n,e,t,r){const s=et(e),a=n0(n,e,t,s),o=e.length,i=Po(n,e,t,s,a),l=["Tensor"];return r&&(l.push(` dtype: ${t}`),l.push(` rank: ${o}`),l.push(` shape: [${e}]`),l.push(" values:")),l.push(i.map(c=>" "+c).join(` +`)),l.join(` +`)}function n0(n,e,t,r){const s=q(e),a=r[r.length-1],o=new Array(a).fill(0),i=e.length,l=t==="complex64"?za(n):n;if(i>1)for(let c=0;cmp){const b=Fa*o;let v=Array.from(n.slice(0,b)),I=Array.from(n.slice((i-Fa)*o,i*o));return t==="complex64"&&(v=za(v),I=za(I)),["["+v.map((S,C)=>La(S,s[C],t)).join(", ")+", ..., "+I.map((S,C)=>La(S,s[i-Fa+C],t)).join(", ")+"]"]}return["["+(t==="complex64"?za(n):Array.from(n)).map((b,v)=>La(b,s[v],t)).join(", ")+"]"]}const c=e.slice(1),u=r.slice(1),d=r[0]*o,p=[];if(i>mp){for(let g=0;g0?p[0]+f:"");for(let g=1;g`Length of values '${s}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=r||Ar(t,this.size),this.strides=et(e)}set(e,...t){t.length===0&&(t=[0]),$(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);const r=this.locToIndex(t);this.values[r]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(const s of e){if(s<0||s>=this.shape[t]){const a=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(a)}t++}let r=e[e.length-1];for(let s=0;sna(r))}catch{throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataToGPU(e){return this.throwIfDisposed(),kn().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=kn().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>na(t))}catch{throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();const e=await kn().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(this.kerasMask&&this.kerasMask.dispose(),kn().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Ks.print(this,e)}clone(){return this.throwIfDisposed(),Ks.clone(this)}toString(e=!1){const t=this.dataSync();return t0(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Ks.cast(this,e)}variable(e=!0,t,r){return this.throwIfDisposed(),kn().makeVariable(this,e,t,r)}}Object.defineProperty(dt,Symbol.hasInstance,{value:n=>!!n&&n.data!=null&&n.dataSync!=null&&n.throwIfDisposed!=null});function Rf(){return jl("Tensor",()=>dt)}Rf();class Yo extends dt{constructor(e,t,r,s){super(e.shape,e.dtype,e.dataId,s),this.trainable=t,this.name=r}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!Vt(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);kn().disposeTensor(this),this.dataId=e.dataId,kn().incRef(this,null)}dispose(){kn().disposeVariable(this),this.isDisposedInternal=!0}}Object.defineProperty(Yo,Symbol.hasInstance,{value:n=>n instanceof dt&&n.assign!=null&&n.assign instanceof Function});/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var gp;(function(n){n.R0="R0",n.R1="R1",n.R2="R2",n.R3="R3",n.R4="R4",n.R5="R5",n.R6="R6"})(gp||(gp={}));var il;(function(n){n.float32="float32",n.int32="int32",n.bool="int32",n.complex64="complex64"})(il||(il={}));var ul;(function(n){n.float32="float32",n.int32="int32",n.bool="bool",n.complex64="complex64"})(ul||(ul={}));var ll;(function(n){n.float32="float32",n.int32="float32",n.bool="float32",n.complex64="complex64"})(ll||(ll={}));var cl;(function(n){n.float32="complex64",n.int32="complex64",n.bool="complex64",n.complex64="complex64"})(cl||(cl={}));const a0={float32:ll,int32:il,bool:ul,complex64:cl};function _r(n,e){if(n==="string"||e==="string"){if(n==="string"&&e==="string")return"string";throw new Error(`Can not upcast ${n} with ${e}`)}return a0[n][e]}function o0(n){return _r(n,"int32")}function Df(n){return n!=null&&typeof n=="object"&&"texture"in n&&n.texture instanceof WebGLTexture}function Pf(n){return typeof GPUBuffer<"u"&&n!=null&&typeof n=="object"&&"buffer"in n&&n.buffer instanceof GPUBuffer}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function pt(n,e){if(n.dtype===e.dtype)return[n,e];const t=_r(n.dtype,e.dtype);return[n.cast(t),e.cast(t)]}function i0(n,e){$(n.dtype===e.dtype,()=>`The dtypes of the first(${n.dtype}) and second(${e.dtype}) input must match`)}function Ff(n){const e=[];return Of(n,e,new Set),e}function Of(n,e,t){if(n==null)return;if(n instanceof dt){e.push(n);return}if(!u0(n))return;const r=n;for(const s in r){const a=r[s];t.has(a)||(t.add(a),Of(a,e,t))}}function u0(n){return Array.isArray(n)||typeof n=="object"}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Fu(n){return n.kernelName!=null}class yp{constructor(){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,get kernelNames(){return Array.from(new Set(this.kernels.map(e=>e.name)))}}}dispose(){for(const e in this.registeredVariables)this.registeredVariables[e].dispose()}}class sa{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new yp}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;const e=this.getSortedBackends();for(let t=0;t{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){pp(e).forEach(r=>{r.disposeFunc!=null&&r.disposeFunc(this.registry[e])})}initializeBackend(e){const t=this.registryFactory[e];if(t==null)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const r=t.factory();if(r&&!(r instanceof Gl)&&typeof r.then=="function"){const s=++this.pendingBackendInitId,a=r.then(o=>s(sthis.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;tthis.startScope(r),()=>this.endScope(s),()=>(s=t(),s instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),s))}scopedRun(e,t,r){e();try{const s=r();return t(),s}catch(s){throw t(),s}}nextTensorId(){return sa.nextTensorId++}nextVariableId(){return sa.nextVariableId++}clone(e){const t=z.runKernel(Di,{x:e}),r={x:e},s=o=>({x:()=>{const i="float32",l={x:o},c={dtype:i};return z.runKernel(bi,l,c)}}),a=[];return this.addTapeNode(this.state.activeScope.name,r,[t],s,a,{}),t}runKernel(e,t,r){if(this.backendName==null&&this.backend,!(Ko(e,this.backendName)!=null))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:r})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,r){const s=this.backend.numDataIds();let a=0;r.forEach(l=>{a+=l.dtype==="complex64"?3:1});const o=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],i=s-t-a-o;if(i>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${i} data ids) after running '${e}'`)}runKernelFunc(e){let t,r=[];const s=this.isTapeOn(),a=this.state.numBytes,o=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let i;this.backendName==null&&this.backend;let l;const c=Fu(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(Fu(e)){const{kernelName:m,inputs:g,attrs:b}=e;this.backendName==null&&this.backend;const v=Ko(m,this.backendName);$(v!=null,()=>`Cannot find registered kernel '${m}' for backend '${this.backendName}'`),i=()=>{const I=this.backend.numDataIds();l=v.kernelFunc({inputs:g,attrs:b,backend:this.backend});const S=Array.isArray(l)?l:[l];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(m,I,S);const C=S.map(T=>T.rank!=null?T:this.makeTensorFromTensorInfo(T));if(s){const T=this.getTensorsForGradient(m,g,C);r=this.saveTensorsForBackwardMode(T)}return C}}else{const{forwardFunc:m}=e,g=b=>{s&&(r=b.map(v=>this.keep(this.clone(v))))};i=()=>{const b=this.backend.numDataIds();l=this.tidy(()=>m(this.backend,g));const v=Array.isArray(l)?l:[l];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(c,b,v),v}}const{inputs:u,attrs:d}=e,p=Fu(e)?null:e.backwardsFunc;let f;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?t=i():(f=this.profiler.profileKernel(c,u,()=>i()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(f),t=f.outputs)}),s&&this.addTapeNode(c,u,t,p,r,d),this.state.profiling&&this.state.activeProfile.kernels.push({name:c,bytesAdded:this.state.numBytes-a,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-o,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(u).map(m=>u[m]!=null?u[m].shape:null),outputShapes:t.map(m=>m.shape),kernelTimeMs:f.timeMs,extraInfo:f.extraInfo}),Array.isArray(l)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(r=>this.keep(this.clone(r)))}getTensorsForGradient(e,t,r){const s=dp(e);if(s!=null){const a=s.inputsToSave||[],o=s.outputsToSave||[];let i;s.saveAllInputs?($(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),i=Object.keys(t).map(c=>t[c])):i=a.map(c=>t[c]);const l=r.filter((c,u)=>o[u]);return i.concat(l)}return[]}makeTensor(e,t,r,s){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");r=r||"float32",s=s||this.backend;let a=e;r==="string"&&ci(e[0])&&(a=e.map(l=>is(l)));const o=s.write(a,t,r),i=new dt(t,r,o,this.nextTensorId());if(this.trackTensor(i,s),r==="string"){const l=this.state.tensorInfo.get(o),c=kw(a);this.state.numBytes+=c-l.bytes,l.bytes=c}return i}makeTensorFromDataId(e,t,r,s){r=r||"float32";const a={dataId:e,shape:t,dtype:r};return this.makeTensorFromTensorInfo(a,s)}makeTensorFromTensorInfo(e,t){const{dataId:r,shape:s,dtype:a}=e,o=new dt(s,a,r,this.nextTensorId());return this.trackTensor(o,t),o}makeVariable(e,t=!0,r,s){r=r||this.nextVariableId().toString(),s!=null&&s!==e.dtype&&(e=e.cast(s));const a=new Yo(e,t,r,this.nextTensorId());if(this.state.registeredVariables[a.name]!=null)throw new Error(`Variable with name ${a.name} was already registered`);return this.state.registeredVariables[a.name]=a,this.incRef(a,this.backend),a}trackTensor(e,t){this.state.numTensors++,e.dtype==="string"&&this.state.numStringTensors++;let r=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(r=e.size*qa(e.dtype)),this.state.numBytes+=r,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:r})),e instanceof Yo||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;const t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,e.dtype==="string"&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),e.dtype!=="complex64"&&e.dtype!=="string"){const r=e.size*qa(e.dtype);this.state.numBytes-=r}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(const e in this.state.registeredVariables){const t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),this.state.registeredVariables[e.name]!=null&&delete this.state.registeredVariables[e.name]}memory(){const e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,e.reasons==null&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;const t=this.state.numBytes,r=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(s=>s.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-r;for(const s of this.state.activeProfile.kernels)s.kernelTimeMs=await s.kernelTimeMs,s.extraInfo=await s.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,r,s,a,o){const i={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:r,saved:a},l=dp(e);l!=null&&(s=l.gradFunc),s!=null&&(i.gradient=c=>(c=c.map((u,d)=>{if(u==null){const p=r[d],f=ps(p.size,p.dtype);return this.makeTensor(f,p.shape,p.dtype)}return u}),s(c.length>1?c:c[0],a,o))),this.state.activeTape.push(i)}keep(e){return e.kept=!0,e}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){const t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){const t=Ff(e),r=new Set(t.map(a=>a.id));for(let a=0;a{!a.kept&&a.scopeId===s.id&&this.track(a)})}gradients(e,t,r,s=!1){if($(t.length>0,()=>"gradients() received an empty list of xs."),r!=null&&r.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${r.dtype}'`);const a=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));$(a instanceof dt,()=>"The result y returned by f() must be a tensor.");const o=Jw(this.state.activeTape,t,a);if(!s&&o.length===0&&t.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",()=>{const i={};i[a.id]=r??l0(a.shape),e0(i,o,c=>this.tidy(c),c0);const l=t.map(c=>i[c.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(c=>{for(const u of c.saved)u.dispose()}),this.state.activeTape=null),{value:a,grads:l}})}customGrad(e){return $(nl(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{$(t.every(i=>i instanceof dt),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let r;const s={};t.forEach((i,l)=>{s[l]=i});const a=(i,l)=>(r=e(...t,l),$(r.value instanceof dt,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),$(nl(r.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),r.value),o=(i,l)=>{const c=r.gradFunc(i,l),u=Array.isArray(c)?c:[c];$(u.length===t.length,()=>"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(...)."),$(u.every(p=>p instanceof dt),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");const d={};return u.forEach((p,f)=>{d[f]=()=>p}),d};return this.runKernelFunc({forwardFunc:a,backwardsFunc:o,inputs:s})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}readToGPU(e,t){return this.state.tensorInfo.get(e).backend.readToGPU(e,t)}async time(e){const t=ta(),r=await this.backend.time(e);return r.wallMs=ta()-t,r}track(e){return this.state.activeScope!=null&&(e.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(e)),e}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new yp;for(const e in this.registry)this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}}sa.nextTensorId=0;sa.nextVariableId=0;function l0(n){const e=Qh(q(n),"float32");return z.makeTensor(e,n,"float32")}function Mf(){const n=ef();if(n._tfengine==null){const e=new Nw(n);n._tfengine=new sa(e)}return Aw(n._tfengine.ENV),r0(()=>n._tfengine),n._tfengine}const z=Mf();function c0(n,e){const t={a:n,b:e};return z.runKernel(di,t)}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function d0(){return typeof window<"u"&&window.document!=null||typeof WorkerGlobalScope<"u"}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ut=fe();Ut.registerFlag("DEBUG",()=>!1,n=>{n&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")});Ut.registerFlag("IS_BROWSER",()=>d0());Ut.registerFlag("IS_NODE",()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u");Ut.registerFlag("IS_CHROME",()=>typeof navigator<"u"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));Ut.registerFlag("IS_SAFARI",()=>typeof navigator<"u"&&navigator!=null&&navigator.userAgent!=null&&/Safari/.test(navigator.userAgent)&&/Apple/.test(navigator.vendor));Ut.registerFlag("PROD",()=>!1);Ut.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Ut.getBool("DEBUG"));Ut.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);Ut.registerFlag("IS_TEST",()=>!1);Ut.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>Ut.getBool("DEBUG"));Ut.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);Ut.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",()=>!1);Ut.registerFlag("USE_SETTIMEOUTCUSTOM",()=>!1);/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Rr(n,e){let t=n;if(mn(n))return e==="string"?[]:[n.length];if(Df(n)){const s=n.channels||"RGBA";return[n.height,n.width*s.length]}else if(Pf(n))return[n.buffer.size/(e==null?4:qa(e))];if(!Array.isArray(n))return[];const r=[];for(;Array.isArray(t)||mn(t)&&e!=="string";)r.push(t.length),t=t[0];return Array.isArray(n)&&fe().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&Lf(n,r,[]),r}function Lf(n,e,t){if(t=t||[],!Array.isArray(n)&&!mn(n)){$(e.length===0,()=>`Element arr[${t.join("][")}] is a primitive, but should be an array/TypedArray of ${e[0]} elements`);return}$(e.length>0,()=>`Element arr[${t.join("][")}] should be a primitive, but is an array of ${n.length} elements`),$(n.length===e[0],()=>`Element arr[${t.join("][")}] should have ${e[0]} elements, but has ${n.length} elements`);const r=e.slice(1);for(let s=0;s=0&&(s=r),bp(r,s,e,t),n==null||!mn(n)&&!Array.isArray(n)&&typeof n!="number"&&typeof n!="boolean"&&typeof n!="string"){const l=n==null?"null":n.constructor.name;throw new Error(`Argument '${e}' passed to '${t}' must be a Tensor or TensorLike, but got '${l}'`)}const a=Rr(n,s);!mn(n)&&!Array.isArray(n)&&(n=[n]);const i=s!=="string"?cu(n,s):fs(n,[],!0);return z.makeTensor(i,a,s)}function Qo(n,e,t,r="numeric"){if(!Array.isArray(n))throw new Error(`Argument ${e} passed to ${t} must be a \`Tensor[]\` or \`TensorLike[]\``);return n.map((a,o)=>N(a,`${e}[${o}]`,t,r))}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const zf="__op";function M(n){const e=Object.keys(n);if(e.length!==1)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${e.length} keys.`);let t=e[0];const r=n[t];t.endsWith("_")&&(t=t.substring(0,t.length-1)),t=t+zf;const s=(...a)=>{z.startScope(t);try{const o=r(...a);return hs(o)&&console.error("Cannot return a Promise inside of tidy."),z.endScope(o),o}catch(o){throw z.endScope(null),o}};return Object.defineProperty(s,"name",{value:t,configurable:!0}),s}/** + * @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. + * ============================================================================= + */function p0(n,e){const t=N(n,"real","complex"),r=N(e,"imag","complex");Yt(t.shape,r.shape,`real and imag shapes, ${t.shape} and ${r.shape}, must match in call to tf.complex().`);const s={real:t,imag:r};return z.runKernel(sf,s)}const Cr=M({complex_:p0});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Dr(n,e,t,r){if(r==null)r=da(n);else if(r==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(Pf(n)||Df(n)){if(r!=="float32"&&r!=="int32")throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${r}.`);return z.backend.createTensorFromGPUData(n,e||t,r)}if(!mn(n)&&!Array.isArray(n)&&typeof n!="number"&&typeof n!="boolean"&&typeof n!="string")throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(e!=null){nn(e);const s=q(e),a=q(t);$(s===a,()=>`Based on the provided shape, [${e}], the tensor should have ${s} values but has ${a}`);for(let o=0;o`Error creating a new Tensor. Inferred shape (${t}) does not match the provided shape (${e}). `)}}return!mn(n)&&!Array.isArray(n)&&(n=[n]),e=e||t,n=r!=="string"?cu(n,r):fs(n,[],!0),z.makeTensor(n,e,r)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function _n(n,e,t){const r=Rr(n,t);return Dr(n,e,r,t)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ms={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};class Cn{static join(e){return new Cn(e).slice()}constructor(e){if(this.shards=[],this.previousShardIndex=0,e==null||(e instanceof Array||(e=[e]),e=e.map(r=>mn(r)?r.buffer:r),e.length===0))return;this.bufferUniformSize=e[0].byteLength;let t=0;for(let r=0;r=this.byteLength)return-1;if(this.bufferUniformSize!=null)return this.previousShardIndex=Math.floor(e/this.bufferUniformSize),this.previousShardIndex;function t(s){return e=s.end?1:0}if(t(this.shards[this.previousShardIndex])===0)return this.previousShardIndex;const r=h0(this.shards,t);return r===-1?-1:(this.previousShardIndex=r,this.previousShardIndex)}}function h0(n,e){let t=0,r=n.length;for(;t<=r;){const s=Math.floor((r-t)/2)+t,a=e(n[s]);if(a===0)return s;a<0?r=s:t=s+1}return-1}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function us(){return z}function Ce(n,e){return z.tidy(n,e)}function Ke(n){Ff(n).forEach(t=>t.dispose())}function zn(n){return z.keep(n)}function f0(n){return z.setBackend(n)}function m0(){return z.ready()}function Qa(){return z.backendName}function Bf(n,e,t=1){return z.registerBackend(n,e,t)}function aa(){return z.backend}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Nr=4;async function g0(n,e){const t=[],r=[],s=Array.isArray(n)?n.map(o=>o.name):Object.keys(n);for(let o=0;o{const p=await l.bytes(),f=p.reduce((b,v)=>b+v.length,0)+Nr*p.length,m=new Uint8Array(f);let g=0;for(let b=0;bt.slice(s+i,s+l));r[a.name]=Vf(a,t.slice(s,s+o)),s+=o}return r}function y0(n,e){const t=q(n.shape);let r;if("quantization"in n){const s=n.quantization;r=ms[s.dtype]}else if(n.dtype==="string"){let s=0;for(let a=0;a(s=await wp(r,s,u),s.slice(c,u)));s=await wp(r,s,o);const i=s.slice(0,o);s=s.slice(o);const l=Vf(a,i);if(t[a.name]=l,Qa()==="webgpu"){const c=aa();"uploadToGPU"in c&&q(l.shape)>=fe().get("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD")&&c.uploadToGPU(l.dataId)}}return t}function w0(n){if(n===null)throw new Error(`Invalid input value: ${JSON.stringify(n)}`);let e=0;const t=[];n.forEach(a=>{if(e+=a.byteLength,t.push(a.byteLength===a.buffer.byteLength?a:new a.constructor(a)),!(a instanceof Float32Array||a instanceof Int32Array||a instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${a.constructor.name}`)});const r=new Uint8Array(e);let s=0;return t.forEach(a=>{r.set(new Uint8Array(a.buffer),s),s+=a.byteLength}),r.buffer}const Td=typeof Buffer<"u"&&(typeof Blob>"u"||typeof atob>"u"||typeof btoa>"u");function xp(n){return Td?Buffer.byteLength(n,"utf8"):new Blob([n]).size}function x0(n){if(Td)return Buffer.from(n).toString("base64");const e=new Uint8Array(n);let t="";for(let r=0,s=e.length;r{let r=t<<13,s=0;for(;(r&8388608)===0;)s-=8388608,r<<=1;return r&=-8388609,s+=947912704,r|s},e=new Uint32Array(2048);e[0]=0;for(let t=1;t<1024;t++)e[t]=n(t);for(let t=1024;t<2048;t++)e[t]=939524096+(t-1024<<13);return e}function k0(){const n=new Uint32Array(64);n[0]=0,n[31]=1199570944,n[32]=2147483648,n[63]=3347054592;for(let e=1;e<31;e++)n[e]=e<<23;for(let e=33;e<63;e++)n[e]=2147483648+(e-32<<23);return n}function _0(){const n=new Uint32Array(64);for(let e=0;e<64;e++)n[e]=1024;return n[0]=n[32]=0,n}function C0(){const n=I0(),e=k0(),t=_0();return r=>{const s=new ArrayBuffer(4*r.length),a=new Uint32Array(s);for(let o=0;o>10]+(i&1023)]+e[i>>10];a[o]=l}return new Float32Array(s)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class ct{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return ct.instance==null&&(ct.instance=new ct),ct.instance}static registerSaveRouter(e){ct.getInstance().saveRouters.push(e)}static registerLoadRouter(e){ct.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return ct.getHandlers(e,"save")}static getLoadHandlers(e,t){return ct.getHandlers(e,"load",t)}static getHandlers(e,t,r){const s=[];return(t==="load"?ct.getInstance().loadRouters:ct.getInstance().saveRouters).forEach(o=>{const i=o(e,r);i!==null&&s.push(i)}),s}}const N0=n=>ct.registerSaveRouter(n),$0=n=>ct.registerLoadRouter(n),T0=n=>ct.getSaveHandlers(n),E0=(n,e)=>ct.getLoadHandlers(n,e);/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const pl="tensorflowjs",hl=1,ss="models_store",br="model_info_store";function jf(){if(!fe().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");const n=typeof window>"u"?self:window,e=n.indexedDB||n.mozIndexedDB||n.webkitIndexedDB||n.msIndexedDB||n.shimIndexedDB;if(e==null)throw new Error("The current browser does not appear to support IndexedDB.");return e}function fl(n){const e=n.result;e.createObjectStore(ss,{keyPath:"modelPath"}),e.createObjectStore(br,{keyPath:"modelPath"})}class gs{constructor(e){if(this.indexedDB=jf(),e==null||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,e)}async load(){return this.databaseAction(this.modelPath)}databaseAction(e,t){return new Promise((r,s)=>{const a=this.indexedDB.open(pl,hl);a.onupgradeneeded=()=>fl(a),a.onsuccess=()=>{const o=a.result;if(t==null){const i=o.transaction(ss,"readonly"),c=i.objectStore(ss).get(this.modelPath);c.onsuccess=()=>{if(c.result==null)return o.close(),s(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));r(c.result.modelArtifacts)},c.onerror=u=>(o.close(),s(c.error)),i.oncomplete=()=>o.close()}else{t.weightData=Cn.join(t.weightData);const i=po(t),l=o.transaction(br,"readwrite");let c=l.objectStore(br),u;try{u=c.put({modelPath:this.modelPath,modelArtifactsInfo:i})}catch(p){return s(p)}let d;u.onsuccess=()=>{d=o.transaction(ss,"readwrite");const p=d.objectStore(ss);let f;try{f=p.put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:i})}catch(m){return s(m)}f.onsuccess=()=>r({modelArtifactsInfo:i}),f.onerror=m=>{c=l.objectStore(br);const g=c.delete(this.modelPath);g.onsuccess=()=>(o.close(),s(f.error)),g.onerror=b=>(o.close(),s(f.error))}},u.onerror=p=>(o.close(),s(u.error)),l.oncomplete=()=>{d==null?o.close():d.oncomplete=()=>o.close()}}},a.onerror=o=>s(a.error)})}}gs.URL_SCHEME="indexeddb://";const qf=n=>fe().getBool("IS_BROWSER")&&!Array.isArray(n)&&n.startsWith(gs.URL_SCHEME)?A0(n.slice(gs.URL_SCHEME.length)):null;ct.registerSaveRouter(qf);ct.registerLoadRouter(qf);function A0(n){return new gs(n)}function R0(n){return n.startsWith(gs.URL_SCHEME)?n.slice(gs.URL_SCHEME.length):n}class D0{constructor(){this.indexedDB=jf()}async listModels(){return new Promise((e,t)=>{const r=this.indexedDB.open(pl,hl);r.onupgradeneeded=()=>fl(r),r.onsuccess=()=>{const s=r.result,a=s.transaction(br,"readonly"),i=a.objectStore(br).getAll();i.onsuccess=()=>{const l={};for(const c of i.result)l[c.modelPath]=c.modelArtifactsInfo;e(l)},i.onerror=l=>(s.close(),t(i.error)),a.oncomplete=()=>s.close()},r.onerror=s=>t(r.error)})}async removeModel(e){return e=R0(e),new Promise((t,r)=>{const s=this.indexedDB.open(pl,hl);s.onupgradeneeded=()=>fl(s),s.onsuccess=()=>{const a=s.result,o=a.transaction(br,"readwrite"),i=o.objectStore(br),l=i.get(e);let c;l.onsuccess=()=>{if(l.result==null)return a.close(),r(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{const u=i.delete(e),d=()=>{c=a.transaction(ss,"readwrite");const f=c.objectStore(ss).delete(e);f.onsuccess=()=>t(l.result.modelArtifactsInfo),f.onerror=m=>r(l.error)};u.onsuccess=d,u.onerror=p=>(d(),a.close(),r(l.error))}},l.onerror=u=>(a.close(),r(l.error)),o.oncomplete=()=>{c==null?a.close():c.oncomplete=()=>a.close()}},s.onerror=a=>r(s.error)})}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Jn="/",Xs="tensorflowjs_models",Kf="info",P0="model_topology",F0="weight_specs",O0="weight_data",M0="model_metadata";function Xf(n){return{info:[Xs,n,Kf].join(Jn),topology:[Xs,n,P0].join(Jn),weightSpecs:[Xs,n,F0].join(Jn),weightData:[Xs,n,O0].join(Jn),modelMetadata:[Xs,n,M0].join(Jn)}}function Yf(n){for(const e of Object.values(n))window.localStorage.removeItem(e)}function L0(n){const e=n.split(Jn);if(e.length<3)throw new Error(`Invalid key format: ${n}`);return e.slice(1,e.length-1).join(Jn)}function z0(n){return n.startsWith(ys.URL_SCHEME)?n.slice(ys.URL_SCHEME.length):n}class ys{constructor(e){if(!fe().getBool("IS_BROWSER")||typeof window>"u"||typeof window.localStorage>"u")throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,e==null||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=Xf(this.modelPath)}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{const t=JSON.stringify(e.modelTopology),r=JSON.stringify(e.weightSpecs),s=po(e),a=Cn.join(e.weightData);try{this.LS.setItem(this.keys.info,JSON.stringify(s)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,r),this.LS.setItem(this.keys.weightData,x0(a));const o={format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,signature:e.signature!=null?e.signature:void 0,userDefinedMetadata:e.userDefinedMetadata!=null?e.userDefinedMetadata:void 0,modelInitializer:e.modelInitializer!=null?e.modelInitializer:void 0,initializerSignature:e.initializerSignature!=null?e.initializerSignature:void 0,trainingConfig:e.trainingConfig!=null?e.trainingConfig:void 0};return this.LS.setItem(this.keys.modelMetadata,JSON.stringify(o)),{modelArtifactsInfo:s}}catch{throw Yf(this.keys),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${s.modelTopologyBytes}, weightSpecsBytes=${s.weightSpecsBytes}, weightDataBytes=${s.weightDataBytes}.`)}}}async load(){const e=JSON.parse(this.LS.getItem(this.keys.info));if(e==null)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if(e.modelTopologyType!=="JSON")throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");const t={},r=JSON.parse(this.LS.getItem(this.keys.topology));if(r==null)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);t.modelTopology=r;const s=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(s==null)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=s;const a=this.LS.getItem(this.keys.modelMetadata);if(a!=null){const i=JSON.parse(a);t.format=i.format,t.generatedBy=i.generatedBy,t.convertedBy=i.convertedBy,i.signature!=null&&(t.signature=i.signature),i.userDefinedMetadata!=null&&(t.userDefinedMetadata=i.userDefinedMetadata),i.modelInitializer!=null&&(t.modelInitializer=i.modelInitializer),i.initializerSignature!=null&&(t.initializerSignature=i.initializerSignature),i.trainingConfig!=null&&(t.trainingConfig=i.trainingConfig)}const o=this.LS.getItem(this.keys.weightData);if(o==null)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=v0(o),t}}ys.URL_SCHEME="localstorage://";const Qf=n=>fe().getBool("IS_BROWSER")&&!Array.isArray(n)&&n.startsWith(ys.URL_SCHEME)?B0(n.slice(ys.URL_SCHEME.length)):null;ct.registerSaveRouter(Qf);ct.registerLoadRouter(Qf);function B0(n){return new ys(n)}class W0{constructor(){$(fe().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),$(typeof window>"u"||typeof window.localStorage<"u",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){const e={},t=Xs+Jn,r=Jn+Kf;for(let s=0;s"scheme must not be undefined or null."),e.endsWith(Zs)&&(e=e.slice(0,e.indexOf(Zs))),$(e.length>0,()=>"scheme must not be an empty string.");const r=Pt.getInstance();$(r.managers[e]==null,()=>`A model store manager is already registered for scheme '${e}'.`),r.managers[e]=t}static getManager(e){const t=Pt.getInstance().managers[e];if(t==null)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(Pt.getInstance().managers)}}function Fo(n){if(n.indexOf(Zs)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Pt.getSchemes().join(",")}`);return{scheme:n.split(Zs)[0],path:n.split(Zs)[1]}}async function Zf(n,e,t=!1){$(n!==e,()=>`Old path and new path are the same: '${n}'`);const r=ct.getLoadHandlers(n);$(r.length>0,()=>`Copying failed because no load handler is found for source URL ${n}.`),$(r.length<2,()=>`Copying failed because more than one (${r.length}) load handlers for source URL ${n}.`);const s=r[0],a=ct.getSaveHandlers(e);$(a.length>0,()=>`Copying failed because no save handler is found for destination URL ${e}.`),$(a.length<2,()=>`Copying failed because more than one (${r.length}) save handlers for destination URL ${e}.`);const o=a[0],i=Fo(n).scheme,l=Fo(n).path,c=i===Fo(n).scheme,u=await s.load();t&&c&&await Pt.getManager(i).removeModel(l);const d=await o.save(u);return t&&!c&&await Pt.getManager(i).removeModel(l),d.modelArtifactsInfo}async function V0(){const n=Pt.getSchemes(),e={};for(const t of n){const r=await Pt.getManager(t).listModels();for(const s in r){const a=t+Zs+s;e[a]=r[s]}}return e}async function U0(n){const e=Fo(n);return Pt.getManager(e.scheme).removeModel(e.path)}async function H0(n,e){return Zf(n,e,!1)}async function G0(n,e){return Zf(n,e,!0)}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class j0{constructor(){this.messageName="setTimeoutCustom",this.functionRefs=[],this.handledMessageCount=0,this.hasEventListener=!1}fetch(e,t){return fetch(e,t)}now(){return performance.now()}encode(e,t){if(t!=="utf-8"&&t!=="utf8")throw new Error(`Browser's encoder only supports utf-8, but got ${t}`);return this.textEncoder==null&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}setTimeoutCustom(e,t){if(typeof window>"u"||!fe().getBool("USE_SETTIMEOUTCUSTOM")){setTimeout(e,t);return}this.functionRefs.push(e),setTimeout(()=>{window.postMessage({name:this.messageName,index:this.functionRefs.length-1},"*")},t),this.hasEventListener||(this.hasEventListener=!0,window.addEventListener("message",r=>{if(r.source===window&&r.data.name===this.messageName){r.stopPropagation();const s=this.functionRefs[r.data.index];s(),this.handledMessageCount++,this.handledMessageCount===this.functionRefs.length&&(this.functionRefs=[],this.handledMessageCount=0)}},!0))}isTypedArray(e){return Cf(e)}}if(fe().get("IS_BROWSER")){fe().setPlatform("browser",new j0);try{Pt.registerManager(ys.URL_SCHEME,new W0)}catch{}try{Pt.registerManager(gs.URL_SCHEME,new D0)}catch{}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const q0={importFetch:()=>require("node-fetch")};let Ou;class K0{constructor(){this.util=require("util"),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return fe().global.fetch!=null?fe().global.fetch(e,t):(Ou==null&&(Ou=q0.importFetch()),Ou(e,t))}now(){const e=process.hrtime();return e[0]*1e3+e[1]/1e6}encode(e,t){if(t!=="utf-8"&&t!=="utf8")throw new Error(`Node built-in encoder only supports utf-8, but got ${t}`);return this.textEncoder.encode(e)}decode(e,t){return e.length===0?"":new this.util.TextDecoder(t).decode(e)}isTypedArray(e){return this.util.types.isFloat32Array(e)||this.util.types.isInt32Array(e)||this.util.types.isUint8Array(e)||this.util.types.isUint8ClampedArray(e)}}fe().get("IS_NODE")&&!fe().get("IS_BROWSER")&&fe().setPlatform("node",new K0);/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ut(n,e="float32",t){return e=e||"float32",nn(n),new ra(n,e,t)}/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function X0(n,e){const t=N(n,"x","cast");if(!Sw(e))throw new Error(`Failed to cast to unknown dtype ${e}`);if(e==="string"&&t.dtype!=="string"||e!=="string"&&t.dtype==="string")throw new Error("Only strings can be casted to strings");const r={x:t},s={dtype:e};return z.runKernel(bi,r,s)}const tt=M({cast_:X0});/** + * @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. + * ============================================================================= + */function Y0(n){const t={x:N(n,"x","clone","string_or_numeric")};return z.runKernel(Di,t)}const vr=M({clone_:Y0});/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Jf(n,e=!1){console.log(n.toString(e))}/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */Mf();const Q0={buffer:ut,cast:tt,clone:vr,print:Jf};s0(Q0);/** + * @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. + * ============================================================================= + */function Z0(n,e){let t=N(n,"a","add"),r=N(e,"b","add");[t,r]=pt(t,r);const s={a:t,b:r};return z.runKernel(di,s)}const he=M({add_:Z0});/** + * @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. + * ============================================================================= + */function J0(n,e){let t=N(n,"a","floorDiv"),r=N(e,"b","floorDiv");[t,r]=pt(t,r);const s={a:t,b:r};return z.runKernel(_c,s)}const em=M({floorDiv_:J0});/** + * @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. + * ============================================================================= + */function e1(n,e){let t=N(n,"a","div"),r=N(e,"b","div");if([t,r]=pt(t,r),t.dtype==="int32"&&r.dtype==="int32")return em(t,r);const s={a:t,b:r},a={};return z.runKernel(mc,s,a)}const Re=M({div_:e1});/** + * @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. + * ============================================================================= + */function t1(n,e){let t=N(n,"a","mul"),r=N(e,"b","mul");[t,r]=pt(t,r);const s={a:t,b:r};return z.runKernel(Gc,s)}const Z=M({mul_:t1});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function n1(n){const e=N(n,"x","abs");if(e.dtype==="complex64"){const t={x:e};return z.runKernel(af,t)}else{const t={x:e};return z.runKernel(ql,t)}}const Jt=M({abs_:n1});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function r1(n){const t={x:N(n,"x","acos")};return z.runKernel(Kl,t)}const s1=M({acos_:r1});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function a1(n){const t={x:N(n,"x","acosh")};return z.runKernel(Xl,t)}const o1=M({acosh_:a1});/** + * @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. + * ============================================================================= + */function i1(n){$(Array.isArray(n),()=>"The argument passed to tf.addN() must be a list of tensors"),$(n.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${n.length}`);const e=n.map((s,a)=>N(s,`tensors${a}`,"addN")),t=e[0];e.forEach(s=>{if(s.dtype!==t.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),e.forEach(s=>{if(!Vt(s.shape,t.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});const r=e;return z.runKernel(pi,r)}const u1=M({addN_:i1});/** + * @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. + * ============================================================================= + */function l1(n,e=null,t=!1){const s={x:N(n,"x","all","bool")},a={axis:e,keepDims:t};return z.runKernel(hi,s,a)}const c1=M({all_:l1});/** + * @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. + * ============================================================================= + */function d1(n,e=null,t=!1){const s={x:N(n,"x","any","bool")},a={axis:e,keepDims:t};return z.runKernel(fi,s,a)}const p1=M({any_:d1});/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function h1(n,e=0){const r={x:N(n,"x","argMax")},s={axis:e};return z.runKernel(Yl,r,s)}const tm=M({argMax_:h1});/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function f1(n,e=0){const r={x:N(n,"x","argMin")},s={axis:e};return z.runKernel(Ql,r,s)}const m1=M({argMin_:f1});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function g1(n){const t={x:N(n,"x","asin")};return z.runKernel(Zl,t)}const y1=M({asin_:g1});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function b1(n){const t={x:N(n,"x","asinh")};return z.runKernel(Jl,t)}const w1=M({asinh_:b1});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function x1(n){const t={x:N(n,"x","atan")};return z.runKernel(ec,t)}const v1=M({atan_:x1});/** + * @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. + * ============================================================================= + */function S1(n,e){let t=N(n,"a","atan2"),r=N(e,"b","atan2");[t,r]=pt(t,r);const s={a:t,b:r};return z.runKernel(nc,s)}const I1=M({atan2_:S1});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function k1(n){const t={x:N(n,"x","atanh")};return z.runKernel(tc,t)}const _1=M({atanh_:k1});/** + * @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. + * ============================================================================= + */function pa(n,e,t,r,s="NHWC",a){const o=n[3],i=[...e,o],l=Fr(s);return Tt(n,i,t,a,r,null,null,l)}function Nn(n,e,t,r,s,a,o="channelsLast"){const[i,l]=Za(e);let c;if(o==="channelsLast")c=[i,l,n[3],n[3]];else if(o==="channelsFirst")c=[i,l,n[1],n[1]];else throw new Error(`Unknown dataFormat ${o}`);return Tt(n,c,t,r,s,a,!1,o)}function Pr(n,e,t,r,s,a,o="NDHWC"){const[i,l,c]=ml(e);let u,d;if(o==="NDHWC")d="channelsLast",u=[i,l,c,n[4],n[4]];else if(o==="NCDHW")d="channelsFirst",u=[i,l,c,n[1],n[1]];else throw new Error(`Unknown dataFormat ${o}`);return Ss(n,u,t,r,s,!1,d,a)}function Tt(n,e,t,r,s,a,o=!1,i="channelsLast"){let[l,c,u,d]=[-1,-1,-1,-1];if(i==="channelsLast")[l,c,u,d]=n;else if(i==="channelsFirst")[l,d,c,u]=n;else throw new Error(`Unknown dataFormat ${i}`);const[p,f,,m]=e,[g,b]=Za(t),[v,I]=Za(r),S=Js(p,v),C=Js(f,I),{padInfo:T,outHeight:O,outWidth:L}=$1(s,c,u,g,b,S,C,a,i),B=o?m*d:m;let A;return i==="channelsFirst"?A=[l,B,O,L]:i==="channelsLast"&&(A=[l,O,L,B]),{batchSize:l,dataFormat:i,inHeight:c,inWidth:u,inChannels:d,outHeight:O,outWidth:L,outChannels:B,padInfo:T,strideHeight:g,strideWidth:b,filterHeight:p,filterWidth:f,effectiveFilterHeight:S,effectiveFilterWidth:C,dilationHeight:v,dilationWidth:I,inShape:n,outShape:A,filterShape:e}}function Ss(n,e,t,r,s,a=!1,o="channelsLast",i){let[l,c,u,d,p]=[-1,-1,-1,-1,-1];if(o==="channelsLast")[l,c,u,d,p]=n;else if(o==="channelsFirst")[l,p,c,u,d]=n;else throw new Error(`Unknown dataFormat ${o}`);const[f,m,g,,b]=e,[v,I,S]=ml(t),[C,T,O]=ml(r),L=Js(f,C),B=Js(m,T),A=Js(g,O),{padInfo:D,outDepth:_,outHeight:V,outWidth:H}=T1(s,c,u,d,v,I,S,L,B,A,i),Y=a?b*p:b;let X;return o==="channelsFirst"?X=[l,Y,_,V,H]:o==="channelsLast"&&(X=[l,_,V,H,Y]),{batchSize:l,dataFormat:o,inDepth:c,inHeight:u,inWidth:d,inChannels:p,outDepth:_,outHeight:V,outWidth:H,outChannels:Y,padInfo:D,strideDepth:v,strideHeight:I,strideWidth:S,filterDepth:f,filterHeight:m,filterWidth:g,effectiveFilterDepth:L,effectiveFilterHeight:B,effectiveFilterWidth:A,dilationDepth:C,dilationHeight:T,dilationWidth:O,inShape:n,outShape:X,filterShape:e}}function C1(n,e,t,r,s){r==null&&(r=nm(n,e,t));const a=n[0],o=n[1],i=Ja((a-e+2*r)/t+1,s),l=Ja((o-e+2*r)/t+1,s);return[i,l]}function N1(n,e,t,r,s,a){s==null&&(s=nm(n,e[0],r[0]));const o=[0,0,0,t];for(let i=0;i<3;i++)n[i]+2*s>=e[i]&&(o[i]=Ja((n[i]-e[i]+2*s)/r[i]+1,a));return o}function nm(n,e,t,r=1){const s=Js(e,r);return Math.floor((n[0]*(t-1)-t+s)/2)}function Za(n){return typeof n=="number"?[n,n,n]:n.length===2?[n[0],n[1],1]:n}function ml(n){return typeof n=="number"?[n,n,n]:n}function Js(n,e){return e<=1?n:n+(n-1)*(e-1)}function $1(n,e,t,r,s,a,o,i,l){let c,u,d;if(typeof n=="number"){c={top:n,bottom:n,left:n,right:n,type:n===0?"VALID":"NUMBER"};const f=C1([e,t],a,r,n,i);u=f[0],d=f[1]}else if(n==="same"){u=Math.ceil(e/r),d=Math.ceil(t/s);const p=Math.max(0,(u-1)*r+a-e),f=Math.max(0,(d-1)*s+o-t),m=Math.floor(p/2),g=p-m,b=Math.floor(f/2),v=f-b;c={top:m,bottom:g,left:b,right:v,type:"SAME"}}else if(n==="valid")c={top:0,bottom:0,left:0,right:0,type:"VALID"},u=Math.ceil((e-a+1)/r),d=Math.ceil((t-o+1)/s);else if(typeof n=="object"){const p=l==="channelsLast"?n[1][0]:n[2][0],f=l==="channelsLast"?n[1][1]:n[2][1],m=l==="channelsLast"?n[2][0]:n[3][0],g=l==="channelsLast"?n[2][1]:n[3][1];c={top:p,bottom:f,left:m,right:g,type:p===0&&f===0&&m===0&&g===0?"VALID":"EXPLICIT"},u=Ja((e-a+p+f)/r+1,i),d=Ja((t-o+m+g)/s+1,i)}else throw Error(`Unknown padding parameter: ${n}`);return{padInfo:c,outHeight:u,outWidth:d}}function T1(n,e,t,r,s,a,o,i,l,c,u){let d,p,f,m;if(n==="valid"&&(n=0),typeof n=="number"){d={top:n,bottom:n,left:n,right:n,front:n,back:n,type:n===0?"VALID":"NUMBER"};const b=N1([e,t,r,1],[i,l,c],1,[s,a,o],n,u);p=b[0],f=b[1],m=b[2]}else if(n==="same"){p=Math.ceil(e/s),f=Math.ceil(t/a),m=Math.ceil(r/o);const g=(p-1)*s+i-e,b=(f-1)*a+l-t,v=(m-1)*o+c-r,I=Math.floor(g/2),S=g-I,C=Math.floor(b/2),T=b-C,O=Math.floor(v/2),L=v-O;d={top:C,bottom:T,left:O,right:L,front:I,back:S,type:"SAME"}}else throw Error(`Unknown padding parameter: ${n}`);return{padInfo:d,outDepth:p,outHeight:f,outWidth:m}}function Ja(n,e){if(!e)return Math.trunc(n);switch(e){case"round":return Math.round(n);case"ceil":return Math.ceil(n);case"floor":return Math.floor(n);default:throw new Error(`Unknown roundingMode ${e}`)}}function Zo(n){const[e,t,r]=Za(n);return e===1&&t===1&&r===1}function $n(n,e){return Zo(n)||Zo(e)}function oa(n){return Za(n).every(e=>e>0)}function Fr(n){if(n==="NHWC")return"channelsLast";if(n==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${n}`)}function Tn(n,e,t){if(t!=null){if(typeof e=="string")throw Error(`Error in ${n}: pad must be an integer when using dimRoundingMode ${t} but got pad ${e}.`);if(typeof e=="number")$(ja(e),()=>`Error in ${n}: pad must be an integer when using dimRoundingMode ${t} but got pad ${e}.`);else if(typeof e=="object")e.forEach(r=>{r.forEach(s=>{$(ja(s),()=>`Error in ${n}: pad must be an integer when using dimRoundingMode ${t} but got pad ${s}.`)})});else throw Error(`Error in ${n}: Unknown padding parameter: ${e}`)}}/** + * @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. + * ============================================================================= + */function E1(n,e){const r={x:N(n,"x","reshape","string_or_numeric")},s={shape:e};return z.runKernel(td,r,s)}const K=M({reshape_:E1});/** + * @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. + * ============================================================================= + */function A1(n,e,t,r,s){const a=N(n,"x","avgPool","float32"),o=1;$($n(t,o),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${t} and dilations '${o}'`);let i=a,l=!1;a.rank===3&&(l=!0,i=K(a,[1,a.shape[0],a.shape[1],a.shape[2]])),$(i.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${i.rank}.`),Tn("avgPool",r,s);const c={x:i},u={filterSize:e,strides:t,pad:r,dimRoundingMode:s};let d=z.runKernel(mi,c,u);return d=tt(d,a.dtype),l?K(d,[d.shape[1],d.shape[2],d.shape[3]]):d}const rm=M({avgPool_:A1});/** + * @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. + * ============================================================================= + */function R1(n,e,t,r,s,a="NDHWC"){const o=N(n,"x","avgPool3d","float32");let i=o,l=!1;o.rank===4&&(l=!0,i=K(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),$(i.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${i.rank}.`),$(a==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`),$(typeof t=="number"&&t>0||Array.isArray(t)&&t[0]>0&&t[1]>0&&t[2]>0,()=>`Error in avgPool3d: Stride must be > 0, but got '${t}'`),Tn("avgPool3d",r,s);const c={x:i},u={filterSize:e,strides:t,pad:r,dimRoundingMode:s,dataFormat:a};let d=z.runKernel(rc,c,u);return d=tt(d,i.dtype),l?K(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}const D1=M({avgPool3d_:R1});/** + * @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. + * ============================================================================= + */function P1(n,e=0){$(n.length>=1,()=>"Pass at least one tensor to concat");const t=Qo(n,"tensors","concat","string_or_numeric");if(t[0].dtype==="complex64"&&t.forEach(a=>{if(a.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor + with dtype ${a.dtype}. `)}),t.length===1)return vr(t[0]);const r=t,s={axis:e};return z.runKernel(ic,r,s)}const wt=M({concat_:P1});/** + * @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. + * ============================================================================= + */function F1(n,e,t=!1,r=!1){let s=N(n,"a","matMul"),a=N(e,"b","matMul");[s,a]=pt(s,a);const o={a:s,b:a},i={transposeA:t,transposeB:r};return z.runKernel(gi,o,i)}const Ze=M({matMul_:F1});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function O1(n){const t={x:N(n,"x","sigmoid","float32")};return z.runKernel(hd,t)}const er=M({sigmoid_:O1});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function M1(n,e,t){const r=N(n,"x","slice","string_or_numeric");if(r.rank===0)throw new Error("Slicing scalar is not possible");const s={x:r},a={begin:e,size:t};return z.runKernel(ld,s,a)}const Ae=M({slice_:M1});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function L1(n){const t={x:N(n,"x","tanh","float32")};return z.runKernel(_d,t)}const gl=M({tanh_:L1});/** + * @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. + * ============================================================================= + */function z1(n,e,t,r,s,a){const o=N(n,"forgetBias","basicLSTMCell"),i=N(e,"lstmKernel","basicLSTMCell"),l=N(t,"lstmBias","basicLSTMCell"),c=N(r,"data","basicLSTMCell"),u=N(s,"c","basicLSTMCell"),d=N(a,"h","basicLSTMCell"),p=wt([c,d],1),f=Ze(p,i),m=he(f,l),g=m.shape[0],b=m.shape[1]/4,v=[g,b],I=Ae(m,[0,0],v),S=Ae(m,[0,b],v),C=Ae(m,[0,b*2],v),T=Ae(m,[0,b*3],v),O=he(Z(er(I),gl(S)),Z(u,er(he(o,C)))),L=Z(gl(O),er(T));return[O,L]}const B1=M({basicLSTMCell_:z1});/** + * @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. + * ============================================================================= + */function W1(n,e,t){const r=N(n,"x","batchToSpaceND"),s=e.reduce((i,l)=>i*l);$(r.rank>=1+e.length,()=>`input rank is ${r.rank} but should be > than blockShape.length ${e.length}`),$(t.length===e.length,()=>`crops.length is ${t.length} but should be equal to blockShape.length ${e.length}`),$(r.shape[0]%s===0,()=>`input tensor batch is ${r.shape[0]} but is not divisible by the product of the elements of blockShape ${e.join(" * ")} === ${s}`);const a={x:r},o={blockShape:e,crops:t};return z.runKernel(sc,a,o)}const sm=M({batchToSpaceND_:W1});function V1(n){let e;return n.rank===0||n.rank===1?e=K(n,[1,1,1,n.size]):n.rank===2?e=K(n,[1,1,n.shape[0],n.shape[1]]):n.rank===3?e=K(n,[1,n.shape[0],n.shape[1],n.shape[2]]):e=n,e}/** + * @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. + * ============================================================================= + */function U1(n,e,t,r,s,a){a==null&&(a=.001);const o=N(n,"x","batchNorm"),i=N(e,"mean","batchNorm"),l=N(t,"variance","batchNorm");let c;s!=null&&(c=N(s,"scale","batchNorm"));let u;r!=null&&(u=N(r,"offset","batchNorm")),$(i.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),$(u==null||i.rank===u.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),$(c==null||i.rank===c.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");const p={x:V1(o),scale:c,offset:u,mean:i,variance:l},f={varianceEpsilon:a},m=z.runKernel(Ai,p,f);return K(m,o.shape)}const du=M({batchNorm_:U1});function H1(n,e,t,r,s,a){const o=N(n,"x","batchNorm"),i=N(e,"mean","batchNorm"),l=N(t,"variance","batchNorm");let c;s!=null&&(c=N(s,"scale","batchNorm"));let u;return r!=null&&(u=N(r,"offset","batchNorm")),$(o.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${o.rank}.`),$(i.rank===2||i.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${i.rank}.`),$(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),c!=null&&$(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${c.rank}.`),u!=null&&$(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${u.rank}.`),du(o,i,l,u,c,a)}const G1=M({batchNorm2d_:H1});function j1(n,e,t,r,s,a){const o=N(n,"x","batchNorm"),i=N(e,"mean","batchNorm"),l=N(t,"variance","batchNorm");let c;s!=null&&(c=N(s,"scale","batchNorm"));let u;return r!=null&&(u=N(r,"offset","batchNorm")),$(o.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${o.rank}.`),$(i.rank===3||i.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${i.rank}.`),$(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),c!=null&&$(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${c.rank}.`),u!=null&&$(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${u.rank}.`),du(o,i,l,u,c,a)}const q1=M({batchNorm3d_:j1});function K1(n,e,t,r,s,a){const o=N(n,"x","batchNorm"),i=N(e,"mean","batchNorm"),l=N(t,"variance","batchNorm");let c;s!=null&&(c=N(s,"scale","batchNorm"));let u;return r!=null&&(u=N(r,"offset","batchNorm")),$(o.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${o.rank}.`),$(i.rank===4||i.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${i.rank}.`),$(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),c!=null&&$(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${c.rank}.`),u!=null&&$(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${u.rank}.`),du(o,i,l,u,c,a)}const X1=M({batchNorm4d_:K1});/** + * @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. + * ============================================================================= + */function Y1(n,e,t){const r=N(n,"x","bincount"),s=N(e,"weights","bincount");$(r.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${r.dtype}`),$(t>=0,()=>`size must be non-negative, but got ${t}.`),$(s.size===r.size||s.size===0,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${r.shape}, weights shape: ${s.shape}.`);const a={x:r,weights:s},o={size:t};return z.runKernel(yi,a,o)}const am=M({bincount_:Y1});/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */function Q1(n,e){const t=N(n,"x","bitwiseAnd"),r=N(e,"y","bitwiseAnd");if(!Vt(t.shape,r.shape))throw new Error(`BitwiseAnd: Tensors must have the same shape. x: ${t.shape}, y: ${r.shape}`);if(t.dtype!=="int32"||r.dtype!=="int32")throw new Error(`BitwiseAnd: Only supports 'int32' values in tensor, found type of x: ${t.dtype} and type of y: ${r.dtype}`);const s={a:t,b:r};return z.runKernel(rf,s)}const Z1=M({bitwiseAnd_:Q1});/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function J1(n,e){const t=N(n,"s0","broadcastArgs","int32"),r=N(e,"s1","broadcastArgs","int32");if(t.rank!==1)throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${t.rank}`);if(r.rank!==1)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${r.rank}`);const s={s0:t,s1:r};return z.runKernel(ac,s)}const e2=M({broadcastArgs_:J1});/** + * @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. + * ============================================================================= + */function t2(n,e){let t=N(n,"broadcastTo","x");const r=t.shape;if(nn(e),e.lengtht.rank){const c=t.shape.slice();for(;c.length=0;c--)if(s[c]===e[c])a[c]=1;else if(t.shape[c]!==1)throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${e}].`);if(a.map((c,u)=>c>1?u:-1).filter(c=>c>=0).length===0)return vr(t);const i={x:t},l={reps:a};return z.runKernel(co,i,l)}const Oo=M({broadcastTo_:t2});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function n2(n){const t={x:N(n,"x","ceil","float32")};return z.runKernel(oc,t)}const r2=M({ceil_:n2});/** + * @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. + * ============================================================================= + */function ho(n,e,t){nn(n),t=t||da(e);const r={shape:n,value:e,dtype:t};return z.runKernel(Ic,{},r)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function s2(n,e,t){const r=N(n,"x","clipByValue");if($(e<=t,()=>`Error in clip: min (${e}) must be less than or equal to max (${t}).`),e===t)return ho(r.shape,e,r.dtype);const s={x:r},a={clipValueMin:e,clipValueMax:t};return z.runKernel(wi,s,a)}const om=M({clipByValue_:s2});function a2(n){return wt(n,0)}const o2=M({concat1d_:a2});function i2(n,e){return wt(n,e)}const u2=M({concat2d_:i2});function l2(n,e){return wt(n,e)}const c2=M({concat3d_:l2});function d2(n,e){return wt(n,e)}const p2=M({concat4d_:d2});/** + * @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. + * ============================================================================= + */function h2(n,e,t,r,s="NHWC",a=[1,1],o){const i=N(n,"x","conv2d","float32"),l=N(e,"filter","conv2d","float32");let c=i,u=!1;i.rank===3&&(u=!0,c=K(i,[1,i.shape[0],i.shape[1],i.shape[2]])),$(c.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${c.rank}.`),$(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),Tn("conv2d",r,o);const d=s==="NHWC"?c.shape[3]:c.shape[1];$(d===l.shape[2],()=>`Error in conv2d: depth of input (${d}) must match input depth for filter ${l.shape[2]}.`),$($n(t,a),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${t} and dilations '${a}'`),$(oa(a),()=>"Error in conv2D: Dilated rates should be larger than 0."),$(oa(t),()=>"Error in conv2D: Strides should be larger than 0.");const p={x:c,filter:l},f={strides:t,pad:r,dataFormat:s,dilations:a,dimRoundingMode:o},m=z.runKernel(xi,p,f);return u?K(m,[m.shape[1],m.shape[2],m.shape[3]]):m}const pu=M({conv2d_:h2});function f2(n,e,t,r,s="NWC",a=1,o){const i=N(n,"x","conv1d"),l=N(e,"filter","conv1d");let c=i,u=!1;i.rank===2&&(u=!0,c=K(i,[1,i.shape[0],i.shape[1]])),$(c.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${c.rank}.`),$(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),Tn("conv1d",r,o),$(c.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${c.shape[2]}) must match input depth for filter ${l.shape[1]}.`),$($n(t,a),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${t} and dilation '${a}'`),$(oa(a),()=>"Error in conv1D: Dilated rates should be larger than 0."),$(oa(t),()=>"Error in conv1D: Stride should be larger than 0."),$(s==="NWC",()=>`Error in conv1d: got dataFormat of ${s} but only NWC is currently supported.`);const d=K(l,[1,l.shape[0],l.shape[1],l.shape[2]]),p=K(c,[c.shape[0],1,c.shape[1],c.shape[2]]),b=pu(p,d,[1,t],r,"NHWC",[1,a],o);return u?K(b,[b.shape[2],b.shape[3]]):K(b,[b.shape[0],b.shape[2],b.shape[3]])}const m2=M({conv1d_:f2});/** + * @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. + * ============================================================================= + */function g2(n,e,t,r,s,a="NHWC",o){$(n.length===e.rank,()=>`Length of inShape (${n.length}) and rank of dy (${e.rank}) must match`);let i=n,l=e,c=!1;e.rank===3&&(c=!0,l=K(e,[1,e.shape[0],e.shape[1],e.shape[2]]),i=[1,n[0],n[1],n[2]]),$(i.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${i.length}.`),$(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),$(t.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${t.rank}`);const u=a==="NHWC"?i[3]:i[1],d=a==="NHWC"?l.shape[3]:l.shape[1];$(u===t.shape[2],()=>`Error in conv2dDerInput: depth of input (${u}) must match input depth for filter ${t.shape[2]}.`),$(d===t.shape[3],()=>`Error in conv2dDerInput: depth of output (${d}) must match output depth for filter ${t.shape[3]}.`),Tn("conv2dDerInput",s,o);const p={dy:l,filter:t},f={strides:r,pad:s,dataFormat:a,dimRoundingMode:o,inputShape:i},m=z.runKernel(vi,p,f);return c?K(m,[m.shape[1],m.shape[2],m.shape[3]]):m}const im=M({conv2DBackpropInput_:g2});function y2(n,e,t,r,s,a){const o=N(n,"x","conv2dTranspose"),i=N(e,"filter","conv2dTranspose");return im(t,o,i,r,s,"NHWC",a)}const b2=M({conv2dTranspose_:y2});/** + * @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. + * ============================================================================= + */function w2(n,e,t,r,s="NDHWC",a=[1,1,1]){const o=N(n,"x","conv3d"),i=N(e,"filter","conv3d");let l=o,c=!1;o.rank===4&&(c=!0,l=K(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),$(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),$(i.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${i.rank}.`),$(l.shape[4]===i.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${i.shape[3]}.`),$($n(t,a),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${t} and dilations '${a}'`),$(s==="NDHWC",()=>`Error in conv3d: got dataFormat of ${s} but only NDHWC is currently supported.`),$(oa(a),()=>"Error in conv3D: Dilated rates should be larger than 0."),$(oa(t),()=>"Error in conv3D: Strides should be larger than 0.");const u={x:l,filter:i},d={strides:t,pad:r,dataFormat:s,dilations:a},p=z.runKernel(Si,u,d);return c?K(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}const x2=M({conv3d_:w2});/** + * @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. + * ============================================================================= + */function v2(n,e,t,r,s){$(n.length===e.rank,()=>`Length of inShape (${n.length}) and rank of dy (${e.rank}) must match`);let a=n,o=e,i=!1;e.rank===4&&(i=!0,o=K(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]),a=[1,n[0],n[1],n[2],n[3]]);const l=a[4],c=o.shape[4];$(a.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${a.length}.`),$(o.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${o.rank}`),$(t.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${t.rank}`),$(l===t.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${t.shape[3]}.`),$(c===t.shape[4],()=>`Error in conv3dDerInput: depth of output (${c}) must match output depth for filter ${t.shape[4]}.`);const u={dy:o,filter:t},d={pad:s,strides:r,inputShape:a},p=z.runKernel(Ii,u,d);return i?K(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}const S2=M({conv3DBackpropInput_:v2});function I2(n,e,t,r,s){const a=N(n,"x","conv3dTranspose"),o=N(e,"filter","conv3dTranspose");return S2(t,a,o,r,s)}const k2=M({conv3dTranspose_:I2});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function _2(n){const t={x:N(n,"x","cos","float32")};return z.runKernel(lc,t)}const C2=M({cos_:_2});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function N2(n){const t={x:N(n,"x","cosh","float32")};return z.runKernel(cc,t)}const $2=M({cosh_:N2});/** + * @license + * Copyright 2022 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. + * ============================================================================= + */function T2(n,e=0,t=!1,r=!1){const a={x:N(n,"x","cumprod")},o={axis:e,exclusive:t,reverse:r};return z.runKernel(ki,a,o)}const E2=M({cumprod_:T2});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function A2(n,e=0,t=!1,r=!1){const a={x:N(n,"x","cumsum")},o={axis:e,exclusive:t,reverse:r};return z.runKernel(_i,a,o)}const R2=M({cumsum_:A2});/** + * @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. + * ============================================================================= + */function D2(n,e,t,r=!1){const s=N(n,"x","denseBincount"),a=N(e,"weights","denseBincount");$(s.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${s.dtype}`),$(s.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${s.rank}.`),$(t>=0,()=>`size must be non-negative, but got ${t}.`),$(a.size===s.size||a.size===0,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${s.shape}, weights shape: ${a.shape}.`);const o={x:s,weights:a},i={size:t,binaryOutput:r};return z.runKernel(dc,o,i)}const P2=M({denseBincount_:D2});/** + * @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. + * ============================================================================= + */function F2(n,e,t="NHWC"){const r=N(n,"x","depthToSpace","float32"),s=t==="NHWC"?r.shape[1]:r.shape[2],a=t==="NHWC"?r.shape[2]:r.shape[3],o=t==="NHWC"?r.shape[3]:r.shape[1];$(e>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${e}`),$(s*e>=0,()=>`Negative dimension size caused by overflow when multiplying + ${s} and ${e} for depthToSpace with input shape + ${r.shape}`),$(a*e>=0,()=>`Negative dimension size caused by overflow when multiplying + ${a} and ${e} for depthToSpace with input shape + ${r.shape}`),$(o%(e*e)===0,()=>`Dimension size must be evenly divisible by ${e*e} but is ${o} for depthToSpace with input shape ${r.shape}`);const i={x:r},l={blockSize:e,dataFormat:t};return z.runKernel(Ni,i,l)}const O2=M({depthToSpace_:F2});/** + * @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. + * ============================================================================= + */function M2(n,e,t,r,s="NHWC",a=[1,1],o){const i=N(n,"x","depthwiseConv2d","float32"),l=N(e,"filter","depthwiseConv2d","float32");let c=i,u=!1;i.rank===3&&(u=!0,c=K(i,[1,i.shape[0],i.shape[1],i.shape[2]])),$(c.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${c.rank}.`),$(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`);const d=s==="NHWC"?c.shape[3]:c.shape[1];$(d===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${d}) must match the inChannels dimension in filter ${l.shape[2]}.`),Tn("depthwiseConv2d",r,o);const p={x:c,filter:l},f={strides:t,pad:r,dataFormat:s,dilations:a,dimRoundingMode:o},m=z.runKernel($i,p,f);return u?K(m,[m.shape[1],m.shape[2],m.shape[3]]):m}const Ad=M({depthwiseConv2d_:M2});/** + * @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. + * ============================================================================= + */function L2(n){const t={x:N(n,"x","diag")};return z.runKernel(pc,t)}const z2=M({diag_:L2});/** + * @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. + * ============================================================================= + */function B2(n,e,t,r,s=[1,1],a="NHWC"){const o=N(n,"x","dilation2d"),i=N(e,"filter","dilation2d");$(o.rank===3||o.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${o.rank}.`),$(i.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${i.rank}.`),$(a==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${a}`);let l=o,c=!1;o.rank===3&&(l=K(o,[1,o.shape[0],o.shape[1],o.shape[2]]),c=!0),$(l.shape[3]===i.shape[2],()=>`Error in dilation2d: input and filter must have the same depth: ${l.shape[3]} vs ${i.shape[2]}`);const u={x:l,filter:i},d={strides:t,pad:r,dilations:s},p=z.runKernel(Ti,u,d);return c?K(p,[p.shape[1],p.shape[2],p.shape[3]]):p}const W2=M({dilation2d_:B2});/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Jo(n,e){const t=n.length,r=[];for(let s=0;s1&&o===1&&r.unshift(a)}return r}function V2(n,e){const t=[];for(let r=0;r1)&&t.unshift(a)}return t}function je(n,e){const t=Math.max(n.length,e.length),r=new Array(t);for(let s=0;s`Error in dot: inputs must all be rank 1 or 2, but got ranks ${t.rank} and ${r.rank}.`);const s=t.rank===1?t.size:t.shape[1],a=r.rank===1?r.size:r.shape[0];if($(s===a,()=>`Error in dot: inner dimensions of inputs must match, but got ${s} and ${a}.`),t.rank===1&&r.rank===1){const o=K(t,[1,-1]),i=K(r,[-1,1]),l=Ze(o,i);return K(l,[])}else if(t.rank===1&&r.rank===2){const o=K(t,[1,-1]),i=K(r,[r.shape[0],r.shape[1]]),l=Ze(o,i);return K(l,[l.size])}else if(t.rank===2&&r.rank===1){const o=K(r,[-1,1]),i=Ze(t,o);return K(i,[i.size])}else{const o=K(r,[r.shape[0],r.shape[1]]);return Ze(t,o)}}const X2=M({dot_:K2});/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function Y2(n,...e){const t=e.map((s,a)=>N(s,`tensors${a}`,"einsum")),r={equation:n};return z.runKernel(df,t,r)}const Ys=M({einsum_:Y2});/** + * @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. + * ============================================================================= + */function Q2(n){const t={x:N(n,"x","elu","float32")};return z.runKernel(gc,t)}const lm=M({elu_:Q2});/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */function Z2(n,e){const t=N(n,"x","ensureShape","string_or_numeric");if(!ww(t.shape,e))throw new Error(`EnsureShape: Shape of tensor ${t.shape} is not compatible with expected shape ${e}`);return n}const J2=M({ensureShape_:Z2});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ex(n){let e=N(n,"x","erf");$(e.dtype==="int32"||e.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),e.dtype==="int32"&&(e=tt(e,"float32"));const t={x:e};return z.runKernel(bc,t)}const tx=M({erf_:ex});/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function cm(n,e){for(let t=0;tn[a]);return[t,s]}function gn(n,e){const t=e.map(r=>1);return nx(n,t,e)}function yn(n,e,t){$(cm(e,t),()=>`${n} supports only inner-most axes for now. Got axes ${e} and rank-${t} input.`)}function Or(n,e){if(cm(n,e))return null;const t=[];for(let r=0;rt.push(r)),t}function hu(n){return n.map((e,t)=>[t,e]).sort((e,t)=>e[1]-t[1]).map(e=>e[0])}function An(n,e){const t=[];for(let r=e-n;r"Axis must be <= rank of the tensor");const r={input:t},s={dim:e};return z.runKernel(vc,r,s)}const en=M({expandDims_:hx});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function fx(n){const t={x:N(n,"x","expm1")};return z.runKernel(Sc,t)}const mx=M({expm1_:fx});/** + * @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. + * ============================================================================= + */function gx(n,e){const t=N(n,"x","tile","string_or_numeric");$(t.rank===e.length,()=>`Error in transpose: rank of input ${t.rank} must match length of reps ${e}.`);const r={x:t},s={reps:e};return z.runKernel(co,r,s)}const Ua=M({tile_:gx});/** + * @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. + * ============================================================================= + */function yx(n,e,t,r="float32"){e==null&&(e=n);const s=ut([n,e],r),a=n<=e?n:e;for(let i=0;i`Error in localResponseNormalization: x must be rank 3 or 4 but got + rank ${a.rank}.`),$(ja(e),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${e}.`);let o=a,i=!1;a.rank===3&&(i=!0,o=K(a,[1,a.shape[0],a.shape[1],a.shape[2]]));const l={x:o},c={depthRadius:e,bias:t,alpha:r,beta:s},u=z.runKernel(Oi,l,c);return i?K(u,[u.shape[1],u.shape[2],u.shape[3]]):u}const Px=M({localResponseNormalization_:Dx});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Fx(n){const t={x:N(n,"x","log","float32")};return z.runKernel(Pc,t)}const to=M({log_:Fx});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ox(n){const t={x:N(n,"x","log1p")};return z.runKernel(Fc,t)}const ym=M({log1p_:Ox});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Mx(n,e){$(nl(n),()=>"The f passed in variableGrads(f) must be a function"),$(e==null||Array.isArray(e)&&e.every(c=>c instanceof Yo),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");const t=e!=null;if(!t){e=[];for(const c in z.registeredVariables)e.push(z.registeredVariables[c])}const r=t?e.filter(c=>!c.trainable):null,s=e.length;e=e.filter(c=>c.trainable),$(e.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${s} variables is trainable.`);const a=!0,{value:o,grads:i}=z.gradients(n,e,null,a);$(i.some(c=>c!=null),()=>"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()."),$(o.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${o.rank} tensor`);const l={};return e.forEach((c,u)=>{i[u]!=null&&(l[c.name]=i[u])}),r?.forEach(c=>l[c.name]=null),{value:o,grads:l}}function sr(n){return z.customGrad(n)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Lx(n){const t={x:N(n,"x","neg")};return z.runKernel(jc,t)}const Bn=M({neg_:Lx});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function zx(n){const t={x:N(n,"x","softplus")};return z.runKernel(fd,t)}const bm=M({softplus_:zx});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Bx(n){const e=N(n,"x","logSigmoid");return sr(r=>({value:Bn(bm(Bn(r))),gradFunc:o=>Z(o,er(Bn(r)))}))(e)}const Wx=M({logSigmoid_:Bx});/** + * @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. + * ============================================================================= + */function Vx(n,e){let t=N(n,"a","sub"),r=N(e,"b","sub");[t,r]=pt(t,r);const s={a:t,b:r};return z.runKernel(Id,s)}const $e=M({sub_:Vx});/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ux(n,e=-1){const t=N(n,"logits","logSoftmax");if(e===-1&&(e=t.rank-1),e!==t.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${t.rank} and axis was ${e}`);return sr((s,a)=>{const i=ea(s,e,!0),l=$e(s,i),c=$e(tt(l,"float32"),to(at(rr(l),e,!0)));return a([c]),{value:c,gradFunc:(d,p)=>{const[f]=p,m=!0,g=rr(f);return $e(d,Z(at(d,e,m),g))}}})(t)}const Hx=M({logSoftmax_:Ux});/** + * @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. + * ============================================================================= + */function Gx(n,e=null,t=!1){const r=N(n,"x","logSumExp"),s=$t(e,r.shape),a=ea(r,s,!0),o=$e(r,a),i=rr(o),l=at(i,s),c=to(l),u=he(K(a,c.shape),c);if(t){const d=gn(u.shape,s);return K(u,d)}return u}const wm=M({logSumExp_:Gx});/** + * @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. + * ============================================================================= + */function jx(n,e){const t=N(n,"a","logicalAnd","bool"),r=N(e,"b","logicalAnd","bool");je(t.shape,r.shape);const s={a:t,b:r};return z.runKernel(Oc,s)}const ei=M({logicalAnd_:jx});/** + * @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. + * ============================================================================= + */function qx(n){const t={x:N(n,"x","logicalNot","bool")};return z.runKernel(Mc,t)}const xm=M({logicalNot_:qx});/** + * @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. + * ============================================================================= + */function Kx(n,e){const t=N(n,"a","logicalOr","bool"),r=N(e,"b","logicalOr","bool");je(t.shape,r.shape);const s={a:t,b:r};return z.runKernel(Lc,s)}const vm=M({logicalOr_:Kx});/** + * @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. + * ============================================================================= + */function Xx(n,e){const t=N(n,"a","logicalXor","bool"),r=N(e,"b","logicalXor","bool");return je(t.shape,r.shape),ei(vm(n,e),xm(ei(n,e)))}const Yx=M({logicalXor_:Xx});/** + * @license + * Copyright 2022 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. + * ============================================================================= + */const Ao=2147483648;function Qx(n,e,t="left"){const r=N(n,"sortedSequence","searchSorted"),s=N(e,"values","searchSorted"),a=r.shape[r.shape.length-1],o=s.shape[s.shape.length-1],i=K(r,[-1,a]),l=K(s,[-1,o]);if(i.rank<2)throw new Error("Sorted input argument must be at least 2-dimensional");if(i.shape[0]!==l.shape[0])throw new Error("Leading dimension of 'sortedSequence' and 'values' must match.");if(q(l.shape)>=Ao)throw new Error(`values tensor size must less than ${Ao}`);if(i.shape[1]>=Ao)throw new Error(`trailing dim_size must less than ${Ao} for int32 output type, was ${i.shape[1]}`);const c={sortedSequence:i,values:l},u={side:t};return z.runKernel(eu,c,u)}const Dd=M({searchSorted_:Qx});/** + * @license + * Copyright 2022 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. + * ============================================================================= + */function Zx(n,e){return Dd(n,e,"left")}/** + * @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. + * ============================================================================= + */function Jx(n,e,t,r,s){const a=N(n,"x","maxPool"),o=1;let i=a,l=!1;a.rank===3&&(l=!0,i=K(a,[1,a.shape[0],a.shape[1],a.shape[2]])),$(i.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`),$($n(t,o),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${t} and dilations '${o}'`),Tn("maxPool",r,s);const c={x:i},u={filterSize:e,strides:t,pad:r,dimRoundingMode:s},d=z.runKernel(Li,c,u);return l?K(d,[d.shape[1],d.shape[2],d.shape[3]]):d}const Sm=M({maxPool_:Jx});/** + * @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. + * ============================================================================= + */function ev(n,e=[1,1,1],t,r,s,a="NDHWC"){const o=N(n,"x","maxPool3d");let i=o,l=!1;o.rank===4&&(l=!0,i=K(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),$(i.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${i.rank}.`),$(a==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`),Tn("maxPool3d",r,s);const c={x:i},u={filterSize:e,strides:t,pad:r,dimRoundingMode:s,dataFormat:a},d=z.runKernel(Wc,c,u);return l?K(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}const tv=M({maxPool3d_:ev});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function nv(n,e,t,r,s=!1){const o={x:N(n,"x","maxPoolWithArgmax")},i={filterSize:e,strides:t,pad:r,includeBatchInIndex:s},l=z.runKernel(Vc,o,i);return{result:l[0],indexes:l[1]}}const rv=M({maxPoolWithArgmax_:nv});/** + * @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. + * ============================================================================= + */function sv(n,e){let t=N(n,"a","maximum"),r=N(e,"b","maximum");[t,r]=pt(t,r),t.dtype==="bool"&&(t=tt(t,"int32"),r=tt(r,"int32")),je(t.shape,r.shape);const s={a:t,b:r};return z.runKernel(Bc,s)}const Im=M({maximum_:sv});/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function av(n,e=null,t=!1){const s={x:N(n,"x","mean")},a={axis:e,keepDims:t};return z.runKernel(zi,s,a)}const ti=M({mean_:av});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function $r(n,e="float32"){if(nn(n),e==="complex64"){const r=$r(n,"float32"),s=$r(n,"float32");return Cr(r,s)}const t=ps(q(n),e);return z.makeTensor(t,n,e)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function as(n,e="float32"){if(nn(n),e==="complex64"){const r=as(n,"float32"),s=$r(n,"float32");return Cr(r,s)}const t=Qh(q(n),e);return z.makeTensor(t,n,e)}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function ov(n,e,{indexing:t="xy"}={}){if(t!=="xy"&&t!=="ij")throw new TypeError(`${t} is not a valid third argument to meshgrid`);if(n===void 0)return[];let r=N(n,"x","meshgrid",n instanceof dt?n.dtype:"float32");if(e===void 0)return[r];let s=N(e,"y","meshgrid",e instanceof dt?e.dtype:"float32");const a=q(r.shape),o=q(s.shape);return t==="xy"?(r=K(r,[1,-1]),s=K(s,[-1,1]),[Ze(as([o,1],r.dtype),r),Ze(s,as([1,a],s.dtype))]):(r=K(r,[-1,1]),s=K(s,[1,-1]),[Ze(r,as([1,o],r.dtype)),Ze(as([a,1],s.dtype),s)])}/** + * @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. + * ============================================================================= + */function iv(n,e){let t=N(n,"a","minimum"),r=N(e,"b","minimum");[t,r]=pt(t,r),t.dtype==="bool"&&(t=tt(t,"int32"),r=tt(r,"int32")),je(t.shape,r.shape);const s={a:t,b:r};return z.runKernel(Uc,s)}const no=M({minimum_:iv});/** + * @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. + * ============================================================================= + */function uv(n,e,t){$(t==="reflect"||t==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${t}.`);const r=N(n,"x","mirrorPad");if(r.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");$(e.length===r.rank,()=>`Padding doesn't match input. Must be ${r.rank}. Got ${e.length}.`);const s=t==="reflect"?1:0;for(let i=0;i"Invalid number of paddings. Must be length of 2 each."),$(e[i][0]>=0&&e[i][0]<=r.shape[i]-s&&e[i][1]>=0&&e[i][1]<=r.shape[i]-s,()=>`Padding in dimension ${i} cannot be greater than or equal to ${r.shape[i]-s} or less than 0 for input of shape ${r.shape}`);const a={paddings:e,mode:t},o={x:r};return z.runKernel(Wi,o,a)}const km=M({mirrorPad_:uv});/** + * @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. + * ============================================================================= + */function lv(n,e){let t=N(n,"a","mod"),r=N(e,"b","mod");[t,r]=pt(t,r);const s={a:t,b:r};return z.runKernel(Hc,s)}const cv=M({mod_:lv});/** + * @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. + * ============================================================================= + */function dv(n,e=null,t=!1){n=N(n,"x","moments");const r=$t(e,n.shape),s=ti(n,r,t);let a=s.shape;t||(a=gn(s.shape,r));const o=hn($e(tt(n,"float32"),K(s,a))),i=ti(o,r,t);return{mean:s,variance:i}}const pv=M({moments_:dv});function hv(n,e,t,r){const s=N(e,"data","multiRNNCell"),a=Qo(t,"c","multiRNNCell"),o=Qo(r,"h","multiRNNCell");let i=s;const l=[];for(let d=0;d2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${o}`);t=t||Math.random();const l={logits:o===1?K(s,[1,-1]):s},c={numSamples:e,seed:t,normalized:r},u=z.runKernel(Vi,l,c);return o===1?K(u,[u.size]):u}const gv=M({multinomial_:mv});/** + * @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. + * ============================================================================= + */function yv(n,e){let t=N(n,"a","notEqual","string_or_numeric"),r=N(e,"b","notEqual","string_or_numeric");[t,r]=pt(t,r),je(t.shape,r.shape);const s={a:t,b:r};return z.runKernel(qc,s)}const _m=M({notEqual_:yv});/** + * @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. + * ============================================================================= + */function bv(n,e,t=1,r=0,s="int32"){if(e<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${e}`);const o={indices:N(n,"indices","oneHot","int32")},i={dtype:s,depth:e,onValue:t,offValue:r};return z.runKernel(Gi,o,i)}const wv=M({oneHot_:bv});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function xv(n){const t={x:N(n,"x","onesLike")};return z.runKernel(Xc,t)}const vv=M({onesLike_:xv});function Sv(n,e){const t=N(n,"v1","outerProduct"),r=N(e,"v2","outerProduct");$(t.rank===1&&r.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${t.rank} and ${r.rank}.`);const s=K(t,[-1,1]),a=K(r,[1,-1]);return Ze(s,a)}const Iv=M({outerProduct_:Sv});/** + * @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. + * ============================================================================= + */function kv(n,e,t=0){const r=N(n,"x","pad");if(r.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const s={paddings:e,constantValue:t},a={x:r};return z.runKernel(ji,a,s)}const Tr=M({pad_:kv});function _v(n,e,t=0){return $(e.length===2,()=>"Invalid number of paddings. Must be length of 2."),Tr(n,[e],t)}const Cv=M({pad1d_:_v});function Nv(n,e,t=0){return $(e.length===2&&e[0].length===2&&e[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Tr(n,e,t)}const $v=M({pad2d_:Nv});function Tv(n,e,t=0){return $(e.length===3&&e[0].length===2&&e[1].length===2&&e[2].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Tr(n,e,t)}const Ev=M({pad3d_:Tv});function Av(n,e,t=0){return $(e.length===4&&e[0].length===2&&e[1].length===2&&e[2].length===2&&e[3].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Tr(n,e,t)}const Rv=M({pad4d_:Av});/** + * @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. + * ============================================================================= + */function Dv(n,e,t){const r=N(n,"x","spaceToBatchND");$(r.rank>=1+e.length,()=>`input rank ${r.rank} should be > than [blockShape] ${e.length}`),$(t.length===e.length,()=>`paddings.shape[0] ${t.length} must be equal to [blockShape] ${e.length}`),$(r.shape.reduce((o,i,l)=>l>0&&l<=e.length?o&&(i+t[l-1][0]+t[l-1][1])%e[l-1]===0:o,!0),()=>`input spatial dimensions ${r.shape.slice(1)} with paddings ${t.toString()} must be divisible by blockShapes ${e.toString()}`);const s={x:r},a={blockShape:e,paddings:t};return z.runKernel(gd,s,a)}const Cm=M({spaceToBatchND_:Dv});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Pv(n,e,t,r,s,a,o){s==null&&(s=[1,1]),a==null&&(a=1),r===0&&(r="valid");const i=N(n,"x","maxPool");let l=i,c=!1;i.rank===3&&(c=!0,l=K(i,[1,i.shape[0],i.shape[1],i.shape[2]])),$($n(a,s),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${a} and dilations '${s}'`);const u=Nn(l.shape,e,a,s,r),d=[u.dilationHeight,u.dilationWidth];let p;r==="same"?p=Ov([u.filterHeight,u.filterWidth],d):p=[[0,0],[0,0]];const f=d[0]===1&&d[1]===1,[m,g]=Fv([u.inHeight,u.inWidth],d,p),b=f?r:"valid",v=f?l:Cm(l,d,m),S=(t==="avg"?()=>rm(v,e,a,b,o):()=>Sm(v,e,a,b,o))(),C=f?S:sm(S,d,g);return c?K(C,[C.shape[1],C.shape[2],C.shape[3]]):C}function Fv(n,e,t){const r=t.map(u=>u[0]),s=t.map(u=>u[1]),a=n.concat(r,s),o=e.map((u,d)=>(u-a[d]%u)%u),i=s.map((u,d)=>u+o[d]),l=e.map((u,d)=>[r[d],i[d]]),c=e.map((u,d)=>[0,o[d]]);return[l,c]}function Ov(n,e){const r=n.map((o,i)=>o+(o-1)*(e[i]-1)).map(o=>o-1),s=r.map(o=>Math.floor(o/2)),a=r.map((o,i)=>o-s[i]);return r.map((o,i)=>[s[i],a[i]])}const Mv=M({pool_:Pv});/** + * @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. + * ============================================================================= + */function Lv(n,e){const t=N(n,"x","prelu"),r=N(e,"alpha","prelu"),s={x:t,alpha:r};return z.runKernel(qi,s)}const Nm=M({prelu_:Lv});/** + * @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. + * ============================================================================= + */function zv(n,e=null,t=!1){let r=N(n,"x","prod");r.dtype==="bool"&&(r=tt(r,"int32"));const s={x:r},a={axis:e,keepDims:t};return z.runKernel(Ki,s,a)}const Bv=M({prod_:zv});/** + * @license + * Copyright 2022 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. + * ============================================================================= + */function Wv(n,e,t,r){const s=n.map((u,d)=>N(u,`tensors${d}`,"raggedGather","int32")),a=N(e,"paramsDenseValues","raggedGather"),o=N(t,"indices","raggedGather","int32"),i={paramsNestedSplits:s,paramsDenseValues:a,indices:o},l={outputRaggedRank:r},c=z.runKernel(Pw,i,l);return{outputNestedSplits:c.slice(0,c.length-1),outputDenseValues:c[c.length-1]}}const Vv=M({raggedGather_:Wv});/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */function Uv(n,e,t){const r=N(n,"starts","raggedRange"),s=N(e,"limits","raggedRange",r.dtype),a=N(t,"deltas","raggedRange",r.dtype),o={starts:r,limits:s,deltas:a},i=z.runKernel(Fw,o);return{rtNestedSplits:i[0],rtDenseValues:i[1]}}const Hv=M({raggedRange_:Uv});/** + * @license + * Copyright 2022 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. + * ============================================================================= + */function Gv(n,e,t,r,s){const a=N(n,"shape","raggedTensorToTensor","int32"),o=N(e,"values","raggedTensorToTensor"),i=N(t,"defaultValue","raggedTensorToTensor",o.dtype),l=r.map((d,p)=>N(d,`tensors${p}`,"raggedTensorToTensor","int32")),c={shape:a,values:o,defaultValue:i,rowPartitionTensors:l},u={rowPartitionTypes:s};return z.runKernel(Ow,c,u)}const jv=M({raggedTensorToTensor_:Gv});/** + * @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. + * ============================================================================= + */function qv(n,e,t){nn(n);const r=q(n);let s=null;if(t==null||t==="float32")s=new Float32Array(r);else if(t==="int32")s=new Int32Array(r);else if(t==="bool")s=new Uint8Array(r);else throw new Error(`Unknown data type ${t}`);for(let a=0;a>>0,p-=l,p*=l,l=p>>>0,p-=l,l+=p*4294967296}return(l>>>0)*23283064365386963e-26};return c}t&&t.exports?t.exports=o:this.alea=o})(Xv,n)})(Mo)),Mo.exports}var Lo={exports:{}},Qv=Lo.exports,Ip;function Zv(){return Ip||(Ip=1,(function(n){(function(e,t,r){function s(i){var l=this,c="";l.x=0,l.y=0,l.z=0,l.w=0,l.next=function(){var d=l.x^l.x<<11;return l.x=l.y,l.y=l.z,l.z=l.w,l.w^=l.w>>>19^d^d>>>8},i===(i|0)?l.x=i:c+=i;for(var u=0;u>>0)/4294967296};return d.double=function(){do var p=c.next()>>>11,f=(c.next()>>>0)/4294967296,m=(p+f)/(1<<21);while(m===0);return m},d.int32=c.next,d.quick=d,u&&(typeof u=="object"&&a(u,c),d.state=function(){return a(c,{})}),d}t&&t.exports?t.exports=o:this.xor128=o})(Qv,n)})(Lo)),Lo.exports}var zo={exports:{}},Jv=zo.exports,kp;function eS(){return kp||(kp=1,(function(n){(function(e,t,r){function s(i){var l=this,c="";l.next=function(){var d=l.x^l.x>>>2;return l.x=l.y,l.y=l.z,l.z=l.w,l.w=l.v,(l.d=l.d+362437|0)+(l.v=l.v^l.v<<4^(d^d<<1))|0},l.x=0,l.y=0,l.z=0,l.w=0,l.v=0,i===(i|0)?l.x=i:c+=i;for(var u=0;u>>4),l.next()}function a(i,l){return l.x=i.x,l.y=i.y,l.z=i.z,l.w=i.w,l.v=i.v,l.d=i.d,l}function o(i,l){var c=new s(i),u=l&&l.state,d=function(){return(c.next()>>>0)/4294967296};return d.double=function(){do var p=c.next()>>>11,f=(c.next()>>>0)/4294967296,m=(p+f)/(1<<21);while(m===0);return m},d.int32=c.next,d.quick=d,u&&(typeof u=="object"&&a(u,c),d.state=function(){return a(c,{})}),d}t&&t.exports?t.exports=o:this.xorwow=o})(Jv,n)})(zo)),zo.exports}var Bo={exports:{}},tS=Bo.exports,_p;function nS(){return _p||(_p=1,(function(n){(function(e,t,r){function s(i){var l=this;l.next=function(){var u=l.x,d=l.i,p,f;return p=u[d],p^=p>>>7,f=p^p<<24,p=u[d+1&7],f^=p^p>>>10,p=u[d+3&7],f^=p^p>>>3,p=u[d+4&7],f^=p^p<<7,p=u[d+7&7],p=p^p<<13,f^=p^p<<9,u[d]=f,l.i=d+1&7,f};function c(u,d){var p,f=[];if(d===(d|0))f[0]=d;else for(d=""+d,p=0;p0;--p)u.next()}c(l,i)}function a(i,l){return l.x=i.x.slice(),l.i=i.i,l}function o(i,l){i==null&&(i=+new Date);var c=new s(i),u=l&&l.state,d=function(){return(c.next()>>>0)/4294967296};return d.double=function(){do var p=c.next()>>>11,f=(c.next()>>>0)/4294967296,m=(p+f)/(1<<21);while(m===0);return m},d.int32=c.next,d.quick=d,u&&(u.x&&a(u,c),d.state=function(){return a(c,{})}),d}t&&t.exports?t.exports=o:this.xorshift7=o})(tS,n)})(Bo)),Bo.exports}var Wo={exports:{}},rS=Wo.exports,Cp;function sS(){return Cp||(Cp=1,(function(n){(function(e,t,r){function s(i){var l=this;l.next=function(){var u=l.w,d=l.X,p=l.i,f,m;return l.w=u=u+1640531527|0,m=d[p+34&127],f=d[p=p+1&127],m^=m<<13,f^=f<<17,m^=m>>>15,f^=f>>>12,m=d[p]=m^f,l.i=p,m+(u^u>>>16)|0};function c(u,d){var p,f,m,g,b,v=[],I=128;for(d===(d|0)?(f=d,d=null):(d=d+"\0",f=0,I=Math.max(I,d.length)),m=0,g=-32;g>>15,f^=f<<4,f^=f>>>13,g>=0&&(b=b+1640531527|0,p=v[g&127]^=f+b,m=p==0?m+1:0);for(m>=128&&(v[(d&&d.length||0)&127]=-1),m=127,g=512;g>0;--g)f=v[m+34&127],p=v[m=m+1&127],f^=f<<13,p^=p<<17,f^=f>>>15,p^=p>>>12,v[m]=f^p;u.w=b,u.X=v,u.i=m}c(l,i)}function a(i,l){return l.i=i.i,l.w=i.w,l.X=i.X.slice(),l}function o(i,l){i==null&&(i=+new Date);var c=new s(i),u=l&&l.state,d=function(){return(c.next()>>>0)/4294967296};return d.double=function(){do var p=c.next()>>>11,f=(c.next()>>>0)/4294967296,m=(p+f)/(1<<21);while(m===0);return m},d.int32=c.next,d.quick=d,u&&(u.X&&a(u,c),d.state=function(){return a(c,{})}),d}t&&t.exports?t.exports=o:this.xor4096=o})(rS,n)})(Wo)),Wo.exports}var Vo={exports:{}},aS=Vo.exports,Np;function oS(){return Np||(Np=1,(function(n){(function(e,t,r){function s(i){var l=this,c="";l.next=function(){var d=l.b,p=l.c,f=l.d,m=l.a;return d=d<<25^d>>>7^p,p=p-f|0,f=f<<24^f>>>8^m,m=m-d|0,l.b=d=d<<20^d>>>12^p,l.c=p=p-f|0,l.d=f<<16^p>>>16^m,l.a=m-d|0},l.a=0,l.b=0,l.c=-1640531527,l.d=1367130551,i===Math.floor(i)?(l.a=i/4294967296|0,l.b=i|0):c+=i;for(var u=0;u>>0)/4294967296};return d.double=function(){do var p=c.next()>>>11,f=(c.next()>>>0)/4294967296,m=(p+f)/(1<<21);while(m===0);return m},d.int32=c.next,d.quick=d,u&&(typeof u=="object"&&a(u,c),d.state=function(){return a(c,{})}),d}t&&t.exports?t.exports=o:this.tychei=o})(aS,n)})(Vo)),Vo.exports}var Uo={exports:{}},iS={},uS=Object.freeze({__proto__:null,default:iS}),yr=zw(uS),lS=Uo.exports,$p;function cS(){return $p||($p=1,(function(n){(function(e,t,r){var s=256,a=6,o=52,i="random",l=r.pow(s,a),c=r.pow(2,o),u=c*2,d=s-1,p;function f(C,T,O){var L=[];T=T==!0?{entropy:!0}:T||{};var B=v(b(T.entropy?[C,S(t)]:C??I(),3),L),A=new m(L),D=function(){for(var _=A.g(a),V=l,H=0;_=u;)_/=2,V/=2,H>>>=1;return(_+H)/V};return D.int32=function(){return A.g(4)|0},D.quick=function(){return A.g(4)/4294967296},D.double=D,v(S(A.S),t),(T.pass||O||function(_,V,H,Y){return Y&&(Y.S&&g(Y,A),_.state=function(){return g(A,{})}),H?(r[i]=_,V):_})(D,B,"global"in T?T.global:this==r,T.state)}function m(C){var T,O=C.length,L=this,B=0,A=L.i=L.j=0,D=L.S=[];for(O||(C=[O++]);B=1||o===0);const i=Math.sqrt(-2*Math.log(o)/o);e=this.mean+this.stdDev*s*i,t=this.mean+this.stdDev*a*i,(!this.truncated||this.isValidTruncated(e))&&(r=!0)}return(!this.truncated||this.isValidTruncated(t))&&(this.nextVal=this.convertValue(t)),this.convertValue(e)}convertValue(e){return this.dtype==null||this.dtype==="float32"?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}}class pS{constructor(e,t,r,s){this.alpha=e,this.beta=1/t,this.dtype=r;const a=s||Math.random();this.randu=Pd.alea(a.toString()),this.randn=new Fd(0,1,r,!1,this.randu()),e<1?this.d=e+2/3:this.d=e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,r,s,a,o;for(;;){do s=this.randn.nextValue(),o=1+this.c*s;while(o<=0);if(o*=o*o,e=s*s,t=1-.331*e*e,r=.5*e+this.d*(1-o+Math.log(o)),a=this.randu(),athis.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=r,s==null&&(s=Math.random()),typeof s=="number"&&(s=s.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=Pd.alea(s)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}/** + * @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. + * ============================================================================= + */function fS(n,e,t=1,r="float32",s){if(nn(n),t==null&&(t=1),r==null&&(r="float32"),r!=="float32"&&r!=="int32")throw new Error(`Unsupported data type ${r}`);const a=new pS(e,t,r,s),o=ut(n,r);for(let i=0;i`Error in reverse1D: x must be rank 1 but got rank ${e.rank}.`),bs(e,0)}const TS=M({reverse1d_:$S});/** + * @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. + * ============================================================================= + */function ES(n,e){const t=N(n,"x","reverse");return $(t.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${t.rank}.`),bs(t,e)}const AS=M({reverse2d_:ES});/** + * @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. + * ============================================================================= + */function RS(n,e){const t=N(n,"x","reverse");return $(t.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${t.rank}.`),bs(t,e)}const DS=M({reverse3d_:RS});/** + * @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. + * ============================================================================= + */function PS(n,e){const t=N(n,"x","reverse");return $(t.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${t.rank}.`),bs(t,e)}const FS=M({reverse4d_:PS});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function OS(n){const t={x:N(n,"x","round")};return z.runKernel(ad,t)}const Em=M({round_:OS});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function MS(n){const t={x:N(n,"x","rsqrt","float32")};return z.runKernel(od,t)}const LS=M({rsqrt_:MS});/** + * @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. + * ============================================================================= + */function zS(n){const t={x:N(n,"x","selu")};return z.runKernel(ud,t)}const BS=M({selu_:zS});function WS(n,e,t,r,s,a=[1,1],o="NHWC"){const i=N(n,"x","separableConv2d"),l=N(e,"depthwiseFilter","separableConv2d"),c=N(t,"pointwiseFilter","separableConv2d");let u=i,d=!1;if(i.rank===3&&(d=!0,u=K(i,[1,i.shape[0],i.shape[1],i.shape[2]])),o==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");$(u.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${u.rank}.`),$(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),$(c.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),$(c.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${c.shape[0]}.`),$(c.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${c.shape[1]}.`);const p=l.shape[2],f=l.shape[3];$(c.shape[2]===p*f,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${p*f}, but got ${c.shape[2]}.`);const m=Ad(u,l,r,s,o,a),b=pu(m,c,1,"valid",o);return d?K(b,[b.shape[1],b.shape[2],b.shape[3]]):b}const VS=M({separableConv2d_:WS});/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */async function US(n,e){const t=N(n,"x","setdiff1d"),r=N(e,"y","setdiff1d");$(t.dtype===r.dtype,()=>`x and y should have the same dtype, but got x (${t.dtype}) and y (${r.dtype}).`),$(t.rank===1,()=>`x should be 1D tensor, but got x (${t.shape}).`),$(r.rank===1,()=>`y should be 1D tensor, but got y (${r.shape}).`);const s=await t.data(),a=await r.data(),o=new Set(a);let i=0;for(let u=0;u`slice1d expects a rank-1 tensor, but got a rank-${r.rank} tensor`),Ae(r,[e],[t])}const ZS=M({slice1d_:QS});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function JS(n,e,t){const r=N(n,"x","slice2d");return $(r.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${r.rank} tensor`),Ae(r,e,t)}const eI=M({slice2d_:JS});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function tI(n,e,t){const r=N(n,"x","slice3d");return $(r.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${r.rank} tensor`),Ae(r,e,t)}const nI=M({slice3d_:tI});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function rI(n,e,t){const r=N(n,"x","slice4d");return $(r.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${r.rank} tensor`),Ae(r,e,t)}const sI=M({slice4d_:rI});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function aI(n,e=-1){const t=N(n,"logits","softmax","float32");if(e===-1&&(e=t.rank-1),e!==t.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${t.rank} and dim was ${e}`);const r={logits:t},s={dim:e};return z.runKernel(nu,r,s)}const oI=M({softmax_:aI});/** + * @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. + * ============================================================================= + */function iI(n){$(n.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${n.dtype}.`);const e={input:n};return z.runKernel(pf,e)}const Md=M({fft_:iI});/** + * @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. + * ============================================================================= + */function uI(n){$(n.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${n.dtype}.`);const e={input:n};return z.runKernel(hf,e)}const ni=M({ifft_:uI});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function lI(n){const e=n.shape[n.shape.length-1],t=n.size/e;let r;if(e<=2){const s=K(n,[t,e]);r=ni(s)}else{const s=[t,2*(e-1)],a=K(so(n),[t,e]),o=K(gu(n),[t,e]),i=bs(Ae(a,[0,1],[t,e-2]),1),l=Z(bs(Ae(o,[0,1],[t,e-2]),1),De(-1)),c=wt([a,i],1),u=wt([o,l],1),d=K(Cr(c,u),[s[0],s[1]]);r=ni(d)}if(r=so(r),n.rank===3&&n.shape[0]!==0){const s=r,a=n.shape[0];r=K(r,[a,r.shape[0]/a,r.shape[1]]),s.dispose()}return r}const Am=M({irfft_:lI});/** + * @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. + * ============================================================================= + */function cI(n,e,t=0){const s={x:N(n,"x","split")},a={numOrSizeSplits:e,axis:t};return z.runKernel(yd,s,a)}const ao=M({split_:cI});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function dI(n,e){$(n.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${n.dtype}`);let t=n.shape[n.shape.length-1];const r=n.size/t;let s;if(e!=null&&e0),g=n.shape.map(b=>b);g[n.shape.length-1]=e,s=Ae(n,m,g),t=e}else if(e!=null&&e>t){const m=n.shape.map(g=>g);m[n.shape.length-1]=e-t,s=wt([n,$r(m)],n.shape.length-1),t=e}else s=n;const a=tn(s),o=K(Cr(s,a),[r,t]),i=Md(o),l=Math.floor(t/2)+1,c=so(i),u=gu(i),d=ao(c,[l,t-l],c.shape.length-1),p=ao(u,[l,t-l],u.shape.length-1),f=s.shape.slice();return f[s.shape.length-1]=l,K(Cr(d[0],p[0]),f)}const Ld=M({rfft_:dI});/** + * @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. + * ============================================================================= + */function pI(n,e){let t=N(n,"a","squaredDifference"),r=N(e,"b","squaredDifference");[t,r]=pt(t,r),je(t.shape,r.shape);const s={a:t,b:r},a={};return z.runKernel(vd,s,a)}const Rm=M({squaredDifference_:pI});/** + * @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. + * ============================================================================= + */function hI(n,e){const t=N(n,"x","squeeze","string_or_numeric");return K(t,xw(t.shape,e).newShape)}const Qe=M({squeeze_:hI});/** + * @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. + * ============================================================================= + */function fI(n,e=0){const t=Qo(n,"tensors","stack","string_or_numeric");$(t.length>=1,()=>"Pass at least one tensor to tf.stack"),t.length>0&&$(e<=t[0].rank,()=>"Axis must be <= rank of the tensor");const r=t,s={axis:e};return z.runKernel(Yc,r,s)}const ar=M({stack_:fI});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function mI(n,e=0){const r={x:N(n,"x","step")},s={alpha:e};return z.runKernel(iu,r,s)}const Dm=M({step_:mI});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function gI(n,e,t,r,s=0,a=0,o=0,i=0,l=0){const u={x:N(n,"x","stridedSlice","string_or_numeric")},d={begin:e,end:t,strides:r,beginMask:s,endMask:a,ellipsisMask:o,newAxisMask:i,shrinkAxisMask:l};return z.runKernel(su,u,d)}const yI=M({stridedSlice_:gI});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function bI(n){const t={x:N(n,"x","tan","float32")};return z.runKernel(kd,t)}const wI=M({tan_:bI});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Nt(n,e){ca(n);const t=Rr(n,e);if(t.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Dr(n,null,t,e)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function fn(n,e,t){if(ca(n),e!=null&&e.length!==2)throw new Error("tensor2d() requires shape to have two numbers");const r=Rr(n,t);if(r.length!==2&&r.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(r.length===1&&e==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Dr(n,e,r,t)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Pm(n,e,t){if(ca(n),e!=null&&e.length!==3)throw new Error("tensor3d() requires shape to have three numbers");const r=Rr(n,t);if(r.length!==3&&r.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(r.length===1&&e==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return Dr(n,e,r,t)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function xI(n,e,t){if(ca(n),e!=null&&e.length!==4)throw new Error("tensor4d() requires shape to have four numbers");const r=Rr(n,t);if(r.length!==4&&r.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(r.length===1&&e==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return Dr(n,e,r,t)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function vI(n,e,t){if(ca(n),e!=null&&e.length!==5)throw new Error("tensor5d() requires shape to have five numbers");const r=Rr(n,t);if(r.length!==5&&r.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(r.length===1&&e==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return Dr(n,e,r,t)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function SI(n,e,t){if(ca(n),e!=null&&e.length!==6)throw new Error("tensor6d() requires shape to have six numbers");const r=Rr(n,t);if(r.length!==6&&r.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(r.length===1&&e==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return e=e||r,Dr(n,e,r,t)}function II(n,e,t){const r=e.rank>1?e.shape[e.rank-1]:1,s=e.rank>1?e.rank-1:1,a=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${t.shape}, indices.shape: ${e.shape}, shape: ${n}, sliceDim: ${r}, and batchDim: ${s}.`;if(t.rank1?e.shape[r-1]:1,a=t.length;let o=1;for(let d=s;d= 0 but got ${e}`);if(e>s)throw new Error(`'k' passed to topk() must be <= the last dimension (${s}) but got ${e}`);const a={x:r},o={k:e,sorted:t},[i,l]=z.runKernel(au,a,o);return{values:i,indices:l}}const NI=M({topk_:CI});/** + * @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. + * ============================================================================= + */function $I(n,e=0,t=1,r,s){if(nn(n),r!=null&&r==="bool")throw new Error("Unsupported data type $ { dtype }");const a=new Fd(e,t,r,!0,s),o=ut(n,r);for(let i=0;i0,()=>"The input tensor must be at least 1D");const r={x:t},s={axis:e},[a,o]=z.runKernel(Sf,r,s);return{values:a,indices:o}}const AI=M({unique_:EI});/** + * @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. + * ============================================================================= + */function RI(n,e,t){const r=N(n,"x","unsortedSegmentSum"),s=N(e,"segmentIds","unsortedSegmentSum","int32");$(ja(t),()=>"numSegments must be of dtype int");const a={x:r,segmentIds:s},o={numSegments:t};return z.runKernel(If,a,o)}const DI=M({unsortedSegmentSum_:RI});/** + * @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. + * ============================================================================= + */function PI(n,e=0){const t=N(n,"x","unstack","string_or_numeric");$(e>=-t.shape.length&&e`Axis = ${e} is not in [-${t.shape.length}, ${t.shape.length})`);const r={value:t},s={axis:e};return z.runKernel(Cd,r,s)}const Is=M({unstack_:PI});/** + * @license + * Copyright 2022 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. + * ============================================================================= + */function FI(n,e){return Dd(n,e,"right")}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function OI(n,e=!0,t,r){return z.makeVariable(n,e,t,r)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function MI(n,e){const t=[];for(let a=0;a0,()=>"mask cannot be scalar"),Yt(i.slice(a,a+o),s.shape,"mask's shape must match the first K dimensions of tensor's shape,");let l=1;for(let g=a;gi).reverse()),$(r.rank===e.length,()=>`Error in transpose: rank of input ${r.rank} must match length of perm ${e}.`),e.forEach(o=>{$(o>=0&&o`All entries in 'perm' must be between 0 and ${r.rank-1} but got ${e}`)}),r.rank<=1)return r.clone();const s={x:r},a={perm:e};return r.dtype==="complex64"?Ce(()=>{let o=so(r),i=gu(r);return o=z.runKernel(Qs,{x:o},a),i=z.runKernel(Qs,{x:i},a),t&&(i=Bn(i)),Cr(o,i)}):z.runKernel(Qs,s,a)}const wl=M({transpose_:WI});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function VI(n,e,t,r,s=!0){const a=N(n,"v","movingAverage"),o=N(e,"x","movingAverage"),i=N(t,"decay","movingAverage");i0(a,o),$(Vt(a.shape,o.shape),()=>"Shape mismatch in v and x");const l=De(1),c=$e(l,i);let u=Z($e(o,a),c);if(s){$(r!=null,()=>"When using zeroDebias: true, step is required.");const d=N(r,"step","movingAverage");u=Re(u,$e(l,eo(i,d)))}return he(a,u)}const UI=M({movingAverage_:VI});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function HI(n,e,t){nn(t);const r=N(n,"indices","scatterND","int32"),s=N(e,"updates","scatterND");Fm(s,r,t);const a={indices:r,updates:s},o={shape:t};return z.runKernel(Zi,a,o)}const GI=M({scatterND_:HI});function jI(n,e,t,r){if(n.dtype!=="int32")throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${n.dtype}.`);if(n.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${n.shape}.`);const s=n.rank>0?n.shape[0]:1,a=n.rank>1?n.shape[1]:1;if(t.length!==a)throw new Error(`outputShape has incorrect number of elements:, ${t.length}, should be: ${a}.`);const o=e.size;if(!(e.rank===0||e.rank===1&&o===s))throw new Error(`sparseValues has incorrect shape ${e.shape}, should be [] or [${s}]`);if(e.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function qI(n,e,t,r=0){nn(t);const s=N(n,"sparseIndices","sparseToDense","int32"),a=N(e,"sparseValues","sparseToDense","string_or_numeric"),o=N(r,"defaultValue","sparseToDense",a.dtype);jI(s,a,t,o);const i={sparseIndices:s,sparseValues:a,defaultValue:o},l={outputShape:t};return z.runKernel(ru,i,l)}const KI=M({sparseToDense_:qI});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function XI(n,e){const t=N(e,"indices","gatherND","int32"),s={params:N(n,"x","gatherND","string_or_numeric"),indices:t};return z.runKernel(Ri,s)}const YI=M({gatherND_:XI});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function QI(n,e){if(e==null)return n.shape.slice();if(Vt(n.shape,e))return e;if(n.shape.length===e.length){const t=[];for(let r=0;r`x has to be a floating point tensor since it's going to be scaled, but got a ${s.dtype} tensor instead.`),$(e>=0&&e<1,()=>`rate must be a float in the range [0, 1), but got ${e}.`),e===0)return n instanceof dt?s.clone():s;const a=QI(s,t),o=1-e,i=Re(hm(he(Od(a,0,1,"float32",r),o)),o);return Z(s,i)}const JI=M({dropout_:ZI});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Mm(n){return Math.floor(Math.pow(2,Math.ceil(Math.log(n)/Math.log(2))))}function zd(n,e,t){const r=1-n%2,s=new Float32Array(n);for(let a=0;a1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${r.rank}`),$(r.rank-1===s.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${r.rank} and targets rank ${s.rank}`),Yt(r.shape.slice(0,r.shape.length-1),s.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");const a=r.shape[r.shape.length-1];$(t>0&&t<=a,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${a}), but got ${t}`);const o=await r.data(),i=await s.data(),[l,c]=[o.length/a,a],u=kr("bool",l);for(let d=0;db.value-g.value),u[d]=0;for(let g=0;g`Error in conv2dDerFilter: input must be rank 4, but got shape ${i.shape}.`),$(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),$(t.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${t}.`);const c=a==="NHWC"?i.shape[3]:i.shape[1],u=a==="NHWC"?l.shape[3]:l.shape[1];$(c===t[2],()=>`Error in conv2dDerFilter: depth of input ${c}) must match input depth in filter (${t[2]}.`),$(u===t[3],()=>`Error in conv2dDerFilter: depth of dy (${u}) must match output depth for filter (${t[3]}).`),Tn("conv2dDerFilter",s,o);const d={x:i,dy:l},p={strides:r,pad:s,dataFormat:a,dimRoundingMode:o,filterShape:t};return z.runKernel(of,d,p)}const rk=M({conv2DBackpropFilter_:nk});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Bd(n,e,t){if(t==null||t==="linear")return n;if(t==="relu")return Z(n,Dm(e));throw new Error(`Cannot compute gradient for fused activation ${t}.`)}function Wd(n,e){let t=e;const r=V2(n.shape,e.shape);return r.length>0&&(t=at(t,r)),K(t,n.shape)}function Vd(n,e,t,r){if(e==="linear")return n;if(e==="relu")return yu(n);if(e==="elu")return lm(n);if(e==="relu6")return Tm(n);if(e==="prelu")return Nm(n,t);if(e==="leakyrelu")return gm(n,r);if(e==="sigmoid")return er(n);throw new Error(`Unknown fused activation ${e}.`)}const Ud=(n,e)=>!(n>0)||e==="linear";/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function sk({x:n,filter:e,strides:t,pad:r,dataFormat:s="NHWC",dilations:a=[1,1],dimRoundingMode:o,bias:i,activation:l="linear",preluActivationWeights:c,leakyreluAlpha:u}){if(l=l||"linear",Ud(z.state.gradientDepth,l)===!1){$(s==="NHWC",()=>`Error in fused conv2d: got dataFormat of ${s} but only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.`);let O=pu(n,e,t,r,s,a,o);return i!=null&&(O=he(O,i)),Vd(O,l,c,u)}const d=N(n,"x","conv2d","float32"),p=N(e,"filter","conv2d","float32");let f=d,m=!1;d.rank===3&&(m=!0,f=K(d,[1,d.shape[0],d.shape[1],d.shape[2]])),$(f.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${f.rank}.`),$(p.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${p.rank}.`),Tn("fused conv2d",r,o);const g=s==="NHWC"?f.shape[3]:f.shape[1];$(p.shape[2]===g,()=>`Error in conv2d: depth of input (${g}) must match input depth for filter ${p.shape[2]}.`),$($n(t,a),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${t} and dilations '${a}'`);const b=Tt(f.shape,p.shape,t,a,r,o);let v;i!=null&&(v=N(i,"bias","fused conv2d"),[v]=pt(v,d),s==="NHWC"?je(b.outShape,v.shape):($(v.shape.length<=1,()=>`Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${v.shape.length}.`),$(v.shape.length===0||v.shape[0]===b.outChannels||v.shape[0]===1,()=>`Error in fused conv2d: bias shape (${v.shape}) is not compatible with the number of output channels (${b.outChannels})`)));let I;if(c!=null){const O=c.shape;if($(O.length<=1||O.length===3,()=>`Error in fused conv2d: only supports scalar, 1-D Tensor or 3-D Tensor PReLU activation weights but got a tensor of rank-${O.length}.`),O.length===1)$(O[0]===1||O[0]===b.outChannels,()=>`Error in fused conv2d: PReLU activation weights (${O}) is not compatible with the number of output channels (${b.outChannels}).`);else if(O.length===3)try{je(O,b.outShape)}catch{const B=`Error in fused conv2d: PReLU activation weights (${O}) is not compatible with the output shape of the conv2d (${b.outShape}).`;throw Error(B)}I=N(c,"prelu weights","fused conv2d")}const S=(O,L)=>{$(s==="NHWC",()=>`Error in gradient of fused conv2D: got dataFormat of ${s} but only NHWC is currently supported.`);const[B,A,D,_]=L,V=Bd(O,D,l);$(Zo(a),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`);const H=im(A.shape,V,B,t,r),Y=rk(A,V,B.shape,t,r),X=[H,Y];if(_!=null){const ee=Wd(_,V);X.push(ee)}return X},C={x:f,filter:p,bias:v,preluActivationWeights:I},T={strides:t,pad:r,dataFormat:s,dilations:a,dimRoundingMode:o,activation:l,leakyreluAlpha:u};return i==null?sr((L,B,A)=>{let D=z.runKernel(Xa,C,T);return A([B,L,D]),m&&(D=K(D,[D.shape[1],D.shape[2],D.shape[3]])),{value:D,gradFunc:S}})(f,p):sr((L,B,A,D)=>{let _=z.runKernel(Xa,C,T);return D([B,L,_,A]),m&&(_=K(_,[_.shape[1],_.shape[2],_.shape[3]])),{value:_,gradFunc:S}})(f,p,v)}const ak=M({fusedConv2d_:sk});/** + * @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. + * ============================================================================= + */function ok(n,e,t,r,s,a=[1,1],o){let i=n;n.rank===3&&(i=K(n,[1,n.shape[0],n.shape[1],n.shape[2]]));let l=e;l.rank===3&&(l=K(e,[1,e.shape[0],e.shape[1],e.shape[2]]));const c={x:i,dy:l},u={strides:r,pad:s,dimRoundingMode:o,dilations:a,filterShape:t};return z.runKernel(uf,c,u)}const ik=M({depthwiseConv2dNativeBackpropFilter_:ok});/** + * @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. + * ============================================================================= + */function uk(n,e,t,r,s,a=[1,1],o){let i=e,l=!1;e.rank===3&&(l=!0,i=K(e,[1,e.shape[0],e.shape[1],e.shape[2]]));const c={dy:i,filter:t},u={strides:r,pad:s,dimRoundingMode:o,dilations:a,inputShape:n},d=z.runKernel(lf,c,u);return l?K(d,[d.shape[1],d.shape[2],d.shape[3]]):d}const lk=M({depthwiseConv2dNativeBackpropInput_:uk});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ck({x:n,filter:e,strides:t,pad:r,dataFormat:s="NHWC",dilations:a=[1,1],dimRoundingMode:o,bias:i,activation:l="linear",preluActivationWeights:c,leakyreluAlpha:u}){if(Ud(z.state.gradientDepth,l)===!1){let T=Ad(n,e,t,r,s,a,o);return i!=null&&(T=he(T,i)),Vd(T,l,c,u)}const d=N(n,"x","depthwiseConv2d","float32"),p=N(e,"filter","depthwiseConv2d","float32");let f=d,m=!1;d.rank===3&&(m=!0,f=K(d,[1,d.shape[0],d.shape[1],d.shape[2]])),$(f.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${f.rank}.`),$(p.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${p.rank}.`),$(f.shape[3]===p.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${f.shape[3]}) must match the inChannels dimension in filter ${p.shape[2]}.`),a==null&&(a=[1,1]),$($n(t,a),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${t} and dilations '${a}'`),Tn("fused depthwiseConv2d",r,o);const g=Tt(f.shape,p.shape,t,a,r,o,!0);let b;i!=null&&(b=N(i,"bias","fused conv2d"),[b]=pt(b,d),je(g.outShape,b.shape));let v;c!=null&&(v=N(c,"prelu weights","fused depthwiseConv2d"));const I=(T,O)=>{$(Zo(a),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`);const[L,B,A,D]=O,_=Bd(T,A,l),V=lk(B.shape,_,L,t,r,a,o),H=ik(B,_,L.shape,t,r,a,o);if(D!=null){const Y=Wd(b,_);return[V,H,Y]}return[V,H]},S={x:f,filter:p,bias:b,preluActivationWeights:v},C={strides:t,pad:r,dataFormat:s,dilations:a,dimRoundingMode:o,activation:l,leakyreluAlpha:u};return i==null?sr((O,L,B)=>{let A=z.runKernel(Ya,S,C);return B([L,O,A]),m&&(A=K(A,[A.shape[1],A.shape[2],A.shape[3]])),{value:A,gradFunc:I}})(f,p):sr((O,L,B,A)=>{let D=z.runKernel(Ya,S,C);return A([L,O,D,B]),m&&(D=K(D,[D.shape[1],D.shape[2],D.shape[3]])),{value:D,gradFunc:I}})(f,p,b)}const dk=M({fusedDepthwiseConv2d_:ck});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function pk({a:n,b:e,transposeA:t=!1,transposeB:r=!1,bias:s,activation:a="linear",preluActivationWeights:o,leakyreluAlpha:i=.2}){if(Ud(z.state.gradientDepth,a)===!1){let _=Ze(n,e,t,r);return s!=null&&(_=he(_,s)),Vd(_,a,o,i)}let l=N(n,"a","fused matMul"),c=N(e,"b","fused matMul");[l,c]=pt(l,c);const u=t?l.shape[l.rank-2]:l.shape[l.rank-1],d=r?c.shape[c.rank-1]:c.shape[c.rank-2],p=t?l.shape[l.rank-1]:l.shape[l.rank-2],f=r?c.shape[c.rank-2]:c.shape[c.rank-1],m=l.shape.slice(0,-2),g=c.shape.slice(0,-2),b=q(m),v=q(g);$(u===d,()=>`Error in fused matMul: inner shapes (${u}) and (${d}) of Tensors with shapes ${l.shape} and ${c.shape} and transposeA=${t} and transposeB=${r} must match.`);const S=je(l.shape.slice(0,-2),c.shape.slice(0,-2)).concat([p,f]),C=t?K(l,[b,u,p]):K(l,[b,p,u]),T=r?K(c,[v,f,d]):K(c,[v,d,f]);let O;s!=null&&(O=N(s,"bias","fused matMul"),[O]=pt(O,l),je(S,O.shape));let L;o!=null&&(L=N(o,"prelu weights","fused matMul"));const B=(_,V)=>{const[H,Y,X,ee]=V,ye=Bd(K(_,X.shape),X,a);let ce,be;if(!t&&!r?(ce=Ze(ye,Y,!1,!0),be=Ze(H,ye,!0,!1)):!t&&r?(ce=Ze(ye,Y,!1,!1),be=Ze(ye,H,!0,!1)):t&&!r?(ce=Ze(Y,ye,!1,!0),be=Ze(H,ye,!1,!1)):(ce=Ze(Y,ye,!0,!0),be=Ze(ye,H,!0,!0)),s!=null){const Se=Wd(ee,ye);return[ce,be,Se]}else return[ce,be]},A={a:C,b:T,bias:O,preluActivationWeights:L},D={transposeA:t,transposeB:r,activation:a,leakyreluAlpha:i};return s==null?sr((V,H,Y)=>{const X=z.runKernel(Ka,A,D);return Y([V,H,X]),{value:K(X,S),gradFunc:B}})(C,T):sr((V,H,Y,X)=>{const ee=z.runKernel(Ka,A,D);return X([V,H,ee,Y]),{value:K(ee,S),gradFunc:B}})(C,T,O)}const hk=M({fusedMatMul_:pk});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var fk=Object.freeze({__proto__:null,conv2d:ak,depthwiseConv2d:dk,matMul:hk});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function mk(n){return zd(n,.54,.46)}const gk=M({hammingWindow_:mk});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function yk(n){return zd(n,.5,.5)}const Lm=M({hannWindow_:yk});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function bk(n,e,t,r=!1,s=0){let a=0;const o=[];for(;a+e<=n.size;)o.push(Ae(n,a,e)),a+=t;if(r)for(;a`Error in cropAndResize: image must be rank 4,but got rank ${o.rank}.`),$(i.rank===2&&i.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${c},4] but had shape ${i.shape}.`),$(l.rank===1&&l.shape[0]===c,()=>`Error in cropAndResize: boxInd must be have size [${c}] but had shape ${i.shape}.`),$(r.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${r.length}.`),$(r[0]>=1&&r[1]>=1,()=>`cropSize must be atleast [1,1], but was ${r}`),$(s==="bilinear"||s==="nearest",()=>`method must be bilinear or nearest, but was ${s}`);const u={image:o,boxes:i,boxInd:l},d={method:s,extrapolationValue:a,cropSize:r};return z.runKernel(Ci,u,d)}const Sk=M({cropAndResize_:vk});/** + * @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. + * ============================================================================= + */function Ik(n){const e=N(n,"image","flipLeftRight","float32");$(e.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${e.rank}.`);const t={image:e};return z.runKernel(Ei,t,{})}const kk=M({flipLeftRight_:Ik});/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function _k(n){const e=N(n,"image","grayscaleToRGB"),t=e.rank-1,r=e.shape[t];$(e.rank>=2,()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${e.rank}.`),$(r===1,()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${r}.`);const s=new Array(e.rank);return s.fill(1,0,t),s[t]=3,Ua(e,s)}const Ck=M({grayscaleToRGB_:_k});/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */function Nk(n){const e=N(n,"image","RGBToGrayscale"),t=e.rank-1,r=e.shape[t];$(e.rank>=2,()=>`Error in RGBToGrayscale: images must be at least rank 2, but got rank ${e.rank}.`),$(r===3,()=>`Error in RGBToGrayscale: last dimension of an RGB image should be size 3, but got size ${r}.`);const s=e.dtype,a=tt(e,"float32"),o=Nt([.2989,.587,.114]);let i;switch(e.rank){case 2:i=Ys("ij,j->i",a,o);break;case 3:i=Ys("ijk,k->ij",a,o);break;case 4:i=Ys("ijkl,l->ijk",a,o);break;case 5:i=Ys("ijklm,m->ijkl",a,o);break;case 6:i=Ys("ijklmn,n->ijklm",a,o);break;default:throw new Error("Not a valid tensor rank.")}return i=en(i,-1),tt(i,s)}const $k=M({rgbToGrayscale_:Nk});/** + * @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. + * ============================================================================= + */function Tk(n,e,t=0,r=.5){const s=N(n,"image","rotateWithOffset","float32");$(s.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${s.rank}.`);const a={image:s},o={radians:e,fillValue:t,center:r};return z.runKernel(uu,a,o)}const Ek=M({rotateWithOffset_:Tk});/** + * @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. + * ============================================================================= + */function fa(n,e,t,r,s,a){r==null&&(r=.5),s==null&&(s=Number.NEGATIVE_INFINITY),a==null&&(a=0);const o=n.shape[0];return t=Math.min(t,o),$(0<=r&&r<=1,()=>`iouThreshold must be in [0, 1], but was '${r}'`),$(n.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${n.rank}'`),$(n.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${n.shape[1]}`),$(e.rank===1,()=>"scores must be a 1D tensor"),$(e.shape[0]===o,()=>`scores has incompatible shape with boxes. Expected ${o}, but was ${e.shape[0]}`),$(0<=a&&a<=1,()=>`softNmsSigma must be in [0, 1], but was '${a}'`),{maxOutputSize:t,iouThreshold:r,scoreThreshold:s,softNmsSigma:a}}/** + * @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. + * ============================================================================= + */function Ak(n,e,t,r=.5,s=Number.NEGATIVE_INFINITY){const a=N(n,"boxes","nonMaxSuppression","float32"),o=N(e,"scores","nonMaxSuppression","float32"),i=fa(a,o,t,r,s);t=i.maxOutputSize,r=i.iouThreshold,s=i.scoreThreshold;const l={maxOutputSize:t,iouThreshold:r,scoreThreshold:s};return z.runKernel(Ui,{boxes:a,scores:o},l)}const Rk=M({nonMaxSuppression_:Ak});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Dk(n,e,t){const r=Pk(n,e,t),s=r<0?-(r+1):r;n.splice(s,0,e)}function Pk(n,e,t){return Ok(n,e,t||Fk)}function Fk(n,e){return n>e?1:n>>1);const i=t(e,n[a]);i>0?r=a+1:(s=a,o=!i)}return o?r:-r-1}/** + * @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. + * ============================================================================= + */function Bm(n,e,t,r,s){return Hd(n,e,t,r,s,0)}function Mk(n,e,t,r,s,a){return Hd(n,e,t,r,s,0,!1,a,!0)}function Wm(n,e,t,r,s,a){return Hd(n,e,t,r,s,a,!0)}function Hd(n,e,t,r,s,a,o=!1,i=!1,l=!1){const c=[];for(let b=0;bs&&c.push({score:e[b],boxIndex:b,suppressBeginIndex:0});c.sort(Ep);const u=a>0?-.5/a:0,d=[],p=[];for(;d.length0;){const b=c.pop(),{score:v,boxIndex:I,suppressBeginIndex:S}=b;if(v=S;--T){const O=Lk(n,I,d[T]);if(O>=r){C=!0;break}if(b.score=b.score*zk(r,u,O),b.score<=s)break}b.suppressBeginIndex=d.length,C||(b.score===v?(d.push(I),p.push(b.score)):b.score>s&&Dk(c,b,Ep))}const f=d.length,m=t-f;i&&m>0&&(d.push(...new Array(m).fill(0)),p.push(...new Array(m).fill(0)));const g={selectedIndices:d};return o&&(g.selectedScores=p),l&&(g.validOutputs=f),g}function Lk(n,e,t){const r=n.subarray(e*4,e*4+4),s=n.subarray(t*4,t*4+4),a=Math.min(r[0],r[2]),o=Math.min(r[1],r[3]),i=Math.max(r[0],r[2]),l=Math.max(r[1],r[3]),c=Math.min(s[0],s[2]),u=Math.min(s[1],s[3]),d=Math.max(s[0],s[2]),p=Math.max(s[1],s[3]),f=(i-a)*(l-o),m=(d-c)*(p-u);if(f<=0||m<=0)return 0;const g=Math.max(a,c),b=Math.max(o,u),v=Math.min(i,d),I=Math.min(l,p),S=Math.max(v-g,0)*Math.max(I-b,0);return S/(f+m-S)}function zk(n,e,t){const r=Math.exp(e*t*t);return t<=n?r:0}function Ep(n,e){return n.score-e.score||n.score===e.score&&e.boxIndex-n.boxIndex}/** + * @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. + * ============================================================================= + */async function Bk(n,e,t,r=.5,s=Number.NEGATIVE_INFINITY){const a=N(n,"boxes","nonMaxSuppressionAsync"),o=N(e,"scores","nonMaxSuppressionAsync"),i=fa(a,o,t,r,s);t=i.maxOutputSize,r=i.iouThreshold,s=i.scoreThreshold;const l=await Promise.all([a.data(),o.data()]),c=l[0],u=l[1],{selectedIndices:d}=Bm(c,u,t,r,s);return a!==n&&a.dispose(),o!==e&&o.dispose(),Nt(d,"int32")}const Wk=Bk;/** + * @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. + * ============================================================================= + */function Vk(n,e,t,r=.5,s=Number.NEGATIVE_INFINITY,a=0){const o=N(n,"boxes","nonMaxSuppression"),i=N(e,"scores","nonMaxSuppression"),l=fa(o,i,t,r,s,a);t=l.maxOutputSize,r=l.iouThreshold,s=l.scoreThreshold,a=l.softNmsSigma;const c={boxes:o,scores:i},u={maxOutputSize:t,iouThreshold:r,scoreThreshold:s,softNmsSigma:a},d=z.runKernel(Hi,c,u);return{selectedIndices:d[0],selectedScores:d[1]}}const Uk=M({nonMaxSuppressionWithScore_:Vk});/** + * @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. + * ============================================================================= + */async function Hk(n,e,t,r=.5,s=Number.NEGATIVE_INFINITY,a=0){const o=N(n,"boxes","nonMaxSuppressionAsync"),i=N(e,"scores","nonMaxSuppressionAsync"),l=fa(o,i,t,r,s,a);t=l.maxOutputSize,r=l.iouThreshold,s=l.scoreThreshold,a=l.softNmsSigma;const c=await Promise.all([o.data(),i.data()]),u=c[0],d=c[1],{selectedIndices:p,selectedScores:f}=Wm(u,d,t,r,s,a);return o!==n&&o.dispose(),i!==e&&i.dispose(),{selectedIndices:Nt(p,"int32"),selectedScores:Nt(f)}}const Gk=Hk;/** + * @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. + * ============================================================================= + */function jk(n,e,t,r=.5,s=Number.NEGATIVE_INFINITY,a=!1){const o=N(n,"boxes","nonMaxSuppression"),i=N(e,"scores","nonMaxSuppression"),l=fa(o,i,t,r,s,null),c=l.maxOutputSize,u=l.iouThreshold,d=l.scoreThreshold,p={boxes:o,scores:i},f={maxOutputSize:c,iouThreshold:u,scoreThreshold:d,padToMaxOutputSize:a},m=z.runKernel(Kc,p,f);return{selectedIndices:m[0],validOutputs:m[1]}}const qk=M({nonMaxSuppressionPadded_:jk});/** + * @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. + * ============================================================================= + */async function Kk(n,e,t,r=.5,s=Number.NEGATIVE_INFINITY,a=!1){const o=N(n,"boxes","nonMaxSuppressionAsync"),i=N(e,"scores","nonMaxSuppressionAsync"),l=fa(o,i,t,r,s,null),c=l.maxOutputSize,u=l.iouThreshold,d=l.scoreThreshold,[p,f]=await Promise.all([o.data(),i.data()]),{selectedIndices:m,validOutputs:g}=Mk(p,f,c,u,d,a);return o!==n&&o.dispose(),i!==e&&i.dispose(),{selectedIndices:Nt(m,"int32"),validOutputs:De(g,"int32")}}const Xk=Kk;/** + * @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. + * ============================================================================= + */function Yk(n,e,t=!1,r=!1){const s=N(n,"images","resizeBilinear");$(s.rank===3||s.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${s.rank}.`),$(e.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${e}.`),$(r===!1||t===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let a=s,o=!1;s.rank===3&&(o=!0,a=K(s,[1,s.shape[0],s.shape[1],s.shape[2]]));const i={images:a},l={alignCorners:t,halfPixelCenters:r,size:e},c=z.runKernel(Yi,i,l);return o?K(c,[c.shape[1],c.shape[2],c.shape[3]]):c}const Qk=M({resizeBilinear_:Yk});/** + * @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. + * ============================================================================= + */function Zk(n,e,t=!1,r=!1){const s=N(n,"images","resizeNearestNeighbor");$(s.rank===3||s.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${s.rank}.`),$(e.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${e}.`),$(s.dtype==="float32"||s.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),$(r===!1||t===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let a=s,o=!1;s.rank===3&&(o=!0,a=K(s,[1,s.shape[0],s.shape[1],s.shape[2]]));const i={images:a},l={alignCorners:t,halfPixelCenters:r,size:e},c=z.runKernel(Xi,i,l);return o?K(c,[c.shape[1],c.shape[2],c.shape[3]]):c}const Jk=M({resizeNearestNeighbor_:Zk});/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function e_(n,e="binary",t=!1,r=.5){const s=N(n,"image","threshold"),a=.2989,o=.587,i=.114,l=s.shape[0]*s.shape[1];let c=Z(Nt([r]),255),u,d,p,f;if($(s.rank===3,()=>`Error in threshold: image must be rank 3,but got rank ${s.rank}.`),$(s.shape[2]===3||s.shape[2]===1,()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${s.shape[2]}.`),$(s.dtype==="int32"||s.dtype==="float32",()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${s.dtype}.`),$(e==="otsu"||e==="binary",()=>`Method must be binary or otsu, but was ${e}`),s.shape[2]===3){[u,d,p]=ao(s,[1,1,1],-1);const b=Z(u,a),v=Z(d,o),I=Z(p,i);f=he(he(b,v),I)}else f=n;if(e==="otsu"){const b=am(tt(Em(f),"int32"),_n([]),256);c=t_(b,l)}const m=t?Rd(f,c):mu(f,c);return tt(Z(m,255),"int32")}function t_(n,e){let t=Nt([-1]),r=Nt([0]),s=Nt([0]),a,o,i,l,c,u;for(let d=0;d`Error in transform: image must be rank 4,but got rank ${o.rank}.`),$(i.rank===2&&(i.shape[0]===o.shape[0]||i.shape[0]===1)&&i.shape[1]===8,()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),$(a==null||a.length===2,()=>`Error in transform: outputShape must be [height, width] or null, but got ${a}.`);const l={image:o,transforms:i},c={interpolation:t,fillMode:r,fillValue:s,outputShape:a};return z.runKernel(ou,l,c)}const s_=M({transform_:r_});/** + * @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. + * ============================================================================= + */function a_(n,e,t){const r=N(n,"a","bandPart");$(r.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${r.rank}.`);const s=r.shape,[a,o]=r.shape.slice(-2);let i,l;typeof e=="number"?($(e%1===0,()=>`bandPart(): numLower must be an integer, got ${e}.`),$(e<=a,()=>`bandPart(): numLower (${e}) must not be greater than the number of rows (${a}).`),i=N(e<0?a:e,"numLower","bandPart")):($(e.dtype==="int32",()=>"bandPart(): numLower's dtype must be an int32."),i=Sr(bl(e,0),a,no(e,a))),typeof t=="number"?($(t%1===0,()=>`bandPart(): numUpper must be an integer, got ${t}.`),$(t<=o,()=>`bandPart(): numUpper (${t}) must not be greater than the number of columns (${o}).`),l=N(t<0?o:t,"numUpper","bandPart")):($(t.dtype==="int32",()=>"bandPart(): numUpper's dtype must be an int32."),l=Sr(bl(t,0),o,no(t,o)));const c=K(ro(0,a,1,"int32"),[-1,1]),u=ro(0,o,1,"int32"),d=$e(c,u),p=ei(Rd(d,i),mm(d,Bn(l))),f=$r([a,o],r.dtype);return K(ar(Is(K(r,[-1,a,o])).map(m=>Sr(p,m,f))),s)}const o_=M({bandPart_:a_});/** + * @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. + * ============================================================================= + */function i_(n){let e;if(Array.isArray(n)){e=!1,$(n!=null&&n.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");const s=n[0].shape[0];for(let a=1;a`Gram-Schmidt: Non-unique lengths found in the input vectors: (${n[a].shape[0]} vs. ${s})`)}else e=!0,n=ao(n,n.shape[0],0).map(s=>Qe(s,[0]));$(n.length<=n[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${n.length}) exceeds number of dimensions (${n[0].shape[0]}).`);const t=[],r=n;for(let s=0;s{let a=r[s];if(s>0)for(let o=0;o=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${n.rank}`),n.rank===2)return Ap(n,e);{const t=n.shape.slice(0,n.shape.length-2).reduce((l,c)=>l*c),r=Is(K(n,[t,n.shape[n.shape.length-2],n.shape[n.shape.length-1]]),0),s=[],a=[];r.forEach(l=>{const[c,u]=Ap(l,e);s.push(c),a.push(u)});const o=K(ar(s,0),n.shape),i=K(ar(a,0),n.shape);return[o,i]}}function Ap(n,e=!1){return z.tidy(()=>{$(n.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${n.shape.length}D Tensor.`);const t=n.shape[0],r=n.shape[1];let s=pm(t),a=vr(n);const o=fn([[1]],[1,1]);let i=vr(o);const l=t>=r?r:t;for(let c=0;c{const f=Ae(a,[c,c],[t-c,1]),m=fu(f),g=Ae(a,[c,c],[1,1]),b=Sr(mu(g,0),fn([[-1]]),fn([[1]])),v=$e(g,Z(b,m)),I=Re(f,v);I.shape[0]===1?i=vr(o):i=wt([o,Ae(I,[1,0],[I.shape[0]-1,I.shape[1]])],0);const S=Bn(Re(Ze(b,v),m)),C=Ae(a,[c,0],[t-c,r]),T=Z(S,i),O=wl(i);if(c===0)a=$e(C,Ze(T,Ze(O,C)));else{const A=$e(C,Ze(T,Ze(O,C)));a=wt([Ae(a,[0,0],[c,r]),A],0)}const L=wl(T),B=Ae(s,[0,c],[t,s.shape[1]-c]);if(c===0)s=$e(B,Ze(Ze(B,i),L));else{const A=$e(B,Ze(Ze(B,i),L));s=wt([Ae(s,[0,0],[t,c]),A],1)}return[i,a,s]}),Ke([u,d,p])}return!e&&t>r&&(s=Ae(s,[0,0],[t,r]),a=Ae(a,[0,0],[r,r])),[s,a]})}const c_=M({qr_:l_});/** + * @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 zt;(function(n){n[n.NONE=0]="NONE",n[n.MEAN=1]="MEAN",n[n.SUM=2]="SUM",n[n.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"})(zt||(zt={}));function d_(n,e,t=zt.SUM_BY_NONZERO_WEIGHTS){const r=N(n,"losses","computeWeightedLoss");let s=null;e!=null&&(s=N(e,"weights","computeWeightedLoss"));const a=s==null?r:Z(r,s);if(t===zt.NONE)return a;if(t===zt.SUM)return at(a);if(t===zt.MEAN){if(s==null)return ti(a);{const o=r.size/s.size,i=Re(at(a),at(s));return o>1?Re(i,De(o)):i}}if(t===zt.SUM_BY_NONZERO_WEIGHTS){if(s==null)return Re(at(a),De(r.size));{const o=Z(s,as(r.shape)),i=tt(at(_m(o,De(0))),"float32");return Re(at(a),i)}}throw Error(`Unknown reduction: ${t}`)}const or=M({computeWeightedLoss_:d_});/** + * @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. + * ============================================================================= + */function p_(n,e,t,r=zt.SUM_BY_NONZERO_WEIGHTS){const s=N(n,"labels","absoluteDifference"),a=N(e,"predictions","absoluteDifference");let o=null;t!=null&&(o=N(t,"weights","absoluteDifference")),Yt(s.shape,a.shape,"Error in absoluteDifference: ");const i=Jt($e(s,a));return or(i,o,r)}const h_=M({absoluteDifference_:p_});function f_(n,e,t,r,s=zt.SUM_BY_NONZERO_WEIGHTS){const a=N(n,"labels","cosineDistance"),o=N(e,"predictions","cosineDistance");let i=null;r!=null&&(i=N(r,"weights","cosineDistance")),Yt(a.shape,o.shape,"Error in cosineDistance: ");const l=De(1),c=$e(l,at(Z(a,o),t,!0));return or(c,i,s)}const m_=M({cosineDistance_:f_});function g_(n,e,t,r=zt.SUM_BY_NONZERO_WEIGHTS){let s=N(n,"labels","hingeLoss");const a=N(e,"predictions","hingeLoss");let o=null;t!=null&&(o=N(t,"weights","hingeLoss")),Yt(s.shape,a.shape,"Error in hingeLoss: ");const i=De(1);s=$e(Z(De(2),s),i);const l=yu($e(i,Z(s,a)));return or(l,o,r)}const y_=M({hingeLoss_:g_});/** + * @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. + * ============================================================================= + */function b_(n,e,t,r=1,s=zt.SUM_BY_NONZERO_WEIGHTS){const a=N(n,"labels","huberLoss"),o=N(e,"predictions","huberLoss");let i=null;t!=null&&(i=N(t,"weights","huberLoss")),Yt(a.shape,o.shape,"Error in huberLoss: ");const l=De(r),c=Jt($e(o,a)),u=no(c,l),d=$e(c,u),p=he(Z(De(.5),hn(u)),Z(l,d));return or(p,i,s)}const w_=M({huberLoss_:b_});/** + * @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. + * ============================================================================= + */function x_(n,e,t,r=1e-7,s=zt.SUM_BY_NONZERO_WEIGHTS){const a=N(n,"labels","logLoss"),o=N(e,"predictions","logLoss");let i=null;t!=null&&(i=N(t,"weights","logLoss")),Yt(a.shape,o.shape,"Error in logLoss: ");const l=De(1),c=De(r),u=Bn(Z(a,to(he(o,c)))),d=Z($e(l,a),to(he($e(l,o),c))),p=$e(u,d);return or(p,i,s)}const v_=M({logLoss_:x_});/** + * @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. + * ============================================================================= + */function S_(n,e,t,r=zt.SUM_BY_NONZERO_WEIGHTS){const s=N(n,"labels","meanSquaredError"),a=N(e,"predictions","meanSquaredError");let o=null;t!=null&&(o=N(t,"weights","meanSquaredError")),Yt(s.shape,a.shape,"Error in meanSquaredError: ");const i=Rm(s,a);return or(i,o,r)}const I_=M({meanSquaredError_:S_});/** + * @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. + * ============================================================================= + */function k_(n,e){const t=N(n,"labels","sigmoidCrossEntropyWithLogits"),r=N(e,"logits","sigmoidCrossEntropyWithLogits");Yt(t.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");const s=yu(r),a=Z(r,t),o=ym(rr(Bn(Jt(r))));return he($e(s,a),o)}function __(n,e,t,r=0,s=zt.SUM_BY_NONZERO_WEIGHTS){let a=N(n,"multiClassLabels","sigmoidCrossEntropy");const o=N(e,"logits","sigmoidCrossEntropy");let i=null;if(t!=null&&(i=N(t,"weights","sigmoidCrossEntropy")),Yt(a.shape,o.shape,"Error in sigmoidCrossEntropy: "),r>0){const c=De(r),u=De(1),d=De(.5);a=he(Z(a,$e(u,c)),Z(d,c))}const l=k_(a,o);return or(l,i,s)}const C_=M({sigmoidCrossEntropy_:__});/** + * @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. + * ============================================================================= + */function N_(n,e,t=-1){if(t===-1&&(t=e.rank-1),t!==e.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${e.rank} and dim was ${t}`);return sr((s,a,o)=>{const l=wm(a,[t],!0),c=$e(tt(a,"float32"),l);o([s,c]);const u=Bn(Z(c,s));return{value:at(u,[t]),gradFunc:(f,m)=>{const[g,b]=m,v=gn(f.shape,[t]);return[Z(K(f,v),$e(tt(g,"float32"),rr(b))),Z(K(f,v),$e(rr(b),tt(g,"float32")))]}}})(n,e)}function $_(n,e,t,r=0,s=zt.SUM_BY_NONZERO_WEIGHTS){let a=N(n,"onehotLabels","softmaxCrossEntropy");const o=N(e,"logits","softmaxCrossEntropy");let i=null;if(t!=null&&(i=N(t,"weights","softmaxCrossEntropy")),Yt(a.shape,o.shape,"Error in softmaxCrossEntropy: "),r>0){const c=De(r),u=De(1),d=De(a.shape[1]);a=he(Z(a,$e(u,c)),Re(c,d))}const l=N_(a,o);return or(l,i,s)}const T_=M({softmaxCrossEntropy_:$_});/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function E_(n,e,t,r){const s=N(n,"indices","sparseFillEmptyRows","int32"),a=N(e,"values","sparseFillEmptyRows"),o=N(t,"denseShape","sparseFillEmptyRows","int32"),i=N(r,"defaultValue","sparseFillEmptyRows",a.dtype);if(s.rank!==2)throw new Error(`Indices should be Tensor2D but received shape + ${s.shape}`);if(a.rank!==1)throw new Error(`Values should be Tensor1D but received shape ${a.shape}`);if(o.rank!==1)throw new Error(`Dense shape should be Tensor1D but received shape ${o.shape}`);if(i.rank!==0)throw new Error(`Default value should be a scalar but received shape ${i.shape}`);const l={indices:s,values:a,denseShape:o,defaultValue:i},c=z.runKernel(bf,l);return{outputIndices:c[0],outputValues:c[1],emptyRowIndicator:c[2],reverseIndexMap:c[3]}}const A_=M({sparseFillEmptyRows_:E_});/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function R_(n,e,t){const r=N(n,"inputIndices","sparseReshape","int32"),s=N(e,"inputShape","sparseReshape","int32"),a=N(t,"newShape","sparseReshape","int32");if(r.rank!==2)throw new Error(`Input indices should be Tensor2D but received shape + ${r.shape}`);if(s.rank!==1)throw new Error(`Input shape should be Tensor1D but received shape ${s.shape}`);if(a.rank!==1)throw new Error(`New shape should be Tensor1D but received shape ${a.shape}`);const o={inputIndices:r,inputShape:s,newShape:a},i=z.runKernel(bd,o);return{outputIndices:i[0],outputShape:i[1]}}const D_=M({sparseReshape_:R_});/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function P_(n,e,t){const r=N(n,"data","sparseSegmentMean"),s=N(e,"indices","sparseSegmentMean","int32"),a=N(t,"segmentIds","sparseSegmentMean","int32");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.rank!==1)throw new Error(`Indices should be Tensor1D but received shape + ${s.shape}`);if(a.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape + ${a.shape}`);const o={data:r,indices:s,segmentIds:a};return z.runKernel(wd,o)}const F_=M({sparseSegmentMean_:P_});/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function O_(n,e,t){const r=N(n,"data","sparseSegmentSum"),s=N(e,"indices","sparseSegmentSum","int32"),a=N(t,"segmentIds","sparseSegmentSum","int32");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.rank!==1)throw new Error(`Indices should be Tensor1D but received shape + ${s.shape}`);if(a.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape + ${a.shape}`);const o={data:r,indices:s,segmentIds:a};return z.runKernel(xd,o)}const M_=M({sparseSegmentSum_:O_});/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function L_(n,e,t,r,s,a,o,i){const l=N(n,"data","stringNGrams","string");if(l.dtype!=="string")throw new Error("Data must be of datatype string");if(l.shape.length!==1)throw new Error(`Data must be a vector, saw: ${l.shape}`);const c=N(e,"dataSplits","stringNGrams");if(c.dtype!=="int32")throw new Error("Data splits must be of datatype int32");const u={separator:t,nGramWidths:r,leftPad:s,rightPad:a,padWidth:o,preserveShortSequences:i},d={data:l,dataSplits:c},p=z.runKernel(Sd,d,u);return{nGrams:p[0],nGramsSplits:p[1]}}const z_=M({stringNGrams_:L_});/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function B_(n,e,t=!0){const r=N(n,"input","stringSplit","string"),s=N(e,"delimiter","stringSplit","string");if(r.rank!==1)throw new Error(`Input should be Tensor1D but received shape ${r.shape}`);if(s.rank!==0)throw new Error(`Delimiter should be a scalar but received shape ${s.shape}`);const a={skipEmpty:t},o={input:r,delimiter:s},i=z.runKernel(xf,o,a);return{indices:i[0],values:i[1],shape:i[2]}}const W_=M({stringSplit_:B_});/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function V_(n,e){const t=N(n,"input","stringToHashBucketFast","string"),r={numBuckets:e};if(e<=0)throw new Error("Number of buckets must be at least 1");const s={input:t};return z.runKernel(vf,s,r)}const U_=M({stringToHashBucketFast_:V_});/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */function H_(n,e,t,r=!0){const s=N(n,"input","staticRegexReplace","string"),a={pattern:e,rewrite:t,replaceGlobal:r};return z.runKernel(Mw,{x:s},a)}const G_=M({staticRegexReplace_:H_});/** + * @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. + * ============================================================================= + */const j_={fft:Md,ifft:ni,rfft:Ld,irfft:Am},q_={hammingWindow:gk,hannWindow:Lm,frame:zm,stft:xk},ls={flipLeftRight:kk,grayscaleToRGB:Ck,resizeNearestNeighbor:Jk,resizeBilinear:Qk,rgbToGrayscale:$k,rotateWithOffset:Ek,cropAndResize:Sk,nonMaxSuppression:Rk,nonMaxSuppressionAsync:Wk,nonMaxSuppressionWithScore:Uk,nonMaxSuppressionWithScoreAsync:Gk,nonMaxSuppressionPadded:qk,nonMaxSuppressionPaddedAsync:Xk,threshold:n_,transform:s_},K_={bandPart:o_,gramSchmidt:u_,qr:c_},X_={absoluteDifference:h_,computeWeightedLoss:or,cosineDistance:m_,hingeLoss:y_,huberLoss:w_,logLoss:v_,meanSquaredError:I_,sigmoidCrossEntropy:C_,softmaxCrossEntropy:T_},Y_={sparseFillEmptyRows:A_,sparseReshape:D_,sparseSegmentMean:F_,sparseSegmentSum:M_},Q_={stringNGrams:z_,stringSplit:W_,stringToHashBucketFast:U_,staticRegexReplace:G_};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Z_=new Map,J_=new Map;class eC{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class ts{constructor(){this.classNameMap={}}static getMap(){return ts.instance==null&&(ts.instance=new ts),ts.instance}static register(e){ts.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function tC(n,e,t){$(n.className!=null,()=>"Class being registered does not have the static className property defined."),$(typeof n.className=="string",()=>"className is required to be a string, but got type "+typeof n.className),$(n.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),typeof e>"u"&&(e="Custom"),typeof t>"u"&&(t=n.className);const r=t,s=e+">"+r;return ts.register(n),Z_.set(s,n),J_.set(n,s),n}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class ks extends eC{minimize(e,t=!1,r){const{value:s,grads:a}=this.computeGradients(e,r);if(r!=null){const o=r.map(i=>({name:i.name,tensor:a[i.name]}));this.applyGradients(o)}else this.applyGradients(a);return Ke(a),t?s:(s.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return Mx(e,t)}dispose(){this.iterations_!=null&&Ke(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:De(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(e){throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`)}async extractIterations(e){return this.iterations_=(await e[0].tensor.data())[0],e.slice(1)}}Object.defineProperty(ks,Symbol.hasInstance,{value:n=>n.minimize!=null&&n.computeGradients!=null&&n.applyGradients!=null});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class nC extends ks{static get className(){return"Adadelta"}constructor(e,t,r=null){super(),this.learningRate=e,this.rho=t,this.epsilon=r,this.accumulatedGrads=[],this.accumulatedUpdates=[],r==null&&(this.epsilon=z.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(r=>r.name):Object.keys(e)).forEach((r,s)=>{const a=z.registeredVariables[r],o=!1;this.accumulatedGrads[s]==null&&(this.accumulatedGrads[s]={originalName:`${r}/accum_grad`,variable:Ce(()=>tn(a).variable(o))}),this.accumulatedUpdates[s]==null&&(this.accumulatedUpdates[s]={originalName:`${r}/accum_var`,variable:Ce(()=>tn(a).variable(o))});const i=Array.isArray(e)?e[s].tensor:e[r];if(i==null)return;const l=this.accumulatedGrads[s].variable,c=this.accumulatedUpdates[s].variable;Ce(()=>{const u=he(Z(l,this.rho),Z(hn(i),1-this.rho)),d=Z(Re(nr(he(c,this.epsilon)),nr(he(l,this.epsilon))),i),p=he(Z(c,this.rho),Z(hn(d),1-this.rho));l.assign(u),c.assign(p);const f=he(Z(d,-this.learningRate),a);a.assign(f)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(Ke(this.accumulatedGrads.map(e=>e.variable)),Ke(this.accumulatedUpdates.map(e=>e.variable)))}async getWeights(){const e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=e.length/2,r=!1;this.accumulatedGrads=e.slice(0,t).map(s=>({originalName:s.name,variable:s.tensor.variable(r)})),this.accumulatedUpdates=e.slice(t,t*2).map(s=>({originalName:s.name,variable:s.tensor.variable(r)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class rC extends ks{static get className(){return"Adagrad"}constructor(e,t=.1){super(),this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map(r=>r.name):Object.keys(e)).forEach((r,s)=>{const a=z.registeredVariables[r];this.accumulatedGrads[s]==null&&(this.accumulatedGrads[s]={originalName:`${r}/accumulator`,variable:Ce(()=>ho(a.shape,this.initialAccumulatorValue).variable(!1))});const o=Array.isArray(e)?e[s].tensor:e[r];if(o==null)return;const i=this.accumulatedGrads[s].variable;Ce(()=>{const l=he(i,hn(o));i.assign(l);const c=he(Z(Re(o,nr(he(l,z.backend.epsilon()))),-this.learningRate),a);a.assign(c)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&Ke(this.accumulatedGrads.map(e=>e.variable))}async getWeights(){return[await this.saveIterations()].concat(this.accumulatedGrads.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=!1;this.accumulatedGrads=e.map(r=>({originalName:r.name,variable:r.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class sC extends ks{static get className(){return"Adam"}constructor(e,t,r,s=null){super(),this.learningRate=e,this.beta1=t,this.beta2=r,this.epsilon=s,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],Ce(()=>{this.accBeta1=De(t).variable(),this.accBeta2=De(r).variable()}),s==null&&(this.epsilon=z.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(r=>r.name):Object.keys(e);Ce(()=>{const r=$e(1,this.accBeta1),s=$e(1,this.accBeta2);t.forEach((a,o)=>{const i=z.registeredVariables[a],l=!1;this.accumulatedFirstMoment[o]==null&&(this.accumulatedFirstMoment[o]={originalName:`${a}/m`,variable:Ce(()=>tn(i).variable(l))}),this.accumulatedSecondMoment[o]==null&&(this.accumulatedSecondMoment[o]={originalName:`${a}/v`,variable:Ce(()=>tn(i).variable(l))});const c=Array.isArray(e)?e[o].tensor:e[a];if(c==null)return;const u=this.accumulatedFirstMoment[o].variable,d=this.accumulatedSecondMoment[o].variable,p=he(Z(u,this.beta1),Z(c,1-this.beta1)),f=he(Z(d,this.beta2),Z(hn(c),1-this.beta2)),m=Re(p,r),g=Re(f,s);u.assign(p),d.assign(f);const b=he(Z(Re(m,he(nr(g),this.epsilon)),-this.learningRate),i);i.assign(b)}),this.accBeta1.assign(Z(this.accBeta1,this.beta1)),this.accBeta2.assign(Z(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&Ke(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&Ke(this.accumulatedSecondMoment.map(e=>e.variable))}async getWeights(){const e=[...this.accumulatedFirstMoment,...this.accumulatedSecondMoment];return[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e),Ce(()=>{this.accBeta1.assign(eo(this.beta1,this.iterations_+1)),this.accBeta2.assign(eo(this.beta2,this.iterations_+1))});const t=e.length/2,r=!1;this.accumulatedFirstMoment=e.slice(0,t).map(s=>({originalName:s.name,variable:s.tensor.variable(r)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(s=>({originalName:s.name,variable:s.tensor.variable(r)}))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class aC extends ks{static get className(){return"Adamax"}constructor(e,t,r,s=null,a=0){super(),this.learningRate=e,this.beta1=t,this.beta2=r,this.epsilon=s,this.decay=a,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],Ce(()=>{this.iteration=De(0).variable(),this.accBeta1=De(t).variable()}),s==null&&(this.epsilon=z.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(r=>r.name):Object.keys(e);Ce(()=>{const r=$e(1,this.accBeta1),s=Re(-this.learningRate,he(Z(this.iteration,this.decay),1));t.forEach((a,o)=>{const i=z.registeredVariables[a],l=!1;this.accumulatedFirstMoment[o]==null&&(this.accumulatedFirstMoment[o]={originalName:`${a}/m`,variable:tn(i).variable(l)}),this.accumulatedWeightedInfNorm[o]==null&&(this.accumulatedWeightedInfNorm[o]={originalName:`${a}/v`,variable:tn(i).variable(l)});const c=Array.isArray(e)?e[o].tensor:e[a];if(c==null)return;const u=this.accumulatedFirstMoment[o].variable,d=this.accumulatedWeightedInfNorm[o].variable,p=he(Z(u,this.beta1),Z(c,1-this.beta1)),f=Z(d,this.beta2),m=Jt(c),g=Im(f,m);u.assign(p),d.assign(g);const b=he(Z(Re(s,r),Re(p,he(g,this.epsilon))),i);i.assign(b)}),this.iteration.assign(he(this.iteration,1)),this.accBeta1.assign(Z(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&Ke(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&Ke(this.accumulatedWeightedInfNorm.map(e=>e.variable))}async getWeights(){throw new Error("getWeights() is not implemented for Adamax yet.")}async setWeights(e){throw new Error("setWeights() is not implemented for Adamax yet.")}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Vm extends ks{static get className(){return"SGD"}constructor(e){super(),this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map(r=>r.name):Object.keys(e)).forEach((r,s)=>{const a=Array.isArray(e)?e[s].tensor:e[r];if(a==null)return;const o=z.registeredVariables[r];Ce(()=>{const i=he(Z(this.c,a),o);o.assign(i)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=zn(De(-e))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(e){if(e=await this.extractIterations(e),e.length!==0)throw new Error("SGD optimizer does not have settable weights.")}getConfig(){return{learningRate:this.learningRate}}static fromConfig(e,t){return new e(t.learningRate)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class oC extends Vm{static get className(){return"Momentum"}constructor(e,t,r=!1){super(e),this.learningRate=e,this.momentum=t,this.useNesterov=r,this.accumulations=[],this.m=De(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(r=>r.name):Object.keys(e)).forEach((r,s)=>{const a=z.registeredVariables[r];this.accumulations[s]==null&&(this.accumulations[s]={originalName:`${r}/momentum`,variable:Ce(()=>tn(a).variable(!1))});const o=this.accumulations[s].variable,i=Array.isArray(e)?e[s].tensor:e[r];i!=null&&Ce(()=>{let l;const c=he(Z(this.m,o),i);this.useNesterov?l=he(Z(this.c,he(i,Z(c,this.m))),a):l=he(Z(this.c,c),a),o.assign(c),a.assign(l)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&Ke(this.accumulations.map(e=>e.variable))}setMomentum(e){this.momentum=e}async getWeights(){return[await this.saveIterations()].concat(this.accumulations.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=!1;this.accumulations=e.map(r=>({originalName:r.name,variable:r.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class iC extends ks{static get className(){return"RMSProp"}constructor(e,t=.9,r=0,s=null,a=!1){if(super(),this.learningRate=e,this.decay=t,this.momentum=r,this.epsilon=s,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=a,s==null&&(this.epsilon=z.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map(r=>r.name):Object.keys(e)).forEach((r,s)=>{const a=z.registeredVariables[r],o=!1;this.accumulatedMeanSquares[s]==null&&(this.accumulatedMeanSquares[s]={originalName:`${r}/rms`,variable:Ce(()=>tn(a).variable(o))}),this.accumulatedMoments[s]==null&&(this.accumulatedMoments[s]={originalName:`${r}/momentum`,variable:Ce(()=>tn(a).variable(o))}),this.accumulatedMeanGrads[s]==null&&this.centered&&(this.accumulatedMeanGrads[s]={originalName:`${r}/mg`,variable:Ce(()=>tn(a).variable(o))});const i=Array.isArray(e)?e[s].tensor:e[r];if(i==null)return;const l=this.accumulatedMeanSquares[s].variable,c=this.accumulatedMoments[s].variable;Ce(()=>{const u=he(Z(l,this.decay),Z(hn(i),1-this.decay));if(this.centered){const d=this.accumulatedMeanGrads[s].variable,p=he(Z(d,this.decay),Z(i,1-this.decay)),f=Re(Z(i,this.learningRate),nr($e(u,he(hn(p),this.epsilon)))),m=he(Z(c,this.momentum),f);l.assign(u),d.assign(p),c.assign(m);const g=$e(a,m);a.assign(g)}else{const d=he(Z(l,this.decay),Z(hn(i),1-this.decay)),p=he(Z(c,this.momentum),Re(Z(i,this.learningRate),nr(he(d,this.epsilon))));l.assign(d),c.assign(p);const f=$e(a,p);a.assign(f)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&Ke(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&Ke(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&Ke(this.accumulatedMoments.map(e=>e.variable))}async getWeights(){const e=[...this.accumulatedMeanSquares,...this.accumulatedMoments];return this.centered&&e.push(...this.accumulatedMeanGrads),[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=this.centered?e.length/3:e.length/2,r=!1;this.accumulatedMeanSquares=e.slice(0,t).map(s=>({originalName:s.name,variable:s.tensor.variable(r)})),this.accumulatedMoments=e.slice(t,t*2).map(s=>({originalName:s.name,variable:s.tensor.variable(r)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(s=>({originalName:s.name,variable:s.tensor.variable(r)})))}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)}}/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */const uC=[nC,rC,sC,aC,oC,iC,Vm];function lC(){for(const n of uC)tC(n)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const cC="model",dC=".json",pC=".weights.bin";function Rp(n){return new Promise(e=>setTimeout(e)).then(n)}class ws{constructor(e){if(!fe().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(ws.URL_SCHEME)&&(e=e.slice(ws.URL_SCHEME.length)),(e==null||e.length===0)&&(e=cC),this.modelJsonFileName=e+dC,this.weightDataFileName=e+pC}async save(e){if(typeof document>"u")throw new Error("Browser downloads are not supported in this environment since `document` is not present");const t=Cn.join(e.weightData),r=window.URL.createObjectURL(new Blob([t],{type:"application/octet-stream"}));if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{const s=[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}],a=Hf(e,s),o=window.URL.createObjectURL(new Blob([JSON.stringify(a)],{type:"application/json"})),i=this.modelJsonAnchor==null?document.createElement("a"):this.modelJsonAnchor;if(i.download=this.modelJsonFileName,i.href=o,await Rp(()=>i.dispatchEvent(new MouseEvent("click"))),e.weightData!=null){const l=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;l.download=this.weightDataFileName,l.href=r,await Rp(()=>l.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:po(e)}}}}ws.URL_SCHEME="downloads://";class hC{constructor(e){if(e==null||e.length<1)throw new Error(`When calling browserFiles, at least 1 file is required, but received ${e}`);this.jsonFile=e[0],this.weightsFiles=e.slice(1)}async load(){return new Promise((e,t)=>{const r=new FileReader;r.onload=s=>{const a=JSON.parse(s.target.result),o=a.modelTopology;if(o==null){t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));return}if(a.weightsManifest==null){t(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));return}if(this.weightsFiles.length===0){e({modelTopology:o});return}const l=Ed(a,c=>this.loadWeights(c));e(l)},r.onerror=s=>t(`Failed to read model topology and weights manifest JSON from file '${this.jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),r.readAsText(this.jsonFile)})}loadWeights(e){const t=[],r=[];for(const o of e)t.push(...o.weights),r.push(...o.paths);const s=this.checkManifestAndWeightFiles(e),a=r.map(o=>this.loadWeightsFile(o,s[o]));return Promise.all(a).then(o=>[t,o])}loadWeightsFile(e,t){return new Promise((r,s)=>{const a=new FileReader;a.onload=o=>{const i=o.target.result;r(i)},a.onerror=o=>s(`Failed to weights data from file of path '${e}'.`),a.readAsArrayBuffer(t)})}checkManifestAndWeightFiles(e){const t=[],r=this.weightsFiles.map(a=>vp(a.name)),s={};for(const a of e)a.paths.forEach(o=>{const i=vp(o);if(t.indexOf(i)!==-1)throw new Error(`Duplicate file basename found in weights manifest: '${i}'`);if(t.push(i),r.indexOf(i)===-1)throw new Error(`Weight file with basename '${i}' is not provided.`);s[o]=this.weightsFiles[r.indexOf(i)]});if(t.length!==this.weightsFiles.length)throw new Error(`Mismatch in the number of files in weights manifest (${t.length}) and the number of weight files provided (${this.weightsFiles.length}).`);return s}}const fC=n=>fe().getBool("IS_BROWSER")&&!Array.isArray(n)&&n.startsWith(ws.URL_SCHEME)?mC(n.slice(ws.URL_SCHEME.length)):null;ct.registerSaveRouter(fC);function mC(n="model"){return new ws(n)}function gC(n){return new hC(n)}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Dp(n,e,t,r){o(n),t=t??0,r=r??1,i(t,r);let s=0;const a=l=>(l.then(c=>{const u=t+ ++s/n.length*(r-t);return e(u),c}),l);function o(l){$(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function i(l,c){$(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),$(c>=0&&c<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${c}`),$(c>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${c}`)}return Promise.all(n.map(a))}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */async function Um(n,e){e==null&&(e={});const t=e.fetchFunc==null?fe().platform.fetch:e.fetchFunc,r=n.map(d=>t(d,e.requestInit,{isBinary:!0})),i=(e.onProgress==null?await Promise.all(r):await Dp(r,e.onProgress,0,.5)).map(d=>d.arrayBuffer());return e.onProgress==null?await Promise.all(i):await Dp(i,e.onProgress,.5,1)}function yC(n,e){var t;const r=e.fetchFunc==null?fe().platform.fetch:e.fetchFunc;let s=0,a;return(t=e.onProgress)===null||t===void 0||t.call(e,0),new ReadableStream({pull:async o=>{for(var i;sUm(o,{requestInit:r}))(n,e,t)}function Hm(n){return async(e,t="",r)=>{const s=e.map(()=>!1),a={},o=r!=null?r.map(()=>!1):[],i=[];if(e.forEach((f,m)=>{let g=0;f.weights.forEach(b=>{const v="quantization"in b?b.quantization.dtype:b.dtype,I=ms[v]*q(b.shape),S=()=>{s[m]=!0,a[m]==null&&(a[m]=[]),a[m].push({manifestEntry:b,groupOffset:g,sizeBytes:I})};r!=null?r.forEach((C,T)=>{C===b.name&&(S(),o[T]=!0)}):S(),i.push(b.name),g+=I})}),!o.every(f=>f)){const f=r.filter((m,g)=>!o[g]);throw new Error(`Could not find weights in manifest with names: ${f.join(", ")}. +Manifest JSON has weights with names: ${i.join(", ")}.`)}const l=s.reduce((f,m,g)=>(m&&f.push(g),f),[]),c=[];l.forEach(f=>{e[f].paths.forEach(m=>{const g=t+(t.endsWith("/")?"":"/")+m;c.push(g)})});const u=await n(c),d={};let p=0;return l.forEach(f=>{const m=e[f].paths.length,g=new Cn(u.slice(p,p+m));a[f].forEach(v=>{const I=g.slice(v.groupOffset,v.groupOffset+v.sizeBytes),S=Wf(I,[v.manifestEntry]);for(const C in S)d[C]=S[C]}),p+=m}),d}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const wC="application/octet-stream",xC="application/json";class Gd{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.weightUrlConverter=t.weightUrlConverter,t.fetchFunc!=null?($(typeof t.fetchFunc=="function",()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=t.fetchFunc):this.fetch=fe().platform.fetch,$(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&$(e.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{},this.loadOptions=t}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");const t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;const r=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],s=Hf(e,r);if(t.body.append("model.json",new Blob([JSON.stringify(s)],{type:xC}),"model.json"),e.weightData!=null){const o=Cn.join(e.weightData);t.body.append("model.weights.bin",new Blob([o],{type:wC}),"model.weights.bin")}const a=await this.fetch(this.path,t);if(a.ok)return{modelArtifactsInfo:po(e),responses:[a]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${a.status}.`)}async loadModelJSON(){const e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch{let o=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?o+=" 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.":o+=" Please make sure the server is serving valid JSON for this request.",new Error(o)}const r=t.modelTopology,s=t.weightsManifest;if(r==null&&s==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return t}async load(){if(this.loadOptions.streamWeights)return this.loadStream();const e=await this.loadModelJSON();return Ed(e,t=>this.loadWeights(t))}async loadStream(){const e=await this.loadModelJSON(),t=await this.getWeightUrls(e.weightsManifest),r=dl(e.weightsManifest),s=()=>yC(t,this.loadOptions);return Object.assign(Object.assign({},e),{weightSpecs:r,getWeightStream:s})}async getWeightUrls(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[r,s]=vC(t),a=this.weightPathPrefix||r,o=[],i=[];for(const l of e)for(const c of l.paths)this.weightUrlConverter!=null?i.push(this.weightUrlConverter(c)):o.push(a+c+s);return this.weightUrlConverter&&o.push(...await Promise.all(i)),o}async loadWeights(e){const t=await this.getWeightUrls(e),r=dl(e),s=await Um(t,this.loadOptions);return[r,s]}}Gd.URL_SCHEME_REGEX=/^https?:\/\//;function vC(n){const e=n.lastIndexOf("/"),t=n.lastIndexOf("?"),r=n.substring(0,e),s=t>e?n.substring(t):"";return[r+"/",s]}function xl(n){return n.match(Gd.URL_SCHEME_REGEX)!=null}const Gm=(n,e)=>{if(typeof fetch>"u"&&(e==null||e.fetchFunc==null))return null;{let t=!0;if(Array.isArray(n)?t=n.every(r=>xl(r)):t=xl(n),t)return jd(n,e)}return null};ct.registerSaveRouter(Gm);ct.registerLoadRouter(Gm);function jd(n,e){return new Gd(n,e)}function SC(n,e){return jd(n,e)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Lu{constructor(e){this.modelArtifacts=e}load(){return this.modelArtifacts}}class jm{constructor(e){this.saveHandler=e}save(e){return this.saveHandler(e)}}class IC{constructor(e){e.load&&(this.load=()=>Promise.resolve(e.load())),e.save&&(this.save=t=>Promise.resolve(e.save(t)))}}function kC(n,e,t,r){const s=arguments;return new IC(qm(...s))}function qm(n,e,t,r){return arguments.length===1?n.modelTopology!=null||n.weightSpecs!=null?new Lu(n):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new Lu({modelTopology:n})):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new Lu({modelTopology:n,weightSpecs:e,weightData:t,trainingConfig:r}))}function _C(n){return new jm(n)}function CC(n){return new jm(n)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var Km=Object.freeze({__proto__:null,CompositeArrayBuffer:Cn,browserFiles:gC,browserHTTPRequest:SC,concatenateArrayBuffers:S0,copyModel:H0,decodeWeights:Wf,decodeWeightsStream:Uf,encodeWeights:g0,fromMemory:kC,fromMemorySync:qm,getLoadHandlers:E0,getModelArtifactsForJSON:Ed,getModelArtifactsForJSONSync:Gf,getModelArtifactsInfoForJSON:po,getSaveHandlers:T0,getWeightSpecs:dl,http:jd,isHTTPScheme:xl,listModels:V0,loadWeights:bC,moveModel:G0,registerLoadRouter:$0,registerSaveRouter:N0,removeModel:U0,weightsLoaderFactory:Hm,withSaveHandler:_C,withSaveHandlerSync:CC});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let Qr,Pp=!1;function NC(n,e=3){if(e>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(n==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let t=!1,r=!1,s=!1,a=!1,o=!1,i=!1;if(n.data instanceof Uint8Array)t=!0;else if(typeof ImageData<"u"&&n instanceof ImageData)r=!0;else if(typeof HTMLVideoElement<"u"&&n instanceof HTMLVideoElement)s=!0;else if(typeof HTMLImageElement<"u"&&n instanceof HTMLImageElement)a=!0;else if(n.getContext!=null)o=!0;else if(typeof ImageBitmap<"u"&&n instanceof ImageBitmap)i=!0;else throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${n.constructor.name}`);if(Ko(al,z.backendName)!=null){const m={pixels:n},g={numChannels:e};return z.runKernel(al,m,g)}const[c,u]=s?[n.videoWidth,n.videoHeight]:[n.width,n.height];let d;if(o)d=n.getContext("2d").getImageData(0,0,c,u).data;else if(r||t)d=n.data;else if(a||s||i){if(Qr==null)if(typeof document>"u")if(typeof OffscreenCanvas<"u"&&typeof OffscreenCanvasRenderingContext2D<"u")Qr=new OffscreenCanvas(1,1).getContext("2d");else throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");else Qr=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});Qr.canvas.width=c,Qr.canvas.height=u,Qr.drawImage(n,0,0,c,u),d=Qr.getImageData(0,0,c,u).data}let p;if(e===4)p=new Int32Array(d);else{const m=c*u;p=new Int32Array(m*e);for(let g=0;g4||e===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${e}`);if(n.dtype!=="float32"&&n.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${n.dtype}. Please use float32 or int32 tensors.`)}async function qd(n,e){let t=N(n,"img","toPixels");if(!(n instanceof dt)){const c=t;t=tt(c,"int32"),c.dispose()}$C(t);const[r,s]=t.shape.slice(0,2),a=t.rank===2?1:t.shape[2],o=await t.data(),i=t.dtype==="float32"?255:1,l=new Uint8ClampedArray(s*r*4);for(let c=0;c1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${f}.`)}else if(t.dtype==="int32"&&(f<0||f>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${f}.`);a===1?(u[0]=f*i,u[1]=f*i,u[2]=f*i):u[p]=f*i}const d=c*4;l[d+0]=Math.round(u[0]),l[d+1]=Math.round(u[1]),l[d+2]=Math.round(u[2]),l[d+3]=Math.round(u[3])}if(e!=null){Pp||Ko(cf,z.backendName)!=null&&(console.warn("tf.browser.toPixels is not efficient to draw tensor on canvas. Please try tf.browser.draw instead."),Pp=!0),e.width=s,e.height=r;const c=e.getContext("2d"),u=new ImageData(l,s,r);c.putImageData(u,0,0)}return t!==n&&t.dispose(),l}const Xm=M({fromPixels_:NC});function Ym(n,e){const t=n.shape.length,r=e.shape.length;if(t<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${t}.`);if(r<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${r}.`);if(e.dtype!=="int32")throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.shape[r-1]>t)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${e.shape[r-1]} vs. ${t}`);if(q(n.shape)===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${n.shape}.`);const s=e.shape,a=s[s.length-1];let o=1;for(let d=0;dd/c),1].slice(0,a);return[l,o,c,u]}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const vl=-2,TC=-1;function EC(n,e,t){const r=n.shape.length;$(r===e.length,()=>`Error in slice${r}D: Length of begin ${e} must match the rank of the array (${r}).`),$(r===t.length,()=>`Error in slice${r}D: Length of size ${t} must match the rank of the array (${r}).`);for(let s=0;s`Error in slice${r}D: begin[${s}] + size[${s}] (${e[s]+t[s]}) would overflow input.shape[${s}] (${n.shape[s]})`)}function Qm(n,e,t){const r=[];for(let s=0;s1){r=s;break}for(let s=r+1;s0||t[s]!==n[s])return!1;return!0}function Jm(n,e){let t=n.length>0?n[n.length-1]:1;for(let r=0;r{$(o!==-1,()=>"slice() does not support negative begin indexing.")});let a;return t==null?a=new Array(s).fill(-1):typeof t=="number"?a=[t,...new Array(s-1).fill(-1)]:t.lengtho>=0?o:($(o===-1,()=>`Negative size values should be exactly -1 but got ${o} for the slice() size at index ${i}.`),n.shape[i]-r[i])),[r,a]}function tg(n,e,t,r,s,a,o,i,l){let c;if(r==null?(c=new Array(e.length),c.fill(1)):c=r,o!=null&&(o&o-1)!==0)throw new Error("Multiple ellipses in slice is not allowed.");let u=!1;const d={dims:c.length,numAddAxisAfterEllipsis:0,begin:e.slice(),end:t.slice(),strides:c.slice(),beginMask:s,endMask:a,ellipsisMask:o,newAxisMask:i,shrinkAxisMask:l};for(let S=0;S0?0:-1,p.strides[S]>0?T:T-1];if(C&&p.strides[S]<=0)throw Error("only stride 1 allowed on non-range indexing.");g=g&&p.strides[S]===1;const B=!!(p.beginMask&1<=T)throw Error(`slice index ${p.begin[S]} of dimension ${S} out of bounds.`)}else p.begin[S]=Fp(p.begin[S],0,p.strides[S],T,O,L),p.end[S]=Fp(p.end[S],1,p.strides[S],T,O,L);const _=p.strides[S]===1&&p.begin[S]===0&&p.end[S]===T;f=f&&_,m=m&&(S===0&&p.strides[S]===1||_)}else f=f&&p.strides[S]===1&&B,m=m&&(S===0&&p.strides[S]===1||B);let A,D=!1;if(p.beginValid&&p.endValid?(A=p.end[S]-p.begin[S],D=!0):C?(A=1,D=!0):B&&T>=0&&(p.strides[S]<0?A=-T:A=T,D=!0),D){let _;A===0||A<0!=p.strides[S]<0?_=0:_=Math.trunc(A/p.strides[S])+(A%p.strides[S]!==0?1:0),b.push(_)}else b.push(-1)}for(let S=0;S=0?v.push(b[C]):C===vl&&v.push(1)}return{finalShapeSparse:v.filter((S,C)=>p.finalShapeGatherIndices[C]!==vl),finalShape:v,isIdentity:f,sliceDim0:m,isSimpleSlice:g,begin:p.begin,end:p.end,strides:p.strides}}function AC(n,e){e.beginMask=0,e.endMask=0,e.shrinkAxisMask=0;let t=0;e.beginValid=n.begin!=null,e.endValid=n.end!=null,e.begin=new Array(e.dims),e.end=new Array(e.dims),e.strides=new Array(e.dims),e.finalShapeGatherIndices=[],e.finalShapeGatherIndicesSparse=[],e.inputShapeGatherIndicesSparse=new Array(e.dims);for(let r=0;r0?a[e]:a[e+1&1];{const o=n<0?r+n:n;return oa[1]?a[1]:o}}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ng(n,e){const t=n[0].length;n.forEach((s,a)=>{$(s.length===t,()=>`Error in concat${t}D: rank of tensors[${a}] must be the same as the rank of the rest (${t})`)}),$(e>=0&&e`Error in concat${t}D: axis must be between 0 and ${t-1}.`);const r=n[0];n.forEach((s,a)=>{for(let o=0;o`Error in concat${t}D: Shape of tensors[${a}] (${s}) does not match the shape of the rest (${r}) along the non-concatenated axis ${a}.`)})}function Ir(n,e){const t=n[0].slice();for(let r=1;r=e*2+1||o%2===1?a.push(o):s.push(o);r.push(...s),r.push(0),r.push(...a)}return r}function xu(n,e,t,r=!0){const s=[];r?s.push(n[0]/t):s.push(n[0]*t);for(let a=1;a/g,Mp=",",Lp="...";function WC(n,e){n=n.replace(/\s/g,"");const t=(n.length-n.replace(BC,"").length)/zu.length;if(t<1)throw new Error("Equations without an arrow are not supported.");if(t>1)throw new Error(`Equation must contain exactly one arrow ("${zu}").`);const[r,s]=n.split(zu);$(r.indexOf(Lp)===-1,()=>`The ellipsis notation ("${Lp}") is not supported yet.`);const a=r.split(Mp),o=a.length;if(e!==o)throw new Error(`Expected ${o} input tensors, received ${e}`);if(o>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");const i=[];for(let p=0;pm.indexOf(f)!==-1))throw new Error(`Output subscripts contain the label ${f} not present in the input subscripts.`);i.indexOf(f)===-1&&i.push(f)}for(let p=0;ps!==-1),{permutationIndices:t,expandDims:r}}function UC(n,e,t){const r=new Array(n);for(let s=0;s`Expected dimension ${r[e[s][o]]} at axis ${o} of input shaped ${JSON.stringify(a)}, but got dimension ${a[o]}`)}}function HC(n,e){const t=n,r=[];let s=0;n.length===0&&t.push(-1),s=n.length+1;for(let o=0;oe===t)}function jC(n,e){const t=[];for(let r=0;r"Number of splits must evenly divide the axis."),r=new Array(e).fill(n.shape[t]/e);else{const s=e.reduce((o,i)=>(i===-1&&(o+=1),o),0);$(s<=1,()=>"There should be only one negative value in split array.");const a=e.indexOf(-1);if(a!==-1){const o=e.reduce((i,l)=>l>0?i+l:i);e[a]=n.shape[t]-o}$(n.shape[t]===e.reduce((o,i)=>o+i),()=>"The sum of sizes must match the size of the axis dimension."),r=e}return r}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function qC(n){return`Received SparseTensor with denseShape[0] = 0 but + indices.shape[0] = ${n}`}function KC(n,e){return`indices(${n}, 0) is invalid: ${e} < 0`}function XC(n,e,t){return`indices(${n}, 0) is invalid: ${e} >= ${t}`}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function YC(n,e){return`only one output dimension may be -1, not both ${n} and ${e}`}function QC(n,e){return`size ${n} must be non-negative, not ${e}`}function ZC(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function JC(n,e){const t=q(n),r=q(e);return`Input to reshape is a SparseTensor with ${t} + dense values, but the requested shape requires a multiple of ${r}. inputShape=${n} outputShape= ${e}`}function eN(n,e){const t=q(n),r=q(e);return`Input to reshape is a tensor with ${t} dense values, but the requested shape has ${r}. inputShape=${n} outputShape=${e}`}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function zp(){return"segment ids must be >= 0"}function tN(){return"segment ids are not increasing"}function nN(n,e){return`Segment id ${n} out of range [0, ${e}), possibly because segmentIds input is not sorted.`}function rN(n,e,t){return`Bad: indices[${n}] == ${e} out of range [0, ${t})`}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function sN(n,e,t){const r=[],s=n.length;for(let a=0;as))throw new Error(`Expect batchDims in the range of [-${s}, ${s}], but got ${r}`);if(r<0&&(r+=s),r>a)throw new Error(`batchDims (${r}) must be less than rank(x) ( + ${a}).`);if(tna(e))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}}function ug(n){return n.map(e=>is(e))}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */lC();/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const aN=fe();aN.registerFlag("KEEP_INTERMEDIATE_TENSORS",()=>!1,n=>{n&&console.warn("Keep intermediate tensors is ON. This will print the values of all intermediate tensors during model inference. Not all models support this mode. For details, check e2e/benchmarks/ model_config.js. This significantly impacts performance.")});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============================================================================= + */var qt;(function(n){n[n.DT_INVALID=0]="DT_INVALID",n[n.DT_FLOAT=1]="DT_FLOAT",n[n.DT_DOUBLE=2]="DT_DOUBLE",n[n.DT_INT32=3]="DT_INT32",n[n.DT_UINT8=4]="DT_UINT8",n[n.DT_INT16=5]="DT_INT16",n[n.DT_INT8=6]="DT_INT8",n[n.DT_STRING=7]="DT_STRING",n[n.DT_COMPLEX64=8]="DT_COMPLEX64",n[n.DT_INT64=9]="DT_INT64",n[n.DT_BOOL=10]="DT_BOOL",n[n.DT_QINT8=11]="DT_QINT8",n[n.DT_QUINT8=12]="DT_QUINT8",n[n.DT_QINT32=13]="DT_QINT32",n[n.DT_BFLOAT16=14]="DT_BFLOAT16",n[n.DT_QINT16=15]="DT_QINT16",n[n.DT_QUINT16=16]="DT_QUINT16",n[n.DT_UINT16=17]="DT_UINT16",n[n.DT_COMPLEX128=18]="DT_COMPLEX128",n[n.DT_HALF=19]="DT_HALF",n[n.DT_RESOURCE=20]="DT_RESOURCE",n[n.DT_VARIANT=21]="DT_VARIANT",n[n.DT_UINT32=22]="DT_UINT32",n[n.DT_UINT64=23]="DT_UINT64",n[n.DT_FLOAT_REF=101]="DT_FLOAT_REF",n[n.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",n[n.DT_INT32_REF=103]="DT_INT32_REF",n[n.DT_UINT8_REF=104]="DT_UINT8_REF",n[n.DT_INT16_REF=105]="DT_INT16_REF",n[n.DT_INT8_REF=106]="DT_INT8_REF",n[n.DT_STRING_REF=107]="DT_STRING_REF",n[n.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",n[n.DT_INT64_REF=109]="DT_INT64_REF",n[n.DT_BOOL_REF=110]="DT_BOOL_REF",n[n.DT_QINT8_REF=111]="DT_QINT8_REF",n[n.DT_QUINT8_REF=112]="DT_QUINT8_REF",n[n.DT_QINT32_REF=113]="DT_QINT32_REF",n[n.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF",n[n.DT_QINT16_REF=115]="DT_QINT16_REF",n[n.DT_QUINT16_REF=116]="DT_QUINT16_REF",n[n.DT_UINT16_REF=117]="DT_UINT16_REF",n[n.DT_COMPLEX128_REF=118]="DT_COMPLEX128_REF",n[n.DT_HALF_REF=119]="DT_HALF_REF",n[n.DT_RESOURCE_REF=120]="DT_RESOURCE_REF",n[n.DT_VARIANT_REF=121]="DT_VARIANT_REF",n[n.DT_UINT32_REF=122]="DT_UINT32_REF",n[n.DT_UINT64_REF=123]="DT_UINT64_REF"})(qt||(qt={}));var Bp;(function(n){(function(e){e[e.LEGACY=0]="LEGACY",e[e.V1=1]="V1",e[e.V2=2]="V2"})(n.CheckpointFormatVersion||(n.CheckpointFormatVersion={}))})(Bp||(Bp={}));/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const oN={};function lg(n){return oN[n]}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function w(n,e,t,r,s){const a=e.inputParams[n];if(a&&a.inputIndexStart!==void 0){const i=a.inputIndexStart,l=a.inputIndexEnd===0?void 0:a.inputIndexEnd===void 0?i+1:a.inputIndexEnd,c=i<0?e.inputNames.length+i:i;if(a.type==="tensor")return St(e.inputNames[c],t,r,s);if(a.type==="tensors"){const p=e.inputs.slice(i,l);return e.inputNames.slice(i,l).filter((m,g)=>{var b;return((b=p[g])===null||b===void 0?void 0:b.op)!=="NoOp"}).map(m=>St(m,t,r,s))}const u=St(e.inputNames[c],t,r,s),d=u.dataSync();return a.type==="number"?d[0]:rl(u.shape,d)}const o=e.attrParams[n];return o&&o.value}function St(n,e,t,r){const[s,a]=Kt(n,t);if(r!=null){const i=r.getHashTableHandleByName(s);if(i!=null)return i}const o=t.currentContextIds.find(i=>!!e[si(s,i)]);return o!==void 0?e[si(s,o)][a]:void 0}function Wp(n,e,t){return e[si(n,t.currentContextId)]}function Qn(n,e){const[t,r,s]=Kt(n,e);return[si(t,e&&e.currentContextId),r,s]}function si(n,e){return e?`${n}-${e}`:n}function Kt(n,e){if(n==="")return["",0,void 0];const t=e!=null&&e.parseNodeNameCache!=null;if(t){const a=e.parseNodeNameCache.get(n);if(a!=null)return a}const r=n.split(":");let s;if(r.length===1)s=[n,0,void 0];else{const a=r[0],o=r.length===3?r[1]:void 0,i=Number(r[r.length-1]);s=[a,i,o]}return t&&e.parseNodeNameCache.set(n,s),s}function Ho(n,e,t){let r=w("pad",n,e,t);if(r==="explicit"){r=w("explicitPaddings",n,e,t);const s=[[0,0],[0,0],[0,0],[0,0]];for(let a=0;a<4;a++)s[a][0]=r[a*2],s[a][1]=r[a*2+1];return s}return r}function Zn(n){return n.kept?n:vr(n)}/** + * @license + * Copyright 2023 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. + * ============================================================================= + */const iN=[{tfOpName:"Add",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddV2",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddN",category:"arithmetic",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"BiasAdd",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"Sub",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"RealDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Div",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"DivNoNan",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mul",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Maximum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Minimum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Pow",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SquaredDifference",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorMod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}];var uN=Object.freeze({__proto__:null,json:iN});/** + * @license + * Copyright 2023 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. + * ============================================================================= + */const lN=[{tfOpName:"Abs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan2",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ceil",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ClipByValue",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"clipValueMin",type:"number"},{start:2,name:"clipValueMax",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Complex",category:"basic_math",inputs:[{start:0,name:"real",type:"tensor"},{start:1,name:"imag",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ComplexAbs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Elu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Exp",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Floor",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Imag",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Neg",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Real",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Prelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"alpha",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu6",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Selu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sigmoid",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Rsqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Square",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sign",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Round",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Expm1",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log1p",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Reciprocal",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Softplus",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Erf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LeakyRelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"alpha",name:"alpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsNan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsFinite",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsInf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}];var cN=Object.freeze({__proto__:null,json:lN});/** + * @license + * Copyright 2023 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. + * ============================================================================= + */const dN=[{tfOpName:"EmptyTensorList",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"maxNumElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"LoopCond",category:"control",inputs:[{start:0,name:"pred",type:"tensor"}]},{tfOpName:"Switch",category:"control",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"pred",type:"tensor"}]},{tfOpName:"Merge",category:"control",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"Enter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"frame_name",name:"frameName",type:"string"},{tfName:"is_constant",name:"isConstant",type:"bool"}]},{tfOpName:"Exit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NextIteration",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayV3",category:"control",inputs:[{start:0,name:"size",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"dynamic_size",name:"dynamicSize",type:"bool"},{tfName:"clear_after_read",name:"clearAfterRead",type:"bool"},{tfName:"identical_element_shapes",name:"identicalElementShapes",type:"bool"},{tfName:"tensor_array_name",name:"name",type:"string"}]},{tfOpName:"TensorArrayWriteV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayReadV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayGatherV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"}]},{tfOpName:"TensorArrayScatterV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArrayConcatV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape_except0",name:"elementShapeExcept0",type:"shape",notSupported:!0}]},{tfOpName:"TensorArraySplitV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"tensor",type:"tensor"},{start:2,name:"lengths",type:"number[]"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArraySizeV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}]},{tfOpName:"TensorArrayCloseV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"}]},{tfOpName:"StatelessIf",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"If",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"StatelessWhile",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"While",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"TensorListScatter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListScatterV2",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"},{start:3,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGather",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListSetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListReserve",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListFromTensor",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListStack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"},{tfName:"num_elements",name:"numElements",type:"dtype"}]},{tfOpName:"TensorListSplit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"},{start:2,name:"lengths",type:"number[]"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcat",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcatV2",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPopBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPushBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListLength",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}]},{tfOpName:"TensorListResize",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"size",type:"number"}]}];var pN=Object.freeze({__proto__:null,json:dN});/** + * @license + * Copyright 2023 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. + * ============================================================================= + */const hN=[{tfOpName:"AvgPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[],notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPoolWithArgmax",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"include_batch_in_index",name:"includeBatchInIndex",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AvgPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Conv1D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"stride",name:"stride",type:"number"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NWC"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"dilation",name:"dilation",type:"number",defaultValue:1}]},{tfOpName:"Conv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"useCudnnOnGpu",name:"useCudnnOnGpu",type:"bool"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"_FusedConv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"use_cudnn_on_gpu",name:"useCudnnOnGpu",type:"bool",defaultValue:!0},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number",defaultValue:.2}]},{tfOpName:"Conv2DBackpropInput",category:"convolution",inputs:[{start:2,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:0,name:"outputShape",type:"number[]"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]",notSupported:!0}]},{tfOpName:"DepthwiseConv2d",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"DepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"FusedDepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]}]},{tfOpName:"Conv3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"Dilation2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"rates",name:"dilations",type:"number[]"},{tfName:"padding",name:"pad",type:"string"}]}];var fN=Object.freeze({__proto__:null,json:hN});/** + * @license + * Copyright 2023 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. + * ============================================================================= + */const mN=[{tfOpName:"Fill",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"},{start:1,name:"value",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"LinSpace",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"num",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"OneHot",category:"creation",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"depth",type:"number"},{start:2,name:"onValue",type:"number",defaultValue:1},{start:3,name:"offValue",type:"number",defaultValue:0}],attrs:[{tfName:"axis",name:"axis",type:"number",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Ones",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"OnesLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"RandomStandardNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"RandomUniform",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number",defaultValue:0},{tfName:"maxval",name:"maxval",type:"number",defaultValue:1},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"RandomUniformInt",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number"},{tfName:"maxval",name:"maxval",type:"number"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Range",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"step",type:"number",defaultValue:0}],attrs:[{tfName:"Tidx",name:"dtype",type:"dtype"}]},{tfOpName:"TruncatedNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"means",name:"mean",type:"number",defaultValue:0},{tfName:"stddev",name:"stdDev",type:"number",defaultValue:1},{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Zeros",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"ZerosLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Multinomial",category:"creation",inputs:[{start:0,name:"logits",type:"tensor"},{start:1,name:"numSamples",type:"number"}],attrs:[{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number"},{tfName:"T",name:"dtype",type:"dtype"},{tfName:"output_dtype",name:"output_dtype",type:"dtype"}]}];var gN=Object.freeze({__proto__:null,json:mN});/** + * @license + * Copyright 2023 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. + * ============================================================================= + */const yN=[{tfOpName:"NonMaxSuppressionV2",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV3",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV4",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"T_threshold",name:"threshold",type:"dtype",notSupported:!0},{tfName:"pad_to_max_output_size",name:"padToMaxOutputSize",type:"bool"}]},{tfOpName:"NonMaxSuppressionV5",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"},{start:5,name:"softNmsSigma",type:"number"}]},{tfOpName:"Where",category:"dynamic",inputs:[{start:0,name:"condition",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ListDiff",category:"dynamic",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}];var bN=Object.freeze({__proto__:null,json:yN});/** + * @license + * Copyright 2023 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. + * ============================================================================= + */const wN=[{tfOpName:"LowerBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{tfOpName:"TopKV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"k",type:"number"}],attrs:[{tfName:"sorted",name:"sorted",type:"bool"}]},{tfOpName:"UpperBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{tfOpName:"Unique",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"UniqueV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]}];var xN=Object.freeze({__proto__:null,json:wN});/** + * @license + * Copyright 2023 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. + * ============================================================================= + */const vN=[{tfOpName:"PlaceholderWithDefault",category:"graph",inputs:[{start:0,name:"default",type:"tensor"}],attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Placeholder",category:"graph",attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Const",category:"graph"},{tfOpName:"Identity",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IdentityN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Snapshot",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Rank",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Size",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Shape",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"ShapeN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Print",category:"graph",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"data",type:"tensors"}],attrs:[{tfName:"message",name:"message",type:"string"},{tfName:"first_n",name:"firstN",type:"number",notSupported:!0},{tfName:"summarize",name:"summarize",type:"number",defaultValue:3}]},{tfOpName:"NoOp",category:"graph",inputs:[]},{tfOpName:"StopGradient",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"FakeQuantWithMinMaxVars",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"min",name:"min",type:"number"},{tfName:"max",name:"max",type:"number"}]}];var SN=Object.freeze({__proto__:null,json:vN});/** + * @license + * Copyright 2023 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. + * ============================================================================= + */const IN=[{tfOpName:"HashTable",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"HashTableV2",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"LookupTableImport",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableImportV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFind",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFindV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableSize",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"LookupTableSizeV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"InitializeTable",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}]},{tfOpName:"InitializeTableV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}]}];var kN=Object.freeze({__proto__:null,json:IN});/** + * @license + * Copyright 2023 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. + * ============================================================================= + */const _N=[{tfOpName:"ResizeBilinear",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ResizeNearestNeighbor",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"CropAndResize",category:"image",inputs:[{start:0,name:"image",type:"tensor"},{start:1,name:"boxes",type:"tensor"},{start:2,name:"boxInd",type:"tensor"},{start:3,name:"cropSize",type:"number[]"}],attrs:[{tfName:"method",name:"method",type:"string"},{tfName:"extrapolation_value",name:"extrapolationValue",type:"number"}]},{tfOpName:"ImageProjectiveTransformV3",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"transforms",type:"tensor"},{start:2,name:"outputShape",type:"number[]"},{start:3,name:"fillValue",type:"number"}],attrs:[{tfName:"interpolation",name:"interpolation",type:"string"},{tfName:"fill_mode",name:"fillMode",type:"string"}]}];var CN=Object.freeze({__proto__:null,json:_N});/** + * @license + * Copyright 2023 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. + * ============================================================================= + */const NN=[{tfOpName:"Equal",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NotEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Greater",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"GreaterEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Less",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LessEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalAnd",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalNot",category:"logical",inputs:[{start:0,name:"a",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalOr",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Select",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SelectV2",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BitwiseAnd",category:"logical",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}]}];var $N=Object.freeze({__proto__:null,json:NN});/** + * @license + * Copyright 2023 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. + * ============================================================================= + */const TN=[{tfOpName:"_FusedMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMulV2",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",category:"matrices",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"perm",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Einsum",category:"matrices",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"equation",name:"equation",type:"string"},{tfName:"N",name:"n",type:"number",defaultValue:2},{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"MatrixBandPart",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"numLower",type:"tensor"},{start:1,name:"numUpper",type:"tensor"}]}];var EN=Object.freeze({__proto__:null,json:TN});/** + * @license + * Copyright 2023 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. + * ============================================================================= + */const AN=[{tfOpName:"EuclideanNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",defaultValue:!1}]},{tfOpName:"FusedBatchNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV2",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV3",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"LRN",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"depth_radius",name:"radius",type:"number",defaultValue:5},{tfName:"bias",name:"bias",type:"number",defaultValue:1},{tfName:"alpha",name:"alpha",type:"number",defaultValue:1},{tfName:"beta",name:"beta",type:"number",defaultValue:.5}]},{tfOpName:"Softmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"LogSoftmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]}];var RN=Object.freeze({__proto__:null,json:AN});/** + * @license + * Copyright 2023 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. + * ============================================================================= + */const DN=[{tfOpName:"Bincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}]},{tfOpName:"DenseBincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}],attrs:[{tfName:"binary_output",name:"binaryOutput",type:"bool"}]},{tfOpName:"Max",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Mean",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Min",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Sum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"All",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Any",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"ArgMin",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Prod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cumprod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]},{tfOpName:"Cumsum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]}];var PN=Object.freeze({__proto__:null,json:DN});/** + * @license + * Copyright 2023 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. + * ============================================================================= + */const FN=[{tfOpName:"ConcatV2",category:"slice_join",inputs:[{start:0,end:-1,name:"tensors",type:"tensors"},{start:-1,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"Concat",category:"slice_join",inputs:[{start:1,end:0,name:"tensors",type:"tensors"},{start:0,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"GatherV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"axis",type:"number",defaultValue:0}],attrs:[{tfName:"batch_dims",name:"batchDims",type:"number",defaultValue:0}]},{tfOpName:"Gather",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",notSupported:!0}]},{tfOpName:"Reverse",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"dims",type:"bool[]"}]},{tfOpName:"ReverseV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}]},{tfOpName:"Slice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"size",type:"number[]"}]},{tfOpName:"StridedSlice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"end",type:"number[]"},{start:3,name:"strides",type:"number[]"}],attrs:[{tfName:"begin_mask",name:"beginMask",type:"number",defaultValue:0},{tfName:"end_mask",name:"endMask",type:"number",defaultValue:0},{tfName:"new_axis_mask",name:"newAxisMask",type:"number",defaultValue:0},{tfName:"ellipsis_mask",name:"ellipsisMask",type:"number",defaultValue:0},{tfName:"shrink_axis_mask",name:"shrinkAxisMask",type:"number",defaultValue:0}]},{tfOpName:"Pack",category:"slice_join",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Unpack",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"num",name:"num",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Tile",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"reps",type:"number[]"}]},{tfOpName:"Split",category:"slice_join",inputs:[{start:0,name:"axis",type:"number",defaultValue:0},{start:1,name:"x",type:"tensor"}],attrs:[{tfName:"num_split",name:"numOrSizeSplits",type:"number",defaultValue:1}]},{tfOpName:"SplitV",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"numOrSizeSplits",type:"number[]"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"ScatterNd",category:"slice_join",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"shape",type:"number[]"}]},{tfOpName:"GatherNd",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}]},{tfOpName:"SparseToDense",category:"slice_join",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!1,notSupported:!0}]},{tfOpName:"TensorScatterUpdate",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"values",type:"tensor"}]}];var ON=Object.freeze({__proto__:null,json:FN});/** + * @license + * Copyright 2023 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. + * ============================================================================= + */const MN=[{tfOpName:"SparseFillEmptyRows",category:"sparse",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"denseShape",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}]},{tfOpName:"SparseReshape",category:"sparse",inputs:[{start:0,name:"inputIndices",type:"tensor"},{start:1,name:"inputShape",type:"tensor"},{start:2,name:"newShape",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SparseSegmentMean",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]},{tfOpName:"SparseSegmentSum",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]}];var LN=Object.freeze({__proto__:null,json:MN});/** + * @license + * Copyright 2023 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. + * ============================================================================= + */const zN=[{tfOpName:"FFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"RFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]},{tfOpName:"IRFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]}];var BN=Object.freeze({__proto__:null,json:zN});/** + * @license + * Copyright 2023 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. + * ============================================================================= + */const WN=[{tfOpName:"StaticRegexReplace",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"pattern",name:"pattern",type:"string"},{tfName:"rewrite",name:"rewrite",type:"string"},{tfName:"replace_global",name:"replaceGlobal",type:"bool"}]},{tfOpName:"StringNGrams",category:"string",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"dataSplits",type:"tensor"}],attrs:[{tfName:"separator",name:"separator",type:"string"},{tfName:"ngram_widths",name:"nGramWidths",type:"number[]"},{tfName:"left_pad",name:"leftPad",type:"string"},{tfName:"right_pad",name:"rightPad",type:"string"},{tfName:"pad_width",name:"padWidth",type:"number"},{tfName:"preserve_short_sequences",name:"preserveShortSequences",type:"bool"}],outputs:["ngrams","ngrams_splits"]},{tfOpName:"StringSplit",category:"string",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"delimiter",type:"tensor"}],attrs:[{tfName:"skip_empty",name:"skipEmpty",type:"bool"}],outputs:["indices","values","shape"]},{tfOpName:"StringToHashBucketFast",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"num_buckets",name:"numBuckets",type:"number"}]}];var VN=Object.freeze({__proto__:null,json:WN});/** + * @license + * Copyright 2023 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. + * ============================================================================= + */const UN=[{tfOpName:"Cast",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"SrcT",name:"sdtype",type:"dtype",notSupported:!0},{tfName:"DstT",name:"dtype",type:"dtype"}]},{tfOpName:"ExpandDims",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"MirrorPad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"mode",name:"mode",type:"string"}]},{tfOpName:"Pad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"constant_value",name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"PadV2",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"},{start:2,name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"Reshape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"EnsureShape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"Squeeze",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"axis",tfDeprecatedName:"squeeze_dims",name:"axis",type:"number[]"}]},{tfOpName:"SpaceToBatchND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"paddings",type:"number[]"}]},{tfOpName:"BatchToSpaceND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"crops",type:"number[]"}]},{tfOpName:"DepthToSpace",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"block_size",name:"blockSize",type:"number"},{tfName:"data_format",name:"dataFormat",type:"string"}]},{tfOpName:"BroadcastTo",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}],attrs:[]},{tfOpName:"BroadcastArgs",category:"transformation",inputs:[{start:0,name:"s0",type:"tensor"},{start:1,name:"s1",type:"tensor"}],attrs:[]}];var HN=Object.freeze({__proto__:null,json:UN});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Vp{static get Instance(){return this._instance||(this._instance=new this)}constructor(){const e=[uN,cN,pN,fN,gN,bN,xN,SN,kN,CN,$N,EN,RN,PN,ON,LN,BN,VN,HN],t=[].concat(...e.map(r=>r.json));this.opMappers=t.reduce((r,s)=>(r[s.tfOpName]=s,r),{})}transformGraph(e,t={}){const r=e.node,s=[],a=[],o=[],i=r.reduce((g,b)=>(g[b.name]=this.mapNode(b),b.op.startsWith("Placeholder")?s.push(g[b.name]):b.op==="Const"?a.push(g[b.name]):(b.input==null||b.input.length===0)&&o.push(g[b.name]),g),{});let l=[];const c=[];let u={},d={};t!=null&&(u=this.mapSignatureEntries(t.inputs),d=this.mapSignatureEntries(t.outputs));const p=Object.keys(i);p.forEach(g=>{const b=i[g];b.inputNames.forEach((v,I)=>{const[S,,C]=Qn(v),T=i[S];if(T.outputs!=null){const O=T.outputs.indexOf(C);if(O!==-1){const L=`${S}:${O}`;b.inputNames[I]=L}}b.inputs.push(T),T.children.push(b)})}),Object.keys(d).length===0?p.forEach(g=>{const b=i[g];b.children.length===0&&c.push(b)}):Object.keys(d).forEach(g=>{const[b]=Qn(g),v=i[b];v!=null&&(v.signatureKey=d[g],c.push(v))}),Object.keys(u).length>0?Object.keys(u).forEach(g=>{const[b]=Qn(g),v=i[b];v&&(v.signatureKey=u[g],l.push(v))}):l=s;let f={};e.library!=null&&e.library.function!=null&&(f=e.library.function.reduce((g,b)=>(g[b.signature.name]=this.mapFunction(b),g),{}));const m={nodes:i,inputs:l,outputs:c,weights:a,placeholders:s,signature:t,functions:f};return o.length>0&&(m.initNodes=o),m}mapSignatureEntries(e){return Object.keys(e||{}).reduce((t,r)=>(t[e[r].name]=r,t),{})}mapNode(e){const t=lg(e.op)||this.opMappers[e.op]||{};e.attr==null&&(e.attr={});const r={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map(s=>s.startsWith("^")?s.slice(1):s),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr,outputs:t.outputs};return t.inputs!=null&&(r.inputParams=t.inputs.reduce((s,a)=>(s[a.name]={type:a.type,inputIndexStart:a.start,inputIndexEnd:a.end},s),{})),t.attrs!=null&&(r.attrParams=t.attrs.reduce((s,a)=>{const o=a.type;let i;switch(a.type){case"string":i=Sl(e.attr,a.tfName,a.defaultValue),i===void 0&&a.tfDeprecatedName&&(i=Sl(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"string[]":i=Tl(e.attr,a.tfName,a.defaultValue),i===void 0&&a.tfDeprecatedName&&(i=Tl(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"number":i=kl(e.attr,a.tfName,a.defaultValue||0),i===void 0&&a.tfDeprecatedName&&(i=kl(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"number[]":i=$l(e.attr,a.tfName,a.defaultValue),i===void 0&&a.tfDeprecatedName&&(i=$l(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"bool":i=Il(e.attr,a.tfName,a.defaultValue),i===void 0&&a.tfDeprecatedName&&(i=Il(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"bool[]":i=Al(e.attr,a.tfName,a.defaultValue),i===void 0&&a.tfDeprecatedName&&(i=Al(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"shape":i=Nl(e.attr,a.tfName,a.defaultValue),i===void 0&&a.tfDeprecatedName&&(i=Nl(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"shape[]":i=El(e.attr,a.tfName,a.defaultValue),i===void 0&&a.tfDeprecatedName&&(i=El(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"dtype":i=_l(e.attr,a.tfName,a.defaultValue),i===void 0&&a.tfDeprecatedName&&(i=_l(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"dtype[]":i=Cl(e.attr,a.tfName,a.defaultValue),i===void 0&&a.tfDeprecatedName&&(i=Cl(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"func":i=Up(e.attr,a.tfName,a.defaultValue),i===void 0&&a.tfDeprecatedName&&(i=Up(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${a.type} for op: ${e.op}`)}return s[a.name]={value:i,type:o},s},{})),r}mapFunction(e){const t=e.nodeDef,r=[],s=[];let a={};t!=null&&(a=t.reduce((d,p)=>(d[p.name]=this.mapNode(p),p.op==="Const"&&s.push(d[p.name]),d),{}));const o=[],i=[];e.signature.inputArg.forEach(d=>{const[p]=Qn(d.name),f={name:p,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:Kd(d.type),type:"dtype"}},children:[]};f.signatureKey=d.name,o.push(f),a[p]=f}),Object.keys(a).forEach(d=>{const p=a[d];p.inputNames.forEach((f,m)=>{const[g,,b]=Qn(f),v=a[g];if(v.outputs!=null){const I=v.outputs.indexOf(b);if(I!==-1){const S=`${g}:${I}`;p.inputNames[m]=S}}p.inputs.push(v),v.children.push(p)})});const c=e.ret;e.signature.outputArg.forEach(d=>{const[p,f]=Qn(c[d.name]),m=a[p];m!=null&&(m.defaultOutput=f,i.push(m))});const u=this.mapArgsToSignature(e);return{nodes:a,inputs:o,outputs:i,weights:s,placeholders:r,signature:u}}mapArgsToSignature(e){return{methodName:e.signature.name,inputs:e.signature.inputArg.reduce((t,r)=>(t[r.name]=this.mapArgToTensorInfo(r),t),{}),outputs:e.signature.outputArg.reduce((t,r)=>(t[r.name]=this.mapArgToTensorInfo(r,e.ret),t),{})}}mapArgToTensorInfo(e,t){let r=e.name;return t!=null&&(r=t[r]),{name:r,dtype:e.type}}}function GN(n){const e=fe().global;if(typeof e.atob<"u")return e.atob(n);if(typeof Buffer<"u")return new Buffer(n,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}function cg(n,e){const t=Array.isArray(n)?String.fromCharCode.apply(null,n):GN(n);return e?t:t.toLowerCase()}function Sl(n,e,t,r=!1){const s=n[e];return s!=null?cg(s.s,r):t}function Il(n,e,t){const r=n[e];return r?r.b:t}function kl(n,e,t){const r=n[e]||{},s=r.i!=null?r.i:r.f!=null?r.f:t;return typeof s=="number"?s:parseInt(s,10)}function Kd(n){switch(typeof n=="string"&&(n=qt[n]),n){case qt.DT_FLOAT:case qt.DT_HALF:return"float32";case qt.DT_INT32:case qt.DT_INT64:case qt.DT_INT8:case qt.DT_UINT8:return"int32";case qt.DT_BOOL:return"bool";case qt.DT_DOUBLE:return"float32";case qt.DT_STRING:return"string";case qt.DT_COMPLEX64:case qt.DT_COMPLEX128:return"complex64";default:return null}}function Up(n,e,t){const r=n[e];return r&&r.func?r.func.name:t}function _l(n,e,t){const r=n[e];return r&&r.type?Kd(r.type):t}function Cl(n,e,t){const r=n[e];return r&&r.list&&r.list.type?r.list.type.map(s=>Kd(s)):t}function dg(n){if(!n.unknownRank)return n.dim!=null?n.dim.map(e=>typeof e.size=="number"?e.size:parseInt(e.size,10)):[]}function Nl(n,e,t){const r=n[e];return r&&r.shape?dg(r.shape):t}function $l(n,e,t){const r=n[e];return r?((r.list.f&&r.list.f.length?r.list.f:r.list.i)||[]).map(s=>typeof s=="number"?s:parseInt(s,10)):t}function Tl(n,e,t,r=!1){const s=n[e];return s&&s.list&&s.list.s?s.list.s.map(a=>cg(a,r)):t}function El(n,e,t){const r=n[e];return r&&r.list&&r.list.shape?r.list.shape.map(s=>dg(s)):t}function Al(n,e,t){const r=n[e];return r&&r.list&&r.list.b?r.list.b:t}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class jN{constructor(e,t,r){this.node=e,this.tensorMap=t,this.context=r,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map(s=>this.getInput(s)),e.rawAttrs!=null&&(this.attrs=Object.keys(e.rawAttrs).reduce((s,a)=>(s[a]=this.getAttr(a),s),{}))}getInput(e){return St(e,this.tensorMap,this.context)}getAttr(e,t){const r=this.node.rawAttrs[e];if(r.tensor!=null)return St(e,this.tensorMap,this.context);if(r.i!=null||r.f!=null)return kl(this.node.rawAttrs,e,t);if(r.s!=null)return Sl(this.node.rawAttrs,e,t);if(r.b!=null)return Il(this.node.rawAttrs,e,t);if(r.shape!=null)return Nl(this.node.rawAttrs,e,t);if(r.type!=null)return _l(this.node.rawAttrs,e,t);if(r.list!=null){if(r.list.i!=null||r.list.f!=null)return $l(this.node.rawAttrs,e,t);if(r.list.s!=null)return Tl(this.node.rawAttrs,e,t);if(r.list.shape!=null)return El(this.node.rawAttrs,e,t);if(r.list.b!=null)return Al(this.node.rawAttrs,e,t);if(r.list.type!=null)return Cl(this.node.rawAttrs,e,t)}return t}}/** + * @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 It=Object.freeze({__proto__:null,OP_SCOPE_SUFFIX:zf,abs:Jt,acos:s1,acosh:o1,add:he,addN:u1,all:c1,any:p1,argMax:tm,argMin:m1,asin:y1,asinh:w1,atan:v1,atan2:I1,atanh:_1,avgPool:rm,avgPool3d:D1,basicLSTMCell:B1,batchNorm:du,batchNorm2d:G1,batchNorm3d:q1,batchNorm4d:X1,batchToSpaceND:sm,bincount:am,bitwiseAnd:Z1,booleanMaskAsync:BI,broadcastArgs:e2,broadcastTo:Oo,buffer:ut,cast:tt,ceil:r2,clipByValue:om,clone:vr,complex:Cr,concat:wt,concat1d:o2,concat2d:u2,concat3d:c2,concat4d:p2,conv1d:m2,conv2d:pu,conv2dTranspose:b2,conv3d:x2,conv3dTranspose:k2,cos:C2,cosh:$2,cosineWindow:zd,cumprod:E2,cumsum:R2,denseBincount:P2,depthToSpace:O2,depthwiseConv2d:Ad,diag:z2,dilation2d:W2,div:Re,divNoNan:q2,dot:X2,dropout:JI,einsum:Ys,elu:lm,enclosingPowerOfTwo:Mm,ensureShape:J2,equal:um,erf:tx,euclideanNorm:dx,exp:rr,expandDims:en,expm1:mx,eye:pm,fft:Md,fill:ho,floor:hm,floorDiv:em,fused:fk,gather:fm,gatherND:YI,greater:mu,greaterEqual:mm,ifft:ni,imag:gu,image:ls,inTopKAsync:tk,irfft:Am,isFinite:kx,isInf:Cx,isNaN:$x,leakyRelu:gm,less:bl,lessEqual:Rd,linalg:K_,linspace:Rx,localResponseNormalization:Px,log:to,log1p:ym,logSigmoid:Wx,logSoftmax:Hx,logSumExp:wm,logicalAnd:ei,logicalNot:xm,logicalOr:vm,logicalXor:Yx,losses:X_,lowerBound:Zx,matMul:Ze,max:ea,maxPool:Sm,maxPool3d:tv,maxPoolWithArgmax:rv,maximum:Im,mean:ti,meshgrid:ov,min:yl,minimum:no,mirrorPad:km,mod:cv,moments:pv,movingAverage:UI,mul:Z,multiRNNCell:fv,multinomial:gv,neg:Bn,norm:fu,notEqual:_m,oneHot:wv,ones:as,onesLike:vv,op:M,outerProduct:Iv,pad:Tr,pad1d:Cv,pad2d:$v,pad3d:Ev,pad4d:Rv,pool:Mv,pow:eo,prelu:Nm,print:Jf,prod:Bv,raggedGather:Vv,raggedRange:Hv,raggedTensorToTensor:jv,rand:Kv,randomGamma:mS,randomNormal:$m,randomStandardNormal:bS,randomUniform:Od,randomUniformInt:vS,range:ro,real:so,reciprocal:kS,relu:yu,relu6:Tm,reshape:K,reverse:bs,reverse1d:TS,reverse2d:AS,reverse3d:DS,reverse4d:FS,rfft:Ld,round:Em,rsqrt:LS,scalar:De,scatterND:GI,searchSorted:Dd,selu:BS,separableConv2d:VS,setdiff1dAsync:HS,sigmoid:er,sign:jS,signal:q_,sin:KS,sinh:YS,slice:Ae,slice1d:ZS,slice2d:eI,slice3d:nI,slice4d:sI,softmax:oI,softplus:bm,spaceToBatchND:Cm,sparse:Y_,sparseToDense:KI,spectral:j_,split:ao,sqrt:nr,square:hn,squaredDifference:Rm,squeeze:Qe,stack:ar,step:Dm,stridedSlice:yI,string:Q_,sub:$e,sum:at,tan:wI,tanh:gl,tensor:_n,tensor1d:Nt,tensor2d:fn,tensor3d:Pm,tensor4d:xI,tensor5d:vI,tensor6d:SI,tensorScatterUpdate:_I,tile:Ua,topk:NI,transpose:wl,truncatedNormal:TI,unique:AI,unsortedSegmentSum:DI,unstack:Is,upperBound:FI,variable:OI,where:Sr,whereAsync:Om,zeros:$r,zerosLike:tn});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const qN=(n,e,t,r=It)=>{switch(n.op){case"BiasAdd":case"AddV2":case"Add":return[r.add(w("a",n,e,t),w("b",n,e,t))];case"AddN":return[r.addN(w("tensors",n,e,t))];case"FloorMod":case"Mod":return[r.mod(w("a",n,e,t),w("b",n,e,t))];case"Mul":return[r.mul(w("a",n,e,t),w("b",n,e,t))];case"RealDiv":case"Div":return[r.div(w("a",n,e,t),w("b",n,e,t))];case"DivNoNan":return[r.divNoNan(w("a",n,e,t),w("b",n,e,t))];case"FloorDiv":return[r.floorDiv(w("a",n,e,t),w("b",n,e,t))];case"Sub":return[r.sub(w("a",n,e,t),w("b",n,e,t))];case"Minimum":return[r.minimum(w("a",n,e,t),w("b",n,e,t))];case"Maximum":return[r.maximum(w("a",n,e,t),w("b",n,e,t))];case"Pow":return[r.pow(w("a",n,e,t),w("b",n,e,t))];case"SquaredDifference":return[r.squaredDifference(w("a",n,e,t),w("b",n,e,t))];default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const KN=(n,e,t,r=It)=>{switch(n.op){case"Abs":case"ComplexAbs":return[r.abs(w("x",n,e,t))];case"Acos":return[r.acos(w("x",n,e,t))];case"Acosh":return[r.acosh(w("x",n,e,t))];case"Asin":return[r.asin(w("x",n,e,t))];case"Asinh":return[r.asinh(w("x",n,e,t))];case"Atan":return[r.atan(w("x",n,e,t))];case"Atan2":return[r.atan2(w("x",n,e,t),w("y",n,e,t))];case"Atanh":return[r.atanh(w("x",n,e,t))];case"Ceil":return[r.ceil(w("x",n,e,t))];case"Complex":return[r.complex(w("real",n,e,t),w("imag",n,e,t))];case"Cos":return[r.cos(w("x",n,e,t))];case"Cosh":return[r.cosh(w("x",n,e,t))];case"Elu":return[r.elu(w("x",n,e,t))];case"Erf":return[r.erf(w("x",n,e,t))];case"Exp":return[r.exp(w("x",n,e,t))];case"Expm1":return[r.expm1(w("x",n,e,t))];case"Floor":return[r.floor(w("x",n,e,t))];case"Log":return[r.log(w("x",n,e,t))];case"Log1p":return[r.log1p(w("x",n,e,t))];case"Imag":return[r.imag(w("x",n,e,t))];case"Neg":return[r.neg(w("x",n,e,t))];case"Reciprocal":return[r.reciprocal(w("x",n,e,t))];case"Real":return[r.real(w("x",n,e,t))];case"Relu":return[r.relu(w("x",n,e,t))];case"Round":return[r.round(w("x",n,e,t))];case"Selu":return[r.selu(w("x",n,e,t))];case"Sigmoid":return[r.sigmoid(w("x",n,e,t))];case"Sin":return[r.sin(w("x",n,e,t))];case"Sign":return[r.sign(w("x",n,e,t))];case"Sinh":return[r.sinh(w("x",n,e,t))];case"Softplus":return[r.softplus(w("x",n,e,t))];case"Sqrt":return[r.sqrt(w("x",n,e,t))];case"Square":return[r.square(w("x",n,e,t))];case"Tanh":return[r.tanh(w("x",n,e,t))];case"Tan":return[r.tan(w("x",n,e,t))];case"ClipByValue":return[r.clipByValue(w("x",n,e,t),w("clipValueMin",n,e,t),w("clipValueMax",n,e,t))];case"Relu6":return[r.relu6(w("x",n,e,t))];case"Rsqrt":return[r.rsqrt(St(n.inputNames[0],e,t))];case"LeakyRelu":return[r.leakyRelu(w("x",n,e,t),w("alpha",n,e,t))];case"Prelu":return[r.prelu(w("x",n,e,t),w("alpha",n,e,t))];case"IsNan":return[r.isNaN(St(n.inputNames[0],e,t))];case"IsInf":return[r.isInf(St(n.inputNames[0],e,t))];case"IsFinite":return[r.isFinite(St(n.inputNames[0],e,t))];default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @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. + * ============================================================================= + */function pn(n,e,t=""){if(!(typeof n=="number"||typeof e=="number")){$(n.length===e.length,()=>t+` Shapes ${n} and ${e} must match`);for(let r=0;rt+` Shapes ${n} and ${e} must match`)}}}function Hp(n){return!(typeof n=="number"||n.some(e=>e<0))}function Oa(n,e,t){let r=Rl(n,t);const s=!Hp(r);if(s&&e.length===0)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${r}`);if(s&&e.forEach(a=>{r=Rl(a.shape,r)}),!Hp(r))throw new Error(`Non-fully-defined elementShape: ${r}`);return r}function Rl(n,e){if(typeof n=="number")return e;if(typeof e=="number")return n;if(n.length!==e.length)throw new Error(`Incompatible ranks during merge: ${n} vs. ${e}`);const t=[];for(let r=0;r=0&&a>=0&&s!==a)throw new Error(`Incompatible shape during merge: ${n} vs. ${e}`);t[r]=s>=0?s:a}return t}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class XN{constructor(e,t,r,s,a,o,i){this.name=e,this.dtype=t,this.maxSize=r,this.elementShape=s,this.identicalElementShapes=a,this.dynamicSize=o,this.clearAfterRead=i,this.tensors=[],this.closed_=!1,this.idTensor=De(0),zn(this.idTensor)}get id(){return this.idTensor.id}get closed(){return this.closed_}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.tensor.id))&&t.tensor.dispose()}),this.tensors=[],this.closed_=!0,this.idTensor.dispose()}size(){return this.tensors.length}read(e){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||e>=this.size())throw new Error(`Tried to read from index ${e}, but array size is: ${this.size()}`);const t=this.tensors[e];if(t.cleared)throw new Error(`TensorArray ${this.name}: Could not read index ${e} twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).`);return this.clearAfterRead&&(t.cleared=!0),t.read=!0,t.tensor}readMany(e){return e.map(t=>this.read(t))}write(e,t){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||!this.dynamicSize&&e>=this.maxSize)throw new Error(`Tried to write to index ${e}, but array is not resizeable and size is: ${this.maxSize}`);const r=this.tensors[e]||{};if(t.dtype!==this.dtype)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, + because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`);if(this.size()===0&&(this.elementShape==null||this.elementShape.length===0)&&(this.elementShape=t.shape),pn(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),r.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(r.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);r.tensor=t,zn(t),r.written=!0,this.tensors[e]=r}writeMany(e,t){if(e.length!==t.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);e.forEach((r,s)=>this.write(r,t[s]))}gather(e,t){if(t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let s=0;s=this.maxSize)throw new Error(`Max index must be < array size (${r} vs. ${this.maxSize})`);this.writeMany(e,Is(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);let r=0;const s=e.map(l=>(r+=l,r));if(r!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to + tensor.shape[0], but sum of lengths is + ${r}, and tensor's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);const a=r===0?0:t.size/r,o=[];Ce(()=>{t=K(t,[1,r,a]);for(let l=0;l{if(r!==a.dtype)throw new Error(`Invalid data types; op elements ${r}, but list elements ${a.dtype}`);pn(t,a.shape,"TensorList shape mismatch: "),zn(a)}),this.idTensor=De(0),this.maxNumElements=s,zn(this.idTensor)}copy(){return new xs([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.id))&&t.dispose()}),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(e,t,r=-1){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(r!==-1&&this.tensors.length!==r)throw new Error(`Operation expected a list with ${r} elements but got a list with ${this.tensors.length} elements.`);pn(e,this.elementShape,"TensorList shape mismatch: ");const s=Oa(this.elementShape,this.tensors,e);return Ce(()=>{const a=this.tensors.map(o=>K(o,s));return ar(a,0)})}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(this.size()===0)throw new Error("Trying to pop from an empty list.");const r=Oa(this.elementShape,this.tensors,e),s=this.tensors.pop();return s.kept=!1,pn(s.shape,e,"TensorList shape mismatch: "),K(s,r)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(pn(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");zn(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);if(this.maxNumElements!==-1&&e>this.maxNumElements)throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);const t=new xs([],this.elementShape,this.elementDtype,this.maxNumElements);t.tensors.length=e;for(let r=0;rthis.tensors.length)throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);if(this.tensors[e]==null)throw new Error(`element at index ${e} is null.`);pn(this.tensors[e].shape,t,"TensorList shape mismatch: ");const s=Oa(this.elementShape,this.tensors,t);return K(this.tensors[e],s)}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(e<0||this.maxNumElements!==-1&&e>=this.maxNumElements)throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);pn(this.elementShape,t.shape,"TensorList shape mismatch: "),zn(t),this.tensors[e]!=null&&(this.tensors[e].kept=!1),this.tensors[e]=t}gather(e,t,r){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);pn(this.elementShape,r,"TensorList shape mismatch: "),e=e.slice(0,this.size());const s=Oa(this.elementShape,this.tensors,r);return e.length===0?_n([],[0].concat(s)):Ce(()=>{const a=e.map(o=>K(this.tensors[o],s));return ar(a,0)})}concat(e,t){if(e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);pn(this.elementShape,t,"TensorList shape mismatch: ");const r=Oa(this.elementShape,this.tensors,t);return this.size()===0?_n([],[0].concat(r)):Ce(()=>{const s=this.tensors.map(a=>K(a,r));return wt(s,0)})}}function YN(n,e,t){const r=n.dtype;if(n.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${n.shape}`);if(n.dtype!==t)throw new Error(`Invalid data types; op elements ${n.dtype}, but list elements ${t}`);const s=n.shape.slice(1);pn(s,e,"TensorList shape mismatch: ");const a=Is(n);return new xs(a,e,r)}function QN(n,e,t,r){return new xs([],n,e,r)}function ZN(n,e,t,r){if(e.length!==n.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${n.shape[0]}`);const s=Math.max(...e);if(r!=null&&r!==-1&&s>=r)throw new Error(`Max index must be < array size (${s} vs. ${r})`);const a=new xs([],t,n.dtype,r),o=Is(n,0);return e.forEach((i,l)=>{a.setItem(i,o[l])}),a}function JN(n,e,t){let r=0;const s=e.map(u=>(r+=u,r));if(r!==n.shape[0])throw new Error(`Expected sum of lengths to be equal to + tensor.shape[0], but sum of lengths is + ${r}, and tensor's shape is: ${n.shape}`);const a=n.shape.slice(1),o=Rl(a,t),i=r===0?0:n.size/r,l=Ce(()=>{const u=[];n=K(n,[1,r,i]);for(let d=0;d{switch(n.op){case"If":case"StatelessIf":{const r=w("thenBranch",n,e,t),s=w("elseBranch",n,e,t),a=w("cond",n,e,t),o=w("args",n,e,t);return(await a.data())[0]?t.functionMap[r].executeFunctionAsync(o,t.tensorArrayMap,t.tensorListMap):t.functionMap[s].executeFunctionAsync(o,t.tensorArrayMap,t.tensorListMap)}case"While":case"StatelessWhile":{const r=w("body",n,e,t),s=w("cond",n,e,t),a=w("args",n,e,t),o=await t.functionMap[s].executeFunctionAsync(a,t.tensorArrayMap,t.tensorListMap),i=a.map(u=>u.id);let l=await o[0].data();o.forEach(u=>{!u.kept&&i.indexOf(u.id)===-1&&u.dispose()});let c=a;for(;l[0];){const u=c;c=await t.functionMap[r].executeFunctionAsync(c,t.tensorArrayMap,t.tensorListMap);const d=c.map(f=>f.id);u.forEach(f=>{!f.kept&&i.indexOf(f.id)===-1&&d.indexOf(f.id)===-1&&f.dispose()});const p=await t.functionMap[s].executeFunctionAsync(c,t.tensorArrayMap,t.tensorListMap);l=await p[0].data(),p.forEach(f=>{!f.kept&&i.indexOf(f.id)===-1&&d.indexOf(f.id)===-1&&f.dispose()})}return c}case"LoopCond":{const r=w("pred",n,e,t);return[Zn(r)]}case"Switch":{const r=w("pred",n,e,t);let s=w("data",n,e,t);return s.kept||(s=Zn(s)),(await r.data())[0]?[void 0,s]:[s,void 0]}case"Merge":{const r=n.inputNames.find(s=>St(s,e,t)!==void 0);if(r){const s=St(r,e,t);return[Zn(s)]}return}case"Enter":{const r=w("frameName",n,e,t),s=w("tensor",n,e,t);return t.enterFrame(r),[Zn(s)]}case"Exit":{const r=w("tensor",n,e,t);return t.exitFrame(),[Zn(r)]}case"NextIteration":{const r=w("tensor",n,e,t);return t.nextIteration(),[Zn(r)]}case"TensorArrayV3":{const r=w("size",n,e,t),s=w("dtype",n,e,t),a=w("elementShape",n,e,t),o=w("dynamicSize",n,e,t),i=w("clearAfterRead",n,e,t),l=w("identicalElementShapes",n,e,t),c=w("name",n,e,t),u=new XN(c,s,r,a,l,o,i);return t.addTensorArray(u),[u.idTensor,De(1)]}case"TensorArrayWriteV3":{const r=w("tensorArrayId",n,e,t),s=w("index",n,e,t),a=w("tensor",n,e,t),o=t.getTensorArray(r.id);return o.write(s,a),[o.idTensor]}case"TensorArrayReadV3":{const r=w("tensorArrayId",n,e,t),s=w("index",n,e,t);return[t.getTensorArray(r.id).read(s)]}case"TensorArrayGatherV3":{const r=w("tensorArrayId",n,e,t),s=w("indices",n,e,t),a=w("dtype",n,e,t);return[t.getTensorArray(r.id).gather(s,a)]}case"TensorArrayScatterV3":{const r=w("tensorArrayId",n,e,t),s=w("indices",n,e,t),a=w("tensor",n,e,t),o=t.getTensorArray(r.id);return o.scatter(s,a),[o.idTensor]}case"TensorArrayConcatV3":{const r=w("tensorArrayId",n,e,t),s=t.getTensorArray(r.id),a=w("dtype",n,e,t);return[s.concat(a)]}case"TensorArraySplitV3":{const r=w("tensorArrayId",n,e,t),s=w("tensor",n,e,t),a=w("lengths",n,e,t),o=t.getTensorArray(r.id);return o.split(a,s),[o.idTensor]}case"TensorArraySizeV3":{const r=w("tensorArrayId",n,e,t),s=t.getTensorArray(r.id);return[De(s.size(),"int32")]}case"TensorArrayCloseV3":{const r=w("tensorArrayId",n,e,t),s=t.getTensorArray(r.id);return s.clearAndClose(),[s.idTensor]}case"TensorListSetItem":{const r=w("tensorListId",n,e,t),s=w("index",n,e,t),a=w("tensor",n,e,t),o=t.getTensorList(r.id);return o.setItem(s,a),[o.idTensor]}case"TensorListGetItem":{const r=w("tensorListId",n,e,t),s=w("index",n,e,t),a=w("elementShape",n,e,t),o=w("elementDType",n,e,t);return[t.getTensorList(r.id).getItem(s,a,o)]}case"TensorListScatterV2":case"TensorListScatter":{const r=w("indices",n,e,t),s=w("tensor",n,e,t),a=w("elementShape",n,e,t),o=w("numElements",n,e,t),i=ZN(s,r,a,o);return t.addTensorList(i),[i.idTensor]}case"TensorListReserve":case"EmptyTensorList":{const r=w("elementShape",n,e,t),s=w("elementDType",n,e,t);let a;n.op==="TensorListReserve"?a="numElements":a="maxNumElements";const o=w(a,n,e,t),i=n.op==="TensorListReserve"?-1:o,l=QN(r,s,o,i);return t.addTensorList(l),[l.idTensor]}case"TensorListGather":{const r=w("tensorListId",n,e,t),s=w("indices",n,e,t),a=w("elementShape",n,e,t),o=w("elementDType",n,e,t);return[t.getTensorList(r.id).gather(s,o,a)]}case"TensorListStack":{const r=w("tensorListId",n,e,t),s=w("elementShape",n,e,t),a=w("elementDType",n,e,t),o=w("numElements",n,e,t);return[t.getTensorList(r.id).stack(s,a,o)]}case"TensorListFromTensor":{const r=w("tensor",n,e,t),s=w("elementShape",n,e,t),a=w("elementDType",n,e,t),o=YN(r,s,a);return t.addTensorList(o),[o.idTensor]}case"TensorListConcat":case"TensorListConcatV2":{const r=w("tensorListId",n,e,t),s=t.getTensorList(r.id),a=w("dtype",n,e,t),o=w("elementShape",n,e,t);return[s.concat(a,o)]}case"TensorListPushBack":{const r=w("tensorListId",n,e,t),s=w("tensor",n,e,t),a=t.getTensorList(r.id);return a.pushBack(s),[a.idTensor]}case"TensorListPopBack":{const r=w("tensorListId",n,e,t),s=w("elementShape",n,e,t),a=w("elementDType",n,e,t);return[t.getTensorList(r.id).popBack(s,a)]}case"TensorListSplit":{const r=w("tensor",n,e,t),s=w("elementShape",n,e,t),a=w("lengths",n,e,t),o=JN(r,a,s);return t.addTensorList(o),[o.idTensor]}case"TensorListLength":{const r=w("tensorListId",n,e,t),s=t.getTensorList(r.id);return[De(s.size(),"int32")]}case"TensorListResize":{const r=w("tensorListId",n,e,t),s=w("size",n,e,t),o=t.getTensorList(r.id).resize(s);return t.addTensorList(o),[o.idTensor]}default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Gp(n,e,t){const[r,s]=w("fusedOps",n,e,t),a=r==="biasadd",o=!a,i=s==="prelu",l=r==="fusedbatchnorm",c=w("numArgs",n,e,t);if(a){if(i&&c!==2)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!i&&a&&c!==1)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(l)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported");const u=w("strides",n,e,t),d=Ho(n,e,t),p=w("dataFormat",n,e,t).toUpperCase(),f=w("dilations",n,e,t);let[m,g]=w("args",n,e,t);o&&(g=m,m=void 0);const b=w("leakyreluAlpha",n,e,t);return{stride:u,pad:d,dataFormat:p,dilations:f,biasArg:m,preluArg:g,activationFunc:s,leakyreluAlpha:b}}const t3=(n,e,t,r=It)=>{switch(n.op){case"Conv1D":{const s=w("stride",n,e,t),a=w("pad",n,e,t),o=w("dataFormat",n,e,t).toUpperCase(),i=w("dilation",n,e,t);return[r.conv1d(w("x",n,e,t),w("filter",n,e,t),s,a,o,i)]}case"Conv2D":{const s=w("strides",n,e,t),a=Ho(n,e,t),o=w("dataFormat",n,e,t).toUpperCase(),i=w("dilations",n,e,t);return[r.conv2d(w("x",n,e,t),w("filter",n,e,t),[s[1],s[2]],a,o,[i[1],i[2]])]}case"_FusedConv2D":{const{stride:s,pad:a,dataFormat:o,dilations:i,biasArg:l,preluArg:c,activationFunc:u,leakyreluAlpha:d}=Gp(n,e,t);return[r.fused.conv2d({x:w("x",n,e,t),filter:w("filter",n,e,t),strides:[s[1],s[2]],pad:a,dataFormat:o,dilations:[i[1],i[2]],bias:l,activation:u,preluActivationWeights:c,leakyreluAlpha:d})]}case"FusedDepthwiseConv2dNative":{const{stride:s,pad:a,dataFormat:o,dilations:i,biasArg:l,preluArg:c,activationFunc:u,leakyreluAlpha:d}=Gp(n,e,t);return[r.fused.depthwiseConv2d({x:w("x",n,e,t),filter:w("filter",n,e,t),strides:[s[1],s[2]],pad:a,dataFormat:o,dilations:[i[1],i[2]],bias:l,activation:u,preluActivationWeights:c,leakyreluAlpha:d})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{const s=w("outputShape",n,e,t),a=w("strides",n,e,t),o=Ho(n,e,t);return[r.conv2dTranspose(w("x",n,e,t),w("filter",n,e,t),s,[a[1],a[2]],o)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{const s=w("strides",n,e,t),a=Ho(n,e,t),o=w("dilations",n,e,t),i=w("dataFormat",n,e,t).toUpperCase();return[r.depthwiseConv2d(w("input",n,e,t),w("filter",n,e,t),[s[1],s[2]],a,i,[o[1],o[2]])]}case"Conv3D":{const s=w("strides",n,e,t),a=w("pad",n,e,t),o=w("dataFormat",n,e,t).toUpperCase(),i=w("dilations",n,e,t);return[r.conv3d(w("x",n,e,t),w("filter",n,e,t),[s[1],s[2],s[3]],a,o,[i[1],i[2],i[3]])]}case"AvgPool":{const s=w("strides",n,e,t),a=w("pad",n,e,t),o=w("kernelSize",n,e,t);return[r.avgPool(w("x",n,e,t),[o[1],o[2]],[s[1],s[2]],a)]}case"MaxPool":{const s=w("strides",n,e,t),a=w("pad",n,e,t),o=w("kernelSize",n,e,t);return[r.maxPool(w("x",n,e,t),[o[1],o[2]],[s[1],s[2]],a)]}case"MaxPoolWithArgmax":{const s=w("strides",n,e,t),a=w("pad",n,e,t),o=w("kernelSize",n,e,t),i=w("includeBatchInIndex",n,e,t),{result:l,indexes:c}=r.maxPoolWithArgmax(w("x",n,e,t),[o[1],o[2]],[s[1],s[2]],a,i);return[l,c]}case"AvgPool3D":{const s=w("strides",n,e,t),a=w("pad",n,e,t),o=w("kernelSize",n,e,t);return[r.avgPool3d(w("x",n,e,t),[o[1],o[2],o[3]],[s[1],s[2],s[3]],a)]}case"MaxPool3D":{const s=w("strides",n,e,t),a=w("pad",n,e,t),o=w("kernelSize",n,e,t);return[r.maxPool3d(w("x",n,e,t),[o[1],o[2],o[3]],[s[1],s[2],s[3]],a)]}case"Dilation2D":{const s=w("strides",n,e,t),a=w("pad",n,e,t),o=w("dilations",n,e,t),i=s[1],l=s[2],c=o[1],u=o[2];return[r.dilation2d(w("x",n,e,t),w("filter",n,e,t),[i,l],a,[c,u],"NHWC")]}default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const n3=(n,e,t,r=It)=>{switch(n.op){case"Fill":{const s=w("shape",n,e,t),a=w("dtype",n,e,t),o=w("value",n,e,t);return[r.fill(s,o,a)]}case"LinSpace":{const s=w("start",n,e,t),a=w("stop",n,e,t),o=w("num",n,e,t);return[r.linspace(s,a,o)]}case"Multinomial":{const s=w("logits",n,e,t),a=w("numSamples",n,e,t),o=w("seed",n,e,t);return[r.multinomial(s,a,o)]}case"OneHot":{const s=w("indices",n,e,t),a=w("depth",n,e,t),o=w("onValue",n,e,t),i=w("offValue",n,e,t),l=w("dtype",n,e,t);return[r.oneHot(s,a,o,i,l)]}case"Ones":return[r.ones(w("shape",n,e,t),w("dtype",n,e,t))];case"OnesLike":return[r.onesLike(w("x",n,e,t))];case"RandomStandardNormal":return[r.randomStandardNormal(w("shape",n,e,t),w("dtype",n,e,t),w("seed",n,e,t))];case"RandomUniform":return[r.randomUniform(w("shape",n,e,t),w("minval",n,e,t),w("maxval",n,e,t),w("dtype",n,e,t))];case"RandomUniformInt":return[r.randomUniformInt(w("shape",n,e,t),w("minval",n,e,t),w("maxval",n,e,t),w("seed",n,e,t))];case"Range":{const s=w("start",n,e,t),a=w("stop",n,e,t),o=w("step",n,e,t);return[r.range(s,a,o,w("dtype",n,e,t))]}case"TruncatedNormal":{const s=w("shape",n,e,t),a=w("mean",n,e,t),o=w("stdDev",n,e,t),i=w("seed",n,e,t);return[r.truncatedNormal(s,a,o,w("dtype",n,e,t),i)]}case"Zeros":return[r.zeros(w("shape",n,e,t),w("dtype",n,e,t))];case"ZerosLike":return[r.zerosLike(w("x",n,e,t))];default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Bu(n,e,t){const r=w("boxes",n,e,t),s=w("scores",n,e,t),a=w("maxOutputSize",n,e,t),o=w("iouThreshold",n,e,t),i=w("scoreThreshold",n,e,t),l=w("softNmsSigma",n,e,t);return{boxes:r,scores:s,maxOutputSize:a,iouThreshold:o,scoreThreshold:i,softNmsSigma:l}}const r3=async(n,e,t,r,s=It)=>{switch(n.op){case"NonMaxSuppressionV5":{const{boxes:a,scores:o,maxOutputSize:i,iouThreshold:l,scoreThreshold:c,softNmsSigma:u}=Bu(n,e,t),d=await s.image.nonMaxSuppressionWithScoreAsync(a,o,i,l,c,u);return[d.selectedIndices,d.selectedScores]}case"NonMaxSuppressionV4":{const{boxes:a,scores:o,maxOutputSize:i,iouThreshold:l,scoreThreshold:c}=Bu(n,e,t),u=w("padToMaxOutputSize",n,e,t),d=await s.image.nonMaxSuppressionPaddedAsync(a,o,i,l,c,u);return[d.selectedIndices,d.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{const{boxes:a,scores:o,maxOutputSize:i,iouThreshold:l,scoreThreshold:c}=Bu(n,e,t);return[await s.image.nonMaxSuppressionAsync(a,o,i,l,c)]}case"Where":{const a=s.cast(w("condition",n,e,t),"bool"),o=[await s.whereAsync(a)];return a.dispose(),o}case"ListDiff":return s.setdiff1dAsync(w("x",n,e,t),w("y",n,e,t));default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const s3=(n,e,t,r=It)=>{switch(n.op){case"LowerBound":{const s=w("sortedSequence",n,e,t),a=w("values",n,e,t);return[r.lowerBound(s,a)]}case"TopKV2":{const s=w("x",n,e,t),a=w("k",n,e,t),o=w("sorted",n,e,t),i=r.topk(s,a,o);return[i.values,i.indices]}case"UpperBound":{const s=w("sortedSequence",n,e,t),a=w("values",n,e,t);return[r.upperBound(s,a)]}case"Unique":{const s=w("x",n,e,t),a=r.unique(s);return[a.values,a.indices]}case"UniqueV2":{const s=w("x",n,e,t),a=w("axis",n,e,t),o=r.unique(s,a);return[o.values,o.indices]}default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const a3=(n,e,t,r=It)=>{switch(n.op){case"Const":return e[n.name];case"PlaceholderWithDefault":const s=w("default",n,e,t);return[St(n.name,e,t)||s];case"Placeholder":return[St(n.name,e,t)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{const u=w("x",n,e,t);return[Zn(u)]}case"IdentityN":return w("x",n,e,t).map(u=>Zn(u));case"Snapshot":const a=w("x",n,e,t);return[Zn(a)];case"Shape":return[r.tensor1d(w("x",n,e,t).shape,"int32")];case"ShapeN":return w("x",n,e,t).map(u=>r.tensor1d(u.shape));case"Size":return[r.scalar(w("x",n,e,t).size,"int32")];case"Rank":return[r.scalar(w("x",n,e,t).rank,"int32")];case"NoOp":return[r.scalar(1)];case"Print":const o=w("x",n,e,t),i=w("data",n,e,t),l=w("message",n,e,t),c=w("summarize",n,e,t);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(l);for(let u=0;ue.dispose()),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return De(this.size(),"int32")}async import(e,t){this.checkKeyAndValueTensor(e,t);const r=await e.data();return this.tensorMap.forEach(s=>s.dispose()),this.tensorMap.clear(),Ce(()=>{const s=Is(t),a=r.length,o=s.length;$(a===o,()=>`The number of elements doesn't match, keys has ${a} elements, the values has ${o} elements.`);for(let i=0;i{const s=[];for(let a=0;a{switch(n.op){case"HashTable":case"HashTableV2":{const s=r.getHashTableHandleByName(n.name);if(s!=null)return[s];{const a=w("keyDType",n,e,t),o=w("valueDType",n,e,t),i=new o3(a,o);return r.addHashTable(n.name,i),[i.handle]}}case"InitializeTable":case"InitializeTableV2":case"LookupTableImport":case"LookupTableImportV2":{const s=w("tableHandle",n,e,t,r),a=w("keys",n,e,t),o=w("values",n,e,t);return[await r.getHashTableById(s.id).import(a,o)]}case"LookupTableFind":case"LookupTableFindV2":{const s=w("tableHandle",n,e,t,r),a=w("keys",n,e,t),o=w("defaultValue",n,e,t);return[await r.getHashTableById(s.id).find(a,o)]}case"LookupTableSize":case"LookupTableSizeV2":{const s=w("tableHandle",n,e,t,r);return[r.getHashTableById(s.id).tensorSize()]}default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const u3=(n,e,t,r=It)=>{switch(n.op){case"ResizeBilinear":{const s=w("images",n,e,t),a=w("size",n,e,t),o=w("alignCorners",n,e,t),i=w("halfPixelCenters",n,e,t);return[r.image.resizeBilinear(s,[a[0],a[1]],o,i)]}case"ResizeNearestNeighbor":{const s=w("images",n,e,t),a=w("size",n,e,t),o=w("alignCorners",n,e,t),i=w("halfPixelCenters",n,e,t);return[r.image.resizeNearestNeighbor(s,[a[0],a[1]],o,i)]}case"CropAndResize":{const s=w("image",n,e,t),a=w("boxes",n,e,t),o=w("boxInd",n,e,t),i=w("cropSize",n,e,t),l=w("method",n,e,t),c=w("extrapolationValue",n,e,t);return[r.image.cropAndResize(s,a,o,i,l,c)]}case"ImageProjectiveTransformV3":{const s=w("images",n,e,t),a=w("transforms",n,e,t),o=w("outputShape",n,e,t),i=w("fillValue",n,e,t),l=w("interpolation",n,e,t),c=w("fillMode",n,e,t);return[r.image.transform(s,a,l.toLowerCase(),c.toLowerCase(),i,o)]}default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const l3=(n,e,t,r=It)=>{switch(n.op){case"Equal":return[r.equal(w("a",n,e,t),w("b",n,e,t))];case"NotEqual":return[r.notEqual(w("a",n,e,t),w("b",n,e,t))];case"Greater":return[r.greater(w("a",n,e,t),w("b",n,e,t))];case"GreaterEqual":return[r.greaterEqual(w("a",n,e,t),w("b",n,e,t))];case"Less":return[r.less(w("a",n,e,t),w("b",n,e,t))];case"LessEqual":return[r.lessEqual(w("a",n,e,t),w("b",n,e,t))];case"LogicalAnd":return[r.logicalAnd(w("a",n,e,t),w("b",n,e,t))];case"LogicalNot":return[r.logicalNot(w("a",n,e,t))];case"LogicalOr":return[r.logicalOr(w("a",n,e,t),w("b",n,e,t))];case"Select":case"SelectV2":return[r.where(w("condition",n,e,t),w("a",n,e,t),w("b",n,e,t))];case"BitwiseAnd":return[r.bitwiseAnd(w("a",n,e,t),w("b",n,e,t))];default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const c3=(n,e,t,r=It)=>{switch(n.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[r.matMul(w("a",n,e,t),w("b",n,e,t),w("transposeA",n,e,t),w("transposeB",n,e,t))];case"Einsum":return[r.einsum(w("equation",n,e,t),...w("tensors",n,e,t))];case"Transpose":return[r.transpose(w("x",n,e,t),w("perm",n,e,t))];case"_FusedMatMul":const[s,a]=w("fusedOps",n,e,t),o=s==="biasadd",i=a==="prelu",l=w("numArgs",n,e,t),c=w("leakyreluAlpha",n,e,t);if(o){if(i&&l!==2)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!i&&l!==1)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}const[u,d]=w("args",n,e,t);return[r.fused.matMul({a:w("a",n,e,t),b:w("b",n,e,t),transposeA:w("transposeA",n,e,t),transposeB:w("transposeB",n,e,t),bias:u,activation:a,preluActivationWeights:d,leakyreluAlpha:c})];case"MatrixBandPart":return[r.linalg.bandPart(w("a",n,e,t),w("numLower",n,e,t),w("numUpper",n,e,t))];default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const d3=(n,e,t,r=It)=>{switch(n.op){case"EuclideanNorm":return[r.euclideanNorm(w("x",n,e,t),w("axis",n,e,t),w("keepDims",n,e,t))];case"FusedBatchNorm":case"FusedBatchNormV2":return[r.batchNorm(w("x",n,e,t),w("mean",n,e,t),w("variance",n,e,t),w("offset",n,e,t),w("scale",n,e,t),w("epsilon",n,e,t))];case"FusedBatchNormV3":return[r.batchNorm(w("x",n,e,t),w("mean",n,e,t),w("variance",n,e,t),w("offset",n,e,t),w("scale",n,e,t),w("epsilon",n,e,t))];case"LRN":return[r.localResponseNormalization(w("x",n,e,t),w("radius",n,e,t),w("bias",n,e,t),w("alpha",n,e,t),w("beta",n,e,t))];case"Softmax":return[r.softmax(w("x",n,e,t))];case"LogSoftmax":return[r.logSoftmax(w("x",n,e,t))];default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2022 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. + * ============================================================================= + */const p3=(n,e,t,r=It)=>{switch(n.op){case"RaggedGather":{const{outputNestedSplits:s,outputDenseValues:a}=r.raggedGather(w("paramsNestedSplits",n,e,t),w("paramsDenseValues",n,e,t),w("indices",n,e,t),w("outputRaggedRank",n,e,t));return s.concat(a)}case"RaggedRange":{const{rtNestedSplits:s,rtDenseValues:a}=r.raggedRange(w("starts",n,e,t),w("limits",n,e,t),w("splits",n,e,t));return[s,a]}case"RaggedTensorToTensor":return[r.raggedTensorToTensor(w("shape",n,e,t),w("values",n,e,t),w("defaultValue",n,e,t),w("rowPartitionTensors",n,e,t),w("rowPartitionTypes",n,e,t))];default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const h3=(n,e,t,r=It)=>{switch(n.op){case"Max":{const i=w("axis",n,e,t),l=w("keepDims",n,e,t);return[r.max(w("x",n,e,t),i,l)]}case"Mean":{const i=w("axis",n,e,t),l=w("keepDims",n,e,t);return[r.mean(w("x",n,e,t),i,l)]}case"Min":{const i=w("axis",n,e,t),l=w("keepDims",n,e,t);return[r.min(w("x",n,e,t),i,l)]}case"Sum":{const i=w("axis",n,e,t),l=w("keepDims",n,e,t);return[r.sum(w("x",n,e,t),i,l)]}case"All":{const i=w("axis",n,e,t),l=w("keepDims",n,e,t);return[r.all(w("x",n,e,t),i,l)]}case"Any":{const i=w("axis",n,e,t),l=w("keepDims",n,e,t);return[r.any(w("x",n,e,t),i,l)]}case"ArgMax":{const i=w("axis",n,e,t);return[r.argMax(w("x",n,e,t),i)]}case"ArgMin":{const i=w("axis",n,e,t);return[r.argMin(w("x",n,e,t),i)]}case"Prod":{const i=w("axis",n,e,t),l=w("keepDims",n,e,t);return[r.prod(w("x",n,e,t),i,l)]}case"Cumprod":{const i=w("axis",n,e,t),l=w("exclusive",n,e,t),c=w("reverse",n,e,t);return[r.cumprod(w("x",n,e,t),i,l,c)]}case"Cumsum":{const i=w("axis",n,e,t),l=w("exclusive",n,e,t),c=w("reverse",n,e,t);return[r.cumsum(w("x",n,e,t),i,l,c)]}case"Bincount":const s=w("x",n,e,t),a=w("weights",n,e,t),o=w("size",n,e,t);return[r.bincount(s,a,o)];case"DenseBincount":{const i=w("x",n,e,t),l=w("weights",n,e,t),c=w("size",n,e,t),u=w("binaryOutput",n,e,t);return[r.denseBincount(i,l,c,u)]}default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const f3=(n,e,t,r=It)=>{switch(n.op){case"ConcatV2":case"Concat":{const s=w("n",n,e,t),a=w("axis",n,e,t);let o=w("tensors",n,e,t);return o=o.slice(0,s),[r.concat(o,a)]}case"Gather":{const s=w("x",n,e,t),a=w("indices",n,e,t);return[r.gather(s,r.cast(a,"int32"),0)]}case"GatherV2":{const s=w("axis",n,e,t),a=w("batchDims",n,e,t),o=w("x",n,e,t),i=w("indices",n,e,t);return[r.gather(o,r.cast(i,"int32"),s,a)]}case"Reverse":{const s=w("dims",n,e,t),a=[];for(let i=0;i{const s=w("axis",n,e,t),a=w("tensors",n,e,t),o=a[0].shape,i=r.squeeze(a[0]).shape,l=a.map(c=>{const u=Vt(c.shape,o);if(!u&&!Vt(r.squeeze(c).shape,i))throw new Error("the input tensors shape does not match");return u?c:r.reshape(c,o)});return[r.stack(l,s)]});case"Unpack":{const s=w("axis",n,e,t),a=w("tensor",n,e,t);return r.unstack(a,s)}case"Tile":{const s=w("reps",n,e,t);return[r.tile(w("x",n,e,t),s)]}case"Split":case"SplitV":{const s=w("axis",n,e,t),a=w("numOrSizeSplits",n,e,t),o=w("x",n,e,t);return r.split(o,a,s)}case"ScatterNd":{const s=w("indices",n,e,t),a=w("values",n,e,t),o=w("shape",n,e,t);return[r.scatterND(s,a,o)]}case"GatherNd":{const s=w("x",n,e,t),a=w("indices",n,e,t);return[r.gatherND(s,a)]}case"SparseToDense":{const s=w("sparseIndices",n,e,t),a=w("outputShape",n,e,t),o=w("sparseValues",n,e,t),i=w("defaultValue",n,e,t);return[r.sparseToDense(s,o,a,o.dtype===i.dtype?i:r.cast(i,o.dtype))]}case"TensorScatterUpdate":{const s=w("indices",n,e,t),a=w("values",n,e,t),o=w("tensor",n,e,t);return[r.tensorScatterUpdate(o,s,a)]}default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const m3=(n,e,t,r=It)=>{switch(n.op){case"SparseFillEmptyRows":{const{outputIndices:s,outputValues:a,emptyRowIndicator:o,reverseIndexMap:i}=r.sparse.sparseFillEmptyRows(w("indices",n,e,t),w("values",n,e,t),w("denseShape",n,e,t),w("defaultValue",n,e,t));return[s,a,o,i]}case"SparseReshape":{const{outputIndices:s,outputShape:a}=r.sparse.sparseReshape(w("inputIndices",n,e,t),w("inputShape",n,e,t),w("newShape",n,e,t));return[s,a]}case"SparseSegmentMean":return[r.sparse.sparseSegmentMean(w("data",n,e,t),w("indices",n,e,t),w("segmentIds",n,e,t))];case"SparseSegmentSum":return[r.sparse.sparseSegmentSum(w("data",n,e,t),w("indices",n,e,t),w("segmentIds",n,e,t))];default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const g3=(n,e,t,r=It)=>{switch(n.op){case"FFT":return[r.fft(w("x",n,e,t))];case"IFFT":return[r.ifft(w("x",n,e,t))];case"RFFT":return[r.rfft(w("x",n,e,t))];case"IRFFT":return[r.irfft(w("x",n,e,t))];default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const y3=(n,e,t,r=It)=>{switch(n.op){case"StaticRegexReplace":return[r.string.staticRegexReplace(w("input",n,e,t),w("pattern",n,e,t),w("rewrite",n,e,t),w("replaceGlobal",n,e,t))];case"StringNGrams":{const{nGrams:s,nGramsSplits:a}=r.string.stringNGrams(w("data",n,e,t),w("dataSplits",n,e,t),w("separator",n,e,t),w("nGramWidths",n,e,t),w("leftPad",n,e,t),w("rightPad",n,e,t),w("padWidth",n,e,t),w("preserveShortSequences",n,e,t));return[s,a]}case"StringSplit":{const{indices:s,values:a,shape:o}=r.string.stringSplit(w("input",n,e,t),w("delimiter",n,e,t),w("skipEmpty",n,e,t));return[s,a,o]}case"StringToHashBucketFast":return[r.string.stringToHashBucketFast(w("input",n,e,t),w("numBuckets",n,e,t))];default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const b3=(n,e,t,r=It)=>{switch(n.op){case"Cast":return[r.cast(w("x",n,e,t),w("dtype",n,e,t))];case"ExpandDims":{const s=w("axis",n,e,t);return[r.expandDims(w("x",n,e,t),s)]}case"Squeeze":{const s=w("axis",n,e,t);return[r.squeeze(w("x",n,e,t),s)]}case"Reshape":return[r.reshape(w("x",n,e,t),w("shape",n,e,t))];case"EnsureShape":return[r.ensureShape(w("x",n,e,t),w("shape",n,e,t))];case"MirrorPad":return[r.mirrorPad(w("x",n,e,t),w("padding",n,e,t),w("mode",n,e,t))];case"PadV2":case"Pad":return[r.pad(w("x",n,e,t),w("padding",n,e,t),w("constantValue",n,e,t))];case"SpaceToBatchND":{const s=w("blockShape",n,e,t),a=w("paddings",n,e,t);return[r.spaceToBatchND(w("x",n,e,t),s,a)]}case"BatchToSpaceND":{const s=w("blockShape",n,e,t),a=w("crops",n,e,t);return[r.batchToSpaceND(w("x",n,e,t),s,a)]}case"DepthToSpace":{const s=w("blockSize",n,e,t),a=w("dataFormat",n,e,t).toUpperCase();return[r.depthToSpace(w("x",n,e,t),s,a)]}case"BroadcastTo":return[r.broadcastTo(w("x",n,e,t),w("shape",n,e,t))];case"BroadcastArgs":return[r.broadcastArgs(w("s0",n,e,t),w("s1",n,e,t))];default:throw TypeError(`Node type ${n.op} is not implemented`)}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function jp(n,e,t,r,s=Ce){const a=((o,i,l)=>{switch(o.category){case"arithmetic":return s(()=>qN(o,i,l));case"basic_math":return s(()=>KN(o,i,l));case"control":return e3(o,i,l);case"convolution":return s(()=>t3(o,i,l));case"creation":return s(()=>n3(o,i,l));case"dynamic":return r3(o,i,l);case"evaluation":return s(()=>s3(o,i,l));case"image":return s(()=>u3(o,i,l));case"graph":return s(()=>a3(o,i,l));case"logical":return s(()=>l3(o,i,l));case"matrices":return s(()=>c3(o,i,l));case"normalization":return s(()=>d3(o,i,l));case"ragged":return s(()=>p3(o,i,l));case"reduction":return s(()=>h3(o,i,l));case"slice_join":return s(()=>f3(o,i,l));case"sparse":return s(()=>m3(o,i,l));case"spectral":return s(()=>g3(o,i,l));case"string":return s(()=>y3(o,i,l));case"transformation":return s(()=>b3(o,i,l));case"hash_table":return i3(o,i,l,r);case"custom":const c=lg(o.op);if(c&&c.customExecutor)return c.customExecutor(new jN(o,i,l));throw TypeError(`Custom op ${o.op} is not registered.`);default:throw TypeError(`Unknown op '${o.op}'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()`)}})(n,e,t);return hs(a)?a.then(o=>[].concat(o)):[].concat(a)}class qp{constructor(e={},t={},r={},s={},a){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=r,this.functionMap=s,this.parseNodeNameCache=a,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}newFrame(e,t){return{id:e,frameName:t,iterationId:0}}set currentContext(e){this.contexts!==e&&(this.contexts=e,this.generateCurrentContextIds())}get currentContext(){return this.contexts}get currentContextId(){return this._currentContextIds[0]}get currentContextIds(){return this._currentContextIds}generateCurrentContextIds(){const e=[];for(let t=0;tt.id===0&&t.iterationId===0?"":`${t.frameName}-${t.iterationId}`).join("/"):""}enterFrame(e){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,e)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)))}exitFrame(){if(this.contexts&&this.contexts.length>1)this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift();else throw new Error("Cannot exit frame, the context is empty")}nextIteration(){if(this.contexts&&this.contexts.length>0){this.contexts=this.contexts.slice(),this.lastId++;const e=Object.assign({},this.contexts[this.contexts.length-1]);e.iterationId+=1,e.id=this.lastId,this.contexts.splice(-1,1,e),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))}else throw new Error("Cannot increase frame iteration, the context is empty")}getWeight(e){return this.weightMap[e]}addTensorArray(e){this.tensorArrayMap[e.id]=e}getTensorArray(e){return this.tensorArrayMap[e]}addTensorList(e){this.tensorListMap[e.id]=e}getTensorList(e){return this.tensorListMap[e]}dispose(e){for(const t in this.tensorArrayMap)this.tensorArrayMap[t].clearAndClose(e);for(const t in this.tensorListMap)this.tensorListMap[t].clearAndClose(e)}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Kp(n,e,t,r){const s=new Set,a=[];let o=null,i=null;const l=new Set,c=new Set(Object.keys(n).map(p=>Kt(p)[0]));r=r||[];const u=new Set(r.map(p=>Kt(p.name)[0])),d=[...e];for(;d.length>0;){const p=d.pop();if((ns(p)||C3(p)||N3(p))&&o==null&&(o=p,i=o.children.map(f=>f.name).filter(f=>s.has(f))),s.add(p.name),t[p.name]==null&&!c.has(p.name)&&!u.has(p.name)){if(p.inputs.length===0){a.push(p.name);continue}p.inputs.forEach(f=>{l.has(f.name)||(l.add(f.name),d.push(f))})}}return{inputs:n,outputs:e,usedNodes:s,missingInputs:a,dynamicNode:o,syncInputs:i}}function w3(n,e){const{usedNodes:t,inputs:r}=e,s=Object.keys(r).map(b=>Kt(b)[0]).map(b=>n.nodes[b]),a=n.initNodes||[],o=b=>t.has(typeof b=="string"?b:b.name);function i(b){return[...new Map(b.map(v=>[v.name,v])).values()]}const l=i([...s,...n.weights,...a]).filter(o),c=i([...l,...Object.values(n.nodes)]).filter(o),u=new Map(c.map(b=>[b.name,b])),d={};for(const b of c){d[b.name]=d[b.name]||0;for(const v of b.children)o(v)||(d[v.name]=Number.POSITIVE_INFINITY),d[v.name]=(d[v.name]||0)+1}const p=Object.entries(d).filter(([,b])=>b===0).map(([b])=>b),f=[...p];for(;p.length>0;){const b=p.pop(),v=u.get(b);for(const I of v.children.filter(o))--d[I.name]===0&&(f.push(I.name),p.push(I.name))}const m=f.map(b=>u.get(b)),g=x3(m,l);return v3(g,l),g}function x3(n,e){const t=new Map(n.map(o=>[o.name,o])),r=e.map(o=>o.name),s=new Set(r);for(;r.length>0;){const o=r.pop(),i=t.get(o);for(const l of i.children)!t.has(l.name)||s.has(l.name)||(s.add(l.name),r.push(l.name))}return n.filter(o=>s.has(o.name))}class Ro extends Error{constructor(e){super(`NodesExecutionOrderError: ${e}`)}}function v3(n,e){const t=new Map(n.map((i,l)=>[i.name,l])),r=new Set(e.map(i=>i.name)),s=i=>r.has(typeof i=="string"?i:i.name),a=new Set(n.map(i=>i.name)),o=i=>a.has(typeof i=="string"?i:i.name);for(const i of n){for(const l of i.children.filter(o)){if(!t.has(l.name))throw new Ro(`Child ${l.name} of node ${i.name} is unreachable.`);if(t.get(i.name)>t.get(l.name))throw new Ro(`Node ${i.name} is scheduled to run after its child ${l.name}.`)}if(!s(i))for(const l of i.inputs){if(!t.has(l.name))throw new Ro(`Input ${l.name} of node ${i.name} is unreachable.`);if(t.get(l.name)>t.get(i.name))throw new Ro(`Node ${i.name} is scheduled to run before its input ${l.name}.`)}}}function S3(n){const e=new Map(n.map((i,l)=>[i.name,l])),t=Number.MAX_SAFE_INTEGER,r=n.map((i,l)=>ns(i)?t:l),s=i=>{const l=r[e.get(i.name)];return l??-1},a=n.map((i,l)=>i.children.map(s).reduce((c,u)=>Math.max(c,u),r[l])),o=new Map;for(let i=0;ie[r].map(s=>s.id));this._weightIds=[].concat(...t),this._weightMap=e}set resourceManager(e){this._resourceManager=e}get inputs(){return this._inputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get outputs(){return this._outputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get inputNodes(){return this._inputs.map(e=>e.signatureKey||e.name)}get outputNodes(){return this._outputs.map(e=>{const t=e.signatureKey||e.name;return e.defaultOutput?`${t}:${e.defaultOutput}`:t})}get functions(){return Object.keys(this._functions).reduce((e,t)=>(e[t]=this._functions[t].signature,e),{})}constructor(e,t){this.graph=e,this.parent=t,this.compiledMap=new Map,this.parseNodeNameCache=new Map,this._weightMap={},this.SEPARATOR=",",this._functions={},this._functionExecutorMap={},this.keepIntermediateTensors=!1,this._outputs=e.outputs,this._inputs=e.inputs,this._initNodes=e.initNodes,this._signature=e.signature,this._functions=e.functions,e.functions!=null&&Object.keys(e.functions).forEach(r=>{this._functionExecutorMap[r]=new ai(e.functions[r],this)})}getCompilationKey(e,t){const r=e.map(a=>a.name).sort(),s=t.map(a=>a.name).sort();return r.join(this.SEPARATOR)+"--"+s.join(this.SEPARATOR)}compile(e,t){const r=Kp(e,t,this.weightMap,this._initNodes),{missingInputs:s,dynamicNode:a,syncInputs:o}=r;if(a!=null)throw new Error(`This execution contains the node '${a.name}', which has the dynamic op '${a.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${o}]`);if(s.length>0){const c=t.map(d=>d.name),u=Object.keys(e);throw new Error(`Cannot compute the outputs [${c}] from the provided inputs [${u}]. Missing the following inputs: [${s}]`)}const i=w3(this.graph,r),l=S3(i);return{orderedNodes:i,nodeLiveUntilMap:l}}cloneAndKeepTensor(e){if(e==null)return null;const t=e.clone();return zn(t),t}cloneTensorList(e){return e?e.map(r=>this.cloneAndKeepTensor(r)):null}cloneTensorMap(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,this.cloneTensorList(r)]))}execute(e,t){this.disposeIntermediateTensors(),e=this.mapInputs(e);const r=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t);const s=r.map(p=>this.graph.nodes[Kt(p)[0]]),a=t.map(p=>Kt(p)[0]),o=new Set(a);let i=a.map(p=>this.graph.nodes[p]);i.length===0&&(i=this._outputs);const l=this.getCompilationKey(s,i);let c=this.compiledMap.get(l);c==null&&(c=this.compile(e,i),this.compiledMap.set(l,c));try{this.keepIntermediateTensors=fe().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(p){this.keepIntermediateTensors=!1,console.warn(p.message)}const u={},d={};return Ce(()=>{const p=new qp(this.weightMap,u,d,this.functionExecutorMap,this.parseNodeNameCache),f=Object.assign({},this.weightMap);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap)),Object.keys(e).forEach(v=>{const[I,S]=Kt(v,p),C=[];C[S]=e[v],f[I]=C,this.keepIntermediateTensors&&(this.clonedTensorsMap[I]=this.cloneTensorList(C))});const m=this.getFrozenTensorIds(f),{orderedNodes:g,nodeLiveUntilMap:b}=c;for(const v of g){if(f[v.name])continue;const I=jp(v,f,p,this._resourceManager);if(hs(I))throw new Error(`The execution of the op '${v.op}' returned a promise. Please use model.executeAsync() instead.`);f[v.name]=I,this.keepIntermediateTensors&&(this.clonedTensorsMap[v.name]=this.cloneTensorList(I)),this.checkTensorForDisposalWithNodeLiveUntilInfo(v,f,p,m,o,b.get(v.name))}return this.parent==null&&p.dispose(m),t.map(v=>St(v,f,p))})}getFrozenTensorIds(e){const t=[].concat.apply([],Object.keys(e).map(r=>e[r]).map(r=>r.map(s=>s.id)));return new Set(t)}checkTensorForDisposal(e,t,r,s,a,o,i){if(!(ns(t)||o.has(e))){for(const l of r[e])l!=null&&(i[l.id]=(i[l.id]||0)+t.children.length);for(const l of t.inputs){if(ns(l))continue;const c=Wp(l.name,r,s);if(c!=null)for(const u of c){if(!u||u.kept||a.has(u.id))continue;const d=i[u.id];d===1?(u.dispose(),delete i[u.id]):d!=null&&i[u.id]--}}}}checkTensorForDisposalWithNodeLiveUntilInfo(e,t,r,s,a,o){function i(l){return ns(l)||a.has(l.name)}if(!(ns(e)||o==null))for(const l of o){if(i(l))continue;const c=Wp(l.name,t,r);for(const u of c)!u||u.kept||s.has(u.id)||u.dispose()}}async executeAsync(e,t){return this._executeAsync(e,t)}disposeIntermediateTensors(){this.clonedTensorsMap&&(Object.values(this.clonedTensorsMap).forEach(e=>{for(const t of e)t&&!t.isDisposed&&t.dispose()}),this.clonedTensorsMap=null)}getIntermediateTensors(){return this.clonedTensorsMap}async _executeAsync(e,t,r=!1,s={},a={}){this.disposeIntermediateTensors(),r||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t));try{this.keepIntermediateTensors=fe().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(p){this.keepIntermediateTensors=!1,console.warn(p.message)}const o=new qp(this.weightMap,s,a,this.functionExecutorMap,this.parseNodeNameCache);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap));const i=await this.executeWithControlFlow(e,o,t,r),l=t.map(p=>St(p,i,o)),c=l.map(p=>p.id),u=Object.keys(e).map(p=>e[p].id),d=new Set([...c,...u,...this.weightIds]);return Object.values(i).forEach(p=>{p.forEach(f=>{f&&!f.isDisposed&&!d.has(f.id)&&f.dispose()})}),this.parent==null&&o.dispose(d),l}async executeFunctionAsync(e,t,r){const s=e.reduce((a,o,i)=>(a[this.inputs[i].name]=o,a),{});return this._executeAsync(s,this.outputNodes,!0,t,r)}async executeWithControlFlow(e,t,r,s){const a=Object.keys(e),o=a.map(C=>this.graph.nodes[Kt(C)[0]]),i=r.map(C=>Kt(C)[0]),l=new Set(i);let c=i.map(C=>this.graph.nodes[C]);c.length===0&&(c=this._outputs);const{usedNodes:u,missingInputs:d,dynamicNode:p,syncInputs:f}=Kp(e,c,this.weightMap,this._initNodes),m=[...o,...this.graph.weights,...this._initNodes||[]].map(C=>({node:C,contexts:t.currentContext})),g=Object.assign({},this.weightMap);Object.keys(e).forEach(C=>{const[T,O]=Kt(C),L=[];L[O]=e[C],g[T]=L});const b={},v=this.getFrozenTensorIds(g),I={};for(;m.length>0;){const C=this.processStack(o,m,t,g,I,v,l,b,u);await Promise.all(C)}p==null&&!s&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");const S=c.filter(C=>!ns(C)&&!St(C.name,g,t)).map(C=>C.name);if(S.length>0){let C="";throw p!=null&&(C=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${f}]`),new Error(`Cannot compute the outputs [${S}] from the provided inputs [${a}]. Consider providing the following inputs: [${d}]. ${C}`)}return g}processStack(e,t,r,s,a,o,i,l,c){const u=[];for(;t.length>0;){const d=t.pop();r.currentContext=d.contexts;let p="";if(d.node.op==="Enter"&&w("isConstant",d.node,s,r)&&([p]=Qn(d.node.name,r)),s[d.node.name]==null){const f=jp(d.node,s,r,this._resourceManager);p||([p]=Qn(d.node.name,r));const m=r.currentContext;hs(f)?u.push(f.then(g=>(s[p]=g,this.keepIntermediateTensors&&(this.clonedTensorsMap[p]=this.cloneTensorList(g)),r.currentContext=m,this.checkTensorForDisposal(p,d.node,s,r,o,i,l),this.processChildNodes(d.node,t,r,s,a,c),g))):(s[p]=f,this.keepIntermediateTensors&&(this.clonedTensorsMap[p]=this.cloneTensorList(f)),this.checkTensorForDisposal(p,d.node,s,r,o,i,l),this.processChildNodes(d.node,t,r,s,a,c))}else this.processChildNodes(d.node,t,r,s,a,c)}return u}processChildNodes(e,t,r,s,a,o){e.children.forEach(i=>{const[l]=Qn(i.name,r);a[l]||!o.has(i.name)||(i.op==="Merge"?i.inputNames.some(c=>!!St(c,s,r))&&(a[l]=!0,t.push({contexts:r.currentContext,node:i})):i.inputNames.every(c=>!!St(c,s,r))&&(a[l]=!0,t.push({contexts:r.currentContext,node:i})))})}dispose(){Object.keys(this.weightMap).forEach(e=>this.weightMap[e].forEach(t=>t.dispose()))}checkInputShapeAndType(e){Object.keys(e).forEach(t=>{const r=e[t],[s]=Kt(t),a=this.graph.nodes[s];if(a.attrParams.shape&&a.attrParams.shape.value){const o=a.attrParams.shape.value,i=o.length===r.shape.length&&r.shape.every((l,c)=>o[c]===-1||o[c]===l);$(i,()=>`The shape of dict['${a.name}'] provided in model.execute(dict) must be [${o}], but was [${r.shape}]`)}a.attrParams.dtype&&a.attrParams.dtype.value&&$(r.dtype===a.attrParams.dtype.value,()=>`The dtype of dict['${a.name}'] provided in model.execute(dict) must be ${a.attrParams.dtype.value}, but was ${r.dtype}`)})}mapInputs(e){var t,r;const s={};for(const a in e){const o=(r=(t=this._signature)===null||t===void 0?void 0:t.inputs)===null||r===void 0?void 0:r[a];o!=null?s[o.name]=e[a]:s[a]=e[a]}return s}checkInputs(e){const t=Object.keys(e).filter(r=>{const[s]=Kt(r);return this.graph.nodes[s]==null});if(t.length>0)throw new Error(`The dict provided in model.execute(dict) has keys: [${t}] that are not part of graph`)}mapOutputs(e){return e.map(t=>{var r,s;const a=(s=(r=this._signature)===null||r===void 0?void 0:r.outputs)===null||s===void 0?void 0:s[t];return a!=null?a.name:t},{})}checkOutputs(e){e.forEach(t=>{const[r]=Kt(t);if(!this.graph.nodes[r])throw new Error(`The output '${t}' is not found in the graph`)})}}class $3{constructor(e={},t={}){this.hashTableNameToHandle=e,this.hashTableMap=t}addHashTable(e,t){this.hashTableNameToHandle[e]=t.handle,this.hashTableMap[t.id]=t}getHashTableHandleByName(e){return this.hashTableNameToHandle[e]}getHashTableById(e){return this.hashTableMap[e]}dispose(){for(const e in this.hashTableMap)this.hashTableMap[e].clearAndClose(),delete this.hashTableMap[e];for(const e in this.hashTableNameToHandle)this.hashTableNameToHandle[e].dispose(),delete this.hashTableNameToHandle[e]}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const T3="?tfjs-format=file",E3="model.json";class A3{get modelVersion(){return this.version}get inputNodes(){return this.executor.inputNodes}get outputNodes(){return this.executor.outputNodes}get inputs(){return this.executor.inputs}get outputs(){return this.executor.outputs}get weights(){return this.executor.weightMap}get metadata(){return this.artifacts.userDefinedMetadata}get modelSignature(){return this.signature}get modelStructuredOutputKeys(){return this.structuredOutputKeys}constructor(e,t={},r=Km){this.modelUrl=e,this.loadOptions=t,this.version="n/a",this.io=r,t==null&&(this.loadOptions={}),this.resourceManager=new $3}findIOHandler(){const e=this.modelUrl;if(e.load!=null)this.handler=e;else if(this.loadOptions.requestInit!=null)this.handler=this.io.browserHTTPRequest(e,this.loadOptions);else{const t=this.io.getLoadHandlers(e,this.loadOptions);if(t.length===0)t.push(this.io.browserHTTPRequest(e,this.loadOptions));else if(t.length>1)throw new Error(`Found more than one (${t.length}) load handlers for URL '${[e]}'`);this.handler=t[0]}}load(){if(this.findIOHandler(),this.handler.load==null)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");const e=this.handler.load();return hs(e)?e.then(t=>t.getWeightStream==null?this.loadSync(t):this.loadStreaming(t)):this.loadSync(e)}loadSync(e){const t=this.io.decodeWeights(e.weightData,e.weightSpecs);return this.loadWithWeightMap(e,t)}async loadStreaming(e){if(e.getWeightStream==null)throw new Error("Model artifacts missing streamWeights function");const t=await Uf(e.getWeightStream(),e.weightSpecs);return this.loadWithWeightMap(e,t)}loadWithWeightMap(e,t){this.artifacts=e;const r=this.artifacts.modelTopology;let s=this.artifacts.signature;if(this.artifacts.userDefinedMetadata!=null){const a=this.artifacts.userDefinedMetadata;a.signature!=null&&(s=a.signature),a.structuredOutputKeys!=null&&(this.structuredOutputKeys=a.structuredOutputKeys)}if(this.signature=s,this.version=`${r.versions.producer}.${r.versions.minConsumer}`,this.executor=new ai(Vp.Instance.transformGraph(r,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(t),this.executor.resourceManager=this.resourceManager,e.modelInitializer!=null&&e.modelInitializer.node!=null){const a=Vp.Instance.transformGraph(e.modelInitializer);this.initializer=new ai(a),this.initializer.weightMap=this.executor.weightMap,this.initializer.resourceManager=this.resourceManager,this.initializerSignature=e.initializerSignature}return!0}async save(e,t){if(typeof e=="string"){const r=this.io.getSaveHandlers(e);if(r.length===0)throw new Error(`Cannot find any save handlers for URL '${e}'`);if(r.length>1)throw new Error(`Found more than one (${r.length}) save handlers for URL '${e}'`);e=r[0]}if(e.save==null)throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return e.save(this.artifacts)}addStructuredOutputNames(e){if(this.structuredOutputKeys){const t=e instanceof dt?[e]:e,r={};return t.forEach((s,a)=>r[this.structuredOutputKeys[a]]=s),r}return e}predict(e,t){const r=this.execute(e,this.outputNodes);return this.addStructuredOutputNames(r)}async predictAsync(e,t){const r=await this.executeAsync(e,this.outputNodes);return this.addStructuredOutputNames(r)}normalizeInputs(e){var t;if(!(e instanceof dt)&&!Array.isArray(e)){const a=(t=this.signature)===null||t===void 0?void 0:t.inputs;if(a!=null)for(const o in a){const i=a[o];i.resourceId!=null&&(e[o]=this.resourceIdToCapturedInput[i.resourceId])}return e}e=Array.isArray(e)?e:[e];const r=Object.keys(this.resourceIdToCapturedInput).length;if(e.length+r!==this.inputNodes.length)throw new Error(`Input tensor count mismatch, the graph model has ${this.inputNodes.length-r} non-resource placeholders, while there are ${e.length} input tensors provided.`);let s=0;return this.inputNodes.reduce((a,o)=>{var i,l,c;const u=(c=(l=(i=this.signature)===null||i===void 0?void 0:i.inputs)===null||l===void 0?void 0:l[o])===null||c===void 0?void 0:c.resourceId;return u!=null?a[o]=this.resourceIdToCapturedInput[u]:a[o]=e[s++],a},{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}executeInitializerGraph(){return this.initializer==null?[]:this.initializerSignature==null?this.initializer.execute({},[]):this.initializer.execute({},Object.keys(this.initializerSignature.outputs))}async executeInitializerGraphAsync(){return this.initializer==null?[]:this.initializerSignature==null?this.initializer.executeAsync({},[]):this.initializer.executeAsync({},Object.keys(this.initializerSignature.outputs))}setResourceIdToCapturedInput(e){if(this.resourceIdToCapturedInput={},this.initializerSignature){const t=this.initializerSignature.outputs,r=Object.keys(t);for(let s=0;s1?r:r[0]}async executeAsync(e,t){this.resourceIdToCapturedInput==null&&this.setResourceIdToCapturedInput(await this.executeInitializerGraphAsync()),e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const r=await this.executor.executeAsync(e,t);return r.length>1?r:r[0]}getIntermediateTensors(){return this.executor.getIntermediateTensors()}disposeIntermediateTensors(){this.executor.disposeIntermediateTensors()}convertTensorMapToTensorsMap(e){return Object.keys(e).reduce((t,r)=>(t[r]=[e[r]],t),{})}dispose(){this.executor.dispose(),this.initializer&&(this.initializer.dispose(),this.resourceIdToCapturedInput&&Ke(this.resourceIdToCapturedInput)),this.resourceManager.dispose()}}async function ia(n,e={},t=Km){if(n==null)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");e==null&&(e={}),e.fromTFHub&&typeof n=="string"&&(n=R3(n));const r=new A3(n,e,t);return await r.load(),r}function R3(n){return n.endsWith("/")||(n=n+"/"),`${n}${E3}${T3}`}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var Ue;(function(n){n[n.float32=0]="float32",n[n.int32=1]="int32",n[n.bool=2]="bool",n[n.string=3]="string",n[n.complex64=4]="complex64"})(Ue||(Ue={}));var oo;(function(n){n[n.linear=0]="linear",n[n.relu=1]="relu",n[n.relu6=2]="relu6",n[n.prelu=3]="prelu",n[n.leakyrelu=4]="leakyrelu",n[n.sigmoid=5]="sigmoid",n[n.elu=6]="elu"})(oo||(oo={}));/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let pg;function D3(n){pg=n.wasm.cwrap(Ka,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function P3(n){const{inputs:e,backend:t,attrs:r}=n,{a:s,b:a,bias:o,preluActivationWeights:i}=e;if(s.dtype!=="float32"||a.dtype!=="float32")throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");const{transposeA:l,transposeB:c,activation:u,leakyreluAlpha:d}=r,p=t.dataIdMap.get(s.dataId).id,f=t.dataIdMap.get(a.dataId).id;let m=0;if(o!=null){const B=t.dataIdMap.get(o.dataId);if(B.shape.length!==1)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${B.shape.length}.`);m=B.id}const g=i==null?0:t.dataIdMap.get(i.dataId).id,b=oo[u];if(b==null)throw new Error(`${u} activation not yet supported for FusedConv2D in the wasm backend.`);const v=l?s.shape[2]:s.shape[1],I=c?a.shape[1]:a.shape[2],S=je(s.shape.slice(0,-2),a.shape.slice(0,-2)),C=t.makeOutput([...S,v,I],s.dtype),T=t.dataIdMap.get(C.dataId).id,O=new Uint8Array(new Int32Array(s.shape).buffer),L=new Uint8Array(new Int32Array(a.shape).buffer);return pg(p,O,s.shape.length,f,L,a.shape.length,l,c,b,m,g,d||0,T),C}const F3={kernelName:Ka,backendName:"wasm",setupFunc:D3,kernelFunc:P3};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Be(n,e){let t;function r(a){t=a.wasm.cwrap(n,null,["number","number","number"])}function s(a){const{backend:o,inputs:{x:i}}=a,l=o.dataIdMap.get(i.dataId).id,c=o.makeOutput(i.shape,e||i.dtype),u=o.dataIdMap.get(c.dataId).id;return q(c.shape)===0||t(l,Ue[i.dtype],u),c}return{kernelName:n,backendName:"wasm",setupFunc:r,kernelFunc:s}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const O3=Be(ql);/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */const M3=Be(Kl);/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */const L3=Be(Xl);/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function mt(n,e,t){let r;function s(o){r=o.wasm.cwrap(n,null,["number","array","number","number","array","number","number","number"])}function a(o){const{backend:i,inputs:l}=o,{a:c,b:u}=l,d=i.dataIdMap.get(c.dataId).id,p=i.dataIdMap.get(u.dataId).id,f=t??c.dtype,m=je(c.shape,u.shape),g=i.makeOutput(m,f);if(q(m)===0)return g;const b=new Uint8Array(new Int32Array(c.shape).buffer),v=new Uint8Array(new Int32Array(u.shape).buffer),I=i.dataIdMap.get(g.dataId).id;return r(d,b,c.shape.length,p,v,u.shape.length,Ue[c.dtype],I),g}return{kernelName:n,backendName:"wasm",setupFunc:s,kernelFunc:a}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const z3=mt(di);/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let hg;function B3(n){hg=n.wasm.cwrap(pi,null,["array","number","number","number"])}function W3(n){const{inputs:e,backend:t}=n,r=t.makeOutput(e[0].shape,e[0].dtype);if(q(r.shape)===0)return r;const s=e.map(i=>t.dataIdMap.get(i.dataId).id),a=new Uint8Array(new Int32Array(s).buffer),o=t.dataIdMap.get(r.dataId).id;return hg(a,s.length,Ue[r.dtype],o),r}const V3={kernelName:pi,backendName:"wasm",setupFunc:B3,kernelFunc:W3};/** + * @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. + * ============================================================================= + */function vu(n){const{inputs:{x:e},backend:t}=n;if(e.dtype==="string")return _n(t.readSync(e.dataId),e.shape,e.dtype);const r=t.makeOutput(e.shape,e.dtype),s=t.typedArrayFromHeap(e);return t.typedArrayFromHeap(r).set(s),r}const U3={kernelName:Di,backendName:"wasm",kernelFunc:vu};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let fg;function H3(n){fg=n.wasm.cwrap(Qs,null,["number","array","number","number","number","array","number"])}function Er(n){const{inputs:e,backend:t,attrs:r}=n,[s,a]=j3(e.x.shape,r.perm);let o=!0;for(let m=0;m=s&&(a===-1||r[a]>r[o])&&(a=o);r[a]=s}return[t,r]}const q3={kernelName:Qs,backendName:"wasm",kernelFunc:Er,setupFunc:H3};/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Mr(n,e,t){const r=n.shape,s=n.shape.length,a=$t(e,r);let o=a;const i=Or(o,s);let l=null,c=!1;if(i!=null){const u=new Array(s);for(let f=0;f`new shape: ${o}, old shape: ${r.shape}. New shape and old shape must have the same number of elements.`),n.backend.incRef(r.dataId),{dataId:r.dataId,shape:o,dtype:r.dtype}}const w$={kernelName:td,backendName:"wasm",kernelFunc:Bt};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let Sg;function x$(n){Sg=n.wasm.cwrap(gi,null,["number","array","number","number","array","number","number","number","number"])}function v$(n){const{inputs:e,backend:t,attrs:r}=n,{a:s,b:a}=e,{transposeA:o,transposeB:i}=r;if(s.dtype!=="float32"||a.dtype!=="float32")throw new Error("BatchMatMul for non non-float32 tensors not yet supported.");const l=s.shape.length,c=a.shape.length,u=o?s.shape[l-2]:s.shape[l-1],d=i?a.shape[c-1]:a.shape[c-2],p=o?s.shape[l-1]:s.shape[l-2],f=i?a.shape[c-2]:a.shape[c-1],m=s.shape.slice(0,-2),g=a.shape.slice(0,-2),b=q(m),v=q(g),S=je(s.shape.slice(0,-2),a.shape.slice(0,-2)).concat([p,f]);$(u===d,()=>`Error in matMul: inner shapes (${u}) and (${d}) of Tensors with shapes ${s.shape} and ${a.shape} and transposeA=${o} and transposeB=${i} must match.`);const C=o?[b,u,p]:[b,p,u],T=i?[v,f,d]:[v,d,f],O=Bt({inputs:{x:s},backend:t,attrs:{shape:C}}),L=Bt({inputs:{x:a},backend:t,attrs:{shape:T}}),B=t.dataIdMap.get(O.dataId).id,A=t.dataIdMap.get(L.dataId).id,D=o?O.shape[2]:O.shape[1],_=i?L.shape[1]:L.shape[2],V=Math.max(b,v),H=t.makeOutput([V,D,_],O.dtype),Y=t.dataIdMap.get(H.dataId).id,X=new Uint8Array(new Int32Array(O.shape).buffer),ee=new Uint8Array(new Int32Array(L.shape).buffer);return Sg(B,X,O.shape.length,A,ee,L.shape.length,o,i,Y),t.disposeData(O.dataId),t.disposeData(L.dataId),H.shape=S,H}const S$={kernelName:gi,backendName:"wasm",setupFunc:x$,kernelFunc:v$};/** + * @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. + * ============================================================================= + */function I$(n){const e=new Float32Array(n.length);for(let t=0;t{const o=je(e,t),i=o.length,l=et(o),c=q(o),u=kr(a,c),d=e.length,p=t.length,f=et(e),m=et(t),g=Jo(e,o),b=Jo(t,o);if(g.length+b.length===0)for(let v=0;vS[L]=0);const C=sl(S,d,f),T=I.slice(-p);b.forEach(L=>T[L]=0);const O=sl(T,p,m);u[v]=n(r[C],s[O])}return[u,o]}}/** + * @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. + * ============================================================================= + */function k$(n,e,t,r){if(r==="int32"){const s=Int32Array.from(n);return[e,"int32",s]}if(r==="bool"){const s=cu([0],t),[a,o]=rn((i,l)=>i!==l?1:0)(e,[],n,s,"bool");return[o,"bool",a]}throw new Error(`Error in Cast: failed to cast ${t} to ${r}`)}/** + * @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. + * ============================================================================= + */const _$=rn(((n,e)=>n+e));/** + * @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. + * ============================================================================= + */function ma(n){return(e,t,r)=>{const s=Ar(t,e.length);for(let a=0;aMath.ceil(n));/** + * @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. + * ============================================================================= + */function Ig(n,e,t,r){const s=Ar(t,q(e));if(r&&t!=="string"){let a=0;n.forEach(o=>{const i=q(o.shape);s.set(o.vals,a),a+=i})}else{let a=0;n.forEach(o=>{const i=t==="string"?ri(o.vals):o.vals;let l=0;for(let c=0;cn===e?1:0);/** + * @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. + * ============================================================================= + */const $$=ma(n=>Math.exp(n));/** + * @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. + * ============================================================================= + */const T$=ma(n=>Math.expm1(n));/** + * @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. + * ============================================================================= + */const E$=ma(n=>Math.floor(n));/** + * @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. + * ============================================================================= + */const A$=rn((n,e)=>Math.floor(n/e));/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function R$(n,e,t,r,s,a,o,i,l){const c=ut([r,a],t);for(let u=0;u=l/a)throw new Error(`Invalid indices: ${d} does not index into ${i}`);for(let f=0;fn>e?1:0);/** + * @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. + * ============================================================================= + */const F$=rn((n,e)=>n>=e?1:0);/** + * @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. + * ============================================================================= + */const O$=rn((n,e)=>nn<=e?1:0);/** + * @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. + * ============================================================================= + */const L$=ma(n=>Math.log(n));/** + * @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. + * ============================================================================= + */function z$(n,e,t,r){const s=kr(r,q(t));for(let a=0;ai)&&(i=c)}s[a]=i}return s}/** + * @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. + * ============================================================================= + */const B$=rn(((n,e)=>Math.max(n,e)));/** + * @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. + * ============================================================================= + */const W$=rn(((n,e)=>Math.min(n,e)));/** + * @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. + * ============================================================================= + */const kg=rn(((n,e)=>n*e));/** + * @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. + * ============================================================================= + */function V$(n,e,t){const r=qw(-1,t);return kg([],e,r,n,t)}/** + * @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. + * ============================================================================= + */const U$=rn(((n,e)=>n!==e?1:0));/** + * @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. + * ============================================================================= + */function H$(n,e,t,r,s){const a=e.length,o=q(e),i=et(e),l=et(s),c=kr(t,q(s));for(let u=0;u1;if(s||a||o)return ps(0,r);const i=Math.abs(Math.ceil((e-n)/t)),l=ps(i,r);e1/Math.sqrt(n));/** + * @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. + * ============================================================================= + */function q$(n,e,t,r,s,a,o,i,l,c){const u=[r/s,s],d=n.values,p=e.values;if(r===0)return ut(t,e.dtype);const f=l instanceof ra?l:ut(u,e.dtype);typeof l=="string"||typeof l=="number"?f.values.fill(l):typeof l=="boolean"&&f.values.fill(+l);for(let m=0;m=r/s)throw new Error(`Invalid indices: ${g} does not index into ${t}`);for(let v=0;vm+e[g]);u.set(c.get(...f),...p)}return s==="string"?ug(u.values):u.values}/** + * @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. + * ============================================================================= + */function K$(n,e,t,r){const s=ut(n,e.dtype);for(let a=0;a0?0:i-l);let f=0;f+=c*this.leftPad.length;for(let I=0;II.forEach(S=>g[b++]=S);for(let I=0;I0){v(e[p+d-1]);for(let I=0;I0){let l=t[0];if(l!==0)throw new Error(`First split value must be 0, got ${l}`);for(let c=1;c=l;if(u=u&&t[c]<=r,!u)throw new Error(`Invalid split value ${t[c]}, must be in [${l}, ${r}]`);l=t[c]}if(l!==r)throw new Error(`Last split value must be data size. Expected ${r}, got ${l}`)}const a=s-1,o=Ar("int32",s);if(r===0||s===0){const l=new Array(r);for(let c=0;c<=a;++c)o[c]=0;return[l,o]}o[0]=0;for(let l=1;l<=a;++l){const c=t[l]-t[l-1];let u=0;this.nGramWidths.forEach(d=>{u+=this.getNumNGrams(c,d)}),this.preserveShort&&c>0&&u===0&&(u=1),o[l]=o[l-1]+u}const i=new Array(o[a]);for(let l=0;l{const p=t[l+1]-t[l],f=this.getNumNGrams(p,d);this.createNGrams(e,c,i,u,f,d),u+=f}),this.preserveShort&&u===o[l]){const d=t[l+1]-t[l];if(d===0)continue;const p=d+2*this.padWidth;this.createNGrams(e,c,i,u,1,p)}}return[i,o]}}function Cg(n,e,t,r,s,a,o,i){return new X$(t,r,s,a,o,i).compute(n,e)}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function Y$(n,e,t,r){if(!n.length)return;if(e.length===0){for(let a=0;an-e));/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Z$(n,e){const t=new Array(n.rank);for(let s=0;s{const t=e.value-n.value;return t===0?n.index-e.index:t};function Tg(n,e,t=0,r=n.length-1){for(;r>t;){if(r-t>600){const i=r-t+1,l=e-t+1,c=Math.log(i),u=.5*Math.exp(2*c/3),d=.5*Math.sqrt(c*u*(i-u)/i)*Math.sign(l-i/2),p=Math.max(t,Math.floor(e-l*u/i+d)),f=Math.min(r,Math.floor(e+(i-l)*u/i+d));Tg(n,e,p,f)}const s=n[e];let a=t,o=r;for(Pa(n,t,e),Ba(n[r],s)>0&&Pa(n,t,r);a0;)o=o-1}Ba(n[t],s)===0?Pa(n,t,o):(o=o+1,Pa(n,o,r)),o<=e&&(t=o+1),e<=o&&(r=o-1)}}function J$(n,e,t,r,s){const a=e[e.length-1],[o,i]=[n.length/a,a],l=kr(t,o*r),c=kr("int32",o*r);for(let d=0;dm[S]={value:I,index:S}),r{for(let b=0;bv*I),l=bu(s.shape,a,i),c=wu(l.length,a.length),u=xu(s.shape,a,i),d=sg(o,a.length),p=ag(u,o,a.length),f=Bt({inputs:{x:s},backend:t,attrs:{shape:l}}),m=Er({inputs:{x:f},backend:t,attrs:{perm:c}}),g=Bt({inputs:{x:m},backend:t,attrs:{shape:u}}),b=vs({inputs:{x:g},backend:t,attrs:{begin:d,size:p}});return t.disposeData(f.dataId),t.disposeData(m.dataId),t.disposeData(g.dataId),b}const oT={kernelName:sc,backendName:"wasm",kernelFunc:aT};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */let Ag;function iT(n){Ag=n.wasm.cwrap(yi,null,["number","number","boolean","number","number","number"])}function uT(n){const{backend:e,inputs:t,attrs:r}=n,{x:s,weights:a}=t,{size:o}=r,i=a.shape.reduce((d,p)=>d*p,1)!==0,l=s.shape.length===1?[o]:[s.shape[0],o],c=e.makeOutput(l,a.dtype);function u(d){return e.dataIdMap.get(d.dataId).id}return Ag(u(s),o,i,u(a),Ue[a.dtype],u(c)),c}const lT={kernelName:yi,backendName:"wasm",setupFunc:iT,kernelFunc:uT};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */const cT=mt(rf);/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */function dT(n){const{inputs:e,backend:t}=n,{s0:r,s1:s}=e,a=t.typedArrayFromHeap(r),o=t.typedArrayFromHeap(s),i=je(Array.from(a),Array.from(o));return t.makeOutput([i.length],"int32",void 0,new Int32Array(i))}const pT={kernelName:ac,backendName:"wasm",kernelFunc:dT};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Lr(n){const{inputs:{x:e},attrs:{dtype:t},backend:r}=n,s=r.makeOutput(e.shape,t),a=r.typedArrayFromHeap(e);return r.typedArrayFromHeap(s).set(a),s}const hT={kernelName:bi,backendName:"wasm",kernelFunc:Lr};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const fT=Be(oc);/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let Rg;function mT(n){Rg=n.wasm.cwrap(wi,null,["number","number","number","number"])}function gT(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{clipValueMin:a,clipValueMax:o}=r,i=t.dataIdMap.get(s.dataId).id,l=t.makeOutput(s.shape,s.dtype),c=t.dataIdMap.get(l.dataId).id;return Rg(i,a,o,c),l}const yT={kernelName:wi,backendName:"wasm",setupFunc:mT,kernelFunc:gT};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Dg(n){const{inputs:e,backend:t}=n,r=$t(n.attrs.axis,e[0].shape)[0],s=e.map(f=>f.shape);ng(s,r);let a=Ir(e.map(f=>f.shape),r);const o=e.filter(f=>q(f.shape)>0);if(o.length===1)return vu({inputs:{x:o[0]},backend:t});const i=t.makeOutput(a,e[0].dtype);if(q(a)===0)return i;if(o[0].dtype==="string"){const f=o.map(S=>{const T=[-1,q(S.shape.slice(r))];return Bt({inputs:{x:S},backend:t,attrs:{shape:T}})}),m=f.map(S=>({vals:t.readSync(S.dataId),shape:S.shape}));a=Ir(f.map(S=>S.shape),1);const g=f[0].shape[0]===1,b=Ig(m,a,e[0].dtype,g),v=Ir(o.map(S=>S.shape),r);i.shape=v;const I=t.dataIdMap.get(i.dataId);return I.stringBytes=ug(b),f.forEach(S=>t.disposeData(S.dataId)),i}const l=q(o[0].shape.slice(0,r));let c=0;const u=o.map(f=>{const m=q(f.shape.slice(r));return c+=m,m}),d=o.map(f=>t.typedArrayFromHeap(f)),p=t.typedArrayFromHeap(i);for(let f=0;f`cumprod does not support ${s.dtype} tensors in the WASM backend`);const c=Or([a],l);let u=s;c!==null&&(u=Er({inputs:{x:s},attrs:{perm:c},backend:t}));const d=An(1,l)[0];yn("cumprod",[d],l);const p=t.makeOutput(u.shape,u.dtype),f=u.shape[d],m=t.dataIdMap.get(u.dataId).id,g=t.dataIdMap.get(p.dataId).id;Bg(m,o?1:0,i?1:0,f,g,Ue[s.dtype]);let b=p;if(c!==null){const v=hu(c);b=Er({inputs:{x:p},attrs:{perm:v},backend:t}),t.disposeData(u.dataId),t.disposeData(p.dataId)}return b}const WT={kernelName:ki,backendName:"wasm",setupFunc:zT,kernelFunc:BT};/** + * @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. + * ============================================================================= + */let Wg;function VT(n){Wg=n.wasm.cwrap(_i,null,["number","number","number","number","number","number"])}function UT(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{axis:a,exclusive:o,reverse:i}=r,l=s.shape.length;$(s.dtype==="float32"||s.dtype==="int32",()=>`cumsum does not support ${s.dtype} tensors in the WASM backend`);const c=Or([a],l);let u=s;c!==null&&(u=Er({inputs:{x:s},attrs:{perm:c},backend:t}));const d=An(1,l)[0];yn("cumsum",[d],l);const p=t.makeOutput(u.shape,u.dtype),f=u.shape[d],m=t.dataIdMap.get(u.dataId).id,g=t.dataIdMap.get(p.dataId).id;Wg(m,o?1:0,i?1:0,f,g,Ue[s.dtype]);let b=p;if(c!==null){const v=hu(c);b=Er({inputs:{x:p},attrs:{perm:v},backend:t}),t.disposeData(u.dataId),t.disposeData(p.dataId)}return b}const HT={kernelName:_i,backendName:"wasm",setupFunc:VT,kernelFunc:UT};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */let Vg;function GT(n){Vg=n.wasm.cwrap("DenseBincount",null,["number","array","number","number","boolean","number","number","boolean","number"])}function jT(n){const{backend:e,inputs:t,attrs:r}=n,{x:s,weights:a}=t,{size:o,binaryOutput:i}=r,l=a.shape.reduce((p,f)=>p*f,1)!==0,c=s.shape.length===1?[o]:[s.shape[0],o],u=e.makeOutput(c,a.dtype);function d(p){return e.dataIdMap.get(p.dataId).id}return Vg(d(s),new Uint8Array(new Int32Array(s.shape).buffer),s.shape.length,o,l,d(a),Ue[a.dtype],i,d(u)),u}const qT={kernelName:dc,backendName:"wasm",setupFunc:GT,kernelFunc:jT};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let Ug;function KT(n){Ug=n.wasm.cwrap(Ni,null,["number","number","number","array","number","array","array","number","number"])}function XT(n){const{backend:e,inputs:t,attrs:r}=n,{x:s}=t,{blockSize:a,dataFormat:o}=r,i=s.shape[0],l=o==="NHWC"?s.shape[1]:s.shape[2],c=o==="NHWC"?s.shape[2]:s.shape[3],u=o==="NHWC"?s.shape[3]:s.shape[1],d=l*a,p=c*a,f=u/(a*a),m=o==="NHWC"?[i,d,p,f]:[i,f,d,p],g=e.makeOutput(m,"float32"),v=e.dataIdMap.get(s.dataId).id,I=new Uint8Array(new Int32Array(et(s.shape)).buffer),S=new Uint8Array(new Int32Array(m).buffer),C=new Uint8Array(new Int32Array(et(m)).buffer),T=e.dataIdMap.get(g.dataId).id;return Ug(v,a,o==="NHWC"?1:0,I,s.shape.length-1,S,C,m.length,T),g}const YT={kernelName:Ni,backendName:"wasm",setupFunc:KT,kernelFunc:XT};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let Hg;function QT(n){Hg=n.wasm.cwrap($i,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function ZT(n){const{inputs:e,attrs:t,backend:r}=n,{x:s,filter:a}=e,o=r.dataIdMap.get(s.dataId).id,i=r.dataIdMap.get(a.dataId).id,{strides:l,dilations:c,pad:u,dimRoundingMode:d}=t,p=c??[1,1],f=Tt(s.shape,a.shape,l,p,u,d,!0),m=f.filterHeight,g=f.filterWidth,b=f.padInfo.top,v=f.padInfo.right,I=f.padInfo.bottom,S=f.padInfo.left,C=f.dilationHeight,T=f.dilationWidth,O=f.strideHeight,L=f.strideWidth,B=f.inChannels,A=f.outChannels,D=f.padInfo.type==="SAME"?1:0;if(f.dataFormat!=="channelsLast")throw new Error(`wasm backend DepthwiseConv2dNative does not support dataFormat:'${f.dataFormat}'. Please use 'channelsLast'.`);const _=r.makeOutput(f.outShape,"float32"),V=r.dataIdMap.get(_.dataId).id;return Hg(o,s.shape[0],s.shape[1],s.shape[2],i,m,g,b,v,I,S,D,C,T,O,L,B,A,V),_}const JT={kernelName:$i,backendName:"wasm",setupFunc:QT,kernelFunc:ZT};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */let Gg;function eE(n){Gg=n.wasm.cwrap("Diag",null,["number","number","number","number"])}function tE(n){const{inputs:e,backend:t}=n,{x:r}=e,s=q(r.shape),a=t.makeOutput([...r.shape,...r.shape],r.dtype);return Gg(t.dataIdMap.get(r.dataId).id,Ue[r.dtype],s,t.dataIdMap.get(a.dataId).id),a}const nE={kernelName:pc,backendName:"wasm",setupFunc:eE,kernelFunc:tE};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */let jg;function rE(n){jg=n.wasm.cwrap(Ti,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function sE(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,filter:a}=e,{strides:o,pad:i,dilations:l}=r;if(s.dtype!==a.dtype)throw new Error(`Dilation2D error: x must have the same dtype as filter. Got ${s.dtype} and ${a.dtype}`);const c=pa(s.shape,a.shape,o,i,"NHWC",l),u=t.makeOutput(c.outShape,s.dtype);return jg(t.dataIdMap.get(s.dataId).id,t.dataIdMap.get(a.dataId).id,t.dataIdMap.get(u.dataId).id,Ue[s.dtype],c.batchSize,c.inChannels,c.inHeight,c.inWidth,c.outHeight,c.outWidth,c.strideHeight,c.strideWidth,c.dilationHeight,c.dilationWidth,c.filterHeight,c.filterWidth,c.padInfo.top,c.padInfo.left),u}const aE={kernelName:Ti,backendName:"wasm",setupFunc:rE,kernelFunc:sE};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */let qg;function oE(n){qg=n.wasm.cwrap(fc,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function iE(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,filter:a,dy:o}=e,{strides:i,pad:l,dilations:c}=r;if(s.dtype!==a.dtype||s.dtype!==o.dtype)throw new Error(`Dilation2DBackpropFilter error: x must have the same dtype as filter and dy. Got ${s.dtype}, ${a.dtype}, and ${o.dtype}`);const u=pa(s.shape,a.shape,i,l,"NHWC",c),d=t.makeOutput(a.shape,a.dtype);return qg(t.dataIdMap.get(s.dataId).id,t.dataIdMap.get(a.dataId).id,t.dataIdMap.get(o.dataId).id,t.dataIdMap.get(d.dataId).id,Ue[s.dtype],u.batchSize,u.inChannels,u.inHeight,u.inWidth,u.outHeight,u.outWidth,u.strideHeight,u.strideWidth,u.dilationHeight,u.dilationWidth,u.filterHeight,u.filterWidth,u.padInfo.top,u.padInfo.left),d}const uE={kernelName:fc,backendName:"wasm",setupFunc:oE,kernelFunc:iE};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */let Kg;function lE(n){Kg=n.wasm.cwrap(hc,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function cE(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,filter:a,dy:o}=e,{strides:i,pad:l,dilations:c}=r;if(s.dtype!==a.dtype||s.dtype!==o.dtype)throw new Error(`Dilation2DBackpropInput error: x must have the same dtype as filter and dy. Got ${s.dtype}, ${a.dtype}, and ${o.dtype}`);const u=pa(s.shape,a.shape,i,l,"NHWC",c),d=t.makeOutput(s.shape,s.dtype);return Kg(t.dataIdMap.get(s.dataId).id,t.dataIdMap.get(a.dataId).id,t.dataIdMap.get(o.dataId).id,t.dataIdMap.get(d.dataId).id,Ue[s.dtype],u.batchSize,u.inChannels,u.inHeight,u.inWidth,u.outHeight,u.outWidth,u.strideHeight,u.strideWidth,u.dilationHeight,u.dilationWidth,u.filterHeight,u.filterWidth,u.padInfo.top,u.padInfo.left),d}const dE={kernelName:hc,backendName:"wasm",setupFunc:lE,kernelFunc:cE};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const pE=Be(gc);/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */let Xg;function hE(n){Xg=n.wasm.cwrap(yc,null,["number","number","number"])}function fE(n){const{inputs:e,backend:t}=n,{dy:r,y:s}=e,a=t.makeOutput(s.shape,"float32"),o=i=>t.dataIdMap.get(i.dataId).id;return Xg(o(s),o(r),o(a)),a}const mE={kernelName:yc,backendName:"wasm",setupFunc:hE,kernelFunc:fE};/** + * @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. + * ============================================================================= + */const gE=!1,yE=mt(wc,gE,"bool");/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */const bE=Be(bc);/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const wE=Be(xc,"float32");/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Fl(n){const{inputs:e,attrs:t,backend:r}=n,{input:s}=e,{dim:a}=t,o=s.shape.length,i=s.shape.slice();let l=a;return a<0&&($(-(o+1)<=a,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),l=o+a+1),i.splice(l,0,1),Bt({inputs:{x:s},backend:r,attrs:{shape:i}})}const xE={kernelName:vc,backendName:"wasm",kernelFunc:Fl};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */const vE=Be(Sc,"float32");/** + * @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. + * ============================================================================= + */function Yg(n){const{attrs:{shape:e,value:t},backend:r}=n;let{attrs:{dtype:s}}=n;s=s||da(t);const a=r.makeOutput(e,s);return r.typedArrayFromHeap(a).fill(t),a}const SE={kernelName:Ic,backendName:"wasm",kernelFunc:Yg};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let Qg;function IE(n){Qg=n.wasm.cwrap(Ei,null,["number","number","number","number","number","number"])}function kE(n){const{inputs:e,backend:t}=n,{image:r}=e,s=t.makeOutput(r.shape,r.dtype),a=t.dataIdMap.get(r.dataId).id,o=t.dataIdMap.get(s.dataId).id,[i,l,c,u]=r.shape;return Qg(a,i,l,c,u,o),s}const _E={kernelName:Ei,backendName:"wasm",kernelFunc:kE,setupFunc:IE};/** + * @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. + * ============================================================================= + */const CE=Be(kc);/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const NE=mt(_c);/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let Zg;function $E(n){Zg=n.wasm.cwrap(Ai,null,["number","number","number","number","number","number","number"])}function TE(n){const{backend:e,inputs:t,attrs:r}=n,{varianceEpsilon:s}=r,{x:a,mean:o,variance:i,offset:l,scale:c}=t,u=e.dataIdMap.get(a.dataId).id,d=e.dataIdMap.get(o.dataId).id,p=e.dataIdMap.get(i.dataId).id,f=l!=null?e.dataIdMap.get(l.dataId).id:0,m=c!=null?e.dataIdMap.get(c.dataId).id:0,g=e.makeOutput(a.shape,a.dtype);if(q(a.shape)===0)return g;const b=e.dataIdMap.get(g.dataId).id;return Zg(u,d,p,f,m,s,b),g}const EE={kernelName:Ai,backendName:"wasm",setupFunc:$E,kernelFunc:TE};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let Jg;function AE(n){Jg=n.wasm.cwrap(Xa,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function RE(n){const{inputs:e,attrs:t,backend:r}=n,{x:s,filter:a,bias:o,preluActivationWeights:i}=e,{strides:l,pad:c,dilations:u,dataFormat:d,dimRoundingMode:p,activation:f,leakyreluAlpha:m}=t,g=Tt(s.shape,a.shape,l,u,c,p),b=oo[f];if(b==null)throw new Error(`${f} activation not yet supported for FusedConv2D in the wasm backend.`);const v=r.dataIdMap.get(s.dataId).id,I=r.dataIdMap.get(a.dataId).id,S=g.outChannels;let C=0;if(o!=null){const Oe=r.dataIdMap.get(o.dataId);if(Oe.shape.length!==1)throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${Oe.shape.length}.`);if(Oe.shape[0]!==S)throw new Error(`FusedConv2D bias shape (${Oe.shape}) does not match the number of output channels (${S})`);C=Oe.id}const T=g.filterHeight,O=g.filterWidth,L=g.padInfo.top,B=g.padInfo.right,A=g.padInfo.bottom,D=g.padInfo.left,_=g.dilationHeight,V=g.dilationWidth,H=g.strideHeight,Y=g.strideWidth,X=g.inChannels,ee=g.padInfo.type==="SAME"?1:0,ye=g.batchSize,ce=g.inHeight,be=g.inWidth;if(d!=="NHWC")throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${d}'. Please use 'NHWC'.`);const Se=r.makeOutput(g.outShape,"float32"),Pe=r.dataIdMap.get(Se.dataId).id,Ve=i==null?0:r.dataIdMap.get(i.dataId).id;return Jg(v,ye,ce,be,I,T,O,C,L,B,A,D,ee,_,V,H,Y,X,S,b,Ve,m||0,Pe),Se}const DE={kernelName:Xa,backendName:"wasm",setupFunc:AE,kernelFunc:RE};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let ey;function PE(n){ey=n.wasm.cwrap(Ya,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function FE(n){const{inputs:e,attrs:t,backend:r}=n,{x:s,filter:a,bias:o,preluActivationWeights:i}=e,{strides:l,pad:c,dilations:u,dataFormat:d,dimRoundingMode:p,activation:f,leakyreluAlpha:m}=t,g=Tt(s.shape,a.shape,l,u,c,p,!0),b=oo[f];if(b==null)throw new Error(`${f} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`);const v=r.dataIdMap.get(s.dataId).id,I=r.dataIdMap.get(a.dataId).id,S=g.outChannels;let C=0;if(o!=null){const Oe=r.dataIdMap.get(o.dataId);if(Oe.shape.length!==1)throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${Oe.shape.length}.`);if(Oe.shape[0]!==S)throw new Error(`FusedDepthwiseConv2D bias shape (${Oe.shape}) does not match the number of output channels (${S})`);C=Oe.id}const T=g.filterHeight,O=g.filterWidth,L=g.padInfo.top,B=g.padInfo.right,A=g.padInfo.bottom,D=g.padInfo.left,_=g.dilationHeight,V=g.dilationWidth,H=g.strideHeight,Y=g.strideWidth,X=g.inChannels,ee=g.padInfo.type==="SAME"?1:0,ye=g.batchSize,ce=g.inHeight,be=g.inWidth;if(d!=="NHWC")throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${d}'. Please use 'NHWC'.`);const Se=r.makeOutput(g.outShape,"float32"),Pe=r.dataIdMap.get(Se.dataId).id,Ve=i==null?0:r.dataIdMap.get(i.dataId).id;return ey(v,ye,ce,be,I,T,O,C,L,B,A,D,ee,_,V,H,Y,X,S,b,Ve,m||0,Pe),Se}const OE={kernelName:Ya,backendName:"wasm",setupFunc:PE,kernelFunc:FE};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let ty;function ME(n){ty=n.wasm.cwrap(Ri,null,["number","number","number","number","number","number","array","number"])}function LE(n){const{backend:e,inputs:t}=n,{params:r,indices:s}=t,[a,o,i,l]=Ym(r,s),c=e.makeOutput(a,r.dtype);if(o===0)return c;const u=s.shape,d=u[u.length-1],f=e.dataIdMap.get(r.dataId).id,g=e.dataIdMap.get(s.dataId).id,b=new Uint8Array(new Int32Array(l).buffer),v=e.dataIdMap.get(c.dataId).id;return ty(f,Ue[r.dtype],g,o,d,i,b,v),c}const zE={kernelName:Ri,backendName:"wasm",setupFunc:ME,kernelFunc:LE};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let ny;function BE(n){ny=n.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])}function WE(n){const{backend:e,inputs:t,attrs:r}=n,{x:s,indices:a}=t,{axis:o,batchDims:i}=r,l=$t(o,s.shape)[0],c=e.readSync(a.dataId),u=s.shape[l];for(let A=0;A=0,()=>`GatherV2: the index value ${D} is not in [0, ${u-1}]`)}const d=ig(s,a,l,i),p=Bt({inputs:{x:s},attrs:{shape:[d.batchSize,d.outerSize,d.dimSize,d.sliceSize]},backend:e}),f=q(a.shape),m=Bt({inputs:{x:a},attrs:{shape:[d.batchSize,f/d.batchSize]},backend:e}),g=[d.batchSize,d.outerSize,f/d.batchSize,d.sliceSize],b=e.makeOutput(g,s.dtype);if(q(s.shape)===0)return b;const v=p.shape.length-1,S=e.dataIdMap.get(p.dataId).id,T=e.dataIdMap.get(m.dataId).id,O=e.dataIdMap.get(b.dataId).id,L=new Uint8Array(new Int32Array(et(p.shape)).buffer),B=new Uint8Array(new Int32Array(et(g)).buffer);return ny(S,Ue[s.dtype],L,v,T,d.batchSize,B,O),e.disposeData(p.dataId),e.disposeData(m.dataId),b.shape=d.outputShape,b}const VE={kernelName:Cc,backendName:"wasm",setupFunc:BE,kernelFunc:WE};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const UE=!1,HE=mt(Nc,UE,"bool");/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const GE=!1,jE=mt($c,GE,"bool");/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */const qE=Be(Tc,"bool");/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */const KE=Be(Ec,"bool");/** + * @license + * Copyright 2022 The TensorFlow Authors. 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. + * ============================================================================= + */const XE=Be(Ac,"bool");/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let ry;function YE(n){ry=n.wasm.cwrap(Pi,null,["number","number","number","number"])}function QE(n){const{inputs:{x:e},attrs:{alpha:t},backend:r}=n,s=r.dataIdMap.get(e.dataId).id,a=r.makeOutput(e.shape,"float32");if(q(e.shape)!==0){const o=r.dataIdMap.get(a.dataId).id;ry(s,Ue[e.dtype],t,o)}return a}const ZE={kernelName:Pi,backendName:"wasm",setupFunc:YE,kernelFunc:QE};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const JE=!1,eA=mt(Rc,JE,"bool");/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const tA=!1,nA=mt(Dc,tA,"bool");/** + * @license + * Copyright 2023 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. + * ============================================================================= + */let sy;function rA(n){sy=n.wasm.cwrap(Fi,null,["number","number","number","number"])}function sA(n){const{attrs:e,backend:t}=n,{start:r,stop:s,num:a}=e,o=Math.floor(a),i=t.makeOutput([o],"float32");return sy(t.dataIdMap.get(i.dataId).id,r,s,o),i}const aA={kernelName:Fi,backendName:"wasm",setupFunc:rA,kernelFunc:sA};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const oA=Be(Pc);/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */const iA=Be(Fc);/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const uA=!1,lA=mt(Oc,uA,"bool");/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const cA=Be(Mc);/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const dA=!1,pA=mt(Lc,dA,"bool");/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const hA=!1,fA=mt(Dw,hA,"bool");/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */let ay;function mA(n){ay=n.wasm.cwrap(Oi,null,["number","number","number","number","number","number","number"])}function gA(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{depthRadius:a,bias:o,alpha:i,beta:l}=r;if(s.dtype!=="float32")throw new Error("LRN error: x must have dtype float32");const c=t.makeOutput(s.shape,s.dtype);return ay(t.dataIdMap.get(s.dataId).id,t.dataIdMap.get(c.dataId).id,s.shape[3],a,o,i,l),c}const yA={kernelName:Oi,backendName:"wasm",setupFunc:mA,kernelFunc:gA};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */let oy;function bA(n){oy=n.wasm.cwrap(zc,null,["number","number","number","number","number","number","number","number","number"])}function wA(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,y:a,dy:o}=e,{depthRadius:i,bias:l,alpha:c,beta:u}=r;if(s.dtype!=="float32"||a.dtype!=="float32"||o.dtype!=="float32")throw new Error("LRNGrad error: x, y, and dy must have dtype float32");const d=t.makeOutput(s.shape,s.dtype);return oy(t.dataIdMap.get(s.dataId).id,t.dataIdMap.get(a.dataId).id,t.dataIdMap.get(o.dataId).id,t.dataIdMap.get(d.dataId).id,o.shape[3],i,l,c,u),d}const xA={kernelName:zc,backendName:"wasm",setupFunc:bA,kernelFunc:wA};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let iy;function vA(n){iy=n.wasm.cwrap(Mi,null,["number","number","number","number"])}function SA(n){const{backend:e,inputs:t,attrs:r}=n,{reductionIndices:s,keepDims:a}=r,{x:o}=t;let l=e.dataIdMap.get(o.dataId).id,c=o;const{transposed:u,axes:d,originalAxes:p,inputWasTransposed:f}=Mr(o,s,e);if(f){const S=e.dataIdMap.get(u.dataId).id;c=u,l=S}const m=c.shape.length;yn("max",d,m);const[g,b]=En(c.shape,d),v=q(b),I=e.makeOutput(g,o.dtype);if(q(c.shape)!==0){const S=e.dataIdMap.get(I.dataId).id;iy(l,Ue[o.dtype],v,S)}if(f&&e.disposeData(u.dataId),a){const S=gn(I.shape,p);I.shape=S}return I}const IA={kernelName:Mi,backendName:"wasm",setupFunc:vA,kernelFunc:SA};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const kA=mt(Bc);/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let uy;function _A(n){uy=n.wasm.cwrap(Li,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function CA(n){const{inputs:e,attrs:t,backend:r}=n,s=e.x,a=r.dataIdMap.get(s.dataId).id;$(s.dtype==="float32",()=>`Error in MaxPool: only float32 input is supported. Got ${s.dtype}.`);const{filterSize:o,strides:i,pad:l,dimRoundingMode:c}=t,u=Nn(s.shape,o,i,1,l,c),d=u.filterHeight,p=u.filterWidth,f=u.padInfo.top,m=u.padInfo.right,g=u.padInfo.bottom,b=u.padInfo.left,v=u.dilationHeight,I=u.dilationWidth,S=u.strideHeight,C=u.strideWidth,T=u.inChannels,O=u.outChannels;if(u.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${u.dataFormat}'. Please use 'channelsLast'.`);const L=r.makeOutput(u.outShape,"float32"),B=r.dataIdMap.get(L.dataId).id;return uy(a,s.shape[0],s.shape[1],s.shape[2],d,p,f,m,g,b,v,I,S,C,T,O,B),L}const NA={kernelName:Li,backendName:"wasm",setupFunc:_A,kernelFunc:CA};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */let ly;function $A(n){ly=n.wasm.cwrap("MaxPool3D",null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function TA(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{filterSize:a,strides:o,pad:i,dimRoundingMode:l,dataFormat:c}=r,u=Pr(s.shape,a,o,1,i,l,c),d=t.makeOutput(u.outShape,s.dtype);return ly(t.dataIdMap.get(s.dataId).id,t.dataIdMap.get(d.dataId).id,u.batchSize,u.inChannels,u.inDepth,u.inHeight,u.inWidth,u.outDepth,u.outHeight,u.outWidth,u.strideDepth,u.strideHeight,u.strideWidth,u.dilationDepth,u.dilationHeight,u.dilationWidth,u.effectiveFilterDepth,u.effectiveFilterHeight,u.effectiveFilterWidth,u.padInfo.front,u.padInfo.top,u.padInfo.left),d}const EA={kernelName:Wc,backendName:"wasm",setupFunc:$A,kernelFunc:TA};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */let cy;function AA(n){cy=n.wasm.cwrap("MaxPool3DGrad",null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function RA(n){const{inputs:e,backend:t,attrs:r}=n,{dy:s,input:a}=e,{filterSize:o,strides:i,pad:l,dimRoundingMode:c}=r,u=Pr(a.shape,o,i,1,l,c),d=t.makeOutput(a.shape,a.dtype);return cy(t.dataIdMap.get(a.dataId).id,t.dataIdMap.get(s.dataId).id,t.dataIdMap.get(d.dataId).id,u.batchSize,u.inChannels,u.inDepth,u.inHeight,u.inWidth,u.outDepth,u.outHeight,u.outWidth,u.strideDepth,u.strideHeight,u.strideWidth,u.dilationDepth,u.dilationHeight,u.dilationWidth,u.effectiveFilterDepth,u.effectiveFilterHeight,u.effectiveFilterWidth,u.padInfo.front,u.padInfo.top,u.padInfo.left),d}const DA={kernelName:gf,backendName:"wasm",setupFunc:AA,kernelFunc:RA};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */let dy;function PA(n){dy=n.wasm.cwrap("MaxPoolGrad",null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function FA(n){const{inputs:e,backend:t,attrs:r}=n,{dy:s,input:a}=e,{filterSize:o,strides:i,pad:l,dimRoundingMode:c}=r,u=Nn(a.shape,o,i,1,l,c),d=t.makeOutput(a.shape,a.dtype);return dy(t.dataIdMap.get(a.dataId).id,t.dataIdMap.get(s.dataId).id,t.dataIdMap.get(d.dataId).id,u.batchSize,u.inChannels,u.inHeight,u.inWidth,u.outHeight,u.outWidth,u.strideHeight,u.strideWidth,u.dilationHeight,u.dilationWidth,u.effectiveFilterHeight,u.effectiveFilterWidth,u.padInfo.top,u.padInfo.left),d}const OA={kernelName:mf,backendName:"wasm",setupFunc:PA,kernelFunc:FA};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */let py;function MA(n){py=n.wasm.cwrap("MaxPoolWithArgmax",null,["number","number","number","number","boolean","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function LA(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{filterSize:a,strides:o,pad:i,includeBatchInIndex:l}=r;$(s.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${s.shape.length}.`);const c=[1,1];$($n(o,c),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`);const u=Nn(s.shape,a,o,[1,1],i),d=t.makeOutput(u.outShape,s.dtype),p=t.makeOutput(u.outShape,"int32");return py(t.dataIdMap.get(s.dataId).id,t.dataIdMap.get(d.dataId).id,t.dataIdMap.get(p.dataId).id,Ue[s.dtype],l,u.batchSize,u.inChannels,u.inHeight,u.inWidth,u.outHeight,u.outWidth,u.strideHeight,u.strideWidth,u.dilationHeight,u.dilationWidth,u.effectiveFilterHeight,u.effectiveFilterWidth,u.padInfo.top,u.padInfo.left),[d,p]}const zA={kernelName:Vc,backendName:"wasm",setupFunc:MA,kernelFunc:LA};/** + * @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. + * ============================================================================= + */let hy;function BA(n){hy=n.wasm.cwrap(zi,null,["number, number, number"])}function WA(n){const{backend:e,inputs:t,attrs:r}=n,{axis:s,keepDims:a}=r,{x:o}=t,i=e.dataIdMap.get(o.dataId).id;let l=i,c=o;const{transposed:u,axes:d,originalAxes:p,inputWasTransposed:f}=Mr(o,s,e);let m=d;if(f){const C=e.dataIdMap.get(u.dataId).id;C!==i&&(c=u,l=C,m=An(m.length,c.shape.length))}yn("mean",m,c.shape.length);const[g,b]=En(c.shape,m),v=q(b);let I=c;c.dtype!=="float32"&&(I=Lr({backend:e,inputs:{x:c},attrs:{dtype:"float32"}}),l=e.dataIdMap.get(I.dataId).id);const S=e.makeOutput(g,"float32");if(q(c.shape)!==0){const C=e.dataIdMap.get(S.dataId).id;hy(l,v,C)}if(f&&e.disposeData(u.dataId),a){const C=gn(S.shape,p);S.shape=C}return c.dtype!=="float32"&&e.disposeData(I.dataId),S}const VA={kernelName:zi,backendName:"wasm",setupFunc:BA,kernelFunc:WA};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let fy;function UA(n){fy=n.wasm.cwrap(Bi,null,["number","number","number","number"])}function HA(n){const{backend:e,inputs:t,attrs:r}=n,{axis:s,keepDims:a}=r,{x:o}=t,i=e.dataIdMap.get(o.dataId).id;let l=i,c=o;const{transposed:u,axes:d,originalAxes:p,inputWasTransposed:f}=Mr(o,s,e);if(f){const S=e.dataIdMap.get(u.dataId).id;S!==i&&(c=u,l=S)}const m=c.shape.length;yn("min",d,m);const[g,b]=En(c.shape,d),v=q(b),I=e.makeOutput(g,c.dtype);if(q(c.shape)!==0){const S=e.dataIdMap.get(I.dataId).id;fy(l,Ue[o.dtype],v,S)}if(f&&e.disposeData(u.dataId),a){const S=gn(I.shape,p);I.shape=S}return I}const GA={kernelName:Bi,backendName:"wasm",setupFunc:UA,kernelFunc:HA};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const jA=mt(Uc);/** + * @license + * Copyright 2021 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 Ol;(function(n){n[n.reflect=0]="reflect",n[n.symmetric=1]="symmetric"})(Ol||(Ol={}));let my;function qA(n){my=n.wasm.cwrap(Wi,null,["number","array","number","number","array","array","number","number"])}function KA(n){const{inputs:{x:e},backend:t,attrs:{paddings:r,mode:s}}=n,a=r.map((m,g)=>m[0]+e.shape[g]+m[1]),o=t.dataIdMap.get(e.dataId).id,i=t.makeOutput(a,e.dtype),l=t.dataIdMap.get(i.dataId).id,c=new Uint8Array(new Int32Array(e.shape).buffer),u=r.map(m=>m[0]),d=r.map(m=>m[1]),p=new Uint8Array(new Int32Array(u).buffer),f=new Uint8Array(new Int32Array(d).buffer);return my(o,c,e.shape.length,Ue[e.dtype],p,f,Ol[s],l),i}const XA={kernelName:Wi,backendName:"wasm",kernelFunc:KA,setupFunc:qA};/** + * @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. + * ============================================================================= + */let gy;function YA(n){gy=n.wasm.cwrap(nu,null,["number","number","number","number"])}function yy(n){const{backend:e,inputs:{logits:t},attrs:{dim:r}}=n,s=e.dataIdMap.get(t.dataId).id,a=e.makeOutput(t.shape,t.dtype),o=e.dataIdMap.get(a.dataId).id,i=t.shape[r],l=q(t.shape)/i;return q(a.shape)===0||gy(s,o,i,l),a}const QA={kernelName:nu,backendName:"wasm",setupFunc:YA,kernelFunc:yy};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */let by;function ZA(n){by=n.wasm.cwrap(Vi,null,["number","number","number","number","number","number"])}function JA(n){const{inputs:e,backend:t,attrs:r}=n,{logits:s}=e,{numSamples:a,seed:o,normalized:i}=r;if(s.dtype!=="float32")throw new Error(`Tensor logits must have dtype float32, got ${s.dtype}`);const l=i?s:yy({inputs:{logits:s},backend:t,attrs:{dim:s.shape.length-1}}),[c,u]=l.shape,d=t.makeOutput([c,a],"int32");return by(t.dataIdMap.get(l.dataId).id,c,u,a,o,t.dataIdMap.get(d.dataId).id),i||t.disposeData(l.dataId),d}const eR={kernelName:Vi,backendName:"wasm",setupFunc:ZA,kernelFunc:JA};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */const tR=mt(Hc);/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const nR=mt(Gc);/** + * @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. + * ============================================================================= + */const rR=Be(jc);/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Xd(n,e){const t=new Int32Array(n.wasm.HEAPU8.buffer,e,4),r=t[0],s=t[1],a=t[2],o=t[3];return n.wasm._free(e),{pSelectedIndices:r,selectedSize:s,pSelectedScores:a,pValidOutputs:o}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let wy;function sR(n){wy=n.wasm.cwrap(Ui,"number",["number","number","number","number","number"])}function aR(n){const{backend:e,inputs:t,attrs:r}=n,{iouThreshold:s,maxOutputSize:a,scoreThreshold:o}=r,{boxes:i,scores:l}=t,c=e.dataIdMap.get(i.dataId).id,u=e.dataIdMap.get(l.dataId).id,d=wy(c,u,a,s,o),{pSelectedIndices:p,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=Xd(e,d);return e.wasm._free(m),e.wasm._free(g),e.makeOutput([f],"int32",p)}const oR={kernelName:Ui,backendName:"wasm",setupFunc:sR,kernelFunc:aR};/** + * @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. + * ============================================================================= + */let xy;function iR(n){xy=n.wasm.cwrap(Kc,"number",["number","number","number","number","number","bool"])}function uR(n){const{backend:e,inputs:t,attrs:r}=n,{iouThreshold:s,maxOutputSize:a,scoreThreshold:o,padToMaxOutputSize:i}=r,{boxes:l,scores:c}=t,u=e.dataIdMap.get(l.dataId).id,d=e.dataIdMap.get(c.dataId).id,p=xy(u,d,a,s,o,i),{pSelectedIndices:f,selectedSize:m,pSelectedScores:g,pValidOutputs:b}=Xd(e,p);e.wasm._free(g);const v=e.makeOutput([m],"int32",f),I=e.makeOutput([],"int32",b);return[v,I]}const lR={kernelName:Kc,backendName:"wasm",setupFunc:iR,kernelFunc:uR};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let vy;function cR(n){vy=n.wasm.cwrap(Hi,"number",["number","number","number","number","number","number"])}function dR(n){const{backend:e,inputs:t,attrs:r}=n,{iouThreshold:s,maxOutputSize:a,scoreThreshold:o,softNmsSigma:i}=r,{boxes:l,scores:c}=t,u=e.dataIdMap.get(l.dataId).id,d=e.dataIdMap.get(c.dataId).id,p=vy(u,d,a,s,o,i),{pSelectedIndices:f,selectedSize:m,pSelectedScores:g,pValidOutputs:b}=Xd(e,p);e.wasm._free(b);const v=e.makeOutput([m],"int32",f),I=e.makeOutput([m],"float32",g);return[v,I]}const pR={kernelName:Hi,backendName:"wasm",setupFunc:cR,kernelFunc:dR};/** + * @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. + * ============================================================================= + */const hR=!1,fR=mt(qc,hR,"bool");/** + * @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. + * ============================================================================= + */let Sy;function mR(n){Sy=n.wasm.cwrap(Gi,null,["number","number","number","number","number"])}function gR(n){const{inputs:e,backend:t,attrs:r}=n,{indices:s}=e,{dtype:a,depth:o,onValue:i,offValue:l}=r,c=t.makeOutput([...s.shape,o],a),u=t.dataIdMap.get(c.dataId).id,p=t.dataIdMap.get(s.dataId).id;return Sy(p,o,i,l,u),c}const yR={kernelName:Gi,backendName:"wasm",setupFunc:mR,kernelFunc:gR};/** + * @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. + * ============================================================================= + */function bR(n){const{inputs:{x:e},backend:t}=n,r=t.makeOutput(e.shape,e.dtype);return t.typedArrayFromHeap(r).fill(1),r}const wR={kernelName:Xc,backendName:"wasm",kernelFunc:bR};/** + * @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. + * ============================================================================= + */function xR(n){const{inputs:e,backend:t,attrs:r}=n,{axis:s}=r;if(e.length===1)return Fl({inputs:{input:e[0]},backend:t,attrs:{dim:s}});const a=e[0].shape,o=e[0].dtype;e.forEach(u=>{Yt(a,u.shape,"All tensors passed to stack must have matching shapes"),$(o===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});const i=[],l=e.map(u=>{const d=Fl({inputs:{input:u},backend:t,attrs:{dim:s}});return i.push(d),d}),c=Dg({inputs:l,backend:t,attrs:{axis:s}});return i.forEach(u=>t.disposeData(u.dataId)),c}const vR={kernelName:Yc,backendName:"wasm",kernelFunc:xR};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let Iy;function SR(n){Iy=n.wasm.cwrap(ji,null,["number","array","number","number","array","array","number","number"])}function IR(n){const{inputs:{x:e},backend:t,attrs:{paddings:r,constantValue:s}}=n,a=r.map((g,b)=>g[0]+e.shape[b]+g[1]);if(q(e.shape)===0)return Yg({backend:t,attrs:{shape:a,value:s,dtype:e.dtype}});const o=t.dataIdMap.get(e.dataId).id,i=t.makeOutput(a,e.dtype),c=t.dataIdMap.get(i.dataId).id,u=new Uint8Array(new Int32Array(e.shape).buffer),d=r.map(g=>g[0]),p=r.map(g=>g[1]),f=new Uint8Array(new Int32Array(d).buffer),m=new Uint8Array(new Int32Array(p).buffer);return Iy(o,u,e.shape.length,Ue[e.dtype],f,m,s,c),i}const ky={kernelName:ji,backendName:"wasm",kernelFunc:IR,setupFunc:SR};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const kR=mt(Qc);/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let _y;function _R(n){_y=n.wasm.cwrap(qi,null,["number","number","number"])}function CR(n){const{inputs:e,backend:t}=n,{x:r,alpha:s}=e,a=t.dataIdMap.get(r.dataId).id,o=t.dataIdMap.get(s.dataId).id;let i=a;const l=r;let c=l;l.dtype!=="float32"&&(c=Lr({backend:t,inputs:{x:r},attrs:{dtype:"float32"}}),i=t.dataIdMap.get(c.dataId).id);const u=t.makeOutput(r.shape,"float32"),d=t.dataIdMap.get(u.dataId).id;return _y(i,o,d),l.dtype!=="float32"&&t.disposeData(c.dataId),u}const NR={kernelName:qi,backendName:"wasm",setupFunc:_R,kernelFunc:CR};/** + * @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. + * ============================================================================= + */let Cy;function $R(n){Cy=n.wasm.cwrap(Ki,null,["number","number","number","number"])}function TR(n){const{backend:e,inputs:t,attrs:r}=n,{axis:s,keepDims:a}=r,{x:o}=t,i=e.dataIdMap.get(o.dataId).id;let l=i,c=o;const{transposed:u,axes:d,originalAxes:p,inputWasTransposed:f}=Mr(o,s,e);let m=d;if(f){const S=e.dataIdMap.get(u.dataId).id;S!==i&&(c=u,l=S,m=An(m.length,c.shape.length))}yn("prod",m,c.shape.length);const[g,b]=En(c.shape,m),v=q(b),I=e.makeOutput(g,c.dtype);if(q(c.shape)!==0){const S=e.dataIdMap.get(I.dataId).id;Cy(l,v,Ue[I.dtype],S)}if(f&&e.disposeData(u.dataId),a){const S=gn(I.shape,p);I.shape=S}return I}const ER={kernelName:Ki,backendName:"wasm",setupFunc:$R,kernelFunc:TR};/** + * @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. + * ============================================================================= + */const AR=n=>{const{backend:e,attrs:t}=n,{start:r,stop:s,step:a,dtype:o}=t,i=_g(r,s,a,o),l=e.makeOutput([i.length],o);return e.typedArrayFromHeap(l).set(i),l},RR={kernelName:Zc,backendName:"wasm",kernelFunc:AR};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const DR=mt(mc);/** + * @license + * Copyright 2022 The TensorFlow Authors. 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. + * ============================================================================= + */const PR=Be(Jc);/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const FR=Be(ed);/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const OR=Be(sd);/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let Ny;function MR(n){Ny=n.wasm.cwrap(Yi,null,["number","number","number","number","number","number","number","number","number","number"])}function LR(n){const{backend:e,inputs:t,attrs:r}=n,{images:s}=t,{alignCorners:a,halfPixelCenters:o,size:i}=r,[l,c]=i,[u,d,p,f]=s.shape,m=[u,l,c,f];let g=e.dataIdMap.get(s.dataId),b;g.dtype!=="float32"&&(b=Lr({backend:e,inputs:{x:s},attrs:{dtype:"float32"}}),g=e.dataIdMap.get(b.dataId));const v=g.id,I=e.makeOutput(m,"float32");if(q(s.shape)===0)return I;const S=e.dataIdMap.get(I.dataId).id;return Ny(v,u,d,p,f,l,c,a?1:0,o?1:0,S),b!=null&&e.disposeData(b.dataId),I}const zR={kernelName:Yi,backendName:"wasm",setupFunc:MR,kernelFunc:LR};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */let $y;function BR(n){$y=n.wasm.cwrap(rd,null,["number","number","number","array","array","boolean"])}function WR(n){const{inputs:e,backend:t,attrs:r}=n,{images:s,dy:a}=e,{alignCorners:o}=r,i=t.makeOutput(s.shape,"float32");let l=t.dataIdMap.get(s.dataId),c;return l.dtype!=="float32"&&(c=Lr({backend:t,inputs:{x:s},attrs:{dtype:"float32"}}),l=t.dataIdMap.get(c.dataId)),$y(t.dataIdMap.get(s.dataId).id,t.dataIdMap.get(a.dataId).id,t.dataIdMap.get(i.dataId).id,new Uint8Array(new Int32Array(s.shape).buffer),new Uint8Array(new Int32Array(a.shape).buffer),o),c!=null&&t.disposeData(c.dataId),i}const VR={kernelName:rd,backendName:"wasm",setupFunc:BR,kernelFunc:WR};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the 'License'); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an 'AS IS' BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let Ty;function UR(n){Ty=n.wasm.cwrap(Xi,null,["number","number","number","number","number","number","number","number","number","number"])}function HR(n){const{backend:e,inputs:t,attrs:r}=n,{images:s}=t,{alignCorners:a,halfPixelCenters:o,size:i}=r,[l,c]=i,[u,d,p,f]=s.shape,m=[u,l,c,f],g=e.makeOutput(m,"float32");if(q(s.shape)===0)return g;let b=e.dataIdMap.get(s.dataId),v;b.dtype!=="float32"&&(v=Lr({backend:e,inputs:{x:s},attrs:{dtype:"float32"}}),b=e.dataIdMap.get(v.dataId));const I=b.id,S=e.dataIdMap.get(g.dataId).id;return Ty(I,u,d,p,f,l,c,a?1:0,o?1:0,S),v!=null&&e.disposeData(v.dataId),g}const GR={kernelName:Xi,backendName:"wasm",setupFunc:UR,kernelFunc:HR};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */let Ey;function jR(n){Ey=n.wasm.cwrap(nd,null,["number","number","number","array","array","boolean"])}function qR(n){const{inputs:e,backend:t,attrs:r}=n,{images:s,dy:a}=e,{alignCorners:o}=r,i=t.makeOutput(s.shape,"float32");let l=t.dataIdMap.get(s.dataId),c;return l.dtype!=="float32"&&(c=Lr({backend:t,inputs:{x:s},attrs:{dtype:"float32"}}),l=t.dataIdMap.get(c.dataId)),Ey(t.dataIdMap.get(s.dataId).id,t.dataIdMap.get(a.dataId).id,t.dataIdMap.get(i.dataId).id,new Uint8Array(new Int32Array(s.shape).buffer),new Uint8Array(new Int32Array(a.shape).buffer),o),c!=null&&t.disposeData(c.dataId),i}const KR={kernelName:nd,backendName:"wasm",setupFunc:jR,kernelFunc:qR};/** + * @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. + * ============================================================================= + */let Ay;function XR(n){Ay=n.wasm.cwrap(Qi,null,["number","array","number","array","number","number"])}function YR(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{dims:a}=r,o=$t(a,s.shape);if(s.shape.length===0)return vu({inputs:{x:s},backend:t});const i=t.makeOutput(s.shape,s.dtype),l=t.dataIdMap.get(s.dataId).id,c=t.dataIdMap.get(i.dataId).id,u=new Uint8Array(new Int32Array(o).buffer),d=new Uint8Array(new Int32Array(s.shape).buffer);Ay(l,u,o.length,d,s.shape.length,c);const p=Bt({inputs:{x:i},attrs:{shape:s.shape},backend:t});return t.disposeData(i.dataId),p}const QR={kernelName:Qi,backendName:"wasm",kernelFunc:YR,setupFunc:XR};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let Ry;function ZR(n){Ry=n.wasm.cwrap(uu,null,["number","number","number","number","number","number","number","number","array","number","number"])}function JR(n){const{inputs:e,backend:t,attrs:r}=n,{image:s}=e,{radians:a,fillValue:o,center:i}=r,l=t.makeOutput(s.shape,s.dtype),c=t.dataIdMap.get(s.dataId).id,u=t.dataIdMap.get(l.dataId).id,[d,p,f,m]=s.shape,[g,b]=rg(i,p,f),v=o===0,I=255,S=typeof o=="number"?[o,o,o,v?0:I]:[...o,I],C=new Uint8Array(new Int32Array(S).buffer);return Ry(c,d,p,f,m,a,g,b,C,S.length,u),l}const eD={kernelName:uu,backendName:"wasm",kernelFunc:JR,setupFunc:ZR};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const tD=Be(ad);/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const nD=Be(od);/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let Dy;function rD(n){Dy=n.wasm.cwrap(Zi,null,["number","number","number","number","number","number","array","number","number"])}function sD(n){const{backend:e,inputs:t,attrs:r}=n,{indices:s,updates:a}=t,{shape:o}=r,i=e.makeOutput(o,a.dtype);if(q(o)===0)return i;const{sliceRank:l,numUpdates:c,sliceSize:u,strides:d,outputSize:p}=ha(a,s,o),m=e.dataIdMap.get(s.dataId).id,b=e.dataIdMap.get(a.dataId).id,v=new Uint8Array(new Int32Array(d).buffer),I=e.dataIdMap.get(i.dataId).id;return Dy(m,b,Ue[a.dtype],l,c,u,v,p,I),i}const aD={kernelName:Zi,backendName:"wasm",setupFunc:rD,kernelFunc:sD};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */let Py;function oD(n){Py=n.wasm.cwrap(eu,null,["number","number","number","number","number","number","bool","number"])}function iD(n){const{inputs:e,backend:t,attrs:r}=n,{sortedSequence:s,values:a}=e,{side:o}=r;if(s.dtype!==a.dtype)throw new Error(`SearchSorted error: sorted_sequence must have the same dtype as values. Got ${s.dtype} and ${a.dtype}`);const i=t.makeOutput(a.shape,"int32");function l(c){return t.dataIdMap.get(c.dataId).id}return Py(l(s),l(a),s.shape[0],s.shape[1],a.shape[1],Ue[s.dtype],o==="left",l(i)),i}const uD={kernelName:eu,backendName:"wasm",setupFunc:oD,kernelFunc:iD};/** + * @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. + * ============================================================================= + */let Fy;function lD(n){Fy=n.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}function cD(n){const{inputs:e,backend:t}=n,{condition:r,t:s,e:a}=e,o=t.dataIdMap.get(r.dataId).id,i=t.dataIdMap.get(s.dataId).id,l=t.dataIdMap.get(a.dataId).id,c=t.makeOutput(s.shape,s.dtype),u=t.dataIdMap.get(c.dataId).id,d=r.shape.length,p=s.shape.length,f=d===0||d>1||p===1?1:q(s.shape.slice(1));return Fy(o,i,l,f,u),c}const dD={kernelName:id,backendName:"wasm",kernelFunc:cD,setupFunc:lD};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */const pD=Be(ud);/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let Oy;function hD(n){Oy=n.wasm.cwrap(hd,null,["number","number"])}function fD(n){const{backend:e,inputs:{x:t}}=n,r=e.dataIdMap.get(t.dataId).id,s=e.makeOutput(t.shape,t.dtype),a=e.dataIdMap.get(s.dataId).id;return q(s.shape)===0||Oy(r,a),s}const mD={kernelName:"Sigmoid",backendName:"wasm",setupFunc:hD,kernelFunc:fD};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */const gD=Be(pd);/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const yD=Be(cd);/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */const bD=Be(dd);/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */const wD=Be(fd);/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function xD(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{blockShape:a,paddings:o}=r,i=q(a),l=[[0,0]];l.push(...o);for(let O=1+a.length;O0?l+1:0;if(u<0)throw new Error(zp());const d=s.shape.slice();d[0]=u;const p=t.dataIdMap.get(s.dataId).id,f=t.dataIdMap.get(a.dataId).id,m=t.dataIdMap.get(o.dataId).id,g=t.makeOutput(d,s.dtype),b=t.dataIdMap.get(g.dataId).id,v=t.makeOutput([4],"int32"),I=t.dataIdMap.get(v.dataId).id;zy(p,Ue[s.dtype],s.shape[0],f,m,b,I,e,0);const S=t.readSync(v.dataId);let C;switch(S[0]){case 0:{C=zp();break}case 1:{C=tN();break}case 2:C=nN(S[1],S[2]);break;case 3:C=rN(S[1],S[2],S[3]);break;default:C=""}if(t.disposeData(v.dataId),C)throw t.disposeData(g.dataId),new Error(C);return g}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function $D(n){return Wy(n,!0)}const TD={kernelName:wd,backendName:"wasm",setupFunc:By,kernelFunc:$D};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function ED(n){return Wy(n,!1)}const AD={kernelName:xd,backendName:"wasm",setupFunc:By,kernelFunc:ED};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */let Vy;function RD(n){Vy=n.wasm.cwrap(ru,null,["number","number","number","number","number","number","number","number","array","number","number"])}function DD(n){const{backend:e,inputs:t,attrs:r}=n,{sparseIndices:s,sparseValues:a,defaultValue:o}=t,{outputShape:i}=r,l=e.makeOutput(i,o.dtype);if(q(i)===0)return l;const{sliceRank:c,numUpdates:u,sliceSize:d,strides:p,outputSize:f}=ha(a,s,i),m=e.dataIdMap.get(s.dataId).id,g=e.dataIdMap.get(a.dataId).id,b=e.dataIdMap.get(o.dataId).id,v=new Uint8Array(new Int32Array(p).buffer),I=e.dataIdMap.get(l.dataId).id;return Vy(m,g,a.shape.length,b,Ue[o.dtype],c,u,d,v,f,I),l}const PD={kernelName:ru,backendName:"wasm",setupFunc:RD,kernelFunc:DD};/** + * @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. + * ============================================================================= + */function FD(n){const{inputs:e,attrs:t,backend:r}=n,{x:s}=e,{numOrSizeSplits:a,axis:o}=t,i=$t(o,s.shape)[0],l=og(s,a,i),c=new Array(s.shape.length).fill(0),u=s.shape.slice();return l.map(d=>{const p=[...u];p[i]=d;const f=vs({inputs:{x:s},attrs:{begin:c,size:p},backend:r});return c[i]+=d,f})}const OD={kernelName:yd,backendName:"wasm",kernelFunc:FD};/** + * @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. + * ============================================================================= + */const MD=Be(md);/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const LD=Be(wf);/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const zD=mt(vd);/** + * @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. + * ============================================================================= + */let Uy;function BD(n){Uy=n.wasm.cwrap(iu,null,["number","number","number","number"])}function WD(n){const{backend:e,inputs:t,attrs:r}=n,{alpha:s}=r,{x:a}=t,o=e.dataIdMap.get(a.dataId).id,i=e.makeOutput(a.shape,a.dtype),l=e.dataIdMap.get(i.dataId).id;return Uy(o,s,Ue[a.dtype],l),i}const VD={kernelName:iu,backendName:"wasm",setupFunc:BD,kernelFunc:WD};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */let Hy;function UD(n){Hy=n.wasm.cwrap(su,null,["number","array","number","array","array","array","array","array","number","number"])}function HD(n){const{backend:e,inputs:t,attrs:r}=n,{x:s}=t,{begin:a,end:o,strides:i,beginMask:l,endMask:c,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:p}=r,{finalShapeSparse:f,finalShape:m,isIdentity:g,sliceDim0:b,isSimpleSlice:v,begin:I,end:S,strides:C}=tg(s.shape,a,o,i,l,c,u,d,p);let T;if(g)T=Bt({inputs:{x:s},backend:e,attrs:{shape:m}});else if(b||v){$(s.shape.length>=1,()=>`Input must have rank at least 1, got: ${s.shape.length}`);const O=Qm(I,S,C),L=vs({inputs:{x:s},backend:e,attrs:{begin:I,size:O}});T=Bt({inputs:{x:L},backend:e,attrs:{shape:m}}),e.disposeData(L.dataId)}else{const O=e.makeOutput(f,"float32"),L=e.dataIdMap.get(s.dataId).id,B=new Uint8Array(new Int32Array(et(s.shape)).buffer),A=new Uint8Array(new Int32Array(I).buffer),D=new Uint8Array(new Int32Array(S).buffer),_=new Uint8Array(new Int32Array(C).buffer),V=new Uint8Array(new Int32Array(f).buffer),H=new Uint8Array(new Int32Array(et(f)).buffer),Y=e.dataIdMap.get(O.dataId).id;Hy(L,B,s.shape.length,A,D,_,V,H,f.length,Y),T=Bt({inputs:{x:O},backend:e,attrs:{shape:m}}),e.disposeData(O.dataId)}return T}const GD={kernelName:su,backendName:"wasm",setupFunc:UD,kernelFunc:HD};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function jD(n){const{backend:e,inputs:t,attrs:r}=n,{data:s,dataSplits:a}=t,{separator:o,nGramWidths:i,leftPad:l,rightPad:c,padWidth:u,preserveShortSequences:d}=r,p=e.readSync(s.dataId),f=e.readSync(a.dataId),[m,g]=Cg(p,f,o,i,l,c,u,d),b=e.makeOutput([m.length],"string"),v=e.dataIdMap.get(b.dataId);v.stringBytes=m;const I=e.makeOutput(a.shape,"int32");return e.typedArrayFromHeap(I).set(g),[b,I]}const qD={kernelName:Sd,backendName:"wasm",kernelFunc:jD};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function KD(n){const{backend:e,inputs:t,attrs:r}=n,{input:s,delimiter:a}=t,{skipEmpty:o}=r,i=e.readSync(s.dataId),l=e.readSync(a.dataId),[c,u,d]=Ng(i,l[0],o),p=u.length,f=e.makeOutput([p,2],"int32");e.typedArrayFromHeap(f).set(c);const g=e.makeOutput([p],"string"),b=e.dataIdMap.get(g.dataId);b.stringBytes=u;const v=e.makeOutput([2],"int32");return e.typedArrayFromHeap(v).set(d),[f,g,v]}const XD={kernelName:xf,backendName:"wasm",kernelFunc:KD};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function YD(n){const{backend:e,inputs:t,attrs:r}=n,{input:s}=t,{numBuckets:a}=r,o=e.readSync(s.dataId),i=$g(o,a),l=e.makeOutput(s.shape,"int32");return e.typedArrayFromHeap(l).set(i),l}const QD={kernelName:vf,backendName:"wasm",kernelFunc:YD};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ZD=mt(Id);/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let Gy;function JD(n){Gy=n.wasm.cwrap(tu,null,["number","number","number","number"])}function eP(n){const{backend:e,inputs:t,attrs:r}=n,{axis:s,keepDims:a}=r,{x:o}=t,i=e.dataIdMap.get(o.dataId).id;let l=i,c=o;const{transposed:u,axes:d,originalAxes:p,inputWasTransposed:f}=Mr(o,s,e);let m=d;if(f){const S=e.dataIdMap.get(u.dataId).id;S!==i&&(c=u,l=S,m=An(m.length,c.shape.length))}yn("sum",m,c.shape.length);const[g,b]=En(c.shape,m),v=q(b),I=e.makeOutput(g,c.dtype);if(q(c.shape)!==0){const S=e.dataIdMap.get(I.dataId).id;Gy(l,v,Ue[I.dtype],S)}if(f&&e.disposeData(u.dataId),a){const S=gn(I.shape,p);I.shape=S}return I}const tP={kernelName:tu,backendName:"wasm",setupFunc:JD,kernelFunc:eP};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const nP=Be(kd);/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const rP=Be(_d);/** + * @license + * Copyright 2022 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. + * ============================================================================= + */let jy;function sP(n){jy=n.wasm.cwrap(Ji,null,["number","number","number","number","number","number","array","number","number","number"])}function aP(n){const{backend:e,inputs:t,attrs:r}=n,{tensor:s,indices:a,updates:o}=t,i=e.makeOutput(s.shape,s.dtype);if(q(s.shape)===0)return i;const{sliceRank:l,numUpdates:c,sliceSize:u,strides:d,outputSize:p}=ha(o,a,s.shape),m=e.dataIdMap.get(a.dataId).id,b=e.dataIdMap.get(o.dataId).id,I=e.dataIdMap.get(s.dataId).id,S=new Uint8Array(new Int32Array(d).buffer),C=e.dataIdMap.get(i.dataId).id;return jy(m,b,Ue[o.dtype],l,c,u,S,p,C,I),i}const oP={kernelName:Ji,backendName:"wasm",setupFunc:sP,kernelFunc:aP};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let qy;function iP(n){qy=n.wasm.cwrap(co,null,["number","array","number","array","number","number"])}function uP(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,a=t.dataIdMap.get(s.dataId).id,{reps:o}=r,i=new Array(s.shape.length);for(let p=0;p{const{x:r}=n,{k:s,sorted:a}=t,o=e.dataIdMap.get(r.dataId).id,i=new Uint8Array(new Int32Array(r.shape).buffer),l=r.shape.slice();l[l.length-1]=s;const c=e.makeOutput(l,r.dtype),u=e.dataIdMap.get(c.dataId).id,d=e.makeOutput(l,"int32"),p=e.dataIdMap.get(d.dataId).id;return Ky(o,i,r.shape.length,Ue[r.dtype],s,a,u,p),[c,d]},pP={kernelName:au,backendName:"wasm",setupFunc:cP,kernelFunc:dP};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */let Xy;function hP(n){Xy=n.wasm.cwrap(ou,null,["number","number","bool","number","number","number","number","number","number","array","number","array","number","number","number","number","number"])}function fP(n){const{backend:e,inputs:t,attrs:r}=n,{image:s,transforms:a}=t,{interpolation:o,fillMode:i,fillValue:l,outputShape:c}=r,[u,d,p,f]=s.shape,[m,g]=c??[d,p],b=[u,m,g,f],v=new Uint8Array(new Int32Array(et(s.shape)).buffer),I=new Uint8Array(new Int32Array(et(b)).buffer),S=e.makeOutput(b,s.dtype),C=e.dataIdMap.get(S.dataId).id,O=e.dataIdMap.get(s.dataId).id,B=e.dataIdMap.get(a.dataId).id,A=o==="nearest"?1:2;let D;switch(i){case"constant":D=1;break;case"reflect":D=2;break;case"wrap":D=3;break;case"nearest":D=4;break;default:D=1;break}return Xy(O,B,a.shape[0]>1,u,m,g,f,p,d,v,s.shape.length-1,I,b.length-1,A,D,l,C),S}const mP={kernelName:ou,backendName:"wasm",setupFunc:hP,kernelFunc:fP};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */function gP(n){const{inputs:e,attrs:t,backend:r}=n,{axis:s}=t,{x:a}=e,{outputValues:o,outputShape:i,indices:l}=Eg(r.readSync(a.dataId),s,a.shape,a.dtype);return[r.makeOutput(i,a.dtype,void 0,o),r.makeOutput([l.length],"int32",void 0,l)]}const yP={kernelName:Sf,backendName:"wasm",kernelFunc:gP};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function bP(n){const{inputs:e,backend:t,attrs:r}=n,{value:s}=e;let{axis:a}=r;a<0&&(a+=s.shape.length);const o=s.shape[a],i=s.shape.length,l=new Array(i-1);let c=0;for(let f=0;f({dataId:f,dtype:m,shape:l}))}const wP={kernelName:Cd,backendName:"wasm",kernelFunc:bP};/** + * @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. + * ============================================================================= + */function xP(n){const{inputs:{x:e},backend:t}=n,r=t.makeOutput(e.shape,e.dtype);return t.typedArrayFromHeap(r).fill(0),r}const vP={kernelName:Nd,backendName:"wasm",kernelFunc:xP};/** + * @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. + * ============================================================================= + */const SP=[F3,O3,M3,L3,z3,V3,Y3,J3,e$,t$,n$,r$,s$,a$,o$,l$,b$,p$,m$,S$,oT,lT,cT,pT,hT,fT,yT,bT,vT,kT,NT,ET,DT,PT,FT,LT,WT,HT,qT,YT,JT,nE,aE,uE,dE,pE,mE,yE,bE,wE,xE,vE,SE,_E,CE,NE,EE,DE,OE,zE,VE,HE,jE,U3,qE,KE,XE,ZE,eA,nA,aA,iA,oA,lA,cA,pA,fA,yA,xA,IA,kA,NA,EA,DA,OA,zA,VA,GA,jA,XA,eR,tR,nR,rR,oR,lR,pR,fR,yR,wR,vR,ky,kR,NR,ER,RR,DR,PR,FR,OR,w$,zR,VR,GR,KR,QR,eD,tD,nD,aD,uD,dD,pD,mD,gD,yD,bD,sT,QA,wD,vD,kD,ND,TD,AD,PD,OD,MD,LD,zD,VD,GD,qD,XD,QD,ZD,tP,nP,rP,oP,lP,pP,mP,q3,yP,wP,vP];for(const n of SP)kf(n);/** + * @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. + * ============================================================================= + */const Ml=fe();Ml.registerFlag("WASM_HAS_SIMD_SUPPORT",async()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,9,1,7,0,65,0,253,15,26,11]))}catch{return!1}});Ml.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",async()=>{if(Ml.get("IS_NODE"))return!1;try{return new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}});var Wu={exports:{}},Xp;function IP(){return Xp||(Xp=1,(function(n,e){var t=(()=>{var r=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(r=r||__filename),(function(s){s=s||{};function a(){return ce.buffer!=ot&&rt(ce.buffer),bn}function o(){return ce.buffer!=ot&&rt(ce.buffer),lr}function i(){return ce.buffer!=ot&&rt(ce.buffer),Rn}function l(){return ce.buffer!=ot&&rt(ce.buffer),Gn}function c(){return ce.buffer!=ot&&rt(ce.buffer),lt}var u=typeof s<"u"?s:{},d,p;u.ready=new Promise(function(P,U){d=P,p=U});var f;typeof process<"u"&&process.listeners&&(f={uncaughtException:process.listeners("uncaughtException"),unhandledRejection:process.listeners("unhandledRejection")});var m=Object.assign({},u),g=(P,U)=>{throw U},b=typeof window=="object",v=typeof importScripts=="function",I=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",S=u.ENVIRONMENT_IS_PTHREAD||!1,C="";function T(P){return u.locateFile?u.locateFile(P,C):C+P}var O,L,B;function A(P){if(P instanceof Ot)return;X("exiting due to exception: "+P)}if(I){var D=yr,_=yr;v?C=_.dirname(C)+"/":C=__dirname+"/",O=(U,te)=>(U=Fn(U)?new URL(U):_.normalize(U),D.readFileSync(U,te?void 0:"utf8")),B=U=>{var te=O(U,!0);return te.buffer||(te=new Uint8Array(te)),te},L=(U,te,xe)=>{U=Fn(U)?new URL(U):_.normalize(U),D.readFile(U,function(Ie,Ne){Ie?xe(Ie):te(Ne.buffer)})},process.argv.length>1&&process.argv[1].replace(/\\/g,"/"),process.argv.slice(2),process.on("uncaughtException",function(U){if(!(U instanceof Ot))throw U}),process.on("unhandledRejection",function(U){throw U}),g=(U,te)=>{if(jn())throw process.exitCode=U,te;A(te),process.exit(U)},u.inspect=function(){return"[Emscripten Module object]"};let P;try{P=yr}catch(U){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),U}Xo.Worker=P.Worker}else(b||v)&&(v?C=self.location.href:typeof document<"u"&&document.currentScript&&(C=document.currentScript.src),typeof r<"u"&&r&&(C=r),C.indexOf("blob:")!==0?C=C.substr(0,C.replace(/[?#].*/,"").lastIndexOf("/")+1):C="",I||(O=P=>{var U=new XMLHttpRequest;return U.open("GET",P,!1),U.send(null),U.responseText},v&&(B=P=>{var U=new XMLHttpRequest;return U.open("GET",P,!1),U.responseType="arraybuffer",U.send(null),new Uint8Array(U.response)}),L=(P,U,te)=>{var xe=new XMLHttpRequest;xe.open("GET",P,!0),xe.responseType="arraybuffer",xe.onload=()=>{if(xe.status==200||xe.status==0&&xe.response){U(xe.response);return}te()},xe.onerror=te,xe.send(null)}));I&&typeof performance>"u"&&(Xo.performance=yr.performance);var V=console.log.bind(console),H=console.warn.bind(console);I&&(V=P=>D.writeSync(1,P+` +`),H=P=>D.writeSync(2,P+` +`));var Y=u.print||V,X=u.printErr||H;Object.assign(u,m),m=null,u.arguments&&u.arguments,u.thisProgram&&u.thisProgram,u.quit&&(g=u.quit);var ee;u.wasmBinary&&(ee=u.wasmBinary);var ye=u.noExitRuntime||!0;typeof WebAssembly!="object"&&Pn("no native wasm support detected");var ce,be,Se=!1,Pe;function Ve(P,U){P||Pn(U)}var Oe=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function Et(P,U,te){U>>>=0;for(var xe=U+te,Ie=U;P[Ie]&&!(Ie>=xe);)++Ie;if(Ie-U>16&&P.buffer&&Oe)return Oe.decode(P.buffer instanceof SharedArrayBuffer?P.slice(U,Ie):P.subarray(U,Ie));for(var Ne="";U>10,56320|Lt&1023)}}return Ne}function Hn(P,U){return P>>>=0,P?Et(o(),P,U):""}function ur(P,U,te,xe){if(te>>>=0,!(xe>0))return 0;for(var Ie=te,Ne=te+xe-1,ue=0;ue=55296&&pe<=57343){var Me=P.charCodeAt(++ue);pe=65536+((pe&1023)<<10)|Me&1023}if(pe<=127){if(te>=Ne)break;U[te++>>>0]=pe}else if(pe<=2047){if(te+1>=Ne)break;U[te++>>>0]=192|pe>>6,U[te++>>>0]=128|pe&63}else if(pe<=65535){if(te+2>=Ne)break;U[te++>>>0]=224|pe>>12,U[te++>>>0]=128|pe>>6&63,U[te++>>>0]=128|pe&63}else{if(te+3>=Ne)break;U[te++>>>0]=240|pe>>18,U[te++>>>0]=128|pe>>12&63,U[te++>>>0]=128|pe>>6&63,U[te++>>>0]=128|pe&63}}return U[te>>>0]=0,te-Ie}function Br(P,U,te){return ur(P,o(),U,te)}var ot,bn,lr,Rn,Gn,lt;S&&(ot=u.buffer);function rt(P){ot=P,u.HEAP8=bn=new Int8Array(P),u.HEAP16=new Int16Array(P),u.HEAP32=Rn=new Int32Array(P),u.HEAPU8=lr=new Uint8Array(P),u.HEAPU16=new Uint16Array(P),u.HEAPU32=Gn=new Uint32Array(P),u.HEAPF32=new Float32Array(P),u.HEAPF64=lt=new Float64Array(P)}var Dn=u.INITIAL_MEMORY||16777216;if(S)ce=u.wasmMemory,ot=u.buffer;else if(u.wasmMemory)ce=u.wasmMemory;else if(ce=new WebAssembly.Memory({initial:Dn/65536,maximum:65536,shared:!0}),!(ce.buffer instanceof SharedArrayBuffer))throw X("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),I&&X("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");ce&&(ot=ce.buffer),Dn=ot.byteLength,rt(ot);var gt,cr=[],Wr=[],Vr=[];function jn(){return ye}function dr(){if(u.preRun)for(typeof u.preRun=="function"&&(u.preRun=[u.preRun]);u.preRun.length;)wn(u.preRun.shift());Xe(cr)}function pr(){S||Xe(Wr)}function Ur(){if(!S){if(u.postRun)for(typeof u.postRun=="function"&&(u.postRun=[u.postRun]);u.postRun.length;)hr(u.postRun.shift());Xe(Vr)}}function wn(P){cr.unshift(P)}function $s(P){Wr.unshift(P)}function hr(P){Vr.unshift(P)}var Qt=0,qn=null;function Ts(P){Qt++,u.monitorRunDependencies&&u.monitorRunDependencies(Qt)}function wa(P){if(Qt--,u.monitorRunDependencies&&u.monitorRunDependencies(Qt),Qt==0&&qn){var U=qn;qn=null,U()}}function Pn(P){u.onAbort&&u.onAbort(P),P="Aborted("+P+")",X(P),Se=!0,Pe=1,P+=". Build with -sASSERTIONS for more info.";var U=new WebAssembly.RuntimeError(P);throw p(U),U}var Es="data:application/octet-stream;base64,";function xn(P){return P.startsWith(Es)}function Fn(P){return P.startsWith("file://")}var yt;yt="tfjs-backend-wasm-threaded-simd.wasm",xn(yt)||(yt=T(yt));function As(P){try{if(P==yt&&ee)return new Uint8Array(ee);if(B)return B(P);throw"both async and sync fetching of the wasm failed"}catch(U){Pn(U)}}function Hr(){if(!ee&&(b||v)){if(typeof fetch=="function"&&!Fn(yt))return fetch(yt,{credentials:"same-origin"}).then(function(P){if(!P.ok)throw"failed to load wasm binary file at '"+yt+"'";return P.arrayBuffer()}).catch(function(){return As(yt)});if(L)return new Promise(function(P,U){L(yt,function(te){P(new Uint8Array(te))},U)})}return Promise.resolve().then(function(){return As(yt)})}function fr(){var P={env:Na,wasi_snapshot_preview1:Na};function U(ue,pe){var Me=ue.exports;if(u.asm=Me,qe(u.asm._emscripten_tls_init),gt=u.asm.__indirect_function_table,$s(u.asm.__wasm_call_ctors),be=pe,!S){var Lt=ae.unusedWorkers.length;ae.unusedWorkers.forEach(function(In){ae.loadWasmModuleToWorker(In,function(){--Lt||wa()})})}}S||Ts();function te(ue){U(ue.instance,ue.module)}function xe(ue){return Hr().then(function(pe){return WebAssembly.instantiate(pe,P)}).then(function(pe){return pe}).then(ue,function(pe){X("failed to asynchronously prepare wasm: "+pe),Pn(pe)})}function Ie(){return!ee&&typeof WebAssembly.instantiateStreaming=="function"&&!xn(yt)&&!Fn(yt)&&!I&&typeof fetch=="function"?fetch(yt,{credentials:"same-origin"}).then(function(ue){var pe=WebAssembly.instantiateStreaming(ue,P);return pe.then(te,function(Me){return X("wasm streaming compile failed: "+Me),X("falling back to ArrayBuffer instantiation"),xe(te)})}):xe(te)}if(u.instantiateWasm)try{var Ne=u.instantiateWasm(P,U);return Ne}catch(ue){X("Module.instantiateWasm callback failed with error: "+ue),p(ue)}return Ie().catch(p),{}}var an={};function Ot(P){this.name="ExitStatus",this.message="Program terminated with exit("+P+")",this.status=P}function Kn(P){var U=ae.pthreads[P];delete ae.pthreads[P],U.terminate(),Ls(P),ae.runningWorkers.splice(ae.runningWorkers.indexOf(U),1),U.pthread_ptr=0}function Gr(P){var U=ae.pthreads[P];U.postMessage({cmd:"cancel"})}function vn(P){var U=ae.pthreads[P];Ve(U),ae.returnWorkerToPool(U)}function On(P){var U=ae.getNewWorker();if(!U)return 6;ae.runningWorkers.push(U),ae.pthreads[P.pthread_ptr]=U,U.pthread_ptr=P.pthread_ptr;var te={cmd:"run",start_routine:P.startRoutine,arg:P.arg,pthread_ptr:P.pthread_ptr};return U.runPthread=()=>{I&&U.ref(),U.postMessage(te,P.transferList),delete U.runPthread},U.loaded&&U.runPthread(),0}function on(P){if(S)return Sn(1,1,P);Pe=P,jn()||(ae.terminateAllThreads(),u.onExit&&u.onExit(P),Se=!0),g(P,new Ot(P))}function j(P,U){if(Pe=P,!U&&S)throw Te(P),"unwind";on(P)}var J=j;function me(P){if(P instanceof Ot||P=="unwind")return Pe;g(1,P)}var ae={unusedWorkers:[],runningWorkers:[],tlsInitFunctions:[],pthreads:{},init:function(){S?ae.initWorker():ae.initMainThread()},initMainThread:function(){for(var P=8;P--;)ae.allocateUnusedWorker()},initWorker:function(){ye=!1},setExitStatus:function(P){Pe=P},terminateAllThreads:function(){for(var P of Object.values(ae.pthreads))ae.returnWorkerToPool(P);for(var P of ae.unusedWorkers)P.terminate();ae.unusedWorkers=[]},returnWorkerToPool:function(P){var U=P.pthread_ptr;delete ae.pthreads[U],ae.unusedWorkers.push(P),ae.runningWorkers.splice(ae.runningWorkers.indexOf(P),1),P.pthread_ptr=0,I&&P.unref(),Ls(U)},receiveObjectTransfer:function(P){},threadInitTLS:function(){ae.tlsInitFunctions.forEach(P=>P())},loadWasmModuleToWorker:function(P,U){P.onmessage=Ne=>{var ue=Ne.data,pe=ue.cmd;if(P.pthread_ptr&&(ae.currentProxiedOperationCallerThread=P.pthread_ptr),ue.targetThread&&ue.targetThread!=Kr()){var Me=ae.pthreads[ue.targetThread];Me?Me.postMessage(ue,ue.transferList):X('Internal error! Worker sent a message "'+pe+'" to target pthread '+ue.targetThread+", but that thread no longer exists!"),ae.currentProxiedOperationCallerThread=void 0;return}pe==="processProxyingQueue"?Ds(ue.queue):pe==="spawnThread"?On(ue):pe==="cleanupThread"?vn(ue.thread):pe==="killThread"?Kn(ue.thread):pe==="cancelThread"?Gr(ue.thread):pe==="loaded"?(P.loaded=!0,I&&P.unref(),U&&U(P),P.runPthread&&P.runPthread()):pe==="print"?Y("Thread "+ue.threadId+": "+ue.text):pe==="printErr"?X("Thread "+ue.threadId+": "+ue.text):pe==="alert"?alert("Thread "+ue.threadId+": "+ue.text):ue.target==="setimmediate"?P.postMessage(ue):pe==="callHandler"?u[ue.handler](...ue.args):pe&&X("worker sent an unknown command "+pe),ae.currentProxiedOperationCallerThread=void 0},P.onerror=Ne=>{var ue="worker sent an error!";throw X(ue+" "+Ne.filename+":"+Ne.lineno+": "+Ne.message),Ne},I&&(P.on("message",function(Ne){P.onmessage({data:Ne})}),P.on("error",function(Ne){P.onerror(Ne)}),P.on("detachedExit",function(){}));var te=[],xe=["onExit","onAbort","print","printErr"];for(var Ie of xe)u.hasOwnProperty(Ie)&&te.push(Ie);P.postMessage({cmd:"load",handlers:te,urlOrBlob:u.mainScriptUrlOrBlob||r,wasmMemory:ce,wasmModule:be})},allocateUnusedWorker:function(){var P,U=T("tfjs-backend-wasm-threaded-simd.worker.js");P=new Worker(U),ae.unusedWorkers.push(P)},getNewWorker:function(){return ae.unusedWorkers.length==0&&(ae.allocateUnusedWorker(),ae.loadWasmModuleToWorker(ae.unusedWorkers[0])),ae.unusedWorkers.pop()}};u.PThread=ae;function Xe(P){for(;P.length>0;)P.shift()(u)}function He(){var P=Kr(),U=i()[P+52>>>2],te=i()[P+56>>>2],xe=U-te;Ta(U,xe),Mn(U)}u.establishStackSpace=He;function Te(P){if(S)return Sn(2,0,P);try{J(P)}catch(U){me(U)}}var we=[];function Ye(P){var U=we[P];return U||(P>=we.length&&(we.length=P+1),we[P]=U=gt.get(P)),U}function At(P,U){var te=Ye(P)(U);jn()?ae.setExitStatus(te):Xr(te)}u.invokeEntryPoint=At;function qe(P){ae.tlsInitFunctions.push(P)}function Mt(P){ko(P,!v,1,!b),ae.threadInitTLS()}function Xn(P){S?postMessage({cmd:"cleanupThread",thread:P}):vn(P)}function Rs(P,U,te,xe){return S?Sn(3,1,P,U,te,xe):ht(P,U,te,xe)}function ht(P,U,te,xe){if(typeof SharedArrayBuffer>"u")return X("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var Ie=[],Ne=0;if(S&&(Ie.length===0||Ne))return Rs(P,U,te,xe);var ue={startRoutine:te,pthread_ptr:P,arg:xe,transferList:Ie};return S?(ue.cmd="spawnThread",postMessage(ue,Ie),0):On(ue)}function un(){return 65536}var Yn=!0;function jr(){return Yn}function Ds(P){Atomics.store(i(),P>>2,1),Kr()&&$a(P),Atomics.compareExchange(i(),P>>2,1,0)}u.executeNotifiedProxyingQueue=Ds;function xa(P,U,te,xe){if(P==U)setTimeout(()=>Ds(xe));else if(S)postMessage({targetThread:P,cmd:"processProxyingQueue",queue:xe});else{var Ie=ae.pthreads[P];if(!Ie)return;Ie.postMessage({cmd:"processProxyingQueue",queue:xe})}return 1}function va(P,U,te){return-1}function mo(){Pn("")}function kt(P){kt.shown||(kt.shown={}),kt.shown[P]||(kt.shown[P]=1,I&&(P="warning: "+P),X(P))}function ln(){I||v||kt("Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread")}function qr(){return Date.now()}function Ps(){return 4294901760}function Sa(){return Ps()}var Fs;I?Fs=()=>{var P=process.hrtime();return P[0]*1e3+P[1]/1e6}:Fs=()=>performance.timeOrigin+performance.now();function Ia(P,U,te){o().copyWithin(P>>>0,U>>>0,U+te>>>0)}function cn(){return I?yr.cpus().length:navigator.hardwareConcurrency}function go(P){var U=zs(),te=P();return Mn(U),te}function Sn(P,U){var te=arguments.length-2,xe=arguments;return go(()=>{for(var Ie=te,Ne=Bs(Ie*8),ue=Ne>>3,pe=0;pe>>0]=Me}return _o(P,Ie,Ne,U)})}var Ht=[];function Os(P,U,te){Ht.length=U;for(var xe=te>>3,Ie=0;Ie>>0];var Ne=P<0,ue=Ne?an[-P-1]:Ms[P];return ue.apply(null,Ht)}function Cu(P){try{return ce.grow(P-ot.byteLength+65535>>>16),rt(ce.buffer),1}catch{}}function yo(P){var U=o().length;if(P=P>>>0,P<=U)return!1;var te=Ps();if(P>te)return!1;let xe=(Me,Lt)=>Me+(Lt-Me%Lt)%Lt;for(var Ie=1;Ie<=4;Ie*=2){var Ne=U*(1+.2/Ie);Ne=Math.min(Ne,P+100663296);var ue=Math.min(te,xe(Math.max(P,Ne),65536)),pe=Cu(ue);if(pe)return!0}return!1}function ka(){throw"unwind"}function bo(P){return S?Sn(4,1,P):52}function wo(P,U,te,xe,Ie){return S?Sn(5,1,P,U,te,xe,Ie):70}var xo=[null,[],[]];function vo(P,U){var te=xo[P];U===0||U===10?((P===1?Y:X)(Et(te,0)),te.length=0):te.push(U)}function _a(P,U,te,xe){if(S)return Sn(6,1,P,U,te,xe);for(var Ie=0,Ne=0;Ne>>2],pe=l()[U+4>>>2];U+=8;for(var Me=0;Me>>0]);Ie+=pe}return l()[xe>>>2]=Ie,0}function Ca(P){var U=u["_"+P];return U}function Rt(P,U){a().set(P,U>>>0)}function So(P,U,te,xe,Ie){var Ne={string:vt=>{var Zt=0;if(vt!=null&&vt!==0){var Ra=(vt.length<<2)+1;Zt=Bs(Ra),Br(vt,Zt,Ra)}return Zt},array:vt=>{var Zt=Bs(vt.length);return Rt(vt,Zt),Zt}};function ue(vt){return U==="string"?Hn(vt):U==="boolean"?!!vt:vt}var pe=Ca(P),Me=[],Lt=0;if(xe)for(var In=0;Inue==="number"||ue==="boolean"),Ne=U!=="string";return Ne&&Ie&&!xe?Ca(P):function(){return So(P,U,te,arguments)}}ae.init();var Ms=[null,on,Te,Rs,bo,wo,_a],Na={__emscripten_init_main_thread_js:Mt,__emscripten_thread_cleanup:Xn,__pthread_create_js:ht,_emscripten_default_pthread_stack_size:un,_emscripten_get_now_is_monotonic:jr,_emscripten_notify_task_queue:xa,_emscripten_set_offscreencanvas_size:va,abort:mo,emscripten_check_blocking_allowed:ln,emscripten_date_now:qr,emscripten_get_heap_max:Sa,emscripten_get_now:Fs,emscripten_memcpy_big:Ia,emscripten_num_logical_cores:cn,emscripten_receive_on_main_thread_js:Os,emscripten_resize_heap:yo,emscripten_unwind_to_js_event_loop:ka,exit:J,fd_close:bo,fd_seek:wo,fd_write:_a,memory:ce||u.wasmMemory};fr(),u.___wasm_call_ctors=function(){return(u.___wasm_call_ctors=u.asm.__wasm_call_ctors).apply(null,arguments)},u._init=function(){return(u._init=u.asm.init).apply(null,arguments)},u._init_with_threads_count=function(){return(u._init_with_threads_count=u.asm.init_with_threads_count).apply(null,arguments)},u._get_threads_count=function(){return(u._get_threads_count=u.asm.get_threads_count).apply(null,arguments)},u._register_tensor=function(){return(u._register_tensor=u.asm.register_tensor).apply(null,arguments)},u._dispose_data=function(){return(u._dispose_data=u.asm.dispose_data).apply(null,arguments)},u._dispose=function(){return(u._dispose=u.asm.dispose).apply(null,arguments)},u._Abs=function(){return(u._Abs=u.asm.Abs).apply(null,arguments)},u._Acos=function(){return(u._Acos=u.asm.Acos).apply(null,arguments)},u._Acosh=function(){return(u._Acosh=u.asm.Acosh).apply(null,arguments)},u._Add=function(){return(u._Add=u.asm.Add).apply(null,arguments)},u._AddN=function(){return(u._AddN=u.asm.AddN).apply(null,arguments)},u._All=function(){return(u._All=u.asm.All).apply(null,arguments)},u._Any=function(){return(u._Any=u.asm.Any).apply(null,arguments)},u._ArgMax=function(){return(u._ArgMax=u.asm.ArgMax).apply(null,arguments)},u._ArgMin=function(){return(u._ArgMin=u.asm.ArgMin).apply(null,arguments)},u._Asin=function(){return(u._Asin=u.asm.Asin).apply(null,arguments)},u._Asinh=function(){return(u._Asinh=u.asm.Asinh).apply(null,arguments)},u._Atan=function(){return(u._Atan=u.asm.Atan).apply(null,arguments)},u._Atan2=function(){return(u._Atan2=u.asm.Atan2).apply(null,arguments)},u._Atanh=function(){return(u._Atanh=u.asm.Atanh).apply(null,arguments)},u._AvgPool=function(){return(u._AvgPool=u.asm.AvgPool).apply(null,arguments)},u._AvgPool3D=function(){return(u._AvgPool3D=u.asm.AvgPool3D).apply(null,arguments)},u._AvgPool3DGrad=function(){return(u._AvgPool3DGrad=u.asm.AvgPool3DGrad).apply(null,arguments)},u._AvgPoolGrad=function(){return(u._AvgPoolGrad=u.asm.AvgPoolGrad).apply(null,arguments)},u._BatchMatMul=function(){return(u._BatchMatMul=u.asm.BatchMatMul).apply(null,arguments)},u._Bincount=function(){return(u._Bincount=u.asm.Bincount).apply(null,arguments)},u._BitwiseAnd=function(){return(u._BitwiseAnd=u.asm.BitwiseAnd).apply(null,arguments)},u._Ceil=function(){return(u._Ceil=u.asm.Ceil).apply(null,arguments)},u._ClipByValue=function(){return(u._ClipByValue=u.asm.ClipByValue).apply(null,arguments)},u._Conv2D=function(){return(u._Conv2D=u.asm.Conv2D).apply(null,arguments)},u._Conv2DBackpropInput=function(){return(u._Conv2DBackpropInput=u.asm.Conv2DBackpropInput).apply(null,arguments)},u._Conv3D=function(){return(u._Conv3D=u.asm.Conv3D).apply(null,arguments)},u._Conv3DBackpropFilterV2=function(){return(u._Conv3DBackpropFilterV2=u.asm.Conv3DBackpropFilterV2).apply(null,arguments)},u._Conv3DBackpropInputV2=function(){return(u._Conv3DBackpropInputV2=u.asm.Conv3DBackpropInputV2).apply(null,arguments)},u._Cos=function(){return(u._Cos=u.asm.Cos).apply(null,arguments)},u._Cosh=function(){return(u._Cosh=u.asm.Cosh).apply(null,arguments)},u._CropAndResize=function(){return(u._CropAndResize=u.asm.CropAndResize).apply(null,arguments)},u._Cumprod=function(){return(u._Cumprod=u.asm.Cumprod).apply(null,arguments)},u._Cumsum=function(){return(u._Cumsum=u.asm.Cumsum).apply(null,arguments)},u._DenseBincount=function(){return(u._DenseBincount=u.asm.DenseBincount).apply(null,arguments)},u._DepthToSpace=function(){return(u._DepthToSpace=u.asm.DepthToSpace).apply(null,arguments)},u._DepthwiseConv2dNative=function(){return(u._DepthwiseConv2dNative=u.asm.DepthwiseConv2dNative).apply(null,arguments)},u._Diag=function(){return(u._Diag=u.asm.Diag).apply(null,arguments)},u._Dilation2D=function(){return(u._Dilation2D=u.asm.Dilation2D).apply(null,arguments)},u._Dilation2DBackpropFilter=function(){return(u._Dilation2DBackpropFilter=u.asm.Dilation2DBackpropFilter).apply(null,arguments)},u._Dilation2DBackpropInput=function(){return(u._Dilation2DBackpropInput=u.asm.Dilation2DBackpropInput).apply(null,arguments)},u._Elu=function(){return(u._Elu=u.asm.Elu).apply(null,arguments)},u._EluGrad=function(){return(u._EluGrad=u.asm.EluGrad).apply(null,arguments)},u._Equal=function(){return(u._Equal=u.asm.Equal).apply(null,arguments)},u._Erf=function(){return(u._Erf=u.asm.Erf).apply(null,arguments)},u._Exp=function(){return(u._Exp=u.asm.Exp).apply(null,arguments)},u._Expm1=function(){return(u._Expm1=u.asm.Expm1).apply(null,arguments)},u._FlipLeftRight=function(){return(u._FlipLeftRight=u.asm.FlipLeftRight).apply(null,arguments)},u._Floor=function(){return(u._Floor=u.asm.Floor).apply(null,arguments)},u._FloorDiv=function(){return(u._FloorDiv=u.asm.FloorDiv).apply(null,arguments)},u._FusedBatchNorm=function(){return(u._FusedBatchNorm=u.asm.FusedBatchNorm).apply(null,arguments)},u._FusedConv2D=function(){return(u._FusedConv2D=u.asm.FusedConv2D).apply(null,arguments)},u._FusedDepthwiseConv2D=function(){return(u._FusedDepthwiseConv2D=u.asm.FusedDepthwiseConv2D).apply(null,arguments)},u._Gather=function(){return(u._Gather=u.asm.Gather).apply(null,arguments)},u._GatherNd=function(){return(u._GatherNd=u.asm.GatherNd).apply(null,arguments)},u._Greater=function(){return(u._Greater=u.asm.Greater).apply(null,arguments)},u._GreaterEqual=function(){return(u._GreaterEqual=u.asm.GreaterEqual).apply(null,arguments)},u._IsFinite=function(){return(u._IsFinite=u.asm.IsFinite).apply(null,arguments)},u._IsInf=function(){return(u._IsInf=u.asm.IsInf).apply(null,arguments)},u._IsNan=function(){return(u._IsNan=u.asm.IsNan).apply(null,arguments)},u._LRN=function(){return(u._LRN=u.asm.LRN).apply(null,arguments)},u._LRNGrad=function(){return(u._LRNGrad=u.asm.LRNGrad).apply(null,arguments)},u._LeakyRelu=function(){return(u._LeakyRelu=u.asm.LeakyRelu).apply(null,arguments)},u._Less=function(){return(u._Less=u.asm.Less).apply(null,arguments)},u._LessEqual=function(){return(u._LessEqual=u.asm.LessEqual).apply(null,arguments)},u._LinSpace=function(){return(u._LinSpace=u.asm.LinSpace).apply(null,arguments)},u._Log=function(){return(u._Log=u.asm.Log).apply(null,arguments)},u._Log1p=function(){return(u._Log1p=u.asm.Log1p).apply(null,arguments)},u._LogicalAnd=function(){return(u._LogicalAnd=u.asm.LogicalAnd).apply(null,arguments)},u._LogicalNot=function(){return(u._LogicalNot=u.asm.LogicalNot).apply(null,arguments)},u._LogicalOr=function(){return(u._LogicalOr=u.asm.LogicalOr).apply(null,arguments)},u._LogicalXor=function(){return(u._LogicalXor=u.asm.LogicalXor).apply(null,arguments)},u._Max=function(){return(u._Max=u.asm.Max).apply(null,arguments)},u._MaxPool=function(){return(u._MaxPool=u.asm.MaxPool).apply(null,arguments)},u._MaxPool3D=function(){return(u._MaxPool3D=u.asm.MaxPool3D).apply(null,arguments)},u._MaxPool3DGrad=function(){return(u._MaxPool3DGrad=u.asm.MaxPool3DGrad).apply(null,arguments)},u._MaxPoolGrad=function(){return(u._MaxPoolGrad=u.asm.MaxPoolGrad).apply(null,arguments)},u._MaxPoolWithArgmax=function(){return(u._MaxPoolWithArgmax=u.asm.MaxPoolWithArgmax).apply(null,arguments)},u._Maximum=function(){return(u._Maximum=u.asm.Maximum).apply(null,arguments)},u._Mean=function(){return(u._Mean=u.asm.Mean).apply(null,arguments)},u._Min=function(){return(u._Min=u.asm.Min).apply(null,arguments)},u._Minimum=function(){return(u._Minimum=u.asm.Minimum).apply(null,arguments)},u._MirrorPad=function(){return(u._MirrorPad=u.asm.MirrorPad).apply(null,arguments)},u._Mod=function(){return(u._Mod=u.asm.Mod).apply(null,arguments)},u._Multinomial=function(){return(u._Multinomial=u.asm.Multinomial).apply(null,arguments)},u._Multiply=function(){return(u._Multiply=u.asm.Multiply).apply(null,arguments)},u._Neg=function(){return(u._Neg=u.asm.Neg).apply(null,arguments)},u._NonMaxSuppressionV3=function(){return(u._NonMaxSuppressionV3=u.asm.NonMaxSuppressionV3).apply(null,arguments)},u._NonMaxSuppressionV4=function(){return(u._NonMaxSuppressionV4=u.asm.NonMaxSuppressionV4).apply(null,arguments)},u._NonMaxSuppressionV5=function(){return(u._NonMaxSuppressionV5=u.asm.NonMaxSuppressionV5).apply(null,arguments)},u._NotEqual=function(){return(u._NotEqual=u.asm.NotEqual).apply(null,arguments)},u._OneHot=function(){return(u._OneHot=u.asm.OneHot).apply(null,arguments)},u._PadV2=function(){return(u._PadV2=u.asm.PadV2).apply(null,arguments)},u._Pow=function(){return(u._Pow=u.asm.Pow).apply(null,arguments)},u._Prelu=function(){return(u._Prelu=u.asm.Prelu).apply(null,arguments)},u._Prod=function(){return(u._Prod=u.asm.Prod).apply(null,arguments)},u._RealDiv=function(){return(u._RealDiv=u.asm.RealDiv).apply(null,arguments)},u._Reciprocal=function(){return(u._Reciprocal=u.asm.Reciprocal).apply(null,arguments)},u._Relu=function(){return(u._Relu=u.asm.Relu).apply(null,arguments)},u._Relu6=function(){return(u._Relu6=u.asm.Relu6).apply(null,arguments)},u._ResizeBilinear=function(){return(u._ResizeBilinear=u.asm.ResizeBilinear).apply(null,arguments)},u._ResizeBilinearGrad=function(){return(u._ResizeBilinearGrad=u.asm.ResizeBilinearGrad).apply(null,arguments)},u._ResizeNearestNeighbor=function(){return(u._ResizeNearestNeighbor=u.asm.ResizeNearestNeighbor).apply(null,arguments)},u._ResizeNearestNeighborGrad=function(){return(u._ResizeNearestNeighborGrad=u.asm.ResizeNearestNeighborGrad).apply(null,arguments)},u._Reverse=function(){return(u._Reverse=u.asm.Reverse).apply(null,arguments)},u._RotateWithOffset=function(){return(u._RotateWithOffset=u.asm.RotateWithOffset).apply(null,arguments)},u._Round=function(){return(u._Round=u.asm.Round).apply(null,arguments)},u._Rsqrt=function(){return(u._Rsqrt=u.asm.Rsqrt).apply(null,arguments)},u._ScatterNd=function(){return(u._ScatterNd=u.asm.ScatterNd).apply(null,arguments)},u._SearchSorted=function(){return(u._SearchSorted=u.asm.SearchSorted).apply(null,arguments)},u._SelectV2=function(){return(u._SelectV2=u.asm.SelectV2).apply(null,arguments)},u._Selu=function(){return(u._Selu=u.asm.Selu).apply(null,arguments)},u._Sigmoid=function(){return(u._Sigmoid=u.asm.Sigmoid).apply(null,arguments)},u._Sign=function(){return(u._Sign=u.asm.Sign).apply(null,arguments)},u._Sin=function(){return(u._Sin=u.asm.Sin).apply(null,arguments)},u._Sinh=function(){return(u._Sinh=u.asm.Sinh).apply(null,arguments)},u._Softmax=function(){return(u._Softmax=u.asm.Softmax).apply(null,arguments)},u._Softplus=function(){return(u._Softplus=u.asm.Softplus).apply(null,arguments)},u._SparseFillEmptyRows=function(){return(u._SparseFillEmptyRows=u.asm.SparseFillEmptyRows).apply(null,arguments)},u._SparseReshape=function(){return(u._SparseReshape=u.asm.SparseReshape).apply(null,arguments)},u._SparseSegmentReduction=function(){return(u._SparseSegmentReduction=u.asm.SparseSegmentReduction).apply(null,arguments)},u._SparseToDense=function(){return(u._SparseToDense=u.asm.SparseToDense).apply(null,arguments)},u._Sqrt=function(){return(u._Sqrt=u.asm.Sqrt).apply(null,arguments)},u._Square=function(){return(u._Square=u.asm.Square).apply(null,arguments)},u._SquaredDifference=function(){return(u._SquaredDifference=u.asm.SquaredDifference).apply(null,arguments)},u._Step=function(){return(u._Step=u.asm.Step).apply(null,arguments)},u._StridedSlice=function(){return(u._StridedSlice=u.asm.StridedSlice).apply(null,arguments)},u._Sub=function(){return(u._Sub=u.asm.Sub).apply(null,arguments)},u._Sum=function(){return(u._Sum=u.asm.Sum).apply(null,arguments)},u._Tan=function(){return(u._Tan=u.asm.Tan).apply(null,arguments)},u._Tanh=function(){return(u._Tanh=u.asm.Tanh).apply(null,arguments)},u._TensorScatterUpdate=function(){return(u._TensorScatterUpdate=u.asm.TensorScatterUpdate).apply(null,arguments)},u._Tile=function(){return(u._Tile=u.asm.Tile).apply(null,arguments)},u._TopK=function(){return(u._TopK=u.asm.TopK).apply(null,arguments)},u._Transform=function(){return(u._Transform=u.asm.Transform).apply(null,arguments)},u._Transpose=function(){return(u._Transpose=u.asm.Transpose).apply(null,arguments)},u.__FusedMatMul=function(){return(u.__FusedMatMul=u.asm._FusedMatMul).apply(null,arguments)},u._malloc=function(){return(u._malloc=u.asm.malloc).apply(null,arguments)},u._free=function(){return(u._free=u.asm.free).apply(null,arguments)},u.__emscripten_tls_init=function(){return(u.__emscripten_tls_init=u.asm._emscripten_tls_init).apply(null,arguments)};var Kr=u._pthread_self=function(){return(Kr=u._pthread_self=u.asm.pthread_self).apply(null,arguments)};u.___errno_location=function(){return(u.___errno_location=u.asm.__errno_location).apply(null,arguments)};var ko=u.__emscripten_thread_init=function(){return(ko=u.__emscripten_thread_init=u.asm._emscripten_thread_init).apply(null,arguments)};u.__emscripten_thread_crashed=function(){return(u.__emscripten_thread_crashed=u.asm._emscripten_thread_crashed).apply(null,arguments)},u._emscripten_main_thread_process_queued_calls=function(){return(u._emscripten_main_thread_process_queued_calls=u.asm.emscripten_main_thread_process_queued_calls).apply(null,arguments)},u._emscripten_main_browser_thread_id=function(){return(u._emscripten_main_browser_thread_id=u.asm.emscripten_main_browser_thread_id).apply(null,arguments)};var _o=u._emscripten_run_in_main_runtime_thread_js=function(){return(_o=u._emscripten_run_in_main_runtime_thread_js=u.asm.emscripten_run_in_main_runtime_thread_js).apply(null,arguments)};u._emscripten_dispatch_to_thread_=function(){return(u._emscripten_dispatch_to_thread_=u.asm.emscripten_dispatch_to_thread_).apply(null,arguments)};var $a=u.__emscripten_proxy_execute_task_queue=function(){return($a=u.__emscripten_proxy_execute_task_queue=u.asm._emscripten_proxy_execute_task_queue).apply(null,arguments)},Ls=u.__emscripten_thread_free_data=function(){return(Ls=u.__emscripten_thread_free_data=u.asm._emscripten_thread_free_data).apply(null,arguments)},Xr=u.__emscripten_thread_exit=function(){return(Xr=u.__emscripten_thread_exit=u.asm._emscripten_thread_exit).apply(null,arguments)},Ta=u._emscripten_stack_set_limits=function(){return(Ta=u._emscripten_stack_set_limits=u.asm.emscripten_stack_set_limits).apply(null,arguments)},zs=u.stackSave=function(){return(zs=u.stackSave=u.asm.stackSave).apply(null,arguments)},Mn=u.stackRestore=function(){return(Mn=u.stackRestore=u.asm.stackRestore).apply(null,arguments)},Bs=u.stackAlloc=function(){return(Bs=u.stackAlloc=u.asm.stackAlloc).apply(null,arguments)};u.dynCall_iijjiiii=function(){return(u.dynCall_iijjiiii=u.asm.dynCall_iijjiiii).apply(null,arguments)},u.dynCall_jiji=function(){return(u.dynCall_jiji=u.asm.dynCall_jiji).apply(null,arguments)},u.keepRuntimeAlive=jn,u.wasmMemory=ce,u.cwrap=Io,u.ExitStatus=Ot,u.PThread=ae;var Ws;qn=function P(){Ws||Co(),Ws||(qn=P)};function Co(P){if(Qt>0)return;if(S){d(u),pr(),startWorker(u);return}if(dr(),Qt>0)return;function U(){Ws||(Ws=!0,u.calledRun=!0,!Se&&(pr(),d(u),u.onRuntimeInitialized&&u.onRuntimeInitialized(),Ur()))}u.setStatus?(u.setStatus("Running..."),setTimeout(function(){setTimeout(function(){u.setStatus("")},1),U()},1)):U()}if(u.preInit)for(typeof u.preInit=="function"&&(u.preInit=[u.preInit]);u.preInit.length>0;)u.preInit.pop()();Co();var Vs;f&&(Vs={uncaughtException:process.listeners("uncaughtException").filter(function(P){return!f.uncaughtException.indexOf(P)>-1}),unhandledRejection:process.listeners("unhandledRejection").filter(function(P){return!f.unhandledRejection.indexOf(P)>-1})});var mr;if(typeof WasmBackendModule<"u")mr=WasmBackendModule;else if(typeof s<"u")mr=s;else throw new Error("Could not find wasm module in post.js");if(Vs){var Yr=mr._dispose;mr._dispose=function(){Yr(),Vs.uncaughtException.forEach(function(P){process.removeListener("uncaughtException",P)}),Vs.unhandledRejection.forEach(function(P){process.removeListener("unhandledRejection",P)})}}return s.ready})})();n.exports=t})(Wu)),Wu.exports}var Yy=IP(),Qy=$d(Yy),kP=qh({__proto__:null,default:Qy},[Yy]),Vu={},Yp;function _P(){return Yp||(Yp=1,Vu.wasmWorkerContents=`"use strict";var Module={};var ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads");var parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",data=>onmessage({data:data}));var fs=require("fs");Object.assign(global,{self:global,require:require,Module:Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:function(f){(0,eval)(fs.readFileSync(f,"utf8")+"//# sourceURL="+f)},postMessage:function(msg){parentPort.postMessage(msg)},performance:global.performance||{now:function(){return Date.now()}}})}var initializedJS=false;var pendingNotifiedProxyingQueues=[];function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,text+" +");return}console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;self.alert=threadAlert;Module["instantiateWasm"]=(info,receiveInstance)=>{var instance=new WebAssembly.Instance(Module["wasmModule"],info);receiveInstance(instance);Module["wasmModule"]=null;return instance.exports};self.onunhandledrejection=e=>{throw e.reason??e};self.startWorker=instance=>{Module=instance;postMessage({"cmd":"loaded"})};self.onmessage=e=>{try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;for(const handler of e.data.handlers){Module[handler]=function(){postMessage({cmd:"callHandler",handler:handler,args:[...arguments]})}}Module["wasmMemory"]=e.data.wasmMemory;Module["buffer"]=Module["wasmMemory"].buffer;Module["ENVIRONMENT_IS_PTHREAD"]=true;if(typeof e.data.urlOrBlob=="string"){importScripts(e.data.urlOrBlob)}else{var objectUrl=URL.createObjectURL(e.data.urlOrBlob);importScripts(objectUrl);URL.revokeObjectURL(objectUrl)}WasmBackendModuleThreadedSimd(Module)}else if(e.data.cmd==="run"){Module["__emscripten_thread_init"](e.data.pthread_ptr,0,0,1);Module["establishStackSpace"]();Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].threadInitTLS();if(!initializedJS){pendingNotifiedProxyingQueues.forEach(queue=>{Module["executeNotifiedProxyingQueue"](queue)});pendingNotifiedProxyingQueues=[];initializedJS=true}try{Module["invokeEntryPoint"](e.data.start_routine,e.data.arg)}catch(ex){if(ex!="unwind"){if(ex instanceof Module["ExitStatus"]){if(Module["keepRuntimeAlive"]()){}else{Module["__emscripten_thread_exit"](ex.status)}}else{throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["__emscripten_thread_exit"](-1)}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processProxyingQueue"){if(initializedJS){Module["executeNotifiedProxyingQueue"](e.data.queue)}else{pendingNotifiedProxyingQueues.push(e.data.queue)}}else if(e.data.cmd){err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){if(Module["__emscripten_thread_crashed"]){Module["__emscripten_thread_crashed"]()}throw ex}};`),Vu}var CP=_P(),Uu={exports:{}},Qp;function NP(){return Qp||(Qp=1,(function(n,e){var t=(()=>{var r=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(r=r||__filename),(function(s){s=s||{};var a=typeof s<"u"?s:{},o,i;a.ready=new Promise(function(j,J){o=j,i=J});var l;typeof process<"u"&&process.listeners&&(l={uncaughtException:process.listeners("uncaughtException"),unhandledRejection:process.listeners("unhandledRejection")});var c=Object.assign({},a),u=typeof window=="object",d=typeof importScripts=="function",p=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",f="";function m(j){return a.locateFile?a.locateFile(j,f):f+j}var g,b,v;if(p){var I=yr,S=yr;d?f=S.dirname(f)+"/":f=__dirname+"/",g=(j,J)=>(j=Dn(j)?new URL(j):S.normalize(j),I.readFileSync(j,J?void 0:"utf8")),v=j=>{var J=g(j,!0);return J.buffer||(J=new Uint8Array(J)),J},b=(j,J,me)=>{j=Dn(j)?new URL(j):S.normalize(j),I.readFile(j,function(ae,Xe){ae?me(ae):J(Xe.buffer)})},process.argv.length>1&&process.argv[1].replace(/\\/g,"/"),process.argv.slice(2),process.on("uncaughtException",function(j){if(!(j instanceof jn))throw j}),process.on("unhandledRejection",function(j){throw j}),a.inspect=function(){return"[Emscripten Module object]"}}else(u||d)&&(d?f=self.location.href:typeof document<"u"&&document.currentScript&&(f=document.currentScript.src),r&&(f=r),f.indexOf("blob:")!==0?f=f.substr(0,f.replace(/[?#].*/,"").lastIndexOf("/")+1):f="",g=j=>{var J=new XMLHttpRequest;return J.open("GET",j,!1),J.send(null),J.responseText},d&&(v=j=>{var J=new XMLHttpRequest;return J.open("GET",j,!1),J.responseType="arraybuffer",J.send(null),new Uint8Array(J.response)}),b=(j,J,me)=>{var ae=new XMLHttpRequest;ae.open("GET",j,!0),ae.responseType="arraybuffer",ae.onload=()=>{if(ae.status==200||ae.status==0&&ae.response){J(ae.response);return}me()},ae.onerror=me,ae.send(null)});var C=a.print||console.log.bind(console),T=a.printErr||console.warn.bind(console);Object.assign(a,c),c=null,a.arguments&&a.arguments,a.thisProgram&&a.thisProgram,a.quit&&a.quit;var O;a.wasmBinary&&(O=a.wasmBinary),a.noExitRuntime,typeof WebAssembly!="object"&&Gn("no native wasm support detected");var L,B=!1,A=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function D(j,J,me){J>>>=0;for(var ae=J+me,Xe=J;j[Xe]&&!(Xe>=ae);)++Xe;if(Xe-J>16&&j.buffer&&A)return A.decode(j.subarray(J,Xe));for(var He="";J>10,56320|At&1023)}}return He}function _(j,J){return j>>>=0,j?D(ee,j,J):""}function V(j,J,me,ae){if(me>>>=0,!(ae>0))return 0;for(var Xe=me,He=me+ae-1,Te=0;Te=55296&&we<=57343){var Ye=j.charCodeAt(++Te);we=65536+((we&1023)<<10)|Ye&1023}if(we<=127){if(me>=He)break;J[me++>>>0]=we}else if(we<=2047){if(me+1>=He)break;J[me++>>>0]=192|we>>6,J[me++>>>0]=128|we&63}else if(we<=65535){if(me+2>=He)break;J[me++>>>0]=224|we>>12,J[me++>>>0]=128|we>>6&63,J[me++>>>0]=128|we&63}else{if(me+3>=He)break;J[me++>>>0]=240|we>>18,J[me++>>>0]=128|we>>12&63,J[me++>>>0]=128|we>>6&63,J[me++>>>0]=128|we&63}}return J[me>>>0]=0,me-Xe}function H(j,J,me){return V(j,ee,J,me)}var Y,X,ee,ye;function ce(j){Y=j,a.HEAP8=X=new Int8Array(j),a.HEAP16=new Int16Array(j),a.HEAP32=new Int32Array(j),a.HEAPU8=ee=new Uint8Array(j),a.HEAPU16=new Uint16Array(j),a.HEAPU32=ye=new Uint32Array(j),a.HEAPF32=new Float32Array(j),a.HEAPF64=new Float64Array(j)}a.INITIAL_MEMORY;var be=[],Se=[],Pe=[];function Ve(){if(a.preRun)for(typeof a.preRun=="function"&&(a.preRun=[a.preRun]);a.preRun.length;)Hn(a.preRun.shift());dr(be)}function Oe(){dr(Se)}function Et(){if(a.postRun)for(typeof a.postRun=="function"&&(a.postRun=[a.postRun]);a.postRun.length;)Br(a.postRun.shift());dr(Pe)}function Hn(j){be.unshift(j)}function ur(j){Se.unshift(j)}function Br(j){Pe.unshift(j)}var ot=0,bn=null;function lr(j){ot++,a.monitorRunDependencies&&a.monitorRunDependencies(ot)}function Rn(j){if(ot--,a.monitorRunDependencies&&a.monitorRunDependencies(ot),ot==0&&bn){var J=bn;bn=null,J()}}function Gn(j){a.onAbort&&a.onAbort(j),j="Aborted("+j+")",T(j),B=!0,j+=". Build with -sASSERTIONS for more info.";var J=new WebAssembly.RuntimeError(j);throw i(J),J}var lt="data:application/octet-stream;base64,";function rt(j){return j.startsWith(lt)}function Dn(j){return j.startsWith("file://")}var gt;gt="tfjs-backend-wasm.wasm",rt(gt)||(gt=m(gt));function cr(j){try{if(j==gt&&O)return new Uint8Array(O);if(v)return v(j);throw"both async and sync fetching of the wasm failed"}catch(J){Gn(J)}}function Wr(){if(!O&&(u||d)){if(typeof fetch=="function"&&!Dn(gt))return fetch(gt,{credentials:"same-origin"}).then(function(j){if(!j.ok)throw"failed to load wasm binary file at '"+gt+"'";return j.arrayBuffer()}).catch(function(){return cr(gt)});if(b)return new Promise(function(j,J){b(gt,function(me){j(new Uint8Array(me))},J)})}return Promise.resolve().then(function(){return cr(gt)})}function Vr(){var j={env:Hr,wasi_snapshot_preview1:Hr};function J(Te,we){var Ye=Te.exports;a.asm=Ye,L=a.asm.memory,ce(L.buffer),a.asm.__indirect_function_table,ur(a.asm.__wasm_call_ctors),Rn()}lr();function me(Te){J(Te.instance)}function ae(Te){return Wr().then(function(we){return WebAssembly.instantiate(we,j)}).then(function(we){return we}).then(Te,function(we){T("failed to asynchronously prepare wasm: "+we),Gn(we)})}function Xe(){return!O&&typeof WebAssembly.instantiateStreaming=="function"&&!rt(gt)&&!Dn(gt)&&!p&&typeof fetch=="function"?fetch(gt,{credentials:"same-origin"}).then(function(Te){var we=WebAssembly.instantiateStreaming(Te,j);return we.then(me,function(Ye){return T("wasm streaming compile failed: "+Ye),T("falling back to ArrayBuffer instantiation"),ae(me)})}):ae(me)}if(a.instantiateWasm)try{var He=a.instantiateWasm(j,J);return He}catch(Te){T("Module.instantiateWasm callback failed with error: "+Te),i(Te)}return Xe().catch(i),{}}function jn(j){this.name="ExitStatus",this.message="Program terminated with exit("+j+")",this.status=j}function dr(j){for(;j.length>0;)j.shift()(a)}function pr(){Gn("")}function Ur(){return 4294901760}function wn(){return Ur()}function $s(j,J,me){ee.copyWithin(j>>>0,J>>>0,J+me>>>0)}function hr(j){try{return L.grow(j-Y.byteLength+65535>>>16),ce(L.buffer),1}catch{}}function Qt(j){var J=ee.length;j=j>>>0;var me=Ur();if(j>me)return!1;let ae=(Ye,At)=>Ye+(At-Ye%At)%At;for(var Xe=1;Xe<=4;Xe*=2){var He=J*(1+.2/Xe);He=Math.min(He,j+100663296);var Te=Math.min(me,ae(Math.max(j,He),65536)),we=hr(Te);if(we)return!0}return!1}function qn(j){return 52}function Ts(j,J,me,ae,Xe){return 70}var wa=[null,[],[]];function Pn(j,J){var me=wa[j];J===0||J===10?((j===1?C:T)(D(me,0)),me.length=0):me.push(J)}function Es(j,J,me,ae){for(var Xe=0,He=0;He>>2],we=ye[J+4>>>2];J+=8;for(var Ye=0;Ye>>0]);Xe+=we}return ye[ae>>>2]=Xe,0}function xn(j){var J=a["_"+j];return J}function Fn(j,J){X.set(j,J>>>0)}function yt(j,J,me,ae,Xe){var He={string:ht=>{var un=0;if(ht!=null&&ht!==0){var Yn=(ht.length<<2)+1;un=Ot(Yn),H(ht,un,Yn)}return un},array:ht=>{var un=Ot(ht.length);return Fn(ht,un),un}};function Te(ht){return J==="string"?_(ht):J==="boolean"?!!ht:ht}var we=xn(j),Ye=[],At=0;if(ae)for(var qe=0;qeTe==="number"||Te==="boolean"),He=J!=="string";return He&&Xe&&!ae?xn(j):function(){return yt(j,J,me,arguments)}}var Hr={abort:pr,emscripten_get_heap_max:wn,emscripten_memcpy_big:$s,emscripten_resize_heap:Qt,fd_close:qn,fd_seek:Ts,fd_write:Es};Vr(),a.___wasm_call_ctors=function(){return(a.___wasm_call_ctors=a.asm.__wasm_call_ctors).apply(null,arguments)},a._init=function(){return(a._init=a.asm.init).apply(null,arguments)},a._init_with_threads_count=function(){return(a._init_with_threads_count=a.asm.init_with_threads_count).apply(null,arguments)},a._get_threads_count=function(){return(a._get_threads_count=a.asm.get_threads_count).apply(null,arguments)},a._register_tensor=function(){return(a._register_tensor=a.asm.register_tensor).apply(null,arguments)},a._dispose_data=function(){return(a._dispose_data=a.asm.dispose_data).apply(null,arguments)},a._dispose=function(){return(a._dispose=a.asm.dispose).apply(null,arguments)},a._Abs=function(){return(a._Abs=a.asm.Abs).apply(null,arguments)},a._Acos=function(){return(a._Acos=a.asm.Acos).apply(null,arguments)},a._Acosh=function(){return(a._Acosh=a.asm.Acosh).apply(null,arguments)},a._Add=function(){return(a._Add=a.asm.Add).apply(null,arguments)},a._AddN=function(){return(a._AddN=a.asm.AddN).apply(null,arguments)},a._All=function(){return(a._All=a.asm.All).apply(null,arguments)},a._Any=function(){return(a._Any=a.asm.Any).apply(null,arguments)},a._ArgMax=function(){return(a._ArgMax=a.asm.ArgMax).apply(null,arguments)},a._ArgMin=function(){return(a._ArgMin=a.asm.ArgMin).apply(null,arguments)},a._Asin=function(){return(a._Asin=a.asm.Asin).apply(null,arguments)},a._Asinh=function(){return(a._Asinh=a.asm.Asinh).apply(null,arguments)},a._Atan=function(){return(a._Atan=a.asm.Atan).apply(null,arguments)},a._Atan2=function(){return(a._Atan2=a.asm.Atan2).apply(null,arguments)},a._Atanh=function(){return(a._Atanh=a.asm.Atanh).apply(null,arguments)},a._AvgPool=function(){return(a._AvgPool=a.asm.AvgPool).apply(null,arguments)},a._AvgPool3D=function(){return(a._AvgPool3D=a.asm.AvgPool3D).apply(null,arguments)},a._AvgPool3DGrad=function(){return(a._AvgPool3DGrad=a.asm.AvgPool3DGrad).apply(null,arguments)},a._AvgPoolGrad=function(){return(a._AvgPoolGrad=a.asm.AvgPoolGrad).apply(null,arguments)},a._BatchMatMul=function(){return(a._BatchMatMul=a.asm.BatchMatMul).apply(null,arguments)},a._Bincount=function(){return(a._Bincount=a.asm.Bincount).apply(null,arguments)},a._BitwiseAnd=function(){return(a._BitwiseAnd=a.asm.BitwiseAnd).apply(null,arguments)},a._Ceil=function(){return(a._Ceil=a.asm.Ceil).apply(null,arguments)},a._ClipByValue=function(){return(a._ClipByValue=a.asm.ClipByValue).apply(null,arguments)},a._Conv2D=function(){return(a._Conv2D=a.asm.Conv2D).apply(null,arguments)},a._Conv2DBackpropInput=function(){return(a._Conv2DBackpropInput=a.asm.Conv2DBackpropInput).apply(null,arguments)},a._Conv3D=function(){return(a._Conv3D=a.asm.Conv3D).apply(null,arguments)},a._Conv3DBackpropFilterV2=function(){return(a._Conv3DBackpropFilterV2=a.asm.Conv3DBackpropFilterV2).apply(null,arguments)},a._Conv3DBackpropInputV2=function(){return(a._Conv3DBackpropInputV2=a.asm.Conv3DBackpropInputV2).apply(null,arguments)},a._Cos=function(){return(a._Cos=a.asm.Cos).apply(null,arguments)},a._Cosh=function(){return(a._Cosh=a.asm.Cosh).apply(null,arguments)},a._CropAndResize=function(){return(a._CropAndResize=a.asm.CropAndResize).apply(null,arguments)},a._Cumprod=function(){return(a._Cumprod=a.asm.Cumprod).apply(null,arguments)},a._Cumsum=function(){return(a._Cumsum=a.asm.Cumsum).apply(null,arguments)},a._DenseBincount=function(){return(a._DenseBincount=a.asm.DenseBincount).apply(null,arguments)},a._DepthToSpace=function(){return(a._DepthToSpace=a.asm.DepthToSpace).apply(null,arguments)},a._DepthwiseConv2dNative=function(){return(a._DepthwiseConv2dNative=a.asm.DepthwiseConv2dNative).apply(null,arguments)},a._Diag=function(){return(a._Diag=a.asm.Diag).apply(null,arguments)},a._Dilation2D=function(){return(a._Dilation2D=a.asm.Dilation2D).apply(null,arguments)},a._Dilation2DBackpropFilter=function(){return(a._Dilation2DBackpropFilter=a.asm.Dilation2DBackpropFilter).apply(null,arguments)},a._Dilation2DBackpropInput=function(){return(a._Dilation2DBackpropInput=a.asm.Dilation2DBackpropInput).apply(null,arguments)},a._Elu=function(){return(a._Elu=a.asm.Elu).apply(null,arguments)},a._EluGrad=function(){return(a._EluGrad=a.asm.EluGrad).apply(null,arguments)},a._Equal=function(){return(a._Equal=a.asm.Equal).apply(null,arguments)},a._Erf=function(){return(a._Erf=a.asm.Erf).apply(null,arguments)},a._Exp=function(){return(a._Exp=a.asm.Exp).apply(null,arguments)},a._Expm1=function(){return(a._Expm1=a.asm.Expm1).apply(null,arguments)},a._FlipLeftRight=function(){return(a._FlipLeftRight=a.asm.FlipLeftRight).apply(null,arguments)},a._Floor=function(){return(a._Floor=a.asm.Floor).apply(null,arguments)},a._FloorDiv=function(){return(a._FloorDiv=a.asm.FloorDiv).apply(null,arguments)},a._FusedBatchNorm=function(){return(a._FusedBatchNorm=a.asm.FusedBatchNorm).apply(null,arguments)},a._FusedConv2D=function(){return(a._FusedConv2D=a.asm.FusedConv2D).apply(null,arguments)},a._FusedDepthwiseConv2D=function(){return(a._FusedDepthwiseConv2D=a.asm.FusedDepthwiseConv2D).apply(null,arguments)},a._Gather=function(){return(a._Gather=a.asm.Gather).apply(null,arguments)},a._GatherNd=function(){return(a._GatherNd=a.asm.GatherNd).apply(null,arguments)},a._Greater=function(){return(a._Greater=a.asm.Greater).apply(null,arguments)},a._GreaterEqual=function(){return(a._GreaterEqual=a.asm.GreaterEqual).apply(null,arguments)},a._IsFinite=function(){return(a._IsFinite=a.asm.IsFinite).apply(null,arguments)},a._IsInf=function(){return(a._IsInf=a.asm.IsInf).apply(null,arguments)},a._IsNan=function(){return(a._IsNan=a.asm.IsNan).apply(null,arguments)},a._LRN=function(){return(a._LRN=a.asm.LRN).apply(null,arguments)},a._LRNGrad=function(){return(a._LRNGrad=a.asm.LRNGrad).apply(null,arguments)},a._LeakyRelu=function(){return(a._LeakyRelu=a.asm.LeakyRelu).apply(null,arguments)},a._Less=function(){return(a._Less=a.asm.Less).apply(null,arguments)},a._LessEqual=function(){return(a._LessEqual=a.asm.LessEqual).apply(null,arguments)},a._LinSpace=function(){return(a._LinSpace=a.asm.LinSpace).apply(null,arguments)},a._Log=function(){return(a._Log=a.asm.Log).apply(null,arguments)},a._Log1p=function(){return(a._Log1p=a.asm.Log1p).apply(null,arguments)},a._LogicalAnd=function(){return(a._LogicalAnd=a.asm.LogicalAnd).apply(null,arguments)},a._LogicalNot=function(){return(a._LogicalNot=a.asm.LogicalNot).apply(null,arguments)},a._LogicalOr=function(){return(a._LogicalOr=a.asm.LogicalOr).apply(null,arguments)},a._LogicalXor=function(){return(a._LogicalXor=a.asm.LogicalXor).apply(null,arguments)},a._Max=function(){return(a._Max=a.asm.Max).apply(null,arguments)},a._MaxPool=function(){return(a._MaxPool=a.asm.MaxPool).apply(null,arguments)},a._MaxPool3D=function(){return(a._MaxPool3D=a.asm.MaxPool3D).apply(null,arguments)},a._MaxPool3DGrad=function(){return(a._MaxPool3DGrad=a.asm.MaxPool3DGrad).apply(null,arguments)},a._MaxPoolGrad=function(){return(a._MaxPoolGrad=a.asm.MaxPoolGrad).apply(null,arguments)},a._MaxPoolWithArgmax=function(){return(a._MaxPoolWithArgmax=a.asm.MaxPoolWithArgmax).apply(null,arguments)},a._Maximum=function(){return(a._Maximum=a.asm.Maximum).apply(null,arguments)},a._Mean=function(){return(a._Mean=a.asm.Mean).apply(null,arguments)},a._Min=function(){return(a._Min=a.asm.Min).apply(null,arguments)},a._Minimum=function(){return(a._Minimum=a.asm.Minimum).apply(null,arguments)},a._MirrorPad=function(){return(a._MirrorPad=a.asm.MirrorPad).apply(null,arguments)},a._Mod=function(){return(a._Mod=a.asm.Mod).apply(null,arguments)},a._Multinomial=function(){return(a._Multinomial=a.asm.Multinomial).apply(null,arguments)},a._Multiply=function(){return(a._Multiply=a.asm.Multiply).apply(null,arguments)},a._Neg=function(){return(a._Neg=a.asm.Neg).apply(null,arguments)},a._NonMaxSuppressionV3=function(){return(a._NonMaxSuppressionV3=a.asm.NonMaxSuppressionV3).apply(null,arguments)},a._NonMaxSuppressionV4=function(){return(a._NonMaxSuppressionV4=a.asm.NonMaxSuppressionV4).apply(null,arguments)},a._NonMaxSuppressionV5=function(){return(a._NonMaxSuppressionV5=a.asm.NonMaxSuppressionV5).apply(null,arguments)},a._NotEqual=function(){return(a._NotEqual=a.asm.NotEqual).apply(null,arguments)},a._OneHot=function(){return(a._OneHot=a.asm.OneHot).apply(null,arguments)},a._PadV2=function(){return(a._PadV2=a.asm.PadV2).apply(null,arguments)},a._Pow=function(){return(a._Pow=a.asm.Pow).apply(null,arguments)},a._Prelu=function(){return(a._Prelu=a.asm.Prelu).apply(null,arguments)},a._Prod=function(){return(a._Prod=a.asm.Prod).apply(null,arguments)},a._RealDiv=function(){return(a._RealDiv=a.asm.RealDiv).apply(null,arguments)},a._Reciprocal=function(){return(a._Reciprocal=a.asm.Reciprocal).apply(null,arguments)},a._Relu=function(){return(a._Relu=a.asm.Relu).apply(null,arguments)},a._Relu6=function(){return(a._Relu6=a.asm.Relu6).apply(null,arguments)},a._ResizeBilinear=function(){return(a._ResizeBilinear=a.asm.ResizeBilinear).apply(null,arguments)},a._ResizeBilinearGrad=function(){return(a._ResizeBilinearGrad=a.asm.ResizeBilinearGrad).apply(null,arguments)},a._ResizeNearestNeighbor=function(){return(a._ResizeNearestNeighbor=a.asm.ResizeNearestNeighbor).apply(null,arguments)},a._ResizeNearestNeighborGrad=function(){return(a._ResizeNearestNeighborGrad=a.asm.ResizeNearestNeighborGrad).apply(null,arguments)},a._Reverse=function(){return(a._Reverse=a.asm.Reverse).apply(null,arguments)},a._RotateWithOffset=function(){return(a._RotateWithOffset=a.asm.RotateWithOffset).apply(null,arguments)},a._Round=function(){return(a._Round=a.asm.Round).apply(null,arguments)},a._Rsqrt=function(){return(a._Rsqrt=a.asm.Rsqrt).apply(null,arguments)},a._ScatterNd=function(){return(a._ScatterNd=a.asm.ScatterNd).apply(null,arguments)},a._SearchSorted=function(){return(a._SearchSorted=a.asm.SearchSorted).apply(null,arguments)},a._SelectV2=function(){return(a._SelectV2=a.asm.SelectV2).apply(null,arguments)},a._Selu=function(){return(a._Selu=a.asm.Selu).apply(null,arguments)},a._Sigmoid=function(){return(a._Sigmoid=a.asm.Sigmoid).apply(null,arguments)},a._Sign=function(){return(a._Sign=a.asm.Sign).apply(null,arguments)},a._Sin=function(){return(a._Sin=a.asm.Sin).apply(null,arguments)},a._Sinh=function(){return(a._Sinh=a.asm.Sinh).apply(null,arguments)},a._Softmax=function(){return(a._Softmax=a.asm.Softmax).apply(null,arguments)},a._Softplus=function(){return(a._Softplus=a.asm.Softplus).apply(null,arguments)},a._SparseFillEmptyRows=function(){return(a._SparseFillEmptyRows=a.asm.SparseFillEmptyRows).apply(null,arguments)},a._SparseReshape=function(){return(a._SparseReshape=a.asm.SparseReshape).apply(null,arguments)},a._SparseSegmentReduction=function(){return(a._SparseSegmentReduction=a.asm.SparseSegmentReduction).apply(null,arguments)},a._SparseToDense=function(){return(a._SparseToDense=a.asm.SparseToDense).apply(null,arguments)},a._Sqrt=function(){return(a._Sqrt=a.asm.Sqrt).apply(null,arguments)},a._Square=function(){return(a._Square=a.asm.Square).apply(null,arguments)},a._SquaredDifference=function(){return(a._SquaredDifference=a.asm.SquaredDifference).apply(null,arguments)},a._Step=function(){return(a._Step=a.asm.Step).apply(null,arguments)},a._StridedSlice=function(){return(a._StridedSlice=a.asm.StridedSlice).apply(null,arguments)},a._Sub=function(){return(a._Sub=a.asm.Sub).apply(null,arguments)},a._Sum=function(){return(a._Sum=a.asm.Sum).apply(null,arguments)},a._Tan=function(){return(a._Tan=a.asm.Tan).apply(null,arguments)},a._Tanh=function(){return(a._Tanh=a.asm.Tanh).apply(null,arguments)},a._TensorScatterUpdate=function(){return(a._TensorScatterUpdate=a.asm.TensorScatterUpdate).apply(null,arguments)},a._Tile=function(){return(a._Tile=a.asm.Tile).apply(null,arguments)},a._TopK=function(){return(a._TopK=a.asm.TopK).apply(null,arguments)},a._Transform=function(){return(a._Transform=a.asm.Transform).apply(null,arguments)},a._Transpose=function(){return(a._Transpose=a.asm.Transpose).apply(null,arguments)},a.__FusedMatMul=function(){return(a.__FusedMatMul=a.asm._FusedMatMul).apply(null,arguments)},a._malloc=function(){return(a._malloc=a.asm.malloc).apply(null,arguments)},a._free=function(){return(a._free=a.asm.free).apply(null,arguments)},a.___errno_location=function(){return(a.___errno_location=a.asm.__errno_location).apply(null,arguments)};var fr=a.stackSave=function(){return(fr=a.stackSave=a.asm.stackSave).apply(null,arguments)},an=a.stackRestore=function(){return(an=a.stackRestore=a.asm.stackRestore).apply(null,arguments)},Ot=a.stackAlloc=function(){return(Ot=a.stackAlloc=a.asm.stackAlloc).apply(null,arguments)};a.dynCall_iijjiiii=function(){return(a.dynCall_iijjiiii=a.asm.dynCall_iijjiiii).apply(null,arguments)},a.dynCall_jiji=function(){return(a.dynCall_jiji=a.asm.dynCall_jiji).apply(null,arguments)},a.cwrap=As;var Kn;bn=function j(){Kn||Gr(),Kn||(bn=j)};function Gr(j){if(ot>0||(Ve(),ot>0))return;function J(){Kn||(Kn=!0,a.calledRun=!0,!B&&(Oe(),o(a),a.onRuntimeInitialized&&a.onRuntimeInitialized(),Et()))}a.setStatus?(a.setStatus("Running..."),setTimeout(function(){setTimeout(function(){a.setStatus("")},1),J()},1)):J()}if(a.preInit)for(typeof a.preInit=="function"&&(a.preInit=[a.preInit]);a.preInit.length>0;)a.preInit.pop()();Gr();var vn;l&&(vn={uncaughtException:process.listeners("uncaughtException").filter(function(j){return!l.uncaughtException.indexOf(j)>-1}),unhandledRejection:process.listeners("unhandledRejection").filter(function(j){return!l.unhandledRejection.indexOf(j)>-1})});var On;if(typeof s<"u")On=s;else if(typeof WasmBackendModuleThreadedSimd<"u")On=WasmBackendModuleThreadedSimd;else throw new Error("Could not find wasm module in post.js");if(vn){var on=On._dispose;On._dispose=function(){on(),vn.uncaughtException.forEach(function(j){process.removeListener("uncaughtException",j)}),vn.unhandledRejection.forEach(function(j){process.removeListener("unhandledRejection",j)})}}return s.ready})})();n.exports=t})(Uu)),Uu.exports}var $P=NP(),Zy=$d($P),TP=Object.freeze({__proto__:null,default:Zy});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Zp=Qy||kP,EP=Zy||TP;class AP extends Gl{constructor(e){super(),this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.initWithThreadsCount(LP),this.wasm.tfjs.getThreadsCount(),this.dataIdMap=new Kh(this,us())}write(e,t,r){const s={id:this.dataIdNextNumber++};return this.move(s,e,t,r,1),s}numDataIds(){return this.dataIdMap.numDataIds()}async time(e){const t=ta();return e(),{kernelMs:ta()-t}}move(e,t,r,s,a){const o=this.dataIdNextNumber++;if(s==="string"){const u=t;this.dataIdMap.set(e,{id:o,stringBytes:u,shape:r,dtype:s,memoryOffset:null,refCount:a});return}const i=q(r),l=i*qa(s),c=this.wasm._malloc(l)>>>0;this.dataIdMap.set(e,{id:o,memoryOffset:c,shape:r,dtype:s,refCount:a}),this.wasm.tfjs.registerTensor(o,i,c),t!=null&&this.wasm.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,l),c)}async read(e){return this.readSync(e)}readSync(e,t,r){const{memoryOffset:s,dtype:a,shape:o,stringBytes:i}=this.dataIdMap.get(e);if(a==="string")return(t==null||t===0)&&(r==null||r>=i.length)?i:i.slice(t,r);t=t||0,r=r||q(o);const l=qa(a),c=this.wasm.HEAPU8.slice(s+t*l,s+r*l);return PP(c.buffer,a)}disposeData(e,t=!1){if(this.dataIdMap.has(e)){const r=this.dataIdMap.get(e);if(r.refCount--,!t&&r.refCount>0)return!1;this.wasm._free(r.memoryOffset),this.wasm.tfjs.disposeData(r.id),this.dataIdMap.delete(e)}return!0}refCount(e){return this.dataIdMap.has(e)?this.dataIdMap.get(e).refCount:0}incRef(e){const t=this.dataIdMap.get(e);t!=null&&t.refCount++}floatPrecision(){return 32}getMemoryOffset(e){return this.dataIdMap.get(e).memoryOffset}dispose(){this.wasm.tfjs.dispose(),"PThread"in this.wasm&&this.wasm.PThread.terminateAllThreads(),this.wasm=null}memory(){return{unreliable:!1}}makeOutput(e,t,r,s){let a;if(r==null)a=this.write(s??null,e,t);else{const o=this.dataIdNextNumber++;a={id:o},this.dataIdMap.set(a,{id:o,memoryOffset:r,shape:e,dtype:t,refCount:1});const i=q(e);this.wasm.tfjs.registerTensor(o,i,r)}return{dataId:a,shape:e,dtype:t}}typedArrayFromHeap({shape:e,dtype:t,dataId:r}){const s=this.wasm.HEAPU8.buffer,{memoryOffset:a}=this.dataIdMap.get(r),o=q(e);switch(t){case"float32":return new Float32Array(s,a,o);case"int32":return new Int32Array(s,a,o);case"bool":return new Uint8Array(s,a,o);default:throw new Error(`Unknown dtype ${t}`)}}}function RP(n){return(e,t)=>(Xw(n,{credentials:"same-origin"}).then(r=>{r.ok||e.env.a(`failed to load wasm binary file at '${n}'`),r.arrayBuffer().then(s=>{WebAssembly.instantiate(s,e).then(a=>{t(a.instance,a.module)})})}),{})}function Jp(n,e,t){let r="tfjs-backend-wasm.wasm";return n&&e?r="tfjs-backend-wasm-threaded-simd.wasm":n&&(r="tfjs-backend-wasm-simd.wasm"),Ha!=null&&Ha[r]!=null?Ha[r]:t+r}async function DP(){const[n,e]=await Promise.all([fe().getAsync("WASM_HAS_SIMD_SUPPORT"),fe().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise((t,r)=>{const s={};s.locateFile=(i,l)=>{if(i.endsWith(".worker.js")){const c=CP.wasmWorkerContents.replace(/\n/g,"\\n"),u=new Blob([c],{type:"application/javascript"});return URL.createObjectURL(u)}return i.endsWith(".wasm")?Jp(n,e,Wa??l):l+i},Jy&&(s.instantiateWasm=RP(Jp(n,e,Wa??"")));let a=!1;s.onAbort=()=>{if(a||Go)return;Go=!0,r({message:"Make sure the server can serve the `.wasm` file relative to the bundled js file. For more details see https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-wasm/README.md#using-bundlers"})};let o;e&&n&&OP==null?(s.mainScriptUrlOrBlob=new Blob(["var WasmBackendModuleThreadedSimd = "+Zp.toString()],{type:"text/javascript"}),o=Zp(s)):o=EP(s),o.then(i=>{a=!0,Go=!1;const l=null;i.tfjs={init:i.cwrap("init",null,[]),initWithThreadsCount:i.cwrap("init_with_threads_count",null,["number"]),getThreadsCount:i.cwrap("get_threads_count","number",[]),registerTensor:i.cwrap("register_tensor",null,["number","number","number"]),disposeData:i.cwrap("dispose_data",l,["number"]),dispose:i.cwrap("dispose",l,[])},t({wasm:i})}).catch(r)})}function PP(n,e){switch(e){case"float32":return new Float32Array(n);case"int32":return new Int32Array(n);case"bool":return new Uint8Array(n);default:throw new Error(`Unknown dtype ${e}`)}}const FP=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"];let OP=null,Wa=null,Ha={},Go=!1,Jy=!1;function MP(n,e=!1){if(Go)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPaths()` before you call `tf.setBackend()` or `tf.ready()`");if(typeof n=="string")Wa=n;else{Ha=n;const t=FP.filter(r=>Ha[r]==null);if(t.length>0)throw new Error(`There were no entries found for the following binaries: ${t.join(",")}. Please either call setWasmPaths with a map providing a path for each binary, or with a string indicating the directory where all the binaries can be found.`)}Jy=e}let LP=-1;/** + * @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. + * ============================================================================= + */const zP=2;Bf("wasm",async()=>{const{wasm:n}=await DP();return new AP(n)},zP);var Hu={},eh;function BP(){return eh||(eh=1,(function(){var n;function e(h){var y=0;return function(){return y>>0)+"_",E=0;return y}),a("Symbol.iterator",function(h){if(h)return h;h=Symbol("Symbol.iterator");for(var y="Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" "),x=0;x"u"?!0:(typeof R=="function"?R=new R("unhandledrejection",{cancelable:!0}):typeof W=="function"?R=new W("unhandledrejection",{cancelable:!0}):(R=s.document.createEvent("CustomEvent"),R.initCustomEvent("unhandledrejection",!1,!0,R)),R.promise=this,R.reason=this.j,G(R))},y.prototype.H=function(){if(this.h!=null){for(var R=0;Rx&&(x=Math.max(0,E+x)),(k==null||k>E)&&(k=E),k=Number(k),0>k&&(k=Math.max(0,E+k)),x=Number(x||0);xx&&(x=Math.max(x+E,0));x"u"||x.execScript("var "+h[0]);for(var k;h.length&&(k=h.shift());)h.length||y===void 0?x[k]&&x[k]!==Object.prototype[k]?x=x[k]:x=x[k]={}:x[k]=y}function ee(h){var y;e:{if((y=Y.navigator)&&(y=y.userAgent))break e;y=""}return y.indexOf(h)!=-1}var ye=Array.prototype.map?function(h,y){return Array.prototype.map.call(h,y,void 0)}:function(h,y){for(var x=h.length,k=Array(x),E=typeof h=="string"?h.split(""):h,F=0;F>4),R!=64&&(y(F<<4&240|R>>2),W!=64&&y(R<<6&192|W))}}function Ve(){if(!be){be={};for(var h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),y=["+/=","+/","-_=","-_.","-_"],x=0;5>x;x++){var k=h.concat(y[x].split(""));ce[x]=k;for(var E=0;E>2];R=y[(R&3)<<4|W>>4],W=y[(W&15)<<2|G>>6],G=y[G&63],x[F++]=Q+R+W+G}switch(Q=0,G=k,h.length-E){case 2:Q=h[E+1],G=y[(Q&15)<<2]||k;case 1:h=h[E],x[F]=y[h>>2]+y[(h&3)<<4|Q>>4]+G+k}return x.join("")}for(y="";10240h;h=Math.abs(h);var x=h>>>0;h=Math.floor((h-x)/4294967296),y&&(x=i(cr(x,h)),y=x.next().value,h=x.next().value,x=y),lt=x>>>0,rt=h>>>0}var gt=typeof BigInt=="function";function cr(h,y){return y=~y,h?h=~h+1:y+=1,[h,y]}function Wr(h,y){this.i=h>>>0,this.h=y>>>0}function Vr(h){if(!h)return jn||(jn=new Wr(0,0));if(!/^-?\d+$/.test(h))return null;if(16>h.length)Dn(Number(h));else if(gt)h=BigInt(h),lt=Number(h&BigInt(4294967295))>>>0,rt=Number(h>>BigInt(32)&BigInt(4294967295));else{var y=+(h[0]==="-");rt=lt=0;for(var x=h.length,k=y,E=(x-y)%6+y;E<=x;k=E,E+=6)k=Number(h.slice(k,E)),rt*=1e6,lt=1e6*lt+k,4294967296<=lt&&(rt+=lt/4294967296|0,lt%=4294967296);y&&(y=i(cr(lt,rt)),h=y.next().value,y=y.next().value,lt=h,rt=y)}return new Wr(lt,rt)}var jn;function dr(h,y){return Error("Invalid wire type: "+h+" (at position "+y+")")}function pr(){return Error("Failed to read varint, encoding is invalid.")}function Ur(h,y){return Error("Tried to read past the end of the data "+y+" > "+h)}function wn(){throw Error("Invalid UTF8")}function $s(h,y){return y=String.fromCharCode.apply(null,y),h==null?y:h+y}var hr=void 0,Qt,qn=typeof TextDecoder<"u",Ts,wa=typeof TextEncoder<"u",Pn;function Es(h){if(h!==Rn)throw Error("illegal external caller")}function xn(h,y){if(Es(y),this.V=h,h!=null&&h.length===0)throw Error("ByteString should be constructed with non-empty values")}function Fn(){return Pn||(Pn=new xn(null,Rn))}function yt(h){Es(Rn);var y=h.V;return y=y==null||Oe&&y!=null&&y instanceof Uint8Array?y:typeof y=="string"?ot(y):null,y==null?y:h.V=y}function As(h){if(typeof h=="string")return{buffer:ot(h),C:!1};if(Array.isArray(h))return{buffer:new Uint8Array(h),C:!1};if(h.constructor===Uint8Array)return{buffer:h,C:!1};if(h.constructor===ArrayBuffer)return{buffer:new Uint8Array(h),C:!1};if(h.constructor===xn)return{buffer:yt(h)||lr(),C:!0};if(h instanceof Uint8Array)return{buffer:new Uint8Array(h.buffer,h.byteOffset,h.byteLength),C:!1};throw Error("Type not convertible to a Uint8Array, expected a Uint8Array, an ArrayBuffer, a base64 encoded string, a ByteString or an Array of numbers")}function Hr(h,y){this.i=null,this.m=!1,this.h=this.j=this.l=0,fr(this,h,y)}function fr(h,y,x){x=x===void 0?{}:x,h.S=x.S===void 0?!1:x.S,y&&(y=As(y),h.i=y.buffer,h.m=y.C,h.l=0,h.j=h.i.length,h.h=h.l)}Hr.prototype.reset=function(){this.h=this.l};function an(h,y){if(h.h=y,y>h.j)throw Ur(h.j,y)}function Ot(h){var y=h.i,x=h.h,k=y[x++],E=k&127;if(k&128&&(k=y[x++],E|=(k&127)<<7,k&128&&(k=y[x++],E|=(k&127)<<14,k&128&&(k=y[x++],E|=(k&127)<<21,k&128&&(k=y[x++],E|=k<<28,k&128&&y[x++]&128&&y[x++]&128&&y[x++]&128&&y[x++]&128&&y[x++]&128)))))throw pr();return an(h,x),E}function Kn(h,y){if(0>y)throw Error("Tried to read a negative byte length: "+y);var x=h.h,k=x+y;if(k>h.j)throw Ur(y,h.j-x);return h.h=k,x}var Gr=[];function vn(){this.h=[]}vn.prototype.length=function(){return this.h.length},vn.prototype.end=function(){var h=this.h;return this.h=[],h};function On(h,y,x){for(;0>>7|x<<25)>>>0,x>>>=7;h.h.push(y)}function on(h,y){for(;127>>=7;h.h.push(y)}function j(h,y){if(Gr.length){var x=Gr.pop();fr(x,h,y),h=x}else h=new Hr(h,y);this.h=h,this.j=this.h.h,this.i=this.l=-1,this.setOptions(y)}j.prototype.setOptions=function(h){h=h===void 0?{}:h,this.ca=h.ca===void 0?!1:h.ca},j.prototype.reset=function(){this.h.reset(),this.j=this.h.h,this.i=this.l=-1};function J(h){var y=h.h;if(y.h==y.j)return!1;h.j=h.h.h;var x=Ot(h.h)>>>0;if(y=x>>>3,x&=7,!(0<=x&&5>=x))throw dr(x,h.j);if(1>y)throw Error("Invalid field number: "+y+" (at position "+h.j+")");return h.l=y,h.i=x,!0}function me(h){switch(h.i){case 0:if(h.i!=0)me(h);else e:{h=h.h;for(var y=h.h,x=y+10,k=h.i;y>>0,h=h.h,an(h,h.h+y));break;case 5:h=h.h,an(h,h.h+4);break;case 3:y=h.l;do{if(!J(h))throw Error("Unmatched start-group tag: stream EOF");if(h.i==4){if(h.l!=y)throw Error("Unmatched end-group tag");break}me(h)}while(!0);break;default:throw dr(h.i,h.j)}}var ae=[];function Xe(){this.j=[],this.i=0,this.h=new vn}function He(h,y){y.length!==0&&(h.j.push(y),h.i+=y.length)}function Te(h,y){if(y=y.R){He(h,h.h.end());for(var x=0;x=h.i?h.B?h.B[y]:void 0:h.o[y+h.G]}function ln(h,y,x,k){xa(h),qr(h,y,x,k)}function qr(h,y,x,k){h.j&&(h.j=void 0),y>=h.i||k?mo(h)[y]=x:(h.o[y+h.G]=x,(h=h.B)&&y in h&&delete h[y])}function Ps(h,y,x,k){var E=kt(h,y);Array.isArray(E)||(E=jr);var F=qe(E);if(F&1||Xn(E),k)F&2||Ye(E,2),x&1||Object.freeze(E);else{k=!(x&2);var R=F&2;x&1||!R?k&&F&16&&!R&&At(E,16):(E=Xn(Array.prototype.slice.call(E)),qr(h,y,E))}return E}function Sa(h,y){var x=kt(h,y),k=x==null?x:typeof x=="number"||x==="NaN"||x==="Infinity"||x==="-Infinity"?Number(x):void 0;return k!=null&&k!==x&&qr(h,y,k),k}function Fs(h,y,x,k,E){h.h||(h.h={});var F=h.h[x],R=Ps(h,x,3,E);if(!F){var W=R;F=[];var G=!!(qe(h.o)&16);R=!!(qe(W)&2);var Q=W;!E&&R&&(W=Array.prototype.slice.call(W));for(var oe=R,ke=0;keR&&typeof h[R]!="number"){var W=h[R++];x(y,W)}for(;R>>0,h=2*(R>>31)+1,F=R>>>23&255,R&=8388607,ln(y,x,F==255?R?NaN:1/0*h:F==0?h*Math.pow(2,-149)*R:h*Math.pow(2,F-150)*(R+Math.pow(2,23))),!0},function(h,y,x){if(y=Sa(y,x),y!=null){on(h.h,8*x+5),h=h.h;var k=+y;k===0?0<1/k?lt=rt=0:(rt=0,lt=2147483648):isNaN(k)?(rt=0,lt=2147483647):(k=(x=0>k?-2147483648:0)?-k:k,34028234663852886e22>>0):11754943508222875e-54>k?(k=Math.round(k/Math.pow(2,-149)),rt=0,lt=(x|k)>>>0):(y=Math.floor(Math.log(k)/Math.LN2),k*=Math.pow(2,-y),k=Math.round(8388608*k),16777216<=k&&++y,rt=0,lt=(x|y+127<<23|k&8388607)>>>0)),x=lt,h.h.push(x>>>0&255),h.h.push(x>>>8&255),h.h.push(x>>>16&255),h.h.push(x>>>24&255)}}),Lt=pe(function(h,y,x){if(h.i!==0)return!1;var k=h.h,E=0,F=h=0,R=k.i,W=k.h;do{var G=R[W++];E|=(G&127)<F&&G&128);for(32>4),F=3;32>F&&G&128;F+=7)G=R[W++],h|=(G&127)<G)k=E>>>0,G=h>>>0,(h=G&2147483648)&&(k=~k+1>>>0,G=~G>>>0,k==0&&(G=G+1>>>0)),k=4294967296*G+(k>>>0);else throw pr();return ln(y,x,h?-k:k),!0},function(h,y,x){y=kt(y,x),y!=null&&(typeof y=="string"&&Vr(y),y!=null&&(on(h.h,8*x),typeof y=="number"?(h=h.h,Dn(y),On(h,lt,rt)):(x=Vr(y),On(h.h,x.i,x.h))))}),In=pe(function(h,y,x){return h.i!==0?!1:(ln(y,x,Ot(h.h)),!0)},function(h,y,x){if(y=kt(y,x),y!=null&&y!=null)if(on(h.h,8*x),h=h.h,x=y,0<=x)on(h,x);else{for(y=0;9>y;y++)h.h.push(x&127|128),x>>=7;h.h.push(1)}}),Ea=pe(function(h,y,x){if(h.i!==2)return!1;var k=Ot(h.h)>>>0;h=h.h;var E=Kn(h,k);if(h=h.i,qn){var F=h,R;(R=Qt)||(R=Qt=new TextDecoder("utf-8",{fatal:!0})),h=E+k,F=E===0&&h===F.length?F:F.subarray(E,h);try{var W=R.decode(F)}catch(ke){if(hr===void 0){try{R.decode(new Uint8Array([128]))}catch{}try{R.decode(new Uint8Array([97])),hr=!0}catch{hr=!1}}throw!hr&&(Qt=void 0),ke}}else{W=E,k=W+k,E=[];for(var G=null,Q,oe;WQ?E.push(Q):224>Q?W>=k?wn():(oe=h[W++],194>Q||(oe&192)!==128?(W--,wn()):E.push((Q&31)<<6|oe&63)):240>Q?W>=k-1?wn():(oe=h[W++],(oe&192)!==128||Q===224&&160>oe||Q===237&&160<=oe||((F=h[W++])&192)!==128?(W--,wn()):E.push((Q&15)<<12|(oe&63)<<6|F&63)):244>=Q?W>=k-2?wn():(oe=h[W++],(oe&192)!==128||(Q<<28)+(oe-144)>>30!==0||((F=h[W++])&192)!==128||((R=h[W++])&192)!==128?(W--,wn()):(Q=(Q&7)<<18|(oe&63)<<12|(F&63)<<6|R&63,Q-=65536,E.push((Q>>10&1023)+55296,(Q&1023)+56320))):wn(),8192<=E.length&&(G=$s(G,E),E.length=0);W=$s(G,E)}return ln(y,x,W),!0},function(h,y,x){if(y=kt(y,x),y!=null){var k=!1;if(k=k===void 0?!1:k,wa){if(k&&/(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])/.test(y))throw Error("Found an unpaired surrogate");y=(Ts||(Ts=new TextEncoder)).encode(y)}else{for(var E=0,F=new Uint8Array(3*y.length),R=0;RW)F[E++]=W;else{if(2048>W)F[E++]=W>>6|192;else{if(55296<=W&&57343>=W){if(56319>=W&&R=G){W=1024*(W-55296)+G-56320+65536,F[E++]=W>>18|240,F[E++]=W>>12&63|128,F[E++]=W>>6&63|128,F[E++]=W&63|128;continue}else R--}if(k)throw Error("Found an unpaired surrogate");W=65533}F[E++]=W>>12|224,F[E++]=W>>6&63|128}F[E++]=W&63|128}}y=E===F.length?F:F.subarray(0,E)}on(h.h,8*x+2),on(h.h,y.length),He(h,h.h.end()),He(h,y)}}),Us=pe(function(h,y,x,k,E){if(h.i!==2)return!1;y=go(y,x,k),x=h.h.j,k=Ot(h.h)>>>0;var F=h.h.h+k,R=F-x;if(0>=R&&(h.h.j=F,E(y,h,void 0,void 0,void 0),R=F-h.h.h),R)throw Error("Message parsing ended unexpectedly. Expected to read "+(k+" bytes, instead read "+(k-R)+" bytes, either the data ended unexpectedly or the message misreported its own length"));return h.h.h=F,h.h.j=x,!0},function(h,y,x,k,E){if(y=Ia(y,k,x),y!=null)for(k=0;k>>=7,R.i++;F.push(W),R.i++}});function Aa(h){return function(y,x){e:{if(ae.length){var k=ae.pop();k.setOptions(x),fr(k.h,y,x),y=k}else y=new j(y,x);try{var E=Ie(h),F=Ne(new E.P,y,E);break e}finally{E=y.h,E.i=null,E.m=!1,E.l=0,E.j=0,E.h=0,E.S=!1,y.l=-1,y.i=-1,100>ae.length&&ae.push(y)}F=void 0}return F}}function vt(h){return function(){var y=new Xe;ue(this,y,mr(h)),He(y,y.h.end());for(var x=new Uint8Array(y.i),k=y.j,E=k.length,F=0,R=0;R15);sn.registerFlag("WEBGPU_CPU_FORWARD",()=>!0);sn.registerFlag("WEBGPU_MATMUL_PROGRAM_TYPE",()=>-1);sn.registerFlag("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE",()=>!0);sn.registerFlag("WEBGPU_USE_LOW_POWER_GPU",()=>!1);sn.registerFlag("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e3);sn.registerFlag("WEBGPU_USE_PROFILE_TOOL",()=>!1);sn.registerFlag("WEBGPU_IMPORT_EXTERNAL_TEXTURE",()=>!0);sn.registerFlag("WEBGPU_USE_NAIVE_CONV2D_DEBUG",()=>!1);sn.registerFlag("WEBGPU_THRESHOLD_TO_INCREASE_WORKGROUPS_FOR_MATMUL",()=>-1);sn.registerFlag("WEBGPU_CONV_SEPARATE_IM2COL_SHADER",()=>!1);sn.registerFlag("WEBGPU_PRINT_SHADER",()=>"");sn.registerFlag("WEBGPU_ENGINE_COMPILE_ONLY",()=>!1);/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */class VP{constructor(e){e&&(this.vendor=e.vendor,this.architecture=e.architecture,this.intelGPUGeneration=this.getIntelGPUGeneration())}getIntelGPUGeneration(){if(this.isIntel()){if(this.architecture.startsWith("gen"))return Number(this.architecture.match(/\d+/));if(this.architecture.startsWith("xe"))return 12}return 0}isIntel(){return this.vendor==="intel"}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class UP{constructor(e){this.device=e,this.numUsedBuffers=0,this.numFreeBuffers=0,this.freeBuffers=new Map,this.usedBuffers=new Map,this.numBytesUsed=0,this.numBytesAllocated=0}acquireBuffer(e,t,r=!1,s=!0){let a;const o=th(e,t);return s?(this.freeBuffers.has(o)||this.freeBuffers.set(o,[]),this.freeBuffers.get(o).length>0?(a=this.freeBuffers.get(o).pop(),this.numFreeBuffers--):(a=this.device.createBuffer({size:e,usage:t,mappedAtCreation:r}),this.numBytesAllocated+=e)):(a=this.device.createBuffer({size:e,usage:t,mappedAtCreation:r}),this.numBytesAllocated+=e),this.usedBuffers.has(o)||this.usedBuffers.set(o,[]),this.usedBuffers.get(o).push(a),this.numUsedBuffers++,this.numBytesUsed+=e,a}releaseBuffer(e,t=!0){if(this.freeBuffers.size===0)return;const r=e.size,s=e.usage,a=th(r,s),o=this.usedBuffers.get(a),i=o.indexOf(e);if(i<0)throw new Error("Cannot find the buffer in buffer manager");o[i]=o[o.length-1],o.pop(),this.numUsedBuffers--,this.numBytesUsed-=r,t?(this.freeBuffers.get(a).push(e),this.numFreeBuffers++):(e.destroy(),this.numBytesAllocated-=r)}getNumUsedBuffers(){return this.numUsedBuffers}getNumFreeBuffers(){return this.numFreeBuffers}dispose(){this.freeBuffers.forEach((e,t)=>{e.forEach(r=>{r.destroy()})}),this.usedBuffers.forEach((e,t)=>{e.forEach(r=>{r.destroy()})}),this.freeBuffers=new Map,this.usedBuffers=new Map,this.numUsedBuffers=0,this.numFreeBuffers=0,this.numBytesUsed=0,this.numBytesAllocated=0}}function th(n,e){return`${n}_${e}`}/** + * @license + * Copyright 2022 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. + * ============================================================================= + */class HP{constructor(e){this.device=e,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures=new Map,this.usedTextures=new Map,this.numBytesUsed=0,this.numBytesAllocated=0}acquireTexture(e,t,r,s){const a=rh(r),o=e*t*a,i=nh(e,t,r,s);if(this.freeTextures.has(i)||this.freeTextures.set(i,[]),this.usedTextures.has(i)||this.usedTextures.set(i,[]),this.numBytesUsed+=o,this.numUsedTextures++,this.freeTextures.get(i).length>0){this.numFreeTextures--;const c=this.freeTextures.get(i).shift();return this.usedTextures.get(i).push(c),c}this.numBytesAllocated+=o;const l=this.device.createTexture({size:[e,t],format:r,usage:s});return this.usedTextures.get(i).push(l),l}releaseTexture(e){if(this.freeTextures.size===0)return;const t=e.width,r=e.height,s=e.format,a=e.usage,o=nh(t,r,s,a);this.freeTextures.has(o)||this.freeTextures.set(o,[]),this.freeTextures.get(o).push(e),this.numFreeTextures++,this.numUsedTextures--;const i=this.usedTextures.get(o),l=i.indexOf(e);if(l<0)throw new Error("Cannot release a texture that was never provided by this texture manager");i.splice(l,1);const c=rh(s),u=t*r*c;this.numBytesUsed-=u}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){this.freeTextures.forEach((e,t)=>{e.forEach(r=>{r.destroy()})}),this.usedTextures.forEach((e,t)=>{e.forEach(r=>{r.destroy()})}),this.freeTextures=new Map,this.usedTextures=new Map,this.numUsedTextures=0,this.numFreeTextures=0,this.numBytesUsed=0,this.numBytesAllocated=0}}function nh(n,e,t,r){return`${n}_${e}_${t}_${r}`}function rh(n){if(n==="rgba8unorm")return 16;throw new Error(`${n} is not supported!`)}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function GP(n,e){if(Math.max(...n)>5)throw new Error("Cannot symbolically compute strides for rank > 6 tensor.");const t=n.length,r="xyzwuv",s=n.map(o=>`${e}.${r[o]}`),a=new Array(t-1);a[t-2]=s[t-1];for(let o=t-3;o>=0;--o)a[o]=`(${a[o+1]} * ${s[o+1]})`;return a}const zr=(n,e,t)=>t==="int32"?`atomicAdd(${n}, bitcast(${e}));`:` + { + var oldValue = 0; + loop { + let newValueF32 = bitcast(oldValue) + (${e}); + let newValue = bitcast(newValueF32); + let res = atomicCompareExchangeWeak(${n}, oldValue, newValue); + if res.exchanged { + break; + } + oldValue = res.old_value; + } + }`;/** + * @license + * Copyright 2022 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 ua;(function(n){n[n.FROM_PIXELS=0]="FROM_PIXELS",n[n.DRAW=1]="DRAW"})(ua||(ua={}));const jP=(n,e,t,r,s)=>{const a={dtype:r.dtype,shape:r.shape},o=KP(t,a,e),i=n.createShaderModule({code:o,label:e.constructor.name});let l=fe().get("WEBGPU_PRINT_SHADER");if(l!==""){l=l.toLowerCase();const c=l.split(",");(l==="all"||c.some(u=>e.shaderKey.toLowerCase().includes(u)))&&(console.group(e.shaderKey),console.debug(o),console.groupEnd())}return s?n.createComputePipelineAsync({compute:{module:i,entryPoint:"_start"},label:e.constructor.name,layout:"auto"}):n.createComputePipeline({compute:{module:i,entryPoint:"_start"},label:e.constructor.name,layout:"auto"})},Ee=(n,e="f32")=>{switch(n){case 1:return`${e}`;case 2:return`vec2<${e}>`;case 3:return`vec3<${e}>`;case 4:return`vec4<${e}>`;default:throw new Error(`${n}-component ${e} is not supported.`)}};function ft(n){if(n<=1)return"i32";if(n===2)return"vec2";if(n===3)return"vec3";if(n===4)return"vec4";if(n===5)return"vec5";if(n===6)return"vec6";throw Error(`GPU for rank ${n} is not yet supported`)}function tr(n){if(n===0)return"x";if(n===1)return"y";if(n===2)return"z";if(n===3)return"w";if(n===4)return"u";if(n===5)return"v";throw Error(`Index ${n} is not yet supported`)}function re(...n){let e;switch(n.length){case 0:e=` + fn main() + `;break;case 1:e=` + fn main(${n[0]} : i32) + `;break;default:throw Error("Unreachable")}return e}function sh(n,e){let t;return t=` + ${qP(e)} + fn _start(@builtin(local_invocation_id) LocalId : vec3, + @builtin(global_invocation_id) GlobalId : vec3, + @builtin(local_invocation_index) LocalIndex: u32, + @builtin(workgroup_id) WorkgroupId : vec3, + @builtin(num_workgroups) NumWorkgroups : vec3) { + localId = LocalId; + localIndex = LocalIndex; + globalId = GlobalId; + numWorkgroups = NumWorkgroups; + workgroupId = WorkgroupId; + ${n?"main(getGlobalIndex());":"main();"}; + } + `,t}function qP(n){return` + @compute @workgroup_size(${n.workgroupSize[0]}, ${n.workgroupSize[1]}, ${n.workgroupSize[2]}) +`}function KP(n,e,t){const r=[],s=t.workgroupSize[0]*t.workgroupSize[1]*t.workgroupSize[2];if(t.outputComponent=t.outputComponent?t.outputComponent:1,r.push(` + + var localId: vec3; + var localIndex: u32; + var globalId: vec3; + var numWorkgroups: vec3; + var workgroupId: vec3; + + // Only used when the y/z dimension of workgroup size is 1. + fn getGlobalIndex() -> i32 { + ${eb(t)?" return i32(globalId.x);":` return i32((workgroupId.z * numWorkgroups.x * numWorkgroups.y + + workgroupId.y * numWorkgroups.x + workgroupId.x) * ${s}u + + localIndex); + `} + } + `),t.pixelsOpType!=null){const m=t.pixelsOpType===ua.FROM_PIXELS?`@group(0) @binding(0) var result: array<${rs(e.dtype,t.outputComponent)}>;`:`@group(0) @binding(1) var inBuf : array<${rs(n[0].dtype,t.outputComponent)}>;`,g=e.shape.length===3?"vec2":"i32";r.push(` + struct Uniform { + outShapeStrides : ${g}, + size : i32, + numChannels : i32, + alpha : f32, + }; + + ${m} + @group(0) @binding(2) var uniforms: Uniform; + `);const b=oh(t);return[ah,r.join(` +`),jo(e.shape),t.getUserCode(),sh(b,t)].join(` +`)}let a,o,i="struct Uniforms { NAN : f32, INFINITY : f32, ";t.variableNames.forEach((m,g)=>{const b=ft(n[g].shape.length);i+=`${m.charAt(0).toLowerCase()+m.slice(1)}Shape : ${b}, `,a=n[g].shape.length-1,o=ft(a),i+=`${m.charAt(0).toLowerCase()+m.slice(1)}ShapeStrides: ${o}, `});const l=ft(e.shape.length);i+=`outShape : ${l}, `,a=e.shape.length-1,o=ft(a),i+=` + outShapeStrides: ${o}, `,t.size&&(i+="size : i32, "),t.uniforms&&(i+=t.uniforms),i+="};",i=rF(i),r.push(i),t.atomic?r.push(` + @group(0) @binding(0) var result: array>; + `):r.push(` + @group(0) @binding(0) var result: array<${rs(e.dtype,t.outputComponent)}>; + `),t.variableNames.forEach((m,g)=>{r.push(` + @group(0) @binding(${1+g}) var ${m}: array<${t.variableComponents?rs(n[g].dtype,t.variableComponents[g]):rs(n[g].dtype,t.outputComponent)}>; + `)}),i!==""&&r.push(` + @group(0) @binding(${1+t.variableNames.length}) var uniforms: Uniforms; + `);const c=eF(e.shape,t.dispatchLayout),u=[ah,r.join(` +`)+YP,jo(e.shape),c,tF(e.shape.length)];t.atomic||u.push(nF(e.shape,e.dtype,t.outputComponent)),t.variableNames.forEach((m,g)=>{u.push(`${jo(n[g].shape,m)}`)});const d=n.map((m,g)=>JP(m,e.shape,t.variableComponents?t.variableComponents[g]:t.outputComponent,t.dispatchLayout.x.length===e.shape.length)).join(` +`);u.push(d),u.push(t.getUserCode());const p=oh(t);return u.push(sh(p,t)),u.join(` +`)}function XP(n,e,t){let r=n.shaderKey;if(n.pixelsOpType!=null)return r;const s=[],a=[];e.forEach(u=>{s.push(u.shape),a.push(u.dtype)}),s.push(t.shape),a.push(t.dtype);const o=e.map(u=>Jo(u.shape,t.shape)),i=e.map(u=>Vt(u.shape,t.shape)).join("_"),l=o.map(u=>u.join("_")).join(";"),c=eb(n)?"flatDispatch":"";return r+="_"+(n.workgroupSize?n.workgroupSize.join(","):"")+s.map(u=>u.length).join(",")+a.join(",")+n.variableNames.join(",")+l+i+c,r}const ah=` + struct vec5 {x: i32, y: i32, z: i32, w: i32, u: i32}; + struct vec6 {x: i32, y: i32, z: i32, w: i32, u: i32, v: i32}; + + // Checks whether coordinates lie within the bounds of the shape. + fn coordsInBounds2D(coord : vec2, shape : vec2) -> bool { + return all(coord >= vec2(0)) && all(coord < shape); + } + fn coordsInBounds3D(coord : vec3, shape : vec3) -> bool { + return all(coord >= vec3(0)) && all(coord < shape); + } + fn coordsInBounds4D(coord : vec4, shape : vec4) -> bool { + return all(coord >= vec4(0)) && all(coord < shape); + } + + fn getIndexFromCoords1D(coord : i32, shape : i32) -> i32 { + return coord; + } + fn getIndexFromCoords2D(coords : vec2, shape : vec2) -> i32 { + return dot(coords, vec2(shape.y, 1)); + } + fn getIndexFromCoords3D(coords : vec3, shape : vec3) -> i32 { + return dot(coords, vec3(shape.y * shape.z, shape.z, 1)); + } + fn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 { + return dot(coords, vec4( + shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1)); + } + fn getIndexFromCoords5D(coords : vec5, shape : vec5) -> i32 { + let shapeStrides: vec5 = vec5(shape.y * shape.z * shape.w * shape.u, shape.z * shape.w * shape.u, shape.w * shape.u, shape.u, 1); + return coords.x*shapeStrides.x + coords.y*shapeStrides.y + coords.z*shapeStrides.z + coords.w*shapeStrides.w + coords.u*shapeStrides.u; + } + fn getIndexFromCoords6D(coords : vec6, shape : vec6) -> i32 { + let shapeStrides: vec6 = vec6(shape.y * shape.z * shape.w * shape.u * shape.v, shape.z * shape.w * shape.u * shape.v, shape.w * shape.u * shape.v, shape.u * shape.v, shape.v, 1); + return coords.x*shapeStrides.x + coords.y*shapeStrides.y + coords.z*shapeStrides.z + coords.w*shapeStrides.w + coords.u*shapeStrides.u + coords.v*shapeStrides.v; + } + + // NaN defination in IEEE 754-1985 is : + // - sign = either 0 or 1. + // - biased exponent = all 1 bits. + // - fraction = anything except all 0 bits (since all 0 bits represents infinity). + // https://en.wikipedia.org/wiki/IEEE_754-1985#Representation_of_non-numbers + fn isnan(val: f32) -> bool { + let floatToUint: u32 = bitcast(val); + return (floatToUint & 0x7fffffffu) > 0x7f800000u; + } + fn isnanVec4(val : vec4) -> vec4 { + let floatToUint: vec4 = bitcast>(val); + return (floatToUint & vec4(0x7fffffffu)) > vec4(0x7f800000u); + } +`,YP=` + fn isinf(val: f32) -> bool { + return abs(val) == uniforms.INFINITY; + } +`;function jo(n,e=""){const t=n.length,r=e!==""?`get${e.charAt(0).toUpperCase()+e.slice(1)}CoordsFromIndex`:"getCoordsFromIndex",s=e!==""?`${e.charAt(0).toLowerCase()+e.slice(1)}ShapeStrides`:"outShapeStrides";if(t<=1)return`fn ${r}(index : i32) -> i32 { return index; }`;const a=et(n),o=ft(t),i=[];for(let c=0;c vec2 { + let d0 = index / uniforms.${s}; let d1 = index - d0 * uniforms.${s}; + return vec2(d0, d1); + }`;let l;return l="var index2 = index;"+a.map((c,u)=>{const d=`let ${i[u]} = index2 / uniforms.${s}.${tr(u)}`,p=u===a.length-1?`let ${i[u+1]} = index2 - ${i[u]} * uniforms.${s}.${tr(u)}`:`index2 = index2 - ${i[u]} * uniforms.${s}.${tr(u)}`;return`${d}; ${p};`}).join(""),` + fn ${r}(index : i32) -> ${o} { + ${l} + return ${o}(${i.join(",")}); + } + `}function QP(n,e){const t=n.name,r=n.shape.length,s=ft(r),a="get"+t.charAt(0).toUpperCase()+t.slice(1),o=["d0","d1","d2","d3","d4","d5"].slice(0,r),i=o.map(u=>`${u} : i32`).join(", ");if(r<1)return` + fn ${a}() -> ${Ee(e)} { + return ${Ee(e)}(${t}[0]); + } + `;const l=`uniforms.${t.charAt(0).toLowerCase()+t.slice(1)}Shape`;let c=`${r}D`;return r===0&&(c="1D"),` + fn ${a}(${i}) -> ${Ee(e)} { + return ${Ee(e)}(${t}[getIndexFromCoords${c}(${s}(${o.join(",")}), + ${l})${e===1?"":` / ${e}`}]); + } + `}function ZP(n,e,t,r){const s=n.name,a=s.charAt(0).toUpperCase()+s.slice(1),o="get"+a+"ByOutput",i=n.shape.length,l=e.length,c=ft(l);if(Vt(n.shape,e)&&r)return` + fn ${o}Index(globalIndex : i32) -> ${Ee(t)} { + return ${Ee(t)}(${s}[globalIndex]); + } + + fn ${o}Coords(coords : ${c}) -> ${Ee(t)} { + return ${Ee(t)}(${s}[${l>1?"getOutputIndexFromCoords(coords)":"coords"}${t===1?"":` / ${t}`}]); + } + `;const u=Jo(n.shape,e),d=l-i;let p="";if(i===0)return` + fn ${o}Index(globalIndex : i32) -> ${Ee(t)}{ + return get${a}(); + } + + fn ${o}Coords(coords : ${c}) -> ${Ee(t)}{ + return get${a}(); + } + `;l<2&&u.length>=1?p="coords = 0;":p=u.map(b=>`coords.${tr(b+d)} = 0;`).join(` +`);let f="";if(l<2&&i>0)f="coords";else if(l>1){const b=ft(i),v=n.shape.map((I,S)=>`coords.${tr(S+d)}`).join(", ");f=`${b}(${v})`}else f="coords";const m=`uniforms.${s.charAt(0).toLowerCase()+s.slice(1)}Shape`,g=`${i}D`;return` + fn ${o}Index(globalIndex : i32) -> ${Ee(t)} { + var coords = getCoordsFromIndex(globalIndex); + ${p} + return ${Ee(t)}(${s}[getIndexFromCoords${g}(${f}, ${m})${t===1?"":` / ${t}`}]); + } + + fn ${o}Coords(coordsIn : ${c}) -> ${Ee(t)} { + var coords = coordsIn; + ${p} + return ${Ee(t)}(${s}[getIndexFromCoords${g}(${f}, ${m})${t===1?"":` / ${t}`}]); + } +`}function JP(n,e,t,r){let s=QP(n,t);return n.shape.length<=e.length&&(s+=ZP(n,e,t,r)),s}function eF(n,e){const{x:t,y:r=[],z:s=[]}=e,a=n.length,o=t.length+r.length+s.length;if(o!==a)return"";if(t.length===a)return`fn getOutputCoords() -> ${ft(a)}{ + let globalIndex = getGlobalIndex(); + return getCoordsFromIndex(globalIndex); + } + `;let i="";const l=[t,r,s];for(let p=0;p ${u} { + ${i} +`;return c.length===0?d+=`return ${u}(0); }`:d+=`return ${u}(${c.join(",")}); }`,d}function tF(n){let e="";switch(n){case 0:case 1:e+=` + fn getOutputIndexFromCoords(coords : i32) -> i32 { + return coords; + } + `;break;case 2:e+=` + fn getOutputIndexFromCoords(coords : vec2) -> i32 { + return dot(coords, vec2(uniforms.outShapeStrides, 1)); + } + `;break;case 3:e+=` + fn getOutputIndexFromCoords(coords : vec3) -> i32 { + return dot(coords, vec3(uniforms.outShapeStrides.x, uniforms.outShapeStrides.y, 1)); + } + `;break;case 4:e+=` + fn getOutputIndexFromCoords(coords : vec4) -> i32 { + return dot(coords, vec4( + uniforms.outShapeStrides.x, uniforms.outShapeStrides.y, uniforms.outShapeStrides.z, 1)); + } + `;break;case 5:e+=` + fn getOutputIndexFromCoords(coords : vec5) -> i32 { + return coords.x * uniforms.outShapeStrides.x + + coords.y * uniforms.outShapeStrides.y + + coords.z * uniforms.outShapeStrides.z + + coords.w * uniforms.outShapeStrides.w + + coords.u; + } + `;break;case 6:e+=` + fn getOutputIndexFromCoords(coords : vec6) -> i32 { + return coords.x * uniforms.outShapeStrides.x + + coords.y * uniforms.outShapeStrides.y + + coords.z * uniforms.outShapeStrides.z + + coords.w * uniforms.outShapeStrides.w + + coords.u * uniforms.outShapeStrides.u + + coords.v; + } + `;break;default:$(!1,()=>`Unsupported ${n}D shape`);break}return e}function eb(n){return n.dispatch[1]===1&&n.dispatch[2]===1}function rs(n,e=1){if(n==="float32")return Ee(e,"f32");if(n==="int32"||n==="bool")return Ee(e,"i32");throw new Error(`type ${n} is not supported.`)}function nF(n,e,t){const r=n.length,s=rs(e,t);let a=`fn setOutputAtIndex(flatIndex : i32, value : ${Ee(t)}) { + result[flatIndex] = ${s}(value); + } + + fn setOutputAtIndexI32(flatIndex : i32, value : ${Ee(t,"i32")}) { + result[flatIndex] = ${s}(value); + } + `;if(r>=2){const o=["d0","d1","d2","d3","d4","d5"].slice(0,r),i=ft(r);a+=` + fn setOutputAtCoords(${o.map(l=>`${l} : i32`).join(", ")}, value : ${Ee(t)}) { + let flatIndex = getOutputIndexFromCoords(${i}(${o.join(", ")})); + setOutputAtIndex(flatIndex${t===1?"":` / ${t}`}, value); + } + fn setOutputAtCoordsI32(${o.map(l=>`${l} : i32`).join(", ")}, value : ${Ee(t,"i32")}) { + let flatIndex = getOutputIndexFromCoords(${i}(${o.join(", ")})); + setOutputAtIndexI32(flatIndex${t===1?"":` / ${t}`}, value); + } + `}return a}function rF(n){const e=/(\w+)\s*:\s*vec(5|6)/g;n=n.replace(e,r=>"@align(16) "+r);const t=/vec(5|6)\s*,\s*(\w+)/g;return n=n.replace(t,(r,s,a)=>`vec${s}, @align(16) ${a}`),n}function oh(n){return!(n.dispatchLayout.hasOwnProperty("y")&&n.dispatchLayout.y.length!==0||n.dispatchLayout.hasOwnProperty("z")&&n.dispatchLayout.z.length!==0)}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const cs=n=>{let e=1;for(let t=0;te[i]))/(t[0]*r[0])),n.y?Math.ceil(cs(n.y.map(i=>e[i]))/(t[1]*r[1])):1,n.z?Math.ceil(cs(n.z.map(i=>e[i]))/(t[2]*r[2])):1];return[s,a,o]}function sF(n,e,t,r=!1){const s=[8,8,1],a=[4,4,1];return r||(n<=8&&(a[1]=1),e<=16&&t<=16&&(s[0]=4)),{workgroupSize:s,elementsPerThread:a}}function tb(n,e,t=!1){if(t)return[8,8,1];const r=cs(n.x.map(a=>e[a])),s=cs(n.y.map(a=>e[a]));return r<=4?[4,16,1]:s<=4?[16,4,1]:[16,16,1]}function nb(n,e,t=!1){if(t)return[4,4,1];const r=cs(n.x.map(a=>e[a])),s=cs(n.y.map(a=>e[a]));return r<=4?[1,2,1]:s<=4?[2,1,1]:[2,2,1]}function ie(n){return{x:n.map((e,t)=>t)}}function ih(n){if(n==="float32"||n==="int32"||n==="bool"||n==="string")return 4;if(n==="complex64")return 8;throw new Error(`Unknown dtype ${n}`)}function rb(){return!!(typeof globalThis<"u"&&globalThis.navigator&&globalThis.navigator.gpu)}function sb(n,e){Array.isArray(n)||(n=[n]),n.forEach(t=>{t!=null&&$(t.dtype!=="complex64",()=>`${e} does not support complex64 tensors in the WebGPU backend.`)})}var Ln;(function(n){n[n.MatMulReduceProgram=0]="MatMulReduceProgram",n[n.MatMulSplitKProgram=1]="MatMulSplitKProgram",n[n.MatMulSmallOutputSizeProgram=2]="MatMulSmallOutputSizeProgram",n[n.MatMulPackedProgram=3]="MatMulPackedProgram",n[n.MatMulMax=4]="MatMulMax"})(Ln||(Ln={}));/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const aF=fe().getNumber("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD"),oF=(n,e)=>{const t=n.limits.maxComputeWorkgroupsPerDimension,r=e.dispatchLayout,s=e.dispatch;if(s.every(o=>o<=t))return s;$(s[0]>t&&r.y===void 0&&r.z===void 0,()=>"Dispatch size exceeds WebGPU limits in Y or Z dimension.");let a=Math.ceil(Math.sqrt(s[0]));return a>t?(a=Math.ceil(Math.cbrt(s[0])),$(a<=t,()=>"Total dispatch size exceeds WebGPU maximum."),[a,a,a]):[a,a,1]};class ga extends Gl{nextDataId(){return ga.nextDataId++}constructor(e,t){if(super(),this.commandQueueOwnedIds=new WeakSet,this.dispatchCountInPass=0,this.disposed=!1,this.downloadWaitMs=0,this.tensorDataPendingDisposal=[],this.queryResolveBuffer=null,this.querySet=null,this.querySetCount=2,this.stagingPendingDisposal=[],this.uniformPendingDisposal=[],this.uploadWaitMs=0,this.hasReadSyncWarned=!1,this.hasTimestampQueryWarned=!1,!rb())throw new Error("WebGPU is not supported on this device");this.pipelineCache={},this.device=e,this.queue=e.queue,this.commandEncoder=null,this.computePassEncoder=null,this.adapterInfo=new VP(t),this.supportTimestampQuery=this.device.features.has("timestamp-query"),this.thresholdToIncreaseWorkgroups=this.adapterInfo.intelGPUGeneration>=12?16:8,this.bufferManager=new UP(this.device),this.textureManager=new HP(this.device),this.tensorMap=new Kh(this,us()),fe().getBool("WEBGPU_USE_PROFILE_TOOL")&&(this.dummyCanvas=document.createElement("canvas"),this.dummyCanvas.width=1,this.dummyCanvas.height=1,this.dummyContext=this.dummyCanvas.getContext("webgpu"),this.dummyContext.configure({device:e,format:"bgra8unorm"}),document.body.appendChild(this.dummyCanvas))}floatPrecision(){return 32}disposeData(e,t=!1){if(!this.tensorMap.has(e))return!0;const r=this.tensorMap.get(e);return t?r.refCount=0:r.refCount--,r.refCount>0?!1:(r.complexTensorInfos!=null&&(this.disposeData(r.complexTensorInfos.real.dataId),this.disposeData(r.complexTensorInfos.imag.dataId)),this.commandQueueOwnedIds.has(e)?(this.tensorDataPendingDisposal.push(e),!0):(this.releaseResource(e),this.tensorMap.delete(e),!0))}memory(){return{numBytesInGPU:this.bufferManager.numBytesUsed,numBytesAllocatedInGPU:this.bufferManager.numBytesAllocated,unreliable:!1}}releaseResource(e){const t=this.tensorMap.get(e);if(!(!t||!t.resource)){if(t.external){t.resource=null;return}t.resource instanceof GPUBuffer?this.bufferManager.releaseBuffer(t.resource):t.resource instanceof GPUTexture&&this.textureManager.releaseTexture(t.resource),t.resource=null}}refCount(e){return this.tensorMap.has(e)?this.tensorMap.get(e).refCount:0}incRef(e){const t=this.tensorMap.get(e);t.refCount++}decRef(e){if(this.tensorMap.has(e)){const t=this.tensorMap.get(e);t.refCount--}}write(e,t,r){if(r==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");const s={id:this.nextDataId()};return this.tensorMap.set(s,{dtype:r,shape:t,values:e,refCount:1}),s}move(e,t,r,s,a){if(s==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.tensorMap.set(e,{dtype:s,shape:r,values:t,refCount:a})}submitQueue(){this.queue.submit([this.commandEncoder.finish()]),this.commandEncoder=null,this.dispatchCountInPass=0,this.commandQueueOwnedIds=new WeakSet,this.tensorDataPendingDisposal.forEach(e=>{this.releaseResource(e),this.tensorMap.delete(e)}),this.uniformPendingDisposal.forEach(e=>this.bufferManager.releaseBuffer(e)),this.stagingPendingDisposal.forEach(e=>this.bufferManager.releaseBuffer(e,!1)),this.tensorDataPendingDisposal=[],this.uniformPendingDisposal=[],this.stagingPendingDisposal=[]}ensureCommandEncoderReady(){this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder())}endComputePassEncoder(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}async checkCompileCompletionAsync(){let e;try{e=await Promise.all(Object.values(this.pipelineCache))}catch(t){throw new Error(t.message)}Object.keys(this.pipelineCache).map((t,r)=>{this.pipelineCache[t]=e[r]})}async getBufferData(e){if(fe().getBool("WEBGPU_ENGINE_COMPILE_ONLY"))return console.warn("The data may be invalid since WEBGPU_ENGINE_COMPILE_ONLY is true, this can only be called when WEBGPU_ENGINE_COMPILE_ONLY is false"),null;const t=e.size,r=this.bufferManager.acquireBuffer(t,GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ);this.ensureCommandEncoderReady(),this.endComputePassEncoder(),this.commandEncoder.copyBufferToBuffer(e,0,r,0,t),this.submitQueue(),await r.mapAsync(GPUMapMode.READ);const s=r.getMappedRange().slice(0);return r.unmap(),r!=null&&this.bufferManager.releaseBuffer(r),fe().getBool("WEBGPU_USE_PROFILE_TOOL")&&($(this.dummyContext!==void 0,()=>"Fail to get context for profiling tool"),this.dummyContext.getCurrentTexture()),s}convertAndCacheOnCPU(e,t){const r=this.tensorMap.get(e);return r.values=t,r.values}readSync(e){const t=this.tensorMap.get(e),{values:r,complexTensorInfos:s}=t;if(r!=null||t.dtype==="string")return r;if(t.dtype==="complex64"){const g=this.readSync(s.real.dataId),b=this.readSync(s.imag.dataId),v=Au(Op(g,b).buffer,"float32");return this.convertAndCacheOnCPU(e,v),v}this.hasReadSyncWarned||(this.hasReadSyncWarned=!0,console.warn("The performance of synchronously reading data from GPU to CPU is poor on the webgpu backend, please use asynchronous APIs instead."));const a=["opaque","premultiplied"],o=t.resource,i=o.size;$(i%4===0,()=>"Because there is 4 bytes for one pixel, buffer size must be multiple of 4.");const l=i/4,c=new ArrayBuffer(i),u=256,d=256,p=a.map(g=>new OffscreenCanvas(u,d)),f=new OffscreenCanvas(u,d);this.endComputePassEncoder(),p.map((g,b)=>{const v=g.getContext("webgpu");return v.configure({device:this.device,format:"bgra8unorm",usage:GPUTextureUsage.COPY_DST,alphaMode:a[b]}),v.getCurrentTexture()}).map((g,b)=>{const v=u*4,I=(B,A,D)=>{this.ensureCommandEncoderReady(),this.commandEncoder.copyBufferToTexture({buffer:o,bytesPerRow:v,offset:D},{texture:g},{width:B,height:A}),this.submitQueue();const _=f.getContext("2d",{willReadFrequently:!0});_.clearRect(0,0,B,A),_.drawImage(p[b],0,0);const V=_.getImageData(0,0,B,A).data,H=a[b],Y=new Uint8ClampedArray(c,D,B*A*4);for(let X=0;X0&&(I(C,T,O),O+=T*(u*4)),C=L%u,C>0&&I(C,1,O)});const m=Au(c,t.dtype);return this.convertAndCacheOnCPU(e,m),m}async read(e){if(!this.tensorMap.has(e))throw new Error(`Tensor ${e} was not registered!`);const t=this.tensorMap.get(e),{values:r}=t;if(r!=null)return r;let s;if(t.dtype==="complex64"){const a=await Promise.all([this.read(t.complexTensorInfos.real.dataId),this.read(t.complexTensorInfos.imag.dataId)]),o=a[0],i=a[1];s=Op(o,i)}else{const a=await this.getBufferData(t.resource);s=Au(a,t.dtype)}return this.convertAndCacheOnCPU(e,s),s}copyBuffer(e){const t=e.size,r=e.usage,s=this.bufferManager.acquireBuffer(t,r);return this.ensureCommandEncoderReady(),this.endComputePassEncoder(),this.commandEncoder.copyBufferToBuffer(e,0,s,0,t),this.submitQueue(),s}createTensorFromGPUData(e,t,r){let s=e.buffer;if(r==="complex64")throw new Error("Cannot write to a complex64 dtype. ");const a={id:this.nextDataId()};this.tensorMap.set(a,{dtype:r,shape:t,values:null,refCount:1,external:e.zeroCopy});const o=this.tensorMap.get(a),i=ih(o.dtype)*q(o.shape);if(e.buffer.sizena(s));return ut(e.shape,e.dtype,r)}catch{throw new Error("Failed to decode encoded string bytes into utf-8")}return ut(e.shape,e.dtype,t)}async time(e){!this.supportTimestampQuery&&!this.hasTimestampQueryWarned&&(console.warn("This device doesn't support timestamp-query extension. Start Chrome browser with flag --enable-dawn-features=allow_unsafe_apis to try it again. Otherwise, zero will be shown for the kernel time when profiling mode is enabled."),this.hasTimestampQueryWarned=!0);const t=this.activeTimers,r=[];let s=!1;this.programTimersStack==null?(this.programTimersStack=r,s=!0):this.activeTimers.push(r),this.activeTimers=r,e();const a=fs(this.activeTimers.map(c=>c.query)).filter(c=>c!=null),o=fs(this.activeTimers.map(c=>c.name)).filter(c=>c!=null);this.activeTimers=t,s&&(this.programTimersStack=null);const i={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null},l=await Promise.all(a);return i.kernelMs=bw(l),i.getExtraProfileInfo=()=>l.map((c,u)=>({name:o[u],ms:c})).map(c=>`${c.name}: ${c.ms}`).join(", "),this.uploadWaitMs=0,this.downloadWaitMs=0,i}makeTensorInfo(e,t,r){return t==="string"&&r!=null&&r.length>0&&ci(r[0])&&(r=r.map(a=>is(a))),{dataId:this.write(r,e,t),shape:e,dtype:t}}tensorToBinding(e){if(!e)return null;const r=this.tensorMap.get(e.dataId).resource;return r instanceof GPUBuffer?{buffer:r}:r instanceof GPUTexture?r.createView():r}uploadToGPU(e){const t=this.tensorMap.get(e);if(t.resource!=null)return;const r=ih(t.dtype)*q(t.shape);let s;const a=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST;if(t.values){if(s=this.bufferManager.acquireBuffer(r,a,!0),s.mapState==="unmapped"){const o=this.bufferManager.acquireBuffer(r,GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC,!0,!1),i=o.getMappedRange();t.dtype==="int32"||t.dtype==="bool"?new Int32Array(i).set(t.values):new Float32Array(i).set(t.values),o.unmap(),this.ensureCommandEncoderReady(),this.endComputePassEncoder(),this.commandEncoder.copyBufferToBuffer(o,0,s,0,r),this.stagingPendingDisposal.push(o)}else{const o=s.getMappedRange();t.dtype==="int32"||t.dtype==="bool"?new Int32Array(o).set(t.values):new Float32Array(o).set(t.values),s.unmap()}t.values=null}else s=this.bufferManager.acquireBuffer(r,a);t.resource=s}makeUniforms(e){let t=0,r=0;const s=[];let a=1;e.forEach(l=>{l.data.length===0&&(l.data=[1]);let c;switch(l.data.length){case 1:c=4;break;case 2:c=8;break;case 3:c=16;break;case 4:c=16;break;case 5:c=16;break;case 6:c=16;break;default:$(!1,()=>`Unsupported ${l.data.length}D shape`)}(r===5||r===6)&&(c=16),c>a&&(a=c),t=Math.ceil(t/c)*c,r=l.data.length,s.push(t),t+=l.data.length*4}),t=Math.ceil(t/a)*a;const o=new ArrayBuffer(t);e.forEach((l,c)=>{const u=s[c];l.type==="int32"?new Int32Array(o,u,l.data.length).set(l.data):l.type==="uint32"?new Uint32Array(o,u,l.data.length).set(l.data):new Float32Array(o,u,l.data.length).set(l.data)});const i=this.bufferManager.acquireBuffer(t,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);return this.queue.writeBuffer(i,0,o,0,t),this.uniformPendingDisposal.push(i),{offset:0,size:t,buffer:i}}runWebGPUProgram(e,t,r,s,a){if(a||(a=this.makeTensorInfo(e.outputShape,r)),q(a.shape)===0)return this.tensorMap.get(a.dataId).values=kr(a.dtype,0),a;this.uploadToGPU(a.dataId),e.dispatch=oF(this.device,e);const o=t.map((l,c)=>{if(l.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");return this.uploadToGPU(l.dataId),{dtype:this.tensorMap.get(l.dataId).dtype,shape:l.shape,name:e.variableNames[c]}});e.shaderKey=XP(e,o,a);const i=fe().getBool("WEBGPU_ENGINE_COMPILE_ONLY");return e.shaderKey in this.pipelineCache||(this.pipelineCache[e.shaderKey]=jP(this.device,e,o,a,i)),e.pipeline=this.pipelineCache[e.shaderKey],i||this.recordAndSubmit(e,a,t,s),a}recordAndSubmit(e,t,r,s){if(e.pipeline instanceof Promise)throw new Error("Please call checkCompileCompletionAsync to ensure parallel compilation is done!");let a=[],o=[];const i="int32";if(e.pixelsOpType==null){a.push({type:"float32",data:[NaN]},{type:"float32",data:[1/0]}),o=r.concat(t).map(f=>f.shape);const p="int32";o.map(f=>{a.push({type:p,data:f});const m=et(f);a.push({type:p,data:m})})}else{const p=et(t.shape);a.push({type:i,data:p})}if(e.size){const p=q(e.outputShape);a.push({type:i,data:[e.outputComponent?p/e.outputComponent:p]})}s&&(a=[...a,...s]);const l=[this.tensorToBinding(t),...r.map(p=>this.tensorToBinding(p)),this.makeUniforms(a)];r.forEach(p=>{this.commandQueueOwnedIds.add(p.dataId)}),this.commandQueueOwnedIds.add(t.dataId);const c=this.device.createBindGroup({layout:e.pipeline.getBindGroupLayout(0),entries:l.map((p,f)=>({binding:f,resource:p}))}),u=this.activeTimers!=null;this.ensureCommandEncoderReady();const d={};u&&this.supportTimestampQuery?(this.endComputePassEncoder(),this.querySet==null&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.querySetCount})),d.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:0,endOfPassWriteIndex:1},this.computePassEncoder=this.commandEncoder.beginComputePass(d)):this.computePassEncoder||(this.computePassEncoder=this.commandEncoder.beginComputePass(d)),this.computePassEncoder.setPipeline(e.pipeline),this.computePassEncoder.setBindGroup(0,c),this.computePassEncoder.dispatchWorkgroups(e.dispatch[0],e.dispatch[1],e.dispatch[2]),this.dispatchCountInPass++,(u||fe().get("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE")<=this.dispatchCountInPass||e.pixelsOpType===ua.DRAW)&&(this.endComputePassEncoder(),u?this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime()}):this.submitQueue())}async getQueryTime(){if(!this.supportTimestampQuery)return 0;this.queryResolveBuffer==null&&(this.queryResolveBuffer=this.bufferManager.acquireBuffer(this.querySetCount*8,GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST|GPUBufferUsage.QUERY_RESOLVE)),this.commandEncoder.resolveQuerySet(this.querySet,0,this.querySetCount,this.queryResolveBuffer,0);const e=this.bufferManager.acquireBuffer(this.querySetCount*8,GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST);this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.querySetCount*8),this.submitQueue(),await e.mapAsync(GPUMapMode.READ);const t=new BigUint64Array(e.getMappedRange()),r=Number(t[1]-t[0])/1e6;return e.unmap(),this.bufferManager.releaseBuffer(e),r}shouldExecuteOnCPU(e,t=aF){return fe().getBool("WEBGPU_CPU_FORWARD")&&e.every(r=>this.tensorMap.get(r.dataId).resource==null&&q(r.shape){const n={powerPreference:fe().get("WEBGPU_USE_LOW_POWER_GPU")?"low-power":"high-performance"},e=await navigator.gpu.requestAdapter(n),t={},r=[];e.features.has("timestamp-query")&&r.push("timestamp-query"),e.features.has("bgra8unorm-storage")&&r.push(["bgra8unorm-storage"]),t.requiredFeatures=r;const s=e.limits;t.requiredLimits={maxComputeWorkgroupStorageSize:s.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:s.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:s.maxStorageBufferBindingSize,maxBufferSize:s.maxBufferSize,maxComputeWorkgroupSizeX:s.maxComputeWorkgroupSizeX,maxComputeInvocationsPerWorkgroup:s.maxComputeInvocationsPerWorkgroup};const a=await e.requestDevice(t),o="info"in e?e.info:"requestAdapterInfo"in e?await e.requestAdapterInfo():void 0;return new ga(a,o)},3);/** + * @license + * Copyright 2021 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 ve;(function(n){n[n.ADD=0]="ADD",n[n.ATAN2=1]="ATAN2",n[n.COMPLEX_MULTIPLY_IMAG=2]="COMPLEX_MULTIPLY_IMAG",n[n.COMPLEX_MULTIPLY_REAL=3]="COMPLEX_MULTIPLY_REAL",n[n.DIV=4]="DIV",n[n.ELU_DER=5]="ELU_DER",n[n.EQUAL=6]="EQUAL",n[n.FLOOR_DIV=7]="FLOOR_DIV",n[n.GREATER=8]="GREATER",n[n.GREATER_EQUAL=9]="GREATER_EQUAL",n[n.LESS=10]="LESS",n[n.LESS_EQUAL=11]="LESS_EQUAL",n[n.LOGICAL_AND=12]="LOGICAL_AND",n[n.LOGICAL_OR=13]="LOGICAL_OR",n[n.MAX=14]="MAX",n[n.MIN=15]="MIN",n[n.MOD=16]="MOD",n[n.MUL=17]="MUL",n[n.NOT_EQUAL=18]="NOT_EQUAL",n[n.POW=19]="POW",n[n.PRELU=20]="PRELU",n[n.SQUARED_DIFFERENCE=21]="SQUARED_DIFFERENCE",n[n.SUB=22]="SUB"})(ve||(ve={}));const iF="let resultTemp = a + b;",uF="let resultTemp = atan2(a, b);",lF="let resultTemp = areal * breal - aimag * bimag;",cF="let resultTemp = areal * bimag + aimag * breal;",dF="let resultTemp = a / b;",pF="let resultTemp = select(a * (b + 1.0), a, b >= b - b);",hF=` + let zero = sign(a) * 0 + 0; + let one = sign(b) * 0 + 1; + let resultTemp = select(zero, one, a == b); +`,fF=` + let remainder = + select(a % b, round(a % b), (round(a) == a) & (round(b) == b)); + let quotient = (a - remainder) / b; + let resultTemp = + round(select(quotient, quotient - 1, sign(remainder) == -sign(b))); +`,mF=` + let zero = sign(a) * 0 + 0; + let one = sign(b) * 0 + 1; + let resultTemp = select(zero, one, a > b); +`,gF=` + let zero = sign(a) * 0 + 0; + let one = sign(b) * 0 + 1; + let resultTemp = select(zero, one, a >= b); +`,yF=` + let zero = sign(a) * 0 + 0; + let one = sign(b) * 0 + 1; + let resultTemp = select(zero, one, a < b); +`,bF=` + let zero = sign(a) * 0 + 0; + let one = sign(b) * 0 + 1; + let resultTemp = select(zero, one, a <= b); +`,wF="return f32(a >= 1.0 && b >= 1.0);",xF=`return (vec4(a >= vec4(1.0)) * + vec4(b >= vec4(1.0)));`,vF="return f32(a >= 1.0 || b >= 1.0);",SF=`return min(vec4(a >= vec4(1.0)) + + vec4(b >= vec4(1.0)), vec4(1.0));`,IF="let resultTemp = max(a, b);",kF="let resultTemp = min(a, b);",_F=` + let isNaN = b == 0.; + var resultTemp = a % b; + resultTemp = select((resultTemp + b) % b, resultTemp, + (a < 0. && b < 0.) || (a >= 0. && b > 0.)); +`,CF=` + let isNaN = !vec4(b); + var resultTemp = vec4(a % b); + if (!((a[0] < 0. && b[0] < 0.) || (a[0] >= 0. && b[0] > 0.))) { + resultTemp[0] = (resultTemp[0] + b[0]) % b[0]; + } + if (!((a[1] < 0. && b[1] < 0.) || (a[1] >= 0. && b[1] > 0.))) { + resultTemp[1] = (resultTemp[1] + b[1]) % b[1]; + } + if (!((a[2] < 0. && b[2] < 0.) || (a[2] >= 0. && b[2] > 0.))) { + resultTemp[2] = (resultTemp[2] + b[2]) % b[2]; + } + if (!((a[3] < 0. && b[3] < 0.) || (a[3] >= 0. && b[3] > 0.))) { + resultTemp[3] = (resultTemp[3] + b[3]) % b[3]; + } +`,NF="let resultTemp = a * b;",$F=` + var resultTemp = f32(a != b); + let valueForNaN = 1.0; +`,TF=` + var resultTemp = vec4(a != b); + let valueForNaN = 1.0; +`,EF=` + let isNaN = a < 0.0 && floor(b) < b; + if (b == 0.0) { + return 1.0; + } + var resultTemp = select(sign(a) * pow(abs(a), b), pow(abs(a), b), + round(abs(b) % 2.0) != 1.0); +`,AF=` + let isModRound1Bool = vec4(round(abs(b) % vec4(2.0))) == vec4(1); + let isModRound1 = vec4(isModRound1Bool); + let multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1); + var resultTemp = multiplier * pow(abs(a), b); + + // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS + let isExpZero = b == vec4(0.0); + if (isExpZero.r) { + resultTemp.r = 1.0; + } + if (isExpZero.g) { + resultTemp.g = 1.0; + } + if (isExpZero.b) { + resultTemp.b = 1.0; + } + if (isExpZero.a) { + resultTemp.a = 1.0; + } + let isNaN = (a < vec4(0.0)) & (floor(b) < b); +`,RF="if (a < 0.0) { return b * a; } return a;",DF=` + let aLessThanZero = vec4(a < vec4(0.0)); + return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a); +`,PF="let resultTemp = (a - b) * (a - b);",FF="let resultTemp = a - b;";function Yd(n,e){let t;do{switch(n){case ve.ATAN2:t=uF;break;case ve.MAX:t=IF;break;case ve.MIN:t=kF;break;case ve.MOD:t=e?CF:_F;break;case ve.NOT_EQUAL:t=e?TF:$F;break;case ve.POW:t=e?AF:EF;break;default:continue}let r,s,a;return e?(r="isnanVec4",s="vec4",a="vec4"):(r="isnan",s="f32",a="bool"),` + let aIsNaN = ${r}(a); + let aPostLegalization = select(a, ${s}(42), aIsNaN); + let bIsNaN = ${r}(b); + let bPostLegalization = select(b, ${s}(42), bIsNaN); + let isNaN = false; + let valueForNaN = uniforms.NAN; + { + let a = aPostLegalization; + let b = bPostLegalization; + ${t} + return select( + resultTemp, ${s}(valueForNaN), + ${a}(isNaN) | aIsNaN | bIsNaN); + } + `}while(!1);switch(n){case ve.ADD:t=iF;break;case ve.COMPLEX_MULTIPLY_IMAG:t=cF;break;case ve.COMPLEX_MULTIPLY_REAL:t=lF;break;case ve.DIV:t=dF;break;case ve.ELU_DER:t=pF;break;case ve.EQUAL:t=hF;break;case ve.FLOOR_DIV:t=fF;break;case ve.GREATER:t=mF;break;case ve.GREATER_EQUAL:t=gF;break;case ve.LESS:t=yF;break;case ve.LESS_EQUAL:t=bF;break;case ve.LOGICAL_AND:return e?xF:wF;case ve.LOGICAL_OR:return e?SF:vF;case ve.MUL:t=NF;break;case ve.PRELU:return e?DF:RF;case ve.SQUARED_DIFFERENCE:t=PF;break;case ve.SUB:t=FF;break}return` + ${t} + return resultTemp; + `}/** + * @license + * Copyright 2021 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 ne;(function(n){n[n.ABS=0]="ABS",n[n.ACOS=1]="ACOS",n[n.ACOSH=2]="ACOSH",n[n.ASIN=3]="ASIN",n[n.ASINH=4]="ASINH",n[n.ATAN=5]="ATAN",n[n.ATANH=6]="ATANH",n[n.CEIL=7]="CEIL",n[n.COS=8]="COS",n[n.COSH=9]="COSH",n[n.ELU=10]="ELU",n[n.ERF=11]="ERF",n[n.EXP=12]="EXP",n[n.EXPM1=13]="EXPM1",n[n.FLOOR=14]="FLOOR",n[n.IS_FINITE=15]="IS_FINITE",n[n.IS_INF=16]="IS_INF",n[n.IS_NAN=17]="IS_NAN",n[n.LINEAR=18]="LINEAR",n[n.LOG=19]="LOG",n[n.LOG1P=20]="LOG1P",n[n.LOGICAL_NOT=21]="LOGICAL_NOT",n[n.NEG=22]="NEG",n[n.RELU=23]="RELU",n[n.RELU6=24]="RELU6",n[n.LEAKYRELU=25]="LEAKYRELU",n[n.RECIPROCAL=26]="RECIPROCAL",n[n.ROUND=27]="ROUND",n[n.RSQRT=28]="RSQRT",n[n.SELU=29]="SELU",n[n.SIGMOID=30]="SIGMOID",n[n.SIGN=31]="SIGN",n[n.SIN=32]="SIN",n[n.SINH=33]="SINH",n[n.SOFTPLUS=34]="SOFTPLUS",n[n.SQRT=35]="SQRT",n[n.SQUARE=36]="SQUARE",n[n.STEP=37]="STEP",n[n.TAN=38]="TAN",n[n.TANH=39]="TANH",n[n.TO_INT=40]="TO_INT"})(ne||(ne={}));const OF="return abs(a);",MF=` + if (abs(a) > 1.) { + return uniforms.NAN; + } + return acos(a); +`,LF=` + if (a < 1.) { + return uniforms.NAN; + } + return acosh(a); +`,zF=` + if (abs(a) > 1.) { + return uniforms.NAN; + } + return asin(a); +`,BF="return asinh(a);",WF=` + if (isnan(a)) { + return uniforms.NAN; + } + return atan(a); +`,VF=` + if (abs(a) > 1.) { + return uniforms.NAN; + } + if (a == 1.) { + return uniforms.INFINITY; + } + if (a == -1.) { + return -uniforms.INFINITY; + } + return atanh(a); +`,UF="return ceil(a);",HF="return cos(a);",GF=` + let e2x = exp(-a); + return (e2x + 1.0 / e2x) / 2.0; +`,jF="return exp(a) - 1.0;",qF="if (a >= 0.0) { return a; } return (exp(a) - 1.0);",KF=` + var resFloat = exp(a) - vec4(1.0); + if (a.r >= 0.0) { + resFloat.r = a.r; + } + if (a.g >= 0.0) { + resFloat.g = a.g; + } + if (a.b >= 0.0) { + resFloat.b = a.b; + } + if (a.a >= 0.0) { + resFloat.a = a.a; + } + return resFloat; +`,XF=` + // Error function is calculated approximately with elementary function. + // See "Handbook of Mathematical Functions with Formulas, + // Graphs, and Mathematical Tables", Abramowitz and Stegun. + let p = ${PC}; + let a1 = ${FC}; + let a2 = ${OC}; + let a3 = ${MC}; + let a4 = ${LC}; + let a5 = ${zC}; + + let sign = sign(a); + let absA = abs(a); + let t = 1.0 / (1.0 + p * absA); + return sign * (1.0 - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * exp(-absA * absA)); +`,YF="return exp(a);",QF="return floor(a);",ZF="return f32(!isnan(a) && !isinf(a));",JF="return f32(isinf(a));",eO="return f32(isnan(a));",tO="return a;",nO=`if (a < 0.0) { return uniforms.NAN; } + return log(a);`,rO=` + if (isnan(a)) { return a; } + return log(1.0 + a); +`,sO="return f32(!(a >= 1.0));",aO="return -a;",oO="if (a < 0.0) { return uniforms.alpha * a; } return a;",iO=` + let aLessThanZero = vec4(a < vec4(0.0)); + return (aLessThanZero * (uniforms.alpha * a)) + ((vec4(1.0) - aLessThanZero) * a); +`,uO="return 1.0 / a;",lO="return select(a, 0.0, a < 0.0);",cO="return clamp(a, 0.0, 6.0);",dO="return clamp(a, vec4(0.0, 0.0, 0.0, 0.0), vec4(6.0, 6.0, 6.0, 6.0));",pO=` + return select(a, vec4(0.0), a < vec4(0.0)); +`,hO="return round(a);",fO="return inverseSqrt(a);",mO=` + if (a >= 0.0) { + return ${DC} * a; + } else { + return ${RC} * (exp(a) - 1.0); + } +`,gO="return 1.0 / (1.0 + exp(-1.0 * a));",yO="return sign(a);",bO="return sin(a);",wO=` + let e2x = exp(a); + return (e2x - 1.0 / e2x) / 2.0; +`,xO=` + let epsilon = 1.1920928955078125e-7; + let threshold = log(epsilon) + 2.0; + + let too_large = a > -threshold; + let too_small = a < threshold; + let exp_a = exp(a); + + if (too_large) { + return a; + } else if (too_small) { + return exp_a; + } else { + return log(exp_a + 1.0); + } +`,vO="return sqrt(a);",SO="return a * a;",IO=` + if (isnan(a)) { + return a; + } + + return select(uniforms.stepAlpha, 1.0, a > 0.0); +`,kO="return tan(a);",_O=` + let e2x = exp(-2.0 * abs(a)); + return sign(a) * (1.0 - e2x) / (1.0 + e2x); +`,CO="return f32(i32((a)));";function Jr(n,e){switch(n){case ne.ABS:return OF;case ne.ACOS:return MF;case ne.ACOSH:return LF;case ne.ASIN:return zF;case ne.ASINH:return BF;case ne.ATAN:return WF;case ne.ATANH:return VF;case ne.COS:return HF;case ne.COSH:return GF;case ne.CEIL:return UF;case ne.ELU:return e?KF:qF;case ne.ERF:return XF;case ne.EXP:return YF;case ne.EXPM1:return jF;case ne.FLOOR:return QF;case ne.IS_FINITE:return ZF;case ne.IS_INF:return JF;case ne.IS_NAN:return eO;case ne.LINEAR:return tO;case ne.LOG:return nO;case ne.LOG1P:return rO;case ne.LOGICAL_NOT:return sO;case ne.NEG:return aO;case ne.LEAKYRELU:return e?iO:oO;case ne.RECIPROCAL:return uO;case ne.RELU:return e?pO:lO;case ne.RELU6:return e?dO:cO;case ne.ROUND:return hO;case ne.RSQRT:return fO;case ne.SELU:return mO;case ne.SIGMOID:return gO;case ne.SIGN:return yO;case ne.SIN:return bO;case ne.SINH:return wO;case ne.SOFTPLUS:return xO;case ne.SQRT:return vO;case ne.SQUARE:return SO;case ne.STEP:return IO;case ne.TAN:return kO;case ne.TANH:return _O;case ne.TO_INT:return CO;default:throw new Error(`BinaryType ${n} is not implemented!`)}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function ir(n,e=!1,t=!1,r=3){if(n===null)return"";let s="";if(n==="linear")s=Jr(ne.LINEAR);else if(n==="relu")s=Jr(ne.RELU,t);else if(n==="elu")s=Jr(ne.ELU,t);else if(n==="relu6")s=Jr(ne.RELU6,t);else if(n==="prelu")s=Yd(ve.PRELU,t);else if(n==="sigmoid")s=Jr(ne.SIGMOID,t);else if(n==="leakyrelu")s=Jr(ne.LEAKYRELU,t);else throw new Error(`Activation ${n} has not been implemented for the WebGPU backend.`);const o=Ee(t?4:1);let i="";return e?i=` + fn activation(a : ${o}, coords : vec${r}) -> ${o} { + let b = getPreluActivationWeightsByOutputCoords(coords); + ${s} + }`:i=` + fn activation(a : ${o}, coords : vec${r}) -> ${o} { + ${s} + }`,i}function _s(n,e){return` + ${n?"value = value + getBiasByOutputCoords(coords);":""} + ${e?"value = activation(value, coords);":""} + `}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ab(n,e,t=!1,r=!1,s=!1,a=1){$(n&&a===1||!n,()=>`transposeA ${n} is not compatible with component size ${a}`);const o=` + ${n?"value = getA(batch, col, row);":"value = getA(batch, row, col);"} + + `,i=e?"value = getB(batch, col, row);":"value = getB(batch, row, col);";return` + fn mm_readA(batch: i32, row: i32, col: i32) -> ${Ee(a)} { + var value = ${Ee(a)}(0.0); + ${t&&s?o:` + ${n?"if(row < uniforms.dimAOuter && col < uniforms.dimInner)":"if(row < uniforms.aShape[1] && col < uniforms.aShape[2])"} + { + ${o} + } + `} + return value; + } + + fn mm_readB(batch: i32, row: i32, col: i32) -> ${Ee(a)} { + var value = ${Ee(a)}(0.0); + ${i} + return value; + } + `}function Qd(n,e,t,r,s=!1,a=!1,o=!1,i=1){return` + ${ab(t,r,s,a,o,i)} + fn mm_write(batch: i32, row: i32, col: i32, valueIn: ${Ee(i)}) { + ${s&&a?"":"if (row < uniforms.dimAOuter && col < uniforms.dimBOuter)"} + { + var value = valueIn; + let coords = vec3(batch, row, col); + ${_s(n,e)} + setOutputAtCoords(coords[0], coords[1], coords[2], value); + } + } + `}const NO=(n,e)=>n?` + mm_Asub[inputRow][inputCol] = mm_readA(batchA, + kStart + inputRow, + globalRowStart + inputCol * ${e}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batchA, + globalRow + innerRow, + kStart + inputCol * ${e}); + `,$O=(n,e,t,r)=>{if(n)return` + for (var k = 0; k < ${r}; k++) { + let BCached0 = mm_Bsub[k][tileCol]; + let ACached0 = mm_Asub[k][localRow]; + for (var i = 0; i < ${t}; i++) { + acc[i] = fma(BCached0, vec4(ACached0[i]), acc[i]); + } + }`;{let s="",a="";for(let o=0;o(ACached[${o}]), acc[i]);`;return` + for (var k = 0; k < ${r/e}; k++) { + ${s} + for (var i = 0; i < ${t}; i++) { + let ACached = mm_Asub[tileRow + i][k]; + ${a} + } + }`}};function Su(n,e,t=!1,r=32,s=!1,a=32,o=!1){const i=e[1]*n[1],l=e[0]*n[0],c=t?i:r,u=t?r:i,d=c/e[0],p=r/e[1],f=n[1],m=n[0];return $((t&&d===4&&n[1]===4||!t&&(d===3||d===4))&&c%e[0]===0&&r%e[1]===0&&n[0]===4,()=>`If transposeA ${t} is true, innerElementSize ${d} and workPerThread[1] ${n[1]} must be 4. + Otherwise, innerElementSize ${d} must be 3 or 4. + tileAWidth ${c} must be divisible by workgroupSize[0]${e[0]}. tileInner ${r} must be divisible by workgroupSize[1] ${e[1]}. colPerThread ${n[0]} must be 4.`),` + var mm_Asub : array, ${c/d}>, ${u}>; + var mm_Bsub : array, ${l/n[0]}>, ${r}>; + + ${re()} { + let localRow = i32(localId.y); + let tileRow = localRow * ${f}; + let tileCol = i32(localId.x); + + let globalRow = i32(globalId.y) * ${f}; + let globalCol = i32(globalId.x) * ${m}; + let batch = ${s?"0":"i32(globalId.z)"}; + let batchA = ${s||!o?"batch":"batch % uniforms.aShape[0]"}; + let batchB = ${s||!o?"batch":"batch % uniforms.bShape[0]"}; + let globalRowStart = i32(workgroupId.y) * ${i}; + + let numTiles = ${s?`${Math.ceil(a/r)}`:`(uniforms.dimInner - 1) / ${r} + 1`}; + var kStart = ${s?`i32(globalId.z) * ${a}`:"0"}; + + var acc: array, ${f}>; + + // Loop over shared dimension. + let tileRowB = localRow * ${p}; + for (var t = 0; t < numTiles; t++) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < ${f}; innerRow++) { + let inputRow = tileRow + innerRow; + let inputCol = tileCol; + ${NO(t,d)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${p}; innerRow++) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batchB, kStart + inputRow, globalCol); + } + kStart = kStart + ${r}; + workgroupBarrier(); + + // Compute acc values for a single thread. + ${$O(t,d,f,r)} + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < ${f}; innerRow++) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } + }`}const uh=n=>n?` + mm_Asub[inputRow][inputCol] = mm_readA(batchA, + kStart + inputRow, + globalRowStart + inputCol); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batchA, + globalRowStart + inputRow, + kStart + inputCol); + `,TO=n=>n?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];";function Iu(n,e,t=!1,r=32,s=!1,a=32,o=!1,i=!1){const l=n[1]*e[1],c=n[0]*e[0],u=t?l:r,d=t?r:l;$(d%e[1]===0&&u%e[0]===0&&r%e[1]===0,()=>`tileAHight ${d} must be divisible by workgroupSize[1]${e[1]}, tileAWidth ${u} must be divisible by workgroupSize[0]${e[0]}, tileInner ${r} must be divisible by workgroupSize[1]${e[1]}`);const p=d/e[1],f=u/e[0],m=r/e[1],g=n[1],b=n[0],v=o?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${l}; + let globalColStart = i32(workgroupId.x) * ${c}; + + // Loop over shared dimension. + for (var t = 0; t < numTiles; t++) { + // Load one tile of A into local memory. + for (var inputRow = localRow; inputRow < ${d}; inputRow = inputRow + ${e[1]}) { + for (var inputCol = localCol; inputCol < ${u}; inputCol = inputCol + ${e[0]}) { + ${uh(t)} + } + } + // Load one tile of B into local memory. + for (var inputRow = localRow; inputRow < ${r}; inputRow = inputRow + ${e[1]}) { + for (var inputCol = localCol; inputCol < ${c}; inputCol = inputCol + ${e[0]}) { + mm_Bsub[inputRow][inputCol] = mm_readB(batchB, + kStart + inputRow, + globalColStart + inputCol); + } + } + kStart = kStart + ${r}; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array; + for (var k = 0; k < ${r}; k++) { + for (var inner = 0; inner < ${b}; inner++) { + BCached[inner] = mm_Bsub[k][localCol + inner * ${e[0]}]; + } + for (var innerRow = 0; innerRow < ${g}; innerRow++) { + let ACached = ${t?`mm_Asub[k][localRow + innerRow * ${e[1]}];`:`mm_Asub[localRow + innerRow * ${e[1]}][k];`} + for (var innerCol = 0; innerCol < ${b}; innerCol++) { + acc[innerRow][innerCol] = + fma(ACached, BCached[innerCol], acc[innerRow][innerCol]); + } + } + } + workgroupBarrier(); + } + for (var innerRow = 0; innerRow < ${g}; innerRow++) { + let gRow = globalRowStart + localRow + innerRow * ${e[1]}; + for (var innerCol = 0; innerCol < ${b}; innerCol++) { + let gCol = globalColStart + localCol + innerCol * ${e[0]}; + mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); + } + } + `:` + let tileRow = i32(localId.y) * ${g}; + let tileCol = i32(localId.x) * ${b}; + + let globalRow = i32(globalId.y) * ${g}; + let globalCol = i32(globalId.x) * ${b}; + let globalRowStart = i32(workgroupId.y) * ${l}; + + let tileRowA = i32(localId.y) * ${p}; + let tileColA = i32(localId.x) * ${f}; + let tileRowB = i32(localId.y) * ${m}; + // Loop over shared dimension. + for (var t = 0; t < numTiles; t++) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < ${p}; innerRow++) { + for (var innerCol = 0; innerCol < ${f}; innerCol++) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${uh(t)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${m}; innerRow++) { + for (var innerCol = 0; innerCol < ${b}; innerCol++) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol + innerCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batchB, + kStart + inputRow, + globalCol + innerCol); + } + } + kStart = kStart + ${r}; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array; + for (var k = 0; k < ${r}; k++) { + for (var inner = 0; inner < ${b}; inner++) { + BCached[inner] = mm_Bsub[k][tileCol + inner]; + } + + for (var innerRow = 0; innerRow < ${g}; innerRow++) { + ${TO(t)} + for (var innerCol = 0; innerCol < ${b}; innerCol++) { + acc[innerRow][innerCol] = + fma(ACached, BCached[innerCol], acc[innerRow][innerCol]); + } + } + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < ${g}; innerRow++) { + for (var innerCol = 0; innerCol < ${b}; innerCol++) { + mm_write(batch, globalRow + innerRow, globalCol + innerCol, + acc[innerRow][innerCol]); + } + } + `;return` + var mm_Asub : array, ${d}>; + var mm_Bsub : array, ${r}>; + + ${re()} { + let batch = ${s?"0":"i32(globalId.z)"}; + let batchA = ${s||!i?"batch":"batch % uniforms.aShape[0]"}; + let batchB = ${s||!i?"batch":"batch % uniforms.bShape[0]"}; + let numTiles = ${s?`${Math.ceil(a/r)}`:`(uniforms.dimInner - 1) / ${r} + 1`}; + var kStart = ${s?`i32(globalId.z) * ${a}`:"0"}; + + var acc : array, ${g}>; + + // Without this initialization strange values show up in acc. + for (var innerRow = 0; innerRow < ${g}; innerRow++) { + for (var innerCol = 0; innerCol < ${b}; innerCol++) { + acc[innerRow][innerCol] = 0.0; + } + } + ${v} + } + `}const EO=n=>n?` + mm_readA(batchA, colA, globalRow), + mm_readA(batchA, colA + 1, globalRow), + mm_readA(batchA, colA + 2, globalRow), + mm_readA(batchA, colA + 3, globalRow) + `:` + mm_readA(batchA, globalRow, colA), + mm_readA(batchA, globalRow, colA + 1), + mm_readA(batchA, globalRow, colA + 2), + mm_readA(batchA, globalRow, colA + 3) + `;function AO(n,e=!1){$(n[1]===1&&n[2]===1,()=>`A linear work group size is required. But got ${n}.`);const t=n[0]*4;return` + var mm_Asub : array, ${n[0]}>; + + ${re()} { + let tileCol = i32(localId.x); + let globalCol = i32(globalId.x); + let globalRow = i32(globalId.y); + + let numTiles = (uniforms.dimInner - 1) / ${t} + 1; + let batch = i32(globalId.z); + let batchA = batch % uniforms.aShape[0]; + let batchB = batch % uniforms.bShape[0]; + // Without this initialization strange values show up in acc. + var acc = 0.0; + + // Loop over shared dimension. + for (var t = 0; t < numTiles; t++) { + // Load one tile of A into local memory. + let colA = t * ${t} + tileCol * 4; + mm_Asub[tileCol] = vec4(${EO(e)}); + workgroupBarrier(); + + // Compute acc values for a single thread. + for (var k = 0; k < ${t/4}; k++) { + let rowB = t * ${t} + k * 4; + let BCached = vec4(mm_readB(batchB, rowB, globalCol), + mm_readB(batchB, rowB + 1, globalCol), + mm_readB(batchB, rowB + 2, globalCol), + mm_readB(batchB, rowB + 3, globalCol)); + + let ACached = mm_Asub[k]; + acc = acc + dot(ACached, BCached); + } + + workgroupBarrier(); + } + + mm_write(batch, globalRow, globalCol, acc); + } + `}class RO{constructor(e,t,r=!1,s=!1,a=null,o=null,i=null,l=!1){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.outputShape=t,this.dispatchLayout={x:[2],y:[1],z:[0]};const c=r?e[1]:e[2];if(this.isVec4=(c%4===0&&!r||t[1]%4===0&&r)&&t[2]%4===0&&!s,this.outputComponent=this.isVec4?4:1,this.isVectorA=t[1]===1&&!r,!this.isVec4&&this.isVectorA)this.elementsPerThread=[1,1,1],this.workgroupSize=[32,1,1];else{const p=sF(t[1],c,t[2],r);this.workgroupSize=p.workgroupSize,this.elementsPerThread=p.elementsPerThread}this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize,this.elementsPerThread);const u=a!=null,d=i!=null;u&&this.variableNames.push("bias"),d&&this.variableNames.push("preluActivationWeights"),this.sequentialAccessByThreads=l,this.transposeA=r,this.transposeB=s,this.addBias=u,this.activation=o,this.hasPreluActivationWeights=d,[this.fitAOuter,this.fitBOuter,this.fitInner]=this.getShapeFit(t[1],t[2],c),this.shaderKey=`matMulPacked_${this.elementsPerThread}_${r}_${s}_${this.activation}_${this.fitAOuter}_${this.fitBOuter}_${this.fitInner}_${this.isVec4}_${this.isVectorA}_${this.sequentialAccessByThreads}`}getShapeFit(e,t,r){const s=this.workgroupSize[1]*this.elementsPerThread[1],a=this.workgroupSize[0]*this.elementsPerThread[0];!this.isVec4&&this.isVectorA?this.tileInner=this.workgroupSize[0]*4:this.tileInner=a;const o=e%s===0,i=t%a===0,l=r%this.tileInner===0;return[o,i,l]}getUserCode(){return` + ${ir(this.activation,this.hasPreluActivationWeights,this.isVec4)} + ${Qd(this.addBias,this.activation,!1,this.transposeB,this.fitAOuter,this.fitBOuter,this.fitInner,this.isVec4?4:1)} + ${this.isVec4?Su(this.elementsPerThread,this.workgroupSize,this.transposeA,this.tileInner,!1,null,!0):this.isVectorA?AO(this.workgroupSize,this.transposeA):Iu(this.elementsPerThread,this.workgroupSize,this.transposeA,this.tileInner,!1,null,this.sequentialAccessByThreads,!0)} + `}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function DO(n){return` + var sumValues : array; + ${re()} { + let coords = getOutputCoords(); + let batch = coords[0]; + let batchA = batch % uniforms.aShape[0]; + let batchB = batch % uniforms.bShape[0]; + let row = coords[1]; + let col = coords[2]; + var sum = 0.0; + let Length = uniforms.dimInner; + for (var k = i32(localId.x); k < Length; k = k + ${n}) { + let dataA = mm_readA(batchA, row, k); + let dataB = mm_readB(batchB, k, col); + sum = sum + dataA * dataB; + } + sumValues[localId.x] = sum; + workgroupBarrier(); + + for(var currentSize = ${n/2}u; currentSize > 1u; + currentSize = currentSize / 2u) { + if (localId.x < currentSize) + { + sumValues[localId.x] = sumValues[localId.x] + sumValues[localId.x + currentSize]; + } + workgroupBarrier(); + } + + if (localId.x == 0u) { + sum = sumValues[0] + sumValues[1]; + mm_write(batch, row, col, sum); + } + } + `}class PO{constructor(e,t=!1,r=!1,s=null,a=null,o=null){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.workgroupSize=[256,1,1],this.outputShape=e,this.dispatchLayout={x:[],y:[1,2],z:[0]},this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize);const i=s!=null,l=o!=null;i&&this.variableNames.push("bias"),l&&this.variableNames.push("preluActivationWeights"),this.transposeA=t,this.transposeB=r,this.addBias=i,this.activation=a,this.hasPreluActivationWeights=l,this.shaderKey=`matMulReduce_${this.activation}_${t}_${r}`}getUserCode(){return` + ${ir(this.activation,this.hasPreluActivationWeights)} + ${Qd(this.addBias,this.activation,this.transposeA,this.transposeB)} + ${DO(this.workgroupSize[0])} + `}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function FO(n){const e=n[1],t=n[0],r=e>t?e:t;return` + var mm_Asub : array, ${e}>; + var mm_Bsub : array, ${r}>; + + // If the output size is small for matrix multiplication, avoid to use vec4 + // and handle some elements per thread to optimally utilize the ALU. + // Read data from global memory to registers firstly, then store them into + // shared memory, so it is instruction-Level parallelism for arithmetic + // operations and others handle IO operations between barrier api, makes ALU + // and load/store units work simultaneously, could improves the performance. + ${re()} { + let tileRow = i32(localId.y); + let tileCol = i32(localId.x); + let globalRow = i32(globalId.y); + let globalCol = i32(globalId.x); + let batch = i32(globalId.z); + let batchA = batch % uniforms.aShape[0]; + let batchB = batch % uniforms.bShape[0]; + + // uniforms.dimInner should be greater than 0. + let numTiles = (uniforms.dimInner - 1) / ${r} + 1; + var acc = 0.0; + + var globalColA = tileCol; + var globalRowB = 0; + var regA = mm_readA(batchA, globalRow, globalColA); + var regB0 = mm_readB(batchB, globalRowB + 2 * tileRow, globalCol); + var regB1 = mm_readB(batchB, globalRowB + 2 * tileRow + 1, globalCol); + globalColA = globalColA + ${r}; + globalRowB = globalRowB + ${r}; + + for (var t = 0; t < numTiles; t = t + 1) { + mm_Asub[tileRow][tileCol] = regA; + mm_Bsub[2 * tileRow][tileCol] = regB0; + mm_Bsub[2 * tileRow + 1][tileCol] = regB1; + + workgroupBarrier(); + + regA = mm_readA(batchA, globalRow, globalColA); + regB0 = mm_readB(batchB, globalRowB + 2 * tileRow, globalCol); + regB1 = mm_readB(batchB, globalRowB + 2 * tileRow + 1, globalCol); + globalColA = globalColA + ${r}; + globalRowB = globalRowB + ${r}; + + for (var k = 0; k < ${r}; k = k + 1) { + acc = acc + mm_Asub[tileRow][k] * mm_Bsub[k][tileCol]; + } + workgroupBarrier(); + } + + mm_write(batch, globalRow, globalCol, acc); + } + `}class OO{constructor(e,t,r,s=!1,a=!1,o=null,i=null,l=null){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.workgroupSize=[16,8,1],this.outputShape=r,this.dispatchLayout={x:[2],y:[1],z:[0]},this.dispatch=[Math.ceil(r[2]/this.workgroupSize[0]),Math.ceil(r[1]/this.workgroupSize[1]),r[0]];const c=o!=null;c&&this.variableNames.push("bias");const u=l!=null;u&&this.variableNames.push("preluActivationWeights"),this.transposeA=s,this.transposeB=a,this.addBias=c,this.activation=i,this.hasPreluActivationWeights=u,this.shaderKey=`matMulSmallOutputSize_${this.activation}_${s}_${a}`}getUserCode(){return` + ${ir(this.activation,this.hasPreluActivationWeights)} + ${Qd(this.addBias,this.activation,this.transposeA,this.transposeB)} + ${FO(this.workgroupSize)} + `}}/** + * @license + * Copyright 2022 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. + * ============================================================================= + */class MO{constructor(e,t,r=!1,s=!1){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.workgroupSize=[8,8,1],this.atomic=!0,this.splitedDimInner=128,$(e[0]===1,()=>"MatMulSplitKProgram only supports batch = 1."),this.outputShape=e,this.dispatchLayout={x:[2],y:[1],z:[0,3]};const a=(r&&this.outputShape[1]%4===0||!r&&t%4===0)&&this.outputShape[2]%4===0;this.elementsPerThread=[4,4,this.splitedDimInner],this.outputComponent=a?4:1,a||(this.outputShape[1]<16&&(this.elementsPerThread[1]=1),this.outputShape[2]<16&&(this.elementsPerThread[0]=1)),this.dispatch=se(this.dispatchLayout,[this.outputShape[0],this.outputShape[1],this.outputShape[2],t],this.workgroupSize,this.elementsPerThread),this.transposeA=r,this.transposeB=s,this.shaderKey=`matMulSplitK_${r}_${s}_${this.elementsPerThread}_${this.outputComponent}`}getUserCode(){const e=this.outputComponent;return` + ${ab(!1,this.transposeB,!1,!1,!1,e)} + fn mm_write(batch: i32, row : i32, col : i32, value : ${Ee(e)}) { + if (row < uniforms.dimAOuter && col < uniforms.dimBOuter) { + let coords = vec3(batch, row, col); + let flatIndex = getOutputIndexFromCoords(coords); + // The problem is that we should initialize output to zero before using. + // Otherwise, the original value will be added to the result. + for (var i = 0; i < ${e}; i = i + 1) { + ${zr("&result[flatIndex + i]",`${e>1?"value[i]":"value"}`,"float32")} + } + } + } + ${e===4?Su(this.elementsPerThread,this.workgroupSize,this.transposeA,32,!0,this.splitedDimInner):Iu(this.elementsPerThread,this.workgroupSize,this.transposeA,32,!0,this.splitedDimInner)} + `}}class LO{constructor(e,t=null,r=null,s=null){this.uniforms="",this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.addBias=t!=null,this.hasPreluActivationWeights=s!=null,this.activation=r,this.addBias&&this.variableNames.push("bias"),this.hasPreluActivationWeights&&this.variableNames.push("preluActivationWeights"),this.shaderKey=`biasActivation_${r}`}getUserCode(){return` + ${ir(this.activation,this.hasPreluActivationWeights)} + ${re("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + var value = getXByOutputIndex(index); + ${_s(this.addBias,this.activation)} + setOutputAtIndex(index, value); + } + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class zO{constructor(e){this.variableNames=[],this.outputShape=[],this.uniforms="value : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="fill"}getUserCode(){return` + ${re("index")} { + if (index < uniforms.size) { + setOutputAtIndex(index, uniforms.value); + } + } + `}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function Wt(n){const{backend:e,attrs:t}=n,{shape:r,value:s}=t;let{dtype:a}=t;if(a=a||da(s),a==="string"){const o=Ar(a,q(r));return o.fill(s),e.makeTensorInfo(r,a,o)}else{const o=new zO(r),i=[{type:"float32",data:[s]}];return e.runWebGPUProgram(o,[],a,i)}}const BO={kernelName:Ic,backendName:"webgpu",kernelFunc:Wt};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function de(n){const{inputs:e,attrs:t}=n,{x:r}=e,{shape:s}=t,a=q(r.shape),o=Xh(s,a),i=q(o);return $(a===i,()=>`The new shape (${o}) has ${i} elements and the old shape (${r.shape}) has ${a} elements. The new shape and old shape must have the same number of elements.`),n.backend.incRef(r.dataId),{dataId:r.dataId,shape:o,dtype:r.dtype}}const WO={kernelName:td,backendName:"webgpu",kernelFunc:de};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function ku({a:n,b:e,transposeA:t,transposeB:r,backend:s,bias:a=null,preluActivationWeights:o=null,leakyreluAlpha:i=0,activation:l=null}){const c=n.shape.length,u=e.shape.length,d=t?n.shape[c-2]:n.shape[c-1],p=r?e.shape[u-1]:e.shape[u-2],f=t?n.shape[c-1]:n.shape[c-2],m=r?e.shape[u-2]:e.shape[u-1],g=n.shape.slice(0,-2),b=e.shape.slice(0,-2),v=q(g),I=q(b),C=je(n.shape.slice(0,-2),e.shape.slice(0,-2)).concat([f,m]);$(d===p,()=>`Error in matMul: inner shapes (${d}) and (${p}) of Tensors with shapes ${n.shape} and ${e.shape} and transposeA=${t} and transposeB=${r} must match.`);const T=t?[v,d,f]:[v,f,d],O=r?[I,m,p]:[I,p,m],L=de({inputs:{x:n},backend:s,attrs:{shape:T}}),B=de({inputs:{x:e},backend:s,attrs:{shape:O}}),A=[L,B],D=Math.max(v,I),_=[L,B],V=[{type:"int32",data:[f]},{type:"int32",data:[m]},{type:"int32",data:[d]}];let H,Y;const X=[D,f,m];let ee=fe().get("WEBGPU_MATMUL_PROGRAM_TYPE");if(ee<0){const ce=fe().getNumber("WEBGPU_THRESHOLD_TO_INCREASE_WORKGROUPS_FOR_MATMUL"),be=ce>0?ce:s.thresholdToIncreaseWorkgroups,Se=D*Math.ceil(f/32)*Math.ceil(m/32);Se<=be||f<=8&&Se<=be*2?D*f*m<=128?ee=Ln.MatMulReduceProgram:D===1&&p>=2e3?ee=Ln.MatMulSplitKProgram:ee=Ln.MatMulSmallOutputSizeProgram:ee=Ln.MatMulPackedProgram}switch(ee){case Ln.MatMulReduceProgram:H=new PO(X,t,r,a,l,o);break;case Ln.MatMulSplitKProgram:{if(Y=Wt({backend:s,attrs:{shape:X,value:0,dtype:n.dtype}}),H=new MO(X,p,t,r),a||l){Y=s.runWebGPUProgram(H,_,n.dtype,V,Y);const be=new LO(Y.shape,a,l,o);let Se=null;const Pe=[Y];a&&Pe.push(a),o&&Pe.push(o),l==="leakyrelu"&&(Se=[{type:"float32",data:[i]}],be.uniforms+=" alpha : f32,");const Ve=s.runWebGPUProgram(be,Pe,Y.dtype,Se);A.push(Y);const Oe=de({inputs:{x:Ve},backend:s,attrs:{shape:C}});A.push(Ve);for(const Et of A)s.disposeData(Et.dataId);return Oe}break}case Ln.MatMulSmallOutputSizeProgram:H=new OO(T,O,X,t,r,a,l,o);break;case Ln.MatMulPackedProgram:const ce=s.adapterInfo.isIntel();H=new RO(T,X,t,r,a,l,o,ce);break;default:throw new Error(`Unsupported MatMulProgramType ${ee}.`)}a&&_.push(a),o&&_.push(o),l==="leakyrelu"&&(V.push({type:"float32",data:[i]}),H.uniforms+=" alpha : f32,"),Y=s.runWebGPUProgram(H,_,n.dtype,V,Y);const ye=de({inputs:{x:Y},backend:s,attrs:{shape:C}});A.push(Y);for(const ce of A)s.disposeData(ce.dataId);return ye}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function VO(n){const{inputs:e,backend:t,attrs:r}=n,{a:s,b:a,bias:o,preluActivationWeights:i}=e,{transposeA:l,transposeB:c,activation:u,leakyreluAlpha:d}=r;return ku({a:s,b:a,transposeA:l,transposeB:c,backend:t,bias:o,preluActivationWeights:i,leakyreluAlpha:d,activation:u})}const UO={kernelName:Ka,backendName:"webgpu",kernelFunc:VO};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */class lh{constructor(e,t,r){this.variableNames=["AReal","AImag","BReal","BImag"],this.workgroupSize=[128,1,1],this.size=!0,this.outputShape=je(t,r),this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey=`binaryOpComplex_${e}`,this.op=e}getUserCode(){return` + fn binaryOpComplex( + areal : f32, aimag : f32, breal : f32, bimag : f32) -> f32 { + ${Yd(this.op,!1)} + } + + ${re("index")} { + if(index < uniforms.size) { + let areal = getARealByOutputIndex(index); + let aimag = getAImagByOutputIndex(index); + let breal = getBRealByOutputIndex(index); + let bimag = getBImagByOutputIndex(index); + setOutputAtIndex(index, binaryOpComplex(areal, aimag, breal, bimag)); + } + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class oi{constructor(e,t,r){if(this.size=!0,this.variableNames=["A","B"],this.outputShape=je(t,r),this.dispatchLayout=ie(this.outputShape),this.op=e,this.useSharedMemoryWithA=t.length<=1&&r.length>1&&t[0]<128,this.useSharedMemoryWithB=r.length<=1&&t.length>1&&r[0]<128,this.useSharedMemoryWithA||this.useSharedMemoryWithB)this.outputComponent=1,this.variableComponents=[1,1],this.lastDimensionSize=this.useSharedMemoryWithB?r[0]:t[0],this.shaderKey=`binary_${e}_${this.lastDimensionSize}`,this.type="shared",this.workgroupSize=[256,1,1];else{const s=t.length>0&&t[t.length-1]%4===0,a=r.length>0&&r[r.length-1]%4===0;s&&a?(this.outputComponent=4,this.variableComponents=[4,4]):s&&(lp(r)||r[r.length-1]===1)||a&&(lp(t)||t[t.length-1]===1)?(this.outputComponent=4,this.variableComponents=s?[4,1]:[1,4]):(this.outputComponent=1,this.variableComponents=[1,1]),this.type="nonshared",this.shaderKey=`binary_${e}_${this.variableComponents}`,this.workgroupSize=[128,1,1]}this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize,[this.outputComponent,1,1])}getUserCode(){let e;const t=this.outputComponent===4?"vec4":"f32",r=` + fn binaryOperation(a : ${t}, b : ${t}) -> ${t} { + ${Yd(this.op,this.outputComponent===4)} + }; + `;if(this.type==="shared"){const s=this.lastDimensionSize>1?`coords[${this.outputShape.length-1}]`:"0",a=this.useSharedMemoryWithB?`let a = getAByOutputIndex(index); + let b = sharedBuf[${s}];`:`let a = sharedBuf[${s}]; + let b = getBByOutputIndex(index);`;e=` + ${r} + var sharedBuf : array; + ${re("index")} { + // Fill in the shared memory buffer. + let localIndex = i32(localId.x); + if(localIndex < ${this.lastDimensionSize}) { + sharedBuf[localIndex] = f32(${this.useSharedMemoryWithB?"B":"A"}[localIndex]); + } + workgroupBarrier(); + + if(index < uniforms.size) { + let coords = getCoordsFromIndex(index); + ${a} + setOutputAtIndex(index, binaryOperation(a, b)); + } + } + `}else e=` + ${r} + ${re("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index * ${this.outputComponent}); + let a = ${t}(getAByOutputCoords(coords)); + let b = ${t}(getBByOutputCoords(coords)); + setOutputAtIndex(index, binaryOperation(a, b)); + } + } + `;return e}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function Xt(n){const{inputs:e}=n,{x:t}=e;return n.backend.incRef(t.dataId),{dataId:t.dataId,shape:t.shape,dtype:t.dtype}}const HO={kernelName:Di,backendName:"webgpu",kernelFunc:Xt};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function Cs(n){const{inputs:e,backend:t}=n,{real:r,imag:s}=e,a=t.makeTensorInfo(r.shape,"complex64"),o=t.tensorMap.get(a.dataId),i=Xt({inputs:{x:r},backend:t}),l=Xt({inputs:{x:s},backend:t});return o.complexTensorInfos={real:i,imag:l},a}const GO={kernelName:sf,backendName:"webgpu",kernelFunc:Cs};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class ya{constructor(e,t,r=""){this.variableNames=["A"],this.size=!0;const s=128;this.workgroupSize=[s,1,1],this.outputShape=e,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.op=t,r!==""&&(this.uniforms=r),this.shaderKey=`unary_${t}`}getUserCode(){return` + fn unaryOperation(a : f32) -> f32 { + ${Jr(this.op,!1)} + } + ${re("index")} { + if (index < uniforms.size) { + let a = getAByOutputIndex(index); + setOutputAtIndex(index, unaryOperation(a)); + } + } + `}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function We({opType:n,cpuKernelImpl:e,dtype:t}){return({inputs:r,backend:s})=>{const{x:a}=r,o=s,i=t||a.dtype;if(o.shouldExecuteOnCPU([a])&&e!=null){const c=o.tensorMap.get(a.dataId),u=e(c.values,i);return o.makeTensorInfo(a.shape,i,u)}const l=new ya(a.shape,n);return o.runWebGPUProgram(l,[a],i)}}function xt({opType:n,cpuKernelImpl:e,supportsComplex:t=!1,dtype:r}){return({inputs:s,backend:a})=>{const{a:o,b:i}=s,l=a;if(t&&o.dtype==="complex64"){const d=l.tensorMap.get(o.dataId),p=l.tensorMap.get(i.dataId);let f,m;if(n!==ve.MUL)[f,m]=[[d.complexTensorInfos.real,p.complexTensorInfos.real],[d.complexTensorInfos.imag,p.complexTensorInfos.imag]].map(b=>{const[v,I]=b,S={dataId:v.dataId,dtype:v.dtype,shape:o.shape},C={dataId:I.dataId,dtype:I.dtype,shape:i.shape},T=new oi(n,o.shape,i.shape);return l.runWebGPUProgram(T,[S,C],_r(v.dtype,I.dtype))});else{const b=new lh(ve.COMPLEX_MULTIPLY_REAL,o.shape,i.shape),v=new lh(ve.COMPLEX_MULTIPLY_IMAG,o.shape,i.shape),I=[{dataId:d.complexTensorInfos.real.dataId,dtype:d.complexTensorInfos.real.dtype,shape:o.shape},{dataId:d.complexTensorInfos.imag.dataId,dtype:d.complexTensorInfos.imag.dtype,shape:o.shape},{dataId:p.complexTensorInfos.real.dataId,dtype:p.complexTensorInfos.real.dtype,shape:i.shape},{dataId:p.complexTensorInfos.imag.dataId,dtype:p.complexTensorInfos.imag.dtype,shape:i.shape}];f=l.runWebGPUProgram(b,I,"float32"),m=l.runWebGPUProgram(v,I,"float32")}const g=Cs({inputs:{real:f,imag:m},backend:l});return l.disposeData(f.dataId),l.disposeData(m.dataId),g}const c=r||_r(o.dtype,i.dtype);if((o.dtype==="string"||i.dtype==="string"||l.shouldExecuteOnCPU([o,i]))&&e!=null){const d=l.tensorMap.get(o.dataId).values,p=l.tensorMap.get(i.dataId).values,f=o.dtype==="string"?ri(d):d,m=o.dtype==="string"?ri(p):p,[g,b]=e(o.shape,i.shape,f,m,c);return l.makeTensorInfo(b,c,g)}const u=new oi(n,o.shape,i.shape);return l.runWebGPUProgram(u,[o,i],c)}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const{addImpl:jO,castImpl:qO,ceilImpl:KO,concatImpl:XO,equalImpl:YO,expImpl:QO,expm1Impl:ZO,floorImpl:JO,floorDivImpl:eM,gatherNdImpl:tM,gatherV2Impl:nM,greaterEqualImpl:rM,greaterImpl:sM,lessEqualImpl:aM,lessImpl:oM,logImpl:iM,maxImpl:uM,maximumImpl:lM,minimumImpl:cM,multiplyImpl:dM,negImpl:pM,notEqualImpl:hM,prodImpl:fM,rangeImpl:mM,rsqrtImpl:gM,scatterImpl:yM,simpleAbsImpl:bM,sliceImpl:wM,stridedSliceImpl:xM,stringNGramsImpl:vM,subImpl:SM,tileImpl:IM,topKImpl:kM,transposeImpl:_M}=eT;/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const CM=We({opType:ne.ABS,cpuKernelImpl:bM}),NM={kernelName:ql,backendName:"webgpu",kernelFunc:CM};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */const $M=We({opType:ne.ACOS}),TM={kernelName:Kl,backendName:"webgpu",kernelFunc:$M};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */const EM=We({opType:ne.ACOSH}),AM={kernelName:Xl,backendName:"webgpu",kernelFunc:EM};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const RM=xt({opType:ve.ADD,cpuKernelImpl:jO,supportsComplex:!0}),DM={kernelName:di,backendName:"webgpu",kernelFunc:RM};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */class PM{constructor(e){this.workPerThread=1,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e[0],this.variableNames=e.map((t,r)=>`T${r}`),this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize,[this.workPerThread,1,1]),this.shaderKey="addN"}getUserCode(){const e=[];this.variableNames.forEach(s=>{e.push(`let v${s} = get${s}ByOutputCoords(coords);`)});const t=this.variableNames.map(s=>`v${s}`).join(" + ");return` + ${re("index")} { + for (var i = 0; i < ${this.workPerThread}; i = i + 1) { + let flatIndex = index * ${this.workPerThread} + i; + if (flatIndex < uniforms.size) { + let coords = getCoordsFromIndex(flatIndex); + ${e.join(` + `)} + setOutputAtIndex(flatIndex, ${t}); + } + } + } + `}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function FM(n){const{inputs:e,backend:t}=n,r=e;if(r.length===1)return Xt({inputs:{x:r[0]},backend:t});const s=r.map(i=>i.dtype).reduce((i,l)=>_r(i,l)),a=r.map(i=>i.shape),o=new PM(a);return t.runWebGPUProgram(o,r,s)}const OM={kernelName:pi,backendName:"webgpu",kernelFunc:FM};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class MM{constructor(e,t){this.variableNames=["A"],this.workgroupSize=[16,16,1];const r=new Array(e.length);for(let s=0;s`Must be a square tile, current tile shape is ${this.workgroupSize[0]} x ${this.workgroupSize[1]}`);const e=this.workgroupSize[0];return` + var tile : array, ${this.workgroupSize[0]}>; + ${re()} { + var x = i32(workgroupId.x) * ${e} + i32(localId.x); + var y = i32(workgroupId.y) * ${e} + i32(localId.y); + let width = uniforms.outShape[0]; + let height = uniforms.outShape[1]; + if (x < width && y < height) { + tile[localId.y][localId.x] = f32(A[y * width + x]); + } + workgroupBarrier(); + + x = i32(workgroupId.y) * ${e} + i32(localId.x); + y = i32(workgroupId.x) * ${e} + i32(localId.y); + if (x < height && y < width) { + setOutputAtIndex((y * height + x), tile[localId.x] + [localId.y]); + } + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class LM{constructor(e,t){this.variableNames=["A"],this.workPerThread=1,this.workgroupSize=[64,1,1],this.size=!0;const r=new Array(e.length);for(let s=0;s6)throw Error(`Transpose for rank ${e} is not yet supported`);const t=new Array(e);for(let r=0;r=32768&&r>=512?this.workgroupSize=[512,1,1]:e.inSize>=4096?this.workgroupSize=[256,1,1]:this.workgroupSize=[64,1,1],this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,[1,1,1]),this.reduceType=t,this.shaderKey=`reduce_${t}`}getUserCode(){let e="",t="0.0";const r=this.workgroupSize[0];this.reduceType==="min"||this.reduceType==="max"?(e=` + if (isnan(candidate)) { + bestValue = uniforms.NAN; + } else if (!isnan(bestValue) && candidate ${this.reduceType==="min"?"<":">"} bestValue) + { bestValue = candidate; }`,t="f32(x[offset])"):this.reduceType==="sum"||this.reduceType==="mean"?e=" bestValue = bestValue + candidate; ":this.reduceType==="prod"?(e=" bestValue = bestValue * candidate; ",t="1.0"):this.reduceType==="all"?(e=" bestValue = f32(bestValue >= 1.0 && candidate >= 1.0); ",t="1.0"):this.reduceType==="any"&&(e=" bestValue = f32(bestValue >= 1.0 || candidate >= 1.0); ",t="0.0");const s=this.reduceType==="mean"?"setOutputAtIndex(outputIndex, bestValue / f32(uniforms.reduceSize));":"setOutputAtIndex(outputIndex, bestValue);";return` + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + + ${` + var xBestValues : array; + `} + fn getOffset(outputIndex : i32) -> i32 { + let outputCoords = getCoordsFromIndex(outputIndex); + let offset = ${this.outputShape.length===1?"outputCoords":"outputCoords[0]"} * uniforms.reduceSize; + return offset; + } + ${re("index")} { + let outputIndex = index / ${r}; + let offset = getOffset(outputIndex); + var bestValue = ${t}; + let Length = uniforms.reduceSize; + let WorkPerThread = DIV_CEIL(u32(Length), ${r}u); + for (var k = i32(localId.x); k < Length && outputIndex < uniforms.size; + k = k + ${r}) { + let candidate = f32(x[offset + k]); + ${e} + } + xBestValues[localId.x] = bestValue; + workgroupBarrier(); + + var reduceSize = min(u32(Length), ${r}u); + for (var currentSize = reduceSize / 2u; reduceSize > 1u; + currentSize = reduceSize / 2u) { + let interval = DIV_CEIL(reduceSize, 2u); + if (localId.x < currentSize) { + let candidate = xBestValues[localId.x + interval]; + ${e} + xBestValues[localId.x] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (localId.x == 0u && outputIndex < uniforms.size) { + ${s} + } + } + `}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const WM={mean:"float32",all:"bool",any:"bool"};function Ns(n,e,t,r,s){const a=n.shape.length,o=[],i=$t(e,n.shape);let l=i;const c=Or(l,a);let u=n;c!=null&&(u=Vn({inputs:{x:n},attrs:{perm:c},backend:s}),l=An(l.length,a),o.push(u)),yn(r,l,a);const[d,p]=En(u.shape,l);let f=d;t&&(f=gn(d,i));let m;if((r==="max"||r==="prod")&&s.shouldExecuteOnCPU([u])){const g=s.tensorMap.get(u.dataId).values;switch(r){case"max":const b=uM(g,q(p),f,n.dtype);m=s.makeTensorInfo(f,n.dtype,b);break;case"prod":const{outVals:v,outShape:I,outDtype:S}=fM(u.shape,u.dtype,g,l);m=s.makeTensorInfo(I,S,v);break;default:throw new Error(`${r} CPU implementation is not yet supported.`)}}else{const g=q(p),v=q(u.shape)/g,I={windowSize:g,inSize:g,batchSize:v,outSize:1},S=WM[r]||o0(n.dtype),C=[{type:"int32",data:[g]}],T=new BM(I,r,s.device.limits.maxComputeWorkgroupSizeX),O=s.runWebGPUProgram(T,[u],S,C);o.push(O),m=de({inputs:{x:O},attrs:{shape:f},backend:s})}return o.forEach(g=>s.disposeData(g.dataId)),m}/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */function VM(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{keepDims:a,axis:o}=r;return Ns(s,o,a,"all",t)}const UM={kernelName:hi,backendName:"webgpu",kernelFunc:VM};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */function HM(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{keepDims:a,axis:o}=r;return Ns(s,o,a,"any",t)}const GM={kernelName:fi,backendName:"webgpu",kernelFunc:HM};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class ib{constructor(e,t,r){this.workgroupSize=[64,1,1],this.variableNames=["x"],this.uniforms="infinityValue : f32,",this.size=!0;const s=[t];this.op=r==="min"?"<":">";const[a,o]=En(e,s);this.outputShape=a.length===0?[1]:a,this.dispatchLayout=ie(this.outputShape),q(o)<32?(this.type="plain",this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize)):(this.type="shared",this.dispatch=se(this.dispatchLayout,this.outputShape,[1,1,1])),this.inputShape=e,this.shaderKey=`argMinMax_${this.op}_${this.type}`}getUserCode(){const e=this.workgroupSize[0],t=()=>this.inputShape.length===1?"uniforms.xShape":`uniforms.xShape.${tr(this.inputShape.length-1)}`,r=()=>{let s="";if(this.outputShape.length===1)this.inputShape.length!==1&&(s+="outputCoords,");else for(let a=0;a u32 { + return ((a - 1u) / b + 1u); + } + + ${` + var xBestIndices : array; + var xBestValues : array; + `} + + ${re("index")} { + let outputIndex = index / ${e}; + let reduceLength = ${t()}; + + var bestIndex = i32(localId.x); + var bestValue = uniforms.infinityValue; + let outputCoords = getCoordsFromIndex(outputIndex); + for (var k = i32(localId.x); k < reduceLength && outputIndex < uniforms.size; + k = k + ${e}) { + let candidate = getX(${r()} k); + if (!isnan(candidate) && candidate ${this.op} bestValue) { + bestValue = candidate; + bestIndex = k; + } + } + xBestValues[localId.x] = bestValue; + xBestIndices[localId.x] = bestIndex; + workgroupBarrier(); + + var reduceSize = min(u32(reduceLength), ${e}u); + for (var currentSize = reduceSize / 2u; reduceSize > 1u; + currentSize = reduceSize / 2u) { + let interval = DIV_CEIL(reduceSize, 2u); + if (localId.x < currentSize) { + let candidate = xBestValues[localId.x + interval]; + if (candidate ${this.op} bestValue) { + bestValue = candidate; + xBestValues[localId.x] = bestValue; + xBestIndices[localId.x] = xBestIndices[localId.x + interval]; + } + } + reduceSize = interval; + workgroupBarrier(); + } + + if (localId.x == 0u && outputIndex < uniforms.size) { + setOutputAtIndexI32(outputIndex, xBestIndices[localId.x]); + } + } + `:` + ${re("index")} { + if (index < uniforms.size) { + let outputCoords = getCoordsFromIndex(index); + var bestIndex = 0; + var bestValue = getX(${r()} 0); + let reduceLength = ${t()}; + for (var i = 1; i < reduceLength; i++) { + let candidate = getX(${r()} i); + if (candidate ${this.op} bestValue) { + bestValue = candidate; + bestIndex = i; + } + } + setOutputAtIndexI32(index, bestIndex); + } + } + `}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function jM(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{axis:a}=r;let o=$t(a,s.shape);const i=Or(o,s.shape.length);let l=s;const c=[];i!=null&&(l=Vn({inputs:{x:s},backend:t,attrs:{perm:i}}),c.push(l),o=An(o.length,l.shape.length)),yn("argMax",[o[0]],l.shape.length);const u=new ib(l.shape,o[0],"max"),d=[{type:"float32",data:[Number.NEGATIVE_INFINITY]}],p=t.runWebGPUProgram(u,[l],"int32",d);return c.forEach(f=>t.disposeData(f.dataId)),p}const qM={kernelName:Yl,backendName:"webgpu",kernelFunc:jM};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function KM(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{axis:a}=r;let o=$t(a,s.shape);const i=Or(o,s.shape.length);let l=s;const c=[];i!=null&&(l=Vn({inputs:{x:s},backend:t,attrs:{perm:i}}),c.push(l),o=An(o.length,l.shape.length)),yn("argMin",[o[0]],l.shape.length);const u=new ib(l.shape,o[0],"min"),d=[{type:"float32",data:[Number.POSITIVE_INFINITY]}],p=t.runWebGPUProgram(u,[l],"int32",d);return c.forEach(f=>t.disposeData(f.dataId)),p}const XM={kernelName:Ql,backendName:"webgpu",kernelFunc:KM};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */const YM=We({opType:ne.ASIN}),QM={kernelName:Zl,backendName:"webgpu",kernelFunc:YM};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */const ZM=We({opType:ne.ASINH}),JM={kernelName:Jl,backendName:"webgpu",kernelFunc:ZM};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */const eL=We({opType:ne.ATAN}),tL={kernelName:ec,backendName:"webgpu",kernelFunc:eL};/** + * @license + * Copyright 2022 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. + * ============================================================================= + */const nL=xt({opType:ve.ATAN2}),rL={kernelName:nc,backendName:"webgpu",kernelFunc:nL};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */const sL=We({opType:ne.ATANH}),aL={kernelName:tc,backendName:"webgpu",kernelFunc:sL};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */class oL{constructor(e){this.variableNames=["x"],this.uniforms="strides : vec2,",this.workgroupSize=[256,1,1],this.size=!0,this.outputShape=e.outShape,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="poolWithFilterSizeEqualsOne"}getUserCode(){return` + ${re("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let batch = coords[0]; + let d = coords[3]; + + let xRCCorner = coords.yz * uniforms.strides; + let xRCorner = xRCCorner.x; + let xCCorner = xRCCorner.y; + + let value = getX(batch, xRCorner, xCCorner, d); + setOutputAtIndex(index, value); + } + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class io{constructor(e,t,r=!1,s=!1,a=!1){if(this.variableNames=["x"],this.uniforms="strides : vec2, pads : vec2, dilations : vec2, convDims : vec2, filterDims : vec2,",this.workgroupSize=[128,1,1],this.size=!0,t==="avg"&&r)throw new Error("Cannot compute positions for average pool.");this.outputShape=e.outShape,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.poolType=t,this.computePositions=r,this.flattenPositions=s,this.includeBatchIndex=a,this.shaderKey=`pool2D_${t}_${r}_${s}_${a}`}getUserCode(){let e;this.poolType==="avg"?e="resultValue = resultValue + value; count = count + 1.0;":this.computePositions?e=`let currMaxValue = mix(value, maxValue, maxValueFound); + if (value >= currMaxValue) { + maxValue = value; + maxValueFound = 1.0; + maxPosition = ${this.flattenPositions?this.includeBatchIndex?"((batch * uniforms.xShape[1] + xR) * uniforms.xShape[2] + xC) * uniforms.xShape[3] + d":"(xR * uniforms.xShape[2] + xC) * uniforms.xShape[3] + d":"wR * uniforms.filterDims.y + wC"}; + }`:e="resultValue = max(value, resultValue);";let t="resultValue";return this.poolType==="avg"&&(t="resultValue / max(count, 1.0)"),` + ${re("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let batch = coords[0]; + let d = coords[3]; + let xRCCorner = vec2(coords.yz) * uniforms.strides - uniforms.pads; + let xRCorner = xRCCorner.x; + let xCCorner = xRCCorner.y; + + ${this.computePositions?`var maxValue = 0.0; + var maxValueFound = 0.0; + var maxPosition = 0;`:`var resultValue = ${this.poolType==="avg"?"0.0":"-1.0 / pow(10.0, -20.0)"};`} + + var count = 0.0; + for (var wR = 0; wR < uniforms.filterDims.x; wR = wR + uniforms.dilations.x) { + let xR = xRCorner + wR; + + if (xR < 0 || xR >= uniforms.convDims.x) { + continue; + } + + for (var wC = 0; wC < uniforms.filterDims.y; wC = wC + uniforms.dilations.y) { + let xC = xCCorner + wC; + if (xC < 0 || xC >= uniforms.convDims.y) { + continue; + } + + let value = getX(batch, xR, xC, d); + ${e} + } + } + + ${this.computePositions?"setOutputAtIndexI32(index, maxPosition);":`setOutputAtIndex(index, ${t});`} + } + } + `}}class Zd{constructor(e,t,r=!1,s=!1,a=!1){if(this.variableNames=["x"],this.uniforms="strides : vec3, pads : vec3, convDims : vec3, filterDims : vec3,",this.workgroupSize=[128,1,1],this.size=!0,t==="avg"&&r)throw new Error("Cannot compute positions for average pool.");this.outputShape=e.outShape,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.poolType=t,this.computePositions=r,this.flattenPositions=s,this.includeBatchIndex=a,this.shaderKey=`pool3D_${t}_${r}_${s}_${a}`}getUserCode(){let e;this.poolType==="avg"?e="resultValue += value; count += 1.0;":this.computePositions?e=`let currMaxValue = mix(value, maxValue, maxValueFound); + if (value >= currMaxValue) { + maxValue = value; + maxValueFound = 1.0; + maxPosition = ${this.flattenPositions?this.includeBatchIndex?"(((batch * uniforms.xShape.y + xD) * uniforms.xShape.z + xR) * uniforms.xShape.w + xC) * uniforms.xShape.u + ch":"((xD * uniforms.xShape.z + xR) * uniforms.xShape.w + xC) * uniforms.xShape.u + ch":"wD * uniforms.filterDims.y * uniforms.filterDims.y + wR * uniforms.filterDims.z + wC"}; + }`:e="resultValue = max(value, resultValue);";let t="resultValue";return this.poolType==="avg"&&(t="resultValue / max(count, 1.0)"),` + ${re("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let batch = coords.x; + let ch = coords.u; + + let xCorner = vec3(coords.y, coords.z, coords.w) * uniforms.strides - uniforms.pads; + let xDCorner = xCorner.x; + let xRCorner = xCorner.y; + let xCCorner = xCorner.z; + + ${this.computePositions?`var maxValue = 0.0; + var maxValueFound = 0.0; + var maxPosition = 0;`:`var resultValue = ${this.poolType==="avg"?"0.0":"-1.0 / pow(10.0, -20.0)"};`} + + var count = 0.0; + for (var wD = 0; wD < uniforms.filterDims.x; wD++) { + let xD = xDCorner + wD; + if (xD < 0 || xD >= uniforms.convDims.x) { + continue; + } + + for (var wR = 0; wR < uniforms.filterDims.y; wR++) { + let xR = xRCorner + wR; + if (xR < 0 || xR >= uniforms.convDims.y) { + continue; + } + + for (var wC = 0; wC < uniforms.filterDims.z; wC++) { + let xC = xCCorner + wC; + if (xC < 0 || xC >= uniforms.convDims.z) { + continue; + } + + let value = getX(batch, xD, xR, xC, ch); + ${e} + } + } + } + + ${this.computePositions?"setOutputAtIndexI32(index, maxPosition);":`setOutputAtIndex(index, ${t});`} + } + } + `}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function ub(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{reductionIndices:a,keepDims:o}=r;return Ns(s,a,o,"max",t)}const iL={kernelName:Mi,backendName:"webgpu",kernelFunc:ub};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function lb(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{keepDims:a,axis:o}=r;return Ns(s,o,a,"mean",t)}const uL={kernelName:zi,backendName:"webgpu",kernelFunc:lb};/** + * @license + * Copyright 2022 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. + * ============================================================================= + */function cb(n,e,t,r){if(e.filterWidth===1&&e.filterHeight===1&&Vt(e.inShape,e.outShape))return Xt({inputs:{x:n},backend:r});if(e.filterWidth===e.inWidth&&e.filterHeight===e.inHeight&&e.batchSize===1&&e.padInfo.type==="VALID"){const o=n.shape.length,i=de({inputs:{x:n},backend:r,attrs:{shape:[n.shape[o-3]*n.shape[o-2],n.shape[o-1]]}});let l;t==="avg"?l=lb({inputs:{x:i},backend:r,attrs:{axis:0,keepDims:!1}}):($(t==="max",()=>`Invalid pool type ${t}`),l=ub({inputs:{x:i},backend:r,attrs:{reductionIndices:0,keepDims:!1}}));const c=de({inputs:{x:l},backend:r,attrs:{shape:e.outShape}});return r.disposeData(i.dataId),r.disposeData(l.dataId),c}let s;const a=[{type:"int32",data:[e.strideHeight,e.strideWidth]}];return e.filterHeight===1&&e.filterWidth===1?s=new oL(e):(t==="avg"?s=new io(e,"avg"):($(t==="max",()=>`Invalid pool type ${t}`),s=new io(e,"max")),a.push({type:"int32",data:[e.padInfo.top,e.padInfo.left]},{type:"int32",data:[e.dilationHeight,e.dilationWidth]},{type:"int32",data:[e.inHeight,e.inWidth]},{type:"int32",data:[e.effectiveFilterHeight,e.effectiveFilterWidth]})),r.runWebGPUProgram(s,[n],n.dtype,a)}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function lL(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=r,u=Nn(s.shape,a,o,1,i,l);return cb(s,u,"avg",t)}const cL={kernelName:mi,backendName:"webgpu",kernelFunc:lL};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */function dL(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{filterSize:a,strides:o,pad:i,dataFormat:l,dimRoundingMode:c}=r,u=[1,1,1],d=Pr(s.shape,a,o,u,i,c,l),p=new Zd(d,"avg"),f=[{type:"int32",data:[d.strideDepth,d.strideHeight,d.strideWidth]},{type:"int32",data:[d.padInfo.front,d.padInfo.top,d.padInfo.left]},{type:"int32",data:[d.inDepth,d.inHeight,d.inWidth]},{type:"int32",data:[d.effectiveFilterDepth,d.effectiveFilterHeight,d.effectiveFilterWidth]}];return t.runWebGPUProgram(p,[s],s.dtype,f)}const pL={kernelName:rc,backendName:"webgpu",kernelFunc:dL};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */class hL{constructor(e){this.variableNames=["dy"],this.uniforms=`strides : vec2, pads : vec2, dilations : vec2, filterDims : vec2, + outHeight : i32, outWidth : i32, avgMultiplier : f32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.inShape,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="avgPool2DBackprop"}getUserCode(){return` + ${re("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let batch = coords[0]; + let d = coords[3]; + + let dyRCCorner = vec2(coords.yz) - uniforms.pads; + let dyRCorner = dyRCCorner.x; + let 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. + var dotProd = 0.0; + for (var wR = 0; wR < uniforms.filterDims[0]; wR = wR + uniforms.dilations[0]) { + let dyR = f32(dyRCorner + wR) / f32(uniforms.strides[0]); + + if (dyR < 0.0 || dyR >= f32(uniforms.outHeight) || fract(dyR) > 0.0) { + continue; + } + let idyR = i32(dyR); + + for (var wC = 0; wC < uniforms.filterDims[1]; wC = wC + uniforms.dilations[1]) { + let dyC = f32(dyCCorner + wC) / f32(uniforms.strides[1]); + + if (dyC < 0.0 || dyC >= f32(uniforms.outWidth) || fract(dyC) > 0.0) { + continue; + } + let idyC = i32(dyC); + + let dyValue = getDy(batch, idyR, idyC, d); + + dotProd = dotProd + dyValue * uniforms.avgMultiplier; + } + } + setOutputAtIndex(index, dotProd); + } + } + `}}class fL{constructor(e){this.variableNames=["dy"],this.uniforms=`strides : vec3, pads : vec3, filterDims : vec3, + outDepth : i32, outHeight : i32, outWidth : i32, avgMultiplier : f32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.inShape,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="avgPool3DBackprop"}getUserCode(){return` + ${re("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let batch = coords.x; + let ch = coords.u; + + let dyCorner = vec3(coords.y, coords.z, coords.w) - uniforms.pads; + let dyDCorner = dyCorner.x; + let dyRCorner = dyCorner.y; + let 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. + var dotProd = 0.0; + for (var wD = 0; wD < uniforms.filterDims[0]; wD++) { + let dyD = f32(dyDCorner + wD) / f32(uniforms.strides[0]); + + if (dyD < 0.0 || dyD >= f32(uniforms.outDepth) || fract(dyD) > 0.0) { + continue; + } + let idyD = i32(dyD); + + for (var wR = 0; wR < uniforms.filterDims[1]; wR++) { + let dyR = f32(dyRCorner + wR) / f32(uniforms.strides[1]); + + if (dyR < 0.0 || dyR >= f32(uniforms.outHeight) || fract(dyR) > 0.0) { + continue; + } + let idyR = i32(dyR); + + for (var wC = 0; wC < uniforms.filterDims[2]; wC++) { + let dyC = f32(dyCCorner + wC) / f32(uniforms.strides[2]); + + if (dyC < 0.0 || dyC >= f32(uniforms.outWidth) || fract(dyC) > 0.0) { + continue; + } + let idyC = i32(dyC); + + let dyValue = getDy(batch, idyD, idyR, idyC, ch); + dotProd += dyValue * uniforms.avgMultiplier; + } + } + } + setOutputAtIndex(index, dotProd); + } + } + `}}/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */function mL(n){const{inputs:e,backend:t,attrs:r}=n,{dy:s,input:a}=e,o=a,{filterSize:i,strides:l,pad:c,dimRoundingMode:u}=r,d=Pr(o.shape,i,l,1,c,u),p=new fL(d),f=1/(d.filterDepth*d.filterHeight*d.filterWidth),m=[{type:"int32",data:[d.strideDepth,d.strideHeight,d.strideWidth]},{type:"int32",data:[d.effectiveFilterDepth-1-d.padInfo.front,d.effectiveFilterHeight-1-d.padInfo.top,d.effectiveFilterWidth-1-d.padInfo.left]},{type:"int32",data:[d.effectiveFilterDepth,d.effectiveFilterHeight,d.effectiveFilterWidth]},{type:"int32",data:[d.outDepth]},{type:"int32",data:[d.outHeight]},{type:"int32",data:[d.outWidth]},{type:"float32",data:[f]}];return t.runWebGPUProgram(p,[s],o.dtype,m)}const gL={kernelName:nf,backendName:"webgpu",kernelFunc:mL};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */function yL(n){const{inputs:e,backend:t,attrs:r}=n,{dy:s,input:a}=e,o=a;sb([s,a],"avgPoolGrad");const{filterSize:i,strides:l,pad:c}=r,u=Nn(o.shape,i,l,1,c),d=new hL(u),p=1/(u.filterHeight*u.filterWidth),f=[{type:"int32",data:[u.strideHeight,u.strideWidth]},{type:"int32",data:[u.effectiveFilterHeight-1-u.padInfo.top,u.effectiveFilterWidth-1-u.padInfo.left]},{type:"int32",data:[u.dilationHeight,u.dilationWidth]},{type:"int32",data:[u.effectiveFilterHeight,u.effectiveFilterWidth]},{type:"int32",data:[u.outHeight]},{type:"int32",data:[u.outWidth]},{type:"float32",data:[p]}];return t.runWebGPUProgram(d,[s],o.dtype,f)}const bL={kernelName:tf,backendName:"webgpu",kernelFunc:yL};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function wL(n){const{inputs:e,backend:t,attrs:r}=n,{a:s,b:a}=e,{transposeA:o,transposeB:i}=r;return ku({a:s,b:a,transposeA:o,transposeB:i,backend:t})}const xL={kernelName:gi,backendName:"webgpu",kernelFunc:wL};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class vL{constructor(e,t){this.variableNames=["source"],this.workPerThread=1,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.rank=t.length,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize,[this.workPerThread,1,1]),this.start=e,this.uniforms=`start : ${ft(e.length)}, `,this.shaderKey="slice"}getUserCode(){const e=ft(this.rank),t=SL(this.rank);let r;return this.start.length===1?r=this.outputShape.map((a,o)=>"sourceLoc = uniforms.start + coords;"):r=this.outputShape.map((a,o)=>`sourceLoc.${Ll[o]} = uniforms.start.${tr(o)} + coords.${Ll[o]};`),` + ${re("index")} { + if (index < uniforms.size) { + var sourceLoc : ${e}; + let coords = getCoordsFromIndex(index); + ${r.join(` +`)} + setOutputAtIndex(index, getSource(${t})); + } + } + `}}const Ll=["x","y","z","w","u","v"];function SL(n){if(n===1)return"sourceLoc";if(n<=6)return Ll.slice(0,n).map(e=>`sourceLoc.${e}`).join(",");throw Error(`Slicing for rank ${n} is not yet supported`)}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function ba(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{begin:a,size:o}=r,[i,l]=eg(s,a,o);if(EC(s,i,l),t.shouldExecuteOnCPU([s])||s.dtype==="string"){const d=t.tensorMap.get(s.dataId),p=wM(d.values,i,l,s.shape,s.dtype);return t.makeTensorInfo(l,s.dtype,p)}if(q(l)===0)return t.makeTensorInfo(l,s.dtype,[]);const c=new vL(i,l),u=[{type:"int32",data:i}];return t.runWebGPUProgram(c,[s],s.dtype,u)}const IL={kernelName:ld,backendName:"webgpu",kernelFunc:ba};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const kL=n=>{const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{blockShape:a,crops:o}=r;$(s.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGPU backend not implemented yet");const i=a.reduce((I,S)=>I*S),l=bu(s.shape,a,i),c=wu(l.length,a.length),u=xu(s.shape,a,i),d=sg(o,a.length),p=ag(u,o,a.length),f=[],m=de({inputs:{x:s},backend:t,attrs:{shape:l}}),g=Vn({inputs:{x:m},backend:t,attrs:{perm:c}}),b=de({inputs:{x:g},backend:t,attrs:{shape:u}}),v=ba({inputs:{x:b},backend:t,attrs:{begin:d,size:p}});return f.push(m),f.push(g),f.push(b),f.forEach(I=>t.disposeData(I.dataId)),v},_L={kernelName:sc,backendName:"webgpu",kernelFunc:kL};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */const CL=` + fn bincount_write(index: i32, value: f32) { + ${zr("&result[index]","value","float32")} + } +`,NL=` + fn bincount_write(index: i32, value: f32) { + atomicStore(&result[index], bitcast(value)); + } +`;class db{constructor(e,t,r=!1){this.outputShape=[],this.variableNames=["x"],this.uniforms="binCountSize : i32,",this.workgroupSize=[64,1,1],this.atomic=!0,this.hasWeights=!0,this.binaryOutput=!1,this.outputShape=e,this.rank=e.length,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.binaryOutput=r,r&&(this.atomic=!1),this.hasWeights=t,this.hasWeights&&this.variableNames.push("w"),this.shaderKey=`bincount_${this.hasWeights}_${this.binaryOutput}_${this.rank}`}getUserCode(){return` + ${this.binaryOutput?NL:CL} + ${re("index")} { + ${this.rank===1?`if (index < uniforms.xShape) { + let indexVal = i32(getX(index)); + if (indexVal < uniforms.binCountSize) { + let value = ${this.binaryOutput?1:this.hasWeights?"getW(index)":"1."}; + bincount_write(indexVal, value); + } + }`:`let coord = getCoordsFromIndex(index); + if (coordsInBounds2D(coord, uniforms.xShape)) { + let indexVal = i32(getX(coord[0], coord[1])); + if (indexVal < uniforms.binCountSize) { + let value = ${this.binaryOutput?1:this.hasWeights?"getW(coord[0], coord[1])":"1."}; + bincount_write(coord.x * uniforms.binCountSize + indexVal, value); + } + }`} + } + `}}/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */function $L(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,weights:a}=e,{size:o}=r,i=q(s.shape),c=q(a.shape)>0,u=[o],d=a.dtype,p=Wt({backend:t,attrs:{shape:u,value:0,dtype:d}}),f=new db([i],c),m=[{type:"int32",data:[o]}],g=c?[s,a]:[s];return t.runWebGPUProgram(f,g,d,m,p)}const TL={kernelName:yi,backendName:"webgpu",kernelFunc:$L};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */class EL{constructor(e){this.outputShape=[],this.variableNames=["s0","s1"],this.uniforms="s0Size : i32, s1Size : i32, ",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=[e],this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="broadcastArgs"}getUserCode(){return` + ${re("index")} { + if (index < uniforms.size) { + var s0 = 1.0; + var s1 = 1.0; + let indexS0 = index - uniforms.size + uniforms.s0Size; + let indexS1 = index - uniforms.size + uniforms.s1Size; + if (indexS0 >= 0) { + s0 = getS0(indexS0); + } + if (indexS1 >= 0) { + s1 = getS1(indexS1); + } + + if (s0 == 1.0) { + setOutputAtIndex(index, s1); + } else if (s1 == 1.0) { + setOutputAtIndex(index, s0); + } else if (s0 != s1) { + setOutputAtIndex(index, uniforms.NAN); + } else { + setOutputAtIndex(index, s0); + } + } + } + `}}/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */function AL(n){const{inputs:e,backend:t}=n,{s0:r,s1:s}=e;if(t.shouldExecuteOnCPU([r,s])){const u=t.tensorMap.get(r.dataId),d=t.tensorMap.get(s.dataId),p=u.values,f=d.values,m=je(Array.from(p),Array.from(f));return t.makeTensorInfo([m.length],"int32",Int32Array.from(m))}const a=q(r.shape),o=q(s.shape),i=Math.max(a,o),l=new EL(i),c=[{type:"int32",data:[a]},{type:"int32",data:[o]}];return t.runWebGPUProgram(l,[r,s],"int32",c)}const RL={kernelName:ac,backendName:"webgpu",kernelFunc:AL};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const pb=xt({opType:ve.NOT_EQUAL,dtype:"bool",cpuKernelImpl:hM}),DL={kernelName:qc,backendName:"webgpu",kernelFunc:pb};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function fo(n){const{inputs:e,backend:t}=n,{input:r}=e,s=t.tensorMap.get(r.dataId);return Xt({inputs:{x:s.complexTensorInfos.real},backend:t})}const PL={kernelName:yf,backendName:"webgpu",kernelFunc:fo};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function FL(n,e){const t=new ya(n.shape,ne.TO_INT),r=e.runWebGPUProgram(t,[n],"int32");return{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function zl(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{dtype:a}=r;if(a==="complex64"){if(s.dtype==="complex64")return Xt({inputs:{x:s},backend:t});const o=$r(s.shape),i=zl({inputs:{x:s},backend:t,attrs:{dtype:"float32"}}),l=Cs({inputs:{real:i,imag:o},backend:t});return o.dispose(),t.disposeData(i.dataId),l}if(s.dtype==="complex64"){const o=fo({inputs:{input:s},backend:t}),i=zl({inputs:{x:o},backend:t,attrs:{dtype:a}});return t.disposeData(o.dataId),i}if(!Iw(s.dtype,a)){const o=Xt({inputs:{x:s},backend:t});return{dataId:o.dataId,shape:o.shape,dtype:a}}if(t.shouldExecuteOnCPU([s])){const o=t.tensorMap.get(s.dataId).values,[i,l,c]=qO(o,s.shape,s.dtype,a);return t.makeTensorInfo(i,l,c)}if(a==="int32")return FL(s,t);if(a==="bool"){const o=t.makeTensorInfo([],"bool",kr("bool",1)),l=pb({inputs:{a:s,b:o},backend:t});return t.disposeData(o.dataId),l}throw new Error(`Error in Cast: failed to cast ${s.dtype} to ${a}`)}const OL={kernelName:bi,backendName:"webgpu",kernelFunc:zl};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const ML=We({opType:ne.CEIL,cpuKernelImpl:KO}),LL={kernelName:oc,backendName:"webgpu",kernelFunc:ML};/** + * @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. + * ============================================================================= + */class zL{constructor(e){this.variableNames=["A"],this.uniforms="minVal : f32, maxVal : f32,",this.workPerThread=4,this.workgroupSize=[64,1,1],this.outputComponent=4,this.size=!0,this.outputShape=e,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize,[this.workPerThread,1,1]),this.shaderKey="clipVec4"}getUserCode(){return` + ${re("index")} { + if(index < uniforms.size) { + let value = getAByOutputIndex(index); + var clampedValue = clamp( + value, vec4(uniforms.minVal), vec4(uniforms.maxVal)); + clampedValue = select(clampedValue, value, isnanVec4(value)); + setOutputAtIndex(index, clampedValue); + } + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class BL{constructor(e){this.variableNames=["A"],this.uniforms="minVal : f32, maxVal : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="clip"}getUserCode(){return` + ${re("index")} { + if(index < uniforms.size) { + let value = getAByOutputIndex(index); + if (isnan(value)) { + setOutputAtIndex(index, value); + return; + } + setOutputAtIndex(index, clamp(value, uniforms.minVal, uniforms.maxVal)); + } + } + `}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function WL(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{clipValueMin:a,clipValueMax:o}=r;let i;const l=[{type:"float32",data:[a]},{type:"float32",data:[o]}];return q(s.shape)%4===0?i=new zL(s.shape):i=new BL(s.shape),t.runWebGPUProgram(i,[s],s.dtype,l)}const VL={kernelName:wi,backendName:"webgpu",kernelFunc:WL};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */class UL{constructor(e){this.outputShape=[],this.variableNames=["real","imag"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="complexAbs"}getUserCode(){return` + ${re("index")} { + if (index < uniforms.size) { + let re = abs(getRealByOutputIndex(index)); + let im = abs(getImagByOutputIndex(index)); + let mx = max(re, im); + + // The length function in wgsl may be not underflow-safe on some GPUs. + // So the safe solution is to ensure underflow-safety in all cases. + setOutputAtIndex(index, select(mx * length(vec2(1, min(re, im)/mx)), 0.0, mx == 0.0)); + } + } + `}}/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */function ch(n,e){return{dataId:e.dataId,dtype:e.dtype,shape:n.shape}}function HL(n){const{inputs:e,backend:t}=n,{x:r}=e,s=t.tensorMap.get(r.dataId),a=new UL(r.shape),o=[ch(r,s.complexTensorInfos.real),ch(r,s.complexTensorInfos.imag)];return t.runWebGPUProgram(a,o,o[0].dtype)}const GL={kernelName:af,backendName:"webgpu",kernelFunc:HL};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class jL{constructor(e){this.uniforms="",this.workPerThread=1,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=Ir(e,1),this.variableNames=e.map((t,r)=>`T${r}`),this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize,[this.workPerThread,1,1]),this.offsetLength=e.length-1;for(let t=0;t0){e.push("if (yC < uniforms.offset0){ setOutputAtCoords(coords.x, coords.y, getT0(yR, yC)); }");for(let a=1;afo({inputs:{input:S},backend:t})),g=n.map(S=>_u({inputs:{input:S},backend:t})),b=Va(m,e,t),v=Va(g,e,t),I=Cs({inputs:{real:b,imag:v},backend:t});return m.forEach(S=>t.disposeData(S.dataId)),g.forEach(S=>t.disposeData(S.dataId)),t.disposeData(b.dataId),t.disposeData(v.dataId),I}let s=t.shouldExecuteOnCPU(n);if(r==="string"&&(s=!0),s){const m=n.map(T=>{const L=[-1,q(T.shape.slice(e))];return de({inputs:{x:T},backend:t,attrs:{shape:L}})}),g=m.map(T=>({vals:t.readSync(T.dataId),shape:T.shape})),b=Ir(m.map(T=>T.shape),1),v=m[0].shape[0]===1,I=XO(g,b,r,v),S=Ir(n.map(T=>T.shape),e),C=t.makeTensorInfo(S,r,I);return m.forEach(T=>t.disposeData(T.dataId)),C}const a=t.device.limits.maxStorageBuffersPerShaderStage-1;if(n.length>a){const m=[];for(let b=0;bm.shape),c=new jL(l),u=[],d=new Array(l.length-1);if(d.length>0){d[0]=l[0][1],u.push({type:"int32",data:[d[0]]});for(let m=1;mt.disposeData(m.dataId));const f=de({inputs:{x:p},backend:t,attrs:{shape:i}});return t.disposeData(p.dataId),f}function KL(n,e,t){const r=Ir(n.map(a=>a.shape),e);return{tensors2D:n.map(a=>de({inputs:{x:a},backend:t,attrs:{shape:[q(a.shape.slice(0,e)),q(a.shape.slice(e))]}})),outShape:r}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function hb(n){const{inputs:e,backend:t,attrs:r}=n,{axis:s}=r,a=$t(s,e[0].shape)[0],o=e.map(c=>c.shape);ng(o,a);const i=Ir(e.map(c=>c.shape),a);if(q(i)===0)return t.makeTensorInfo(i,e[0].dtype,[]);const l=e.filter(c=>q(c.shape)>0);return l.length===1?Xt({inputs:{x:l[0]},backend:t}):Va(l,a,t)}const XL={kernelName:ic,backendName:"webgpu",kernelFunc:hb};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function YL(n,e,t,r,s=!1,a=null,o=!1,i=4,l=4,c=4){const u=A=>{switch(A){case 1:return"resData = f32(x[xIndex]);";case 3:return"resData = vec3(x[xIndex], x[xIndex + 1], x[xIndex + 2]);";case 4:return"resData = vec4(x[xIndex / 4]);";default:throw new Error(`innerElementSize ${A} is not supported.`)}},d=A=>{switch(A){case 1:return"return f32(W[row * uniforms.wShape[3] + col]);";case 4:return"return vec4(W[(row * uniforms.wShape[3] + col) / 4]);";default:throw new Error(`innerElementSize ${A} is not supported.`)}},p=n?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,f=n?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,m=n?"uniforms.xShape[1]":"uniforms.xShape[2]",g=n?"uniforms.xShape[2]":"uniforms.xShape[3]",b=n?"row":"col",v=n?"col":"row",I=` + let inChannels = uniforms.wShape[2]; + let outWidth = ${n?"uniforms.outShape[2]":"uniforms.outShape[3]"}; + let outRow = ${b} / outWidth; + let outCol = ${b} % outWidth; + + let WRow = ${v} / (uniforms.filterDims[1] * inChannels); + let WCol = ${v} / inChannels % uniforms.filterDims[1]; + let xRow = outRow * uniforms.strides[0] + uniforms.dilations[0] * WRow - uniforms.pads[0]; + let xCol = outCol * uniforms.strides[1] + uniforms.dilations[1] * WCol - uniforms.pads[1]; + let xCh = ${v} % inChannels; + var resData = ${Ee(i)}(0.0); + // The bounds checking is always needed since we use it to pad zero for + // the 'same' padding type. + if (xRow >= 0 && xRow < ${m} && xCol >= 0 && xCol < ${g}) { + ${p} + let xIndex = getIndexFromCoords4D(coord, uniforms.xShape); + ${u(i)} + } + return resData;`,S=n?e&&r?` + ${I}`:` + if (row < uniforms.dimAOuter && col < uniforms.dimInner) { + ${I} + } + return ${Ee(i)}(0.0);`:r&&t?` + ${I}`:` + if (row < uniforms.dimInner && col < uniforms.dimBOuter) { + ${I} + } + return ${Ee(i)}(0.0);`,C=`${d(l)}`,T=Ee(c),O=Ee(n?i:l),L=Ee(n?l:i);return` + ${ir(a,o,c===4,4)} + fn mm_readA(batch: i32, row : i32, col : i32) -> ${O} { + ${n?S:C} + } + + fn mm_readB(batch: i32, row : i32, col : i32) -> ${L} { + ${n?C:S} + } + + fn mm_write(batch: i32, row : i32, col : i32, valueIn : ${T}) { + if (row < uniforms.dimAOuter && col < uniforms.dimBOuter) + { + var value = valueIn; + let outWidth = ${n?"uniforms.outShape[2]":"uniforms.outShape[3]"}; + ${f} + ${_s(s,a)} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`}class QL{constructor(e,t,r,s,a=!1,o=null,i=!1,l=!1){this.variableNames=["x","W"],this.uniforms="filterDims : vec2, pads : vec2, strides : vec2, dilations : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.outputShape=e.outShape,this.isChannelsLast=e.dataFormat==="channelsLast",this.isVec4=((e.inChannels%4===0||e.inChannels%3===0)&&this.isChannelsLast||e.outWidth%4===0&&!this.isChannelsLast)&&e.outChannels%4===0,this.dispatchLayout=this.isChannelsLast?{x:[3],y:[1,2],z:[0]}:{x:[2,3],y:[1],z:[0]},this.workgroupSize=tb(this.dispatchLayout,this.outputShape,this.isVec4),this.elementsPerThread=nb(this.dispatchLayout,this.outputShape,this.isVec4),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize,this.elementsPerThread),this.isVec4?(this.outputComponent=4,this.isChannelsLast&&e.inChannels%4!==0?(this.innerElementSize=3,this.variableComponents=[1,4]):(this.innerElementSize=4,this.variableComponents=[4,4]),a&&(this.variableNames.push("bias"),this.variableComponents.push(4)),i&&(this.variableNames.push("preluActivationWeights"),this.variableComponents.push(4))):(this.innerElementSize=this.elementsPerThread[0],a&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights")),this.sequentialAccessByThreads=l,this.addBias=a,this.activation=o,this.hasPreluActivationWeights=i,this.tileAOuter=this.workgroupSize[1]*this.elementsPerThread[1],this.tileBOuter=this.workgroupSize[0]*this.elementsPerThread[0],this.tileInner=Math.max(this.workgroupSize[0]*this.innerElementSize,this.workgroupSize[1]),this.fitAOuter=t%this.tileAOuter===0,this.fitBOuter=r%this.tileBOuter===0,this.fitInner=s%this.tileInner===0,this.shaderKey=`conv2DMM_${this.elementsPerThread}_${this.activation}}_${this.fitAOuter}_${this.fitBOuter}_${this.fitInner}_${this.isVec4}_${this.innerElementSize}_${this.isChannelsLast}_${this.sequentialAccessByThreads}`}getUserCode(){const e=this.isVec4?Su(this.elementsPerThread,this.workgroupSize,!this.isChannelsLast,this.tileInner):Iu(this.elementsPerThread,this.workgroupSize,!this.isChannelsLast,this.tileInner,!1,null,this.sequentialAccessByThreads),t=this.isVec4?[this.innerElementSize,4,4]:[1,1,1];return` + ${YL(this.isChannelsLast,this.fitAOuter,this.fitBOuter,this.fitInner,this.addBias,this.activation,this.hasPreluActivationWeights,t[0],t[1],t[2])} + ${e} + `}}/** + * @license + * Copyright 2022 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. + * ============================================================================= + */class ZL{constructor(e,t=!1,r=null,s=!1){this.variableNames=["x","W"],this.uniforms="filterDims: vec2, pads: vec2, strides: vec2, dilations: vec2,",this.workgroupSize=[4,4,8],this.outputShape=e.outShape,this.isChannelsLast=e.dataFormat==="channelsLast",this.dispatchLayout=this.isChannelsLast?{x:[2],y:[1],z:[0,3]}:{x:[3],y:[2],z:[0,1]},this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.addBias=t,this.activation=r,this.hasPreluActivationWeights=s,t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.shaderKey=`conv2dnaive_${this.activation}_${this.isChannelsLast}`}getUserCode(){return` + ${ir(this.activation,this.hasPreluActivationWeights,!1,4)} + fn readInp(batch : i32, row : i32, col : i32, chan : i32) -> f32{ + let coords = vec4(batch, row, col, chan); + if (coordsInBounds4D(coords, uniforms.xShape)) { + return getX(batch, row, col, chan); + } else { + return 0.0; + } + } + fn readFilt(row : i32, col : i32, xChannel : i32, outChannel : i32) -> f32{ + let coords = vec4(row, col, xChannel, outChannel); + if(coordsInBounds4D(coords, uniforms.wShape)) { + return getW(row, col, xChannel, outChannel); + } else { + return 0.0; + } + } + fn writeResult(batch : i32, row : i32, col : i32, chan : i32, valueIn : f32) { + let coords = ${this.isChannelsLast?"vec4(batch, row, col, chan);":"vec4(batch, chan, row, col);"} + if (coordsInBounds4D(coords, uniforms.outShape)) { + var value = valueIn; + ${_s(this.addBias,this.activation)} + setOutputAtCoords(coords.x, coords.y, coords.z, coords.w, value); + } + } + ${re("index")} { + let coords = getOutputCoords(); + let batch = coords[0]; + let outChannel = ${this.isChannelsLast?"coords[3];":"coords[1];"} + let outRow = ${this.isChannelsLast?"coords[1];":"coords[2];"} + let outCol = ${this.isChannelsLast?"coords[2];":"coords[3];"} + var acc : f32 = 0.0; + for (var row = 0; row < uniforms.filterDims[0]; row = row + 1) { + for (var col = 0; col < uniforms.filterDims[1]; col = col + 1) { + let xRow = outRow * uniforms.strides[0] + uniforms.dilations[0] * row - uniforms.pads[0]; + let xCol = outCol * uniforms.strides[1] + uniforms.dilations[1] * col - uniforms.pads[1]; + for (var xChannel = 0; xChannel < ${this.isChannelsLast?"uniforms.xShape[3];":"uniforms.xShape[1];"} xChannel = xChannel + 1) { + ${this.isChannelsLast?"let v = readInp(batch, xRow, xCol, xChannel);":"let v = readInp(batch, xChannel, xRow, xCol);"} + let f = readFilt(row, col, xChannel, outChannel); + acc = acc + v * f; + } + } + } + writeResult(batch, outRow, outCol, outChannel, acc); + } + `}}/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */class JL{constructor(e,t){this.variableNames=["x"],this.uniforms=`pads : vec2, strides : vec2, dilations : vec2, outWidth : i32, itemsPerBlockRow : i32, + inChannels : i32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.isChannelsLast=t,this.shaderKey=`im2col_${this.isChannelsLast}`}getUserCode(){const e=this.isChannelsLast?1:2,t=this.isChannelsLast?2:3,r=this.isChannelsLast?"coords[1]":"coords[2]",s=this.isChannelsLast?"coords[2]":"coords[1]",a=this.isChannelsLast?"getX(batch, xRow, xCol, ch)":"getX(batch, ch, xRow, xCol)";return` + ${re("index")} { + let coords = getCoordsFromIndex(index); + if(index < uniforms.size) { + let batch = coords[0]; + let row = ${r}; + let col = ${s}; + let offsetY = (row / uniforms.outWidth) * uniforms.strides[0] - uniforms.pads[0]; + let xRow = offsetY + uniforms.dilations[0] * (col / uniforms.itemsPerBlockRow); + var value = 0.0; + if(xRow < uniforms.xShape[${e}] && xRow >= 0) { + let offsetX = (row % uniforms.outWidth) * uniforms.strides[1] - + uniforms.pads[1]; + let xCol = offsetX + uniforms.dilations[1] * ((col % + uniforms.itemsPerBlockRow) / uniforms.inChannels); + let ch = col % uniforms.inChannels; + if(xCol < uniforms.xShape[${t}] && xCol >= 0) { + value = ${a}; + } + } + setOutputAtIndex(index, value); + } + } + `}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function ii(n,e){const t=n.length;return t>=3?e?[...n.slice(0,-3),n[t-3]*n[t-2],n[t-1]]:[...n.slice(0,-3),n[t-3],n[t-2]*n[t-1]]:!e&&t===1&&n[0]>1?[n[0],1]:null}function ez({x:n,filter:e,convInfo:t,backend:r,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){const l=t.dataFormat==="channelsLast",c=!l,u=!1,d=l&&t.filterHeight===t.inHeight&&t.filterWidth===t.inWidth&&t.padInfo.type==="VALID",p=[];let f,m;if(d){const v=t.inHeight*t.inWidth*t.inChannels;f=de({inputs:{x:n},backend:r,attrs:{shape:[1,t.batchSize,v]}}),m=de({inputs:{x:e},backend:r,attrs:{shape:[1,v,t.outChannels]}})}else f=de({inputs:{x:n},backend:r,attrs:{shape:l?[t.batchSize,t.inHeight*t.inWidth,t.inChannels]:[t.batchSize,t.inChannels,t.inHeight*t.inWidth]}}),m=de({inputs:{x:e},backend:r,attrs:{shape:[1,t.inChannels,t.outChannels]}});if(p.push(f),p.push(m),a!=null){const v=ii(a.shape,l);v!=null&&(a=de({inputs:{x:a},backend:r,attrs:{shape:v}}),p.push(a))}if(s!=null){const v=ii(s.shape,l);v!=null&&(s=de({inputs:{x:s},backend:r,attrs:{shape:v}}),p.push(s))}const g=ku({a:l?f:m,b:l?m:f,transposeA:c,transposeB:u,backend:r,bias:s,activation:i,preluActivationWeights:a,leakyreluAlpha:o}),b=de({inputs:{x:g},backend:r,attrs:{shape:t.outShape}});p.push(g);for(const v of p)r.disposeData(v.dataId);return b}function tz({x:n,filter:e,convInfo:t,backend:r,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){const{filterWidth:l,filterHeight:c,inChannels:u,strideWidth:d,strideHeight:p,padInfo:f,outWidth:m,outHeight:g,dilationWidth:b,dilationHeight:v,dataFormat:I}=t,S=I==="channelsLast",C=l*c*u,T=g*m,O=S?[t.batchSize,T,C]:[t.batchSize,C,T],L=new JL(O,S),B=[{type:"int32",data:[f.top,f.left]},{type:"int32",data:[p,d]},{type:"int32",data:[v,b]},{type:"int32",data:[m]},{type:"int32",data:[u*l]},{type:"int32",data:[u]}],A=r.runWebGPUProgram(L,[n],n.dtype,B),D=[];D.push(A);const _=de({inputs:{x:e},backend:r,attrs:{shape:[1,C,-1]}});if(D.push(_),a!=null){const ee=ii(a.shape,S);ee!=null&&(a=de({inputs:{x:a},backend:r,attrs:{shape:ee}}),D.push(a))}if(s!=null){const ee=ii(s.shape,S);ee!=null&&(s=de({inputs:{x:s},backend:r,attrs:{shape:ee}}),D.push(s))}const Y=ku({a:S?A:_,b:S?_:A,transposeA:!S,transposeB:!1,backend:r,bias:s,activation:i,preluActivationWeights:a,leakyreluAlpha:o}),X=de({inputs:{x:Y},backend:r,attrs:{shape:t.outShape}});D.push(Y);for(const ee of D)r.disposeData(ee.dataId);return X}function fb({x:n,filter:e,convInfo:t,backend:r,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){const l=s!=null,c=a!=null,u=t.dataFormat==="channelsLast",d=u&&t.filterHeight===t.inHeight&&t.filterWidth===t.inWidth&&t.padInfo.type==="VALID",p=fe().getBool("WEBGPU_USE_NAIVE_CONV2D_DEBUG");if(!p&&(d||t.filterHeight===1&&t.filterWidth===1&&t.dilationHeight===1&&t.dilationWidth===1&&t.strideHeight===1&&t.strideWidth===1&&(t.padInfo.type==="SAME"||t.padInfo.type==="VALID")))return ez({x:n,filter:e,convInfo:t,backend:r,bias:s,activation:i,preluActivationWeights:a,leakyreluAlpha:o});const f=fe().getNumber("WEBGPU_THRESHOLD_TO_INCREASE_WORKGROUPS_FOR_MATMUL"),m=f>-1?f:r.thresholdToIncreaseWorkgroups,g=t.batchSize*Math.ceil(t.outHeight*t.outWidth/32)*Math.ceil(t.outChannels/32);if(fe().getBool("WEBGPU_CONV_SEPARATE_IM2COL_SHADER")||g<=m)return tz({x:n,filter:e,convInfo:t,backend:r,bias:s,preluActivationWeights:a,leakyreluAlpha:o,activation:i});let b;const v=[t.padInfo.top,t.padInfo.left],I=[{type:"int32",data:[t.filterHeight,t.filterWidth]},{type:"int32",data:[...v]},{type:"int32",data:[t.strideHeight,t.strideWidth]},{type:"int32",data:[t.dilationHeight,t.dilationWidth]}];if(p)b=new ZL(t,l,i,c);else{const O=u?t.outHeight*t.outWidth:t.outChannels,L=u?t.outChannels:t.outHeight*t.outWidth,B=t.filterHeight*t.filterWidth*t.inChannels;I.push({type:"int32",data:[O]},{type:"int32",data:[L]},{type:"int32",data:[B]});const A=r.adapterInfo.isIntel();b=new QL(t,O,L,B,l,i,c,A)}const S=[],C=[n,e];l&&(!u&&s.shape.length===1&&(s=de({inputs:{x:s},backend:r,attrs:{shape:[s.shape[0],1,1]}}),S.push(s)),C.push(s)),c&&(!u&&a.shape.length===1&&(a=de({inputs:{x:a},backend:r,attrs:{shape:[a.shape[0],1,1]}}),S.push(a)),C.push(a)),i==="leakyrelu"&&(I.push({type:"float32",data:[o]}),b.uniforms+=" alpha : f32,");const T=r.runWebGPUProgram(b,C,n.dtype,I);for(const O of S)r.disposeData(O.dataId);return T}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function nz(n){const{inputs:e,attrs:t,backend:r}=n,{x:s,filter:a}=e,{strides:o,pad:i,dataFormat:l,dilations:c,dimRoundingMode:u}=t,d=Fr(l),p=Tt(s.shape,a.shape,o,c,i,u,!1,d);return fb({x:s,filter:a,convInfo:p,backend:r})}const rz={kernelName:xi,backendName:"webgpu",kernelFunc:nz};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */class sz{constructor(e){this.variableNames=["dy","W"],this.uniforms="filterDims : vec2, pads : vec2, strides : vec2, outBackprop : vec4,",this.workgroupSize=[64,1,1],this.size=!1,this.isVec4=!1,this.workPerThread=1,this.outputShape=e.inShape,this.isChannelsLast=e.dataFormat==="channelsLast",this.isVec4=this.isChannelsLast&&e.outChannels%4===0&&e.inChannels%4===0,this.isVec4?(this.workPerThread=2,this.outputComponent=4,this.workgroupSize=[4,4,4],this.dispatchLayout={x:[3],y:[2],z:[0,1]},this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize,[4,this.workPerThread,1])):(this.size=!0,this.workPerThread=1,this.workgroupSize=[64,1,1],this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize)),this.shaderKey=`conv2DDerInput_${this.isChannelsLast}_${this.isVec4}_${this.workPerThread}`}getUserCode(){const e=this.isChannelsLast?1:2,t=this.isChannelsLast?2:3,r=this.isChannelsLast?3:1,s=` + ${re()} { + let batch = i32(globalId.z) / uniforms.outShape[1]; + let r = i32(globalId.z) % uniforms.outShape[1]; + let c = i32(globalId.y) * ${this.workPerThread}; + let d1 = i32(globalId.x) * 4; + + let dyCorner = vec2(r, c) - uniforms.pads; + + // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). + // ? = to be determined. : = across all values in that axis. + var dotProd: array, ${this.workPerThread}>; + for (var i = 0; i < ${this.workPerThread}; i++) { + dotProd[i] = vec4(0.0); + } + for (var wR = 0; wR < uniforms.filterDims.x; wR = wR + 1) { + let dyR = f32(dyCorner.x + wR) / f32(uniforms.strides.x); + let wRPerm = uniforms.filterDims.x - 1 - wR; + if (dyR < 0.0 || dyR >= f32(uniforms.outBackprop[1]) || + fract(dyR) > 0.0) { + continue; + } + let idyR = i32(dyR); + + for (var wC = 0; wC < uniforms.filterDims.y; wC = wC + 1) { + let dyC = f32(dyCorner.y + wC) / f32(uniforms.strides.y); + let dyC2 = f32(dyCorner.y + 1 + wC) / f32(uniforms.strides.y); + let wCPerm = uniforms.filterDims.y - 1 - wC; + var bDyCVal = true; + var bDyCVal2 = true; + if (dyC < 0.0 || dyC >= f32(uniforms.outBackprop[2]) || + fract(dyC) > 0.0) { + bDyCVal = false; + } + if (dyC2 < 0.0 || dyC2 >= f32(uniforms.outBackprop[2]) || + fract(dyC2) > 0.0) { + bDyCVal2 = false; + } + + let idyC = i32(dyC); + let idyC2 = i32(dyC2); + if (bDyCVal && bDyCVal2) { + let d2Length = uniforms.outBackprop[3]; + for (var d2 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = getW(wRPerm, wCPerm, d1, d2); + let wValue1 = getW(wRPerm, wCPerm, d1 + 1, d2); + let wValue2 = getW(wRPerm, wCPerm, d1 + 2, d2); + let wValue3 = getW(wRPerm, wCPerm, d1 + 3, d2); + var xValue = getDy(batch, idyR, idyC, d2); + let tmpval = vec4(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[0] = dotProd[0] + tmpval; + xValue = getDy(batch, idyR, idyC2, d2); + dotProd[1] = dotProd[1] + vec4(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + } + } else if (bDyCVal) { + let d2Length = uniforms.outBackprop[3]; + for (var d2 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = getW(wRPerm, wCPerm, d1, d2); + let wValue1 = getW(wRPerm, wCPerm, d1 + 1, d2); + let wValue2 = getW(wRPerm, wCPerm, d1 + 2, d2); + let wValue3 = getW(wRPerm, wCPerm, d1 + 3, d2); + var xValue = getDy(batch, idyR, idyC, d2); + let tmpval = vec4(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[0] = dotProd[0] + tmpval; + } + } else if (bDyCVal2) { + let d2Length = uniforms.outBackprop[3]; + for (var d2 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = getW(wRPerm, wCPerm, d1, d2); + let wValue1 = getW(wRPerm, wCPerm, d1 + 1, d2); + let wValue2 = getW(wRPerm, wCPerm, d1 + 2, d2); + let wValue3 = getW(wRPerm, wCPerm, d1 + 3, d2); + var xValue = getDy(batch, idyR, idyC2, d2); + let tmpval = vec4(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[1] = dotProd[1] + tmpval; + } + } + } + } + + for (var i = 0; i < ${this.workPerThread}; i = i + 1) { + let coords = vec4(batch, r, c + i, d1); + if (coordsInBounds4D(coords, uniforms.outShape)) { + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], dotProd[i]); + } + } + } + `;return this.isVec4?` + ${s} + `:` + ${re("index")} { + if(index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let batch = coords[0]; + let d1 = coords[${r}]; + + let dyCorner = vec2(coords[${e}], coords[${t}]) - uniforms.pads; + let dyRCorner = dyCorner.x; + let 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. + var dotProd = 0.0; + for (var wR = 0; wR < uniforms.filterDims.x; wR = wR + 1) { + let dyR = (f32(dyRCorner) + f32(wR)) / f32(uniforms.strides.x); + let wRPerm = uniforms.filterDims.x - 1 - wR; + if (dyR < 0.0 || dyR >= f32(uniforms.outBackprop[1]) || fract(dyR) > 0.0 || + wRPerm < 0) { + continue; + } + let idyR = i32(dyR); + + for (var wC = 0; wC < uniforms.filterDims.y; wC = wC + 1) { + let dyC = (f32(dyCCorner) + f32(wC)) / f32(uniforms.strides.y); + let wCPerm = uniforms.filterDims.y - 1 - wC; + if (dyC < 0.0 || dyC >= f32(uniforms.outBackprop[2]) || + fract(dyC) > 0.0 || wCPerm < 0) { + continue; + } + let idyC = i32(dyC); + + for (var d2 = 0; d2 < uniforms.outBackprop[3]; d2 = d2 + 1) { + let xValue = ${this.isChannelsLast?"getDy(batch, idyR, idyC, d2)":"getDy(batch, d2, idyR, idyC)"}; + let wValue = getW(wRPerm, wCPerm, d1, d2); + dotProd = dotProd + xValue * wValue; + } + } + } + setOutputAtIndex(index, dotProd); + } + } + `}}class az{constructor(e){this.variableNames=["x","dy"],this.uniforms="pads : vec2, strides : vec2, batchSize : i32, outHeight : i32, outWidth : i32, inHeight : i32, inWidth : i32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.filterShape,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.isChannelsLast=e.dataFormat==="channelsLast",this.shaderKey=`conv2DDerFilter_${this.isChannelsLast}`}getUserCode(){return` + ${re("index")} { + if(index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let wR = coords[0]; + let wC = coords[1]; + let d1 = coords[2]; + let d2 = coords[3]; + + // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2). + // ? = to be determined. : = across all values in that axis. + var dotProd = 0.0; + for (var b = 0; b < uniforms.batchSize; b = b + 1) { + for (var yR = 0; yR < uniforms.outHeight; yR = yR + 1) { + let xR = wR + yR * uniforms.strides[0] - uniforms.pads[0]; + if (xR < 0 || xR >= uniforms.inHeight) { + continue; + } + + for (var yC = 0; yC < uniforms.outWidth; yC = yC + 1) { + let xC = wC + yC * uniforms.strides[1] - uniforms.pads[1]; + + if (xC < 0 || xC >= uniforms.inWidth) { + continue; + } + + if (${this.isChannelsLast}) { + let dyValue = getDy(b, yR, yC, d2); + let xValue = getX(b, xR, xC, d1); + dotProd = dotProd + xValue * dyValue; + } else { + let dyValue = getDy(b, d2, yR, yC); + let xValue = getX(b, d1, xR, xC); + dotProd = dotProd + xValue * dyValue; + } + } + } + } + setOutputAtIndex(index, dotProd); + } + } + `}}class oz{constructor(e){this.variableNames=["x","dy"],this.uniforms=`pads : vec3, strides : vec3, batchSize : i32, outDepth : i32, + outHeight : i32, outWidth : i32, inDepth : i32, inHeight : i32, inWidth : i32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.filterShape,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="conv3DDerFilter"}getUserCode(){return` + ${re("index")} { + if(index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let wF = coords.x; + let wR = coords.y; + let wC = coords.z; + let d1 = coords.w; + let d2 = coords.u; + + var dotProd = 0.0; + for (var b = 0; b < uniforms.batchSize; b++) { + for (var yF = 0; yF < uniforms.outDepth; yF++) { + let xF = wF + yF * uniforms.strides[0] - uniforms.pads[0]; + if (xF < 0 || xF >= uniforms.inDepth) { + continue; + } + + for (var yR = 0; yR < uniforms.outHeight; yR++) { + let xR = wR + yR * uniforms.strides[1] - uniforms.pads[1]; + if (xR < 0 || xR >= uniforms.inHeight) { + continue; + } + + for (var yC = 0; yC < uniforms.outWidth; yC++) { + let xC = wC + yC * uniforms.strides[2] - uniforms.pads[2]; + if (xC < 0 || xC >= uniforms.inWidth) { + continue; + } + + let dyValue = getDy(b, yF, yR, yC, d2); + let xValue = getX(b, xF, xR, xC, d1); + dotProd += xValue * dyValue; + } + } + } + } + setOutputAtIndex(index, dotProd); + } + } + `}}class iz{constructor(e){this.variableNames=["dy","W"],this.uniforms=`filterDims : vec3, pads : vec3, strides : vec3, + outDepth : i32, outHeight : i32, outWidth : i32, outChannels : i32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.inShape,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="conv3DDerInput"}getUserCode(){return` + ${re("index")} { + if(index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let batch = coords.x; + let d1 = coords.u; + + let dyCorner = vec3(coords.y, coords.z, coords.w) - uniforms.pads; + let dyFCorner = dyCorner.x; + let dyRCorner = dyCorner.y; + let dyCCorner = dyCorner.z; + + var dotProd = 0.0; + for (var wF = 0; wF < uniforms.filterDims[0]; wF++) { + let dyF = f32(dyFCorner + wF) / f32(uniforms.strides[0]); + if (dyF < 0.0 || dyF >= f32(uniforms.outDepth) || fract(dyF) > 0.0) { + continue; + } + let idyF = i32(dyF); + + let wFPerm = uniforms.filterDims[0] - 1 - wF; + + for (var wR = 0; wR < uniforms.filterDims[1]; wR++) { + let dyR = f32(dyRCorner + wR) / f32(uniforms.strides[1]); + + if (dyR < 0.0 || dyR >= f32(uniforms.outHeight) || fract(dyR) > 0.0) { + continue; + } + let idyR = i32(dyR); + + let wRPerm = uniforms.filterDims[1] - 1 - wR; + + for (var wC = 0; wC < uniforms.filterDims[2]; wC++) { + let dyC = f32(dyCCorner + wC) / f32(uniforms.strides[2]); + + if (dyC < 0.0 || dyC >= f32(uniforms.outWidth) || fract(dyC) > 0.0) { + continue; + } + let idyC = i32(dyC); + + let wCPerm = uniforms.filterDims[2] - 1 - wC; + + for (var d2 = 0; d2 < uniforms.outChannels; d2++) { + let xValue = getDy(batch, idyF, idyR, idyC, d2); + let wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2); + dotProd += xValue * wValue; + } + } + } + } + setOutputAtIndex(index, dotProd); + } + } + `}}/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */function uz(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,dy:a}=e,{strides:o,pad:i,dataFormat:l,dimRoundingMode:c,filterShape:u}=r,d=Fr(l),p=Tt(s.shape,u,o,1,i,c,!1,d),f=new az(p),m=[{type:"int32",data:[p.padInfo.top,p.padInfo.left]},{type:"int32",data:[p.strideHeight,p.strideWidth]},{type:"int32",data:[p.batchSize]},{type:"int32",data:[p.outHeight]},{type:"int32",data:[p.outWidth]},{type:"int32",data:[p.inHeight]},{type:"int32",data:[p.inWidth]}];return t.runWebGPUProgram(f,[s,a],s.dtype,m)}const lz={kernelName:of,backendName:"webgpu",kernelFunc:uz};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function cz(n=4){const e=a=>{switch(a){case 1:return"return W[getIndexFromCoords4D(coord, uniforms.wShape)];";case 4:return` + let coord1 = vec4(coordX, coordY, col + 1, rowInner); + let coord2 = vec4(coordX, coordY, col + 2, rowInner); + let coord3 = vec4(coordX, coordY, col + 3, rowInner); + let v0 = W[getIndexFromCoords4D(coord, uniforms.wShape)]; + let v1 = W[getIndexFromCoords4D(coord1, uniforms.wShape)]; + let v2 = W[getIndexFromCoords4D(coord2, uniforms.wShape)]; + let v3 = W[getIndexFromCoords4D(coord3, uniforms.wShape)]; + return vec4(v0, v1, v2, v3); + `;default:throw new Error(`innerElementSize ${a} is not supported.`)}},r=`if (row < uniforms.dimAOuter && col < uniforms.dimInner) { + ${` + let outRow = row / uniforms.outShape[2]; + let outCol = row % uniforms.outShape[2]; + + let WRow = col / (uniforms.filterDims[1] * uniforms.outBackprop[3]); + let WCol = col / uniforms.outBackprop[3] % uniforms.filterDims[1]; + let xR = f32(outRow - uniforms.pads[0] + WRow) / f32(uniforms.strides[0]); + let xC = f32(outCol - uniforms.pads[1] + WCol) / f32(uniforms.strides[1]); + if (xR < 0.0 || xR >= f32(uniforms.outBackprop[1]) || fract(xR) > 0.0) { + return ${Ee(n)}(0.0); + } + if (xC < 0.0 || xC >= f32(uniforms.outBackprop[2]) || fract(xC) > 0.0) { + return ${Ee(n)}(0.0); + } + let coord = vec4( + batch, + i32(xR), + i32(xC), + col % uniforms.outBackprop[3]); + return x[getIndexFromCoords4D(coord, uniforms.xShape)/${n}];`} + } + return ${Ee(n)}(0.0);`;return` + fn mm_readA(batch: i32, row : i32, col : i32) -> ${Ee(n)} { + ${r} + } + + fn mm_readB(batch: i32, row : i32, col : i32) -> ${Ee(n)} { + let coordX = uniforms.filterDims.x - 1 - + row / (uniforms.filterDims[1] * uniforms.outBackprop[3]); + let coordY = uniforms.filterDims.y - 1 - + (row / uniforms.outBackprop[3]) % uniforms.filterDims[1]; + if (row < uniforms.dimInner && col < uniforms.dimBOuter && + coordX >= 0 && coordY >= 0) { + let rowInner = row % uniforms.outBackprop[3]; + let coord = vec4(coordX, coordY, col, rowInner); + ${e(n)} + } + return ${Ee(n)}(0.0); + } + + fn mm_write(batch: i32, row : i32, col : i32, valueInput : ${Ee(n)}) { + if (row < uniforms.dimAOuter && col < uniforms.dimBOuter) { + var value = valueInput; + let outCoord = vec4( + batch, + row / uniforms.outShape[2], + row % uniforms.outShape[2], + col); + result[getIndexFromCoords4D(outCoord, uniforms.outShape)/${n}] = value; + } + }`}class dz{constructor(e){this.variableNames=["x","W"],this.uniforms="filterDims : vec2, pads : vec2, strides : vec2, outBackprop : vec4, dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.outputShape=e.inShape,$(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),this.isVec4=e.inChannels%4===0&&e.outChannels%4===0,this.dispatchLayout={x:[3],y:[1,2],z:[0]},this.workgroupSize=tb(this.dispatchLayout,this.outputShape,this.isVec4),this.elementsPerThread=nb(this.dispatchLayout,this.outputShape,this.isVec4),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize,this.elementsPerThread),this.isVec4&&(this.outputComponent=4,this.variableComponents=[4,1]),this.shaderKey=`conv2DDerInputMM_${this.isVec4}_${this.elementsPerThread}`}getUserCode(){const e=this.isVec4?Su(this.elementsPerThread,this.workgroupSize):Iu(this.elementsPerThread,this.workgroupSize);return` + ${cz(this.isVec4?4:1)} + ${e} + `}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function pz(n){const{inputs:e,backend:t,attrs:r}=n,{dy:s,filter:a}=e,{inputShape:o,strides:i,pad:l,dataFormat:c,dimRoundingMode:u}=r,d=Fr(c),p=Tt(o,a.shape,i,1,l,u,!1,d),f=[{type:"int32",data:[p.filterHeight,p.filterWidth]},{type:"int32",data:[p.filterHeight-1-p.padInfo.top,p.filterWidth-1-p.padInfo.left]},{type:"int32",data:[p.strideHeight,p.strideWidth]},{type:"int32",data:[p.batchSize,p.outHeight,p.outWidth,p.outChannels]}];let m;if(fe().getBool("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE")||p.dataFormat!=="channelsLast")m=new sz(p);else{m=new dz(p);const g=p.inHeight*p.inWidth,b=p.inChannels,v=p.filterHeight*p.filterWidth*p.outChannels;f.push({type:"uint32",data:[g]},{type:"uint32",data:[b]},{type:"uint32",data:[v]})}return t.runWebGPUProgram(m,[s,a],"float32",f)}const hz={kernelName:vi,backendName:"webgpu",kernelFunc:pz};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */class fz{constructor(e){this.variableNames=["x","W"],this.uniforms="filterDims: vec3, pads: vec3, strides: vec3, dilations: vec3,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.outShape,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="conv3dnaive"}getUserCode(){return` + ${re("index")} { + if (index < uniforms.size) { + let coords = getOutputCoords(); + let batch = coords.x; + let d2 = coords.u; + + let xFRCCorner = vec3(coords.y, coords.z, coords.w) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + + let inputDepthNearestVec4 = (uniforms.xShape.u / 4) * 4; + let inputDepthVec4Remainder = uniforms.xShape.u % 4; + + var dotProd = 0.0; + for (var wF = 0; wF < uniforms.filterDims[0]; wF++) { + let xF = xFCorner + wF * uniforms.dilations[0]; + if (xF < 0 || xF >= uniforms.xShape.y) { + continue; + } + + for (var wR = 0; wR < uniforms.filterDims[1]; wR++) { + let xR = xRCorner + wR * uniforms.dilations[1]; + if (xR < 0 || xR >= uniforms.xShape.z) { + continue; + } + + for (var wC = 0; wC < uniforms.filterDims[2]; wC++) { + let xC = xCCorner + wC * uniforms.dilations[2]; + if (xC < 0 || xC >= uniforms.xShape.w) { + continue; + } + + for (var d1 = 0; d1 < inputDepthNearestVec4; d1 += 4) { + let 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) + ); + let 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 (inputDepthVec4Remainder == 1) { + dotProd += getX(batch, xF, xR, xC, inputDepthNearestVec4) * + getW(wF, wR, wC, inputDepthNearestVec4, d2); + } else if (inputDepthVec4Remainder == 2) { + let xValues = vec2( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1) + ); + let wValues = vec2( + getW(wF, wR, wC, inputDepthNearestVec4, d2), + getW(wF, wR, wC, inputDepthNearestVec4 + 1, d2) + ); + dotProd += dot(xValues, wValues); + } else if (inputDepthVec4Remainder == 3) { + let xValues = vec3( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2) + ); + let wValues = vec3( + getW(wF, wR, wC, inputDepthNearestVec4, d2), + getW(wF, wR, wC, inputDepthNearestVec4 + 1, d2), + getW(wF, wR, wC, inputDepthNearestVec4 + 2, d2) + ); + dotProd += dot(xValues, wValues); + } + } + } + } + setOutputAtIndex(index, dotProd); + } + }`}}/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */function mz(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,filter:a}=e,{strides:o,pad:i,dilations:l}=r,c=Ss(s.shape,a.shape,o,l,i),u=[c.padInfo.front,c.padInfo.top,c.padInfo.left],d=[{type:"int32",data:[c.filterDepth,c.filterHeight,c.filterWidth]},{type:"int32",data:[...u]},{type:"int32",data:[c.strideDepth,c.strideHeight,c.strideWidth]},{type:"int32",data:[c.dilationDepth,c.dilationHeight,c.dilationWidth]}],p=new fz(c),f=_r(s.dtype,a.dtype);return t.runWebGPUProgram(p,[s,a],f,d)}const gz={kernelName:Si,backendName:"webgpu",kernelFunc:mz};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */function yz(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,dy:a}=e,{strides:o,pad:i,filterShape:l}=r,c=Ss(s.shape,l,o,1,i),u=new oz(c),d=[{type:"int32",data:[c.padInfo.front,c.padInfo.top,c.padInfo.left]},{type:"int32",data:[c.strideDepth,c.strideHeight,c.strideWidth]},{type:"int32",data:[c.batchSize]},{type:"int32",data:[c.outDepth]},{type:"int32",data:[c.outHeight]},{type:"int32",data:[c.outWidth]},{type:"int32",data:[c.inDepth]},{type:"int32",data:[c.inHeight]},{type:"int32",data:[c.inWidth]}];return t.runWebGPUProgram(u,[s,a],a.dtype,d)}const bz={kernelName:uc,backendName:"webgpu",kernelFunc:yz};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */function wz(n){const{inputs:e,backend:t,attrs:r}=n,{dy:s,filter:a}=e,{strides:o,pad:i,inputShape:l}=r,c=Ss(l,a.shape,o,1,i),u=new iz(c),d=[{type:"int32",data:[c.filterDepth,c.filterHeight,c.filterWidth]},{type:"int32",data:[c.filterDepth-1-c.padInfo.front,c.filterHeight-1-c.padInfo.top,c.filterWidth-1-c.padInfo.left]},{type:"int32",data:[c.strideDepth,c.strideHeight,c.strideWidth]},{type:"int32",data:[c.outDepth]},{type:"int32",data:[c.outHeight]},{type:"int32",data:[c.outWidth]},{type:"int32",data:[c.outChannels]}];return t.runWebGPUProgram(u,[s,a],s.dtype,d)}const xz={kernelName:Ii,backendName:"webgpu",kernelFunc:wz};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const vz=We({opType:ne.COS}),Sz={kernelName:lc,backendName:"webgpu",kernelFunc:vz};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const Iz=We({opType:ne.COSH}),kz={kernelName:cc,backendName:"webgpu",kernelFunc:Iz};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class _z{constructor(e,t,r,s){this.variableNames=["Image","Boxes","BoxInd"],this.uniforms="extrapolationValue : f32,",this.workgroupSize=[64,1,1],this.size=!0;const[a]=t;this.outputShape=[a,r[0],r[1],e],this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.methodId=s==="bilinear"?1:0,this.cropHeightBiggerThan1=this.outputShape[1]>1,this.cropWidthBiggerThan1=this.outputShape[2]>1,this.shaderKey=`cropAndResize_${this.methodId}_${this.cropHeightBiggerThan1}_${this.cropWidthBiggerThan1}`}getUserCode(){const[e,t]=["f32(uniforms.imageShape[1] - 1)","f32(uniforms.imageShape[2] - 1)"],[r,s,a]=this.cropHeightBiggerThan1?[`(${e} / f32(uniforms.outShape[1] - 1))`,"(y2-y1) * height_ratio",`y1*${e} + f32(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${e}`],[o,i,l]=this.cropWidthBiggerThan1?[`(${t} / f32(uniforms.outShape[2] - 1))`,"(x2-x1) * width_ratio",`x1*${t} + f32(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${t}`];return` + ${re("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let height_ratio = f32(${r}); + let width_ratio = f32(${o}); + let b = coords[0]; + let y = coords[1]; + let x = coords[2]; + let d = coords[3]; + // get box vals + let y1 = getBoxes(b, 0); + let x1 = getBoxes(b, 1); + let y2 = getBoxes(b, 2); + let x2 = getBoxes(b, 3); + // get image in batch index + let bInd = i32(round(getBoxInd(b))); + if(bInd < 0 || bInd >= uniforms.outShape[0]) { + return; + } + let height_scale = ${s}; + let width_scale = ${i}; + let in_y = ${a}; + if( in_y < 0.0 || in_y > ${e} ) { + setOutputAtIndex(index, uniforms.extrapolationValue); + return; + } + let in_x = ${l}; + if( in_x < 0.0 || in_x > ${t} ) { + setOutputAtIndex(index, uniforms.extrapolationValue); + return; + } + let sourceFracIndexCR = vec2(in_x,in_y); + if(${this.methodId} == 1) { + // Compute the four integer indices. + let sourceFloorCR = vec2(sourceFracIndexCR); + let sourceCeilCR = vec2(ceil(sourceFracIndexCR)); + let topLeft = getImage(bInd, sourceFloorCR.y, sourceFloorCR.x, d); + let bottomLeft = getImage(bInd, sourceCeilCR.y, sourceFloorCR.x, d); + let topRight = getImage(bInd, sourceFloorCR.y, sourceCeilCR.x, d); + let bottomRight = getImage(bInd, sourceCeilCR.y, sourceCeilCR.x, d); + let fracCR = sourceFracIndexCR - vec2(sourceFloorCR); + let top = topLeft + (topRight - topLeft) * fracCR.x; + let bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x; + let newValue = top + (bottom - top) * fracCR.y; + setOutputAtIndex(index, newValue); + } else { + // Compute the coordinators of nearest neighbor point. + let sourceNearestCR = vec2(floor( + sourceFracIndexCR + vec2(0.5,0.5))); + let newValue = getImage( + bInd, sourceNearestCR.y, sourceNearestCR.x, d); + setOutputAtIndex(index, newValue); + } + } + } + `}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const Cz=n=>{const{inputs:e,backend:t,attrs:r}=n,{image:s,boxes:a,boxInd:o}=e,{cropSize:i,method:l,extrapolationValue:c}=r,u=new _z(s.shape[3],a.shape,i,l),d=[{type:"float32",data:[c]}];return t.runWebGPUProgram(u,[s,a,o],"float32",d)},Nz={kernelName:Ci,backendName:"webgpu",kernelFunc:Cz};/** + * @license + * Copyright 2022 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 uo;(function(n){n.Prod="*",n.Sum="+"})(uo||(uo={}));class dh{constructor(e,t,r,s){this.variableNames=["x"],this.uniforms="index : f32,",this.size=!0,this.workgroupSize=[128,1,1],this.outputShape=t,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.exclusive=r,this.reverse=s,this.op=e,this.shaderKey=`cum_${this.op}_${this.exclusive}_${this.reverse}`}getUserCode(){const e=this.outputShape.length,t=this.op===uo.Prod?"1.0":"0.0",r=this.exclusive?t:`getX(${ph(e,"coords",this.op)})`,s=this.outputShape[this.outputShape.length-1];let a="",o="";return this.exclusive?(a=this.reverse?`end != ${s-1}`:"end != 0",o=this.reverse?"end + 1":"end - 1"):(a=this.reverse?`end + pow2 < ${s}`:"end >= pow2",o=this.reverse?"end + pow2":"end - pow2"),` + ${re("index")} { + if (index < uniforms.size) { + var coords = getCoordsFromIndex(index); + + let end = ${hh(e,"coords",this.op)}; + var val = ${r}; + let pow2 = i32(pow(2.0, uniforms.index)); + if (${a}) { + let idx = ${o}; + ${hh(e,"coords",this.op)} = idx; + val ${this.op}= getX(${ph(e,"coords",this.op)}); + } + setOutputAtIndex(index, val); + } + } + `}}function ph(n,e,t){if(n===1)return`${e}`;if(n===2)return`${e}.x, ${e}.y`;if(n===3)return`${e}.x, ${e}.y, ${e}.z`;if(n===4)return`${e}.x, ${e}.y, ${e}.z, ${e}.w`;throw Error(`Cumulative ${t} for rank ${n} is not yet supported`)}function hh(n,e,t){if(n===1)return`${e}`;if(n===2)return`${e}.y`;if(n===3)return`${e}.z`;if(n===4)return`${e}.w`;throw Error(`Cumulative ${t} for rank ${n} is not yet supported`)}/** + * @license + * Copyright 2022 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. + * ============================================================================= + */function mb(n,e,t,r,s,a){const o=e.shape.length,i=Or([r],o);let l=e;i!=null&&(l=Vn({inputs:{x:e},backend:t,attrs:{perm:i}}));const c=An(1,o)[0];if(c!==o-1)throw new Error(`WebGPU cumprod shader expects an inner-most axis=${e.shape.length-1} but got axis=${r}`);const u=l.shape[c];let d=Xt({inputs:{x:l},backend:t});for(let p=0;p<=Math.ceil(Math.log2(u))-1;p++){const f=new dh(n,l.shape,!1,a),m=d,g=[{type:"float32",data:[p]}];d=t.runWebGPUProgram(f,[d],d.dtype,g),t.disposeData(m.dataId)}if(s){const p=new dh(n,l.shape,s,a),f=d,m=[{type:"float32",data:[0]}];d=t.runWebGPUProgram(p,[d],d.dtype,m),t.disposeData(f.dataId)}if(i!=null){const p=hu(i),f=Vn({inputs:{x:d},backend:t,attrs:{perm:p}});return t.disposeData(d.dataId),t.disposeData(l.dataId),f}return d}/** + * @license + * Copyright 2022 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. + * ============================================================================= + */function $z(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{axis:a,exclusive:o,reverse:i}=r;return mb(uo.Prod,s,t,a,o,i)}const Tz={kernelName:ki,backendName:"webgpu",kernelFunc:$z};/** + * @license + * Copyright 2022 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. + * ============================================================================= + */function Ez(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{axis:a,exclusive:o,reverse:i}=r;return mb(uo.Sum,s,t,a,o,i)}const Az={kernelName:_i,backendName:"webgpu",kernelFunc:Ez};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */function Rz(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,weights:a}=e,{size:o,binaryOutput:i}=r,l=s.shape.length===1,u=q(a.shape)>0,d=a.dtype,p=l?[s.shape[0]]:[s.shape[0],s.shape[1]],f=l?[o]:[s.shape[0],o],m=Wt({backend:t,attrs:{shape:f,value:0,dtype:d}}),g=new db(p,u,i),b=[{type:"int32",data:[o]}],v=u?[s,a]:[s];return t.runWebGPUProgram(g,v,d,b,m)}const Dz={kernelName:dc,backendName:"webgpu",kernelFunc:Rz};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */class Pz{constructor(e,t){this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.uniforms="blockSize : i32,",this.outputShape=e,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey=`depthToSpace_${t}`,this.dataFormat=t}getUserCode(){return` + ${re("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let b = coords[0]; + let h = ${this.getHeightCoordString()}; + let w = ${this.getWidthCoordString()}; + let d = ${this.getDepthCoordString()}; + + let in_h = h / uniforms.blockSize; + let offset_h = h % uniforms.blockSize; + let in_w = w / uniforms.blockSize; + let offset_w = w % uniforms.blockSize; + let offset_d = (offset_h * uniforms.blockSize + offset_w) * + ${this.getOutputDepthSize()}; + let in_d = d + offset_d; + + let rlt = ${this.getInputSamplingString()}; + setOutputAtIndex(index, rlt); + } + }`}getHeightCoordString(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"}getWidthCoordString(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"}getDepthCoordString(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"}getOutputDepthSize(){return this.dataFormat==="NHWC"?"uniforms.outShape[3]":"uniforms.outShape[1]"}getInputSamplingString(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function Fz(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{blockSize:a,dataFormat:o}=r,i=s.shape[0],l=o==="NHWC"?s.shape[1]:s.shape[2],c=o==="NHWC"?s.shape[2]:s.shape[3],u=o==="NHWC"?s.shape[3]:s.shape[1],d=l*a,p=c*a,f=u/(a*a),m=o==="NHWC"?[i,d,p,f]:[i,f,d,p],g=[{type:"int32",data:[a]}],b=new Pz(m,o);return t.runWebGPUProgram(b,[s],s.dtype,g)}const Oz={kernelName:Ni,backendName:"webgpu",kernelFunc:Fz};/** + * @license + * Copyright 2022 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. + * ============================================================================= + */class Mz{constructor(e,t,r,s=!1,a=null,o=!1){this.variableNames=["x","W"],this.uniforms="pads : vec2, inDims : vec2,",this.workgroupSize=[16,16,1],this.outputShape=e,this.dispatchLayout={x:[3],y:[2],z:[0,1]},this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),s&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),this.addBias=s,this.activation=a,this.hasPreluActivation=o,this.filterHeight=t,this.filterWidth=r,this.shaderKey=`depthwiseNCHW_${this.activation}_${this.filterHeight}_${this.filterWidth}`}getUserCode(){const e=this.filterWidth*this.filterHeight,t=this.workgroupSize[0]*this.workgroupSize[1]*this.workgroupSize[2],r=this.workgroupSize[1]+this.filterHeight-1,s=this.workgroupSize[0]+this.filterWidth-1;return` + ${ir(this.activation,this.hasPreluActivation,!1,4)} + + var mm_Asub : array, ${r}>; + var mm_Bsub : array, ${this.filterHeight}>; + fn readX(batch : i32, channel : i32, row : i32, col : i32) -> f32 { + var value = 0.0; + if (row >=0 && row < uniforms.inDims[0] && col >=0 && col < uniforms.inDims[1]) + { + value = getX(batch, channel, row, col); + } + return value; + } + + ${re()} { + let coords = getOutputCoords(); + let batch = coords[0]; + let xRCCorner = vec2(coords.zw) - uniforms.pads; + let channelMul = uniforms.wShape[3]; + let d1 = coords[1] / channelMul; + let q = coords[1] % channelMul; + + let inputRowStart = xRCCorner.x; + let inputColStart = xRCCorner.y; + + let localRow = i32(localId.y); + let localCol = i32(localId.x); + + // Load one tile of X into local memory. + for (var inputRow = localRow; inputRow < ${r}; inputRow = inputRow + ${this.workgroupSize[1]}) { + for (var inputCol = localCol; inputCol < ${s}; inputCol = inputCol + ${this.workgroupSize[0]}) { + let rowOffset = inputRow - localRow; + let colOffset = inputCol - localCol; + mm_Asub[inputRow][inputCol] = readX(batch, d1, inputRowStart + rowOffset, inputColStart + colOffset); + } + } + + // Load one tile of W into local memory. + var wIndex = i32(localIndex); + ${e, inDims : vec2, virtualWidth : i32,",this.workgroupSize=[64,1,1],this.workPerThread=4,this.outputComponent=4,this.outputShape=e.outShape,this.virtualWidth=Math.ceil(this.outputShape[2]/this.workPerThread)*this.workPerThread;const a=[this.outputShape[0],this.outputShape[1],this.virtualWidth,this.outputShape[3]];this.dispatchLayout=ie(a),this.dispatch=se(this.dispatchLayout,a,this.workgroupSize,[this.outputComponent*this.workPerThread,1,1]),$(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=r,this.hasPreluActivation=s,this.shaderKey=`depthwiseVec4_${r}_${this.convInfo.filterHeight}_${this.convInfo.filterWidth}_${this.convInfo.strideHeight}_${this.convInfo.strideWidth}_${this.workPerThread}`}getUserCode(){const e=(this.workPerThread-1)*this.convInfo.strideWidth+this.convInfo.filterWidth,t=this.convInfo.strideHeight,r=this.convInfo.strideWidth;return` + ${ir(this.activation,this.hasPreluActivation,!0,4)} + fn readX(batch : i32, row : i32, col : i32, channel : i32) -> vec4 { + var value = vec4(0.0); + if (col >=0 && col < uniforms.inDims[1]) { + value = getX(batch, row, col, channel); + } + return value; + } + + ${re("index")} { + let width0 = uniforms.outShape[3] / ${this.outputComponent}; + let d1 = (index % width0) * ${this.outputComponent}; + var index1 = index / width0; + let width1 = uniforms.virtualWidth / ${this.workPerThread}; + let c = (index1 % width1) * ${this.workPerThread}; + index1 = index1 / width1; + let r = index1 % uniforms.outShape[1]; + let batch = index1 / uniforms.outShape[1]; + + let xRCCorner = vec2(r, c) * vec2(${t}, ${r}) - uniforms.pads; + + let xRCorner = xRCCorner.x; + let xCCorner = xRCCorner.y; + var xVals : array, ${e}>; + var dotProd : array, ${this.workPerThread}>; + for (var i = 0; i < ${this.workPerThread}; i++) { + dotProd[i] = vec4(0.0); + } + + // Use constant instead of uniform can give better performance. + for (var wR = 0; wR < ${this.convInfo.filterHeight}; wR = wR + 1) { + let xR = xRCorner + wR; + if (xR >=0 && xR < uniforms.inDims[0]) { + for (var i = 0; i < ${e}; i++) { + xVals[i] = readX(batch, xR, xCCorner + i, d1); + } + for (var wC = 0; wC < ${this.convInfo.filterWidth}; wC = wC + 1) { + let wValue = getW(wR, wC, d1, 0); + for (var i = 0; i < ${this.workPerThread}; i++) { + dotProd[i] = fma(xVals[i * ${r} + wC], wValue, dotProd[i]); + } + } + } + } + + for (var i = 0; i < ${this.workPerThread}; i = i + 1) { + let coords = vec4(batch, r, c + i, d1); + if (coordsInBounds4D(coords, uniforms.outShape)) { + var value = dotProd[i]; + ${_s(this.addBias,this.activation)} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + } + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class yb{constructor(e,t=!1,r=null,s=!1){this.variableNames=["x","W"],this.uniforms=`pads : vec2, inDims : vec2, filterHeight : i32, + filterWidth : i32, strides : vec2, dilations : vec2,`,this.workgroupSize=[256,1,1],this.size=!0,this.outputShape=e.outShape,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.isChannelsLast=e.dataFormat==="channelsLast",t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=r,this.hasPreluActivation=s,this.shaderKey=`depthwise_${this.activation}_${this.isChannelsLast}`}getUserCode(){const e=this.isChannelsLast?"getX(batch, xR, xC, d1);":"getX(batch, d1, xR, xC);";return` + ${ir(this.activation,this.hasPreluActivation,!1,4)} + + ${re("index")} { + if (index < uniforms.size) { + let coords = getOutputCoords(); + let batch = coords[0]; + let xRCCorner = vec2(coords.${this.isChannelsLast?"yz":"zw"}) * uniforms.strides - uniforms.pads; + let d2 = coords[${this.isChannelsLast?3:1}]; + let channelMul = uniforms.wShape[3]; + let d1 = d2 / channelMul; + let q = d2 % channelMul; + + let inputRowStart = xRCCorner.x; + let inputColStart = xRCCorner.y; + let inputRowEnd = inputRowStart + uniforms.filterHeight * + uniforms.dilations[0]; + let inputColEnd = inputColStart + uniforms.filterWidth * + uniforms.dilations[1]; + + // Convolve x(?, ?, d1)|x(d1, ?, ?) with w(:, :, d1, q) to get + // y(yR, yC, d2)|y(d2, yR, yC). ? = to be determined. : = across all + // values in that axis. x(?, ?, d1) and y(yR, yC, d2) is for NHWC. + // x(d1, ?, ?) and y(d2, yR, yC) is for NCHW. + var value = 0.0; + + // Extract if checking out of for loop for performance. + if (inputRowStart >= 0 && inputColStart >= 0 && + inputRowEnd < uniforms.inDims[0] && + inputColEnd < uniforms.inDims[1]) { + for (var wR = 0; wR < uniforms.filterHeight; wR = wR + 1) { + let xR = inputRowStart + wR * uniforms.dilations[0]; + + for (var wC = 0; wC < uniforms.filterWidth; wC = wC + 1) { + let xC = inputColStart + wC * uniforms.dilations[1]; + + let xVal = ${e}; + let wVal = getW(wR, wC, d1, q); + value = value + xVal * wVal; + } + } + } else { + for (var wR = 0; wR < uniforms.filterHeight; wR = wR + 1) { + let xR = inputRowStart + wR * uniforms.dilations[0]; + + if (xR < 0 || xR >= uniforms.inDims[0]) { + continue; + } + + for (var wC = 0; wC < uniforms.filterWidth; wC = wC + 1) { + let xC = inputColStart + wC * uniforms.dilations[1]; + + if (xC < 0 || xC >= uniforms.inDims[1]) { + continue; + } + + let xVal = ${e}; + let wVal = getW(wR, wC, d1, q); + value = value + xVal * wVal; + } + } + } + ${_s(this.addBias,this.activation)} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + } + `}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function Lz(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,filter:a}=e,{strides:o,pad:i,dataFormat:l,dilations:c,dimRoundingMode:u}=r,d=Fr(l);let p=c;p==null&&(p=[1,1]);const f=Tt(s.shape,a.shape,o,p,i,u,!0,d),m=[{type:"int32",data:[f.padInfo.top,f.padInfo.left]},{type:"int32",data:[f.inHeight,f.inWidth]}],g=f.dataFormat==="channelsLast";let b;return!g&&f.inHeight>16&&f.inWidth>16&&f.strideHeight===1&&f.strideWidth===1&&f.dilationWidth===1&&f.dilationHeight===1&&f.inChannels===f.outChannels?b=new Mz(f.outShape,f.filterHeight,f.filterWidth):g&&f.outHeight>4&&f.outWidth>4&&f.strideWidth<=2&&f.inChannels===f.outChannels&&f.dilationHeight===1&&f.dilationWidth===1&&f.inChannels%4===0?(b=new gb(f),m.push({type:"int32",data:[b.virtualWidth]})):(b=new yb(f),m.push({type:"int32",data:[f.filterHeight]},{type:"int32",data:[f.filterWidth]},{type:"int32",data:[f.strideHeight,f.strideWidth]},{type:"int32",data:[f.dilationHeight,f.dilationWidth]})),t.runWebGPUProgram(b,[s,a],s.dtype,m)}const zz={kernelName:$i,backendName:"webgpu",kernelFunc:Lz};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */class Bz{constructor(e){this.variableNames=["x","dy"],this.uniforms=`strides : vec2, pads : vec2, filterDims : vec2, outHeight : i32, + outWidth : i32, inHeight : i32, inWidth : i32, batchSize : i32, channelMul : i32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.filterShape,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="depthwise_conv2d_backprop_filter"}getUserCode(){return` + ${re("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let wR = coords[0]; + let wC = coords[1]; + let d1 = coords[2]; + let dm = coords[3]; + let d2 = d1 * uniforms.channelMul + dm; + + var dotProd = 0.0; + for (var b = 0; b < uniforms.batchSize; b++) { + for (var yR = 0; yR < uniforms.outHeight; yR++) { + let xR = wR + yR * uniforms.strides[0] - uniforms.pads[0]; + + if (xR < 0 || xR >= uniforms.inHeight) { + continue; + } + + for (var yC = 0; yC < uniforms.outWidth; yC++) { + let xC = wC + yC * uniforms.strides[1] - uniforms.pads[1]; + + if (xC < 0 || xC >= uniforms.inWidth) { + continue; + } + + let dyValue = getDy(b, yR, yC, d2); + let xValue = getX(b, xR, xC, d1); + dotProd += xValue * dyValue; + } + } + } + setOutputAtIndex(index, dotProd); + } + } + `}}class Wz{constructor(e){this.variableNames=["dy","W"],this.uniforms=`strides : vec2, pads : vec2, filterDims : vec2, + outHeight : i32, outWidth : i32, channelMul : i32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.inShape,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="depthwise_conv2d_backprop_input"}getUserCode(){return` + ${re("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let batch = coords[0]; + let d1 = coords[3]; + let dyCorner = coords.yz - uniforms.pads; + let dyRCorner = dyCorner.x; + let dyCCorner = dyCorner.y; + + var dotProd = 0.0; + for (var wR = 0; wR < uniforms.filterDims[0]; wR++) { + let dyR = f32(dyRCorner + wR) / f32(uniforms.strides[0]); + + if (dyR < 0.0 || dyR >= f32(uniforms.outHeight) || fract(dyR) > 0.0) { + continue; + } + + let idyR = i32(dyR); + let wRPerm = uniforms.filterDims[0] - 1 - wR; + + for (var wC = 0; wC < uniforms.filterDims[1]; wC++) { + let dyC = f32(dyCCorner + wC) / f32(uniforms.strides[1]); + + if (dyC < 0.0 || dyC >= f32(uniforms.outWidth) || fract(dyC) > 0.0) { + continue; + } + + let idyC = i32(dyC); + let wCPerm = uniforms.filterDims[1] - 1 - wC; + + for (var dm = 0; dm < uniforms.channelMul; dm++) { + let d2 = d1 * uniforms.channelMul + dm; + let xValue = getDy(batch, idyR, idyC, d2); + let wValue = getW(wRPerm, wCPerm, d1, dm); + dotProd += xValue * wValue; + } + } + } + setOutputAtIndex(index, dotProd); + } + } + `}}/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */function Vz(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,dy:a}=e,{strides:o,dilations:i,pad:l,dimRoundingMode:c,filterShape:u}=r,d=Tt(s.shape,u,o,i,l,c,!0),p=new Bz(d),f=[{type:"int32",data:[d.strideHeight,d.strideWidth]},{type:"int32",data:[d.padInfo.top,d.padInfo.left]},{type:"int32",data:[d.filterHeight,d.filterWidth]},{type:"int32",data:[d.outHeight]},{type:"int32",data:[d.outWidth]},{type:"int32",data:[d.inHeight]},{type:"int32",data:[d.inWidth]},{type:"int32",data:[d.batchSize]},{type:"int32",data:[d.outChannels/d.inChannels]}];return t.runWebGPUProgram(p,[s,a],"float32",f)}const Uz={kernelName:uf,backendName:"webgpu",kernelFunc:Vz};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */function Hz(n){const{inputs:e,backend:t,attrs:r}=n,{dy:s,filter:a}=e,{strides:o,dilations:i,pad:l,dimRoundingMode:c,inputShape:u}=r,d=Tt(u,a.shape,o,i,l,c,!0),p=new Wz(d),f=[{type:"int32",data:[d.strideHeight,d.strideWidth]},{type:"int32",data:[d.filterHeight-1-d.padInfo.top,d.filterWidth-1-d.padInfo.left]},{type:"int32",data:[d.filterHeight,d.filterWidth]},{type:"int32",data:[d.outHeight]},{type:"int32",data:[d.outWidth]},{type:"int32",data:[d.outChannels/d.inChannels]}];return t.runWebGPUProgram(p,[s,a],s.dtype,f)}const Gz={kernelName:lf,backendName:"webgpu",kernelFunc:Hz};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */class jz{constructor(e){this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=[e,e],this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="diag"}getUserCode(){return` + ${re("index")} { + if (index < uniforms.size) { + let coords = getOutputCoords(); + let value = select(0.0, getX(coords[0]), coords[0] == coords[1]); + setOutputAtIndex(index, value); + } + } + `}}/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */function qz(n){const{inputs:e,backend:t}=n,{x:r}=e,s=[...r.shape,...r.shape],a=q(r.shape),o=de({inputs:{x:r},backend:t,attrs:{shape:[a]}}),i=new jz(a),l=t.runWebGPUProgram(i,[o],o.dtype),c=de({inputs:{x:l},backend:t,attrs:{shape:s}});return t.disposeData(o.dataId),t.disposeData(l.dataId),c}const Kz={kernelName:pc,backendName:"webgpu",kernelFunc:qz};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */class Xz{constructor(e){this.variableNames=["x","w"],this.uniforms="filterDims: vec2, pads: vec2, strides: vec2, dilations: vec2",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.outShape,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="dilation2d"}getUserCode(){return` + ${re("index")} { + if (index < uniforms.size) { + let neg_infinity = -3.4e38; + let coords = getOutputCoords(); + let batch = coords.x; + let d1 = coords.w; + let outTopLeftCorner = coords.yz * uniforms.strides - uniforms.pads; + let hBeg = outTopLeftCorner.x; + let wBeg = outTopLeftCorner.y; + + var curVal = neg_infinity; + for (var h = 0; h < uniforms.filterDims[0]; h = h + 1) { + let hIn = hBeg + h * uniforms.dilations[0]; + + if (hIn >= 0 && hIn < uniforms.xShape[1]) { + for (var w = 0; w < uniforms.filterDims[1]; w = w + 1) { + let wIn = wBeg + w * uniforms.dilations[1]; + + if (wIn >= 0 && wIn < uniforms.xShape[2]) { + let val = getX(batch, hIn, wIn, d1) + getW(h, w, d1); + if (val > curVal) { + curVal = val; + } + } + } + } + } + + setOutputAtIndex(index, curVal); + } + } + `}}/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */function Yz(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,filter:a}=e,{strides:o,pad:i,dilations:l}=r,c=pa(s.shape,a.shape,o,i,"NHWC",l),u=[c.padInfo.top,c.padInfo.left],d=[{type:"int32",data:[c.filterHeight,c.filterWidth]},{type:"int32",data:[...u]},{type:"int32",data:[c.strideHeight,c.strideWidth]},{type:"int32",data:[c.dilationHeight,c.dilationWidth]}],p=new Xz(c);return t.runWebGPUProgram(p,[s,a],s.dtype,d)}const Qz={kernelName:Ti,backendName:"webgpu",kernelFunc:Yz};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */class Zz{constructor(e,t){if(this.variableNames=["x","w","dy"],this.uniforms="filterDims: vec2, pads: vec2, strides: vec2, dilations: vec2, dySize: i32,",this.workgroupSize=[64,1,1],this.atomic=!0,this.outputShape=e.inShape,this.dispatchLayout=ie(e.outShape),this.dispatch=se(this.dispatchLayout,e.outShape,this.workgroupSize),t!=="float32"&&t!=="int32")throw new Error(`Dilation2DBackpropInput only supports float32 and int32 + types, does not support ${t} type.`);this.type=t,this.shaderKey="dilation2DBackpropInput"}getUserCode(){return` + ${re("index")} { + if (index < uniforms.dySize) { + let coords = getDyCoordsFromIndex(index); + let b = coords[0]; + let r = coords[1]; + let c = coords[2]; + let d = coords[3]; + + let dyCorner = vec2(r, c) * uniforms.strides - uniforms.pads; + var curVal = -3.4e38; // neg_infinity + var xRMax = 0; + var xCMax = 0; + + // In the case of multiple argmax branches, we only back-propagate + // along the last branch, i.e., the one with largest value of + // 'wR * uniforms.filterDims[1] + wC', similarly to the max-pooling + // backward routines. + for (var wR = 0; wR < uniforms.filterDims[0]; wR++) { + let xR = dyCorner.x + wR * uniforms.dilations[0]; + + if (xR >= 0 && xR < uniforms.xShape[1]) { + for (var wC = 0; wC < uniforms.filterDims[1]; wC++) { + let xC = dyCorner.y + wC * uniforms.dilations[1]; + + if (xC >= 0 && xC < uniforms.xShape[2]) { + let val = getX(b, xR, xC, d) + getW(wR, wC, d); + if (val > curVal) { + curVal = val; + xRMax = xR; + xCMax = xC; + } + } + } + } + } + + let flatIndexIn = d + uniforms.xShape[3] * + (xCMax + uniforms.xShape[2] * (xRMax + uniforms.xShape[1] * b)); + let value = getDy(b, r, c, d); + ${zr("&result[flatIndexIn]","value",this.type)} + } + } + `}}class Jz{constructor(e,t,r){if(this.variableNames=["x","w","dy"],this.uniforms="filterDims: vec2, pads: vec2, strides: vec2, dilations: vec2, dySize: i32,",this.workgroupSize=[64,1,1],this.atomic=!0,this.outputShape=e.filterShape,this.dispatchLayout=ie(e.outShape),this.dispatch=se(this.dispatchLayout,e.outShape,this.workgroupSize),r!=="float32"&&r!=="int32")throw new Error(`Dilation2DBackpropFilter only supports float32 and int32 + types, does not support ${r} type.`);this.type=r,this.shaderKey="dilation2DBackpropFilter"}getUserCode(){return` + ${re("index")} { + if (index < uniforms.dySize) { + let coords = getDyCoordsFromIndex(index); + let b = coords[0]; + let r = coords[1]; + let c = coords[2]; + let d = coords[3]; + + let dyCorner = vec2(r, c) * uniforms.strides - uniforms.pads; + var curVal = -3.4e38; // neg_infinity + var wRMax = 0; + var wCMax = 0; + + // In the case of multiple argmax branches, we only back-propagate + // along the last branch, i.e., the one with largest value of + // 'wR * uniforms.filterDims[1] + wC', similarly to the max-pooling + // backward routines. + for (var wR = 0; wR < uniforms.filterDims[0]; wR++) { + let xR = dyCorner.x + wR * uniforms.dilations[0]; + + if (xR >= 0 && xR < uniforms.xShape[1]) { + for (var wC = 0; wC < uniforms.filterDims[1]; wC++) { + let xC = dyCorner.y + wC * uniforms.dilations[1]; + + if (xC >= 0 && xC < uniforms.xShape[2]) { + let val = getX(b, xR, xC, d) + getW(wR, wC, d); + if (val > curVal) { + curVal = val; + wRMax = wR; + wCMax = wC; + } + } + } + } + } + + let flatIndexIn = d + uniforms.wShape[2] * (wCMax + wRMax * uniforms.wShape[1]); + let value = getDy(b, r, c, d); + ${zr("&result[flatIndexIn]","value",this.type)} + } + } + `}}/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */function eB(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,filter:a,dy:o}=e,{strides:i,pad:l,dilations:c}=r,u=pa(s.shape,a.shape,i,l,"NHWC",c),d=a.dtype,p=new Jz(u,a.shape,d),f=[{type:"int32",data:[u.filterHeight,u.filterWidth]},{type:"int32",data:[u.padInfo.top,u.padInfo.left]},{type:"int32",data:[u.strideHeight,u.strideWidth]},{type:"int32",data:[u.dilationHeight,u.dilationWidth]},{type:"int32",data:[q(u.outShape)]}],m=Wt({backend:t,attrs:{shape:a.shape,value:0,dtype:d}});return t.runWebGPUProgram(p,[s,a,o],d,f,m)}const tB={kernelName:fc,backendName:"webgpu",kernelFunc:eB};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */function nB(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,filter:a,dy:o}=e,{strides:i,pad:l,dilations:c}=r,u=pa(s.shape,a.shape,i,l,"NHWC",c),d=s.dtype,p=new Zz(u,d),f=[{type:"int32",data:[u.filterHeight,u.filterWidth]},{type:"int32",data:[u.padInfo.top,u.padInfo.left]},{type:"int32",data:[u.strideHeight,u.strideWidth]},{type:"int32",data:[u.dilationHeight,u.dilationWidth]},{type:"int32",data:[q(u.outShape)]}],m=Wt({backend:t,attrs:{shape:u.inShape,value:0,dtype:d}});return t.runWebGPUProgram(p,[s,a,o],d,f,m)}const rB={kernelName:hc,backendName:"webgpu",kernelFunc:nB};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */class sB{constructor(e,t,r){this.variableNames=["Image"],this.uniforms="alpha: f32,",this.workgroupSize=[64,1,1],this.pixelsOpType=ua.DRAW,this.size=!0,this.outputShape=e,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.type=t,this.textureFormat=r,this.shaderKey=`draw_${t}_${r}`}getUserCode(){let e;const t=this.type==="float32"?"value":"value / 255.0";return e=` + if (uniforms.numChannels == 1) { + rgba[0] = ${t}; + rgba[1] = ${t}; + rgba[2] = ${t}; + } else { + rgba[d] = ${t}; + }`,` + @group(0) @binding(0) var outImage : texture_storage_2d<${this.textureFormat}, write>; + ${re("index")} { + if (index < uniforms.size) { + var rgba = vec4(0.0, 0.0, 0.0, uniforms.alpha); + for (var d = 0; d < uniforms.numChannels; d = d + 1) { + let value = f32(inBuf[index * uniforms.numChannels + d]); + ${e} + } + rgba.x = rgba.x * rgba.w; + rgba.y = rgba.y * rgba.w; + rgba.z = rgba.z * rgba.w; + let coords = getCoordsFromIndex(index); + textureStore(outImage, vec2(coords.yx), rgba); + } + } + `}}/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use backend 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. + * ============================================================================= + */function aB(n){const{inputs:e,backend:t,attrs:r}=n,{image:s}=e,{canvas:a,options:o}=r,[i,l]=s.shape.slice(0,2),{imageOptions:c}=o||{},u=c?.alpha||1,d=t.device.features.has("bgra8unorm-storage")?"bgra8unorm":"rgba8unorm",p=[i,l],f=new sB(p,s.dtype,d);a.width=l,a.height=i;const m="webgpu";let g=a.getContext(m),b;g||(b=new OffscreenCanvas(l,i),g=b.getContext(m));const v=s.shape.length===3?s.shape[2]:1;g.configure({device:t.device,format:d,usage:GPUTextureUsage.STORAGE_BINDING,alphaMode:"premultiplied"});const I="int32",S=t.makeTensorInfo(p,I),C=t.tensorMap.get(S.dataId);C.resource=g.getCurrentTexture(),C.external=!0;const T=[{type:"uint32",data:[v]},{type:"float32",data:[u]}];if(t.runWebGPUProgram(f,[s],I,T,S),b){const O=a.getContext("2d");if(!O)throw new Error("Please make sure this canvas has only been used for 2d or webgpu context!");O.drawImage(b,0,0)}return t.disposeData(S.dataId),s}const oB={kernelName:cf,backendName:"webgpu",kernelFunc:aB};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const bb=xt({opType:ve.MUL,cpuKernelImpl:dM,supportsComplex:!0}),iB={kernelName:Gc,backendName:"webgpu",kernelFunc:bb};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function wb(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{axis:a,keepDims:o}=r;return Ns(s,a,o,"sum",t)}const uB={kernelName:tu,backendName:"webgpu",kernelFunc:wb};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function lB(n){const{inputs:e,backend:t,attrs:r}=n,{equation:s}=r,a=e,{allDims:o,summedDims:i,idDims:l}=WC(s,a.length);UC(o.length,l,a);const{path:c,steps:u}=HC(i,l),d=u.length;let p=null,f=o.length;const m=[];for(let g=0;g=0&&(p=wb({inputs:{x:p},backend:t,attrs:{axis:c[g]-(o.length-f),keepDims:!1}}),m.push(p)),f--)}for(const g of m)g!==p&&t.disposeData(g.dataId);return p}const cB={kernelName:df,backendName:"webgpu",kernelFunc:lB};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const dB=We({opType:ne.ELU}),pB={kernelName:gc,backendName:"webgpu",kernelFunc:dB};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */const hB=n=>{const{inputs:e,backend:t}=n,{dy:r,y:s}=e,a=new oi(ve.ELU_DER,r.shape,s.shape);return t.runWebGPUProgram(a,[r,s],r.dtype)},fB={kernelName:yc,backendName:"webgpu",kernelFunc:hB};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const mB=xt({opType:ve.EQUAL,dtype:"bool",cpuKernelImpl:YO}),gB={kernelName:wc,backendName:"webgpu",kernelFunc:mB};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */const yB=We({opType:ne.ERF}),bB={kernelName:bc,backendName:"webgpu",kernelFunc:yB};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const wB=We({opType:ne.EXP,cpuKernelImpl:QO,dtype:"float32"}),xB={kernelName:xc,backendName:"webgpu",kernelFunc:wB};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function Bl(n){const{inputs:e,attrs:t,backend:r}=n,{dim:s}=t,{input:a}=e,o=a.shape.length,i=a.shape.slice();let l=s;return s<0&&($(-(o+1)<=s,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),l=o+s+1),i.splice(l,0,1),de({inputs:{x:a},backend:r,attrs:{shape:i}})}const vB={kernelName:vc,backendName:"webgpu",kernelFunc:Bl};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const SB=We({opType:ne.EXPM1,cpuKernelImpl:ZO}),IB={kernelName:Sc,backendName:"webgpu",kernelFunc:SB};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */class fh{constructor(e,t){this.variableNames=["real","imag"],this.outputShape=[],this.uniforms="exponentMultiplier : f32, denominator: f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.component=e,this.shaderKey=`fft_${e}`}getUserCode(){return` + fn unaryOpComplex(real: f32, expR: f32, imag: f32, expI: f32) -> f32 { + ${this.component==="real"?"return real * expR - imag * expI;":"return real * expI + imag * expR;"} + } + + fn mulMatDFT(batch: i32, index: i32) -> f32 { + let indexRatio = f32(index) / f32(uniforms.realShape[1]); + let exponentMultiplierTimesIndexRatio = + uniforms.exponentMultiplier * indexRatio; + + var result = 0.0; + + for (var i = 0; i < uniforms.realShape[1]; i = i + 1) { + // x = (-2|2 * PI / N) * index * i; + let x = exponentMultiplierTimesIndexRatio * f32(i); + let expR = cos(x); + let expI = sin(x); + let real = getReal(batch, i); + let imag = getImag(batch, i); + + result = result + + unaryOpComplex(real, expR, imag, expI) / uniforms.denominator; + } + + return result; + } + + ${re("index")} { + if (index < uniforms.size) { + let coords = getOutputCoords(); + setOutputAtIndex(index, mulMatDFT(coords[0], coords[1])); + } + } + `}}/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */function xb(n,e,t){const r=t.tensorMap.get(n.dataId),s=q(n.shape),a=n.shape[n.shape.length-1],o=s/a,i=[],l=de({inputs:{x:n},backend:t,attrs:{shape:[o,a]}});i.push(l);const c=l.shape,u=new fh("real",c),d=new fh("imag",c),p=[{dataId:r.complexTensorInfos.real.dataId,dtype:r.complexTensorInfos.real.dtype,shape:c},{dataId:r.complexTensorInfos.imag.dataId,dtype:r.complexTensorInfos.imag.dtype,shape:c}],f=e?2*Math.PI:-2*Math.PI,m=e?c[1]:1,g=[{type:"float32",data:[f]},{type:"float32",data:[m]}],b=t.runWebGPUProgram(u,p,"float32",g);i.push(b);const v=t.runWebGPUProgram(d,p,"float32",g);i.push(v);const I=Cs({inputs:{real:b,imag:v},backend:t});i.push(I);const S=de({inputs:{x:I},backend:t,attrs:{shape:n.shape}});return i.forEach(C=>t.disposeData(C.dataId)),S}/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */function kB(n){const{inputs:e,backend:t}=n,{input:r}=e;return xb(r,!1,t)}const _B={kernelName:pf,backendName:"webgpu",kernelFunc:kB};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */class CB{constructor(e){this.outputShape=[],this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="flipLeftRight"}getUserCode(){return` + ${re("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let coordX = uniforms.xShape[2] - coords[2] - 1; + let outputValue = getX(coords[0], coords[1], coordX, coords[3]); + setOutputAtIndex(index, outputValue); + } + } + `}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const NB={kernelName:Ei,backendName:"webgpu",kernelFunc:({inputs:n,backend:e})=>{const{image:t}=n,r=e,s=new CB(t.shape);return r.runWebGPUProgram(s,[t],t.dtype)}};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const $B=We({opType:ne.FLOOR,cpuKernelImpl:JO}),TB={kernelName:kc,backendName:"webgpu",kernelFunc:$B};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const EB=xt({opType:ve.FLOOR_DIV,cpuKernelImpl:eM,dtype:"int32"}),AB={kernelName:_c,backendName:"webgpu",kernelFunc:EB};/** + * @license + * Copyright 2022 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. + * ============================================================================= + */class RB{constructor(e,t,r=!1){this.pixelsOpType=ua.FROM_PIXELS,this.outputShape=[0],this.variableNames=[],this.workgroupSize=[256,1,1],this.outputShape=e,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize,[t,1,1]),this.importVideo=r,this.shaderKey=`fromPixels_${this.importVideo}`}getUserCode(){const e=this.importVideo?"textureLoad(src, vec2(coords.yx));":"textureLoad(src, vec2(coords.yx), 0)";return` + @binding(1) @group(0) var src: ${this.importVideo?"texture_external":"texture_2d"}; + ${re("index")} { + let flatIndex = index * uniforms.numChannels; + if (flatIndex < uniforms.size) { + let coords = getCoordsFromIndex(flatIndex); + let values = ${e}; + for (var i = 0; i < uniforms.numChannels; i = i + 1) { + result[flatIndex + i] = i32(floor(255.0 * values[i])); + } + } + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use backend 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. + * ============================================================================= + */const DB={kernelName:al,backendName:"webgpu",kernelFunc:PB};let Hs,Gu=fe().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");function PB(n){const{inputs:e,backend:t,attrs:r}=n;let{pixels:s}=e;const{numChannels:a}=r;if(s==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");const o=typeof HTMLVideoElement<"u"&&s instanceof HTMLVideoElement,i=typeof HTMLImageElement<"u"&&s instanceof HTMLImageElement,l=typeof HTMLCanvasElement<"u"&&s instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&s instanceof OffscreenCanvas,c=typeof ImageBitmap<"u"&&s instanceof ImageBitmap,[u,d]=o?[s.videoWidth,s.videoHeight]:[s.width,s.height],p=[d,u,a],f=fe().getBool("WEBGPU_IMPORT_EXTERNAL_TEXTURE")&&o,m=o||i;if(c||l||m){let I;if(f)I=t.device.importExternalTexture({source:s});else{if(m){const H=fe().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");(Hs==null||H!==Gu)&&(Gu=H,Hs=document.createElement("canvas").getContext("2d",{willReadFrequently:Gu})),Hs.canvas.width=u,Hs.canvas.height=d,Hs.drawImage(s,0,0,u,d),s=Hs.canvas}const D=GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING,V=t.textureManager.acquireTexture(p[1],p[0],"rgba8unorm",D);t.queue.copyExternalImageToTexture({source:s},{texture:V},[p[1],p[0]]),I=V}const S=q(p),C=et(p),T=new RB(p,a,f),O=[{type:"uint32",data:[S]},{type:"uint32",data:[a]},{type:"uint32",data:[...C]}],L=t.makeTensorInfo([d,u],"int32"),B=t.tensorMap.get(L.dataId);B.resource=I;const A=t.runWebGPUProgram(T,[L],"int32",O);return t.disposeData(L.dataId),A}const g=s.data;let b=g;if(a!=null&&a!==4){b=new Uint8Array(s.width*s.height*a);const I=g.length;let S=0;for(let C=0;C(xValue, -meanValue, offsetValue), vec3(inv, inv, 1.0))); + } + } + `}}/** + * @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. + * ============================================================================= + */const OB={kernelName:Ai,backendName:"webgpu",kernelFunc:({inputs:n,attrs:e,backend:t})=>{const{x:r,scale:s,offset:a,mean:o,variance:i}=n,{varianceEpsilon:l}=e,c=t,u=[r,o,i];let d=null;a!=null&&(d=a.shape,u.push(a));let p=null;s!=null&&(p=s.shape,u.push(s));const f=new FB(r.shape,o.shape,i.shape,d,p),m=[{type:"float32",data:[l]}];return c.runWebGPUProgram(f,u,r.dtype,m)}};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function MB(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,filter:a,bias:o,preluActivationWeights:i}=e,{strides:l,pad:c,dataFormat:u,dilations:d,dimRoundingMode:p,activation:f,leakyreluAlpha:m}=r,g=Fr(u),b=Tt(s.shape,a.shape,l,d,c,p,!1,g);return fb({x:s,filter:a,convInfo:b,backend:t,bias:o,preluActivationWeights:i,leakyreluAlpha:m,activation:f})}const LB={kernelName:Xa,backendName:"webgpu",kernelFunc:MB};/** + * @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. + * ============================================================================= + */function zB(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,filter:a,bias:o,preluActivationWeights:i}=e,{strides:l,pad:c,dilations:u,dimRoundingMode:d,activation:p,leakyreluAlpha:f}=r;let m=u;m==null&&(m=[1,1]),$($n(l,m),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${m}'`);const g=Tt(s.shape,a.shape,l,m,c,d,!0),b=[s,a],v=o!=null,I=i!=null;v&&b.push(o),I&&b.push(i);const S=[{type:"int32",data:[g.padInfo.top,g.padInfo.left]},{type:"int32",data:[g.inHeight,g.inWidth]}];let C;return g.outHeight>4&&g.outWidth>4&&g.strideWidth<=2&&g.inChannels===g.outChannels&&g.dilationHeight===1&&g.dilationWidth===1&&g.inChannels%4===0?(C=new gb(g,v,p,I),S.push({type:"int32",data:[C.virtualWidth]})):(C=new yb(g,v,p,I),S.push({type:"int32",data:[g.filterHeight]},{type:"int32",data:[g.filterWidth]},{type:"int32",data:[g.strideHeight,g.strideWidth]},{type:"int32",data:[g.dilationHeight,g.dilationWidth]})),p==="leakyrelu"&&(S.push({type:"float32",data:[f]}),C.uniforms+=" alpha : f32,"),t.runWebGPUProgram(C,b,"float32",S)}const BB={kernelName:Ya,backendName:"webgpu",kernelFunc:zB};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */class WB{constructor(e,t){this.variableNames=["A","indices"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey=`gathernd_${e}`,this.sliceDim=e,this.uniforms=`sliceDim : i32, strides : ${ft(e)},`}getUserCode(){let e;return this.sliceDim>1?e="uniforms.strides[j]":e="uniforms.strides",` + ${re("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + var flattenIndex = 0; + for (var j = 0; j < uniforms.sliceDim; j = j + 1) { + let indexTemp = i32(round(getIndices(coords[0], j))); + let strideNum = ${e}; + flattenIndex = flattenIndex + indexTemp * strideNum; + } + + setOutputAtIndex(index, getA(flattenIndex, coords[1])); + } + } + `}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function VB(n){const{inputs:e,backend:t}=n,{params:r,indices:s}=e,a=s.shape,o=a[a.length-1],i=q(r.shape),[l,c,u,d]=Ym(r,s),p=de({inputs:{x:s},backend:t,attrs:{shape:[c,o]}}),f=de({inputs:{x:r},backend:t,attrs:{shape:[q(r.shape)/u,u]}});if(t.shouldExecuteOnCPU([r,s])||r.dtype==="string"){const I=t.readSync(s.dataId),S=t.bufferSync(r),C=tM(I,S,r.dtype,c,o,u,d,r.shape,i);return t.makeTensorInfo(l,r.dtype,C.values)}const m=new WB(o,[c,u]),g=[{type:"int32",data:[o]},{type:"int32",data:d}],b=t.runWebGPUProgram(m,[f,p],f.dtype,g),v=de({inputs:{x:b},backend:t,attrs:{shape:l}});return t.disposeData(p.dataId),t.disposeData(f.dataId),t.disposeData(b.dataId),v}const UB={kernelName:Ri,backendName:"webgpu",kernelFunc:VB};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */class HB{constructor(e,t){this.variableNames=["A","indices"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.slice(),this.aShape=e,this.outputShape=t,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="gather"}getUserCode(){const e=GB(this.aShape);return` + ${re("index")} { + if (index < uniforms.size) { + let resRC = getCoordsFromIndex(index); + let indexZ = i32(getIndices(resRC.x, resRC.z)); + let inBounds = select(0.0, 1.0, indexZ >= 0 && indexZ < uniforms.aShape[2]); + setOutputAtIndex(index, inBounds * getA(${e})); + } + } + `}}function GB(n){const e=["resRC.x","resRC.y","resRC.z","resRC.w"],t=[];for(let r=0;rt.disposeData(A.dataId)),t.makeTensorInfo(c.outputShape,B.dtype,B.values)}const g=new HB(p.shape,m),b=t.runWebGPUProgram(g,[p,f],p.dtype);d.push(b);const v=de({inputs:{x:b},backend:t,attrs:{shape:c.outputShape}});return d.forEach(I=>t.disposeData(I.dataId)),v}const jB={kernelName:Cc,backendName:"webgpu",kernelFunc:vb};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const qB=xt({opType:ve.GREATER,cpuKernelImpl:sM,dtype:"bool"}),KB={kernelName:Nc,backendName:"webgpu",kernelFunc:qB};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const XB=xt({opType:ve.GREATER_EQUAL,dtype:"bool",cpuKernelImpl:rM}),YB={kernelName:$c,backendName:"webgpu",kernelFunc:XB};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */function QB(n){const{inputs:e,backend:t}=n,{input:r}=e;return xb(r,!0,t)}const ZB={kernelName:hf,backendName:"webgpu",kernelFunc:QB};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */const JB=We({opType:ne.IS_FINITE,dtype:"bool"}),eW={kernelName:Tc,backendName:"webgpu",kernelFunc:JB};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */const tW=We({opType:ne.IS_INF,dtype:"bool"}),nW={kernelName:Ec,backendName:"webgpu",kernelFunc:tW};/** + * @license + * Copyright 2022 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. + * ============================================================================= + */const rW=We({opType:ne.IS_NAN,dtype:"bool"}),sW={kernelName:Ac,backendName:"webgpu",kernelFunc:rW};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function aW(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{alpha:a}=r,o=[{type:"float32",data:[a]}],i=new ya(s.shape,ne.LEAKYRELU,"alpha : f32,");return t.runWebGPUProgram(i,[s],"float32",o)}const oW={kernelName:Pi,backendName:"webgpu",kernelFunc:aW};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const iW=xt({opType:ve.LESS,dtype:"bool",cpuKernelImpl:oM}),uW={kernelName:Rc,backendName:"webgpu",kernelFunc:iW};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const lW=xt({opType:ve.LESS_EQUAL,dtype:"bool",cpuKernelImpl:aM}),cW={kernelName:Dc,backendName:"webgpu",kernelFunc:lW};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */class dW{constructor(e){this.variableNames=[],this.outputShape=[],this.uniforms="start : f32, step : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=[e],this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="linSpace"}getUserCode(){return` + ${re("index")} { + if (index < uniforms.size) { + setOutputAtIndex(index, uniforms.start + f32(index) * uniforms.step); + } + } + `}}/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */function pW(n){const{backend:e,attrs:t}=n,{start:r,stop:s,num:a}=t,o=(s-r)/(a-1),i=new dW(a),l=[{type:"float32",data:[r]},{type:"float32",data:[o]}];return e.runWebGPUProgram(i,[],"float32",l)}const hW={kernelName:Fi,backendName:"webgpu",kernelFunc:pW};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const fW=We({opType:ne.LOG,cpuKernelImpl:iM}),mW={kernelName:Pc,backendName:"webgpu",kernelFunc:fW};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */const gW=We({opType:ne.LOG1P}),yW={kernelName:Fc,backendName:"webgpu",kernelFunc:gW};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const bW=xt({opType:ve.LOGICAL_AND,dtype:"bool"}),wW={kernelName:Oc,backendName:"webgpu",kernelFunc:bW};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const xW=We({opType:ne.LOGICAL_NOT}),vW={kernelName:Mc,backendName:"webgpu",kernelFunc:xW};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */const SW=xt({opType:ve.LOGICAL_OR}),IW={kernelName:Lc,backendName:"webgpu",kernelFunc:SW};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */const Sb=` + var powValue = 0.0; + let basis = uniforms.bias + uniforms.alpha * sum; + if (uniforms.beta == 0.5) { + powValue = inverseSqrt(basis); + } else if (uniforms.beta == 1.0) { + powValue = 1.0 / basis; + } else { + powValue = exp(log(basis) * (-uniforms.beta)); + } +`;class kW{constructor(e){this.outputShape=[],this.variableNames=["x"],this.uniforms="radius : i32, bias : f32, alpha : f32, beta : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="lrn"}getUserCode(){return` + ${re("index")} { + if (index < uniforms.size) { + let coords = getOutputCoords(); + let b = coords[0]; + let r = coords[1]; + let c = coords[2]; + let d = coords[3]; + + let x = getX(b, r, c, d); + var sum = 0.0; + for (var i = -uniforms.radius; i <= uniforms.radius; i = i + 1) { + let idx = d + i; + if (idx >= 0 && idx < uniforms.xShape[3]) { + let z = getX(b, r, c, idx); + sum = sum + z * z; + } + } + ${Sb} + + setOutputAtIndex(index, x * powValue); + } + } + `}}class _W{constructor(e,t){this.outputShape=[],this.variableNames=["x"],this.uniforms="radius : i32, bias : f32, alpha : f32, beta : f32,",this.workgroupSize=[256,1,1],this.maxAllowRadius=16,$(t<=this.maxAllowRadius,()=>`Radius must be less than or equal to ${this.maxAllowRadius}, current radius is ${t}`),this.outputShape=e,this.elementsPerWorkgroup=this.workgroupSize[0]-2*this.maxAllowRadius,this.dispatchLayout={x:[3],y:[2],z:[0,1]},this.dispatch=se(this.dispatchLayout,this.outputShape,[this.elementsPerWorkgroup,this.workgroupSize[1],this.workgroupSize[2]]),this.shaderKey="lrn_shared"}getUserCode(){return` + var lrnSub: array; + const elementsPerWorkgroup = ${this.elementsPerWorkgroup}; + const maxAllowRadius = ${this.maxAllowRadius}; + + ${re()} { + let localDepth = i32(localId.x); + let workgroupDepth = i32(workgroupId.x) * elementsPerWorkgroup; + let xDepth = workgroupDepth + localDepth - maxAllowRadius; + let b = i32(globalId.z) / uniforms.xShape[1]; + let r = i32(globalId.z) - b * uniforms.xShape[1]; + let c = i32(globalId.y); + let d = workgroupDepth + localDepth; + + var x = 0.0; + if (xDepth >= 0 && xDepth < uniforms.xShape[3]) { + x = getX(b, r, c, xDepth); + } + lrnSub[localDepth] = x; + workgroupBarrier(); + + if (localDepth < elementsPerWorkgroup && d < uniforms.outShape[3]) { + var sum = 0.0; + let index = localDepth + maxAllowRadius; + for (var i = -uniforms.radius; i <= uniforms.radius; i = i + 1) { + let z = lrnSub[index + i]; + sum = sum + z * z; + } + ${Sb} + + setOutputAtCoords(b, r, c, d, lrnSub[index] * powValue); + } + } `}}/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */function CW(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{depthRadius:a,bias:o,alpha:i,beta:l}=r;let c;a>16?c=new kW(s.shape):c=new _W(s.shape,a);const u=[{type:"int32",data:[a]},{type:"float32",data:[o]},{type:"float32",data:[i]},{type:"float32",data:[l]}];return t.runWebGPUProgram(c,[s],s.dtype,u)}const NW={kernelName:Oi,backendName:"webgpu",kernelFunc:CW};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */class $W{constructor(e){this.outputShape=[],this.variableNames=["inputImage","outputImage","dy"],this.uniforms="depthRadius : i32, bias : f32, alpha : f32, beta : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="lrn_grad"}getUserCode(){return` + ${re("index")} { + if (index < uniforms.size) { + let coords = getOutputCoords(); + let b = coords[0]; + let r = coords[1]; + let c = coords[2]; + + let MIN_DEPTH_BEGIN = 0; + let MAX_DEPTH_END = uniforms.outShape[3]; + var result = 0.0; + for (var d = MIN_DEPTH_BEGIN; d < MAX_DEPTH_END; d++) { + let depthBegin = max(MIN_DEPTH_BEGIN, d - uniforms.depthRadius); + let depthEnd = min(MAX_DEPTH_END, d + uniforms.depthRadius + 1); + + var norm = 0.0; + for (var 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 = uniforms.alpha * norm + uniforms.bias; + + for (var k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; k++) { + if (k < depthBegin) { + continue; + } else if (k >= depthBegin && k < depthEnd) { + var dyi = -2.0 * uniforms.alpha * uniforms.beta + * getInputImage(b, r, c, k) * getOutputImage(b, r, c, d) / norm; + if (k == d) { + dyi += pow(norm, -1.0 * uniforms.beta); + } + if (k == coords[3]) { + dyi *= getDy(b, r, c, d); + result += dyi; + } + } else { + break; + } + } + } + + setOutputAtIndex(index, result); + } + } + `}}/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */function TW(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,y:a,dy:o}=e,{depthRadius:i,bias:l,alpha:c,beta:u}=r,d=new $W(s.shape),p=[{type:"int32",data:[i]},{type:"float32",data:[l]},{type:"float32",data:[c]},{type:"float32",data:[u]}];return t.runWebGPUProgram(d,[s,a,o],s.dtype,p)}const EW={kernelName:zc,backendName:"webgpu",kernelFunc:TW};/** + * @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. + * ============================================================================= + */const AW=xt({opType:ve.MAX,cpuKernelImpl:lM}),RW={kernelName:Bc,backendName:"webgpu",kernelFunc:AW};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function DW(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=r,u=Nn(s.shape,a,o,1,i,l);return cb(s,u,"max",t)}const PW={kernelName:Li,backendName:"webgpu",kernelFunc:DW};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */function FW(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{filterSize:a,strides:o,pad:i,dataFormat:l,dimRoundingMode:c}=r,u=[1,1,1],d=Pr(s.shape,a,o,u,i,c,l),p=new Zd(d,"max"),f=[{type:"int32",data:[d.strideDepth,d.strideHeight,d.strideWidth]},{type:"int32",data:[d.padInfo.front,d.padInfo.top,d.padInfo.left]},{type:"int32",data:[d.inDepth,d.inHeight,d.inWidth]},{type:"int32",data:[d.effectiveFilterDepth,d.effectiveFilterHeight,d.effectiveFilterWidth]}];return t.runWebGPUProgram(p,[s],s.dtype,f)}const OW={kernelName:Wc,backendName:"webgpu",kernelFunc:FW};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */class MW{constructor(e){this.variableNames=["dy","maxPos"],this.uniforms=`strides : vec2, pads : vec2, dilations : vec2, filterDims : vec2, + outHeight : i32, outWidth : i32`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.inShape,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="maxPool2DBackprop"}getUserCode(){return` + ${re("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let batch = coords[0]; + let d = coords[3]; + + let dyRCCorner = vec2(coords.yz) - uniforms.pads; + let dyRCorner = dyRCCorner.x; + let 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. + var dotProd = 0.0; + let lastIndex = uniforms.filterDims[0] * uniforms.filterDims[1] - 1; + for (var wR = 0; wR < uniforms.filterDims[0]; wR += uniforms.dilations[0]) { + let dyR = f32(dyRCorner + wR) / f32(uniforms.strides[0]); + + if (dyR < 0.0 || dyR >= f32(uniforms.outHeight) || fract(dyR) > 0.0) { + continue; + } + let idyR = i32(dyR); + + for (var wC = 0; wC < uniforms.filterDims[1]; wC += uniforms.dilations[1]) { + let dyC = f32(dyCCorner + wC) / f32(uniforms.strides[1]); + + if (dyC < 0.0 || dyC >= f32(uniforms.outWidth) || fract(dyC) > 0.0) { + continue; + } + let idyC = i32(dyC); + + let dyValue = getDy(batch, idyR, idyC, d); + let maxPosValue = lastIndex - i32(getMaxPos(batch, idyR, idyC, d)); + + // Get the current value, check it against the value from the + // position matrix. + let curPosValue = wR * uniforms.filterDims[1] + wC; + let mask = select(0.0, 1.0, maxPosValue == curPosValue); + dotProd += dyValue * mask; + } + } + setOutputAtIndex(index, dotProd); + } + } + `}}class LW{constructor(e){this.variableNames=["dy","maxPos"],this.uniforms=`strides : vec3, pads : vec3, filterDims : vec3, + outDepth : i32, outHeight : i32, outWidth : i32`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.inShape,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="maxPool3DBackprop"}getUserCode(){return` + ${re("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let batch = coords.x; + let ch = coords.u; + + let dyCorner = vec3(coords.y, coords.z, coords.w) - uniforms.pads; + let dyDCorner = dyCorner.x; + let dyRCorner = dyCorner.y; + let 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. + var dotProd = 0.0; + let lastIndex = uniforms.filterDims[0] * uniforms.filterDims[1] * uniforms.filterDims[2] - 1; + + for (var wD = 0; wD < uniforms.filterDims[0]; wD++) { + let dyD = f32(dyDCorner + wD) / f32(uniforms.strides[0]); + + if (dyD < 0.0 || dyD >= f32(uniforms.outDepth) || fract(dyD) > 0.0) { + continue; + } + let idyD = i32(dyD); + + for (var wR = 0; wR < uniforms.filterDims[1]; wR++) { + let dyR = f32(dyRCorner + wR) / f32(uniforms.strides[1]); + + if (dyR < 0.0 || dyR >= f32(uniforms.outHeight) || fract(dyR) > 0.0) { + continue; + } + let idyR = i32(dyR); + + for (var wC = 0; wC < uniforms.filterDims[2]; wC++) { + let dyC = f32(dyCCorner + wC) / f32(uniforms.strides[2]); + + if (dyC < 0.0 || dyC >= f32(uniforms.outWidth) || fract(dyC) > 0.0) { + continue; + } + let idyC = i32(dyC); + + let dyValue = getDy(batch, idyD, idyR, idyC, ch); + let maxPosValue = lastIndex - i32(getMaxPos(batch, idyD, idyR, idyC, ch)); + + // Get the current value, check it against the value from the + // position matrix. + let curPosValue = wD * uniforms.filterDims[1] * uniforms.filterDims[2] + wR * uniforms.filterDims[2] + wC; + let mask = select(0.0, 1.0, maxPosValue == curPosValue); + dotProd += dyValue * mask; + } + } + } + + setOutputAtIndex(index, dotProd); + } + } + `}}/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */function zW(n){const{inputs:e,backend:t,attrs:r}=n,{dy:s,input:a}=e,o=a,{filterSize:i,strides:l,pad:c,dimRoundingMode:u}=r,d=[1,1,1],p=Pr(o.shape,i,l,d,c,u),f=new Zd(p,"max",!0);let m=[{type:"int32",data:[p.strideDepth,p.strideHeight,p.strideWidth]},{type:"int32",data:[p.padInfo.front,p.padInfo.top,p.padInfo.left]},{type:"int32",data:[p.inDepth,p.inHeight,p.inWidth]},{type:"int32",data:[p.effectiveFilterDepth,p.effectiveFilterHeight,p.effectiveFilterWidth]}];const g=t.runWebGPUProgram(f,[o],"int32",m),b=new LW(p);m=[{type:"int32",data:[p.strideDepth,p.strideHeight,p.strideWidth]},{type:"int32",data:[p.effectiveFilterDepth-1-p.padInfo.front,p.effectiveFilterHeight-1-p.padInfo.top,p.effectiveFilterWidth-1-p.padInfo.left]},{type:"int32",data:[p.effectiveFilterDepth,p.effectiveFilterHeight,p.effectiveFilterWidth]},{type:"int32",data:[p.outDepth]},{type:"int32",data:[p.outHeight]},{type:"int32",data:[p.outWidth]}];const v=t.runWebGPUProgram(b,[s,g],o.dtype,m);return t.disposeData(g.dataId),v}const BW={kernelName:gf,backendName:"webgpu",kernelFunc:zW};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */function WW(n){const{inputs:e,backend:t,attrs:r}=n,{dy:s,input:a,output:o}=e,i=a;sb([a,o],"maxPoolGrad");const{filterSize:l,strides:c,pad:u,dimRoundingMode:d}=r,p=Nn(i.shape,l,c,1,u,d),f=new io(p,"max",!0);let m=[{type:"int32",data:[p.strideHeight,p.strideWidth]},{type:"int32",data:[p.padInfo.top,p.padInfo.left]},{type:"int32",data:[p.dilationHeight,p.dilationWidth]},{type:"int32",data:[p.inHeight,p.inWidth]},{type:"int32",data:[p.effectiveFilterHeight,p.effectiveFilterWidth]}];const g=t.runWebGPUProgram(f,[i],"int32",m),b=new MW(p);m=[{type:"int32",data:[p.strideHeight,p.strideWidth]},{type:"int32",data:[p.effectiveFilterHeight-1-p.padInfo.top,p.effectiveFilterWidth-1-p.padInfo.left]},{type:"int32",data:[p.dilationHeight,p.dilationWidth]},{type:"int32",data:[p.effectiveFilterHeight,p.effectiveFilterWidth]},{type:"int32",data:[p.outHeight]},{type:"int32",data:[p.outWidth]}];const v=t.runWebGPUProgram(b,[s,g],i.dtype,m);return t.disposeData(g.dataId),v}const VW={kernelName:mf,backendName:"webgpu",kernelFunc:WW};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */function UW(n){const{inputs:e,backend:t,attrs:r}=n,{filterSize:s,strides:a,pad:o,includeBatchInIndex:i}=r,{x:l}=e;$(l.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${l.shape.length}.`);const c=[1,1];$($n(a,c),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${c}'`);const u=Nn(l.shape,s,a,c,o),d=[{type:"int32",data:[u.strideHeight,u.strideWidth]},{type:"int32",data:[u.padInfo.top,u.padInfo.left]},{type:"int32",data:[u.dilationHeight,u.dilationWidth]},{type:"int32",data:[u.inHeight,u.inWidth]},{type:"int32",data:[u.effectiveFilterHeight,u.effectiveFilterWidth]}];let p=new io(u,"max",!1);const f=t.runWebGPUProgram(p,[l],l.dtype,d);p=new io(u,"max",!0,!0,i);const m=t.runWebGPUProgram(p,[l],"int32",d);return[f,m]}const HW={kernelName:Vc,backendName:"webgpu",kernelFunc:UW};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function GW(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{axis:a,keepDims:o}=r;return Ns(s,a,o,"min",t)}const jW={kernelName:Bi,backendName:"webgpu",kernelFunc:GW};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const qW=xt({opType:ve.MIN,cpuKernelImpl:cM}),KW={kernelName:Uc,backendName:"webgpu",kernelFunc:qW};/** + * @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. + * ============================================================================= + */class XW{constructor(e,t,r){this.uniforms="",this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=t.map((s,a)=>s[0]+e[a]+s[1]),this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.xShape=e,t.map((s,a)=>{this.uniforms+=` pad${a} : vec2,`}),this.offset=r==="reflect"?0:1,this.shaderKey=`mirrorPad_${r}`}getUserCode(){const e=this.xShape.length,t=this.xShape.map((c,u)=>`uniforms.pad${u}[0]`).join(","),r=this.xShape.map((c,u)=>`uniforms.pad${u}[0] + uniforms.xShape${e>1?`[${u}]`:""}`).join(","),s=e===1?"start":"start[i]",a=e===1?"end":"end[i]",o=e===1?"outC":"outC[i]",i=ft(e),l=e>1?["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,e):"coords";return` + ${re("index")} { + if (index < uniforms.size) { + let start = ${i}(${t}); + let end = ${i}(${r}); + var outC = getCoordsFromIndex(index); + for (var i = 0; i < ${e}; i = i + 1) { + if (${o} < ${s}) { + ${o} = ${s} * 2 - ${o} - ${this.offset}; + } else if(${o} >= ${a}) { + ${o} = (${a} - 1) * 2 - ${o} + ${this.offset}; + } + } + let coords = outC - start; + setOutputAtIndex(index, getX(${l})); + } + } + `}}/** + * @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. + * ============================================================================= + */const YW={kernelName:Wi,backendName:"webgpu",kernelFunc:({inputs:n,attrs:e,backend:t})=>{const{x:r}=n,{paddings:s,mode:a}=e,o=t,i=s.map(u=>({type:"int32",data:[u[0],u[1]]})),l=new XW(r.shape,s,a);return o.runWebGPUProgram(l,[r],r.dtype,i)}};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */const QW=xt({opType:ve.MOD}),ZW={kernelName:Hc,backendName:"webgpu",kernelFunc:QW};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */class JW{constructor(e,t){this.variableNames=["probs"],this.outputShape=[],this.uniforms="seed : f32, numOutcomes: i32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=[e,t],this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="multinomial"}getUserCode(){return` + //Based on the work of Dave Hoskins + //https://www.shadertoy.com/view/4djSRW + fn random (seed : f32, resultUV : vec2) -> f32 { + let HASHSCALE1 = 443.8975; + let p = resultUV * seed; + var p3 = fract(vec3(p.xyx) * HASHSCALE1); + p3 = p3 + dot(p3, p3.yzx + 19.19); + return fract((p3.x + p3.y) * p3.z); + } + + ${re("index")} { + if (index < uniforms.size) { + let coords = getOutputCoords(); + let batch = coords[0]; + + let resUV = vec2(f32(coords[1]) / f32(uniforms.outShape[1]), + f32(coords[0]) / f32(uniforms.outShape[0])); + let r = random(uniforms.seed, resUV); + var cdf = 0.0; + for (var i = 0; i < uniforms.numOutcomes - 1; i = i + 1) { + cdf = cdf + getProbs(batch, i); + + if (r < cdf) { + setOutputAtIndexI32(index, i); + return; + } + } + + // If no other event happened, last event happened. + setOutputAtIndexI32(index, uniforms.numOutcomes - 1); + } + } + `}}/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */class eV{constructor(e){this.variableNames=["logits"],this.outputShape=e,this.dispatchLayout=ie(this.outputShape),this.dispatch=[this.outputShape[0],1,1],this.outputShape[1]>=4096?this.workgroupSize=[256,1,1]:this.workgroupSize=[64,1,1],this.shaderKey="softmax"}getUserCode(){return` + var buf : array; + var rowMaxShared : f32; + var rowSumShared : f32; + const blockSize = ${this.workgroupSize[0]}; + ${re("index")} { + let row = index / blockSize; + let tid = i32(localId.x); + let cols = uniforms.outShape[1]; + + var threadMax = -3.402823e+38f; + for (var col = tid; col < cols; col += blockSize) { + let value = getLogits(row, col); + threadMax = max(threadMax, value); + } + if (tid < cols) { + buf[tid] = threadMax; + } + workgroupBarrier(); + + var reduceSize = min(cols, blockSize); + for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { + reduceSize = currSize + (reduceSize & 1); + if (tid < currSize) { + buf[tid] = max(buf[tid], buf[tid + reduceSize]); + } + workgroupBarrier(); + } + + if (tid == 0) { + rowMaxShared = buf[0]; + } + workgroupBarrier(); + + var threadSum = 0.0; + for (var col = tid; col < cols; col += blockSize) { + let subExp = exp(getLogits(row, col) - rowMaxShared); + threadSum += subExp; + } + buf[tid] = threadSum; + workgroupBarrier(); + + for (var currSize = blockSize >> 1; currSize > 0; currSize = currSize >> 1) { + if (tid < currSize) { + buf[tid] = buf[tid] + buf[tid + currSize]; + } + workgroupBarrier(); + } + + if (tid == 0) { + rowSumShared = buf[0]; + } + workgroupBarrier(); + + for (var col = tid; col < cols; col += blockSize) { + let value = exp(getLogits(row, col) - rowMaxShared) / rowSumShared; + setOutputAtCoords(row, col, value); + } + } + `}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function Ib(n){const{inputs:e,backend:t,attrs:r}=n,{logits:s}=e,{dim:a}=r,o=de({inputs:{x:s},backend:t,attrs:{shape:[q(s.shape)/s.shape[a],s.shape[a]]}}),i=new eV(o.shape),l=t.runWebGPUProgram(i,[o],s.dtype),c=de({inputs:{x:l},backend:t,attrs:{shape:s.shape}});return t.disposeData(o.dataId),t.disposeData(l.dataId),c}const tV={kernelName:nu,backendName:"webgpu",kernelFunc:Ib};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */function nV(n){const{inputs:e,backend:t,attrs:r}=n,{logits:s}=e,{numSamples:a,seed:o,normalized:i}=r,l=i?s:Ib({inputs:{logits:s},backend:t,attrs:{dim:s.shape.length-1}}),c=l.shape[0],u=l.shape[1],d=new JW(c,a),p=[{type:"float32",data:[o]},{type:"int32",data:[u]}],f=t.runWebGPUProgram(d,[l],"int32",p);return i||t.disposeData(l.dataId),f}const rV={kernelName:Vi,backendName:"webgpu",kernelFunc:nV};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function sV(n){const{inputs:e,backend:t}=n,{x:r}=e;if(t.shouldExecuteOnCPU([r])){const a=t.tensorMap.get(r.dataId),[o,i]=pM(a.values,r.shape,r.dtype);return t.makeTensorInfo(i,r.dtype,o)}const s=new ya(r.shape,ne.NEG);return t.runWebGPUProgram(s,[r],r.dtype)}const aV={kernelName:jc,backendName:"webgpu",kernelFunc:sV};/** + * @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. + * ============================================================================= + */function oV(n){console.warn("tf.nonMaxSuppression() in webgpu locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:e,backend:t,attrs:r}=n,{boxes:s,scores:a}=e,{maxOutputSize:o,iouThreshold:i,scoreThreshold:l}=r,c=t.readSync(s.dataId),u=t.readSync(a.dataId),{selectedIndices:d}=Bm(c,u,o,i,l);return t.makeTensorInfo([d.length],"int32",new Int32Array(d))}const iV={kernelName:Ui,backendName:"webgpu",kernelFunc:oV};/** + * @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. + * ============================================================================= + */function uV(n){console.warn("tf.nonMaxSuppression() in webgpu locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:e,backend:t,attrs:r}=n,{boxes:s,scores:a}=e,{maxOutputSize:o,iouThreshold:i,scoreThreshold:l,softNmsSigma:c}=r,u=t.readSync(s.dataId),d=t.readSync(a.dataId),p=o,f=i,m=l,g=c,{selectedIndices:b,selectedScores:v}=Wm(u,d,p,f,m,g);return[t.makeTensorInfo([b.length],"int32",new Int32Array(b)),t.makeTensorInfo([v.length],"float32",new Float32Array(v))]}const lV={kernelName:Hi,backendName:"webgpu",kernelFunc:uV};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */class cV{constructor(e,t){this.variableNames=["x"],this.uniforms="onValue : f32, offValue : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=[e,t],this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="onehot"}getUserCode(){return` + ${re("index")} { + if(index < uniforms.size) { + let coords = getCoordsFromIndex(index); + setOutputAtIndex(index, mix(uniforms.offValue, uniforms.onValue, + f32(i32(round(getX(coords.x))) == coords.y))); + } + } + `}}/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */function dV(n){const{inputs:e,backend:t,attrs:r}=n,{indices:s}=e,{dtype:a,depth:o,onValue:i,offValue:l}=r,c=q(s.shape),u=new cV(c,o),d=de({inputs:{x:s},backend:t,attrs:{shape:[c]}}),p=[{type:"float32",data:[i]},{type:"float32",data:[l]}],f=t.runWebGPUProgram(u,[d],a,p);t.disposeData(d.dataId);const m=[...s.shape,o],g=de({inputs:{x:f},backend:t,attrs:{shape:m}});return t.disposeData(f.dataId),g}const pV={kernelName:Gi,backendName:"webgpu",kernelFunc:dV};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function ui(n){const{inputs:e,backend:t}=n,{x:r}=e;if(r.dtype==="complex64"){const s=fo({inputs:{input:r},backend:t}),a=ui({inputs:{x:s},backend:t}),o=_u({inputs:{input:r},backend:t}),i=ui({inputs:{x:o},backend:t}),l=Cs({inputs:{real:a,imag:i},backend:t});return t.disposeData(s.dataId),t.disposeData(a.dataId),t.disposeData(o.dataId),t.disposeData(i.dataId),l}else return Wt({attrs:{shape:r.shape,dtype:r.dtype,value:r.dtype==="string"?"":0},backend:t})}const hV={kernelName:Nd,backendName:"webgpu",kernelFunc:ui};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function kb(n){const{inputs:e,backend:t}=n,{x:r}=e;if(r.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(r.dtype==="complex64"){const s=fo({inputs:{input:r},backend:t}),a=kb({inputs:{x:s},backend:t}),o=_u({inputs:{input:r},backend:t}),i=ui({inputs:{x:o},backend:t}),l=Cs({inputs:{real:a,imag:i},backend:t});return t.disposeData(s.dataId),t.disposeData(a.dataId),t.disposeData(o.dataId),t.disposeData(i.dataId),l}else return Wt({attrs:{shape:r.shape,dtype:r.dtype,value:1},backend:t})}const fV={kernelName:Xc,backendName:"webgpu",kernelFunc:kb};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function mV(n){const{inputs:e,backend:t,attrs:r}=n,{axis:s}=r;if(e.length===1)return Bl({inputs:{input:e[0]},backend:t,attrs:{dim:s}});const a=e[0].shape,o=e[0].dtype;e.forEach(u=>{Yt(a,u.shape,"All tensors passed to stack must have matching shapes"),$(o===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});const i=[],l=e.map(u=>{const d=Bl({inputs:{input:u},backend:t,attrs:{dim:s}});return i.push(d),d}),c=hb({inputs:l,backend:t,attrs:{axis:s}});return i.forEach(u=>t.disposeData(u.dataId)),c}const gV={kernelName:Yc,backendName:"webgpu",kernelFunc:mV};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function _b(n,e=!1){const t=n.length,r=ft(t),s=n.map((d,p)=>`uniforms.pad${p}[0]`).join(","),a=n.map((d,p)=>`uniforms.pad${p}[0] + uniforms.xShape${t>1?`[${p}]`:""}`).join(","),o=t>1?`${r}(${s})`:`${s}`,i=t>1?`${r}(${a})`:`${a}`,l=t>1?"any(paddedCoords < start)":"paddedCoords < start",c=t>1?"any(paddedCoords >= end)":"paddedCoords >= end",u=t>1?["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,t):"coords";return` + let start = ${o}; + let end = ${i}; + if (${l} || ${c}) { + setOutputAtIndex(index, ${e?0:"uniforms.constantValue"}); + } else { + let coords = paddedCoords - start; + setOutputAtIndex(index, getX(${u})); + } + `}class yV{constructor(e,t){this.variableNames=["x"],this.uniforms="constantValue : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=t.map((r,s)=>r[0]+e[s]+r[1]),this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),t.map((r,s)=>{this.uniforms+=` pad${s} : vec2,`}),this.xShape=e,this.shaderKey="pad"}getUserCode(){return` + ${re("index")} { + if (index < uniforms.size) { + let paddedCoords = getCoordsFromIndex(index); + ${_b(this.xShape)} + } + } + `}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const bV=n=>{const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{paddings:a,constantValue:o}=r;if(a.every(c=>Vt(c,[0,0])))return Xt({inputs:{x:s},backend:t});if(q(s.shape)===0){const c=a.map((u,d)=>u[0]+s.shape[d]+u[1]);return Wt({backend:t,attrs:{shape:c,value:o,dtype:s.dtype}})}const i=[{type:"float32",data:[o]}];a.map(c=>i.push({type:"int32",data:[c[0],c[1]]}));const l=new yV(s.shape,a);return t.runWebGPUProgram(l,[s],s.dtype,i)},wV={kernelName:ji,backendName:"webgpu",kernelFunc:bV};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const xV=xt({opType:ve.POW}),vV={kernelName:Qc,backendName:"webgpu",kernelFunc:xV};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function SV(n){const{inputs:e,backend:t}=n,{x:r,alpha:s}=e,a=new oi(ve.PRELU,r.shape,s.shape);return t.runWebGPUProgram(a,[r,s],"float32")}const IV={kernelName:qi,backendName:"webgpu",kernelFunc:SV};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function kV(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{axis:a,keepDims:o}=r;return Ns(s,a,o,"prod",t)}const _V={kernelName:Ki,backendName:"webgpu",kernelFunc:kV};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const CV=n=>{const{backend:e,attrs:t}=n,{start:r,stop:s,step:a,dtype:o}=t,i=mM(r,s,a,o);return e.makeTensorInfo([i.length],o,i)},NV={kernelName:Zc,backendName:"webgpu",kernelFunc:CV};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const $V=xt({opType:ve.DIV}),TV={kernelName:mc,backendName:"webgpu",kernelFunc:$V};/** + * @license + * Copyright 2022 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. + * ============================================================================= + */const EV=We({opType:ne.RECIPROCAL}),AV={kernelName:Jc,backendName:"webgpu",kernelFunc:EV};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const RV=We({opType:ne.RELU}),DV={kernelName:ed,backendName:"webgpu",kernelFunc:RV};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const PV=We({opType:ne.RELU6}),FV={kernelName:sd,backendName:"webgpu",kernelFunc:PV};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class OV{constructor(e,t,r){this.variableNames=["x"],this.uniforms="adjustHeightWidth : vec2, halfPixelCenters : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=[e[0],t,r,e[3]],this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="resizeBilinear"}getUserCode(){return` + ${re("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let b = coords[0]; + let d = coords[3]; + let rc = coords.yz; + + let effectiveInSize = vec2( + f32(uniforms.xShape.y) - uniforms.adjustHeightWidth[0], + f32(uniforms.xShape.z) - uniforms.adjustHeightWidth[1]); + + let effectiveOutSize = vec2( + f32(uniforms.outShape.y) - uniforms.adjustHeightWidth[0], + f32(uniforms.outShape.z) - uniforms.adjustHeightWidth[1]); + + let effectiveInputOverOutputRatioRC = + effectiveInSize / effectiveOutSize; + + // Fractional source index + let sourceFracIndexRC = + (vec2(rc) + vec2(uniforms.halfPixelCenters)) * + effectiveInputOverOutputRatioRC - vec2(uniforms.halfPixelCenters); + + // Compute the four integer indices. + let sourceFloorRC = vec2(sourceFracIndexRC); + let sourceCeilRC = vec2( + min(vec2(uniforms.xShape.yz) - vec2(1.0), ceil(sourceFracIndexRC))); + + let topLeft = getX(b, sourceFloorRC.x, sourceFloorRC.y, d); + let bottomLeft = getX(b, sourceCeilRC.x, sourceFloorRC.y, d); + let topRight = getX(b, sourceFloorRC.x, sourceCeilRC.y, d); + let bottomRight = getX(b, sourceCeilRC.x, sourceCeilRC.y, d); + + let fracRC = sourceFracIndexRC - vec2(sourceFloorRC); + + let top = topLeft + (topRight - topLeft) * fracRC.y; + let bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y; + let newValue = top + (bottom - top) * fracRC.x; + + setOutputAtIndex(index, newValue); + } + } + `}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function MV(n){const{inputs:e,backend:t,attrs:r}=n,{images:s}=e,{alignCorners:a,size:o,halfPixelCenters:i}=r,[l,c]=o,u=a&&l>1?1:0,d=a&&c>1?1:0,f=[{type:"float32",data:[u,d]},{type:"float32",data:[i?.5:0]}],m=new OV(s.shape,l,c);return t.runWebGPUProgram(m,[s],"float32",f)}const LV={kernelName:Yi,backendName:"webgpu",kernelFunc:MV};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */class zV{constructor(e,t){this.variableNames=["dy"],this.uniforms=`effectiveXSize : vec2, effectiveYSize : vec2, heightScale : f32, widthScale : f32, + invHeightScale : f32, invWidthScale : f32, winHeight : i32, winWidth : i32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.alignCorners=t,this.shaderKey=`resizeBilinearBackprop_${t}`}getUserCode(){return` + ${re("index")} { + if (index < uniforms.size) { + let coords = getOutputCoords(); + let b = coords[0]; + let d = coords[3]; + let r = coords[1]; + let c = coords[2]; + + var accumulator = 0.0; + + // Compute bounds for where in dy we will look + let startRLerp = floor(f32(r) * uniforms.invHeightScale); + let startDyR = i32(startRLerp - f32(uniforms.winHeight / 2)); + + let startCLerp = floor(f32(c) * uniforms.invWidthScale); + let startDyC = i32(startCLerp - f32(uniforms.winWidth / 2)); + + // Loop over dy + for (var dyROffset = 0; dyROffset < uniforms.winHeight; dyROffset++) { + let dyR = startDyR + dyROffset; + + // Guard against the window exceeding the bounds of dy + if (dyR < 0 || dyR >= uniforms.dyShape[1]) { + continue; + } + + for (var dyCOffset = 0; dyCOffset < uniforms.winWidth; dyCOffset++) { + let dyC = startDyC + dyCOffset; + + // Guard against the window exceeding the bounds of dy + if (dyC < 0 || dyC >= uniforms.dyShape[2]) { + continue; + } + + let dxR = f32(dyR) * uniforms.heightScale; + let topDxRIndex = i32(floor(dxR)); + let bottomDxRIndex = i32(min(ceil(dxR), f32(uniforms.outShape[1] - 1))); + let dxRLerp = dxR - f32(topDxRIndex); + let inverseDxRLerp = 1.0 - dxRLerp; + + let dxC = f32(dyC) * uniforms.widthScale; + let leftDxCIndex = i32(floor(dxC)); + let rightDxCIndex = i32(min(ceil(dxC), f32(uniforms.outShape[2] - 1))); + let dxCLerp = dxC - f32(leftDxCIndex); + let 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 + + setOutputAtIndex(index, accumulator); + } + } + `}}/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */function BV(n){const{inputs:e,backend:t,attrs:r}=n,{images:s,dy:a}=e,{alignCorners:o}=r,[,i,l]=s.shape,[,c,u]=a.shape,d=[o&&c>1?i-1:i,o&&u>1?l-1:l],p=[o&&c>1?c-1:c,o&&u>1?u-1:u],f=d[0]/p[0],m=d[1]/p[1],g=1/f,b=1/m,v=Math.ceil(g)*2+2,I=Math.ceil(b)*2+2,S=new zV(s.shape,o),C=[{type:"int32",data:d},{type:"int32",data:p},{type:"float32",data:[f]},{type:"float32",data:[m]},{type:"float32",data:[g]},{type:"float32",data:[b]},{type:"int32",data:[v]},{type:"int32",data:[I]}];return t.runWebGPUProgram(S,[a],a.dtype,C)}const WV={kernelName:rd,backendName:"webgpu",kernelFunc:BV};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */class VV{constructor(e,t,r,s){this.variableNames=["x"],this.uniforms="adjustHeightWidth : vec2, roundBase : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=[e[0],t,r,e[3]],this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.halfPixelCenters=s,this.shaderKey=`resizeNearest_${s}`}getUserCode(){let e;return this.halfPixelCenters?e="max((vec2(rc) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":e="vec2(rc) * effectiveInputOverOutputRatioRC",` + ${re("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let b = coords[0]; + let d = coords[3]; + let rc = coords.yz; + + let effectiveInSize = vec2( + f32(uniforms.xShape.y) - uniforms.adjustHeightWidth[0], + f32(uniforms.xShape.z) - uniforms.adjustHeightWidth[1]); + + let effectiveOutSize = vec2( + f32(uniforms.outShape.y) - uniforms.adjustHeightWidth[0], + f32(uniforms.outShape.z) - uniforms.adjustHeightWidth[1]); + + let effectiveInputOverOutputRatioRC = + effectiveInSize / effectiveOutSize; + + // Fractional source index + let sourceFracIndexRC = ${e}; + + // Compute the coordinators of nearest neighbor point. + let inputShapeRC = vec2(f32(uniforms.xShape.y), f32(uniforms.xShape.z)); + let sourceNearestRC = vec2( + min(inputShapeRC - 1.0, floor(sourceFracIndexRC + uniforms.roundBase))); + let newValue = getX(b, sourceNearestRC.x, sourceNearestRC.y, d); + + setOutputAtIndex(index, newValue); + } + } + `}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function UV(n){const{inputs:e,backend:t,attrs:r}=n,{images:s}=e,{alignCorners:a,halfPixelCenters:o,size:i}=r,[l,c]=i,u=a&&l>1?1:0,d=a&&c>1?1:0,f=[{type:"float32",data:[u,d]},{type:"float32",data:[a?.5:0]}],m=new VV(s.shape,l,c,o);return t.runWebGPUProgram(m,[s],s.dtype,f)}const HV={kernelName:Xi,backendName:"webgpu",kernelFunc:UV};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */class GV{constructor(e,t){this.variableNames=["dy"],this.uniforms=`effectiveXSize : vec2, effectiveYSize : vec2, invHeightScale : f32, invWidthScale : f32, + winHeight : i32, winWidth : i32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.alignCorners=t,this.shaderKey=`resizeNearestNeigborBackprop_${t}`}getUserCode(){return` + ${re("index")} { + if (index < uniforms.size) { + let coords = getOutputCoords(); + let b = coords[0]; + let d = coords[3]; + let r = coords[1]; + let c = coords[2]; + + var accumulator = 0.0; + + // Compute bounds for where in dy we will look + let startRLerp = floor(f32(r) * uniforms.invHeightScale); + let startDyR = i32(floor(startRLerp - f32(uniforms.winHeight / 2))); + + let startCLerp = floor(f32(c) * uniforms.invWidthScale); + let startDyC = i32(floor(startCLerp - f32(uniforms.winWidth / 2))); + + // Loop over dy + for (var dyROffset = 0; dyROffset < uniforms.winHeight; dyROffset++) { + let dyR = startDyR + dyROffset; + + // Guard against the window exceeding the bounds of dy + if (dyR < 0 || dyR >= uniforms.dyShape[1]) { + continue; + } + + for (var dyCOffset = 0; dyCOffset < uniforms.winWidth; dyCOffset++) { + let dyC = startDyC + dyCOffset; + + // Guard against the window exceeding the bounds of dy + if (dyC < 0 || dyC >= uniforms.dyShape[2]) { + continue; + } + + let sourceFracRow = f32(uniforms.effectiveXSize[0]) * + (f32(dyR) / f32(uniforms.effectiveYSize[0])); + + let sourceFracCol = f32(uniforms.effectiveXSize[1]) * + (f32(dyC) / f32(uniforms.effectiveYSize[1])); + + let sourceNearestRow = + i32(min(f32(uniforms.outShape[1] - 1), + ${this.alignCorners?"floor(sourceFracRow + 0.5)":"floor(sourceFracRow)"})); + + let sourceNearestCol = + i32(min(f32(uniforms.outShape[2] - 1), + ${this.alignCorners?"floor(sourceFracCol + 0.5)":"floor(sourceFracCol)"})); + + if (r == sourceNearestRow && c == sourceNearestCol) { + accumulator += getDy(b, dyR, dyC, d); + } + } + } + // End loop over dy + + setOutputAtIndex(index, accumulator); + } + } + `}}/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */function jV(n){const{inputs:e,backend:t,attrs:r}=n,{images:s,dy:a}=e,{alignCorners:o}=r,[,i,l]=s.shape,[,c,u]=a.shape,d=[o&&c>1?i-1:i,o&&u>1?l-1:l],p=[o&&c>1?c-1:c,o&&u>1?u-1:u],f=d[0]/p[0],m=d[1]/p[1],g=1/f,b=1/m,v=Math.ceil(g)*2+2,I=Math.ceil(b)*2+2,S=new GV(s.shape,o),C=[{type:"int32",data:d},{type:"int32",data:p},{type:"float32",data:[g]},{type:"float32",data:[b]},{type:"int32",data:[v]},{type:"int32",data:[I]}];return t.runWebGPUProgram(S,[a],a.dtype,C)}const qV={kernelName:nd,backendName:"webgpu",kernelFunc:jV};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */class KV{constructor(e){this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.uniforms=" axis : vec4,",this.shaderKey="reverse"}getUserCode(){return` + + // Using uniform variables as judging conditions, so the function has + // coherent execution within all threads. + fn getReverseCoords(coords : vec4) -> vec4 { + var reverseCoords = coords; + if (uniforms.axis[0] == 1) { + reverseCoords[0] = uniforms.xShape[0] - coords[0] - 1; + } + if (uniforms.axis[1] == 1) { + reverseCoords[1] = uniforms.xShape[1] - coords[1] - 1; + } + if (uniforms.axis[2] == 1) { + reverseCoords[2] = uniforms.xShape[2] - coords[2] - 1; + } + if (uniforms.axis[3] == 1) { + reverseCoords[3] = uniforms.xShape[3] - coords[3] - 1; + } + + return reverseCoords; + } + + ${re("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let reverseCoords = getReverseCoords(coords); + setOutputAtIndex(index, getX(reverseCoords[0], + reverseCoords[1], reverseCoords[2], reverseCoords[3])); + } + } + `}}/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */function XV(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{dims:a}=r,o=s.shape.length;if(o===0)return Xt({inputs:{x:s},backend:t});const i=s.shape,l=[1,1,1,1];i.forEach((b,v)=>{const I=v+4-o;l[I]=b});const c=$t(a,s.shape),u=[0,0,0,0];c.forEach(b=>{const v=b+4-o;u[v]=1});const d=[{type:"int32",data:u}],p=de({inputs:{x:s},backend:t,attrs:{shape:l}}),f=new KV(l),m=t.runWebGPUProgram(f,[p],p.dtype,d);t.disposeData(p.dataId);const g=de({inputs:{x:m},backend:t,attrs:{shape:i}});return t.disposeData(m.dataId),g}const YV={kernelName:Qi,backendName:"webgpu",kernelFunc:XV};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */class QV{constructor(e,t){this.outputShape=[],this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.uniforms=`centerX : f32, centerY : f32, sinRadians : f32, + cosRadians : f32,`,this.shaderKey="rotate",this.outputShape=e,typeof t=="number"?(this.uniforms+=" fillValue : f32,",this.fillSnippet="var outputValue = uniforms.fillValue;",this.shaderKey+="_float"):(this.uniforms+=" fillValue : vec3,",this.fillSnippet="var outputValue = uniforms.fillValue[coords[3]];",this.shaderKey+="_vec3")}getUserCode(){return` + ${re("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let coordXFloat = (f32(coords[2]) - uniforms.centerX) * + uniforms.cosRadians - (f32(coords[1]) - uniforms.centerY) * + uniforms.sinRadians; + let coordYFloat = (f32(coords[2]) - uniforms.centerX) * + uniforms.sinRadians + (f32(coords[1]) - uniforms.centerY) * + uniforms.cosRadians; + let coordX = i32(round(coordXFloat + uniforms.centerX)); + let coordY = i32(round(coordYFloat + uniforms.centerY)); + ${this.fillSnippet} + if(coordX >= 0 && coordX < uniforms.xShape[2] && coordY >= 0 && + coordY < uniforms.xShape[1]) { + outputValue = getX(coords[0], coordY, coordX, coords[3]); + } + setOutputAtIndex(index, outputValue); + } + } + `}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const ZV={kernelName:uu,backendName:"webgpu",kernelFunc:({inputs:n,attrs:e,backend:t})=>{const{image:r}=n,{radians:s,fillValue:a,center:o}=e,i=t,l=new QV(r.shape,a),[c,u]=rg(o,r.shape[1],r.shape[2]),d=[{type:"float32",data:[c]},{type:"float32",data:[u]},{type:"float32",data:[Math.sin(s)]},{type:"float32",data:[Math.cos(s)]}];return typeof a=="number"?d.push({type:"float32",data:[Number.parseFloat(a.toFixed(2))]}):d.push({type:"float32",data:a}),i.runWebGPUProgram(l,[r],r.dtype,d)}};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */const JV=We({opType:ne.ROUND}),e4={kernelName:ad,backendName:"webgpu",kernelFunc:JV};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const t4=We({opType:ne.RSQRT,cpuKernelImpl:gM}),n4={kernelName:od,backendName:"webgpu",kernelFunc:t4};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */class Ga{constructor(e,t,r,s,a,o,i,l=!0){this.variableNames=["updates","indices"],this.workgroupSize=[64,1,1],this.atomic=!0,this.outputShape=o,this.type=i,this.sumDupeIndices=l,this.dispatchLayout=ie(e),this.dispatch=se(this.dispatchLayout,e,this.workgroupSize),this.sliceDimGreaterThanOne=t>1,this.shaderKey=`scatter_${r}_${s}_${this.sliceDimGreaterThanOne}_${i}_${l}_${a.length}`;const c=ft(a.length);this.uniforms=`sliceDim : i32, strides: ${c}, updatesSize: i32,`,this.updatesRank=s,this.indicesRank=r}getUserCode(){let e="";this.indicesRank===1?e="coords[0]":this.indicesRank===2&&(e="coords[0], j");const t=`getIndices(${e})`,r=this.sliceDimGreaterThanOne?"uniforms.strides[j]":"uniforms.strides";let s="",a="";this.dispatchLayout.x.length===1?(s="flattenedIndex",a=` + fn getUpdatesCoordsFromFlatIndex(index : i32) -> i32 { + return index; + } + `):this.dispatchLayout.x.length===2&&(s="vec2(flattenedIndex, coords[1])",a=` + fn getUpdatesCoordsFromFlatIndex(index : i32) -> vec2 { + // N.B. |updates| could be a scalar tensor, conceptually representing a + // 2D tensor with all values equal to that. By design, its size must be + // the same as |outShape[1]| in one dimension, and |indicesShape[0]| + // gives the other. + let sliceSize = uniforms.outShape[1]; + let d0 = index / sliceSize; + let d1 = index - d0 * sliceSize; + return vec2(d0, d1); + } + `);const i=`getUpdates(${Array.from({length:this.updatesRank},(c,u)=>`coords[${u}]`).join(", ")})`;return` + ${a} + ${re("index")} { + if (index < uniforms.updatesSize) { + let coords = getUpdatesCoordsFromFlatIndex(index); + var flattenedIndex = 0; + for (var j = 0; j < uniforms.sliceDim; j = j + 1) { + let indexInside = i32(round(${t})); + flattenedIndex = flattenedIndex + indexInside * ${r}; + } + let updateValue = + ${rs(this.type)}(${i}); + let flatIndex = getOutputIndexFromCoords(${s}); + + ${this.sumDupeIndices?zr("&result[flatIndex]","updateValue",this.type):"atomicStore(&result[flatIndex], bitcast(updateValue));"} + } + }`}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function r4(n){const{inputs:e,backend:t,attrs:r}=n,{indices:s,updates:a}=e,{shape:o}=r,{sliceRank:i,numUpdates:l,sliceSize:c,strides:u,outputSize:d}=ha(a,s,o),p=[d/c,c];if(d===0)return t.makeTensorInfo(o,s.dtype);const f=de({inputs:{x:s},backend:t,attrs:{shape:[l,i]}}),m=de({inputs:{x:a},backend:t,attrs:{shape:[l,c]}}),g=m.dtype,b=Wt({backend:t,attrs:{shape:p,value:0,dtype:g}}),v=q(m.shape),I=[{type:"int32",data:[i]},{type:"int32",data:u},{type:"int32",data:[v]}],S=new Ga(m.shape,i,f.shape.length,m.shape.length,u,p,g),C=t.runWebGPUProgram(S,[m,f],g,I,b),T=de({inputs:{x:C},backend:t,attrs:{shape:o}});return t.disposeData(f.dataId),t.disposeData(m.dataId),t.disposeData(C.dataId),T}const s4={kernelName:Zi,backendName:"webgpu",kernelFunc:r4};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */class a4{constructor(e,t){this.outputShape=[],this.variableNames=["sortedSequence","values"],this.uniforms="numInputs : i32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.side=t,this.shaderKey=`search_sorted_${t}`}getUserCode(){return` + fn findBound(batch: i32, value: f32) -> i32 { + var left = i32(0); + var right = uniforms.numInputs; + while (left < right) { + var mid = (left + right) / 2; + if (getSortedSequence(batch, mid) ${this.side==="left"?"<":"<="} value) { + left = mid + 1; + } else { + right = mid; + } + } + return right; + } + + ${re("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let value = getValuesByOutputIndex(index); + setOutputAtIndexI32(index, findBound(coords[0], value)); + } + } + `}}/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */function o4(n){const{inputs:e,backend:t,attrs:r}=n,{sortedSequence:s,values:a}=e,{side:o}=r,i=new a4([a.shape[0],a.shape[1]],o),l=[{type:"int32",data:[s.shape[1]]}];return t.runWebGPUProgram(i,[s,a],"int32",l)}const i4={kernelName:eu,backendName:"webgpu",kernelFunc:o4};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class u4{constructor(e,t,r){this.variableNames=["c","a","b"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.cRank=e,this.rank=r,this.shaderKey="select"}getUserCode(){let e,t;if(this.rank>4)throw Error(`Where for rank ${this.rank} is not yet supported`);if(this.rank===1)t="resRC",e="resRC";else{const s=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[],o=[];for(let i=0;i= 1.0) { + setOutputAtIndex(index, getA(${t})); + } else { + setOutputAtIndex(index, getB(${t})); + } + } + } + `}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function l4(n){const{inputs:e,backend:t}=n,{condition:r,t:s,e:a}=e,o=new u4(r.shape.length,s.shape,s.shape.length);return t.runWebGPUProgram(o,[r,s,a],_r(s.dtype,a.dtype))}const c4={kernelName:id,backendName:"webgpu",kernelFunc:l4};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */const d4=We({opType:ne.SELU}),p4={kernelName:ud,backendName:"webgpu",kernelFunc:d4};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const h4=We({opType:ne.SIGMOID}),f4={kernelName:hd,backendName:"webgpu",kernelFunc:h4};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */const m4=We({opType:ne.SIGN}),g4={kernelName:pd,backendName:"webgpu",kernelFunc:m4};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const y4=We({opType:ne.SIN}),b4={kernelName:cd,backendName:"webgpu",kernelFunc:y4};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const w4=We({opType:ne.SINH}),x4={kernelName:dd,backendName:"webgpu",kernelFunc:w4};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */const v4=We({opType:ne.SOFTPLUS}),S4={kernelName:fd,backendName:"webgpu",kernelFunc:v4};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */class I4{constructor(e,t,r,s,a,o){this.variableNames=["x"],this.outputShape=[],this.uniforms="",this.workgroupSize=[64,1,1],this.size=!0;const i=new Array(s.length);for(let l=0;l{this.uniforms+=` pad${c} : vec2,`}),this.shaderKey=`spaceToBatchND_${a}`}getUserCode(){const e=ft(this.outputShape.length),t=ob(this.newDim);return` + ${jo(this.paddedXShape,"PaddedX")} + ${re("index")} { + if(index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let switchedIndex = getIndexFromCoords${this.outputShape.length}D(${e}(${t}), uniforms.reshapedPaddedXShape); + let paddedCoords = getPaddedXCoordsFromIndex(switchedIndex); + ${_b(this.xShape,!0)} + } + } + `}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const k4=n=>{const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{blockShape:a,paddings:o}=r;$(s.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGPU backend not implemented yet");const i=a.reduce((I,S)=>I*S),l=[[0,0]];l.push(...o);for(let I=1+a.length;II[0]+s.shape[S]+I[1]),u=bu(c,a,i,!1),d=wu(u.length,a.length,!1),p=xu(c,a,i,!1),f=et(c),m=new I4(s.shape,c,l,u,d,f.length),g=[{type:"int32",data:u},{type:"int32",data:f}];l.map(I=>g.push({type:"int32",data:[I[0],I[1]]}));const b=t.runWebGPUProgram(m,[s],s.dtype,g),v=de({inputs:{x:b},backend:t,attrs:{shape:p}});return t.disposeData(b.dataId),v},_4={kernelName:gd,backendName:"webgpu",kernelFunc:k4};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */class C4{constructor(e,t,r){this.variableNames=["input","indices","segmentIds"],this.outputShape=[],this.uniforms="segmentSize : i32, sparseSize : i32,",this.workgroupSize=[64,1,1],this.atomic=!0,this.outputShape=e,this.type=r,this.dispatchLayout=ie([t]),this.dispatch=se(this.dispatchLayout,[t],this.workgroupSize),this.shaderKey="sparseSegmentSum"}getUserCode(){return` + ${re("index")} { + if (index < uniforms.sparseSize) { + let indexInSegmentIds = index / uniforms.segmentSize; + let indexInSegment = index % uniforms.segmentSize; + let indexInInput = indices[indexInSegmentIds]; + let segmentId = segmentIds[indexInSegmentIds]; + + let value = input[indexInInput * uniforms.segmentSize + indexInSegment]; + let outIndex = segmentId * uniforms.segmentSize + indexInSegment; + ${zr("&result[outIndex]","value",this.type)} + } + } + `}}class N4{constructor(e,t){this.variableNames=["segmentIds"],this.outputShape=[],this.workgroupSize=[64,1,1],this.atomic=!0,this.outputShape=[e],this.dispatchLayout=ie(t),this.dispatch=se(this.dispatchLayout,t,this.workgroupSize),this.shaderKey="sparseSegmentIdCountProgram"}getUserCode(){return` + ${re("index")} { + if (index < uniforms.segmentIdsShape) { + let segmentId = segmentIds[index]; + ${zr("&result[segmentId]","1","int32")} + } + } + `}}class $4{constructor(e,t){this.variableNames=["segmentSum","sameSegmentIdCount"],this.outputShape=[],this.uniforms="segmentSize : i32",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.type=t,this.dispatchLayout=ie(e),this.dispatch=se(this.dispatchLayout,e,this.workgroupSize),this.shaderKey="sparseSegmentMean"}getUserCode(){return` + ${re("index")} { + if (index < uniforms.size) { + let segmentId = index / uniforms.segmentSize; + let count = sameSegmentIdCount[segmentId]; + if (count != 0) { + ${this.type==="float32"?"setOutputAtIndex(index, segmentSum[index] / f32(count));":"setOutputAtIndexI32(index, segmentSum[index] / count);"} + } + } + } + `}}/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */function Cb(n,e,t,r=!1,s){const o=q(n.shape)/n.shape[0],i=n.dtype,l=q(e.shape),c=s.readSync(t.dataId),d=l>0?c[l-1]+1:0;let p;const f=n.shape.slice();f[0]=d;const m=l*o,g=Wt({backend:s,attrs:{shape:f,value:0,dtype:i}});p=new C4(f,m,i);let b=[{type:"int32",data:[o]},{type:"int32",data:[m]}];const v=s.runWebGPUProgram(p,[n,e,t],i,b,g);if(r)return v;const I=Wt({backend:s,attrs:{shape:[d],value:0,dtype:"int32"}});p=new N4(d,t.shape);const S=s.runWebGPUProgram(p,[t],"int32",null,I),C=Wt({backend:s,attrs:{shape:f,value:0,dtype:i}});p=new $4(f,i),b=[{type:"int32",data:[o]}];const T=s.runWebGPUProgram(p,[v,S],i,b,C);return s.disposeData(v.dataId),s.disposeData(S.dataId),T}/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */function T4(n){const{inputs:e,backend:t}=n,{data:r,indices:s,segmentIds:a}=e;return Cb(r,s,a,!1,t)}const E4={kernelName:wd,backendName:"webgpu",kernelFunc:T4};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */function A4(n){const{inputs:e,backend:t}=n,{data:r,indices:s,segmentIds:a}=e;return Cb(r,s,a,!0,t)}const R4={kernelName:xd,backendName:"webgpu",kernelFunc:A4};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */class D4{constructor(e,t){this.variableNames=["A"],this.workgroupSize=[64,1,1],this.size=!0;const r=new Array(e.length);for(let s=0;s=5)throw Error(`Tile for rank ${n} is not yet supported`);if(n===1)return`(resRC % ${e}aShape)`;const t=["resRC.x","resRC.y","resRC.z","resRC.w"],r=[];for(let s=0;s=5){const l=t.readSync(s.dataId),c=s.dtype==="string"?l.map(p=>na(p)):l,u=ut(s.shape,s.dtype,c),d=IM(u,a);return t.makeTensorInfo(d.shape,d.dtype,d.values)}const o=new D4(s.shape,a);return t.runWebGPUProgram(o,[s],s.dtype)}const F4={kernelName:co,backendName:"webgpu",kernelFunc:Jd};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function O4(n){const{inputs:e,backend:t,attrs:r}=n,{sparseIndices:s,sparseValues:a,defaultValue:o}=e,{outputShape:i}=r,{sliceRank:l,numUpdates:c,sliceSize:u,strides:d,outputSize:p}=ha(a,s,i),f=!1;if(a.dtype==="string"){const B=t.bufferSync(s),A=t.bufferSync(a),D=na(t.readSync(o.dataId)[0]),_=yM(B,A,i,p,u,c,l,d,D,f);return t.makeTensorInfo(i,_.dtype,_.values)}const m=[p/u,u],g=de({inputs:{x:s},backend:t,attrs:{shape:[c,l]}}),b=a.shape.length?de({inputs:{x:a},backend:t,attrs:{shape:[c,u]}}):Xt({inputs:{x:a},backend:t}),v=b.dtype,I=t.makeTensorInfo([],v,ps(1,v)),S=de({inputs:{x:o},backend:t,attrs:{shape:Array(m.length).fill(1)}}),C=Jd({inputs:{x:S},backend:t,attrs:{reps:m}}),T=q([c,u]),O=[{type:"int32",data:[l]},{type:"int32",data:d},{type:"int32",data:[T]}];switch(c){case 0:break;case 1:{const B=new Ga([c,u],l,g.shape.length,b.shape.length,d,m,v,f);t.runWebGPUProgram(B,[b,g],v,O,C)}break;default:{const B=new Ga([c,u],l,g.shape.length,I.shape.length,d,m,v,f);t.runWebGPUProgram(B,[I,g],v,O,C)}{const B=new Ga([c,u],l,g.shape.length,b.shape.length,d,m,v);t.runWebGPUProgram(B,[b,g],v,O,C)}}const L=de({inputs:{x:C},backend:t,attrs:{shape:i}});return t.disposeData(g.dataId),t.disposeData(b.dataId),t.disposeData(S.dataId),t.disposeData(I.dataId),t.disposeData(C.dataId),L}const M4={kernelName:ru,backendName:"webgpu",kernelFunc:O4};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function L4(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{numOrSizeSplits:a,axis:o}=r,i=$t(o,s.shape)[0],l=og(s,a,i),c=s.shape.length,u=new Array(c).fill(0),d=s.shape.slice();return l.map(p=>{const f=[...d];f[i]=p;const m=ba({inputs:{x:s},backend:t,attrs:{begin:u,size:f}});return u[i]+=p,m})}const z4={kernelName:yd,backendName:"webgpu",kernelFunc:L4};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const B4=We({opType:ne.SQRT}),W4={kernelName:md,backendName:"webgpu",kernelFunc:B4};/** + * @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. + * ============================================================================= + */const V4={kernelName:wf,backendName:"webgpu",kernelFunc:({inputs:n,backend:e})=>{const{x:t}=n,r=e,s=new ya(t.shape,ne.SQUARE);return r.runWebGPUProgram(s,[t],t.dtype)}};/** + * @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. + * ============================================================================= + */const U4=xt({opType:ve.SQUARED_DIFFERENCE}),H4={kernelName:vd,backendName:"webgpu",kernelFunc:U4};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */function G4({inputs:n,attrs:e,backend:t}){const{x:r}=n,s=new ya(r.shape,ne.STEP,"stepAlpha : f32,"),a=[{type:"float32",data:[e.alpha]}];return t.runWebGPUProgram(s,[r],r.dtype,a)}const j4={kernelName:iu,backendName:"webgpu",kernelFunc:G4};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class q4{constructor(e){this.variableNames=["x"],this.workPerThread=1,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize,[this.workPerThread,1,1]);const t=ft(this.outputShape.length);this.uniforms=`begin : ${t}, strides : ${t}, `,this.shaderKey="stridedSlice"}getUserCode(){const e=this.outputShape.length;let t="";if(e===1)t="coords * uniforms.strides + uniforms.begin";else{let s=0;t=this.outputShape.map((a,o)=>(s++,this.outputShape.length===1?`coords * uniforms.strides[${o}] + uniforms.begin[${o}]`:`coords[${s-1}] * uniforms.strides[${o}] + uniforms.begin[${o}]`)).join(",")}return` + ${re("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + setOutputAtIndex(index, getX(${t})); + } + } + `}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function K4(n){const{inputs:e,backend:t,attrs:r}=n,{x:s}=e,{begin:a,end:o,strides:i,beginMask:l,endMask:c,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:p}=r,{finalShapeSparse:f,finalShape:m,isIdentity:g,sliceDim0:b,isSimpleSlice:v,begin:I,end:S,strides:C}=tg(s.shape,a,o,i,l,c,u,d,p);let T;if(g)T=de({inputs:{x:s},backend:t,attrs:{shape:m}});else if(b||v){$(s.shape.length>=1,()=>`Input must have rank at least 1, got: ${s.shape.length}`);const O=Qm(I,S,C),L=ba({inputs:{x:s},backend:t,attrs:{begin:I,size:O}});T=de({inputs:{x:L},backend:t,attrs:{shape:m}}),t.disposeData(L.dataId)}else if(t.shouldExecuteOnCPU([s])){const L=t.readSync(s.dataId),B=ut(s.shape,s.dtype,L),A=xM(f,B,C,I);T=t.makeTensorInfo(m,s.dtype,A.values)}else{const L=new q4(f),B=[{type:"int32",data:I},{type:"int32",data:C}],A=t.runWebGPUProgram(L,[s],s.dtype,B);T=de({inputs:{x:A},backend:t,attrs:{shape:m}}),t.disposeData(A.dataId)}return T}const X4={kernelName:su,backendName:"webgpu",kernelFunc:K4};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function Y4(n){const{inputs:e,backend:t,attrs:r}=n,{separator:s,nGramWidths:a,leftPad:o,rightPad:i,padWidth:l,preserveShortSequences:c}=r,{data:u,dataSplits:d}=e,p=t.readSync(u.dataId),f=t.readSync(d.dataId),[m,g]=vM(p,f,s,a,o,i,l,c);return[t.makeTensorInfo([m.length],"string",m),t.makeTensorInfo(d.shape,"int32",g)]}const Q4={kernelName:Sd,backendName:"webgpu",kernelFunc:Y4};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const Z4=xt({opType:ve.SUB,cpuKernelImpl:SM,supportsComplex:!0}),J4={kernelName:Id,backendName:"webgpu",kernelFunc:Z4};/** + * @license + * Copyright 2022 Google LLC. + * 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. + * ============================================================================= + */const eU=We({opType:ne.TAN}),tU={kernelName:kd,backendName:"webgpu",kernelFunc:eU};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */const nU=We({opType:ne.TANH}),rU={kernelName:_d,backendName:"webgpu",kernelFunc:nU};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */function sU(n){const{inputs:e,backend:t,attrs:r}=n,{tensor:s,indices:a,updates:o}=e,{sliceRank:i,numUpdates:l,sliceSize:c,strides:u,outputSize:d}=ha(o,a,s.shape),p=[d/c,c];if(d===0)return t.makeTensorInfo(s.shape,a.dtype);const f=[],m=de({inputs:{x:a},backend:t,attrs:{shape:[l,i]}});f.push(m);const g=de({inputs:{x:o},backend:t,attrs:{shape:[l,c]}});f.push(g);const b=de({inputs:{x:s},backend:t,attrs:{shape:p}});f.push(b);const v=Jd({inputs:{x:b},backend:t,attrs:{reps:Array(p.length).fill(1)}}),I=new Ga([l,c],i,m.shape.length,g.shape.length,u,p,s.dtype,!1),S=q([l,c]),C=[{type:"int32",data:[i]},{type:"int32",data:u},{type:"int32",data:[S]}],T=t.runWebGPUProgram(I,[g,m],b.dtype,C,v);f.push(T);const O=de({inputs:{x:T},backend:t,attrs:{shape:s.shape}});return f.forEach(L=>t.disposeData(L.dataId)),O}const aU={kernelName:Ji,backendName:"webgpu",kernelFunc:sU};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */class oU{constructor(e){this.variableNames=["x","indices"],this.workgroupSize=[256,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.uniforms=`inputSize : i32, firstPass : i32, negativeInf : f32, + dir : i32, inc : i32,`,this.shaderKey="swap"}getUserCode(){return` + ${re("index")} { + if (index < uniforms.size) { + let outC = getCoordsFromIndex(index); + let batch = outC[0]; + let elemIdx = outC[1]; + // We compare elements pair-wise within a group of size 2 * inc. + // The comparing rule for each group alternates between ascending + // and descending. Within each group, we compare each pair at + // positions i and i+inc. To decide whether an element at position i + // is x0 or x1, we mod it by 2 * inc, if the result is smaller than + // inc, it is in the first half of the group, we denote it as x0, + // otherwise we denote it as x1. + // For example, as shown in the Bitonic top K paper referenced + // above, Figure5(a) shows that element[1] is in the second half of + // the group when group size is 2, but it is in the first half of + // the group when group size is 4. + let isFirstInPair = elemIdx % (2 * uniforms.inc) < uniforms.inc; + var i = 0; + if (isFirstInPair) { + i = elemIdx; + } else { + i = elemIdx - uniforms.inc; + } + + var i0 = 0; + if (uniforms.firstPass == 1) { + i0 = i; + } else { + i0 = i32(getIndices(batch, i)); + } + + var i1 = 0; + if (uniforms.firstPass == 1) { + i1 = i + uniforms.inc; + } else { + i1 = i32(getIndices(batch, i + uniforms.inc)); + } + + var x0 = f32(0.0); + var x1 = f32(0.0); + if (i0 < uniforms.inputSize) { + x0 = getX(batch, i0); + } else { + x0 = uniforms.negativeInf; + } + if (i1 < uniforms.inputSize) { + x1 = getX(batch, i1); + } else { + x1 = uniforms.negativeInf; + } + + let reverse = elemIdx % (2 * uniforms.dir) >= uniforms.dir; + let isGreater = x0 > x1 || (x0 == x1 && i1 > i0); + if (reverse == isGreater) { + // Elements in opposite order of direction + let iTemp = i0; + i0 = i1; + i1 = iTemp; + } + if (isFirstInPair) { + setOutputAtIndex(index, f32(i0)); + } else { + setOutputAtIndex(index, f32(i1)); + } + } + } + `}}class iU{constructor(e){this.variableNames=["x","indices"],this.workgroupSize=[256,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.uniforms="inputSize : i32, firstPass : i32, k : i32,",this.shaderKey="merge"}getUserCode(){return` + ${re("index")} { + if (index < uniforms.size) { + let outC = getCoordsFromIndex(index); + let batch = outC[0]; + let elemIdx = outC[1]; + // The output size is half of the previous size. + // If the previous sequence is | | | | _ _ _ _ | | | | _ _ _ _ + // (k=4), we only need to output the indices at positions |, the + // indices at positions _ can be thrown away, see Figure5(b) After + // Phase 2 (Merge phase) in the Bitonic Top K paper referenced + // above. + // For example, the paper shows we only need to output the orange + // bars. The output sequence should look like this | | | | | | | |. + // Because the sequence is halved, to map the output index back to + // the previous sequence to find the corresponding value, we need + // to double the index. When we double the index, we basically + // interpolate a position, so 2i looks like + // | _ | _ | _ | _ | _ | _ | _. We move the | to the first k + // position of each 2k positions by - elemIdx % k. E.g. for output + // at index 4,5,6,7, we want to get the corresponding element at + // original index 8,9,10,11, for output at index 8,9,10,11, + // we want to get the corresponding element at original index + // 16,17,18,19, so on and so forth. + + var i = 0; + if (elemIdx < uniforms.k) { + i = elemIdx; + } else { + i = elemIdx * 2 - elemIdx % uniforms.k; + } + var i0 = 0; + if (uniforms.firstPass == 1) { + i0 = i; + } else { + i0 = i32(getIndices(batch, i)); + } + var i1 = 0; + if (uniforms.firstPass == 1) { + i1 = i + uniforms.k; + } else { + i1 = i32(getIndices(batch, i + uniforms.k)); + } + + let x0 = getX(batch, i0); + var x1 = f32(0.0); + if (i1 < uniforms.inputSize) { + x1 = getX(batch, i1); + } else { + x1 = x0; + } + + if (x0 >= x1) { + setOutputAtIndex(index, f32(i0)); + } else { + setOutputAtIndex(index, f32(i1)); + } + } + } + `}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function Gs(n,e){e!==null&&n.disposeData(e.dataId)}function mh(n){let e=1;for(;em===null?[d,d]:[d,m],b=(T,O,L)=>{const B=g(),A=new oU(L),_=[{type:"int32",data:[l]},{type:"int32",data:[m===null?1:0]},{type:"float32",data:[Number.NEGATIVE_INFINITY]},{type:"int32",data:[T]},{type:"int32",data:[O]}],V=m;m=t.runWebGPUProgram(A,B,"int32",_),Gs(t,V)};for(let T=1;T=1;L/=2)b(O,L,[u,f])}for(let T=f;T>p;T/=2){const O=g(),L=new iU([u,T/2]),A=[{type:"int32",data:[l]},{type:"int32",data:[m===null?1:0]},{type:"int32",data:[p]}],D=m;m=t.runWebGPUProgram(L,O,"int32",A),Gs(t,D);const _=p/2,V=_*2;for(let H=_;H>=1;H/=2)b(V,H,m.shape)}let v=m;m=ba({inputs:{x:m},backend:t,attrs:{begin:0,size:[u,a]}}),Gs(t,v);let I=vb({inputs:{x:d,indices:m},backend:t,attrs:{axis:1,batchDims:1}});Gs(t,d);const S=i.slice(0,-1);S.push(a),v=m,m=de({inputs:{x:m},attrs:{shape:S},backend:t}),Gs(t,v);const C=I;return I=de({inputs:{x:I},attrs:{shape:S},backend:t}),Gs(t,C),[I,m]}const lU={kernelName:au,backendName:"webgpu",kernelFunc:uU};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */class cU{constructor(e){this.variableNames=["Image","Transforms"],this.uniforms="interpolationModeId : i32, fillModeId : i32, fillValue : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=ie(this.outputShape),this.dispatch=se(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="transform"}getUserCode(){return` + fn mapCoord(outCoord : f32, len : f32) -> f32{ + var inCoord = outCoord; + if(uniforms.fillModeId == 2) { + if (inCoord < 0.0) { + if (len <= 1.0) { + inCoord = 0.0; + } else { + let sz2 = 2.0 * len; + if (inCoord < sz2) { + inCoord = sz2 * f32(i32(f32(-inCoord / sz2))) + + inCoord; + } + if (inCoord < -len) { + inCoord = inCoord + sz2; + } else { + inCoord = -inCoord - 1.0; + } + } + } else if (inCoord > len - 1.0) { + if (len <= 1.0) { + inCoord = 0.0; + } else { + let sz2 = 2.0 * len; + inCoord = inCoord - sz2 * f32(i32(f32(inCoord / sz2))); + if (inCoord >= len) { + inCoord = sz2 - inCoord - 1.0; + } + } + } + return clamp(inCoord, 0.0, len - 1.0); + } else if (uniforms.fillModeId == 3) { + if (inCoord < 0.0) { + if (len <= 1.0) { + inCoord = 0.0; + } else { + let sz = len - 1.0; + inCoord = inCoord + len * (f32(i32(f32(-inCoord / sz))) + 1.0); + } + } else if (inCoord > len - 1.0) { + if (len <= 1.0) { + inCoord = 0.0; + } else { + let sz = len - 1.0; + inCoord = inCoord - len * f32(i32(f32(inCoord / sz))); + } + } + return clamp(inCoord, 0.0, len - 1.0); + } else if (uniforms.fillModeId == 4) { + return clamp(outCoord, 0.0, len - 1.0); + } + return outCoord; + } + fn readWithFillValue(batch : i32, coordY : i32, coordX : i32, + channel : i32) -> f32 { + var outputValue : f32; + if (0 <= coordY && coordY < uniforms.imageShape[1] && 0 <= coordX && coordX < uniforms.imageShape[2]) { + outputValue = getImage(batch, coordY, coordX, channel); + } else { + outputValue = uniforms.fillValue; + } + return outputValue; + } + + ${re("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + var outputValue : f32; + let batch = coords[0]; + let x = coords[2]; + let y = coords[1]; + let channel = coords[3]; + let xf = f32(x); + let yf = f32(y); + let a1 = getTransforms(batch, 0); + let a2 = getTransforms(batch, 1); + let a3 = getTransforms(batch, 2); + let b1 = getTransforms(batch, 3); + let b2 = getTransforms(batch, 4); + let b3 = getTransforms(batch, 5); + let c1 = getTransforms(batch, 6); + let c2 = getTransforms(batch, 7); + let projection = c1 * xf + c2 * yf + 1.0; + if (projection == 0.0) { + outputValue = uniforms.fillValue; + } else { + let inX = (a1 * xf + a2 * yf + a3) / projection; + let inY = (b1 * xf + b2 * yf + b3) / projection; + let mapX = mapCoord(inX, f32(uniforms.imageShape[2])); + let mapY = mapCoord(inY, f32(uniforms.imageShape[1])); + + if (uniforms.interpolationModeId == 1) { + let coordY = i32(round(mapY)); + let coordX = i32(round(mapX)); + outputValue = readWithFillValue(batch, coordY, coordX, + channel); + } else { + let yFloor = floor(mapY); + let xFloor = floor(mapX); + let yCeil = yFloor + 1.0; + let xCeil = xFloor + 1.0; + let valueYFloor = (xCeil - mapX) * + readWithFillValue(batch, i32(yFloor), i32(xFloor), channel) + + (mapX - xFloor) * + readWithFillValue(batch, i32(yFloor), i32(xCeil), channel); + let valueYCeil = (xCeil - mapX) * + readWithFillValue(batch, i32(yCeil), i32(xFloor), channel) + + (mapX - xFloor) * + readWithFillValue(batch, i32(yCeil), i32(xCeil), channel); + outputValue = (yCeil - mapY) * valueYFloor + + (mapY - yFloor) * valueYCeil; + } + } + setOutputAtIndex(index, outputValue); + } + } + `}}/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function dU(n){const{inputs:e,backend:t,attrs:r}=n,{image:s,transforms:a}=e,{interpolation:o,fillMode:i,fillValue:l,outputShape:c}=r,[u,d,p,f]=s.shape,[m,g]=c??[d,p],b=[u,m,g,f],v=new cU(b),I=o==="nearest"?1:2;let S;switch(i){case"constant":S=1;break;case"reflect":S=2;break;case"wrap":S=3;break;case"nearest":S=4;break;default:S=1;break}const C=[{type:"int32",data:[I]},{type:"int32",data:[S]},{type:"float32",data:[l]}];return t.runWebGPUProgram(v,[s,a],"float32",C)}const pU={kernelName:ou,backendName:"webgpu",kernelFunc:dU};/** + * @license + * Copyright 2021 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. + * ============================================================================= + */function hU(n){const{inputs:e,backend:t,attrs:r}=n,{value:s}=e;let{axis:a}=r;a<0&&(a+=s.shape.length);const o=s,i=o.shape.length,l=s.shape[a],c=new Array(i-1);let u=0;for(let g=0;gt.disposeData(g.dataId)),m}const fU={kernelName:Cd,backendName:"webgpu",kernelFunc:hU};/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */class mU{constructor(e,t,r){if(this.outputShape=[],this.variableNames=["x","segmentIds"],this.uniforms="numSegments : i32, xSize: i32,",this.workgroupSize=[64,1,1],this.atomic=!0,this.outputShape=t,this.dispatchLayout=ie(e),this.dispatch=se(this.dispatchLayout,e,this.workgroupSize),r!=="float32"&&r!=="int32")throw new Error(`UnsortedSegmentSum only supports float32 and int32 + types, does not support ${r} type.`);this.type=r,this.shaderKey="unsortedSegmentSum"}getUserCode(){return` + ${re("index")} { + if (index < uniforms.xSize) { + let coords = getXCoordsFromIndex(index); + let b = coords[0]; + let inCol = coords[1]; + + let segmentId = i32(getSegmentIds(inCol)); + if (segmentId >= 0) { + let flatIndex = b * uniforms.numSegments + segmentId % uniforms.numSegments; + let value = getX(b, inCol); + + ${zr("&result[flatIndex]","value",this.type)} + } + } + } + `}}/** + * @license + * Copyright 2023 Google LLC. + * 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. + * ============================================================================= + */function gU(n){const{inputs:e,backend:t,attrs:r}=n,{x:s,segmentIds:a}=e,{numSegments:o}=r,i=s.shape.length,l=[];let c=0;const u=Or([c],i);let d=s;u!=null&&(d=Vn({inputs:{x:s},backend:t,attrs:{perm:u}}),l.push(d),c=An(1,i)[0]);const p=sN(d.shape,c,o),f=q([d.shape[c]]),m=de({inputs:{x:d},backend:t,attrs:{shape:[-1,f]}});l.push(m);const g=s.dtype,b=[m.shape[0],o],v=Wt({backend:t,attrs:{shape:b,value:0,dtype:g}}),I=new mU(m.shape,b,g),S=[{type:"int32",data:[o]},{type:"int32",data:[q(m.shape)]}],C=t.runWebGPUProgram(I,[m,a],g,S,v),T=de({inputs:{x:C},backend:t,attrs:{shape:p}});l.push(C);let O=T;if(u!=null){l.push(T);const L=hu(u);O=Vn({inputs:{x:O},backend:t,attrs:{perm:L}})}return l.forEach(L=>t.disposeData(L.dataId)),O}const yU={kernelName:If,backendName:"webgpu",kernelFunc:gU};/** + * @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. + * ============================================================================= + */const bU=[UO,NM,TM,AM,DM,OM,UM,GM,qM,XM,QM,JM,tL,rL,aL,cL,pL,gL,bL,xL,_L,TL,RL,OL,LL,VL,GO,GL,XL,rz,lz,hz,gz,bz,xz,Sz,kz,Nz,Tz,Az,Dz,Oz,Uz,Gz,zz,Kz,Qz,tB,rB,oB,cB,pB,fB,gB,bB,xB,vB,IB,_B,BO,NB,DB,TB,AB,OB,LB,BB,UB,jB,KB,YB,HO,ZB,qL,eW,nW,sW,oW,uW,cW,hW,yW,mW,wW,vW,IW,NW,EW,iL,RW,PW,VW,OW,BW,HW,uL,jW,KW,YW,ZW,rV,iB,aV,iV,lV,DL,pV,fV,gV,wV,vV,IV,_V,NV,PL,TV,AV,DV,FV,WO,LV,WV,HV,qV,YV,ZV,e4,n4,s4,i4,c4,p4,f4,g4,b4,x4,IL,j4,X4,Q4,tV,S4,_4,E4,R4,M4,z4,W4,V4,H4,J4,uB,tU,rU,aU,F4,lU,pU,zM,fU,yU,hV];for(const n of bU)kf(n);/** + * @license + * Copyright 2023 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 Nb=function(n,e){return(Nb=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,r){t.__proto__=r}||function(t,r){for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(t[s]=r[s])})(n,e)};function $b(n,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function t(){this.constructor=n}Nb(n,e),n.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}var Je=function(){return(Je=Object.assign||function(n){for(var e,t=1,r=arguments.length;t0&&s[s.length-1])||u[0]!==6&&u[0]!==2)){o=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]=256)throw new Error("Mask value must be in range [0, 255] but got ".concat(n));if(!Number.isInteger(n))throw new Error("Mask value must be an integer but got ".concat(n))}var Ma={runtime:"mediapipe",enableSmoothing:!0,enableSegmentation:!1,smoothSegmentation:!0,modelType:"full"},xU=(function(){function n(e){this.mask=e}return n.prototype.toCanvasImageSource=function(){return Le(this,void 0,void 0,(function(){return ze(this,(function(e){return[2,this.mask]}))}))},n.prototype.toImageData=function(){return Le(this,void 0,void 0,(function(){return ze(this,(function(e){return[2,Eb(this.mask)]}))}))},n.prototype.toTensor=function(){return Le(this,void 0,void 0,(function(){return ze(this,(function(e){return[2,wU(this.mask)]}))}))},n.prototype.getUnderlyingType=function(){return"canvasimagesource"},n})();function vU(n){return Ab(n),"person"}var SU=(function(){function n(e){var t,r=this;switch(this.width=0,this.height=0,this.selfieMode=!1,this.poseSolution=new WP.Pose({locateFile:function(s,a){if(e.solutionPath){var o=e.solutionPath.replace(/\/+$/,"");return"".concat(o,"/").concat(s)}return"".concat(a,"/").concat(s)}}),e.modelType){case"lite":t=0;break;case"heavy":t=2;break;case"full":default:t=1}this.poseSolution.setOptions({modelComplexity:t,smoothLandmarks:e.enableSmoothing,enableSegmentation:e.enableSegmentation,smoothSegmentation:e.smoothSegmentation,selfieMode:this.selfieMode}),this.poseSolution.onResults((function(s){if(r.height=s.image.height,r.width=s.image.width,s.poseLandmarks==null)r.poses=[];else{var a=r.translateOutput(s.poseLandmarks,s.poseWorldLandmarks);s.segmentationMask&&(a.segmentation={maskValueToLabel:vU,mask:new xU(s.segmentationMask)}),r.poses=[a]}}))}return n.prototype.translateOutput=function(e,t){var r=this,s={keypoints:e.map((function(a,o){return{x:a.x*r.width,y:a.y*r.height,z:a.z,score:a.visibility,name:lo[o]}}))};return t!=null&&(s.keypoints3D=t.map((function(a,o){return{x:a.x,y:a.y,z:a.z,score:a.visibility,name:lo[o]}}))),s},n.prototype.estimatePoses=function(e,t,r){return Le(this,void 0,void 0,(function(){var s,a;return ze(this,(function(o){switch(o.label){case 0:return t&&t.flipHorizontal&&t.flipHorizontal!==this.selfieMode&&(this.selfieMode=t.flipHorizontal,this.poseSolution.setOptions({selfieMode:this.selfieMode})),e instanceof dt?(a=ImageData.bind,[4,qd(e)]):[3,2];case 1:return s=new(a.apply(ImageData,[void 0,o.sent(),e.shape[1],e.shape[0]])),[3,3];case 2:s=e,o.label=3;case 3:return e=s,[4,this.poseSolution.send({image:e},r)];case 4:return o.sent(),[2,this.poses]}}))}))},n.prototype.dispose=function(){this.poseSolution.close()},n.prototype.reset=function(){this.poseSolution.reset()},n.prototype.initialize=function(){return this.poseSolution.initialize()},n})();function IU(n){return Le(this,void 0,void 0,(function(){var e,t;return ze(this,(function(r){switch(r.label){case 0:return e=(function(s){if(s==null)return Je({},Ma);var a=Je({},s);return a.runtime="mediapipe",a.enableSegmentation==null&&(a.enableSegmentation=Ma.enableSegmentation),a.enableSmoothing==null&&(a.enableSmoothing=Ma.enableSmoothing),a.smoothSegmentation==null&&(a.smoothSegmentation=Ma.smoothSegmentation),a.modelType==null&&(a.modelType=Ma.modelType),a})(n),[4,(t=new SU(e)).initialize()];case 1:return r.sent(),[2,t]}}))}))}function la(n){return n instanceof dt?{height:n.shape[0],width:n.shape[1]}:{height:n.height,width:n.width}}function Rb(n){return n-2*Math.PI*Math.floor((n+Math.PI)/(2*Math.PI))}function ep(n){return n instanceof dt?n:Xm(n)}function Db(n,e,t){return Wl(t,"inputResolution"),[1/t.width*n[0][0]*e.width,1/t.height*n[0][1]*e.width,n[0][3]*e.width,1/t.width*n[1][0]*e.height,1/t.height*n[1][1]*e.height,n[1][3]*e.height,0,0]}function Wl(n,e){$(n.width!==0,(function(){return"".concat(e," width cannot be 0.")})),$(n.height!==0,(function(){return"".concat(e," height cannot be 0.")}))}function ju(n,e,t){var r=t.rotationVectorStartKeypointIndex,s=t.rotationVectorEndKeypointIndex,a=n.locationData,o=a.relativeKeypoints[r].x*e.width,i=a.relativeKeypoints[r].y*e.height,l=a.relativeKeypoints[s].x*e.width,c=a.relativeKeypoints[s].y*e.height,u=2*Math.sqrt((l-o)*(l-o)+(c-i)*(c-i)),d=(function(p,f,m){var g,b=p.locationData,v=m.rotationVectorStartKeypointIndex,I=m.rotationVectorEndKeypointIndex;g=m.rotationVectorTargetAngle?m.rotationVectorTargetAngle:Math.PI*m.rotationVectorTargetAngleDegree/180;var S=b.relativeKeypoints[v].x*f.width,C=b.relativeKeypoints[v].y*f.height,T=b.relativeKeypoints[I].x*f.width,O=b.relativeKeypoints[I].y*f.height;return Rb(g-Math.atan2(-(O-C),T-S))})(n,e,t);return{xCenter:o/e.width,yCenter:i/e.height,width:u/e.width,height:u/e.height,rotation:d}}function Pb(n){if(n.length!==16)throw new Error("Array length must be 16 but got ".concat(n.length));return[[n[0],n[1],n[2],n[3]],[n[4],n[5],n[6],n[7]],[n[8],n[9],n[10],n[11]],[n[12],n[13],n[14],n[15]]]}function qu(n,e,t,r,s,a,o){return n[e][s]*(n[t][a]*n[r][o]-n[t][o]*n[r][a])}function Dt(n,e,t){var r=(e+1)%4,s=(e+2)%4,a=(e+3)%4,o=(t+1)%4,i=(t+2)%4,l=(t+3)%4;return qu(n,r,s,a,o,i,l)+qu(n,s,a,r,o,i,l)+qu(n,a,r,s,o,i,l)}function gh(n,e,t){t===void 0&&(t={ignoreRotation:!1});for(var r=[],s=0,a=n;sye?(Y=A.width,X=A.width*ee,be=(1-ye/ee)/2):(Y=A.height/ee,X=A.height,ce=(1-ee/ye)/2),A.width=Y,A.height=X,{top:be,left:ce,right:ce,bottom:be}})(O,v,I),B=(r=O,s=T.width,a=T.height,o=!1,i=r.width,l=r.height,c=o?-1:1,u=Math.cos(r.rotation),d=Math.sin(r.rotation),p=r.xCenter,f=r.yCenter,m=1/s,g=1/a,(b=new Array(16))[0]=i*u*c*m,b[1]=-l*d*m,b[2]=0,b[3]=(-.5*i*u*c+.5*l*d+p)*m,b[4]=i*d*c*g,b[5]=l*u*g,b[6]=0,b[7]=(-.5*l*u-.5*i*d*c+f)*g,b[8]=0,b[9]=0,b[10]=i*m,b[11]=0,b[12]=0,b[13]=0,b[14]=0,b[15]=1,Pb(b));return{imageTensor:Ce((function(){var A=ep(n),D=fn(Db(B,T,v),[1,8]),_=S==="zero"?"constant":"nearest",V=ls.transform(en(tt(A,"float32")),D,"bilinear",_,0,[v.height,v.width]);return C!=null?Fb(V,C):V})),padding:L,transformationMatrix:B}}function yh(n,e,t,r){return r===1?.5*(n+e):n+(e-n)*t/(r-1)}function kU(n){return Ce((function(){var e=(function(s){return Ce((function(){return[Ae(s,[0,0,0],[1,-1,1]),Ae(s,[0,0,1],[1,-1,-1])]}))})(n),t=e[0],r=e[1];return{boxes:Qe(r),logits:Qe(t)}}))}function Ob(n){return n!=null&&n.currentTime!=null}function bh(n){for(var e={locationData:{relativeKeypoints:[]}},t=Number.MAX_SAFE_INTEGER,r=Number.MIN_SAFE_INTEGER,s=Number.MAX_SAFE_INTEGER,a=Number.MIN_SAFE_INTEGER,o=0;o-1})),Ke([s,a,o]),[2,l]}}))}))}function Mb(n,e){return n.map((function(t){var r=Je(Je({},t),{x:t.x*e.width,y:t.y*e.height});return t.z!=null&&(r.z=t.z*e.width),r}))}function CU(n,e,t){return Le(this,void 0,void 0,(function(){var r,s,a,o,i,l,c,u,d,p,f,m,g,b,v,I,S,C,T,O,L,B,A,D;return ze(this,(function(_){switch(_.label){case 0:if(r=Qe(e,[0]),s=r.shape,a=s[0],o=s[1],i=s[2],n.length!==i)throw new Error("Expected heatmap to have same number of channels as the number of landmarks. But got landmarks length: "+"".concat(n.length,", heatmap length: ").concat(i));return l=[],[4,r.buffer()];case 1:for(c=_.sent(),u=0;u=o||m<0||f>=a)){for(g=Math.trunc((t.kernelSize-1)/2),b=Math.max(0,f-g),v=Math.min(o,f+g+1),I=Math.max(0,m-g),S=Math.min(a,m+g+1),C=0,T=0,O=0,L=0,B=I;B=t.minConfidenceToRefine&&C>0&&(p.x=T/o/C,p.y=O/a/C)}return r.dispose(),[2,l]}}))}))}function wh(n,e){var t=e.left,r=e.top,s=e.left+e.right,a=e.top+e.bottom;return n.map((function(o){return Je(Je({},o),{x:(o.x-t)/(1-s),y:(o.y-r)/(1-a),z:o.z/(1-s)})}))}function NU(n,e,t){return Qa()==="webgl"?(function(r,s,a){var o=a.combineWithPreviousRatio.toFixed(2),i={variableNames:["prevMask","newMask"],outputShape:r.shape,userCode:` + void main() { + ivec2 coords = getOutputCoords(); + int height = coords[0]; + int width = coords[1]; + + float prevMaskValue = getPrevMask(height, width); + float newMaskValue = getNewMask(height, width); + + /* + * Assume p := newMaskValue + * H(p) := 1 + (p * log(p) + (1-p) * log(1-p)) / log(2) + * uncertainty alpha(p) = + * Clamp(1 - (1 - H(p)) * (1 - H(p)), 0, 1) [squaring the + * uncertainty] + * + * The following polynomial approximates uncertainty alpha as a + * function of (p + 0.5): + */ + const float c1 = 5.68842; + const float c2 = -0.748699; + const float c3 = -57.8051; + const float c4 = 291.309; + const float c5 = -624.717; + float t = newMaskValue - 0.5; + float x = t * t; + + float uncertainty = + 1.0 - min(1.0, x * (c1 + x * (c2 + x * (c3 + x * (c4 + x * c5))))); + + float outputValue = newMaskValue + (prevMaskValue - newMaskValue) * + (uncertainty * `.concat(o,`); + + setOutput(outputValue); + } +`)},l=aa();return Ce((function(){var c=l.compileAndRun(i,[r,s]);return us().makeTensorFromDataId(c.dataId,c.shape,c.dtype)}))})(n,e,t):Ce((function(){var r=$e(e,.5),s=hn(r),a=$e(1,no(1,Z(s,he(5.68842,Z(s,he(-.748699,Z(s,he(-57.8051,Z(s,he(291.309,Z(s,-624.717)))))))))));return he(e,Z($e(n,e),Z(a,t.combineWithPreviousRatio)))}))}function $U(n,e,t){return Le(this,void 0,void 0,(function(){var r,s,a,o,i;return ze(this,(function(l){switch(l.label){case 0:return r=n[0],s=n[1],a=(function(c,u,d){return Ce((function(){var p,f,m,g;d.reverseOutputOrder?(f=Qe(Ae(c,[0,d.boxCoordOffset+0],[-1,1])),p=Qe(Ae(c,[0,d.boxCoordOffset+1],[-1,1])),g=Qe(Ae(c,[0,d.boxCoordOffset+2],[-1,1])),m=Qe(Ae(c,[0,d.boxCoordOffset+3],[-1,1]))):(p=Qe(Ae(c,[0,d.boxCoordOffset+0],[-1,1])),f=Qe(Ae(c,[0,d.boxCoordOffset+1],[-1,1])),m=Qe(Ae(c,[0,d.boxCoordOffset+2],[-1,1])),g=Qe(Ae(c,[0,d.boxCoordOffset+3],[-1,1]))),f=he(Z(Re(f,d.xScale),u.w),u.x),p=he(Z(Re(p,d.yScale),u.h),u.y),d.applyExponentialOnBoxSize?(m=Z(rr(Re(m,d.hScale)),u.h),g=Z(rr(Re(g,d.wScale)),u.w)):(m=Z(Re(m,d.hScale),u.h),g=Z(Re(g,d.wScale),u.h));var b=$e(p,Re(m,2)),v=$e(f,Re(g,2)),I=he(p,Re(m,2)),S=he(f,Re(g,2)),C=wt([K(b,[d.numBoxes,1]),K(v,[d.numBoxes,1]),K(I,[d.numBoxes,1]),K(S,[d.numBoxes,1])],1);if(d.numKeypoints)for(var T=0;T0)for((u=l.locationData).relativeKeypoints=[],d=t.numKeypoints*t.numValuesPerKeypoint,p=0;p1&&(d.y=r?e.inputImageHeight-o[c+1]:o[c+1]),a>2&&(d.z=o[c+2]),a>3&&(d.score=AU(e.visibilityActivation,o[c+3])),i.push(d);for(u=0;u=s)return e;this.lastTimestamp!==0&&s!==0&&(this.frequency=1/(1e-6*(s-this.lastTimestamp))),this.lastTimestamp=s;var a=this.x.hasLastRawValue()?(e-this.x.lastRawValue())*r*this.frequency:0,o=this.dx.applyWithAlpha(a,this.getAlpha(this.derivateCutOff)),i=this.minCutOff+this.beta*Math.abs(o),l=this.thresholdCutOff!=null?this.thresholdCutOff+this.thresholdBeta*Math.abs(o):null;return this.x.applyWithAlpha(e,this.getAlpha(i),l)},n.prototype.getAlpha=function(e){return 1/(1+this.frequency/(2*Math.PI*e))},n})(),Ul=(function(){function n(e){this.config=e}return n.prototype.apply=function(e,t,r){var s=this;if(e==null)return this.reset(),null;this.initializeFiltersIfEmpty(e);var a=1;if(!this.config.disableValueScaling){if(r=a)return e;if(this.lastTimestamp===-1)s=1;else{for(var o=e*r-this.lastValue*this.lastValueScale,i=a-this.lastTimestamp,l=o,c=i,u=(1+this.window.length)*(1e6/30),d=0,p=this.window;du)break;l+=f.distance,c+=f.duration}var m=l/(1e-6*c);s=1-1/(1+this.config.velocityScale*Math.abs(m)),this.window.unshift({distance:o,duration:i}),this.window.length>this.config.windowSize&&this.window.pop()}return this.lastValue=e,this.lastValueScale=r,this.lastTimestamp=a,this.lowPassFilter.applyWithAlpha(e,s)},n})(),DU=(function(){function n(e){this.config=e}return n.prototype.apply=function(e,t,r){var s=this;if(e==null)return this.reset(),null;var a=1;if(!this.config.disableValueScaling){if(r0){var T=I===d.strides.length-1?1:yh(d.minScale,d.maxScale,I+1,d.strides.length);v.push(Math.sqrt(S*T)),b.push(d.interpolatedScaleAspectRatio)}}I++}for(var O=0;O0)B=d.featureMapHeight[f],A=d.featureMapWidth[f];else{var D=d.strides[f];B=Math.ceil(d.inputSizeHeight/D),A=Math.ceil(d.inputSizeWidth/D)}for(var _=0;_ 0."));if(H.maxPoses>1)throw new Error("Multi-pose detection is not implemented yet. Please set maxPoses to 1.");return H})(t),e==null?(this.reset(),[2,[]]):(this.maxPoses=s.maxPoses,this.timestamp=r!=null?1e3*r:Ob(e)?1e6*e.currentTime:null,a=la(e),o=Ce((function(){return tt(ep(e),"float32")})),(i=this.regionOfInterest)!=null?[3,2]:[4,this.detectPose(o)]);case 1:if((l=_.sent()).length===0)return this.reset(),o.dispose(),[2,[]];c=l[0],i=this.poseDetectionToRoi(c,a),_.label=2;case 2:return[4,this.poseLandmarksByRoi(i,o)];case 3:return u=_.sent(),o.dispose(),u==null?(this.reset(),[2,[]]):(d=u.landmarks,p=u.auxiliaryLandmarks,f=u.poseScore,m=u.worldLandmarks,g=u.segmentationMask,b=this.poseLandmarkFiltering(d,p,m,a),v=b.actualLandmarksFiltered,I=b.auxiliaryLandmarksFiltered,S=b.actualWorldLandmarksFiltered,C=this.poseLandmarksToRoi(I,a),this.regionOfInterest=C,T=this.smoothSegmentation&&g!=null?this.poseSegmentationFiltering(g):g,(O=v!=null?Mb(v,a):null)!=null&&O.forEach((function(V,H){V.name=lo[H]})),(L=S)!=null&&L.forEach((function(V,H){V.name=lo[H]})),B={score:f,keypoints:O,keypoints3D:L},T!==null&&(A=Ce((function(){var V=en(T,2),H=Tr(V,[[0,0],[0,0],[0,1]]);return km(H,[[0,0],[0,0],[0,2]],"symmetric")})),this.smoothSegmentation||Ke(T),D={maskValueToLabel:XU,mask:new KU(A)},B.segmentation=D),[2,[B]])}}))}))},n.prototype.poseSegmentationFiltering=function(e){var t=this.prevFilteredSegmentationMask;return t.size===0?this.prevFilteredSegmentationMask=e:(this.prevFilteredSegmentationMask=NU(t,e,qU),Ke(e)),Ke(t),this.prevFilteredSegmentationMask},n.prototype.dispose=function(){this.detectorModel.dispose(),this.landmarkModel.dispose(),Ke([this.anchorTensor.x,this.anchorTensor.y,this.anchorTensor.w,this.anchorTensor.h,this.prevFilteredSegmentationMask])},n.prototype.reset=function(){this.regionOfInterest=null,this.enableSegmentation&&(Ke(this.prevFilteredSegmentationMask),this.prevFilteredSegmentationMask=fn([],[0,0])),this.visibilitySmoothingFilterActual=null,this.visibilitySmoothingFilterAuxiliary=null,this.landmarksSmoothingFilterActual=null,this.landmarksSmoothingFilterAuxiliary=null},n.prototype.detectPose=function(e){return Le(this,void 0,void 0,(function(){var t,r,s,a,o,i,l,c,u,d;return ze(this,(function(p){switch(p.label){case 0:return t=Vl(e,LU),r=t.imageTensor,s=t.padding,a=this.detectorModel.predict(r),o=kU(a),i=o.boxes,[4,$U([l=o.logits,i],this.anchorTensor,OU)];case 1:return(c=p.sent()).length===0?(Ke([r,a,l,i]),[2,c]):[4,_U(c,this.maxPoses,MU)];case 2:return u=p.sent(),d=(function(f,m){f===void 0&&(f=[]);for(var g=m.left,b=m.top,v=m.left+m.right,I=m.top+m.bottom,S=0;S-1,r=typeof e.landmarkModelUrl=="string"&&e.landmarkModelUrl.indexOf("https://tfhub.dev")>-1,[4,Promise.all([ia(e.detectorModelUrl,{fromTFHub:t}),ia(e.landmarkModelUrl,{fromTFHub:r})])];case 1:return s=i.sent(),a=s[0],o=s[1],[2,new YU(a,o,e.enableSmoothing,e.enableSegmentation,e.smoothSegmentation,e.modelType)]}}))}))}var ds,Wn,Lb=(function(){function n(e){(function(t){if(t.maxTracks<1)throw new Error("Must specify 'maxTracks' to be at least 1, but "+"encountered ".concat(t.maxTracks));if(t.maxAge<=0)throw new Error("Must specify 'maxAge' to be positive, but "+"encountered ".concat(t.maxAge));if(t.keypointTrackerParams!==void 0){if(t.keypointTrackerParams.keypointConfidenceThreshold<0||t.keypointTrackerParams.keypointConfidenceThreshold>1)throw new Error("Must specify 'keypointConfidenceThreshold' to be in the range [0, 1], but encountered "+"".concat(t.keypointTrackerParams.keypointConfidenceThreshold));if(t.keypointTrackerParams.minNumberOfKeypoints<1)throw new Error("Must specify 'minNumberOfKeypoints' to be at least 1, but "+"encountered ".concat(t.keypointTrackerParams.minNumberOfKeypoints));for(var r=0,s=t.keypointTrackerParams.keypointFalloff;r=this.minSimilarity&&m>u&&(c=f,u=m)}if(c>=0){var g=this.tracks[c];g=Object.assign(g,this.createTrack(e[l],r,g.id)),e[l].id=g.id;var b=s.indexOf(c);s.splice(b,1)}else a.push(l)}else a.push(l)}for(var v=0,I=a;v=o||a>=i)return 0;var l=(o-s)*(i-a);return l/(t.box.width*t.box.height+r.box.width*r.box.height-l)},e})(Lb),JU=(function(n){function e(t){var r=n.call(this,t)||this;return r.keypointThreshold=t.keypointTrackerParams.keypointConfidenceThreshold,r.keypointFalloff=t.keypointTrackerParams.keypointFalloff,r.minNumKeyoints=t.keypointTrackerParams.minNumberOfKeypoints,r}return $b(e,n),e.prototype.computeSimilarity=function(t){if(t.length===0||this.tracks.length===0)return[[]];for(var r=[],s=0,a=t;sr.keypointThreshold})),a=Math.min.apply(Math,os([1],s.map((function(l){return l.x})),!1)),o=Math.max.apply(Math,os([0],s.map((function(l){return l.x})),!1)),i=Math.min.apply(Math,os([1],s.map((function(l){return l.y})),!1));return(o-a)*(Math.max.apply(Math,os([0],s.map((function(l){return l.y})),!1))-i)},e})(Lb);function eH(n){switch(n){case Wn.BlazePose:return lo.reduce((function(e,t,r){return e[t]=r,e}),{});case Wn.PoseNet:case Wn.MoveNet:return Un.reduce((function(e,t,r){return e[t]=r,e}),{});default:throw new Error("Model ".concat(n," is not supported."))}}(function(n){n.Keypoint="keypoint",n.BoundingBox="boundingBox"})(ds||(ds={})),(function(n){n.MoveNet="MoveNet",n.BlazePose="BlazePose",n.PoseNet="PoseNet"})(Wn||(Wn={}));var _h=["SinglePose.Lightning","SinglePose.Thunder","MultiPose.Lightning"],zb={modelType:"SinglePose.Lightning",enableSmoothing:!0},Ch={},Nh={frequency:30,minCutOff:2.5,beta:300,derivateCutOff:2.5,thresholdCutOff:.5,thresholdBeta:5,disableValueScaling:!0},Qu={maxTracks:18,maxAge:1e3,minSimilarity:.2,keypointTrackerParams:{keypointConfidenceThreshold:.3,keypointFalloff:[.026,.025,.025,.035,.035,.079,.079,.072,.072,.062,.062,.107,.107,.087,.087,.089,.089],minNumberOfKeypoints:4}},$h={maxTracks:18,maxAge:1e3,minSimilarity:.15,trackerParams:{}};function tH(n,e,t,r){for(var s={},a=0,o=Un;a.2||I[S.right_hip].score>.2)&&(I[S.left_shoulder].score>.2||I[S.right_shoulder].score>.2)})(e,t)){var l=(s.left_hip[0]+s.right_hip[0])/2,c=(s.left_hip[1]+s.right_hip[1])/2,u=(function(I,S,C,T,O){for(var L=["left_shoulder","right_shoulder","left_hip","right_hip"],B=0,A=0,D=0;DB&&(B=X),(ee=Math.abs(O-C[L[D]][1]))>A&&(A=ee);for(var _=0,V=0,H=0,Y=Object.keys(C);H_&&(_=X),(ee=Math.abs(O-C[ye][1]))>V&&(V=ee))}return[B,A,_,V]})(e,t,s,l,c),d=u[0],p=u[1],f=u[2],m=u[3],g=Math.max(1.9*p,1.9*d,1.2*f,1.2*m),b=[l-(g=Math.min(g,Math.max(c,r.width-c,l,r.height-l))),c-g];if(g>Math.max(r.width,r.height)/2)return Hl(n==null,r);var v=2*g;return{yMin:b[0]/r.height,xMin:b[1]/r.width,yMax:(b[0]+v)/r.height,xMax:(b[1]+v)/r.width,height:(b[0]+v)/r.height-b[0]/r.height,width:(b[1]+v)/r.width-b[1]/r.width}}return Hl(n==null,r)}function Hl(n,e){var t,r,s,a;return n?e.width>e.height?(t=1,r=e.height/e.width,s=0,a=(e.width/2-e.height/2)/e.width):(t=e.width/e.height,r=1,s=(e.height/2-e.width/2)/e.height,a=0):e.width>e.height?(t=e.width/e.height,r=1,s=(e.height/2-e.width/2)/e.height,a=0):(t=1,r=e.height/e.width,s=0,a=(e.width/2-e.height/2)/e.width),{yMin:s,xMin:a,yMax:s+t,xMax:a+r,height:t,width:r}}function nH(n){var e,t=n==null?zb:Je({},n);if(t.modelType==null)t.modelType="SinglePose.Lightning";else if(_h.indexOf(t.modelType)<0)throw new Error("Invalid architecture ".concat(t.modelType,". ")+"Should be one of ".concat(_h));if(t.enableSmoothing==null&&(t.enableSmoothing=!0),t.minPoseScore!=null&&(t.minPoseScore<0||t.minPoseScore>1))throw new Error("minPoseScore should be between 0.0 and 1.0");if(t.multiPoseMaxDimension!=null&&(t.multiPoseMaxDimension%32!=0||t.multiPoseMaxDimension<32))throw new Error("multiPoseMaxDimension must be a multiple of 32 and higher than 0");if(t.modelType==="MultiPose.Lightning"&&t.enableTracking==null&&(t.enableTracking=!0),t.modelType==="MultiPose.Lightning"&&t.enableTracking===!0)if(t.trackerType==null&&(t.trackerType=ds.BoundingBox),t.trackerType===ds.Keypoint)t.trackerConfig!=null?t.trackerConfig=(function(r){var s=Th(Qu,r);return s.keypointTrackerParams=Je({},Qu.keypointTrackerParams),r.keypointTrackerParams!=null&&(r.keypointTrackerParams.keypointConfidenceThreshold!=null&&(s.keypointTrackerParams.keypointConfidenceThreshold=r.keypointTrackerParams.keypointConfidenceThreshold),r.keypointTrackerParams.keypointFalloff!=null&&(s.keypointTrackerParams.keypointFalloff=r.keypointTrackerParams.keypointFalloff),r.keypointTrackerParams.minNumberOfKeypoints!=null&&(s.keypointTrackerParams.minNumberOfKeypoints=r.keypointTrackerParams.minNumberOfKeypoints)),s})(t.trackerConfig):t.trackerConfig=Qu;else{if(t.trackerType!==ds.BoundingBox)throw new Error("Tracker type not supported by MoveNet");t.trackerConfig!=null?t.trackerConfig=(e=t.trackerConfig,Th($h,e)):t.trackerConfig=$h}return t}function Th(n,e){var t={maxTracks:n.maxTracks,maxAge:n.maxAge,minSimilarity:n.minSimilarity};return e.maxTracks!=null&&(t.maxTracks=e.maxTracks),e.maxAge!=null&&(t.maxAge=e.maxAge),e.minSimilarity!=null&&(t.minSimilarity=e.minSimilarity),t}var rH=(function(){function n(e,t){this.moveNetModel=e,this.modelInputResolution={height:0,width:0},this.keypointIndexByName=eH(Wn.MoveNet),t.modelType==="SinglePose.Lightning"?(this.modelInputResolution.width=192,this.modelInputResolution.height=192):t.modelType==="SinglePose.Thunder"&&(this.modelInputResolution.width=256,this.modelInputResolution.height=256),this.multiPoseModel=t.modelType==="MultiPose.Lightning",this.multiPoseModel||(this.keypointFilter=new Ul(Nh),this.cropRegionFilterYMin=new wr(.9),this.cropRegionFilterXMin=new wr(.9),this.cropRegionFilterYMax=new wr(.9),this.cropRegionFilterXMax=new wr(.9)),this.enableSmoothing=t.enableSmoothing,t.minPoseScore?this.minPoseScore=t.minPoseScore:this.minPoseScore=.25,t.multiPoseMaxDimension?this.multiPoseMaxDimension=t.multiPoseMaxDimension:this.multiPoseMaxDimension=256,this.enableTracking=t.enableTracking,this.multiPoseModel&&this.enableTracking&&(t.trackerType===ds.Keypoint?this.tracker=new JU(t.trackerConfig):t.trackerType===ds.BoundingBox&&(this.tracker=new ZU(t.trackerConfig)),this.enableSmoothing&&(this.keypointFilterMap=new Map))}return n.prototype.runSinglePersonPoseModel=function(e){return Le(this,void 0,void 0,(function(){var t,r,s,a,o;return ze(this,(function(i){switch(i.label){case 0:if((t=this.moveNetModel.execute(e)).shape.length!==4||t.shape[0]!==1||t.shape[1]!==1||t.shape[2]!==17||t.shape[3]!==3)throw t.dispose(),new Error("Unexpected output shape from model: [".concat(t.shape,"]"));return Qa()==="webgpu"?[3,1]:(r=t.dataSync(),[3,3]);case 1:return[4,t.data()];case 2:r=i.sent(),i.label=3;case 3:for(t.dispose(),s={keypoints:[],score:0},a=0,o=0;o<17;++o)s.keypoints[o]={y:r[3*o],x:r[3*o+1],score:r[3*o+2]},s.keypoints[o].score>.2&&(++a,s.score+=s.keypoints[o].score);return a>0&&(s.score/=a),[2,s]}}))}))},n.prototype.runMultiPersonPoseModel=function(e){return Le(this,void 0,void 0,(function(){var t,r,s,a,o,i,l,c;return ze(this,(function(u){switch(u.label){case 0:if((t=this.moveNetModel.execute(e)).shape.length!==3||t.shape[0]!==1||t.shape[2]!==56)throw t.dispose(),new Error("Unexpected output shape from model: [".concat(t.shape,"]"));return Qa()==="webgpu"?[3,1]:(r=t.dataSync(),[3,3]);case 1:return[4,t.data()];case 2:r=u.sent(),u.label=3;case 3:for(t.dispose(),s=[],a=r.length/56,o=0;ot.height?(a=this.multiPoseMaxDimension,o=Math.round(this.multiPoseMaxDimension*t.height/t.width),s=ls.resizeBilinear(e,[o,a]),l=a,c=32*Math.ceil(o/32),i=Tr(s,[[0,0],[0,c-o],[0,0],[0,0]])):(a=Math.round(this.multiPoseMaxDimension*t.width/t.height),o=this.multiPoseMaxDimension,s=ls.resizeBilinear(e,[o,a]),l=32*Math.ceil(a/32),c=o,i=Tr(s,[[0,0],[0,0],[0,l-a],[0,0]])),s.dispose(),e.dispose(),u=tt(i,"int32"),i.dispose(),[4,this.runMultiPersonPoseModel(u)];case 1:for(d=b.sent(),u.dispose(),d=d.filter((function(v){return v.score>=g.minPoseScore})),f=0;f-1,[4,ia(e.modelUrl,{fromTFHub:r})]):[3,2];case 1:return t=a.sent(),[3,4];case 2:return s=void 0,e.modelType==="SinglePose.Lightning"?s="https://tfhub.dev/google/tfjs-model/movenet/singlepose/lightning/4":e.modelType==="SinglePose.Thunder"?s="https://tfhub.dev/google/tfjs-model/movenet/singlepose/thunder/4":e.modelType==="MultiPose.Lightning"&&(s="https://tfhub.dev/google/tfjs-model/movenet/multipose/lightning/1"),[4,ia(s,{fromTFHub:r})];case 3:t=a.sent(),a.label=4;case 4:return Qa()==="webgl"&&fe().set("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",0),[2,new rH(t,e)]}}))}))}var Eh={architecture:"MobileNetV1",outputStride:16,multiplier:.75,inputResolution:{height:257,width:257}},Ah=["MobileNetV1","ResNet50"],Rh={MobileNetV1:[8,16],ResNet50:[16]},aH=[8,16,32],Dh={MobileNetV1:[.5,.75,1],ResNet50:[1]},Ph=[1,2,4],Fh={maxPoses:1,flipHorizontal:!1},oH={maxPoses:5,flipHorizontal:!1,scoreThreshold:.5,nmsRadius:20},iH=[-123.15,-115.9,-103.06];function Zu(n){return Math.floor(n/2)}var uH=(function(){function n(e,t){this.priorityQueue=new Array(e),this.numberOfElements=-1,this.getElementValue=t}return n.prototype.enqueue=function(e){this.priorityQueue[++this.numberOfElements]=e,this.swim(this.numberOfElements)},n.prototype.dequeue=function(){var e=this.priorityQueue[0];return this.exchange(0,this.numberOfElements--),this.sink(0),this.priorityQueue[this.numberOfElements+1]=null,e},n.prototype.empty=function(){return this.numberOfElements===-1},n.prototype.size=function(){return this.numberOfElements+1},n.prototype.all=function(){return this.priorityQueue.slice(0,this.numberOfElements+1)},n.prototype.max=function(){return this.priorityQueue[0]},n.prototype.swim=function(e){for(;e>0&&this.less(Zu(e),e);)this.exchange(e,Zu(e)),e=Zu(e)},n.prototype.sink=function(e){for(;2*e<=this.numberOfElements;){var t=2*e;if(te){c=!1;break}if(!c)break}return c}function cH(n){return Le(this,void 0,void 0,(function(){return ze(this,(function(e){return[2,Promise.all(n.map((function(t){return t.buffer()})))]}))}))}function Bb(n,e,t,r){return{y:r.get(n,e,t),x:r.get(n,e,t+17)}}function Wb(n,e,t){var r=Bb(n.heatmapY,n.heatmapX,n.id,t),s=r.y,a=r.x;return{x:n.heatmapX*e+a,y:n.heatmapY*e+s}}function Vb(n,e,t,r){var s=t.x,a=t.y;return n.some((function(o){var i,l,c,u,d,p,f=o.keypoints;return i=a,l=s,c=f[r].y,u=f[r].x,(d=c-i)*d+(p=u-l)*p<=e}))}var Oh=Un.reduce((function(n,e,t){return n[e]=t,n}),{}),Ub=[["nose","left_eye"],["left_eye","left_ear"],["nose","right_eye"],["right_eye","right_ear"],["nose","left_shoulder"],["left_shoulder","left_elbow"],["left_elbow","left_wrist"],["left_shoulder","left_hip"],["left_hip","left_knee"],["left_knee","left_ankle"],["nose","right_shoulder"],["right_shoulder","right_elbow"],["right_elbow","right_wrist"],["right_shoulder","right_hip"],["right_hip","right_knee"],["right_knee","right_ankle"]].map((function(n){var e=n[0],t=n[1];return[Oh[e],Oh[t]]})),Ju=Ub.map((function(n){return n[1]})),Mh=Ub.map((function(n){return n[0]}));function Lh(n,e,t){return nt?t:n}function el(n,e,t,r){return{y:Lh(Math.round(n.y/e),0,t-1),x:Lh(Math.round(n.x/e),0,r-1)}}function zh(n,e){return{x:n.x+e.x,y:n.y+e.y}}function Bh(n,e,t,r,s,a,o,i){i===void 0&&(i=2);for(var l=r.shape,c=l[0],u=l[1],d={y:e.y,x:e.x},p=zh(d,(function(I,S,C){var T=C.shape[2]/2;return{y:C.get(S.y,S.x,I),x:C.get(S.y,S.x,T+I)}})(n,el(d,a,c,u),o)),f=0;f=0;--p){var f=Ju[p],m=Mh[p];l[f]&&!l[m]&&(l[m]=Bh(p,l[f],m,e,t,r,a))}for(p=0;p vec2 { + let outIndexY = y * uniforms.bShape.x * uniforms.bShape.y + x * uniforms.bShape.y + index; + let outIndexX = outIndexY + uniforms.bShape.z; + let outY = i32(B[outIndexY]); + let outX = i32(B[outIndexX]); + return vec2(outY, outX); + } + + `.concat(Hb("index"),` { + if (index < uniforms.size) { + let indexY = index * `).concat(this.supportedLastDimension,`; + let indexX = indexY + 1; + let heatmapY = A[indexY]; + let heatmapX = A[indexX]; + let out = getOffsetPoint(i32(heatmapY), i32(heatmapX), index); + result[indexY] = f32(out[0]); + result[indexX] = f32(out[1]); + } + } + `)},n})();function yH(n,e){if(aa()instanceof ga)return(function(t,r){var s=aa(),a=new gH(t.shape),o=s.runWebGPUProgram(a,[t,r],"float32");return us().makeTensorFromTensorInfo(o)})(n,e);throw new Error("getOffsetVectorsGPU is not supported in this backend!")}function Gb(n){var e=n.shape,t=e[0],r=e[1],s=e[2];return Ce((function(){var a,o,i=K(n,[t*r,s]),l=tm(i,0),c=en(Re(l,De(r,"int32")),1),u=en((a=l,o=r,Ce((function(){var d=Re(a,De(o,"int32"));return $e(a,Z(d,De(o,"int32")))}))),1);return wt([c,u],1)}))}function bH(n,e,t){return Ce((function(){var r=(function(s,a){for(var o=[],i=0;i=0,(function(){return"outputStride of ".concat(i," is invalid. ")+"It must be either 8 or 16."}))})(t.outputStride),(function(i,l){$(Wh(i.height,l),(function(){return"height of ".concat(i.height," is invalid for output stride ")+"".concat(l,".")})),$(Wh(i.width,l),(function(){return"width of ".concat(i.width," is invalid for output stride ")+"".concat(l,".")}))})(o,t.outputStride),this.inputResolution=o,this.outputStride=t.outputStride,this.architecture=t.architecture}return n.prototype.estimatePoses=function(e,t){return t===void 0&&(t=Fh),Le(this,void 0,void 0,(function(){return ze(this,(function(r){return[2,this.estimatePosesGPU(e,t,!1)]}))}))},n.prototype.estimatePosesGPU=function(e,t,r){return t===void 0&&(t=Fh),r===void 0&&(r=!1),Le(this,void 0,void 0,(function(){var s,a,o,i,l,c,u,d,p,f,m,g,b,v,I,S,C,T;return ze(this,(function(O){switch(O.label){case 0:return s=(function(L){var B=L;if(B.maxPoses==null&&(B.maxPoses=1),B.maxPoses<=0)throw new Error("Invalid maxPoses ".concat(B.maxPoses,". Should be > 0."));if(B.maxPoses>1){if((B=Je(Je({},oH),B)).scoreThreshold<0||B.scoreThreshold>1)throw new Error("Invalid scoreThreshold ".concat(B.scoreThreshold,". ")+"Should be in range [0.0, 1.0]");if(B.nmsRadius<=0)throw new Error("Invalid nmsRadius ".concat(B.nmsRadius,"."))}return B})(t),e==null?[2,r?[[],[]]:[]]:(this.maxPoses=s.maxPoses,a=Vl(e,{outputTensorSize:this.inputResolution,keepAspectRatio:!0,borderMode:"replicate"}),o=a.imageTensor,i=a.padding,l=this.architecture==="ResNet50"?he(o,iH):Fb(o,[-1,1]),c=this.posenetModel.predict(l),this.architecture==="ResNet50"?(u=Qe(c[2],[0]),d=Qe(c[3],[0]),p=Qe(c[0],[0]),f=Qe(c[1],[0])):(u=Qe(c[0],[0]),d=Qe(c[1],[0]),p=Qe(c[2],[0]),f=Qe(c[3],[0])),m=er(d),this.maxPoses!==1?[3,5]:r?[4,vH(m,u,this.outputStride)]:[3,2]);case 1:return b=O.sent(),I=b[0],v=b[1],g=[I,v],[3,4];case 2:return[4,xH(m,u,this.outputStride)];case 3:I=O.sent(),g=[I],O.label=4;case 4:return[3,7];case 5:if(r)throw new Error("GPU renderer only supports single pose!");return[4,hH(m,u,p,f,this.outputStride,this.maxPoses,s.scoreThreshold,s.nmsRadius)];case 6:g=O.sent(),O.label=7;case 7:if(r){if(s.flipHorizontal===!0)throw new Error("flipHorizontal is not supported!");S=this.getCanvasInfo(la(e),this.inputResolution,i)}else T=la(e),C=(function(L,B,A,D){var _=B.height,V=B.width,H=_/(A.height*(1-D.top-D.bottom)),Y=V/(A.width*(1-D.left-D.right)),X=-D.top*A.height,ee=-D.left*A.width;if(Y===1&&H===1&&X===0&&ee===0)return L;for(var ye=0,ce=L;ye{const e=n.data;try{if(e.type==="init"){MP(e.wasmBase),await f0("wasm"),await m0(),tl=await IH(Wn.MoveNet,{modelType:e.variant==="thunder"?jh.modelType.SINGLEPOSE_THUNDER:jh.modelType.SINGLEPOSE_LIGHTNING,enableSmoothing:!0,modelUrl:e.modelUrl}),self.postMessage({type:"ready"});return}if(e.type==="frame"){if(!tl){e.bitmap.close();return}const t=performance.now(),r=await tl.estimatePoses(e.bitmap);e.bitmap.close(),self.postMessage({type:"pose",t:e.t,inferMs:performance.now()-t,keypoints:r[0]?.keypoints??[]})}}catch(t){self.postMessage({type:"error",message:String(t).slice(0,200)})}};